1 //===-- LLParser.cpp - Parser Class ---------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the parser class for .ll files. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/AsmParser/LLParser.h" 14 #include "llvm/ADT/APSInt.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/None.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/AsmParser/LLToken.h" 20 #include "llvm/AsmParser/SlotMapping.h" 21 #include "llvm/BinaryFormat/Dwarf.h" 22 #include "llvm/IR/Argument.h" 23 #include "llvm/IR/AutoUpgrade.h" 24 #include "llvm/IR/BasicBlock.h" 25 #include "llvm/IR/CallingConv.h" 26 #include "llvm/IR/Comdat.h" 27 #include "llvm/IR/ConstantRange.h" 28 #include "llvm/IR/Constants.h" 29 #include "llvm/IR/DebugInfoMetadata.h" 30 #include "llvm/IR/DerivedTypes.h" 31 #include "llvm/IR/Function.h" 32 #include "llvm/IR/GlobalIFunc.h" 33 #include "llvm/IR/GlobalObject.h" 34 #include "llvm/IR/InlineAsm.h" 35 #include "llvm/IR/Instructions.h" 36 #include "llvm/IR/Intrinsics.h" 37 #include "llvm/IR/LLVMContext.h" 38 #include "llvm/IR/Metadata.h" 39 #include "llvm/IR/Module.h" 40 #include "llvm/IR/Value.h" 41 #include "llvm/IR/ValueSymbolTable.h" 42 #include "llvm/Support/Casting.h" 43 #include "llvm/Support/ErrorHandling.h" 44 #include "llvm/Support/MathExtras.h" 45 #include "llvm/Support/SaveAndRestore.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include <algorithm> 48 #include <cassert> 49 #include <cstring> 50 #include <iterator> 51 #include <vector> 52 53 using namespace llvm; 54 55 static std::string getTypeString(Type *T) { 56 std::string Result; 57 raw_string_ostream Tmp(Result); 58 Tmp << *T; 59 return Tmp.str(); 60 } 61 62 /// Run: module ::= toplevelentity* 63 bool LLParser::Run(bool UpgradeDebugInfo, 64 DataLayoutCallbackTy DataLayoutCallback) { 65 // Prime the lexer. 66 Lex.Lex(); 67 68 if (Context.shouldDiscardValueNames()) 69 return error( 70 Lex.getLoc(), 71 "Can't read textual IR with a Context that discards named Values"); 72 73 if (M) { 74 if (parseTargetDefinitions()) 75 return true; 76 77 if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple())) 78 M->setDataLayout(*LayoutOverride); 79 } 80 81 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) || 82 validateEndOfIndex(); 83 } 84 85 bool LLParser::parseStandaloneConstantValue(Constant *&C, 86 const SlotMapping *Slots) { 87 restoreParsingState(Slots); 88 Lex.Lex(); 89 90 Type *Ty = nullptr; 91 if (parseType(Ty) || parseConstantValue(Ty, C)) 92 return true; 93 if (Lex.getKind() != lltok::Eof) 94 return error(Lex.getLoc(), "expected end of string"); 95 return false; 96 } 97 98 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read, 99 const SlotMapping *Slots) { 100 restoreParsingState(Slots); 101 Lex.Lex(); 102 103 Read = 0; 104 SMLoc Start = Lex.getLoc(); 105 Ty = nullptr; 106 if (parseType(Ty)) 107 return true; 108 SMLoc End = Lex.getLoc(); 109 Read = End.getPointer() - Start.getPointer(); 110 111 return false; 112 } 113 114 void LLParser::restoreParsingState(const SlotMapping *Slots) { 115 if (!Slots) 116 return; 117 NumberedVals = Slots->GlobalValues; 118 NumberedMetadata = Slots->MetadataNodes; 119 for (const auto &I : Slots->NamedTypes) 120 NamedTypes.insert( 121 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy()))); 122 for (const auto &I : Slots->Types) 123 NumberedTypes.insert( 124 std::make_pair(I.first, std::make_pair(I.second, LocTy()))); 125 } 126 127 /// validateEndOfModule - Do final validity and basic correctness checks at the 128 /// end of the module. 129 bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) { 130 if (!M) 131 return false; 132 // Handle any function attribute group forward references. 133 for (const auto &RAG : ForwardRefAttrGroups) { 134 Value *V = RAG.first; 135 const std::vector<unsigned> &Attrs = RAG.second; 136 AttrBuilder B(Context); 137 138 for (const auto &Attr : Attrs) { 139 auto R = NumberedAttrBuilders.find(Attr); 140 if (R != NumberedAttrBuilders.end()) 141 B.merge(R->second); 142 } 143 144 if (Function *Fn = dyn_cast<Function>(V)) { 145 AttributeList AS = Fn->getAttributes(); 146 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs()); 147 AS = AS.removeFnAttributes(Context); 148 149 FnAttrs.merge(B); 150 151 // If the alignment was parsed as an attribute, move to the alignment 152 // field. 153 if (FnAttrs.hasAlignmentAttr()) { 154 Fn->setAlignment(FnAttrs.getAlignment()); 155 FnAttrs.removeAttribute(Attribute::Alignment); 156 } 157 158 AS = AS.addFnAttributes(Context, FnAttrs); 159 Fn->setAttributes(AS); 160 } else if (CallInst *CI = dyn_cast<CallInst>(V)) { 161 AttributeList AS = CI->getAttributes(); 162 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs()); 163 AS = AS.removeFnAttributes(Context); 164 FnAttrs.merge(B); 165 AS = AS.addFnAttributes(Context, FnAttrs); 166 CI->setAttributes(AS); 167 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) { 168 AttributeList AS = II->getAttributes(); 169 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs()); 170 AS = AS.removeFnAttributes(Context); 171 FnAttrs.merge(B); 172 AS = AS.addFnAttributes(Context, FnAttrs); 173 II->setAttributes(AS); 174 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) { 175 AttributeList AS = CBI->getAttributes(); 176 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs()); 177 AS = AS.removeFnAttributes(Context); 178 FnAttrs.merge(B); 179 AS = AS.addFnAttributes(Context, FnAttrs); 180 CBI->setAttributes(AS); 181 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) { 182 AttrBuilder Attrs(M->getContext(), GV->getAttributes()); 183 Attrs.merge(B); 184 GV->setAttributes(AttributeSet::get(Context,Attrs)); 185 } else { 186 llvm_unreachable("invalid object with forward attribute group reference"); 187 } 188 } 189 190 // If there are entries in ForwardRefBlockAddresses at this point, the 191 // function was never defined. 192 if (!ForwardRefBlockAddresses.empty()) 193 return error(ForwardRefBlockAddresses.begin()->first.Loc, 194 "expected function name in blockaddress"); 195 196 for (const auto &NT : NumberedTypes) 197 if (NT.second.second.isValid()) 198 return error(NT.second.second, 199 "use of undefined type '%" + Twine(NT.first) + "'"); 200 201 for (StringMap<std::pair<Type*, LocTy> >::iterator I = 202 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) 203 if (I->second.second.isValid()) 204 return error(I->second.second, 205 "use of undefined type named '" + I->getKey() + "'"); 206 207 if (!ForwardRefComdats.empty()) 208 return error(ForwardRefComdats.begin()->second, 209 "use of undefined comdat '$" + 210 ForwardRefComdats.begin()->first + "'"); 211 212 if (!ForwardRefVals.empty()) 213 return error(ForwardRefVals.begin()->second.second, 214 "use of undefined value '@" + ForwardRefVals.begin()->first + 215 "'"); 216 217 if (!ForwardRefValIDs.empty()) 218 return error(ForwardRefValIDs.begin()->second.second, 219 "use of undefined value '@" + 220 Twine(ForwardRefValIDs.begin()->first) + "'"); 221 222 if (!ForwardRefMDNodes.empty()) 223 return error(ForwardRefMDNodes.begin()->second.second, 224 "use of undefined metadata '!" + 225 Twine(ForwardRefMDNodes.begin()->first) + "'"); 226 227 // Resolve metadata cycles. 228 for (auto &N : NumberedMetadata) { 229 if (N.second && !N.second->isResolved()) 230 N.second->resolveCycles(); 231 } 232 233 for (auto *Inst : InstsWithTBAATag) { 234 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa); 235 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag"); 236 auto *UpgradedMD = UpgradeTBAANode(*MD); 237 if (MD != UpgradedMD) 238 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD); 239 } 240 241 // Look for intrinsic functions and CallInst that need to be upgraded. We use 242 // make_early_inc_range here because we may remove some functions. 243 for (Function &F : llvm::make_early_inc_range(*M)) 244 UpgradeCallsToIntrinsic(&F); 245 246 // Some types could be renamed during loading if several modules are 247 // loaded in the same LLVMContext (LTO scenario). In this case we should 248 // remangle intrinsics names as well. 249 for (Function &F : llvm::make_early_inc_range(*M)) { 250 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F)) { 251 F.replaceAllUsesWith(Remangled.getValue()); 252 F.eraseFromParent(); 253 } 254 } 255 256 if (UpgradeDebugInfo) 257 llvm::UpgradeDebugInfo(*M); 258 259 UpgradeModuleFlags(*M); 260 UpgradeSectionAttributes(*M); 261 262 if (!Slots) 263 return false; 264 // Initialize the slot mapping. 265 // Because by this point we've parsed and validated everything, we can "steal" 266 // the mapping from LLParser as it doesn't need it anymore. 267 Slots->GlobalValues = std::move(NumberedVals); 268 Slots->MetadataNodes = std::move(NumberedMetadata); 269 for (const auto &I : NamedTypes) 270 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first)); 271 for (const auto &I : NumberedTypes) 272 Slots->Types.insert(std::make_pair(I.first, I.second.first)); 273 274 return false; 275 } 276 277 /// Do final validity and basic correctness checks at the end of the index. 278 bool LLParser::validateEndOfIndex() { 279 if (!Index) 280 return false; 281 282 if (!ForwardRefValueInfos.empty()) 283 return error(ForwardRefValueInfos.begin()->second.front().second, 284 "use of undefined summary '^" + 285 Twine(ForwardRefValueInfos.begin()->first) + "'"); 286 287 if (!ForwardRefAliasees.empty()) 288 return error(ForwardRefAliasees.begin()->second.front().second, 289 "use of undefined summary '^" + 290 Twine(ForwardRefAliasees.begin()->first) + "'"); 291 292 if (!ForwardRefTypeIds.empty()) 293 return error(ForwardRefTypeIds.begin()->second.front().second, 294 "use of undefined type id summary '^" + 295 Twine(ForwardRefTypeIds.begin()->first) + "'"); 296 297 return false; 298 } 299 300 //===----------------------------------------------------------------------===// 301 // Top-Level Entities 302 //===----------------------------------------------------------------------===// 303 304 bool LLParser::parseTargetDefinitions() { 305 while (true) { 306 switch (Lex.getKind()) { 307 case lltok::kw_target: 308 if (parseTargetDefinition()) 309 return true; 310 break; 311 case lltok::kw_source_filename: 312 if (parseSourceFileName()) 313 return true; 314 break; 315 default: 316 return false; 317 } 318 } 319 } 320 321 bool LLParser::parseTopLevelEntities() { 322 // If there is no Module, then parse just the summary index entries. 323 if (!M) { 324 while (true) { 325 switch (Lex.getKind()) { 326 case lltok::Eof: 327 return false; 328 case lltok::SummaryID: 329 if (parseSummaryEntry()) 330 return true; 331 break; 332 case lltok::kw_source_filename: 333 if (parseSourceFileName()) 334 return true; 335 break; 336 default: 337 // Skip everything else 338 Lex.Lex(); 339 } 340 } 341 } 342 while (true) { 343 switch (Lex.getKind()) { 344 default: 345 return tokError("expected top-level entity"); 346 case lltok::Eof: return false; 347 case lltok::kw_declare: 348 if (parseDeclare()) 349 return true; 350 break; 351 case lltok::kw_define: 352 if (parseDefine()) 353 return true; 354 break; 355 case lltok::kw_module: 356 if (parseModuleAsm()) 357 return true; 358 break; 359 case lltok::LocalVarID: 360 if (parseUnnamedType()) 361 return true; 362 break; 363 case lltok::LocalVar: 364 if (parseNamedType()) 365 return true; 366 break; 367 case lltok::GlobalID: 368 if (parseUnnamedGlobal()) 369 return true; 370 break; 371 case lltok::GlobalVar: 372 if (parseNamedGlobal()) 373 return true; 374 break; 375 case lltok::ComdatVar: if (parseComdat()) return true; break; 376 case lltok::exclaim: 377 if (parseStandaloneMetadata()) 378 return true; 379 break; 380 case lltok::SummaryID: 381 if (parseSummaryEntry()) 382 return true; 383 break; 384 case lltok::MetadataVar: 385 if (parseNamedMetadata()) 386 return true; 387 break; 388 case lltok::kw_attributes: 389 if (parseUnnamedAttrGrp()) 390 return true; 391 break; 392 case lltok::kw_uselistorder: 393 if (parseUseListOrder()) 394 return true; 395 break; 396 case lltok::kw_uselistorder_bb: 397 if (parseUseListOrderBB()) 398 return true; 399 break; 400 } 401 } 402 } 403 404 /// toplevelentity 405 /// ::= 'module' 'asm' STRINGCONSTANT 406 bool LLParser::parseModuleAsm() { 407 assert(Lex.getKind() == lltok::kw_module); 408 Lex.Lex(); 409 410 std::string AsmStr; 411 if (parseToken(lltok::kw_asm, "expected 'module asm'") || 412 parseStringConstant(AsmStr)) 413 return true; 414 415 M->appendModuleInlineAsm(AsmStr); 416 return false; 417 } 418 419 /// toplevelentity 420 /// ::= 'target' 'triple' '=' STRINGCONSTANT 421 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT 422 bool LLParser::parseTargetDefinition() { 423 assert(Lex.getKind() == lltok::kw_target); 424 std::string Str; 425 switch (Lex.Lex()) { 426 default: 427 return tokError("unknown target property"); 428 case lltok::kw_triple: 429 Lex.Lex(); 430 if (parseToken(lltok::equal, "expected '=' after target triple") || 431 parseStringConstant(Str)) 432 return true; 433 M->setTargetTriple(Str); 434 return false; 435 case lltok::kw_datalayout: 436 Lex.Lex(); 437 if (parseToken(lltok::equal, "expected '=' after target datalayout") || 438 parseStringConstant(Str)) 439 return true; 440 M->setDataLayout(Str); 441 return false; 442 } 443 } 444 445 /// toplevelentity 446 /// ::= 'source_filename' '=' STRINGCONSTANT 447 bool LLParser::parseSourceFileName() { 448 assert(Lex.getKind() == lltok::kw_source_filename); 449 Lex.Lex(); 450 if (parseToken(lltok::equal, "expected '=' after source_filename") || 451 parseStringConstant(SourceFileName)) 452 return true; 453 if (M) 454 M->setSourceFileName(SourceFileName); 455 return false; 456 } 457 458 /// parseUnnamedType: 459 /// ::= LocalVarID '=' 'type' type 460 bool LLParser::parseUnnamedType() { 461 LocTy TypeLoc = Lex.getLoc(); 462 unsigned TypeID = Lex.getUIntVal(); 463 Lex.Lex(); // eat LocalVarID; 464 465 if (parseToken(lltok::equal, "expected '=' after name") || 466 parseToken(lltok::kw_type, "expected 'type' after '='")) 467 return true; 468 469 Type *Result = nullptr; 470 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result)) 471 return true; 472 473 if (!isa<StructType>(Result)) { 474 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID]; 475 if (Entry.first) 476 return error(TypeLoc, "non-struct types may not be recursive"); 477 Entry.first = Result; 478 Entry.second = SMLoc(); 479 } 480 481 return false; 482 } 483 484 /// toplevelentity 485 /// ::= LocalVar '=' 'type' type 486 bool LLParser::parseNamedType() { 487 std::string Name = Lex.getStrVal(); 488 LocTy NameLoc = Lex.getLoc(); 489 Lex.Lex(); // eat LocalVar. 490 491 if (parseToken(lltok::equal, "expected '=' after name") || 492 parseToken(lltok::kw_type, "expected 'type' after name")) 493 return true; 494 495 Type *Result = nullptr; 496 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result)) 497 return true; 498 499 if (!isa<StructType>(Result)) { 500 std::pair<Type*, LocTy> &Entry = NamedTypes[Name]; 501 if (Entry.first) 502 return error(NameLoc, "non-struct types may not be recursive"); 503 Entry.first = Result; 504 Entry.second = SMLoc(); 505 } 506 507 return false; 508 } 509 510 /// toplevelentity 511 /// ::= 'declare' FunctionHeader 512 bool LLParser::parseDeclare() { 513 assert(Lex.getKind() == lltok::kw_declare); 514 Lex.Lex(); 515 516 std::vector<std::pair<unsigned, MDNode *>> MDs; 517 while (Lex.getKind() == lltok::MetadataVar) { 518 unsigned MDK; 519 MDNode *N; 520 if (parseMetadataAttachment(MDK, N)) 521 return true; 522 MDs.push_back({MDK, N}); 523 } 524 525 Function *F; 526 if (parseFunctionHeader(F, false)) 527 return true; 528 for (auto &MD : MDs) 529 F->addMetadata(MD.first, *MD.second); 530 return false; 531 } 532 533 /// toplevelentity 534 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ... 535 bool LLParser::parseDefine() { 536 assert(Lex.getKind() == lltok::kw_define); 537 Lex.Lex(); 538 539 Function *F; 540 return parseFunctionHeader(F, true) || parseOptionalFunctionMetadata(*F) || 541 parseFunctionBody(*F); 542 } 543 544 /// parseGlobalType 545 /// ::= 'constant' 546 /// ::= 'global' 547 bool LLParser::parseGlobalType(bool &IsConstant) { 548 if (Lex.getKind() == lltok::kw_constant) 549 IsConstant = true; 550 else if (Lex.getKind() == lltok::kw_global) 551 IsConstant = false; 552 else { 553 IsConstant = false; 554 return tokError("expected 'global' or 'constant'"); 555 } 556 Lex.Lex(); 557 return false; 558 } 559 560 bool LLParser::parseOptionalUnnamedAddr( 561 GlobalVariable::UnnamedAddr &UnnamedAddr) { 562 if (EatIfPresent(lltok::kw_unnamed_addr)) 563 UnnamedAddr = GlobalValue::UnnamedAddr::Global; 564 else if (EatIfPresent(lltok::kw_local_unnamed_addr)) 565 UnnamedAddr = GlobalValue::UnnamedAddr::Local; 566 else 567 UnnamedAddr = GlobalValue::UnnamedAddr::None; 568 return false; 569 } 570 571 /// parseUnnamedGlobal: 572 /// OptionalVisibility (ALIAS | IFUNC) ... 573 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility 574 /// OptionalDLLStorageClass 575 /// ... -> global variable 576 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ... 577 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier 578 /// OptionalVisibility 579 /// OptionalDLLStorageClass 580 /// ... -> global variable 581 bool LLParser::parseUnnamedGlobal() { 582 unsigned VarID = NumberedVals.size(); 583 std::string Name; 584 LocTy NameLoc = Lex.getLoc(); 585 586 // Handle the GlobalID form. 587 if (Lex.getKind() == lltok::GlobalID) { 588 if (Lex.getUIntVal() != VarID) 589 return error(Lex.getLoc(), 590 "variable expected to be numbered '%" + Twine(VarID) + "'"); 591 Lex.Lex(); // eat GlobalID; 592 593 if (parseToken(lltok::equal, "expected '=' after name")) 594 return true; 595 } 596 597 bool HasLinkage; 598 unsigned Linkage, Visibility, DLLStorageClass; 599 bool DSOLocal; 600 GlobalVariable::ThreadLocalMode TLM; 601 GlobalVariable::UnnamedAddr UnnamedAddr; 602 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass, 603 DSOLocal) || 604 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr)) 605 return true; 606 607 switch (Lex.getKind()) { 608 default: 609 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility, 610 DLLStorageClass, DSOLocal, TLM, UnnamedAddr); 611 case lltok::kw_alias: 612 case lltok::kw_ifunc: 613 return parseAliasOrIFunc(Name, NameLoc, Linkage, Visibility, 614 DLLStorageClass, DSOLocal, TLM, UnnamedAddr); 615 } 616 } 617 618 /// parseNamedGlobal: 619 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ... 620 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier 621 /// OptionalVisibility OptionalDLLStorageClass 622 /// ... -> global variable 623 bool LLParser::parseNamedGlobal() { 624 assert(Lex.getKind() == lltok::GlobalVar); 625 LocTy NameLoc = Lex.getLoc(); 626 std::string Name = Lex.getStrVal(); 627 Lex.Lex(); 628 629 bool HasLinkage; 630 unsigned Linkage, Visibility, DLLStorageClass; 631 bool DSOLocal; 632 GlobalVariable::ThreadLocalMode TLM; 633 GlobalVariable::UnnamedAddr UnnamedAddr; 634 if (parseToken(lltok::equal, "expected '=' in global variable") || 635 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass, 636 DSOLocal) || 637 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr)) 638 return true; 639 640 switch (Lex.getKind()) { 641 default: 642 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility, 643 DLLStorageClass, DSOLocal, TLM, UnnamedAddr); 644 case lltok::kw_alias: 645 case lltok::kw_ifunc: 646 return parseAliasOrIFunc(Name, NameLoc, Linkage, Visibility, 647 DLLStorageClass, DSOLocal, TLM, UnnamedAddr); 648 } 649 } 650 651 bool LLParser::parseComdat() { 652 assert(Lex.getKind() == lltok::ComdatVar); 653 std::string Name = Lex.getStrVal(); 654 LocTy NameLoc = Lex.getLoc(); 655 Lex.Lex(); 656 657 if (parseToken(lltok::equal, "expected '=' here")) 658 return true; 659 660 if (parseToken(lltok::kw_comdat, "expected comdat keyword")) 661 return tokError("expected comdat type"); 662 663 Comdat::SelectionKind SK; 664 switch (Lex.getKind()) { 665 default: 666 return tokError("unknown selection kind"); 667 case lltok::kw_any: 668 SK = Comdat::Any; 669 break; 670 case lltok::kw_exactmatch: 671 SK = Comdat::ExactMatch; 672 break; 673 case lltok::kw_largest: 674 SK = Comdat::Largest; 675 break; 676 case lltok::kw_nodeduplicate: 677 SK = Comdat::NoDeduplicate; 678 break; 679 case lltok::kw_samesize: 680 SK = Comdat::SameSize; 681 break; 682 } 683 Lex.Lex(); 684 685 // See if the comdat was forward referenced, if so, use the comdat. 686 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable(); 687 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name); 688 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name)) 689 return error(NameLoc, "redefinition of comdat '$" + Name + "'"); 690 691 Comdat *C; 692 if (I != ComdatSymTab.end()) 693 C = &I->second; 694 else 695 C = M->getOrInsertComdat(Name); 696 C->setSelectionKind(SK); 697 698 return false; 699 } 700 701 // MDString: 702 // ::= '!' STRINGCONSTANT 703 bool LLParser::parseMDString(MDString *&Result) { 704 std::string Str; 705 if (parseStringConstant(Str)) 706 return true; 707 Result = MDString::get(Context, Str); 708 return false; 709 } 710 711 // MDNode: 712 // ::= '!' MDNodeNumber 713 bool LLParser::parseMDNodeID(MDNode *&Result) { 714 // !{ ..., !42, ... } 715 LocTy IDLoc = Lex.getLoc(); 716 unsigned MID = 0; 717 if (parseUInt32(MID)) 718 return true; 719 720 // If not a forward reference, just return it now. 721 if (NumberedMetadata.count(MID)) { 722 Result = NumberedMetadata[MID]; 723 return false; 724 } 725 726 // Otherwise, create MDNode forward reference. 727 auto &FwdRef = ForwardRefMDNodes[MID]; 728 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc); 729 730 Result = FwdRef.first.get(); 731 NumberedMetadata[MID].reset(Result); 732 return false; 733 } 734 735 /// parseNamedMetadata: 736 /// !foo = !{ !1, !2 } 737 bool LLParser::parseNamedMetadata() { 738 assert(Lex.getKind() == lltok::MetadataVar); 739 std::string Name = Lex.getStrVal(); 740 Lex.Lex(); 741 742 if (parseToken(lltok::equal, "expected '=' here") || 743 parseToken(lltok::exclaim, "Expected '!' here") || 744 parseToken(lltok::lbrace, "Expected '{' here")) 745 return true; 746 747 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name); 748 if (Lex.getKind() != lltok::rbrace) 749 do { 750 MDNode *N = nullptr; 751 // parse DIExpressions inline as a special case. They are still MDNodes, 752 // so they can still appear in named metadata. Remove this logic if they 753 // become plain Metadata. 754 if (Lex.getKind() == lltok::MetadataVar && 755 Lex.getStrVal() == "DIExpression") { 756 if (parseDIExpression(N, /*IsDistinct=*/false)) 757 return true; 758 // DIArgLists should only appear inline in a function, as they may 759 // contain LocalAsMetadata arguments which require a function context. 760 } else if (Lex.getKind() == lltok::MetadataVar && 761 Lex.getStrVal() == "DIArgList") { 762 return tokError("found DIArgList outside of function"); 763 } else if (parseToken(lltok::exclaim, "Expected '!' here") || 764 parseMDNodeID(N)) { 765 return true; 766 } 767 NMD->addOperand(N); 768 } while (EatIfPresent(lltok::comma)); 769 770 return parseToken(lltok::rbrace, "expected end of metadata node"); 771 } 772 773 /// parseStandaloneMetadata: 774 /// !42 = !{...} 775 bool LLParser::parseStandaloneMetadata() { 776 assert(Lex.getKind() == lltok::exclaim); 777 Lex.Lex(); 778 unsigned MetadataID = 0; 779 780 MDNode *Init; 781 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here")) 782 return true; 783 784 // Detect common error, from old metadata syntax. 785 if (Lex.getKind() == lltok::Type) 786 return tokError("unexpected type in metadata definition"); 787 788 bool IsDistinct = EatIfPresent(lltok::kw_distinct); 789 if (Lex.getKind() == lltok::MetadataVar) { 790 if (parseSpecializedMDNode(Init, IsDistinct)) 791 return true; 792 } else if (parseToken(lltok::exclaim, "Expected '!' here") || 793 parseMDTuple(Init, IsDistinct)) 794 return true; 795 796 // See if this was forward referenced, if so, handle it. 797 auto FI = ForwardRefMDNodes.find(MetadataID); 798 if (FI != ForwardRefMDNodes.end()) { 799 FI->second.first->replaceAllUsesWith(Init); 800 ForwardRefMDNodes.erase(FI); 801 802 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work"); 803 } else { 804 if (NumberedMetadata.count(MetadataID)) 805 return tokError("Metadata id is already used"); 806 NumberedMetadata[MetadataID].reset(Init); 807 } 808 809 return false; 810 } 811 812 // Skips a single module summary entry. 813 bool LLParser::skipModuleSummaryEntry() { 814 // Each module summary entry consists of a tag for the entry 815 // type, followed by a colon, then the fields which may be surrounded by 816 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing 817 // support is in place we will look for the tokens corresponding to the 818 // expected tags. 819 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module && 820 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags && 821 Lex.getKind() != lltok::kw_blockcount) 822 return tokError( 823 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the " 824 "start of summary entry"); 825 if (Lex.getKind() == lltok::kw_flags) 826 return parseSummaryIndexFlags(); 827 if (Lex.getKind() == lltok::kw_blockcount) 828 return parseBlockCount(); 829 Lex.Lex(); 830 if (parseToken(lltok::colon, "expected ':' at start of summary entry") || 831 parseToken(lltok::lparen, "expected '(' at start of summary entry")) 832 return true; 833 // Now walk through the parenthesized entry, until the number of open 834 // parentheses goes back down to 0 (the first '(' was parsed above). 835 unsigned NumOpenParen = 1; 836 do { 837 switch (Lex.getKind()) { 838 case lltok::lparen: 839 NumOpenParen++; 840 break; 841 case lltok::rparen: 842 NumOpenParen--; 843 break; 844 case lltok::Eof: 845 return tokError("found end of file while parsing summary entry"); 846 default: 847 // Skip everything in between parentheses. 848 break; 849 } 850 Lex.Lex(); 851 } while (NumOpenParen > 0); 852 return false; 853 } 854 855 /// SummaryEntry 856 /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry 857 bool LLParser::parseSummaryEntry() { 858 assert(Lex.getKind() == lltok::SummaryID); 859 unsigned SummaryID = Lex.getUIntVal(); 860 861 // For summary entries, colons should be treated as distinct tokens, 862 // not an indication of the end of a label token. 863 Lex.setIgnoreColonInIdentifiers(true); 864 865 Lex.Lex(); 866 if (parseToken(lltok::equal, "expected '=' here")) 867 return true; 868 869 // If we don't have an index object, skip the summary entry. 870 if (!Index) 871 return skipModuleSummaryEntry(); 872 873 bool result = false; 874 switch (Lex.getKind()) { 875 case lltok::kw_gv: 876 result = parseGVEntry(SummaryID); 877 break; 878 case lltok::kw_module: 879 result = parseModuleEntry(SummaryID); 880 break; 881 case lltok::kw_typeid: 882 result = parseTypeIdEntry(SummaryID); 883 break; 884 case lltok::kw_typeidCompatibleVTable: 885 result = parseTypeIdCompatibleVtableEntry(SummaryID); 886 break; 887 case lltok::kw_flags: 888 result = parseSummaryIndexFlags(); 889 break; 890 case lltok::kw_blockcount: 891 result = parseBlockCount(); 892 break; 893 default: 894 result = error(Lex.getLoc(), "unexpected summary kind"); 895 break; 896 } 897 Lex.setIgnoreColonInIdentifiers(false); 898 return result; 899 } 900 901 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) { 902 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) || 903 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility; 904 } 905 906 // If there was an explicit dso_local, update GV. In the absence of an explicit 907 // dso_local we keep the default value. 908 static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) { 909 if (DSOLocal) 910 GV.setDSOLocal(true); 911 } 912 913 static std::string typeComparisonErrorMessage(StringRef Message, Type *Ty1, 914 Type *Ty2) { 915 std::string ErrString; 916 raw_string_ostream ErrOS(ErrString); 917 ErrOS << Message << " (" << *Ty1 << " vs " << *Ty2 << ")"; 918 return ErrOS.str(); 919 } 920 921 /// parseAliasOrIFunc: 922 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier 923 /// OptionalVisibility OptionalDLLStorageClass 924 /// OptionalThreadLocal OptionalUnnamedAddr 925 /// 'alias|ifunc' AliaseeOrResolver SymbolAttrs* 926 /// 927 /// AliaseeOrResolver 928 /// ::= TypeAndValue 929 /// 930 /// SymbolAttrs 931 /// ::= ',' 'partition' StringConstant 932 /// 933 /// Everything through OptionalUnnamedAddr has already been parsed. 934 /// 935 bool LLParser::parseAliasOrIFunc(const std::string &Name, LocTy NameLoc, 936 unsigned L, unsigned Visibility, 937 unsigned DLLStorageClass, bool DSOLocal, 938 GlobalVariable::ThreadLocalMode TLM, 939 GlobalVariable::UnnamedAddr UnnamedAddr) { 940 bool IsAlias; 941 if (Lex.getKind() == lltok::kw_alias) 942 IsAlias = true; 943 else if (Lex.getKind() == lltok::kw_ifunc) 944 IsAlias = false; 945 else 946 llvm_unreachable("Not an alias or ifunc!"); 947 Lex.Lex(); 948 949 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L; 950 951 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage)) 952 return error(NameLoc, "invalid linkage type for alias"); 953 954 if (!isValidVisibilityForLinkage(Visibility, L)) 955 return error(NameLoc, 956 "symbol with local linkage must have default visibility"); 957 958 Type *Ty; 959 LocTy ExplicitTypeLoc = Lex.getLoc(); 960 if (parseType(Ty) || 961 parseToken(lltok::comma, "expected comma after alias or ifunc's type")) 962 return true; 963 964 Constant *Aliasee; 965 LocTy AliaseeLoc = Lex.getLoc(); 966 if (Lex.getKind() != lltok::kw_bitcast && 967 Lex.getKind() != lltok::kw_getelementptr && 968 Lex.getKind() != lltok::kw_addrspacecast && 969 Lex.getKind() != lltok::kw_inttoptr) { 970 if (parseGlobalTypeAndValue(Aliasee)) 971 return true; 972 } else { 973 // The bitcast dest type is not present, it is implied by the dest type. 974 ValID ID; 975 if (parseValID(ID, /*PFS=*/nullptr)) 976 return true; 977 if (ID.Kind != ValID::t_Constant) 978 return error(AliaseeLoc, "invalid aliasee"); 979 Aliasee = ID.ConstantVal; 980 } 981 982 Type *AliaseeType = Aliasee->getType(); 983 auto *PTy = dyn_cast<PointerType>(AliaseeType); 984 if (!PTy) 985 return error(AliaseeLoc, "An alias or ifunc must have pointer type"); 986 unsigned AddrSpace = PTy->getAddressSpace(); 987 988 if (IsAlias && !PTy->isOpaqueOrPointeeTypeMatches(Ty)) { 989 return error( 990 ExplicitTypeLoc, 991 typeComparisonErrorMessage( 992 "explicit pointee type doesn't match operand's pointee type", Ty, 993 PTy->getNonOpaquePointerElementType())); 994 } 995 996 if (!IsAlias && !PTy->getPointerElementType()->isFunctionTy()) { 997 return error(ExplicitTypeLoc, 998 "explicit pointee type should be a function type"); 999 } 1000 1001 GlobalValue *GVal = nullptr; 1002 1003 // See if the alias was forward referenced, if so, prepare to replace the 1004 // forward reference. 1005 if (!Name.empty()) { 1006 auto I = ForwardRefVals.find(Name); 1007 if (I != ForwardRefVals.end()) { 1008 GVal = I->second.first; 1009 ForwardRefVals.erase(Name); 1010 } else if (M->getNamedValue(Name)) { 1011 return error(NameLoc, "redefinition of global '@" + Name + "'"); 1012 } 1013 } else { 1014 auto I = ForwardRefValIDs.find(NumberedVals.size()); 1015 if (I != ForwardRefValIDs.end()) { 1016 GVal = I->second.first; 1017 ForwardRefValIDs.erase(I); 1018 } 1019 } 1020 1021 // Okay, create the alias/ifunc but do not insert it into the module yet. 1022 std::unique_ptr<GlobalAlias> GA; 1023 std::unique_ptr<GlobalIFunc> GI; 1024 GlobalValue *GV; 1025 if (IsAlias) { 1026 GA.reset(GlobalAlias::create(Ty, AddrSpace, 1027 (GlobalValue::LinkageTypes)Linkage, Name, 1028 Aliasee, /*Parent*/ nullptr)); 1029 GV = GA.get(); 1030 } else { 1031 GI.reset(GlobalIFunc::create(Ty, AddrSpace, 1032 (GlobalValue::LinkageTypes)Linkage, Name, 1033 Aliasee, /*Parent*/ nullptr)); 1034 GV = GI.get(); 1035 } 1036 GV->setThreadLocalMode(TLM); 1037 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility); 1038 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 1039 GV->setUnnamedAddr(UnnamedAddr); 1040 maybeSetDSOLocal(DSOLocal, *GV); 1041 1042 // At this point we've parsed everything except for the IndirectSymbolAttrs. 1043 // Now parse them if there are any. 1044 while (Lex.getKind() == lltok::comma) { 1045 Lex.Lex(); 1046 1047 if (Lex.getKind() == lltok::kw_partition) { 1048 Lex.Lex(); 1049 GV->setPartition(Lex.getStrVal()); 1050 if (parseToken(lltok::StringConstant, "expected partition string")) 1051 return true; 1052 } else { 1053 return tokError("unknown alias or ifunc property!"); 1054 } 1055 } 1056 1057 if (Name.empty()) 1058 NumberedVals.push_back(GV); 1059 1060 if (GVal) { 1061 // Verify that types agree. 1062 if (GVal->getType() != GV->getType()) 1063 return error( 1064 ExplicitTypeLoc, 1065 "forward reference and definition of alias have different types"); 1066 1067 // If they agree, just RAUW the old value with the alias and remove the 1068 // forward ref info. 1069 GVal->replaceAllUsesWith(GV); 1070 GVal->eraseFromParent(); 1071 } 1072 1073 // Insert into the module, we know its name won't collide now. 1074 if (IsAlias) 1075 M->getAliasList().push_back(GA.release()); 1076 else 1077 M->getIFuncList().push_back(GI.release()); 1078 assert(GV->getName() == Name && "Should not be a name conflict!"); 1079 1080 return false; 1081 } 1082 1083 /// parseGlobal 1084 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier 1085 /// OptionalVisibility OptionalDLLStorageClass 1086 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace 1087 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs 1088 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility 1089 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr 1090 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type 1091 /// Const OptionalAttrs 1092 /// 1093 /// Everything up to and including OptionalUnnamedAddr has been parsed 1094 /// already. 1095 /// 1096 bool LLParser::parseGlobal(const std::string &Name, LocTy NameLoc, 1097 unsigned Linkage, bool HasLinkage, 1098 unsigned Visibility, unsigned DLLStorageClass, 1099 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM, 1100 GlobalVariable::UnnamedAddr UnnamedAddr) { 1101 if (!isValidVisibilityForLinkage(Visibility, Linkage)) 1102 return error(NameLoc, 1103 "symbol with local linkage must have default visibility"); 1104 1105 unsigned AddrSpace; 1106 bool IsConstant, IsExternallyInitialized; 1107 LocTy IsExternallyInitializedLoc; 1108 LocTy TyLoc; 1109 1110 Type *Ty = nullptr; 1111 if (parseOptionalAddrSpace(AddrSpace) || 1112 parseOptionalToken(lltok::kw_externally_initialized, 1113 IsExternallyInitialized, 1114 &IsExternallyInitializedLoc) || 1115 parseGlobalType(IsConstant) || parseType(Ty, TyLoc)) 1116 return true; 1117 1118 // If the linkage is specified and is external, then no initializer is 1119 // present. 1120 Constant *Init = nullptr; 1121 if (!HasLinkage || 1122 !GlobalValue::isValidDeclarationLinkage( 1123 (GlobalValue::LinkageTypes)Linkage)) { 1124 if (parseGlobalValue(Ty, Init)) 1125 return true; 1126 } 1127 1128 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty)) 1129 return error(TyLoc, "invalid type for global variable"); 1130 1131 GlobalValue *GVal = nullptr; 1132 1133 // See if the global was forward referenced, if so, use the global. 1134 if (!Name.empty()) { 1135 auto I = ForwardRefVals.find(Name); 1136 if (I != ForwardRefVals.end()) { 1137 GVal = I->second.first; 1138 ForwardRefVals.erase(I); 1139 } else if (M->getNamedValue(Name)) { 1140 return error(NameLoc, "redefinition of global '@" + Name + "'"); 1141 } 1142 } else { 1143 auto I = ForwardRefValIDs.find(NumberedVals.size()); 1144 if (I != ForwardRefValIDs.end()) { 1145 GVal = I->second.first; 1146 ForwardRefValIDs.erase(I); 1147 } 1148 } 1149 1150 GlobalVariable *GV = new GlobalVariable( 1151 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr, 1152 GlobalVariable::NotThreadLocal, AddrSpace); 1153 1154 if (Name.empty()) 1155 NumberedVals.push_back(GV); 1156 1157 // Set the parsed properties on the global. 1158 if (Init) 1159 GV->setInitializer(Init); 1160 GV->setConstant(IsConstant); 1161 GV->setLinkage((GlobalValue::LinkageTypes)Linkage); 1162 maybeSetDSOLocal(DSOLocal, *GV); 1163 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility); 1164 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 1165 GV->setExternallyInitialized(IsExternallyInitialized); 1166 GV->setThreadLocalMode(TLM); 1167 GV->setUnnamedAddr(UnnamedAddr); 1168 1169 if (GVal) { 1170 if (!GVal->getType()->isOpaque() && GVal->getValueType() != Ty) 1171 return error( 1172 TyLoc, 1173 "forward reference and definition of global have different types"); 1174 1175 GVal->replaceAllUsesWith(GV); 1176 GVal->eraseFromParent(); 1177 } 1178 1179 // parse attributes on the global. 1180 while (Lex.getKind() == lltok::comma) { 1181 Lex.Lex(); 1182 1183 if (Lex.getKind() == lltok::kw_section) { 1184 Lex.Lex(); 1185 GV->setSection(Lex.getStrVal()); 1186 if (parseToken(lltok::StringConstant, "expected global section string")) 1187 return true; 1188 } else if (Lex.getKind() == lltok::kw_partition) { 1189 Lex.Lex(); 1190 GV->setPartition(Lex.getStrVal()); 1191 if (parseToken(lltok::StringConstant, "expected partition string")) 1192 return true; 1193 } else if (Lex.getKind() == lltok::kw_align) { 1194 MaybeAlign Alignment; 1195 if (parseOptionalAlignment(Alignment)) 1196 return true; 1197 GV->setAlignment(Alignment); 1198 } else if (Lex.getKind() == lltok::MetadataVar) { 1199 if (parseGlobalObjectMetadataAttachment(*GV)) 1200 return true; 1201 } else { 1202 Comdat *C; 1203 if (parseOptionalComdat(Name, C)) 1204 return true; 1205 if (C) 1206 GV->setComdat(C); 1207 else 1208 return tokError("unknown global variable property!"); 1209 } 1210 } 1211 1212 AttrBuilder Attrs(M->getContext()); 1213 LocTy BuiltinLoc; 1214 std::vector<unsigned> FwdRefAttrGrps; 1215 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc)) 1216 return true; 1217 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) { 1218 GV->setAttributes(AttributeSet::get(Context, Attrs)); 1219 ForwardRefAttrGroups[GV] = FwdRefAttrGrps; 1220 } 1221 1222 return false; 1223 } 1224 1225 /// parseUnnamedAttrGrp 1226 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}' 1227 bool LLParser::parseUnnamedAttrGrp() { 1228 assert(Lex.getKind() == lltok::kw_attributes); 1229 LocTy AttrGrpLoc = Lex.getLoc(); 1230 Lex.Lex(); 1231 1232 if (Lex.getKind() != lltok::AttrGrpID) 1233 return tokError("expected attribute group id"); 1234 1235 unsigned VarID = Lex.getUIntVal(); 1236 std::vector<unsigned> unused; 1237 LocTy BuiltinLoc; 1238 Lex.Lex(); 1239 1240 if (parseToken(lltok::equal, "expected '=' here") || 1241 parseToken(lltok::lbrace, "expected '{' here")) 1242 return true; 1243 1244 auto R = NumberedAttrBuilders.find(VarID); 1245 if (R == NumberedAttrBuilders.end()) 1246 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first; 1247 1248 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) || 1249 parseToken(lltok::rbrace, "expected end of attribute group")) 1250 return true; 1251 1252 if (!R->second.hasAttributes()) 1253 return error(AttrGrpLoc, "attribute group has no attributes"); 1254 1255 return false; 1256 } 1257 1258 static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind) { 1259 switch (Kind) { 1260 #define GET_ATTR_NAMES 1261 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \ 1262 case lltok::kw_##DISPLAY_NAME: \ 1263 return Attribute::ENUM_NAME; 1264 #include "llvm/IR/Attributes.inc" 1265 default: 1266 return Attribute::None; 1267 } 1268 } 1269 1270 bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B, 1271 bool InAttrGroup) { 1272 if (Attribute::isTypeAttrKind(Attr)) 1273 return parseRequiredTypeAttr(B, Lex.getKind(), Attr); 1274 1275 switch (Attr) { 1276 case Attribute::Alignment: { 1277 MaybeAlign Alignment; 1278 if (InAttrGroup) { 1279 uint32_t Value = 0; 1280 Lex.Lex(); 1281 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value)) 1282 return true; 1283 Alignment = Align(Value); 1284 } else { 1285 if (parseOptionalAlignment(Alignment, true)) 1286 return true; 1287 } 1288 B.addAlignmentAttr(Alignment); 1289 return false; 1290 } 1291 case Attribute::StackAlignment: { 1292 unsigned Alignment; 1293 if (InAttrGroup) { 1294 Lex.Lex(); 1295 if (parseToken(lltok::equal, "expected '=' here") || 1296 parseUInt32(Alignment)) 1297 return true; 1298 } else { 1299 if (parseOptionalStackAlignment(Alignment)) 1300 return true; 1301 } 1302 B.addStackAlignmentAttr(Alignment); 1303 return false; 1304 } 1305 case Attribute::AllocSize: { 1306 unsigned ElemSizeArg; 1307 Optional<unsigned> NumElemsArg; 1308 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg)) 1309 return true; 1310 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg); 1311 return false; 1312 } 1313 case Attribute::VScaleRange: { 1314 unsigned MinValue, MaxValue; 1315 if (parseVScaleRangeArguments(MinValue, MaxValue)) 1316 return true; 1317 B.addVScaleRangeAttr(MinValue, 1318 MaxValue > 0 ? MaxValue : Optional<unsigned>()); 1319 return false; 1320 } 1321 case Attribute::Dereferenceable: { 1322 uint64_t Bytes; 1323 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes)) 1324 return true; 1325 B.addDereferenceableAttr(Bytes); 1326 return false; 1327 } 1328 case Attribute::DereferenceableOrNull: { 1329 uint64_t Bytes; 1330 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes)) 1331 return true; 1332 B.addDereferenceableOrNullAttr(Bytes); 1333 return false; 1334 } 1335 default: 1336 B.addAttribute(Attr); 1337 Lex.Lex(); 1338 return false; 1339 } 1340 } 1341 1342 /// parseFnAttributeValuePairs 1343 /// ::= <attr> | <attr> '=' <value> 1344 bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B, 1345 std::vector<unsigned> &FwdRefAttrGrps, 1346 bool InAttrGrp, LocTy &BuiltinLoc) { 1347 bool HaveError = false; 1348 1349 B.clear(); 1350 1351 while (true) { 1352 lltok::Kind Token = Lex.getKind(); 1353 if (Token == lltok::rbrace) 1354 return HaveError; // Finished. 1355 1356 if (Token == lltok::StringConstant) { 1357 if (parseStringAttribute(B)) 1358 return true; 1359 continue; 1360 } 1361 1362 if (Token == lltok::AttrGrpID) { 1363 // Allow a function to reference an attribute group: 1364 // 1365 // define void @foo() #1 { ... } 1366 if (InAttrGrp) { 1367 HaveError |= error( 1368 Lex.getLoc(), 1369 "cannot have an attribute group reference in an attribute group"); 1370 } else { 1371 // Save the reference to the attribute group. We'll fill it in later. 1372 FwdRefAttrGrps.push_back(Lex.getUIntVal()); 1373 } 1374 Lex.Lex(); 1375 continue; 1376 } 1377 1378 SMLoc Loc = Lex.getLoc(); 1379 if (Token == lltok::kw_builtin) 1380 BuiltinLoc = Loc; 1381 1382 Attribute::AttrKind Attr = tokenToAttribute(Token); 1383 if (Attr == Attribute::None) { 1384 if (!InAttrGrp) 1385 return HaveError; 1386 return error(Lex.getLoc(), "unterminated attribute group"); 1387 } 1388 1389 if (parseEnumAttribute(Attr, B, InAttrGrp)) 1390 return true; 1391 1392 // As a hack, we allow function alignment to be initially parsed as an 1393 // attribute on a function declaration/definition or added to an attribute 1394 // group and later moved to the alignment field. 1395 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment) 1396 HaveError |= error(Loc, "this attribute does not apply to functions"); 1397 } 1398 } 1399 1400 //===----------------------------------------------------------------------===// 1401 // GlobalValue Reference/Resolution Routines. 1402 //===----------------------------------------------------------------------===// 1403 1404 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy) { 1405 // For opaque pointers, the used global type does not matter. We will later 1406 // RAUW it with a global/function of the correct type. 1407 if (PTy->isOpaque()) 1408 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false, 1409 GlobalValue::ExternalWeakLinkage, nullptr, "", 1410 nullptr, GlobalVariable::NotThreadLocal, 1411 PTy->getAddressSpace()); 1412 1413 Type *ElemTy = PTy->getNonOpaquePointerElementType(); 1414 if (auto *FT = dyn_cast<FunctionType>(ElemTy)) 1415 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, 1416 PTy->getAddressSpace(), "", M); 1417 else 1418 return new GlobalVariable( 1419 *M, ElemTy, false, GlobalValue::ExternalWeakLinkage, nullptr, "", 1420 nullptr, GlobalVariable::NotThreadLocal, PTy->getAddressSpace()); 1421 } 1422 1423 Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty, 1424 Value *Val) { 1425 Type *ValTy = Val->getType(); 1426 if (ValTy == Ty) 1427 return Val; 1428 if (Ty->isLabelTy()) 1429 error(Loc, "'" + Name + "' is not a basic block"); 1430 else 1431 error(Loc, "'" + Name + "' defined with type '" + 1432 getTypeString(Val->getType()) + "' but expected '" + 1433 getTypeString(Ty) + "'"); 1434 return nullptr; 1435 } 1436 1437 /// getGlobalVal - Get a value with the specified name or ID, creating a 1438 /// forward reference record if needed. This can return null if the value 1439 /// exists but does not have the right type. 1440 GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty, 1441 LocTy Loc) { 1442 PointerType *PTy = dyn_cast<PointerType>(Ty); 1443 if (!PTy) { 1444 error(Loc, "global variable reference must have pointer type"); 1445 return nullptr; 1446 } 1447 1448 // Look this name up in the normal function symbol table. 1449 GlobalValue *Val = 1450 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name)); 1451 1452 // If this is a forward reference for the value, see if we already created a 1453 // forward ref record. 1454 if (!Val) { 1455 auto I = ForwardRefVals.find(Name); 1456 if (I != ForwardRefVals.end()) 1457 Val = I->second.first; 1458 } 1459 1460 // If we have the value in the symbol table or fwd-ref table, return it. 1461 if (Val) 1462 return cast_or_null<GlobalValue>( 1463 checkValidVariableType(Loc, "@" + Name, Ty, Val)); 1464 1465 // Otherwise, create a new forward reference for this value and remember it. 1466 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy); 1467 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 1468 return FwdVal; 1469 } 1470 1471 GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) { 1472 PointerType *PTy = dyn_cast<PointerType>(Ty); 1473 if (!PTy) { 1474 error(Loc, "global variable reference must have pointer type"); 1475 return nullptr; 1476 } 1477 1478 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr; 1479 1480 // If this is a forward reference for the value, see if we already created a 1481 // forward ref record. 1482 if (!Val) { 1483 auto I = ForwardRefValIDs.find(ID); 1484 if (I != ForwardRefValIDs.end()) 1485 Val = I->second.first; 1486 } 1487 1488 // If we have the value in the symbol table or fwd-ref table, return it. 1489 if (Val) 1490 return cast_or_null<GlobalValue>( 1491 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val)); 1492 1493 // Otherwise, create a new forward reference for this value and remember it. 1494 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy); 1495 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 1496 return FwdVal; 1497 } 1498 1499 //===----------------------------------------------------------------------===// 1500 // Comdat Reference/Resolution Routines. 1501 //===----------------------------------------------------------------------===// 1502 1503 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) { 1504 // Look this name up in the comdat symbol table. 1505 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable(); 1506 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name); 1507 if (I != ComdatSymTab.end()) 1508 return &I->second; 1509 1510 // Otherwise, create a new forward reference for this value and remember it. 1511 Comdat *C = M->getOrInsertComdat(Name); 1512 ForwardRefComdats[Name] = Loc; 1513 return C; 1514 } 1515 1516 //===----------------------------------------------------------------------===// 1517 // Helper Routines. 1518 //===----------------------------------------------------------------------===// 1519 1520 /// parseToken - If the current token has the specified kind, eat it and return 1521 /// success. Otherwise, emit the specified error and return failure. 1522 bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) { 1523 if (Lex.getKind() != T) 1524 return tokError(ErrMsg); 1525 Lex.Lex(); 1526 return false; 1527 } 1528 1529 /// parseStringConstant 1530 /// ::= StringConstant 1531 bool LLParser::parseStringConstant(std::string &Result) { 1532 if (Lex.getKind() != lltok::StringConstant) 1533 return tokError("expected string constant"); 1534 Result = Lex.getStrVal(); 1535 Lex.Lex(); 1536 return false; 1537 } 1538 1539 /// parseUInt32 1540 /// ::= uint32 1541 bool LLParser::parseUInt32(uint32_t &Val) { 1542 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 1543 return tokError("expected integer"); 1544 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1); 1545 if (Val64 != unsigned(Val64)) 1546 return tokError("expected 32-bit integer (too large)"); 1547 Val = Val64; 1548 Lex.Lex(); 1549 return false; 1550 } 1551 1552 /// parseUInt64 1553 /// ::= uint64 1554 bool LLParser::parseUInt64(uint64_t &Val) { 1555 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 1556 return tokError("expected integer"); 1557 Val = Lex.getAPSIntVal().getLimitedValue(); 1558 Lex.Lex(); 1559 return false; 1560 } 1561 1562 /// parseTLSModel 1563 /// := 'localdynamic' 1564 /// := 'initialexec' 1565 /// := 'localexec' 1566 bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) { 1567 switch (Lex.getKind()) { 1568 default: 1569 return tokError("expected localdynamic, initialexec or localexec"); 1570 case lltok::kw_localdynamic: 1571 TLM = GlobalVariable::LocalDynamicTLSModel; 1572 break; 1573 case lltok::kw_initialexec: 1574 TLM = GlobalVariable::InitialExecTLSModel; 1575 break; 1576 case lltok::kw_localexec: 1577 TLM = GlobalVariable::LocalExecTLSModel; 1578 break; 1579 } 1580 1581 Lex.Lex(); 1582 return false; 1583 } 1584 1585 /// parseOptionalThreadLocal 1586 /// := /*empty*/ 1587 /// := 'thread_local' 1588 /// := 'thread_local' '(' tlsmodel ')' 1589 bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) { 1590 TLM = GlobalVariable::NotThreadLocal; 1591 if (!EatIfPresent(lltok::kw_thread_local)) 1592 return false; 1593 1594 TLM = GlobalVariable::GeneralDynamicTLSModel; 1595 if (Lex.getKind() == lltok::lparen) { 1596 Lex.Lex(); 1597 return parseTLSModel(TLM) || 1598 parseToken(lltok::rparen, "expected ')' after thread local model"); 1599 } 1600 return false; 1601 } 1602 1603 /// parseOptionalAddrSpace 1604 /// := /*empty*/ 1605 /// := 'addrspace' '(' uint32 ')' 1606 bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) { 1607 AddrSpace = DefaultAS; 1608 if (!EatIfPresent(lltok::kw_addrspace)) 1609 return false; 1610 return parseToken(lltok::lparen, "expected '(' in address space") || 1611 parseUInt32(AddrSpace) || 1612 parseToken(lltok::rparen, "expected ')' in address space"); 1613 } 1614 1615 /// parseStringAttribute 1616 /// := StringConstant 1617 /// := StringConstant '=' StringConstant 1618 bool LLParser::parseStringAttribute(AttrBuilder &B) { 1619 std::string Attr = Lex.getStrVal(); 1620 Lex.Lex(); 1621 std::string Val; 1622 if (EatIfPresent(lltok::equal) && parseStringConstant(Val)) 1623 return true; 1624 B.addAttribute(Attr, Val); 1625 return false; 1626 } 1627 1628 /// Parse a potentially empty list of parameter or return attributes. 1629 bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) { 1630 bool HaveError = false; 1631 1632 B.clear(); 1633 1634 while (true) { 1635 lltok::Kind Token = Lex.getKind(); 1636 if (Token == lltok::StringConstant) { 1637 if (parseStringAttribute(B)) 1638 return true; 1639 continue; 1640 } 1641 1642 SMLoc Loc = Lex.getLoc(); 1643 Attribute::AttrKind Attr = tokenToAttribute(Token); 1644 if (Attr == Attribute::None) 1645 return HaveError; 1646 1647 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false)) 1648 return true; 1649 1650 if (IsParam && !Attribute::canUseAsParamAttr(Attr)) 1651 HaveError |= error(Loc, "this attribute does not apply to parameters"); 1652 if (!IsParam && !Attribute::canUseAsRetAttr(Attr)) 1653 HaveError |= error(Loc, "this attribute does not apply to return values"); 1654 } 1655 } 1656 1657 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) { 1658 HasLinkage = true; 1659 switch (Kind) { 1660 default: 1661 HasLinkage = false; 1662 return GlobalValue::ExternalLinkage; 1663 case lltok::kw_private: 1664 return GlobalValue::PrivateLinkage; 1665 case lltok::kw_internal: 1666 return GlobalValue::InternalLinkage; 1667 case lltok::kw_weak: 1668 return GlobalValue::WeakAnyLinkage; 1669 case lltok::kw_weak_odr: 1670 return GlobalValue::WeakODRLinkage; 1671 case lltok::kw_linkonce: 1672 return GlobalValue::LinkOnceAnyLinkage; 1673 case lltok::kw_linkonce_odr: 1674 return GlobalValue::LinkOnceODRLinkage; 1675 case lltok::kw_available_externally: 1676 return GlobalValue::AvailableExternallyLinkage; 1677 case lltok::kw_appending: 1678 return GlobalValue::AppendingLinkage; 1679 case lltok::kw_common: 1680 return GlobalValue::CommonLinkage; 1681 case lltok::kw_extern_weak: 1682 return GlobalValue::ExternalWeakLinkage; 1683 case lltok::kw_external: 1684 return GlobalValue::ExternalLinkage; 1685 } 1686 } 1687 1688 /// parseOptionalLinkage 1689 /// ::= /*empty*/ 1690 /// ::= 'private' 1691 /// ::= 'internal' 1692 /// ::= 'weak' 1693 /// ::= 'weak_odr' 1694 /// ::= 'linkonce' 1695 /// ::= 'linkonce_odr' 1696 /// ::= 'available_externally' 1697 /// ::= 'appending' 1698 /// ::= 'common' 1699 /// ::= 'extern_weak' 1700 /// ::= 'external' 1701 bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage, 1702 unsigned &Visibility, 1703 unsigned &DLLStorageClass, bool &DSOLocal) { 1704 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage); 1705 if (HasLinkage) 1706 Lex.Lex(); 1707 parseOptionalDSOLocal(DSOLocal); 1708 parseOptionalVisibility(Visibility); 1709 parseOptionalDLLStorageClass(DLLStorageClass); 1710 1711 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) { 1712 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch"); 1713 } 1714 1715 return false; 1716 } 1717 1718 void LLParser::parseOptionalDSOLocal(bool &DSOLocal) { 1719 switch (Lex.getKind()) { 1720 default: 1721 DSOLocal = false; 1722 break; 1723 case lltok::kw_dso_local: 1724 DSOLocal = true; 1725 Lex.Lex(); 1726 break; 1727 case lltok::kw_dso_preemptable: 1728 DSOLocal = false; 1729 Lex.Lex(); 1730 break; 1731 } 1732 } 1733 1734 /// parseOptionalVisibility 1735 /// ::= /*empty*/ 1736 /// ::= 'default' 1737 /// ::= 'hidden' 1738 /// ::= 'protected' 1739 /// 1740 void LLParser::parseOptionalVisibility(unsigned &Res) { 1741 switch (Lex.getKind()) { 1742 default: 1743 Res = GlobalValue::DefaultVisibility; 1744 return; 1745 case lltok::kw_default: 1746 Res = GlobalValue::DefaultVisibility; 1747 break; 1748 case lltok::kw_hidden: 1749 Res = GlobalValue::HiddenVisibility; 1750 break; 1751 case lltok::kw_protected: 1752 Res = GlobalValue::ProtectedVisibility; 1753 break; 1754 } 1755 Lex.Lex(); 1756 } 1757 1758 /// parseOptionalDLLStorageClass 1759 /// ::= /*empty*/ 1760 /// ::= 'dllimport' 1761 /// ::= 'dllexport' 1762 /// 1763 void LLParser::parseOptionalDLLStorageClass(unsigned &Res) { 1764 switch (Lex.getKind()) { 1765 default: 1766 Res = GlobalValue::DefaultStorageClass; 1767 return; 1768 case lltok::kw_dllimport: 1769 Res = GlobalValue::DLLImportStorageClass; 1770 break; 1771 case lltok::kw_dllexport: 1772 Res = GlobalValue::DLLExportStorageClass; 1773 break; 1774 } 1775 Lex.Lex(); 1776 } 1777 1778 /// parseOptionalCallingConv 1779 /// ::= /*empty*/ 1780 /// ::= 'ccc' 1781 /// ::= 'fastcc' 1782 /// ::= 'intel_ocl_bicc' 1783 /// ::= 'coldcc' 1784 /// ::= 'cfguard_checkcc' 1785 /// ::= 'x86_stdcallcc' 1786 /// ::= 'x86_fastcallcc' 1787 /// ::= 'x86_thiscallcc' 1788 /// ::= 'x86_vectorcallcc' 1789 /// ::= 'arm_apcscc' 1790 /// ::= 'arm_aapcscc' 1791 /// ::= 'arm_aapcs_vfpcc' 1792 /// ::= 'aarch64_vector_pcs' 1793 /// ::= 'aarch64_sve_vector_pcs' 1794 /// ::= 'msp430_intrcc' 1795 /// ::= 'avr_intrcc' 1796 /// ::= 'avr_signalcc' 1797 /// ::= 'ptx_kernel' 1798 /// ::= 'ptx_device' 1799 /// ::= 'spir_func' 1800 /// ::= 'spir_kernel' 1801 /// ::= 'x86_64_sysvcc' 1802 /// ::= 'win64cc' 1803 /// ::= 'webkit_jscc' 1804 /// ::= 'anyregcc' 1805 /// ::= 'preserve_mostcc' 1806 /// ::= 'preserve_allcc' 1807 /// ::= 'ghccc' 1808 /// ::= 'swiftcc' 1809 /// ::= 'swifttailcc' 1810 /// ::= 'x86_intrcc' 1811 /// ::= 'hhvmcc' 1812 /// ::= 'hhvm_ccc' 1813 /// ::= 'cxx_fast_tlscc' 1814 /// ::= 'amdgpu_vs' 1815 /// ::= 'amdgpu_ls' 1816 /// ::= 'amdgpu_hs' 1817 /// ::= 'amdgpu_es' 1818 /// ::= 'amdgpu_gs' 1819 /// ::= 'amdgpu_ps' 1820 /// ::= 'amdgpu_cs' 1821 /// ::= 'amdgpu_kernel' 1822 /// ::= 'tailcc' 1823 /// ::= 'cc' UINT 1824 /// 1825 bool LLParser::parseOptionalCallingConv(unsigned &CC) { 1826 switch (Lex.getKind()) { 1827 default: CC = CallingConv::C; return false; 1828 case lltok::kw_ccc: CC = CallingConv::C; break; 1829 case lltok::kw_fastcc: CC = CallingConv::Fast; break; 1830 case lltok::kw_coldcc: CC = CallingConv::Cold; break; 1831 case lltok::kw_cfguard_checkcc: CC = CallingConv::CFGuard_Check; break; 1832 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break; 1833 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break; 1834 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break; 1835 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break; 1836 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break; 1837 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break; 1838 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break; 1839 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break; 1840 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break; 1841 case lltok::kw_aarch64_sve_vector_pcs: 1842 CC = CallingConv::AArch64_SVE_VectorCall; 1843 break; 1844 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break; 1845 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break; 1846 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break; 1847 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break; 1848 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break; 1849 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break; 1850 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break; 1851 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break; 1852 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break; 1853 case lltok::kw_win64cc: CC = CallingConv::Win64; break; 1854 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break; 1855 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break; 1856 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break; 1857 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break; 1858 case lltok::kw_ghccc: CC = CallingConv::GHC; break; 1859 case lltok::kw_swiftcc: CC = CallingConv::Swift; break; 1860 case lltok::kw_swifttailcc: CC = CallingConv::SwiftTail; break; 1861 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break; 1862 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break; 1863 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break; 1864 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break; 1865 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break; 1866 case lltok::kw_amdgpu_gfx: CC = CallingConv::AMDGPU_Gfx; break; 1867 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break; 1868 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break; 1869 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break; 1870 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break; 1871 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break; 1872 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break; 1873 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break; 1874 case lltok::kw_tailcc: CC = CallingConv::Tail; break; 1875 case lltok::kw_cc: { 1876 Lex.Lex(); 1877 return parseUInt32(CC); 1878 } 1879 } 1880 1881 Lex.Lex(); 1882 return false; 1883 } 1884 1885 /// parseMetadataAttachment 1886 /// ::= !dbg !42 1887 bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) { 1888 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment"); 1889 1890 std::string Name = Lex.getStrVal(); 1891 Kind = M->getMDKindID(Name); 1892 Lex.Lex(); 1893 1894 return parseMDNode(MD); 1895 } 1896 1897 /// parseInstructionMetadata 1898 /// ::= !dbg !42 (',' !dbg !57)* 1899 bool LLParser::parseInstructionMetadata(Instruction &Inst) { 1900 do { 1901 if (Lex.getKind() != lltok::MetadataVar) 1902 return tokError("expected metadata after comma"); 1903 1904 unsigned MDK; 1905 MDNode *N; 1906 if (parseMetadataAttachment(MDK, N)) 1907 return true; 1908 1909 Inst.setMetadata(MDK, N); 1910 if (MDK == LLVMContext::MD_tbaa) 1911 InstsWithTBAATag.push_back(&Inst); 1912 1913 // If this is the end of the list, we're done. 1914 } while (EatIfPresent(lltok::comma)); 1915 return false; 1916 } 1917 1918 /// parseGlobalObjectMetadataAttachment 1919 /// ::= !dbg !57 1920 bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) { 1921 unsigned MDK; 1922 MDNode *N; 1923 if (parseMetadataAttachment(MDK, N)) 1924 return true; 1925 1926 GO.addMetadata(MDK, *N); 1927 return false; 1928 } 1929 1930 /// parseOptionalFunctionMetadata 1931 /// ::= (!dbg !57)* 1932 bool LLParser::parseOptionalFunctionMetadata(Function &F) { 1933 while (Lex.getKind() == lltok::MetadataVar) 1934 if (parseGlobalObjectMetadataAttachment(F)) 1935 return true; 1936 return false; 1937 } 1938 1939 /// parseOptionalAlignment 1940 /// ::= /* empty */ 1941 /// ::= 'align' 4 1942 bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) { 1943 Alignment = None; 1944 if (!EatIfPresent(lltok::kw_align)) 1945 return false; 1946 LocTy AlignLoc = Lex.getLoc(); 1947 uint64_t Value = 0; 1948 1949 LocTy ParenLoc = Lex.getLoc(); 1950 bool HaveParens = false; 1951 if (AllowParens) { 1952 if (EatIfPresent(lltok::lparen)) 1953 HaveParens = true; 1954 } 1955 1956 if (parseUInt64(Value)) 1957 return true; 1958 1959 if (HaveParens && !EatIfPresent(lltok::rparen)) 1960 return error(ParenLoc, "expected ')'"); 1961 1962 if (!isPowerOf2_64(Value)) 1963 return error(AlignLoc, "alignment is not a power of two"); 1964 if (Value > Value::MaximumAlignment) 1965 return error(AlignLoc, "huge alignments are not supported yet"); 1966 Alignment = Align(Value); 1967 return false; 1968 } 1969 1970 /// parseOptionalDerefAttrBytes 1971 /// ::= /* empty */ 1972 /// ::= AttrKind '(' 4 ')' 1973 /// 1974 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'. 1975 bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind, 1976 uint64_t &Bytes) { 1977 assert((AttrKind == lltok::kw_dereferenceable || 1978 AttrKind == lltok::kw_dereferenceable_or_null) && 1979 "contract!"); 1980 1981 Bytes = 0; 1982 if (!EatIfPresent(AttrKind)) 1983 return false; 1984 LocTy ParenLoc = Lex.getLoc(); 1985 if (!EatIfPresent(lltok::lparen)) 1986 return error(ParenLoc, "expected '('"); 1987 LocTy DerefLoc = Lex.getLoc(); 1988 if (parseUInt64(Bytes)) 1989 return true; 1990 ParenLoc = Lex.getLoc(); 1991 if (!EatIfPresent(lltok::rparen)) 1992 return error(ParenLoc, "expected ')'"); 1993 if (!Bytes) 1994 return error(DerefLoc, "dereferenceable bytes must be non-zero"); 1995 return false; 1996 } 1997 1998 /// parseOptionalCommaAlign 1999 /// ::= 2000 /// ::= ',' align 4 2001 /// 2002 /// This returns with AteExtraComma set to true if it ate an excess comma at the 2003 /// end. 2004 bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment, 2005 bool &AteExtraComma) { 2006 AteExtraComma = false; 2007 while (EatIfPresent(lltok::comma)) { 2008 // Metadata at the end is an early exit. 2009 if (Lex.getKind() == lltok::MetadataVar) { 2010 AteExtraComma = true; 2011 return false; 2012 } 2013 2014 if (Lex.getKind() != lltok::kw_align) 2015 return error(Lex.getLoc(), "expected metadata or 'align'"); 2016 2017 if (parseOptionalAlignment(Alignment)) 2018 return true; 2019 } 2020 2021 return false; 2022 } 2023 2024 /// parseOptionalCommaAddrSpace 2025 /// ::= 2026 /// ::= ',' addrspace(1) 2027 /// 2028 /// This returns with AteExtraComma set to true if it ate an excess comma at the 2029 /// end. 2030 bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc, 2031 bool &AteExtraComma) { 2032 AteExtraComma = false; 2033 while (EatIfPresent(lltok::comma)) { 2034 // Metadata at the end is an early exit. 2035 if (Lex.getKind() == lltok::MetadataVar) { 2036 AteExtraComma = true; 2037 return false; 2038 } 2039 2040 Loc = Lex.getLoc(); 2041 if (Lex.getKind() != lltok::kw_addrspace) 2042 return error(Lex.getLoc(), "expected metadata or 'addrspace'"); 2043 2044 if (parseOptionalAddrSpace(AddrSpace)) 2045 return true; 2046 } 2047 2048 return false; 2049 } 2050 2051 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg, 2052 Optional<unsigned> &HowManyArg) { 2053 Lex.Lex(); 2054 2055 auto StartParen = Lex.getLoc(); 2056 if (!EatIfPresent(lltok::lparen)) 2057 return error(StartParen, "expected '('"); 2058 2059 if (parseUInt32(BaseSizeArg)) 2060 return true; 2061 2062 if (EatIfPresent(lltok::comma)) { 2063 auto HowManyAt = Lex.getLoc(); 2064 unsigned HowMany; 2065 if (parseUInt32(HowMany)) 2066 return true; 2067 if (HowMany == BaseSizeArg) 2068 return error(HowManyAt, 2069 "'allocsize' indices can't refer to the same parameter"); 2070 HowManyArg = HowMany; 2071 } else 2072 HowManyArg = None; 2073 2074 auto EndParen = Lex.getLoc(); 2075 if (!EatIfPresent(lltok::rparen)) 2076 return error(EndParen, "expected ')'"); 2077 return false; 2078 } 2079 2080 bool LLParser::parseVScaleRangeArguments(unsigned &MinValue, 2081 unsigned &MaxValue) { 2082 Lex.Lex(); 2083 2084 auto StartParen = Lex.getLoc(); 2085 if (!EatIfPresent(lltok::lparen)) 2086 return error(StartParen, "expected '('"); 2087 2088 if (parseUInt32(MinValue)) 2089 return true; 2090 2091 if (EatIfPresent(lltok::comma)) { 2092 if (parseUInt32(MaxValue)) 2093 return true; 2094 } else 2095 MaxValue = MinValue; 2096 2097 auto EndParen = Lex.getLoc(); 2098 if (!EatIfPresent(lltok::rparen)) 2099 return error(EndParen, "expected ')'"); 2100 return false; 2101 } 2102 2103 /// parseScopeAndOrdering 2104 /// if isAtomic: ::= SyncScope? AtomicOrdering 2105 /// else: ::= 2106 /// 2107 /// This sets Scope and Ordering to the parsed values. 2108 bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID, 2109 AtomicOrdering &Ordering) { 2110 if (!IsAtomic) 2111 return false; 2112 2113 return parseScope(SSID) || parseOrdering(Ordering); 2114 } 2115 2116 /// parseScope 2117 /// ::= syncscope("singlethread" | "<target scope>")? 2118 /// 2119 /// This sets synchronization scope ID to the ID of the parsed value. 2120 bool LLParser::parseScope(SyncScope::ID &SSID) { 2121 SSID = SyncScope::System; 2122 if (EatIfPresent(lltok::kw_syncscope)) { 2123 auto StartParenAt = Lex.getLoc(); 2124 if (!EatIfPresent(lltok::lparen)) 2125 return error(StartParenAt, "Expected '(' in syncscope"); 2126 2127 std::string SSN; 2128 auto SSNAt = Lex.getLoc(); 2129 if (parseStringConstant(SSN)) 2130 return error(SSNAt, "Expected synchronization scope name"); 2131 2132 auto EndParenAt = Lex.getLoc(); 2133 if (!EatIfPresent(lltok::rparen)) 2134 return error(EndParenAt, "Expected ')' in syncscope"); 2135 2136 SSID = Context.getOrInsertSyncScopeID(SSN); 2137 } 2138 2139 return false; 2140 } 2141 2142 /// parseOrdering 2143 /// ::= AtomicOrdering 2144 /// 2145 /// This sets Ordering to the parsed value. 2146 bool LLParser::parseOrdering(AtomicOrdering &Ordering) { 2147 switch (Lex.getKind()) { 2148 default: 2149 return tokError("Expected ordering on atomic instruction"); 2150 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break; 2151 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break; 2152 // Not specified yet: 2153 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break; 2154 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break; 2155 case lltok::kw_release: Ordering = AtomicOrdering::Release; break; 2156 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break; 2157 case lltok::kw_seq_cst: 2158 Ordering = AtomicOrdering::SequentiallyConsistent; 2159 break; 2160 } 2161 Lex.Lex(); 2162 return false; 2163 } 2164 2165 /// parseOptionalStackAlignment 2166 /// ::= /* empty */ 2167 /// ::= 'alignstack' '(' 4 ')' 2168 bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) { 2169 Alignment = 0; 2170 if (!EatIfPresent(lltok::kw_alignstack)) 2171 return false; 2172 LocTy ParenLoc = Lex.getLoc(); 2173 if (!EatIfPresent(lltok::lparen)) 2174 return error(ParenLoc, "expected '('"); 2175 LocTy AlignLoc = Lex.getLoc(); 2176 if (parseUInt32(Alignment)) 2177 return true; 2178 ParenLoc = Lex.getLoc(); 2179 if (!EatIfPresent(lltok::rparen)) 2180 return error(ParenLoc, "expected ')'"); 2181 if (!isPowerOf2_32(Alignment)) 2182 return error(AlignLoc, "stack alignment is not a power of two"); 2183 return false; 2184 } 2185 2186 /// parseIndexList - This parses the index list for an insert/extractvalue 2187 /// instruction. This sets AteExtraComma in the case where we eat an extra 2188 /// comma at the end of the line and find that it is followed by metadata. 2189 /// Clients that don't allow metadata can call the version of this function that 2190 /// only takes one argument. 2191 /// 2192 /// parseIndexList 2193 /// ::= (',' uint32)+ 2194 /// 2195 bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices, 2196 bool &AteExtraComma) { 2197 AteExtraComma = false; 2198 2199 if (Lex.getKind() != lltok::comma) 2200 return tokError("expected ',' as start of index list"); 2201 2202 while (EatIfPresent(lltok::comma)) { 2203 if (Lex.getKind() == lltok::MetadataVar) { 2204 if (Indices.empty()) 2205 return tokError("expected index"); 2206 AteExtraComma = true; 2207 return false; 2208 } 2209 unsigned Idx = 0; 2210 if (parseUInt32(Idx)) 2211 return true; 2212 Indices.push_back(Idx); 2213 } 2214 2215 return false; 2216 } 2217 2218 //===----------------------------------------------------------------------===// 2219 // Type Parsing. 2220 //===----------------------------------------------------------------------===// 2221 2222 /// parseType - parse a type. 2223 bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) { 2224 SMLoc TypeLoc = Lex.getLoc(); 2225 switch (Lex.getKind()) { 2226 default: 2227 return tokError(Msg); 2228 case lltok::Type: 2229 // Type ::= 'float' | 'void' (etc) 2230 Result = Lex.getTyVal(); 2231 Lex.Lex(); 2232 2233 // Handle "ptr" opaque pointer type. 2234 // 2235 // Type ::= ptr ('addrspace' '(' uint32 ')')? 2236 if (Result->isOpaquePointerTy()) { 2237 unsigned AddrSpace; 2238 if (parseOptionalAddrSpace(AddrSpace)) 2239 return true; 2240 Result = PointerType::get(getContext(), AddrSpace); 2241 2242 // Give a nice error for 'ptr*'. 2243 if (Lex.getKind() == lltok::star) 2244 return tokError("ptr* is invalid - use ptr instead"); 2245 2246 // Fall through to parsing the type suffixes only if this 'ptr' is a 2247 // function return. Otherwise, return success, implicitly rejecting other 2248 // suffixes. 2249 if (Lex.getKind() != lltok::lparen) 2250 return false; 2251 } 2252 break; 2253 case lltok::lbrace: 2254 // Type ::= StructType 2255 if (parseAnonStructType(Result, false)) 2256 return true; 2257 break; 2258 case lltok::lsquare: 2259 // Type ::= '[' ... ']' 2260 Lex.Lex(); // eat the lsquare. 2261 if (parseArrayVectorType(Result, false)) 2262 return true; 2263 break; 2264 case lltok::less: // Either vector or packed struct. 2265 // Type ::= '<' ... '>' 2266 Lex.Lex(); 2267 if (Lex.getKind() == lltok::lbrace) { 2268 if (parseAnonStructType(Result, true) || 2269 parseToken(lltok::greater, "expected '>' at end of packed struct")) 2270 return true; 2271 } else if (parseArrayVectorType(Result, true)) 2272 return true; 2273 break; 2274 case lltok::LocalVar: { 2275 // Type ::= %foo 2276 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()]; 2277 2278 // If the type hasn't been defined yet, create a forward definition and 2279 // remember where that forward def'n was seen (in case it never is defined). 2280 if (!Entry.first) { 2281 Entry.first = StructType::create(Context, Lex.getStrVal()); 2282 Entry.second = Lex.getLoc(); 2283 } 2284 Result = Entry.first; 2285 Lex.Lex(); 2286 break; 2287 } 2288 2289 case lltok::LocalVarID: { 2290 // Type ::= %4 2291 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()]; 2292 2293 // If the type hasn't been defined yet, create a forward definition and 2294 // remember where that forward def'n was seen (in case it never is defined). 2295 if (!Entry.first) { 2296 Entry.first = StructType::create(Context); 2297 Entry.second = Lex.getLoc(); 2298 } 2299 Result = Entry.first; 2300 Lex.Lex(); 2301 break; 2302 } 2303 } 2304 2305 // parse the type suffixes. 2306 while (true) { 2307 switch (Lex.getKind()) { 2308 // End of type. 2309 default: 2310 if (!AllowVoid && Result->isVoidTy()) 2311 return error(TypeLoc, "void type only allowed for function results"); 2312 return false; 2313 2314 // Type ::= Type '*' 2315 case lltok::star: 2316 if (Result->isLabelTy()) 2317 return tokError("basic block pointers are invalid"); 2318 if (Result->isVoidTy()) 2319 return tokError("pointers to void are invalid - use i8* instead"); 2320 if (!PointerType::isValidElementType(Result)) 2321 return tokError("pointer to this type is invalid"); 2322 Result = PointerType::getUnqual(Result); 2323 Lex.Lex(); 2324 break; 2325 2326 // Type ::= Type 'addrspace' '(' uint32 ')' '*' 2327 case lltok::kw_addrspace: { 2328 if (Result->isLabelTy()) 2329 return tokError("basic block pointers are invalid"); 2330 if (Result->isVoidTy()) 2331 return tokError("pointers to void are invalid; use i8* instead"); 2332 if (!PointerType::isValidElementType(Result)) 2333 return tokError("pointer to this type is invalid"); 2334 unsigned AddrSpace; 2335 if (parseOptionalAddrSpace(AddrSpace) || 2336 parseToken(lltok::star, "expected '*' in address space")) 2337 return true; 2338 2339 Result = PointerType::get(Result, AddrSpace); 2340 break; 2341 } 2342 2343 /// Types '(' ArgTypeListI ')' OptFuncAttrs 2344 case lltok::lparen: 2345 if (parseFunctionType(Result)) 2346 return true; 2347 break; 2348 } 2349 } 2350 } 2351 2352 /// parseParameterList 2353 /// ::= '(' ')' 2354 /// ::= '(' Arg (',' Arg)* ')' 2355 /// Arg 2356 /// ::= Type OptionalAttributes Value OptionalAttributes 2357 bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList, 2358 PerFunctionState &PFS, bool IsMustTailCall, 2359 bool InVarArgsFunc) { 2360 if (parseToken(lltok::lparen, "expected '(' in call")) 2361 return true; 2362 2363 while (Lex.getKind() != lltok::rparen) { 2364 // If this isn't the first argument, we need a comma. 2365 if (!ArgList.empty() && 2366 parseToken(lltok::comma, "expected ',' in argument list")) 2367 return true; 2368 2369 // parse an ellipsis if this is a musttail call in a variadic function. 2370 if (Lex.getKind() == lltok::dotdotdot) { 2371 const char *Msg = "unexpected ellipsis in argument list for "; 2372 if (!IsMustTailCall) 2373 return tokError(Twine(Msg) + "non-musttail call"); 2374 if (!InVarArgsFunc) 2375 return tokError(Twine(Msg) + "musttail call in non-varargs function"); 2376 Lex.Lex(); // Lex the '...', it is purely for readability. 2377 return parseToken(lltok::rparen, "expected ')' at end of argument list"); 2378 } 2379 2380 // parse the argument. 2381 LocTy ArgLoc; 2382 Type *ArgTy = nullptr; 2383 Value *V; 2384 if (parseType(ArgTy, ArgLoc)) 2385 return true; 2386 2387 AttrBuilder ArgAttrs(M->getContext()); 2388 2389 if (ArgTy->isMetadataTy()) { 2390 if (parseMetadataAsValue(V, PFS)) 2391 return true; 2392 } else { 2393 // Otherwise, handle normal operands. 2394 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS)) 2395 return true; 2396 } 2397 ArgList.push_back(ParamInfo( 2398 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs))); 2399 } 2400 2401 if (IsMustTailCall && InVarArgsFunc) 2402 return tokError("expected '...' at end of argument list for musttail call " 2403 "in varargs function"); 2404 2405 Lex.Lex(); // Lex the ')'. 2406 return false; 2407 } 2408 2409 /// parseRequiredTypeAttr 2410 /// ::= attrname(<ty>) 2411 bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken, 2412 Attribute::AttrKind AttrKind) { 2413 Type *Ty = nullptr; 2414 if (!EatIfPresent(AttrToken)) 2415 return true; 2416 if (!EatIfPresent(lltok::lparen)) 2417 return error(Lex.getLoc(), "expected '('"); 2418 if (parseType(Ty)) 2419 return true; 2420 if (!EatIfPresent(lltok::rparen)) 2421 return error(Lex.getLoc(), "expected ')'"); 2422 2423 B.addTypeAttr(AttrKind, Ty); 2424 return false; 2425 } 2426 2427 /// parseOptionalOperandBundles 2428 /// ::= /*empty*/ 2429 /// ::= '[' OperandBundle [, OperandBundle ]* ']' 2430 /// 2431 /// OperandBundle 2432 /// ::= bundle-tag '(' ')' 2433 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')' 2434 /// 2435 /// bundle-tag ::= String Constant 2436 bool LLParser::parseOptionalOperandBundles( 2437 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) { 2438 LocTy BeginLoc = Lex.getLoc(); 2439 if (!EatIfPresent(lltok::lsquare)) 2440 return false; 2441 2442 while (Lex.getKind() != lltok::rsquare) { 2443 // If this isn't the first operand bundle, we need a comma. 2444 if (!BundleList.empty() && 2445 parseToken(lltok::comma, "expected ',' in input list")) 2446 return true; 2447 2448 std::string Tag; 2449 if (parseStringConstant(Tag)) 2450 return true; 2451 2452 if (parseToken(lltok::lparen, "expected '(' in operand bundle")) 2453 return true; 2454 2455 std::vector<Value *> Inputs; 2456 while (Lex.getKind() != lltok::rparen) { 2457 // If this isn't the first input, we need a comma. 2458 if (!Inputs.empty() && 2459 parseToken(lltok::comma, "expected ',' in input list")) 2460 return true; 2461 2462 Type *Ty = nullptr; 2463 Value *Input = nullptr; 2464 if (parseType(Ty) || parseValue(Ty, Input, PFS)) 2465 return true; 2466 Inputs.push_back(Input); 2467 } 2468 2469 BundleList.emplace_back(std::move(Tag), std::move(Inputs)); 2470 2471 Lex.Lex(); // Lex the ')'. 2472 } 2473 2474 if (BundleList.empty()) 2475 return error(BeginLoc, "operand bundle set must not be empty"); 2476 2477 Lex.Lex(); // Lex the ']'. 2478 return false; 2479 } 2480 2481 /// parseArgumentList - parse the argument list for a function type or function 2482 /// prototype. 2483 /// ::= '(' ArgTypeListI ')' 2484 /// ArgTypeListI 2485 /// ::= /*empty*/ 2486 /// ::= '...' 2487 /// ::= ArgTypeList ',' '...' 2488 /// ::= ArgType (',' ArgType)* 2489 /// 2490 bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, 2491 bool &IsVarArg) { 2492 unsigned CurValID = 0; 2493 IsVarArg = false; 2494 assert(Lex.getKind() == lltok::lparen); 2495 Lex.Lex(); // eat the (. 2496 2497 if (Lex.getKind() == lltok::rparen) { 2498 // empty 2499 } else if (Lex.getKind() == lltok::dotdotdot) { 2500 IsVarArg = true; 2501 Lex.Lex(); 2502 } else { 2503 LocTy TypeLoc = Lex.getLoc(); 2504 Type *ArgTy = nullptr; 2505 AttrBuilder Attrs(M->getContext()); 2506 std::string Name; 2507 2508 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs)) 2509 return true; 2510 2511 if (ArgTy->isVoidTy()) 2512 return error(TypeLoc, "argument can not have void type"); 2513 2514 if (Lex.getKind() == lltok::LocalVar) { 2515 Name = Lex.getStrVal(); 2516 Lex.Lex(); 2517 } else if (Lex.getKind() == lltok::LocalVarID) { 2518 if (Lex.getUIntVal() != CurValID) 2519 return error(TypeLoc, "argument expected to be numbered '%" + 2520 Twine(CurValID) + "'"); 2521 ++CurValID; 2522 Lex.Lex(); 2523 } 2524 2525 if (!FunctionType::isValidArgumentType(ArgTy)) 2526 return error(TypeLoc, "invalid type for function argument"); 2527 2528 ArgList.emplace_back(TypeLoc, ArgTy, 2529 AttributeSet::get(ArgTy->getContext(), Attrs), 2530 std::move(Name)); 2531 2532 while (EatIfPresent(lltok::comma)) { 2533 // Handle ... at end of arg list. 2534 if (EatIfPresent(lltok::dotdotdot)) { 2535 IsVarArg = true; 2536 break; 2537 } 2538 2539 // Otherwise must be an argument type. 2540 TypeLoc = Lex.getLoc(); 2541 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs)) 2542 return true; 2543 2544 if (ArgTy->isVoidTy()) 2545 return error(TypeLoc, "argument can not have void type"); 2546 2547 if (Lex.getKind() == lltok::LocalVar) { 2548 Name = Lex.getStrVal(); 2549 Lex.Lex(); 2550 } else { 2551 if (Lex.getKind() == lltok::LocalVarID) { 2552 if (Lex.getUIntVal() != CurValID) 2553 return error(TypeLoc, "argument expected to be numbered '%" + 2554 Twine(CurValID) + "'"); 2555 Lex.Lex(); 2556 } 2557 ++CurValID; 2558 Name = ""; 2559 } 2560 2561 if (!ArgTy->isFirstClassType()) 2562 return error(TypeLoc, "invalid type for function argument"); 2563 2564 ArgList.emplace_back(TypeLoc, ArgTy, 2565 AttributeSet::get(ArgTy->getContext(), Attrs), 2566 std::move(Name)); 2567 } 2568 } 2569 2570 return parseToken(lltok::rparen, "expected ')' at end of argument list"); 2571 } 2572 2573 /// parseFunctionType 2574 /// ::= Type ArgumentList OptionalAttrs 2575 bool LLParser::parseFunctionType(Type *&Result) { 2576 assert(Lex.getKind() == lltok::lparen); 2577 2578 if (!FunctionType::isValidReturnType(Result)) 2579 return tokError("invalid function return type"); 2580 2581 SmallVector<ArgInfo, 8> ArgList; 2582 bool IsVarArg; 2583 if (parseArgumentList(ArgList, IsVarArg)) 2584 return true; 2585 2586 // Reject names on the arguments lists. 2587 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 2588 if (!ArgList[i].Name.empty()) 2589 return error(ArgList[i].Loc, "argument name invalid in function type"); 2590 if (ArgList[i].Attrs.hasAttributes()) 2591 return error(ArgList[i].Loc, 2592 "argument attributes invalid in function type"); 2593 } 2594 2595 SmallVector<Type*, 16> ArgListTy; 2596 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 2597 ArgListTy.push_back(ArgList[i].Ty); 2598 2599 Result = FunctionType::get(Result, ArgListTy, IsVarArg); 2600 return false; 2601 } 2602 2603 /// parseAnonStructType - parse an anonymous struct type, which is inlined into 2604 /// other structs. 2605 bool LLParser::parseAnonStructType(Type *&Result, bool Packed) { 2606 SmallVector<Type*, 8> Elts; 2607 if (parseStructBody(Elts)) 2608 return true; 2609 2610 Result = StructType::get(Context, Elts, Packed); 2611 return false; 2612 } 2613 2614 /// parseStructDefinition - parse a struct in a 'type' definition. 2615 bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name, 2616 std::pair<Type *, LocTy> &Entry, 2617 Type *&ResultTy) { 2618 // If the type was already defined, diagnose the redefinition. 2619 if (Entry.first && !Entry.second.isValid()) 2620 return error(TypeLoc, "redefinition of type"); 2621 2622 // If we have opaque, just return without filling in the definition for the 2623 // struct. This counts as a definition as far as the .ll file goes. 2624 if (EatIfPresent(lltok::kw_opaque)) { 2625 // This type is being defined, so clear the location to indicate this. 2626 Entry.second = SMLoc(); 2627 2628 // If this type number has never been uttered, create it. 2629 if (!Entry.first) 2630 Entry.first = StructType::create(Context, Name); 2631 ResultTy = Entry.first; 2632 return false; 2633 } 2634 2635 // If the type starts with '<', then it is either a packed struct or a vector. 2636 bool isPacked = EatIfPresent(lltok::less); 2637 2638 // If we don't have a struct, then we have a random type alias, which we 2639 // accept for compatibility with old files. These types are not allowed to be 2640 // forward referenced and not allowed to be recursive. 2641 if (Lex.getKind() != lltok::lbrace) { 2642 if (Entry.first) 2643 return error(TypeLoc, "forward references to non-struct type"); 2644 2645 ResultTy = nullptr; 2646 if (isPacked) 2647 return parseArrayVectorType(ResultTy, true); 2648 return parseType(ResultTy); 2649 } 2650 2651 // This type is being defined, so clear the location to indicate this. 2652 Entry.second = SMLoc(); 2653 2654 // If this type number has never been uttered, create it. 2655 if (!Entry.first) 2656 Entry.first = StructType::create(Context, Name); 2657 2658 StructType *STy = cast<StructType>(Entry.first); 2659 2660 SmallVector<Type*, 8> Body; 2661 if (parseStructBody(Body) || 2662 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct"))) 2663 return true; 2664 2665 STy->setBody(Body, isPacked); 2666 ResultTy = STy; 2667 return false; 2668 } 2669 2670 /// parseStructType: Handles packed and unpacked types. </> parsed elsewhere. 2671 /// StructType 2672 /// ::= '{' '}' 2673 /// ::= '{' Type (',' Type)* '}' 2674 /// ::= '<' '{' '}' '>' 2675 /// ::= '<' '{' Type (',' Type)* '}' '>' 2676 bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) { 2677 assert(Lex.getKind() == lltok::lbrace); 2678 Lex.Lex(); // Consume the '{' 2679 2680 // Handle the empty struct. 2681 if (EatIfPresent(lltok::rbrace)) 2682 return false; 2683 2684 LocTy EltTyLoc = Lex.getLoc(); 2685 Type *Ty = nullptr; 2686 if (parseType(Ty)) 2687 return true; 2688 Body.push_back(Ty); 2689 2690 if (!StructType::isValidElementType(Ty)) 2691 return error(EltTyLoc, "invalid element type for struct"); 2692 2693 while (EatIfPresent(lltok::comma)) { 2694 EltTyLoc = Lex.getLoc(); 2695 if (parseType(Ty)) 2696 return true; 2697 2698 if (!StructType::isValidElementType(Ty)) 2699 return error(EltTyLoc, "invalid element type for struct"); 2700 2701 Body.push_back(Ty); 2702 } 2703 2704 return parseToken(lltok::rbrace, "expected '}' at end of struct"); 2705 } 2706 2707 /// parseArrayVectorType - parse an array or vector type, assuming the first 2708 /// token has already been consumed. 2709 /// Type 2710 /// ::= '[' APSINTVAL 'x' Types ']' 2711 /// ::= '<' APSINTVAL 'x' Types '>' 2712 /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>' 2713 bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) { 2714 bool Scalable = false; 2715 2716 if (IsVector && Lex.getKind() == lltok::kw_vscale) { 2717 Lex.Lex(); // consume the 'vscale' 2718 if (parseToken(lltok::kw_x, "expected 'x' after vscale")) 2719 return true; 2720 2721 Scalable = true; 2722 } 2723 2724 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() || 2725 Lex.getAPSIntVal().getBitWidth() > 64) 2726 return tokError("expected number in address space"); 2727 2728 LocTy SizeLoc = Lex.getLoc(); 2729 uint64_t Size = Lex.getAPSIntVal().getZExtValue(); 2730 Lex.Lex(); 2731 2732 if (parseToken(lltok::kw_x, "expected 'x' after element count")) 2733 return true; 2734 2735 LocTy TypeLoc = Lex.getLoc(); 2736 Type *EltTy = nullptr; 2737 if (parseType(EltTy)) 2738 return true; 2739 2740 if (parseToken(IsVector ? lltok::greater : lltok::rsquare, 2741 "expected end of sequential type")) 2742 return true; 2743 2744 if (IsVector) { 2745 if (Size == 0) 2746 return error(SizeLoc, "zero element vector is illegal"); 2747 if ((unsigned)Size != Size) 2748 return error(SizeLoc, "size too large for vector"); 2749 if (!VectorType::isValidElementType(EltTy)) 2750 return error(TypeLoc, "invalid vector element type"); 2751 Result = VectorType::get(EltTy, unsigned(Size), Scalable); 2752 } else { 2753 if (!ArrayType::isValidElementType(EltTy)) 2754 return error(TypeLoc, "invalid array element type"); 2755 Result = ArrayType::get(EltTy, Size); 2756 } 2757 return false; 2758 } 2759 2760 //===----------------------------------------------------------------------===// 2761 // Function Semantic Analysis. 2762 //===----------------------------------------------------------------------===// 2763 2764 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f, 2765 int functionNumber) 2766 : P(p), F(f), FunctionNumber(functionNumber) { 2767 2768 // Insert unnamed arguments into the NumberedVals list. 2769 for (Argument &A : F.args()) 2770 if (!A.hasName()) 2771 NumberedVals.push_back(&A); 2772 } 2773 2774 LLParser::PerFunctionState::~PerFunctionState() { 2775 // If there were any forward referenced non-basicblock values, delete them. 2776 2777 for (const auto &P : ForwardRefVals) { 2778 if (isa<BasicBlock>(P.second.first)) 2779 continue; 2780 P.second.first->replaceAllUsesWith( 2781 UndefValue::get(P.second.first->getType())); 2782 P.second.first->deleteValue(); 2783 } 2784 2785 for (const auto &P : ForwardRefValIDs) { 2786 if (isa<BasicBlock>(P.second.first)) 2787 continue; 2788 P.second.first->replaceAllUsesWith( 2789 UndefValue::get(P.second.first->getType())); 2790 P.second.first->deleteValue(); 2791 } 2792 } 2793 2794 bool LLParser::PerFunctionState::finishFunction() { 2795 if (!ForwardRefVals.empty()) 2796 return P.error(ForwardRefVals.begin()->second.second, 2797 "use of undefined value '%" + ForwardRefVals.begin()->first + 2798 "'"); 2799 if (!ForwardRefValIDs.empty()) 2800 return P.error(ForwardRefValIDs.begin()->second.second, 2801 "use of undefined value '%" + 2802 Twine(ForwardRefValIDs.begin()->first) + "'"); 2803 return false; 2804 } 2805 2806 /// getVal - Get a value with the specified name or ID, creating a 2807 /// forward reference record if needed. This can return null if the value 2808 /// exists but does not have the right type. 2809 Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty, 2810 LocTy Loc) { 2811 // Look this name up in the normal function symbol table. 2812 Value *Val = F.getValueSymbolTable()->lookup(Name); 2813 2814 // If this is a forward reference for the value, see if we already created a 2815 // forward ref record. 2816 if (!Val) { 2817 auto I = ForwardRefVals.find(Name); 2818 if (I != ForwardRefVals.end()) 2819 Val = I->second.first; 2820 } 2821 2822 // If we have the value in the symbol table or fwd-ref table, return it. 2823 if (Val) 2824 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val); 2825 2826 // Don't make placeholders with invalid type. 2827 if (!Ty->isFirstClassType()) { 2828 P.error(Loc, "invalid use of a non-first-class type"); 2829 return nullptr; 2830 } 2831 2832 // Otherwise, create a new forward reference for this value and remember it. 2833 Value *FwdVal; 2834 if (Ty->isLabelTy()) { 2835 FwdVal = BasicBlock::Create(F.getContext(), Name, &F); 2836 } else { 2837 FwdVal = new Argument(Ty, Name); 2838 } 2839 2840 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 2841 return FwdVal; 2842 } 2843 2844 Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) { 2845 // Look this name up in the normal function symbol table. 2846 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr; 2847 2848 // If this is a forward reference for the value, see if we already created a 2849 // forward ref record. 2850 if (!Val) { 2851 auto I = ForwardRefValIDs.find(ID); 2852 if (I != ForwardRefValIDs.end()) 2853 Val = I->second.first; 2854 } 2855 2856 // If we have the value in the symbol table or fwd-ref table, return it. 2857 if (Val) 2858 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val); 2859 2860 if (!Ty->isFirstClassType()) { 2861 P.error(Loc, "invalid use of a non-first-class type"); 2862 return nullptr; 2863 } 2864 2865 // Otherwise, create a new forward reference for this value and remember it. 2866 Value *FwdVal; 2867 if (Ty->isLabelTy()) { 2868 FwdVal = BasicBlock::Create(F.getContext(), "", &F); 2869 } else { 2870 FwdVal = new Argument(Ty); 2871 } 2872 2873 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 2874 return FwdVal; 2875 } 2876 2877 /// setInstName - After an instruction is parsed and inserted into its 2878 /// basic block, this installs its name. 2879 bool LLParser::PerFunctionState::setInstName(int NameID, 2880 const std::string &NameStr, 2881 LocTy NameLoc, Instruction *Inst) { 2882 // If this instruction has void type, it cannot have a name or ID specified. 2883 if (Inst->getType()->isVoidTy()) { 2884 if (NameID != -1 || !NameStr.empty()) 2885 return P.error(NameLoc, "instructions returning void cannot have a name"); 2886 return false; 2887 } 2888 2889 // If this was a numbered instruction, verify that the instruction is the 2890 // expected value and resolve any forward references. 2891 if (NameStr.empty()) { 2892 // If neither a name nor an ID was specified, just use the next ID. 2893 if (NameID == -1) 2894 NameID = NumberedVals.size(); 2895 2896 if (unsigned(NameID) != NumberedVals.size()) 2897 return P.error(NameLoc, "instruction expected to be numbered '%" + 2898 Twine(NumberedVals.size()) + "'"); 2899 2900 auto FI = ForwardRefValIDs.find(NameID); 2901 if (FI != ForwardRefValIDs.end()) { 2902 Value *Sentinel = FI->second.first; 2903 if (Sentinel->getType() != Inst->getType()) 2904 return P.error(NameLoc, "instruction forward referenced with type '" + 2905 getTypeString(FI->second.first->getType()) + 2906 "'"); 2907 2908 Sentinel->replaceAllUsesWith(Inst); 2909 Sentinel->deleteValue(); 2910 ForwardRefValIDs.erase(FI); 2911 } 2912 2913 NumberedVals.push_back(Inst); 2914 return false; 2915 } 2916 2917 // Otherwise, the instruction had a name. Resolve forward refs and set it. 2918 auto FI = ForwardRefVals.find(NameStr); 2919 if (FI != ForwardRefVals.end()) { 2920 Value *Sentinel = FI->second.first; 2921 if (Sentinel->getType() != Inst->getType()) 2922 return P.error(NameLoc, "instruction forward referenced with type '" + 2923 getTypeString(FI->second.first->getType()) + 2924 "'"); 2925 2926 Sentinel->replaceAllUsesWith(Inst); 2927 Sentinel->deleteValue(); 2928 ForwardRefVals.erase(FI); 2929 } 2930 2931 // Set the name on the instruction. 2932 Inst->setName(NameStr); 2933 2934 if (Inst->getName() != NameStr) 2935 return P.error(NameLoc, "multiple definition of local value named '" + 2936 NameStr + "'"); 2937 return false; 2938 } 2939 2940 /// getBB - Get a basic block with the specified name or ID, creating a 2941 /// forward reference record if needed. 2942 BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name, 2943 LocTy Loc) { 2944 return dyn_cast_or_null<BasicBlock>( 2945 getVal(Name, Type::getLabelTy(F.getContext()), Loc)); 2946 } 2947 2948 BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) { 2949 return dyn_cast_or_null<BasicBlock>( 2950 getVal(ID, Type::getLabelTy(F.getContext()), Loc)); 2951 } 2952 2953 /// defineBB - Define the specified basic block, which is either named or 2954 /// unnamed. If there is an error, this returns null otherwise it returns 2955 /// the block being defined. 2956 BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name, 2957 int NameID, LocTy Loc) { 2958 BasicBlock *BB; 2959 if (Name.empty()) { 2960 if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) { 2961 P.error(Loc, "label expected to be numbered '" + 2962 Twine(NumberedVals.size()) + "'"); 2963 return nullptr; 2964 } 2965 BB = getBB(NumberedVals.size(), Loc); 2966 if (!BB) { 2967 P.error(Loc, "unable to create block numbered '" + 2968 Twine(NumberedVals.size()) + "'"); 2969 return nullptr; 2970 } 2971 } else { 2972 BB = getBB(Name, Loc); 2973 if (!BB) { 2974 P.error(Loc, "unable to create block named '" + Name + "'"); 2975 return nullptr; 2976 } 2977 } 2978 2979 // Move the block to the end of the function. Forward ref'd blocks are 2980 // inserted wherever they happen to be referenced. 2981 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB); 2982 2983 // Remove the block from forward ref sets. 2984 if (Name.empty()) { 2985 ForwardRefValIDs.erase(NumberedVals.size()); 2986 NumberedVals.push_back(BB); 2987 } else { 2988 // BB forward references are already in the function symbol table. 2989 ForwardRefVals.erase(Name); 2990 } 2991 2992 return BB; 2993 } 2994 2995 //===----------------------------------------------------------------------===// 2996 // Constants. 2997 //===----------------------------------------------------------------------===// 2998 2999 /// parseValID - parse an abstract value that doesn't necessarily have a 3000 /// type implied. For example, if we parse "4" we don't know what integer type 3001 /// it has. The value will later be combined with its type and checked for 3002 /// basic correctness. PFS is used to convert function-local operands of 3003 /// metadata (since metadata operands are not just parsed here but also 3004 /// converted to values). PFS can be null when we are not parsing metadata 3005 /// values inside a function. 3006 bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) { 3007 ID.Loc = Lex.getLoc(); 3008 switch (Lex.getKind()) { 3009 default: 3010 return tokError("expected value token"); 3011 case lltok::GlobalID: // @42 3012 ID.UIntVal = Lex.getUIntVal(); 3013 ID.Kind = ValID::t_GlobalID; 3014 break; 3015 case lltok::GlobalVar: // @foo 3016 ID.StrVal = Lex.getStrVal(); 3017 ID.Kind = ValID::t_GlobalName; 3018 break; 3019 case lltok::LocalVarID: // %42 3020 ID.UIntVal = Lex.getUIntVal(); 3021 ID.Kind = ValID::t_LocalID; 3022 break; 3023 case lltok::LocalVar: // %foo 3024 ID.StrVal = Lex.getStrVal(); 3025 ID.Kind = ValID::t_LocalName; 3026 break; 3027 case lltok::APSInt: 3028 ID.APSIntVal = Lex.getAPSIntVal(); 3029 ID.Kind = ValID::t_APSInt; 3030 break; 3031 case lltok::APFloat: 3032 ID.APFloatVal = Lex.getAPFloatVal(); 3033 ID.Kind = ValID::t_APFloat; 3034 break; 3035 case lltok::kw_true: 3036 ID.ConstantVal = ConstantInt::getTrue(Context); 3037 ID.Kind = ValID::t_Constant; 3038 break; 3039 case lltok::kw_false: 3040 ID.ConstantVal = ConstantInt::getFalse(Context); 3041 ID.Kind = ValID::t_Constant; 3042 break; 3043 case lltok::kw_null: ID.Kind = ValID::t_Null; break; 3044 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break; 3045 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break; 3046 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break; 3047 case lltok::kw_none: ID.Kind = ValID::t_None; break; 3048 3049 case lltok::lbrace: { 3050 // ValID ::= '{' ConstVector '}' 3051 Lex.Lex(); 3052 SmallVector<Constant*, 16> Elts; 3053 if (parseGlobalValueVector(Elts) || 3054 parseToken(lltok::rbrace, "expected end of struct constant")) 3055 return true; 3056 3057 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size()); 3058 ID.UIntVal = Elts.size(); 3059 memcpy(ID.ConstantStructElts.get(), Elts.data(), 3060 Elts.size() * sizeof(Elts[0])); 3061 ID.Kind = ValID::t_ConstantStruct; 3062 return false; 3063 } 3064 case lltok::less: { 3065 // ValID ::= '<' ConstVector '>' --> Vector. 3066 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct. 3067 Lex.Lex(); 3068 bool isPackedStruct = EatIfPresent(lltok::lbrace); 3069 3070 SmallVector<Constant*, 16> Elts; 3071 LocTy FirstEltLoc = Lex.getLoc(); 3072 if (parseGlobalValueVector(Elts) || 3073 (isPackedStruct && 3074 parseToken(lltok::rbrace, "expected end of packed struct")) || 3075 parseToken(lltok::greater, "expected end of constant")) 3076 return true; 3077 3078 if (isPackedStruct) { 3079 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size()); 3080 memcpy(ID.ConstantStructElts.get(), Elts.data(), 3081 Elts.size() * sizeof(Elts[0])); 3082 ID.UIntVal = Elts.size(); 3083 ID.Kind = ValID::t_PackedConstantStruct; 3084 return false; 3085 } 3086 3087 if (Elts.empty()) 3088 return error(ID.Loc, "constant vector must not be empty"); 3089 3090 if (!Elts[0]->getType()->isIntegerTy() && 3091 !Elts[0]->getType()->isFloatingPointTy() && 3092 !Elts[0]->getType()->isPointerTy()) 3093 return error( 3094 FirstEltLoc, 3095 "vector elements must have integer, pointer or floating point type"); 3096 3097 // Verify that all the vector elements have the same type. 3098 for (unsigned i = 1, e = Elts.size(); i != e; ++i) 3099 if (Elts[i]->getType() != Elts[0]->getType()) 3100 return error(FirstEltLoc, "vector element #" + Twine(i) + 3101 " is not of type '" + 3102 getTypeString(Elts[0]->getType())); 3103 3104 ID.ConstantVal = ConstantVector::get(Elts); 3105 ID.Kind = ValID::t_Constant; 3106 return false; 3107 } 3108 case lltok::lsquare: { // Array Constant 3109 Lex.Lex(); 3110 SmallVector<Constant*, 16> Elts; 3111 LocTy FirstEltLoc = Lex.getLoc(); 3112 if (parseGlobalValueVector(Elts) || 3113 parseToken(lltok::rsquare, "expected end of array constant")) 3114 return true; 3115 3116 // Handle empty element. 3117 if (Elts.empty()) { 3118 // Use undef instead of an array because it's inconvenient to determine 3119 // the element type at this point, there being no elements to examine. 3120 ID.Kind = ValID::t_EmptyArray; 3121 return false; 3122 } 3123 3124 if (!Elts[0]->getType()->isFirstClassType()) 3125 return error(FirstEltLoc, "invalid array element type: " + 3126 getTypeString(Elts[0]->getType())); 3127 3128 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size()); 3129 3130 // Verify all elements are correct type! 3131 for (unsigned i = 0, e = Elts.size(); i != e; ++i) { 3132 if (Elts[i]->getType() != Elts[0]->getType()) 3133 return error(FirstEltLoc, "array element #" + Twine(i) + 3134 " is not of type '" + 3135 getTypeString(Elts[0]->getType())); 3136 } 3137 3138 ID.ConstantVal = ConstantArray::get(ATy, Elts); 3139 ID.Kind = ValID::t_Constant; 3140 return false; 3141 } 3142 case lltok::kw_c: // c "foo" 3143 Lex.Lex(); 3144 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(), 3145 false); 3146 if (parseToken(lltok::StringConstant, "expected string")) 3147 return true; 3148 ID.Kind = ValID::t_Constant; 3149 return false; 3150 3151 case lltok::kw_asm: { 3152 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ',' 3153 // STRINGCONSTANT 3154 bool HasSideEffect, AlignStack, AsmDialect, CanThrow; 3155 Lex.Lex(); 3156 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) || 3157 parseOptionalToken(lltok::kw_alignstack, AlignStack) || 3158 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) || 3159 parseOptionalToken(lltok::kw_unwind, CanThrow) || 3160 parseStringConstant(ID.StrVal) || 3161 parseToken(lltok::comma, "expected comma in inline asm expression") || 3162 parseToken(lltok::StringConstant, "expected constraint string")) 3163 return true; 3164 ID.StrVal2 = Lex.getStrVal(); 3165 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) | 3166 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3); 3167 ID.Kind = ValID::t_InlineAsm; 3168 return false; 3169 } 3170 3171 case lltok::kw_blockaddress: { 3172 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')' 3173 Lex.Lex(); 3174 3175 ValID Fn, Label; 3176 3177 if (parseToken(lltok::lparen, "expected '(' in block address expression") || 3178 parseValID(Fn, PFS) || 3179 parseToken(lltok::comma, 3180 "expected comma in block address expression") || 3181 parseValID(Label, PFS) || 3182 parseToken(lltok::rparen, "expected ')' in block address expression")) 3183 return true; 3184 3185 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName) 3186 return error(Fn.Loc, "expected function name in blockaddress"); 3187 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName) 3188 return error(Label.Loc, "expected basic block name in blockaddress"); 3189 3190 // Try to find the function (but skip it if it's forward-referenced). 3191 GlobalValue *GV = nullptr; 3192 if (Fn.Kind == ValID::t_GlobalID) { 3193 if (Fn.UIntVal < NumberedVals.size()) 3194 GV = NumberedVals[Fn.UIntVal]; 3195 } else if (!ForwardRefVals.count(Fn.StrVal)) { 3196 GV = M->getNamedValue(Fn.StrVal); 3197 } 3198 Function *F = nullptr; 3199 if (GV) { 3200 // Confirm that it's actually a function with a definition. 3201 if (!isa<Function>(GV)) 3202 return error(Fn.Loc, "expected function name in blockaddress"); 3203 F = cast<Function>(GV); 3204 if (F->isDeclaration()) 3205 return error(Fn.Loc, "cannot take blockaddress inside a declaration"); 3206 } 3207 3208 if (!F) { 3209 // Make a global variable as a placeholder for this reference. 3210 GlobalValue *&FwdRef = 3211 ForwardRefBlockAddresses.insert(std::make_pair( 3212 std::move(Fn), 3213 std::map<ValID, GlobalValue *>())) 3214 .first->second.insert(std::make_pair(std::move(Label), nullptr)) 3215 .first->second; 3216 if (!FwdRef) { 3217 unsigned FwdDeclAS; 3218 if (ExpectedTy) { 3219 // If we know the type that the blockaddress is being assigned to, 3220 // we can use the address space of that type. 3221 if (!ExpectedTy->isPointerTy()) 3222 return error(ID.Loc, 3223 "type of blockaddress must be a pointer and not '" + 3224 getTypeString(ExpectedTy) + "'"); 3225 FwdDeclAS = ExpectedTy->getPointerAddressSpace(); 3226 } else if (PFS) { 3227 // Otherwise, we default the address space of the current function. 3228 FwdDeclAS = PFS->getFunction().getAddressSpace(); 3229 } else { 3230 llvm_unreachable("Unknown address space for blockaddress"); 3231 } 3232 FwdRef = new GlobalVariable( 3233 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage, 3234 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS); 3235 } 3236 3237 ID.ConstantVal = FwdRef; 3238 ID.Kind = ValID::t_Constant; 3239 return false; 3240 } 3241 3242 // We found the function; now find the basic block. Don't use PFS, since we 3243 // might be inside a constant expression. 3244 BasicBlock *BB; 3245 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) { 3246 if (Label.Kind == ValID::t_LocalID) 3247 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc); 3248 else 3249 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc); 3250 if (!BB) 3251 return error(Label.Loc, "referenced value is not a basic block"); 3252 } else { 3253 if (Label.Kind == ValID::t_LocalID) 3254 return error(Label.Loc, "cannot take address of numeric label after " 3255 "the function is defined"); 3256 BB = dyn_cast_or_null<BasicBlock>( 3257 F->getValueSymbolTable()->lookup(Label.StrVal)); 3258 if (!BB) 3259 return error(Label.Loc, "referenced value is not a basic block"); 3260 } 3261 3262 ID.ConstantVal = BlockAddress::get(F, BB); 3263 ID.Kind = ValID::t_Constant; 3264 return false; 3265 } 3266 3267 case lltok::kw_dso_local_equivalent: { 3268 // ValID ::= 'dso_local_equivalent' @foo 3269 Lex.Lex(); 3270 3271 ValID Fn; 3272 3273 if (parseValID(Fn, PFS)) 3274 return true; 3275 3276 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName) 3277 return error(Fn.Loc, 3278 "expected global value name in dso_local_equivalent"); 3279 3280 // Try to find the function (but skip it if it's forward-referenced). 3281 GlobalValue *GV = nullptr; 3282 if (Fn.Kind == ValID::t_GlobalID) { 3283 if (Fn.UIntVal < NumberedVals.size()) 3284 GV = NumberedVals[Fn.UIntVal]; 3285 } else if (!ForwardRefVals.count(Fn.StrVal)) { 3286 GV = M->getNamedValue(Fn.StrVal); 3287 } 3288 3289 assert(GV && "Could not find a corresponding global variable"); 3290 3291 if (!GV->getValueType()->isFunctionTy()) 3292 return error(Fn.Loc, "expected a function, alias to function, or ifunc " 3293 "in dso_local_equivalent"); 3294 3295 ID.ConstantVal = DSOLocalEquivalent::get(GV); 3296 ID.Kind = ValID::t_Constant; 3297 return false; 3298 } 3299 3300 case lltok::kw_no_cfi: { 3301 // ValID ::= 'no_cfi' @foo 3302 Lex.Lex(); 3303 3304 if (parseValID(ID, PFS)) 3305 return true; 3306 3307 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName) 3308 return error(ID.Loc, "expected global value name in no_cfi"); 3309 3310 ID.NoCFI = true; 3311 return false; 3312 } 3313 3314 case lltok::kw_trunc: 3315 case lltok::kw_zext: 3316 case lltok::kw_sext: 3317 case lltok::kw_fptrunc: 3318 case lltok::kw_fpext: 3319 case lltok::kw_bitcast: 3320 case lltok::kw_addrspacecast: 3321 case lltok::kw_uitofp: 3322 case lltok::kw_sitofp: 3323 case lltok::kw_fptoui: 3324 case lltok::kw_fptosi: 3325 case lltok::kw_inttoptr: 3326 case lltok::kw_ptrtoint: { 3327 unsigned Opc = Lex.getUIntVal(); 3328 Type *DestTy = nullptr; 3329 Constant *SrcVal; 3330 Lex.Lex(); 3331 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") || 3332 parseGlobalTypeAndValue(SrcVal) || 3333 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") || 3334 parseType(DestTy) || 3335 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast")) 3336 return true; 3337 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy)) 3338 return error(ID.Loc, "invalid cast opcode for cast from '" + 3339 getTypeString(SrcVal->getType()) + "' to '" + 3340 getTypeString(DestTy) + "'"); 3341 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, 3342 SrcVal, DestTy); 3343 ID.Kind = ValID::t_Constant; 3344 return false; 3345 } 3346 case lltok::kw_extractvalue: { 3347 Lex.Lex(); 3348 Constant *Val; 3349 SmallVector<unsigned, 4> Indices; 3350 if (parseToken(lltok::lparen, 3351 "expected '(' in extractvalue constantexpr") || 3352 parseGlobalTypeAndValue(Val) || parseIndexList(Indices) || 3353 parseToken(lltok::rparen, "expected ')' in extractvalue constantexpr")) 3354 return true; 3355 3356 if (!Val->getType()->isAggregateType()) 3357 return error(ID.Loc, "extractvalue operand must be aggregate type"); 3358 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 3359 return error(ID.Loc, "invalid indices for extractvalue"); 3360 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices); 3361 ID.Kind = ValID::t_Constant; 3362 return false; 3363 } 3364 case lltok::kw_insertvalue: { 3365 Lex.Lex(); 3366 Constant *Val0, *Val1; 3367 SmallVector<unsigned, 4> Indices; 3368 if (parseToken(lltok::lparen, "expected '(' in insertvalue constantexpr") || 3369 parseGlobalTypeAndValue(Val0) || 3370 parseToken(lltok::comma, 3371 "expected comma in insertvalue constantexpr") || 3372 parseGlobalTypeAndValue(Val1) || parseIndexList(Indices) || 3373 parseToken(lltok::rparen, "expected ')' in insertvalue constantexpr")) 3374 return true; 3375 if (!Val0->getType()->isAggregateType()) 3376 return error(ID.Loc, "insertvalue operand must be aggregate type"); 3377 Type *IndexedType = 3378 ExtractValueInst::getIndexedType(Val0->getType(), Indices); 3379 if (!IndexedType) 3380 return error(ID.Loc, "invalid indices for insertvalue"); 3381 if (IndexedType != Val1->getType()) 3382 return error(ID.Loc, "insertvalue operand and field disagree in type: '" + 3383 getTypeString(Val1->getType()) + 3384 "' instead of '" + getTypeString(IndexedType) + 3385 "'"); 3386 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices); 3387 ID.Kind = ValID::t_Constant; 3388 return false; 3389 } 3390 case lltok::kw_icmp: 3391 case lltok::kw_fcmp: { 3392 unsigned PredVal, Opc = Lex.getUIntVal(); 3393 Constant *Val0, *Val1; 3394 Lex.Lex(); 3395 if (parseCmpPredicate(PredVal, Opc) || 3396 parseToken(lltok::lparen, "expected '(' in compare constantexpr") || 3397 parseGlobalTypeAndValue(Val0) || 3398 parseToken(lltok::comma, "expected comma in compare constantexpr") || 3399 parseGlobalTypeAndValue(Val1) || 3400 parseToken(lltok::rparen, "expected ')' in compare constantexpr")) 3401 return true; 3402 3403 if (Val0->getType() != Val1->getType()) 3404 return error(ID.Loc, "compare operands must have the same type"); 3405 3406 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal; 3407 3408 if (Opc == Instruction::FCmp) { 3409 if (!Val0->getType()->isFPOrFPVectorTy()) 3410 return error(ID.Loc, "fcmp requires floating point operands"); 3411 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1); 3412 } else { 3413 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!"); 3414 if (!Val0->getType()->isIntOrIntVectorTy() && 3415 !Val0->getType()->isPtrOrPtrVectorTy()) 3416 return error(ID.Loc, "icmp requires pointer or integer operands"); 3417 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1); 3418 } 3419 ID.Kind = ValID::t_Constant; 3420 return false; 3421 } 3422 3423 // Unary Operators. 3424 case lltok::kw_fneg: { 3425 unsigned Opc = Lex.getUIntVal(); 3426 Constant *Val; 3427 Lex.Lex(); 3428 if (parseToken(lltok::lparen, "expected '(' in unary constantexpr") || 3429 parseGlobalTypeAndValue(Val) || 3430 parseToken(lltok::rparen, "expected ')' in unary constantexpr")) 3431 return true; 3432 3433 // Check that the type is valid for the operator. 3434 switch (Opc) { 3435 case Instruction::FNeg: 3436 if (!Val->getType()->isFPOrFPVectorTy()) 3437 return error(ID.Loc, "constexpr requires fp operands"); 3438 break; 3439 default: llvm_unreachable("Unknown unary operator!"); 3440 } 3441 unsigned Flags = 0; 3442 Constant *C = ConstantExpr::get(Opc, Val, Flags); 3443 ID.ConstantVal = C; 3444 ID.Kind = ValID::t_Constant; 3445 return false; 3446 } 3447 // Binary Operators. 3448 case lltok::kw_add: 3449 case lltok::kw_fadd: 3450 case lltok::kw_sub: 3451 case lltok::kw_fsub: 3452 case lltok::kw_mul: 3453 case lltok::kw_fmul: 3454 case lltok::kw_udiv: 3455 case lltok::kw_sdiv: 3456 case lltok::kw_fdiv: 3457 case lltok::kw_urem: 3458 case lltok::kw_srem: 3459 case lltok::kw_frem: 3460 case lltok::kw_shl: 3461 case lltok::kw_lshr: 3462 case lltok::kw_ashr: { 3463 bool NUW = false; 3464 bool NSW = false; 3465 bool Exact = false; 3466 unsigned Opc = Lex.getUIntVal(); 3467 Constant *Val0, *Val1; 3468 Lex.Lex(); 3469 if (Opc == Instruction::Add || Opc == Instruction::Sub || 3470 Opc == Instruction::Mul || Opc == Instruction::Shl) { 3471 if (EatIfPresent(lltok::kw_nuw)) 3472 NUW = true; 3473 if (EatIfPresent(lltok::kw_nsw)) { 3474 NSW = true; 3475 if (EatIfPresent(lltok::kw_nuw)) 3476 NUW = true; 3477 } 3478 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv || 3479 Opc == Instruction::LShr || Opc == Instruction::AShr) { 3480 if (EatIfPresent(lltok::kw_exact)) 3481 Exact = true; 3482 } 3483 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") || 3484 parseGlobalTypeAndValue(Val0) || 3485 parseToken(lltok::comma, "expected comma in binary constantexpr") || 3486 parseGlobalTypeAndValue(Val1) || 3487 parseToken(lltok::rparen, "expected ')' in binary constantexpr")) 3488 return true; 3489 if (Val0->getType() != Val1->getType()) 3490 return error(ID.Loc, "operands of constexpr must have same type"); 3491 // Check that the type is valid for the operator. 3492 switch (Opc) { 3493 case Instruction::Add: 3494 case Instruction::Sub: 3495 case Instruction::Mul: 3496 case Instruction::UDiv: 3497 case Instruction::SDiv: 3498 case Instruction::URem: 3499 case Instruction::SRem: 3500 case Instruction::Shl: 3501 case Instruction::AShr: 3502 case Instruction::LShr: 3503 if (!Val0->getType()->isIntOrIntVectorTy()) 3504 return error(ID.Loc, "constexpr requires integer operands"); 3505 break; 3506 case Instruction::FAdd: 3507 case Instruction::FSub: 3508 case Instruction::FMul: 3509 case Instruction::FDiv: 3510 case Instruction::FRem: 3511 if (!Val0->getType()->isFPOrFPVectorTy()) 3512 return error(ID.Loc, "constexpr requires fp operands"); 3513 break; 3514 default: llvm_unreachable("Unknown binary operator!"); 3515 } 3516 unsigned Flags = 0; 3517 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 3518 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap; 3519 if (Exact) Flags |= PossiblyExactOperator::IsExact; 3520 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags); 3521 ID.ConstantVal = C; 3522 ID.Kind = ValID::t_Constant; 3523 return false; 3524 } 3525 3526 // Logical Operations 3527 case lltok::kw_and: 3528 case lltok::kw_or: 3529 case lltok::kw_xor: { 3530 unsigned Opc = Lex.getUIntVal(); 3531 Constant *Val0, *Val1; 3532 Lex.Lex(); 3533 if (parseToken(lltok::lparen, "expected '(' in logical constantexpr") || 3534 parseGlobalTypeAndValue(Val0) || 3535 parseToken(lltok::comma, "expected comma in logical constantexpr") || 3536 parseGlobalTypeAndValue(Val1) || 3537 parseToken(lltok::rparen, "expected ')' in logical constantexpr")) 3538 return true; 3539 if (Val0->getType() != Val1->getType()) 3540 return error(ID.Loc, "operands of constexpr must have same type"); 3541 if (!Val0->getType()->isIntOrIntVectorTy()) 3542 return error(ID.Loc, 3543 "constexpr requires integer or integer vector operands"); 3544 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1); 3545 ID.Kind = ValID::t_Constant; 3546 return false; 3547 } 3548 3549 case lltok::kw_getelementptr: 3550 case lltok::kw_shufflevector: 3551 case lltok::kw_insertelement: 3552 case lltok::kw_extractelement: 3553 case lltok::kw_select: { 3554 unsigned Opc = Lex.getUIntVal(); 3555 SmallVector<Constant*, 16> Elts; 3556 bool InBounds = false; 3557 Type *Ty; 3558 Lex.Lex(); 3559 3560 if (Opc == Instruction::GetElementPtr) 3561 InBounds = EatIfPresent(lltok::kw_inbounds); 3562 3563 if (parseToken(lltok::lparen, "expected '(' in constantexpr")) 3564 return true; 3565 3566 LocTy ExplicitTypeLoc = Lex.getLoc(); 3567 if (Opc == Instruction::GetElementPtr) { 3568 if (parseType(Ty) || 3569 parseToken(lltok::comma, "expected comma after getelementptr's type")) 3570 return true; 3571 } 3572 3573 Optional<unsigned> InRangeOp; 3574 if (parseGlobalValueVector( 3575 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) || 3576 parseToken(lltok::rparen, "expected ')' in constantexpr")) 3577 return true; 3578 3579 if (Opc == Instruction::GetElementPtr) { 3580 if (Elts.size() == 0 || 3581 !Elts[0]->getType()->isPtrOrPtrVectorTy()) 3582 return error(ID.Loc, "base of getelementptr must be a pointer"); 3583 3584 Type *BaseType = Elts[0]->getType(); 3585 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType()); 3586 if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) { 3587 return error( 3588 ExplicitTypeLoc, 3589 typeComparisonErrorMessage( 3590 "explicit pointee type doesn't match operand's pointee type", 3591 Ty, BasePointerType->getNonOpaquePointerElementType())); 3592 } 3593 3594 unsigned GEPWidth = 3595 BaseType->isVectorTy() 3596 ? cast<FixedVectorType>(BaseType)->getNumElements() 3597 : 0; 3598 3599 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 3600 for (Constant *Val : Indices) { 3601 Type *ValTy = Val->getType(); 3602 if (!ValTy->isIntOrIntVectorTy()) 3603 return error(ID.Loc, "getelementptr index must be an integer"); 3604 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) { 3605 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements(); 3606 if (GEPWidth && (ValNumEl != GEPWidth)) 3607 return error( 3608 ID.Loc, 3609 "getelementptr vector index has a wrong number of elements"); 3610 // GEPWidth may have been unknown because the base is a scalar, 3611 // but it is known now. 3612 GEPWidth = ValNumEl; 3613 } 3614 } 3615 3616 SmallPtrSet<Type*, 4> Visited; 3617 if (!Indices.empty() && !Ty->isSized(&Visited)) 3618 return error(ID.Loc, "base element of getelementptr must be sized"); 3619 3620 if (!GetElementPtrInst::getIndexedType(Ty, Indices)) 3621 return error(ID.Loc, "invalid getelementptr indices"); 3622 3623 if (InRangeOp) { 3624 if (*InRangeOp == 0) 3625 return error(ID.Loc, 3626 "inrange keyword may not appear on pointer operand"); 3627 --*InRangeOp; 3628 } 3629 3630 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, 3631 InBounds, InRangeOp); 3632 } else if (Opc == Instruction::Select) { 3633 if (Elts.size() != 3) 3634 return error(ID.Loc, "expected three operands to select"); 3635 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1], 3636 Elts[2])) 3637 return error(ID.Loc, Reason); 3638 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]); 3639 } else if (Opc == Instruction::ShuffleVector) { 3640 if (Elts.size() != 3) 3641 return error(ID.Loc, "expected three operands to shufflevector"); 3642 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 3643 return error(ID.Loc, "invalid operands to shufflevector"); 3644 SmallVector<int, 16> Mask; 3645 ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask); 3646 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask); 3647 } else if (Opc == Instruction::ExtractElement) { 3648 if (Elts.size() != 2) 3649 return error(ID.Loc, "expected two operands to extractelement"); 3650 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1])) 3651 return error(ID.Loc, "invalid extractelement operands"); 3652 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]); 3653 } else { 3654 assert(Opc == Instruction::InsertElement && "Unknown opcode"); 3655 if (Elts.size() != 3) 3656 return error(ID.Loc, "expected three operands to insertelement"); 3657 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 3658 return error(ID.Loc, "invalid insertelement operands"); 3659 ID.ConstantVal = 3660 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]); 3661 } 3662 3663 ID.Kind = ValID::t_Constant; 3664 return false; 3665 } 3666 } 3667 3668 Lex.Lex(); 3669 return false; 3670 } 3671 3672 /// parseGlobalValue - parse a global value with the specified type. 3673 bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) { 3674 C = nullptr; 3675 ValID ID; 3676 Value *V = nullptr; 3677 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) || 3678 convertValIDToValue(Ty, ID, V, nullptr); 3679 if (V && !(C = dyn_cast<Constant>(V))) 3680 return error(ID.Loc, "global values must be constants"); 3681 return Parsed; 3682 } 3683 3684 bool LLParser::parseGlobalTypeAndValue(Constant *&V) { 3685 Type *Ty = nullptr; 3686 return parseType(Ty) || parseGlobalValue(Ty, V); 3687 } 3688 3689 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) { 3690 C = nullptr; 3691 3692 LocTy KwLoc = Lex.getLoc(); 3693 if (!EatIfPresent(lltok::kw_comdat)) 3694 return false; 3695 3696 if (EatIfPresent(lltok::lparen)) { 3697 if (Lex.getKind() != lltok::ComdatVar) 3698 return tokError("expected comdat variable"); 3699 C = getComdat(Lex.getStrVal(), Lex.getLoc()); 3700 Lex.Lex(); 3701 if (parseToken(lltok::rparen, "expected ')' after comdat var")) 3702 return true; 3703 } else { 3704 if (GlobalName.empty()) 3705 return tokError("comdat cannot be unnamed"); 3706 C = getComdat(std::string(GlobalName), KwLoc); 3707 } 3708 3709 return false; 3710 } 3711 3712 /// parseGlobalValueVector 3713 /// ::= /*empty*/ 3714 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)* 3715 bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts, 3716 Optional<unsigned> *InRangeOp) { 3717 // Empty list. 3718 if (Lex.getKind() == lltok::rbrace || 3719 Lex.getKind() == lltok::rsquare || 3720 Lex.getKind() == lltok::greater || 3721 Lex.getKind() == lltok::rparen) 3722 return false; 3723 3724 do { 3725 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange)) 3726 *InRangeOp = Elts.size(); 3727 3728 Constant *C; 3729 if (parseGlobalTypeAndValue(C)) 3730 return true; 3731 Elts.push_back(C); 3732 } while (EatIfPresent(lltok::comma)); 3733 3734 return false; 3735 } 3736 3737 bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) { 3738 SmallVector<Metadata *, 16> Elts; 3739 if (parseMDNodeVector(Elts)) 3740 return true; 3741 3742 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts); 3743 return false; 3744 } 3745 3746 /// MDNode: 3747 /// ::= !{ ... } 3748 /// ::= !7 3749 /// ::= !DILocation(...) 3750 bool LLParser::parseMDNode(MDNode *&N) { 3751 if (Lex.getKind() == lltok::MetadataVar) 3752 return parseSpecializedMDNode(N); 3753 3754 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N); 3755 } 3756 3757 bool LLParser::parseMDNodeTail(MDNode *&N) { 3758 // !{ ... } 3759 if (Lex.getKind() == lltok::lbrace) 3760 return parseMDTuple(N); 3761 3762 // !42 3763 return parseMDNodeID(N); 3764 } 3765 3766 namespace { 3767 3768 /// Structure to represent an optional metadata field. 3769 template <class FieldTy> struct MDFieldImpl { 3770 typedef MDFieldImpl ImplTy; 3771 FieldTy Val; 3772 bool Seen; 3773 3774 void assign(FieldTy Val) { 3775 Seen = true; 3776 this->Val = std::move(Val); 3777 } 3778 3779 explicit MDFieldImpl(FieldTy Default) 3780 : Val(std::move(Default)), Seen(false) {} 3781 }; 3782 3783 /// Structure to represent an optional metadata field that 3784 /// can be of either type (A or B) and encapsulates the 3785 /// MD<typeofA>Field and MD<typeofB>Field structs, so not 3786 /// to reimplement the specifics for representing each Field. 3787 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl { 3788 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy; 3789 FieldTypeA A; 3790 FieldTypeB B; 3791 bool Seen; 3792 3793 enum { 3794 IsInvalid = 0, 3795 IsTypeA = 1, 3796 IsTypeB = 2 3797 } WhatIs; 3798 3799 void assign(FieldTypeA A) { 3800 Seen = true; 3801 this->A = std::move(A); 3802 WhatIs = IsTypeA; 3803 } 3804 3805 void assign(FieldTypeB B) { 3806 Seen = true; 3807 this->B = std::move(B); 3808 WhatIs = IsTypeB; 3809 } 3810 3811 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB) 3812 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false), 3813 WhatIs(IsInvalid) {} 3814 }; 3815 3816 struct MDUnsignedField : public MDFieldImpl<uint64_t> { 3817 uint64_t Max; 3818 3819 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX) 3820 : ImplTy(Default), Max(Max) {} 3821 }; 3822 3823 struct LineField : public MDUnsignedField { 3824 LineField() : MDUnsignedField(0, UINT32_MAX) {} 3825 }; 3826 3827 struct ColumnField : public MDUnsignedField { 3828 ColumnField() : MDUnsignedField(0, UINT16_MAX) {} 3829 }; 3830 3831 struct DwarfTagField : public MDUnsignedField { 3832 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {} 3833 DwarfTagField(dwarf::Tag DefaultTag) 3834 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {} 3835 }; 3836 3837 struct DwarfMacinfoTypeField : public MDUnsignedField { 3838 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {} 3839 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType) 3840 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {} 3841 }; 3842 3843 struct DwarfAttEncodingField : public MDUnsignedField { 3844 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {} 3845 }; 3846 3847 struct DwarfVirtualityField : public MDUnsignedField { 3848 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {} 3849 }; 3850 3851 struct DwarfLangField : public MDUnsignedField { 3852 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {} 3853 }; 3854 3855 struct DwarfCCField : public MDUnsignedField { 3856 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {} 3857 }; 3858 3859 struct EmissionKindField : public MDUnsignedField { 3860 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {} 3861 }; 3862 3863 struct NameTableKindField : public MDUnsignedField { 3864 NameTableKindField() 3865 : MDUnsignedField( 3866 0, (unsigned) 3867 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {} 3868 }; 3869 3870 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> { 3871 DIFlagField() : MDFieldImpl(DINode::FlagZero) {} 3872 }; 3873 3874 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> { 3875 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {} 3876 }; 3877 3878 struct MDAPSIntField : public MDFieldImpl<APSInt> { 3879 MDAPSIntField() : ImplTy(APSInt()) {} 3880 }; 3881 3882 struct MDSignedField : public MDFieldImpl<int64_t> { 3883 int64_t Min; 3884 int64_t Max; 3885 3886 MDSignedField(int64_t Default = 0) 3887 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {} 3888 MDSignedField(int64_t Default, int64_t Min, int64_t Max) 3889 : ImplTy(Default), Min(Min), Max(Max) {} 3890 }; 3891 3892 struct MDBoolField : public MDFieldImpl<bool> { 3893 MDBoolField(bool Default = false) : ImplTy(Default) {} 3894 }; 3895 3896 struct MDField : public MDFieldImpl<Metadata *> { 3897 bool AllowNull; 3898 3899 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {} 3900 }; 3901 3902 struct MDStringField : public MDFieldImpl<MDString *> { 3903 bool AllowEmpty; 3904 MDStringField(bool AllowEmpty = true) 3905 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {} 3906 }; 3907 3908 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> { 3909 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {} 3910 }; 3911 3912 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> { 3913 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {} 3914 }; 3915 3916 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> { 3917 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true) 3918 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {} 3919 3920 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max, 3921 bool AllowNull = true) 3922 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {} 3923 3924 bool isMDSignedField() const { return WhatIs == IsTypeA; } 3925 bool isMDField() const { return WhatIs == IsTypeB; } 3926 int64_t getMDSignedValue() const { 3927 assert(isMDSignedField() && "Wrong field type"); 3928 return A.Val; 3929 } 3930 Metadata *getMDFieldValue() const { 3931 assert(isMDField() && "Wrong field type"); 3932 return B.Val; 3933 } 3934 }; 3935 3936 } // end anonymous namespace 3937 3938 namespace llvm { 3939 3940 template <> 3941 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) { 3942 if (Lex.getKind() != lltok::APSInt) 3943 return tokError("expected integer"); 3944 3945 Result.assign(Lex.getAPSIntVal()); 3946 Lex.Lex(); 3947 return false; 3948 } 3949 3950 template <> 3951 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 3952 MDUnsignedField &Result) { 3953 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 3954 return tokError("expected unsigned integer"); 3955 3956 auto &U = Lex.getAPSIntVal(); 3957 if (U.ugt(Result.Max)) 3958 return tokError("value for '" + Name + "' too large, limit is " + 3959 Twine(Result.Max)); 3960 Result.assign(U.getZExtValue()); 3961 assert(Result.Val <= Result.Max && "Expected value in range"); 3962 Lex.Lex(); 3963 return false; 3964 } 3965 3966 template <> 3967 bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) { 3968 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3969 } 3970 template <> 3971 bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) { 3972 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3973 } 3974 3975 template <> 3976 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) { 3977 if (Lex.getKind() == lltok::APSInt) 3978 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3979 3980 if (Lex.getKind() != lltok::DwarfTag) 3981 return tokError("expected DWARF tag"); 3982 3983 unsigned Tag = dwarf::getTag(Lex.getStrVal()); 3984 if (Tag == dwarf::DW_TAG_invalid) 3985 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'"); 3986 assert(Tag <= Result.Max && "Expected valid DWARF tag"); 3987 3988 Result.assign(Tag); 3989 Lex.Lex(); 3990 return false; 3991 } 3992 3993 template <> 3994 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 3995 DwarfMacinfoTypeField &Result) { 3996 if (Lex.getKind() == lltok::APSInt) 3997 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3998 3999 if (Lex.getKind() != lltok::DwarfMacinfo) 4000 return tokError("expected DWARF macinfo type"); 4001 4002 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal()); 4003 if (Macinfo == dwarf::DW_MACINFO_invalid) 4004 return tokError("invalid DWARF macinfo type" + Twine(" '") + 4005 Lex.getStrVal() + "'"); 4006 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type"); 4007 4008 Result.assign(Macinfo); 4009 Lex.Lex(); 4010 return false; 4011 } 4012 4013 template <> 4014 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4015 DwarfVirtualityField &Result) { 4016 if (Lex.getKind() == lltok::APSInt) 4017 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4018 4019 if (Lex.getKind() != lltok::DwarfVirtuality) 4020 return tokError("expected DWARF virtuality code"); 4021 4022 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal()); 4023 if (Virtuality == dwarf::DW_VIRTUALITY_invalid) 4024 return tokError("invalid DWARF virtuality code" + Twine(" '") + 4025 Lex.getStrVal() + "'"); 4026 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code"); 4027 Result.assign(Virtuality); 4028 Lex.Lex(); 4029 return false; 4030 } 4031 4032 template <> 4033 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) { 4034 if (Lex.getKind() == lltok::APSInt) 4035 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4036 4037 if (Lex.getKind() != lltok::DwarfLang) 4038 return tokError("expected DWARF language"); 4039 4040 unsigned Lang = dwarf::getLanguage(Lex.getStrVal()); 4041 if (!Lang) 4042 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() + 4043 "'"); 4044 assert(Lang <= Result.Max && "Expected valid DWARF language"); 4045 Result.assign(Lang); 4046 Lex.Lex(); 4047 return false; 4048 } 4049 4050 template <> 4051 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) { 4052 if (Lex.getKind() == lltok::APSInt) 4053 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4054 4055 if (Lex.getKind() != lltok::DwarfCC) 4056 return tokError("expected DWARF calling convention"); 4057 4058 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal()); 4059 if (!CC) 4060 return tokError("invalid DWARF calling convention" + Twine(" '") + 4061 Lex.getStrVal() + "'"); 4062 assert(CC <= Result.Max && "Expected valid DWARF calling convention"); 4063 Result.assign(CC); 4064 Lex.Lex(); 4065 return false; 4066 } 4067 4068 template <> 4069 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4070 EmissionKindField &Result) { 4071 if (Lex.getKind() == lltok::APSInt) 4072 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4073 4074 if (Lex.getKind() != lltok::EmissionKind) 4075 return tokError("expected emission kind"); 4076 4077 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal()); 4078 if (!Kind) 4079 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() + 4080 "'"); 4081 assert(*Kind <= Result.Max && "Expected valid emission kind"); 4082 Result.assign(*Kind); 4083 Lex.Lex(); 4084 return false; 4085 } 4086 4087 template <> 4088 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4089 NameTableKindField &Result) { 4090 if (Lex.getKind() == lltok::APSInt) 4091 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4092 4093 if (Lex.getKind() != lltok::NameTableKind) 4094 return tokError("expected nameTable kind"); 4095 4096 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal()); 4097 if (!Kind) 4098 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() + 4099 "'"); 4100 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind"); 4101 Result.assign((unsigned)*Kind); 4102 Lex.Lex(); 4103 return false; 4104 } 4105 4106 template <> 4107 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4108 DwarfAttEncodingField &Result) { 4109 if (Lex.getKind() == lltok::APSInt) 4110 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4111 4112 if (Lex.getKind() != lltok::DwarfAttEncoding) 4113 return tokError("expected DWARF type attribute encoding"); 4114 4115 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal()); 4116 if (!Encoding) 4117 return tokError("invalid DWARF type attribute encoding" + Twine(" '") + 4118 Lex.getStrVal() + "'"); 4119 assert(Encoding <= Result.Max && "Expected valid DWARF language"); 4120 Result.assign(Encoding); 4121 Lex.Lex(); 4122 return false; 4123 } 4124 4125 /// DIFlagField 4126 /// ::= uint32 4127 /// ::= DIFlagVector 4128 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic 4129 template <> 4130 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) { 4131 4132 // parser for a single flag. 4133 auto parseFlag = [&](DINode::DIFlags &Val) { 4134 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) { 4135 uint32_t TempVal = static_cast<uint32_t>(Val); 4136 bool Res = parseUInt32(TempVal); 4137 Val = static_cast<DINode::DIFlags>(TempVal); 4138 return Res; 4139 } 4140 4141 if (Lex.getKind() != lltok::DIFlag) 4142 return tokError("expected debug info flag"); 4143 4144 Val = DINode::getFlag(Lex.getStrVal()); 4145 if (!Val) 4146 return tokError(Twine("invalid debug info flag flag '") + 4147 Lex.getStrVal() + "'"); 4148 Lex.Lex(); 4149 return false; 4150 }; 4151 4152 // parse the flags and combine them together. 4153 DINode::DIFlags Combined = DINode::FlagZero; 4154 do { 4155 DINode::DIFlags Val; 4156 if (parseFlag(Val)) 4157 return true; 4158 Combined |= Val; 4159 } while (EatIfPresent(lltok::bar)); 4160 4161 Result.assign(Combined); 4162 return false; 4163 } 4164 4165 /// DISPFlagField 4166 /// ::= uint32 4167 /// ::= DISPFlagVector 4168 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32 4169 template <> 4170 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) { 4171 4172 // parser for a single flag. 4173 auto parseFlag = [&](DISubprogram::DISPFlags &Val) { 4174 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) { 4175 uint32_t TempVal = static_cast<uint32_t>(Val); 4176 bool Res = parseUInt32(TempVal); 4177 Val = static_cast<DISubprogram::DISPFlags>(TempVal); 4178 return Res; 4179 } 4180 4181 if (Lex.getKind() != lltok::DISPFlag) 4182 return tokError("expected debug info flag"); 4183 4184 Val = DISubprogram::getFlag(Lex.getStrVal()); 4185 if (!Val) 4186 return tokError(Twine("invalid subprogram debug info flag '") + 4187 Lex.getStrVal() + "'"); 4188 Lex.Lex(); 4189 return false; 4190 }; 4191 4192 // parse the flags and combine them together. 4193 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero; 4194 do { 4195 DISubprogram::DISPFlags Val; 4196 if (parseFlag(Val)) 4197 return true; 4198 Combined |= Val; 4199 } while (EatIfPresent(lltok::bar)); 4200 4201 Result.assign(Combined); 4202 return false; 4203 } 4204 4205 template <> 4206 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) { 4207 if (Lex.getKind() != lltok::APSInt) 4208 return tokError("expected signed integer"); 4209 4210 auto &S = Lex.getAPSIntVal(); 4211 if (S < Result.Min) 4212 return tokError("value for '" + Name + "' too small, limit is " + 4213 Twine(Result.Min)); 4214 if (S > Result.Max) 4215 return tokError("value for '" + Name + "' too large, limit is " + 4216 Twine(Result.Max)); 4217 Result.assign(S.getExtValue()); 4218 assert(Result.Val >= Result.Min && "Expected value in range"); 4219 assert(Result.Val <= Result.Max && "Expected value in range"); 4220 Lex.Lex(); 4221 return false; 4222 } 4223 4224 template <> 4225 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) { 4226 switch (Lex.getKind()) { 4227 default: 4228 return tokError("expected 'true' or 'false'"); 4229 case lltok::kw_true: 4230 Result.assign(true); 4231 break; 4232 case lltok::kw_false: 4233 Result.assign(false); 4234 break; 4235 } 4236 Lex.Lex(); 4237 return false; 4238 } 4239 4240 template <> 4241 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) { 4242 if (Lex.getKind() == lltok::kw_null) { 4243 if (!Result.AllowNull) 4244 return tokError("'" + Name + "' cannot be null"); 4245 Lex.Lex(); 4246 Result.assign(nullptr); 4247 return false; 4248 } 4249 4250 Metadata *MD; 4251 if (parseMetadata(MD, nullptr)) 4252 return true; 4253 4254 Result.assign(MD); 4255 return false; 4256 } 4257 4258 template <> 4259 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4260 MDSignedOrMDField &Result) { 4261 // Try to parse a signed int. 4262 if (Lex.getKind() == lltok::APSInt) { 4263 MDSignedField Res = Result.A; 4264 if (!parseMDField(Loc, Name, Res)) { 4265 Result.assign(Res); 4266 return false; 4267 } 4268 return true; 4269 } 4270 4271 // Otherwise, try to parse as an MDField. 4272 MDField Res = Result.B; 4273 if (!parseMDField(Loc, Name, Res)) { 4274 Result.assign(Res); 4275 return false; 4276 } 4277 4278 return true; 4279 } 4280 4281 template <> 4282 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) { 4283 LocTy ValueLoc = Lex.getLoc(); 4284 std::string S; 4285 if (parseStringConstant(S)) 4286 return true; 4287 4288 if (!Result.AllowEmpty && S.empty()) 4289 return error(ValueLoc, "'" + Name + "' cannot be empty"); 4290 4291 Result.assign(S.empty() ? nullptr : MDString::get(Context, S)); 4292 return false; 4293 } 4294 4295 template <> 4296 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) { 4297 SmallVector<Metadata *, 4> MDs; 4298 if (parseMDNodeVector(MDs)) 4299 return true; 4300 4301 Result.assign(std::move(MDs)); 4302 return false; 4303 } 4304 4305 template <> 4306 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4307 ChecksumKindField &Result) { 4308 Optional<DIFile::ChecksumKind> CSKind = 4309 DIFile::getChecksumKind(Lex.getStrVal()); 4310 4311 if (Lex.getKind() != lltok::ChecksumKind || !CSKind) 4312 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() + 4313 "'"); 4314 4315 Result.assign(*CSKind); 4316 Lex.Lex(); 4317 return false; 4318 } 4319 4320 } // end namespace llvm 4321 4322 template <class ParserTy> 4323 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) { 4324 do { 4325 if (Lex.getKind() != lltok::LabelStr) 4326 return tokError("expected field label here"); 4327 4328 if (ParseField()) 4329 return true; 4330 } while (EatIfPresent(lltok::comma)); 4331 4332 return false; 4333 } 4334 4335 template <class ParserTy> 4336 bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) { 4337 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 4338 Lex.Lex(); 4339 4340 if (parseToken(lltok::lparen, "expected '(' here")) 4341 return true; 4342 if (Lex.getKind() != lltok::rparen) 4343 if (parseMDFieldsImplBody(ParseField)) 4344 return true; 4345 4346 ClosingLoc = Lex.getLoc(); 4347 return parseToken(lltok::rparen, "expected ')' here"); 4348 } 4349 4350 template <class FieldTy> 4351 bool LLParser::parseMDField(StringRef Name, FieldTy &Result) { 4352 if (Result.Seen) 4353 return tokError("field '" + Name + "' cannot be specified more than once"); 4354 4355 LocTy Loc = Lex.getLoc(); 4356 Lex.Lex(); 4357 return parseMDField(Loc, Name, Result); 4358 } 4359 4360 bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) { 4361 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 4362 4363 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \ 4364 if (Lex.getStrVal() == #CLASS) \ 4365 return parse##CLASS(N, IsDistinct); 4366 #include "llvm/IR/Metadata.def" 4367 4368 return tokError("expected metadata type"); 4369 } 4370 4371 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT 4372 #define NOP_FIELD(NAME, TYPE, INIT) 4373 #define REQUIRE_FIELD(NAME, TYPE, INIT) \ 4374 if (!NAME.Seen) \ 4375 return error(ClosingLoc, "missing required field '" #NAME "'"); 4376 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \ 4377 if (Lex.getStrVal() == #NAME) \ 4378 return parseMDField(#NAME, NAME); 4379 #define PARSE_MD_FIELDS() \ 4380 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \ 4381 do { \ 4382 LocTy ClosingLoc; \ 4383 if (parseMDFieldsImpl( \ 4384 [&]() -> bool { \ 4385 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \ 4386 return tokError(Twine("invalid field '") + Lex.getStrVal() + \ 4387 "'"); \ 4388 }, \ 4389 ClosingLoc)) \ 4390 return true; \ 4391 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \ 4392 } while (false) 4393 #define GET_OR_DISTINCT(CLASS, ARGS) \ 4394 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS) 4395 4396 /// parseDILocationFields: 4397 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6, 4398 /// isImplicitCode: true) 4399 bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) { 4400 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4401 OPTIONAL(line, LineField, ); \ 4402 OPTIONAL(column, ColumnField, ); \ 4403 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4404 OPTIONAL(inlinedAt, MDField, ); \ 4405 OPTIONAL(isImplicitCode, MDBoolField, (false)); 4406 PARSE_MD_FIELDS(); 4407 #undef VISIT_MD_FIELDS 4408 4409 Result = 4410 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val, 4411 inlinedAt.Val, isImplicitCode.Val)); 4412 return false; 4413 } 4414 4415 /// parseGenericDINode: 4416 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...}) 4417 bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) { 4418 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4419 REQUIRED(tag, DwarfTagField, ); \ 4420 OPTIONAL(header, MDStringField, ); \ 4421 OPTIONAL(operands, MDFieldList, ); 4422 PARSE_MD_FIELDS(); 4423 #undef VISIT_MD_FIELDS 4424 4425 Result = GET_OR_DISTINCT(GenericDINode, 4426 (Context, tag.Val, header.Val, operands.Val)); 4427 return false; 4428 } 4429 4430 /// parseDISubrange: 4431 /// ::= !DISubrange(count: 30, lowerBound: 2) 4432 /// ::= !DISubrange(count: !node, lowerBound: 2) 4433 /// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3) 4434 bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) { 4435 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4436 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \ 4437 OPTIONAL(lowerBound, MDSignedOrMDField, ); \ 4438 OPTIONAL(upperBound, MDSignedOrMDField, ); \ 4439 OPTIONAL(stride, MDSignedOrMDField, ); 4440 PARSE_MD_FIELDS(); 4441 #undef VISIT_MD_FIELDS 4442 4443 Metadata *Count = nullptr; 4444 Metadata *LowerBound = nullptr; 4445 Metadata *UpperBound = nullptr; 4446 Metadata *Stride = nullptr; 4447 4448 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * { 4449 if (Bound.isMDSignedField()) 4450 return ConstantAsMetadata::get(ConstantInt::getSigned( 4451 Type::getInt64Ty(Context), Bound.getMDSignedValue())); 4452 if (Bound.isMDField()) 4453 return Bound.getMDFieldValue(); 4454 return nullptr; 4455 }; 4456 4457 Count = convToMetadata(count); 4458 LowerBound = convToMetadata(lowerBound); 4459 UpperBound = convToMetadata(upperBound); 4460 Stride = convToMetadata(stride); 4461 4462 Result = GET_OR_DISTINCT(DISubrange, 4463 (Context, Count, LowerBound, UpperBound, Stride)); 4464 4465 return false; 4466 } 4467 4468 /// parseDIGenericSubrange: 4469 /// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride: 4470 /// !node3) 4471 bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) { 4472 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4473 OPTIONAL(count, MDSignedOrMDField, ); \ 4474 OPTIONAL(lowerBound, MDSignedOrMDField, ); \ 4475 OPTIONAL(upperBound, MDSignedOrMDField, ); \ 4476 OPTIONAL(stride, MDSignedOrMDField, ); 4477 PARSE_MD_FIELDS(); 4478 #undef VISIT_MD_FIELDS 4479 4480 auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * { 4481 if (Bound.isMDSignedField()) 4482 return DIExpression::get( 4483 Context, {dwarf::DW_OP_consts, 4484 static_cast<uint64_t>(Bound.getMDSignedValue())}); 4485 if (Bound.isMDField()) 4486 return Bound.getMDFieldValue(); 4487 return nullptr; 4488 }; 4489 4490 Metadata *Count = ConvToMetadata(count); 4491 Metadata *LowerBound = ConvToMetadata(lowerBound); 4492 Metadata *UpperBound = ConvToMetadata(upperBound); 4493 Metadata *Stride = ConvToMetadata(stride); 4494 4495 Result = GET_OR_DISTINCT(DIGenericSubrange, 4496 (Context, Count, LowerBound, UpperBound, Stride)); 4497 4498 return false; 4499 } 4500 4501 /// parseDIEnumerator: 4502 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind") 4503 bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) { 4504 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4505 REQUIRED(name, MDStringField, ); \ 4506 REQUIRED(value, MDAPSIntField, ); \ 4507 OPTIONAL(isUnsigned, MDBoolField, (false)); 4508 PARSE_MD_FIELDS(); 4509 #undef VISIT_MD_FIELDS 4510 4511 if (isUnsigned.Val && value.Val.isNegative()) 4512 return tokError("unsigned enumerator with negative value"); 4513 4514 APSInt Value(value.Val); 4515 // Add a leading zero so that unsigned values with the msb set are not 4516 // mistaken for negative values when used for signed enumerators. 4517 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet()) 4518 Value = Value.zext(Value.getBitWidth() + 1); 4519 4520 Result = 4521 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val)); 4522 4523 return false; 4524 } 4525 4526 /// parseDIBasicType: 4527 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32, 4528 /// encoding: DW_ATE_encoding, flags: 0) 4529 bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) { 4530 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4531 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \ 4532 OPTIONAL(name, MDStringField, ); \ 4533 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4534 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4535 OPTIONAL(encoding, DwarfAttEncodingField, ); \ 4536 OPTIONAL(flags, DIFlagField, ); 4537 PARSE_MD_FIELDS(); 4538 #undef VISIT_MD_FIELDS 4539 4540 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val, 4541 align.Val, encoding.Val, flags.Val)); 4542 return false; 4543 } 4544 4545 /// parseDIStringType: 4546 /// ::= !DIStringType(name: "character(4)", size: 32, align: 32) 4547 bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) { 4548 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4549 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \ 4550 OPTIONAL(name, MDStringField, ); \ 4551 OPTIONAL(stringLength, MDField, ); \ 4552 OPTIONAL(stringLengthExpression, MDField, ); \ 4553 OPTIONAL(stringLocationExpression, MDField, ); \ 4554 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4555 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4556 OPTIONAL(encoding, DwarfAttEncodingField, ); 4557 PARSE_MD_FIELDS(); 4558 #undef VISIT_MD_FIELDS 4559 4560 Result = GET_OR_DISTINCT( 4561 DIStringType, 4562 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val, 4563 stringLocationExpression.Val, size.Val, align.Val, encoding.Val)); 4564 return false; 4565 } 4566 4567 /// parseDIDerivedType: 4568 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0, 4569 /// line: 7, scope: !1, baseType: !2, size: 32, 4570 /// align: 32, offset: 0, flags: 0, extraData: !3, 4571 /// dwarfAddressSpace: 3) 4572 bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) { 4573 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4574 REQUIRED(tag, DwarfTagField, ); \ 4575 OPTIONAL(name, MDStringField, ); \ 4576 OPTIONAL(file, MDField, ); \ 4577 OPTIONAL(line, LineField, ); \ 4578 OPTIONAL(scope, MDField, ); \ 4579 REQUIRED(baseType, MDField, ); \ 4580 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4581 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4582 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \ 4583 OPTIONAL(flags, DIFlagField, ); \ 4584 OPTIONAL(extraData, MDField, ); \ 4585 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \ 4586 OPTIONAL(annotations, MDField, ); 4587 PARSE_MD_FIELDS(); 4588 #undef VISIT_MD_FIELDS 4589 4590 Optional<unsigned> DWARFAddressSpace; 4591 if (dwarfAddressSpace.Val != UINT32_MAX) 4592 DWARFAddressSpace = dwarfAddressSpace.Val; 4593 4594 Result = GET_OR_DISTINCT(DIDerivedType, 4595 (Context, tag.Val, name.Val, file.Val, line.Val, 4596 scope.Val, baseType.Val, size.Val, align.Val, 4597 offset.Val, DWARFAddressSpace, flags.Val, 4598 extraData.Val, annotations.Val)); 4599 return false; 4600 } 4601 4602 bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) { 4603 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4604 REQUIRED(tag, DwarfTagField, ); \ 4605 OPTIONAL(name, MDStringField, ); \ 4606 OPTIONAL(file, MDField, ); \ 4607 OPTIONAL(line, LineField, ); \ 4608 OPTIONAL(scope, MDField, ); \ 4609 OPTIONAL(baseType, MDField, ); \ 4610 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4611 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4612 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \ 4613 OPTIONAL(flags, DIFlagField, ); \ 4614 OPTIONAL(elements, MDField, ); \ 4615 OPTIONAL(runtimeLang, DwarfLangField, ); \ 4616 OPTIONAL(vtableHolder, MDField, ); \ 4617 OPTIONAL(templateParams, MDField, ); \ 4618 OPTIONAL(identifier, MDStringField, ); \ 4619 OPTIONAL(discriminator, MDField, ); \ 4620 OPTIONAL(dataLocation, MDField, ); \ 4621 OPTIONAL(associated, MDField, ); \ 4622 OPTIONAL(allocated, MDField, ); \ 4623 OPTIONAL(rank, MDSignedOrMDField, ); \ 4624 OPTIONAL(annotations, MDField, ); 4625 PARSE_MD_FIELDS(); 4626 #undef VISIT_MD_FIELDS 4627 4628 Metadata *Rank = nullptr; 4629 if (rank.isMDSignedField()) 4630 Rank = ConstantAsMetadata::get(ConstantInt::getSigned( 4631 Type::getInt64Ty(Context), rank.getMDSignedValue())); 4632 else if (rank.isMDField()) 4633 Rank = rank.getMDFieldValue(); 4634 4635 // If this has an identifier try to build an ODR type. 4636 if (identifier.Val) 4637 if (auto *CT = DICompositeType::buildODRType( 4638 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val, 4639 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val, 4640 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val, 4641 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, 4642 Rank, annotations.Val)) { 4643 Result = CT; 4644 return false; 4645 } 4646 4647 // Create a new node, and save it in the context if it belongs in the type 4648 // map. 4649 Result = GET_OR_DISTINCT( 4650 DICompositeType, 4651 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val, 4652 size.Val, align.Val, offset.Val, flags.Val, elements.Val, 4653 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val, 4654 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank, 4655 annotations.Val)); 4656 return false; 4657 } 4658 4659 bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) { 4660 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4661 OPTIONAL(flags, DIFlagField, ); \ 4662 OPTIONAL(cc, DwarfCCField, ); \ 4663 REQUIRED(types, MDField, ); 4664 PARSE_MD_FIELDS(); 4665 #undef VISIT_MD_FIELDS 4666 4667 Result = GET_OR_DISTINCT(DISubroutineType, 4668 (Context, flags.Val, cc.Val, types.Val)); 4669 return false; 4670 } 4671 4672 /// parseDIFileType: 4673 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir", 4674 /// checksumkind: CSK_MD5, 4675 /// checksum: "000102030405060708090a0b0c0d0e0f", 4676 /// source: "source file contents") 4677 bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) { 4678 // The default constructed value for checksumkind is required, but will never 4679 // be used, as the parser checks if the field was actually Seen before using 4680 // the Val. 4681 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4682 REQUIRED(filename, MDStringField, ); \ 4683 REQUIRED(directory, MDStringField, ); \ 4684 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \ 4685 OPTIONAL(checksum, MDStringField, ); \ 4686 OPTIONAL(source, MDStringField, ); 4687 PARSE_MD_FIELDS(); 4688 #undef VISIT_MD_FIELDS 4689 4690 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum; 4691 if (checksumkind.Seen && checksum.Seen) 4692 OptChecksum.emplace(checksumkind.Val, checksum.Val); 4693 else if (checksumkind.Seen || checksum.Seen) 4694 return Lex.Error("'checksumkind' and 'checksum' must be provided together"); 4695 4696 Optional<MDString *> OptSource; 4697 if (source.Seen) 4698 OptSource = source.Val; 4699 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val, 4700 OptChecksum, OptSource)); 4701 return false; 4702 } 4703 4704 /// parseDICompileUnit: 4705 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang", 4706 /// isOptimized: true, flags: "-O2", runtimeVersion: 1, 4707 /// splitDebugFilename: "abc.debug", 4708 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2, 4709 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd, 4710 /// sysroot: "/", sdk: "MacOSX.sdk") 4711 bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) { 4712 if (!IsDistinct) 4713 return Lex.Error("missing 'distinct', required for !DICompileUnit"); 4714 4715 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4716 REQUIRED(language, DwarfLangField, ); \ 4717 REQUIRED(file, MDField, (/* AllowNull */ false)); \ 4718 OPTIONAL(producer, MDStringField, ); \ 4719 OPTIONAL(isOptimized, MDBoolField, ); \ 4720 OPTIONAL(flags, MDStringField, ); \ 4721 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \ 4722 OPTIONAL(splitDebugFilename, MDStringField, ); \ 4723 OPTIONAL(emissionKind, EmissionKindField, ); \ 4724 OPTIONAL(enums, MDField, ); \ 4725 OPTIONAL(retainedTypes, MDField, ); \ 4726 OPTIONAL(globals, MDField, ); \ 4727 OPTIONAL(imports, MDField, ); \ 4728 OPTIONAL(macros, MDField, ); \ 4729 OPTIONAL(dwoId, MDUnsignedField, ); \ 4730 OPTIONAL(splitDebugInlining, MDBoolField, = true); \ 4731 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \ 4732 OPTIONAL(nameTableKind, NameTableKindField, ); \ 4733 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \ 4734 OPTIONAL(sysroot, MDStringField, ); \ 4735 OPTIONAL(sdk, MDStringField, ); 4736 PARSE_MD_FIELDS(); 4737 #undef VISIT_MD_FIELDS 4738 4739 Result = DICompileUnit::getDistinct( 4740 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val, 4741 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val, 4742 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val, 4743 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val, 4744 rangesBaseAddress.Val, sysroot.Val, sdk.Val); 4745 return false; 4746 } 4747 4748 /// parseDISubprogram: 4749 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo", 4750 /// file: !1, line: 7, type: !2, isLocal: false, 4751 /// isDefinition: true, scopeLine: 8, containingType: !3, 4752 /// virtuality: DW_VIRTUALTIY_pure_virtual, 4753 /// virtualIndex: 10, thisAdjustment: 4, flags: 11, 4754 /// spFlags: 10, isOptimized: false, templateParams: !4, 4755 /// declaration: !5, retainedNodes: !6, thrownTypes: !7, 4756 /// annotations: !8) 4757 bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) { 4758 auto Loc = Lex.getLoc(); 4759 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4760 OPTIONAL(scope, MDField, ); \ 4761 OPTIONAL(name, MDStringField, ); \ 4762 OPTIONAL(linkageName, MDStringField, ); \ 4763 OPTIONAL(file, MDField, ); \ 4764 OPTIONAL(line, LineField, ); \ 4765 OPTIONAL(type, MDField, ); \ 4766 OPTIONAL(isLocal, MDBoolField, ); \ 4767 OPTIONAL(isDefinition, MDBoolField, (true)); \ 4768 OPTIONAL(scopeLine, LineField, ); \ 4769 OPTIONAL(containingType, MDField, ); \ 4770 OPTIONAL(virtuality, DwarfVirtualityField, ); \ 4771 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \ 4772 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \ 4773 OPTIONAL(flags, DIFlagField, ); \ 4774 OPTIONAL(spFlags, DISPFlagField, ); \ 4775 OPTIONAL(isOptimized, MDBoolField, ); \ 4776 OPTIONAL(unit, MDField, ); \ 4777 OPTIONAL(templateParams, MDField, ); \ 4778 OPTIONAL(declaration, MDField, ); \ 4779 OPTIONAL(retainedNodes, MDField, ); \ 4780 OPTIONAL(thrownTypes, MDField, ); \ 4781 OPTIONAL(annotations, MDField, ); 4782 PARSE_MD_FIELDS(); 4783 #undef VISIT_MD_FIELDS 4784 4785 // An explicit spFlags field takes precedence over individual fields in 4786 // older IR versions. 4787 DISubprogram::DISPFlags SPFlags = 4788 spFlags.Seen ? spFlags.Val 4789 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val, 4790 isOptimized.Val, virtuality.Val); 4791 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct) 4792 return Lex.Error( 4793 Loc, 4794 "missing 'distinct', required for !DISubprogram that is a Definition"); 4795 Result = GET_OR_DISTINCT( 4796 DISubprogram, 4797 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val, 4798 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val, 4799 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val, 4800 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val)); 4801 return false; 4802 } 4803 4804 /// parseDILexicalBlock: 4805 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9) 4806 bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) { 4807 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4808 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4809 OPTIONAL(file, MDField, ); \ 4810 OPTIONAL(line, LineField, ); \ 4811 OPTIONAL(column, ColumnField, ); 4812 PARSE_MD_FIELDS(); 4813 #undef VISIT_MD_FIELDS 4814 4815 Result = GET_OR_DISTINCT( 4816 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val)); 4817 return false; 4818 } 4819 4820 /// parseDILexicalBlockFile: 4821 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9) 4822 bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) { 4823 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4824 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4825 OPTIONAL(file, MDField, ); \ 4826 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX)); 4827 PARSE_MD_FIELDS(); 4828 #undef VISIT_MD_FIELDS 4829 4830 Result = GET_OR_DISTINCT(DILexicalBlockFile, 4831 (Context, scope.Val, file.Val, discriminator.Val)); 4832 return false; 4833 } 4834 4835 /// parseDICommonBlock: 4836 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9) 4837 bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) { 4838 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4839 REQUIRED(scope, MDField, ); \ 4840 OPTIONAL(declaration, MDField, ); \ 4841 OPTIONAL(name, MDStringField, ); \ 4842 OPTIONAL(file, MDField, ); \ 4843 OPTIONAL(line, LineField, ); 4844 PARSE_MD_FIELDS(); 4845 #undef VISIT_MD_FIELDS 4846 4847 Result = GET_OR_DISTINCT(DICommonBlock, 4848 (Context, scope.Val, declaration.Val, name.Val, 4849 file.Val, line.Val)); 4850 return false; 4851 } 4852 4853 /// parseDINamespace: 4854 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9) 4855 bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) { 4856 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4857 REQUIRED(scope, MDField, ); \ 4858 OPTIONAL(name, MDStringField, ); \ 4859 OPTIONAL(exportSymbols, MDBoolField, ); 4860 PARSE_MD_FIELDS(); 4861 #undef VISIT_MD_FIELDS 4862 4863 Result = GET_OR_DISTINCT(DINamespace, 4864 (Context, scope.Val, name.Val, exportSymbols.Val)); 4865 return false; 4866 } 4867 4868 /// parseDIMacro: 4869 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: 4870 /// "SomeValue") 4871 bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) { 4872 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4873 REQUIRED(type, DwarfMacinfoTypeField, ); \ 4874 OPTIONAL(line, LineField, ); \ 4875 REQUIRED(name, MDStringField, ); \ 4876 OPTIONAL(value, MDStringField, ); 4877 PARSE_MD_FIELDS(); 4878 #undef VISIT_MD_FIELDS 4879 4880 Result = GET_OR_DISTINCT(DIMacro, 4881 (Context, type.Val, line.Val, name.Val, value.Val)); 4882 return false; 4883 } 4884 4885 /// parseDIMacroFile: 4886 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3) 4887 bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) { 4888 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4889 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \ 4890 OPTIONAL(line, LineField, ); \ 4891 REQUIRED(file, MDField, ); \ 4892 OPTIONAL(nodes, MDField, ); 4893 PARSE_MD_FIELDS(); 4894 #undef VISIT_MD_FIELDS 4895 4896 Result = GET_OR_DISTINCT(DIMacroFile, 4897 (Context, type.Val, line.Val, file.Val, nodes.Val)); 4898 return false; 4899 } 4900 4901 /// parseDIModule: 4902 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: 4903 /// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes", 4904 /// file: !1, line: 4, isDecl: false) 4905 bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) { 4906 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4907 REQUIRED(scope, MDField, ); \ 4908 REQUIRED(name, MDStringField, ); \ 4909 OPTIONAL(configMacros, MDStringField, ); \ 4910 OPTIONAL(includePath, MDStringField, ); \ 4911 OPTIONAL(apinotes, MDStringField, ); \ 4912 OPTIONAL(file, MDField, ); \ 4913 OPTIONAL(line, LineField, ); \ 4914 OPTIONAL(isDecl, MDBoolField, ); 4915 PARSE_MD_FIELDS(); 4916 #undef VISIT_MD_FIELDS 4917 4918 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val, 4919 configMacros.Val, includePath.Val, 4920 apinotes.Val, line.Val, isDecl.Val)); 4921 return false; 4922 } 4923 4924 /// parseDITemplateTypeParameter: 4925 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false) 4926 bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) { 4927 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4928 OPTIONAL(name, MDStringField, ); \ 4929 REQUIRED(type, MDField, ); \ 4930 OPTIONAL(defaulted, MDBoolField, ); 4931 PARSE_MD_FIELDS(); 4932 #undef VISIT_MD_FIELDS 4933 4934 Result = GET_OR_DISTINCT(DITemplateTypeParameter, 4935 (Context, name.Val, type.Val, defaulted.Val)); 4936 return false; 4937 } 4938 4939 /// parseDITemplateValueParameter: 4940 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter, 4941 /// name: "V", type: !1, defaulted: false, 4942 /// value: i32 7) 4943 bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) { 4944 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4945 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \ 4946 OPTIONAL(name, MDStringField, ); \ 4947 OPTIONAL(type, MDField, ); \ 4948 OPTIONAL(defaulted, MDBoolField, ); \ 4949 REQUIRED(value, MDField, ); 4950 4951 PARSE_MD_FIELDS(); 4952 #undef VISIT_MD_FIELDS 4953 4954 Result = GET_OR_DISTINCT( 4955 DITemplateValueParameter, 4956 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val)); 4957 return false; 4958 } 4959 4960 /// parseDIGlobalVariable: 4961 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo", 4962 /// file: !1, line: 7, type: !2, isLocal: false, 4963 /// isDefinition: true, templateParams: !3, 4964 /// declaration: !4, align: 8) 4965 bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) { 4966 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4967 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \ 4968 OPTIONAL(scope, MDField, ); \ 4969 OPTIONAL(linkageName, MDStringField, ); \ 4970 OPTIONAL(file, MDField, ); \ 4971 OPTIONAL(line, LineField, ); \ 4972 OPTIONAL(type, MDField, ); \ 4973 OPTIONAL(isLocal, MDBoolField, ); \ 4974 OPTIONAL(isDefinition, MDBoolField, (true)); \ 4975 OPTIONAL(templateParams, MDField, ); \ 4976 OPTIONAL(declaration, MDField, ); \ 4977 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4978 OPTIONAL(annotations, MDField, ); 4979 PARSE_MD_FIELDS(); 4980 #undef VISIT_MD_FIELDS 4981 4982 Result = 4983 GET_OR_DISTINCT(DIGlobalVariable, 4984 (Context, scope.Val, name.Val, linkageName.Val, file.Val, 4985 line.Val, type.Val, isLocal.Val, isDefinition.Val, 4986 declaration.Val, templateParams.Val, align.Val, 4987 annotations.Val)); 4988 return false; 4989 } 4990 4991 /// parseDILocalVariable: 4992 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo", 4993 /// file: !1, line: 7, type: !2, arg: 2, flags: 7, 4994 /// align: 8) 4995 /// ::= !DILocalVariable(scope: !0, name: "foo", 4996 /// file: !1, line: 7, type: !2, arg: 2, flags: 7, 4997 /// align: 8) 4998 bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) { 4999 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5000 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 5001 OPTIONAL(name, MDStringField, ); \ 5002 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \ 5003 OPTIONAL(file, MDField, ); \ 5004 OPTIONAL(line, LineField, ); \ 5005 OPTIONAL(type, MDField, ); \ 5006 OPTIONAL(flags, DIFlagField, ); \ 5007 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 5008 OPTIONAL(annotations, MDField, ); 5009 PARSE_MD_FIELDS(); 5010 #undef VISIT_MD_FIELDS 5011 5012 Result = GET_OR_DISTINCT(DILocalVariable, 5013 (Context, scope.Val, name.Val, file.Val, line.Val, 5014 type.Val, arg.Val, flags.Val, align.Val, 5015 annotations.Val)); 5016 return false; 5017 } 5018 5019 /// parseDILabel: 5020 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7) 5021 bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) { 5022 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5023 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 5024 REQUIRED(name, MDStringField, ); \ 5025 REQUIRED(file, MDField, ); \ 5026 REQUIRED(line, LineField, ); 5027 PARSE_MD_FIELDS(); 5028 #undef VISIT_MD_FIELDS 5029 5030 Result = GET_OR_DISTINCT(DILabel, 5031 (Context, scope.Val, name.Val, file.Val, line.Val)); 5032 return false; 5033 } 5034 5035 /// parseDIExpression: 5036 /// ::= !DIExpression(0, 7, -1) 5037 bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) { 5038 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 5039 Lex.Lex(); 5040 5041 if (parseToken(lltok::lparen, "expected '(' here")) 5042 return true; 5043 5044 SmallVector<uint64_t, 8> Elements; 5045 if (Lex.getKind() != lltok::rparen) 5046 do { 5047 if (Lex.getKind() == lltok::DwarfOp) { 5048 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) { 5049 Lex.Lex(); 5050 Elements.push_back(Op); 5051 continue; 5052 } 5053 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'"); 5054 } 5055 5056 if (Lex.getKind() == lltok::DwarfAttEncoding) { 5057 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) { 5058 Lex.Lex(); 5059 Elements.push_back(Op); 5060 continue; 5061 } 5062 return tokError(Twine("invalid DWARF attribute encoding '") + 5063 Lex.getStrVal() + "'"); 5064 } 5065 5066 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 5067 return tokError("expected unsigned integer"); 5068 5069 auto &U = Lex.getAPSIntVal(); 5070 if (U.ugt(UINT64_MAX)) 5071 return tokError("element too large, limit is " + Twine(UINT64_MAX)); 5072 Elements.push_back(U.getZExtValue()); 5073 Lex.Lex(); 5074 } while (EatIfPresent(lltok::comma)); 5075 5076 if (parseToken(lltok::rparen, "expected ')' here")) 5077 return true; 5078 5079 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements)); 5080 return false; 5081 } 5082 5083 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct) { 5084 return parseDIArgList(Result, IsDistinct, nullptr); 5085 } 5086 /// ParseDIArgList: 5087 /// ::= !DIArgList(i32 7, i64 %0) 5088 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct, 5089 PerFunctionState *PFS) { 5090 assert(PFS && "Expected valid function state"); 5091 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 5092 Lex.Lex(); 5093 5094 if (parseToken(lltok::lparen, "expected '(' here")) 5095 return true; 5096 5097 SmallVector<ValueAsMetadata *, 4> Args; 5098 if (Lex.getKind() != lltok::rparen) 5099 do { 5100 Metadata *MD; 5101 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS)) 5102 return true; 5103 Args.push_back(dyn_cast<ValueAsMetadata>(MD)); 5104 } while (EatIfPresent(lltok::comma)); 5105 5106 if (parseToken(lltok::rparen, "expected ')' here")) 5107 return true; 5108 5109 Result = GET_OR_DISTINCT(DIArgList, (Context, Args)); 5110 return false; 5111 } 5112 5113 /// parseDIGlobalVariableExpression: 5114 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1) 5115 bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result, 5116 bool IsDistinct) { 5117 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5118 REQUIRED(var, MDField, ); \ 5119 REQUIRED(expr, MDField, ); 5120 PARSE_MD_FIELDS(); 5121 #undef VISIT_MD_FIELDS 5122 5123 Result = 5124 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val)); 5125 return false; 5126 } 5127 5128 /// parseDIObjCProperty: 5129 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo", 5130 /// getter: "getFoo", attributes: 7, type: !2) 5131 bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) { 5132 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5133 OPTIONAL(name, MDStringField, ); \ 5134 OPTIONAL(file, MDField, ); \ 5135 OPTIONAL(line, LineField, ); \ 5136 OPTIONAL(setter, MDStringField, ); \ 5137 OPTIONAL(getter, MDStringField, ); \ 5138 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \ 5139 OPTIONAL(type, MDField, ); 5140 PARSE_MD_FIELDS(); 5141 #undef VISIT_MD_FIELDS 5142 5143 Result = GET_OR_DISTINCT(DIObjCProperty, 5144 (Context, name.Val, file.Val, line.Val, setter.Val, 5145 getter.Val, attributes.Val, type.Val)); 5146 return false; 5147 } 5148 5149 /// parseDIImportedEntity: 5150 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1, 5151 /// line: 7, name: "foo", elements: !2) 5152 bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) { 5153 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5154 REQUIRED(tag, DwarfTagField, ); \ 5155 REQUIRED(scope, MDField, ); \ 5156 OPTIONAL(entity, MDField, ); \ 5157 OPTIONAL(file, MDField, ); \ 5158 OPTIONAL(line, LineField, ); \ 5159 OPTIONAL(name, MDStringField, ); \ 5160 OPTIONAL(elements, MDField, ); 5161 PARSE_MD_FIELDS(); 5162 #undef VISIT_MD_FIELDS 5163 5164 Result = GET_OR_DISTINCT(DIImportedEntity, 5165 (Context, tag.Val, scope.Val, entity.Val, file.Val, 5166 line.Val, name.Val, elements.Val)); 5167 return false; 5168 } 5169 5170 #undef PARSE_MD_FIELD 5171 #undef NOP_FIELD 5172 #undef REQUIRE_FIELD 5173 #undef DECLARE_FIELD 5174 5175 /// parseMetadataAsValue 5176 /// ::= metadata i32 %local 5177 /// ::= metadata i32 @global 5178 /// ::= metadata i32 7 5179 /// ::= metadata !0 5180 /// ::= metadata !{...} 5181 /// ::= metadata !"string" 5182 bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) { 5183 // Note: the type 'metadata' has already been parsed. 5184 Metadata *MD; 5185 if (parseMetadata(MD, &PFS)) 5186 return true; 5187 5188 V = MetadataAsValue::get(Context, MD); 5189 return false; 5190 } 5191 5192 /// parseValueAsMetadata 5193 /// ::= i32 %local 5194 /// ::= i32 @global 5195 /// ::= i32 7 5196 bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg, 5197 PerFunctionState *PFS) { 5198 Type *Ty; 5199 LocTy Loc; 5200 if (parseType(Ty, TypeMsg, Loc)) 5201 return true; 5202 if (Ty->isMetadataTy()) 5203 return error(Loc, "invalid metadata-value-metadata roundtrip"); 5204 5205 Value *V; 5206 if (parseValue(Ty, V, PFS)) 5207 return true; 5208 5209 MD = ValueAsMetadata::get(V); 5210 return false; 5211 } 5212 5213 /// parseMetadata 5214 /// ::= i32 %local 5215 /// ::= i32 @global 5216 /// ::= i32 7 5217 /// ::= !42 5218 /// ::= !{...} 5219 /// ::= !"string" 5220 /// ::= !DILocation(...) 5221 bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) { 5222 if (Lex.getKind() == lltok::MetadataVar) { 5223 MDNode *N; 5224 // DIArgLists are a special case, as they are a list of ValueAsMetadata and 5225 // so parsing this requires a Function State. 5226 if (Lex.getStrVal() == "DIArgList") { 5227 if (parseDIArgList(N, false, PFS)) 5228 return true; 5229 } else if (parseSpecializedMDNode(N)) { 5230 return true; 5231 } 5232 MD = N; 5233 return false; 5234 } 5235 5236 // ValueAsMetadata: 5237 // <type> <value> 5238 if (Lex.getKind() != lltok::exclaim) 5239 return parseValueAsMetadata(MD, "expected metadata operand", PFS); 5240 5241 // '!'. 5242 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here"); 5243 Lex.Lex(); 5244 5245 // MDString: 5246 // ::= '!' STRINGCONSTANT 5247 if (Lex.getKind() == lltok::StringConstant) { 5248 MDString *S; 5249 if (parseMDString(S)) 5250 return true; 5251 MD = S; 5252 return false; 5253 } 5254 5255 // MDNode: 5256 // !{ ... } 5257 // !7 5258 MDNode *N; 5259 if (parseMDNodeTail(N)) 5260 return true; 5261 MD = N; 5262 return false; 5263 } 5264 5265 //===----------------------------------------------------------------------===// 5266 // Function Parsing. 5267 //===----------------------------------------------------------------------===// 5268 5269 bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V, 5270 PerFunctionState *PFS) { 5271 if (Ty->isFunctionTy()) 5272 return error(ID.Loc, "functions are not values, refer to them as pointers"); 5273 5274 switch (ID.Kind) { 5275 case ValID::t_LocalID: 5276 if (!PFS) 5277 return error(ID.Loc, "invalid use of function-local name"); 5278 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc); 5279 return V == nullptr; 5280 case ValID::t_LocalName: 5281 if (!PFS) 5282 return error(ID.Loc, "invalid use of function-local name"); 5283 V = PFS->getVal(ID.StrVal, Ty, ID.Loc); 5284 return V == nullptr; 5285 case ValID::t_InlineAsm: { 5286 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2)) 5287 return error(ID.Loc, "invalid type for inline asm constraint string"); 5288 V = InlineAsm::get( 5289 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1, 5290 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1); 5291 return false; 5292 } 5293 case ValID::t_GlobalName: 5294 V = getGlobalVal(ID.StrVal, Ty, ID.Loc); 5295 if (V && ID.NoCFI) 5296 V = NoCFIValue::get(cast<GlobalValue>(V)); 5297 return V == nullptr; 5298 case ValID::t_GlobalID: 5299 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc); 5300 if (V && ID.NoCFI) 5301 V = NoCFIValue::get(cast<GlobalValue>(V)); 5302 return V == nullptr; 5303 case ValID::t_APSInt: 5304 if (!Ty->isIntegerTy()) 5305 return error(ID.Loc, "integer constant must have integer type"); 5306 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits()); 5307 V = ConstantInt::get(Context, ID.APSIntVal); 5308 return false; 5309 case ValID::t_APFloat: 5310 if (!Ty->isFloatingPointTy() || 5311 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal)) 5312 return error(ID.Loc, "floating point constant invalid for type"); 5313 5314 // The lexer has no type info, so builds all half, bfloat, float, and double 5315 // FP constants as double. Fix this here. Long double does not need this. 5316 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) { 5317 // Check for signaling before potentially converting and losing that info. 5318 bool IsSNAN = ID.APFloatVal.isSignaling(); 5319 bool Ignored; 5320 if (Ty->isHalfTy()) 5321 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, 5322 &Ignored); 5323 else if (Ty->isBFloatTy()) 5324 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven, 5325 &Ignored); 5326 else if (Ty->isFloatTy()) 5327 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 5328 &Ignored); 5329 if (IsSNAN) { 5330 // The convert call above may quiet an SNaN, so manufacture another 5331 // SNaN. The bitcast works because the payload (significand) parameter 5332 // is truncated to fit. 5333 APInt Payload = ID.APFloatVal.bitcastToAPInt(); 5334 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(), 5335 ID.APFloatVal.isNegative(), &Payload); 5336 } 5337 } 5338 V = ConstantFP::get(Context, ID.APFloatVal); 5339 5340 if (V->getType() != Ty) 5341 return error(ID.Loc, "floating point constant does not have type '" + 5342 getTypeString(Ty) + "'"); 5343 5344 return false; 5345 case ValID::t_Null: 5346 if (!Ty->isPointerTy()) 5347 return error(ID.Loc, "null must be a pointer type"); 5348 V = ConstantPointerNull::get(cast<PointerType>(Ty)); 5349 return false; 5350 case ValID::t_Undef: 5351 // FIXME: LabelTy should not be a first-class type. 5352 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 5353 return error(ID.Loc, "invalid type for undef constant"); 5354 V = UndefValue::get(Ty); 5355 return false; 5356 case ValID::t_EmptyArray: 5357 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0) 5358 return error(ID.Loc, "invalid empty array initializer"); 5359 V = UndefValue::get(Ty); 5360 return false; 5361 case ValID::t_Zero: 5362 // FIXME: LabelTy should not be a first-class type. 5363 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 5364 return error(ID.Loc, "invalid type for null constant"); 5365 V = Constant::getNullValue(Ty); 5366 return false; 5367 case ValID::t_None: 5368 if (!Ty->isTokenTy()) 5369 return error(ID.Loc, "invalid type for none constant"); 5370 V = Constant::getNullValue(Ty); 5371 return false; 5372 case ValID::t_Poison: 5373 // FIXME: LabelTy should not be a first-class type. 5374 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 5375 return error(ID.Loc, "invalid type for poison constant"); 5376 V = PoisonValue::get(Ty); 5377 return false; 5378 case ValID::t_Constant: 5379 if (ID.ConstantVal->getType() != Ty) 5380 return error(ID.Loc, "constant expression type mismatch: got type '" + 5381 getTypeString(ID.ConstantVal->getType()) + 5382 "' but expected '" + getTypeString(Ty) + "'"); 5383 V = ID.ConstantVal; 5384 return false; 5385 case ValID::t_ConstantStruct: 5386 case ValID::t_PackedConstantStruct: 5387 if (StructType *ST = dyn_cast<StructType>(Ty)) { 5388 if (ST->getNumElements() != ID.UIntVal) 5389 return error(ID.Loc, 5390 "initializer with struct type has wrong # elements"); 5391 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct)) 5392 return error(ID.Loc, "packed'ness of initializer and type don't match"); 5393 5394 // Verify that the elements are compatible with the structtype. 5395 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i) 5396 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i)) 5397 return error( 5398 ID.Loc, 5399 "element " + Twine(i) + 5400 " of struct initializer doesn't match struct element type"); 5401 5402 V = ConstantStruct::get( 5403 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal)); 5404 } else 5405 return error(ID.Loc, "constant expression type mismatch"); 5406 return false; 5407 } 5408 llvm_unreachable("Invalid ValID"); 5409 } 5410 5411 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) { 5412 C = nullptr; 5413 ValID ID; 5414 auto Loc = Lex.getLoc(); 5415 if (parseValID(ID, /*PFS=*/nullptr)) 5416 return true; 5417 switch (ID.Kind) { 5418 case ValID::t_APSInt: 5419 case ValID::t_APFloat: 5420 case ValID::t_Undef: 5421 case ValID::t_Constant: 5422 case ValID::t_ConstantStruct: 5423 case ValID::t_PackedConstantStruct: { 5424 Value *V; 5425 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr)) 5426 return true; 5427 assert(isa<Constant>(V) && "Expected a constant value"); 5428 C = cast<Constant>(V); 5429 return false; 5430 } 5431 case ValID::t_Null: 5432 C = Constant::getNullValue(Ty); 5433 return false; 5434 default: 5435 return error(Loc, "expected a constant value"); 5436 } 5437 } 5438 5439 bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) { 5440 V = nullptr; 5441 ValID ID; 5442 return parseValID(ID, PFS, Ty) || 5443 convertValIDToValue(Ty, ID, V, PFS); 5444 } 5445 5446 bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) { 5447 Type *Ty = nullptr; 5448 return parseType(Ty) || parseValue(Ty, V, PFS); 5449 } 5450 5451 bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc, 5452 PerFunctionState &PFS) { 5453 Value *V; 5454 Loc = Lex.getLoc(); 5455 if (parseTypeAndValue(V, PFS)) 5456 return true; 5457 if (!isa<BasicBlock>(V)) 5458 return error(Loc, "expected a basic block"); 5459 BB = cast<BasicBlock>(V); 5460 return false; 5461 } 5462 5463 /// FunctionHeader 5464 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility 5465 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName 5466 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign 5467 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn 5468 bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine) { 5469 // parse the linkage. 5470 LocTy LinkageLoc = Lex.getLoc(); 5471 unsigned Linkage; 5472 unsigned Visibility; 5473 unsigned DLLStorageClass; 5474 bool DSOLocal; 5475 AttrBuilder RetAttrs(M->getContext()); 5476 unsigned CC; 5477 bool HasLinkage; 5478 Type *RetType = nullptr; 5479 LocTy RetTypeLoc = Lex.getLoc(); 5480 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass, 5481 DSOLocal) || 5482 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 5483 parseType(RetType, RetTypeLoc, true /*void allowed*/)) 5484 return true; 5485 5486 // Verify that the linkage is ok. 5487 switch ((GlobalValue::LinkageTypes)Linkage) { 5488 case GlobalValue::ExternalLinkage: 5489 break; // always ok. 5490 case GlobalValue::ExternalWeakLinkage: 5491 if (IsDefine) 5492 return error(LinkageLoc, "invalid linkage for function definition"); 5493 break; 5494 case GlobalValue::PrivateLinkage: 5495 case GlobalValue::InternalLinkage: 5496 case GlobalValue::AvailableExternallyLinkage: 5497 case GlobalValue::LinkOnceAnyLinkage: 5498 case GlobalValue::LinkOnceODRLinkage: 5499 case GlobalValue::WeakAnyLinkage: 5500 case GlobalValue::WeakODRLinkage: 5501 if (!IsDefine) 5502 return error(LinkageLoc, "invalid linkage for function declaration"); 5503 break; 5504 case GlobalValue::AppendingLinkage: 5505 case GlobalValue::CommonLinkage: 5506 return error(LinkageLoc, "invalid function linkage type"); 5507 } 5508 5509 if (!isValidVisibilityForLinkage(Visibility, Linkage)) 5510 return error(LinkageLoc, 5511 "symbol with local linkage must have default visibility"); 5512 5513 if (!FunctionType::isValidReturnType(RetType)) 5514 return error(RetTypeLoc, "invalid function return type"); 5515 5516 LocTy NameLoc = Lex.getLoc(); 5517 5518 std::string FunctionName; 5519 if (Lex.getKind() == lltok::GlobalVar) { 5520 FunctionName = Lex.getStrVal(); 5521 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok. 5522 unsigned NameID = Lex.getUIntVal(); 5523 5524 if (NameID != NumberedVals.size()) 5525 return tokError("function expected to be numbered '%" + 5526 Twine(NumberedVals.size()) + "'"); 5527 } else { 5528 return tokError("expected function name"); 5529 } 5530 5531 Lex.Lex(); 5532 5533 if (Lex.getKind() != lltok::lparen) 5534 return tokError("expected '(' in function argument list"); 5535 5536 SmallVector<ArgInfo, 8> ArgList; 5537 bool IsVarArg; 5538 AttrBuilder FuncAttrs(M->getContext()); 5539 std::vector<unsigned> FwdRefAttrGrps; 5540 LocTy BuiltinLoc; 5541 std::string Section; 5542 std::string Partition; 5543 MaybeAlign Alignment; 5544 std::string GC; 5545 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 5546 unsigned AddrSpace = 0; 5547 Constant *Prefix = nullptr; 5548 Constant *Prologue = nullptr; 5549 Constant *PersonalityFn = nullptr; 5550 Comdat *C; 5551 5552 if (parseArgumentList(ArgList, IsVarArg) || 5553 parseOptionalUnnamedAddr(UnnamedAddr) || 5554 parseOptionalProgramAddrSpace(AddrSpace) || 5555 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false, 5556 BuiltinLoc) || 5557 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) || 5558 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) || 5559 parseOptionalComdat(FunctionName, C) || 5560 parseOptionalAlignment(Alignment) || 5561 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) || 5562 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) || 5563 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) || 5564 (EatIfPresent(lltok::kw_personality) && 5565 parseGlobalTypeAndValue(PersonalityFn))) 5566 return true; 5567 5568 if (FuncAttrs.contains(Attribute::Builtin)) 5569 return error(BuiltinLoc, "'builtin' attribute not valid on function"); 5570 5571 // If the alignment was parsed as an attribute, move to the alignment field. 5572 if (FuncAttrs.hasAlignmentAttr()) { 5573 Alignment = FuncAttrs.getAlignment(); 5574 FuncAttrs.removeAttribute(Attribute::Alignment); 5575 } 5576 5577 // Okay, if we got here, the function is syntactically valid. Convert types 5578 // and do semantic checks. 5579 std::vector<Type*> ParamTypeList; 5580 SmallVector<AttributeSet, 8> Attrs; 5581 5582 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 5583 ParamTypeList.push_back(ArgList[i].Ty); 5584 Attrs.push_back(ArgList[i].Attrs); 5585 } 5586 5587 AttributeList PAL = 5588 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs), 5589 AttributeSet::get(Context, RetAttrs), Attrs); 5590 5591 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy()) 5592 return error(RetTypeLoc, "functions with 'sret' argument must return void"); 5593 5594 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg); 5595 PointerType *PFT = PointerType::get(FT, AddrSpace); 5596 5597 Fn = nullptr; 5598 GlobalValue *FwdFn = nullptr; 5599 if (!FunctionName.empty()) { 5600 // If this was a definition of a forward reference, remove the definition 5601 // from the forward reference table and fill in the forward ref. 5602 auto FRVI = ForwardRefVals.find(FunctionName); 5603 if (FRVI != ForwardRefVals.end()) { 5604 FwdFn = FRVI->second.first; 5605 if (!FwdFn->getType()->isOpaque()) { 5606 if (!FwdFn->getType()->getNonOpaquePointerElementType()->isFunctionTy()) 5607 return error(FRVI->second.second, "invalid forward reference to " 5608 "function as global value!"); 5609 if (FwdFn->getType() != PFT) 5610 return error(FRVI->second.second, 5611 "invalid forward reference to " 5612 "function '" + 5613 FunctionName + 5614 "' with wrong type: " 5615 "expected '" + 5616 getTypeString(PFT) + "' but was '" + 5617 getTypeString(FwdFn->getType()) + "'"); 5618 } 5619 ForwardRefVals.erase(FRVI); 5620 } else if ((Fn = M->getFunction(FunctionName))) { 5621 // Reject redefinitions. 5622 return error(NameLoc, 5623 "invalid redefinition of function '" + FunctionName + "'"); 5624 } else if (M->getNamedValue(FunctionName)) { 5625 return error(NameLoc, "redefinition of function '@" + FunctionName + "'"); 5626 } 5627 5628 } else { 5629 // If this is a definition of a forward referenced function, make sure the 5630 // types agree. 5631 auto I = ForwardRefValIDs.find(NumberedVals.size()); 5632 if (I != ForwardRefValIDs.end()) { 5633 FwdFn = cast<Function>(I->second.first); 5634 if (!FwdFn->getType()->isOpaque() && FwdFn->getType() != PFT) 5635 return error(NameLoc, "type of definition and forward reference of '@" + 5636 Twine(NumberedVals.size()) + 5637 "' disagree: " 5638 "expected '" + 5639 getTypeString(PFT) + "' but was '" + 5640 getTypeString(FwdFn->getType()) + "'"); 5641 ForwardRefValIDs.erase(I); 5642 } 5643 } 5644 5645 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace, 5646 FunctionName, M); 5647 5648 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS"); 5649 5650 if (FunctionName.empty()) 5651 NumberedVals.push_back(Fn); 5652 5653 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage); 5654 maybeSetDSOLocal(DSOLocal, *Fn); 5655 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility); 5656 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 5657 Fn->setCallingConv(CC); 5658 Fn->setAttributes(PAL); 5659 Fn->setUnnamedAddr(UnnamedAddr); 5660 Fn->setAlignment(MaybeAlign(Alignment)); 5661 Fn->setSection(Section); 5662 Fn->setPartition(Partition); 5663 Fn->setComdat(C); 5664 Fn->setPersonalityFn(PersonalityFn); 5665 if (!GC.empty()) Fn->setGC(GC); 5666 Fn->setPrefixData(Prefix); 5667 Fn->setPrologueData(Prologue); 5668 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps; 5669 5670 // Add all of the arguments we parsed to the function. 5671 Function::arg_iterator ArgIt = Fn->arg_begin(); 5672 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) { 5673 // If the argument has a name, insert it into the argument symbol table. 5674 if (ArgList[i].Name.empty()) continue; 5675 5676 // Set the name, if it conflicted, it will be auto-renamed. 5677 ArgIt->setName(ArgList[i].Name); 5678 5679 if (ArgIt->getName() != ArgList[i].Name) 5680 return error(ArgList[i].Loc, 5681 "redefinition of argument '%" + ArgList[i].Name + "'"); 5682 } 5683 5684 if (FwdFn) { 5685 FwdFn->replaceAllUsesWith(Fn); 5686 FwdFn->eraseFromParent(); 5687 } 5688 5689 if (IsDefine) 5690 return false; 5691 5692 // Check the declaration has no block address forward references. 5693 ValID ID; 5694 if (FunctionName.empty()) { 5695 ID.Kind = ValID::t_GlobalID; 5696 ID.UIntVal = NumberedVals.size() - 1; 5697 } else { 5698 ID.Kind = ValID::t_GlobalName; 5699 ID.StrVal = FunctionName; 5700 } 5701 auto Blocks = ForwardRefBlockAddresses.find(ID); 5702 if (Blocks != ForwardRefBlockAddresses.end()) 5703 return error(Blocks->first.Loc, 5704 "cannot take blockaddress inside a declaration"); 5705 return false; 5706 } 5707 5708 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() { 5709 ValID ID; 5710 if (FunctionNumber == -1) { 5711 ID.Kind = ValID::t_GlobalName; 5712 ID.StrVal = std::string(F.getName()); 5713 } else { 5714 ID.Kind = ValID::t_GlobalID; 5715 ID.UIntVal = FunctionNumber; 5716 } 5717 5718 auto Blocks = P.ForwardRefBlockAddresses.find(ID); 5719 if (Blocks == P.ForwardRefBlockAddresses.end()) 5720 return false; 5721 5722 for (const auto &I : Blocks->second) { 5723 const ValID &BBID = I.first; 5724 GlobalValue *GV = I.second; 5725 5726 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) && 5727 "Expected local id or name"); 5728 BasicBlock *BB; 5729 if (BBID.Kind == ValID::t_LocalName) 5730 BB = getBB(BBID.StrVal, BBID.Loc); 5731 else 5732 BB = getBB(BBID.UIntVal, BBID.Loc); 5733 if (!BB) 5734 return P.error(BBID.Loc, "referenced value is not a basic block"); 5735 5736 Value *ResolvedVal = BlockAddress::get(&F, BB); 5737 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(), 5738 ResolvedVal); 5739 if (!ResolvedVal) 5740 return true; 5741 GV->replaceAllUsesWith(ResolvedVal); 5742 GV->eraseFromParent(); 5743 } 5744 5745 P.ForwardRefBlockAddresses.erase(Blocks); 5746 return false; 5747 } 5748 5749 /// parseFunctionBody 5750 /// ::= '{' BasicBlock+ UseListOrderDirective* '}' 5751 bool LLParser::parseFunctionBody(Function &Fn) { 5752 if (Lex.getKind() != lltok::lbrace) 5753 return tokError("expected '{' in function body"); 5754 Lex.Lex(); // eat the {. 5755 5756 int FunctionNumber = -1; 5757 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1; 5758 5759 PerFunctionState PFS(*this, Fn, FunctionNumber); 5760 5761 // Resolve block addresses and allow basic blocks to be forward-declared 5762 // within this function. 5763 if (PFS.resolveForwardRefBlockAddresses()) 5764 return true; 5765 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS); 5766 5767 // We need at least one basic block. 5768 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder) 5769 return tokError("function body requires at least one basic block"); 5770 5771 while (Lex.getKind() != lltok::rbrace && 5772 Lex.getKind() != lltok::kw_uselistorder) 5773 if (parseBasicBlock(PFS)) 5774 return true; 5775 5776 while (Lex.getKind() != lltok::rbrace) 5777 if (parseUseListOrder(&PFS)) 5778 return true; 5779 5780 // Eat the }. 5781 Lex.Lex(); 5782 5783 // Verify function is ok. 5784 return PFS.finishFunction(); 5785 } 5786 5787 /// parseBasicBlock 5788 /// ::= (LabelStr|LabelID)? Instruction* 5789 bool LLParser::parseBasicBlock(PerFunctionState &PFS) { 5790 // If this basic block starts out with a name, remember it. 5791 std::string Name; 5792 int NameID = -1; 5793 LocTy NameLoc = Lex.getLoc(); 5794 if (Lex.getKind() == lltok::LabelStr) { 5795 Name = Lex.getStrVal(); 5796 Lex.Lex(); 5797 } else if (Lex.getKind() == lltok::LabelID) { 5798 NameID = Lex.getUIntVal(); 5799 Lex.Lex(); 5800 } 5801 5802 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc); 5803 if (!BB) 5804 return true; 5805 5806 std::string NameStr; 5807 5808 // parse the instructions in this block until we get a terminator. 5809 Instruction *Inst; 5810 do { 5811 // This instruction may have three possibilities for a name: a) none 5812 // specified, b) name specified "%foo =", c) number specified: "%4 =". 5813 LocTy NameLoc = Lex.getLoc(); 5814 int NameID = -1; 5815 NameStr = ""; 5816 5817 if (Lex.getKind() == lltok::LocalVarID) { 5818 NameID = Lex.getUIntVal(); 5819 Lex.Lex(); 5820 if (parseToken(lltok::equal, "expected '=' after instruction id")) 5821 return true; 5822 } else if (Lex.getKind() == lltok::LocalVar) { 5823 NameStr = Lex.getStrVal(); 5824 Lex.Lex(); 5825 if (parseToken(lltok::equal, "expected '=' after instruction name")) 5826 return true; 5827 } 5828 5829 switch (parseInstruction(Inst, BB, PFS)) { 5830 default: 5831 llvm_unreachable("Unknown parseInstruction result!"); 5832 case InstError: return true; 5833 case InstNormal: 5834 BB->getInstList().push_back(Inst); 5835 5836 // With a normal result, we check to see if the instruction is followed by 5837 // a comma and metadata. 5838 if (EatIfPresent(lltok::comma)) 5839 if (parseInstructionMetadata(*Inst)) 5840 return true; 5841 break; 5842 case InstExtraComma: 5843 BB->getInstList().push_back(Inst); 5844 5845 // If the instruction parser ate an extra comma at the end of it, it 5846 // *must* be followed by metadata. 5847 if (parseInstructionMetadata(*Inst)) 5848 return true; 5849 break; 5850 } 5851 5852 // Set the name on the instruction. 5853 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst)) 5854 return true; 5855 } while (!Inst->isTerminator()); 5856 5857 return false; 5858 } 5859 5860 //===----------------------------------------------------------------------===// 5861 // Instruction Parsing. 5862 //===----------------------------------------------------------------------===// 5863 5864 /// parseInstruction - parse one of the many different instructions. 5865 /// 5866 int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB, 5867 PerFunctionState &PFS) { 5868 lltok::Kind Token = Lex.getKind(); 5869 if (Token == lltok::Eof) 5870 return tokError("found end of file when expecting more instructions"); 5871 LocTy Loc = Lex.getLoc(); 5872 unsigned KeywordVal = Lex.getUIntVal(); 5873 Lex.Lex(); // Eat the keyword. 5874 5875 switch (Token) { 5876 default: 5877 return error(Loc, "expected instruction opcode"); 5878 // Terminator Instructions. 5879 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false; 5880 case lltok::kw_ret: 5881 return parseRet(Inst, BB, PFS); 5882 case lltok::kw_br: 5883 return parseBr(Inst, PFS); 5884 case lltok::kw_switch: 5885 return parseSwitch(Inst, PFS); 5886 case lltok::kw_indirectbr: 5887 return parseIndirectBr(Inst, PFS); 5888 case lltok::kw_invoke: 5889 return parseInvoke(Inst, PFS); 5890 case lltok::kw_resume: 5891 return parseResume(Inst, PFS); 5892 case lltok::kw_cleanupret: 5893 return parseCleanupRet(Inst, PFS); 5894 case lltok::kw_catchret: 5895 return parseCatchRet(Inst, PFS); 5896 case lltok::kw_catchswitch: 5897 return parseCatchSwitch(Inst, PFS); 5898 case lltok::kw_catchpad: 5899 return parseCatchPad(Inst, PFS); 5900 case lltok::kw_cleanuppad: 5901 return parseCleanupPad(Inst, PFS); 5902 case lltok::kw_callbr: 5903 return parseCallBr(Inst, PFS); 5904 // Unary Operators. 5905 case lltok::kw_fneg: { 5906 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5907 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true); 5908 if (Res != 0) 5909 return Res; 5910 if (FMF.any()) 5911 Inst->setFastMathFlags(FMF); 5912 return false; 5913 } 5914 // Binary Operators. 5915 case lltok::kw_add: 5916 case lltok::kw_sub: 5917 case lltok::kw_mul: 5918 case lltok::kw_shl: { 5919 bool NUW = EatIfPresent(lltok::kw_nuw); 5920 bool NSW = EatIfPresent(lltok::kw_nsw); 5921 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw); 5922 5923 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false)) 5924 return true; 5925 5926 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true); 5927 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true); 5928 return false; 5929 } 5930 case lltok::kw_fadd: 5931 case lltok::kw_fsub: 5932 case lltok::kw_fmul: 5933 case lltok::kw_fdiv: 5934 case lltok::kw_frem: { 5935 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5936 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true); 5937 if (Res != 0) 5938 return Res; 5939 if (FMF.any()) 5940 Inst->setFastMathFlags(FMF); 5941 return 0; 5942 } 5943 5944 case lltok::kw_sdiv: 5945 case lltok::kw_udiv: 5946 case lltok::kw_lshr: 5947 case lltok::kw_ashr: { 5948 bool Exact = EatIfPresent(lltok::kw_exact); 5949 5950 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false)) 5951 return true; 5952 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true); 5953 return false; 5954 } 5955 5956 case lltok::kw_urem: 5957 case lltok::kw_srem: 5958 return parseArithmetic(Inst, PFS, KeywordVal, 5959 /*IsFP*/ false); 5960 case lltok::kw_and: 5961 case lltok::kw_or: 5962 case lltok::kw_xor: 5963 return parseLogical(Inst, PFS, KeywordVal); 5964 case lltok::kw_icmp: 5965 return parseCompare(Inst, PFS, KeywordVal); 5966 case lltok::kw_fcmp: { 5967 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5968 int Res = parseCompare(Inst, PFS, KeywordVal); 5969 if (Res != 0) 5970 return Res; 5971 if (FMF.any()) 5972 Inst->setFastMathFlags(FMF); 5973 return 0; 5974 } 5975 5976 // Casts. 5977 case lltok::kw_trunc: 5978 case lltok::kw_zext: 5979 case lltok::kw_sext: 5980 case lltok::kw_fptrunc: 5981 case lltok::kw_fpext: 5982 case lltok::kw_bitcast: 5983 case lltok::kw_addrspacecast: 5984 case lltok::kw_uitofp: 5985 case lltok::kw_sitofp: 5986 case lltok::kw_fptoui: 5987 case lltok::kw_fptosi: 5988 case lltok::kw_inttoptr: 5989 case lltok::kw_ptrtoint: 5990 return parseCast(Inst, PFS, KeywordVal); 5991 // Other. 5992 case lltok::kw_select: { 5993 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5994 int Res = parseSelect(Inst, PFS); 5995 if (Res != 0) 5996 return Res; 5997 if (FMF.any()) { 5998 if (!isa<FPMathOperator>(Inst)) 5999 return error(Loc, "fast-math-flags specified for select without " 6000 "floating-point scalar or vector return type"); 6001 Inst->setFastMathFlags(FMF); 6002 } 6003 return 0; 6004 } 6005 case lltok::kw_va_arg: 6006 return parseVAArg(Inst, PFS); 6007 case lltok::kw_extractelement: 6008 return parseExtractElement(Inst, PFS); 6009 case lltok::kw_insertelement: 6010 return parseInsertElement(Inst, PFS); 6011 case lltok::kw_shufflevector: 6012 return parseShuffleVector(Inst, PFS); 6013 case lltok::kw_phi: { 6014 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6015 int Res = parsePHI(Inst, PFS); 6016 if (Res != 0) 6017 return Res; 6018 if (FMF.any()) { 6019 if (!isa<FPMathOperator>(Inst)) 6020 return error(Loc, "fast-math-flags specified for phi without " 6021 "floating-point scalar or vector return type"); 6022 Inst->setFastMathFlags(FMF); 6023 } 6024 return 0; 6025 } 6026 case lltok::kw_landingpad: 6027 return parseLandingPad(Inst, PFS); 6028 case lltok::kw_freeze: 6029 return parseFreeze(Inst, PFS); 6030 // Call. 6031 case lltok::kw_call: 6032 return parseCall(Inst, PFS, CallInst::TCK_None); 6033 case lltok::kw_tail: 6034 return parseCall(Inst, PFS, CallInst::TCK_Tail); 6035 case lltok::kw_musttail: 6036 return parseCall(Inst, PFS, CallInst::TCK_MustTail); 6037 case lltok::kw_notail: 6038 return parseCall(Inst, PFS, CallInst::TCK_NoTail); 6039 // Memory. 6040 case lltok::kw_alloca: 6041 return parseAlloc(Inst, PFS); 6042 case lltok::kw_load: 6043 return parseLoad(Inst, PFS); 6044 case lltok::kw_store: 6045 return parseStore(Inst, PFS); 6046 case lltok::kw_cmpxchg: 6047 return parseCmpXchg(Inst, PFS); 6048 case lltok::kw_atomicrmw: 6049 return parseAtomicRMW(Inst, PFS); 6050 case lltok::kw_fence: 6051 return parseFence(Inst, PFS); 6052 case lltok::kw_getelementptr: 6053 return parseGetElementPtr(Inst, PFS); 6054 case lltok::kw_extractvalue: 6055 return parseExtractValue(Inst, PFS); 6056 case lltok::kw_insertvalue: 6057 return parseInsertValue(Inst, PFS); 6058 } 6059 } 6060 6061 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind. 6062 bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) { 6063 if (Opc == Instruction::FCmp) { 6064 switch (Lex.getKind()) { 6065 default: 6066 return tokError("expected fcmp predicate (e.g. 'oeq')"); 6067 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break; 6068 case lltok::kw_one: P = CmpInst::FCMP_ONE; break; 6069 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break; 6070 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break; 6071 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break; 6072 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break; 6073 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break; 6074 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break; 6075 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break; 6076 case lltok::kw_une: P = CmpInst::FCMP_UNE; break; 6077 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break; 6078 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break; 6079 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break; 6080 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break; 6081 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break; 6082 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break; 6083 } 6084 } else { 6085 switch (Lex.getKind()) { 6086 default: 6087 return tokError("expected icmp predicate (e.g. 'eq')"); 6088 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break; 6089 case lltok::kw_ne: P = CmpInst::ICMP_NE; break; 6090 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break; 6091 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break; 6092 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break; 6093 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break; 6094 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break; 6095 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break; 6096 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break; 6097 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break; 6098 } 6099 } 6100 Lex.Lex(); 6101 return false; 6102 } 6103 6104 //===----------------------------------------------------------------------===// 6105 // Terminator Instructions. 6106 //===----------------------------------------------------------------------===// 6107 6108 /// parseRet - parse a return instruction. 6109 /// ::= 'ret' void (',' !dbg, !1)* 6110 /// ::= 'ret' TypeAndValue (',' !dbg, !1)* 6111 bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB, 6112 PerFunctionState &PFS) { 6113 SMLoc TypeLoc = Lex.getLoc(); 6114 Type *Ty = nullptr; 6115 if (parseType(Ty, true /*void allowed*/)) 6116 return true; 6117 6118 Type *ResType = PFS.getFunction().getReturnType(); 6119 6120 if (Ty->isVoidTy()) { 6121 if (!ResType->isVoidTy()) 6122 return error(TypeLoc, "value doesn't match function result type '" + 6123 getTypeString(ResType) + "'"); 6124 6125 Inst = ReturnInst::Create(Context); 6126 return false; 6127 } 6128 6129 Value *RV; 6130 if (parseValue(Ty, RV, PFS)) 6131 return true; 6132 6133 if (ResType != RV->getType()) 6134 return error(TypeLoc, "value doesn't match function result type '" + 6135 getTypeString(ResType) + "'"); 6136 6137 Inst = ReturnInst::Create(Context, RV); 6138 return false; 6139 } 6140 6141 /// parseBr 6142 /// ::= 'br' TypeAndValue 6143 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6144 bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) { 6145 LocTy Loc, Loc2; 6146 Value *Op0; 6147 BasicBlock *Op1, *Op2; 6148 if (parseTypeAndValue(Op0, Loc, PFS)) 6149 return true; 6150 6151 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) { 6152 Inst = BranchInst::Create(BB); 6153 return false; 6154 } 6155 6156 if (Op0->getType() != Type::getInt1Ty(Context)) 6157 return error(Loc, "branch condition must have 'i1' type"); 6158 6159 if (parseToken(lltok::comma, "expected ',' after branch condition") || 6160 parseTypeAndBasicBlock(Op1, Loc, PFS) || 6161 parseToken(lltok::comma, "expected ',' after true destination") || 6162 parseTypeAndBasicBlock(Op2, Loc2, PFS)) 6163 return true; 6164 6165 Inst = BranchInst::Create(Op1, Op2, Op0); 6166 return false; 6167 } 6168 6169 /// parseSwitch 6170 /// Instruction 6171 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']' 6172 /// JumpTable 6173 /// ::= (TypeAndValue ',' TypeAndValue)* 6174 bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) { 6175 LocTy CondLoc, BBLoc; 6176 Value *Cond; 6177 BasicBlock *DefaultBB; 6178 if (parseTypeAndValue(Cond, CondLoc, PFS) || 6179 parseToken(lltok::comma, "expected ',' after switch condition") || 6180 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) || 6181 parseToken(lltok::lsquare, "expected '[' with switch table")) 6182 return true; 6183 6184 if (!Cond->getType()->isIntegerTy()) 6185 return error(CondLoc, "switch condition must have integer type"); 6186 6187 // parse the jump table pairs. 6188 SmallPtrSet<Value*, 32> SeenCases; 6189 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table; 6190 while (Lex.getKind() != lltok::rsquare) { 6191 Value *Constant; 6192 BasicBlock *DestBB; 6193 6194 if (parseTypeAndValue(Constant, CondLoc, PFS) || 6195 parseToken(lltok::comma, "expected ',' after case value") || 6196 parseTypeAndBasicBlock(DestBB, PFS)) 6197 return true; 6198 6199 if (!SeenCases.insert(Constant).second) 6200 return error(CondLoc, "duplicate case value in switch"); 6201 if (!isa<ConstantInt>(Constant)) 6202 return error(CondLoc, "case value is not a constant integer"); 6203 6204 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB)); 6205 } 6206 6207 Lex.Lex(); // Eat the ']'. 6208 6209 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size()); 6210 for (unsigned i = 0, e = Table.size(); i != e; ++i) 6211 SI->addCase(Table[i].first, Table[i].second); 6212 Inst = SI; 6213 return false; 6214 } 6215 6216 /// parseIndirectBr 6217 /// Instruction 6218 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']' 6219 bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) { 6220 LocTy AddrLoc; 6221 Value *Address; 6222 if (parseTypeAndValue(Address, AddrLoc, PFS) || 6223 parseToken(lltok::comma, "expected ',' after indirectbr address") || 6224 parseToken(lltok::lsquare, "expected '[' with indirectbr")) 6225 return true; 6226 6227 if (!Address->getType()->isPointerTy()) 6228 return error(AddrLoc, "indirectbr address must have pointer type"); 6229 6230 // parse the destination list. 6231 SmallVector<BasicBlock*, 16> DestList; 6232 6233 if (Lex.getKind() != lltok::rsquare) { 6234 BasicBlock *DestBB; 6235 if (parseTypeAndBasicBlock(DestBB, PFS)) 6236 return true; 6237 DestList.push_back(DestBB); 6238 6239 while (EatIfPresent(lltok::comma)) { 6240 if (parseTypeAndBasicBlock(DestBB, PFS)) 6241 return true; 6242 DestList.push_back(DestBB); 6243 } 6244 } 6245 6246 if (parseToken(lltok::rsquare, "expected ']' at end of block list")) 6247 return true; 6248 6249 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size()); 6250 for (unsigned i = 0, e = DestList.size(); i != e; ++i) 6251 IBI->addDestination(DestList[i]); 6252 Inst = IBI; 6253 return false; 6254 } 6255 6256 /// parseInvoke 6257 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList 6258 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue 6259 bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) { 6260 LocTy CallLoc = Lex.getLoc(); 6261 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext()); 6262 std::vector<unsigned> FwdRefAttrGrps; 6263 LocTy NoBuiltinLoc; 6264 unsigned CC; 6265 unsigned InvokeAddrSpace; 6266 Type *RetType = nullptr; 6267 LocTy RetTypeLoc; 6268 ValID CalleeID; 6269 SmallVector<ParamInfo, 16> ArgList; 6270 SmallVector<OperandBundleDef, 2> BundleList; 6271 6272 BasicBlock *NormalBB, *UnwindBB; 6273 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 6274 parseOptionalProgramAddrSpace(InvokeAddrSpace) || 6275 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 6276 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) || 6277 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 6278 NoBuiltinLoc) || 6279 parseOptionalOperandBundles(BundleList, PFS) || 6280 parseToken(lltok::kw_to, "expected 'to' in invoke") || 6281 parseTypeAndBasicBlock(NormalBB, PFS) || 6282 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") || 6283 parseTypeAndBasicBlock(UnwindBB, PFS)) 6284 return true; 6285 6286 // If RetType is a non-function pointer type, then this is the short syntax 6287 // for the call, which means that RetType is just the return type. Infer the 6288 // rest of the function argument types from the arguments that are present. 6289 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 6290 if (!Ty) { 6291 // Pull out the types of all of the arguments... 6292 std::vector<Type*> ParamTypes; 6293 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 6294 ParamTypes.push_back(ArgList[i].V->getType()); 6295 6296 if (!FunctionType::isValidReturnType(RetType)) 6297 return error(RetTypeLoc, "Invalid result type for LLVM function"); 6298 6299 Ty = FunctionType::get(RetType, ParamTypes, false); 6300 } 6301 6302 CalleeID.FTy = Ty; 6303 6304 // Look up the callee. 6305 Value *Callee; 6306 if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID, 6307 Callee, &PFS)) 6308 return true; 6309 6310 // Set up the Attribute for the function. 6311 SmallVector<Value *, 8> Args; 6312 SmallVector<AttributeSet, 8> ArgAttrs; 6313 6314 // Loop through FunctionType's arguments and ensure they are specified 6315 // correctly. Also, gather any parameter attributes. 6316 FunctionType::param_iterator I = Ty->param_begin(); 6317 FunctionType::param_iterator E = Ty->param_end(); 6318 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 6319 Type *ExpectedTy = nullptr; 6320 if (I != E) { 6321 ExpectedTy = *I++; 6322 } else if (!Ty->isVarArg()) { 6323 return error(ArgList[i].Loc, "too many arguments specified"); 6324 } 6325 6326 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 6327 return error(ArgList[i].Loc, "argument is not of expected type '" + 6328 getTypeString(ExpectedTy) + "'"); 6329 Args.push_back(ArgList[i].V); 6330 ArgAttrs.push_back(ArgList[i].Attrs); 6331 } 6332 6333 if (I != E) 6334 return error(CallLoc, "not enough parameters specified for call"); 6335 6336 if (FnAttrs.hasAlignmentAttr()) 6337 return error(CallLoc, "invoke instructions may not have an alignment"); 6338 6339 // Finish off the Attribute and check them 6340 AttributeList PAL = 6341 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 6342 AttributeSet::get(Context, RetAttrs), ArgAttrs); 6343 6344 InvokeInst *II = 6345 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList); 6346 II->setCallingConv(CC); 6347 II->setAttributes(PAL); 6348 ForwardRefAttrGroups[II] = FwdRefAttrGrps; 6349 Inst = II; 6350 return false; 6351 } 6352 6353 /// parseResume 6354 /// ::= 'resume' TypeAndValue 6355 bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) { 6356 Value *Exn; LocTy ExnLoc; 6357 if (parseTypeAndValue(Exn, ExnLoc, PFS)) 6358 return true; 6359 6360 ResumeInst *RI = ResumeInst::Create(Exn); 6361 Inst = RI; 6362 return false; 6363 } 6364 6365 bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args, 6366 PerFunctionState &PFS) { 6367 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad")) 6368 return true; 6369 6370 while (Lex.getKind() != lltok::rsquare) { 6371 // If this isn't the first argument, we need a comma. 6372 if (!Args.empty() && 6373 parseToken(lltok::comma, "expected ',' in argument list")) 6374 return true; 6375 6376 // parse the argument. 6377 LocTy ArgLoc; 6378 Type *ArgTy = nullptr; 6379 if (parseType(ArgTy, ArgLoc)) 6380 return true; 6381 6382 Value *V; 6383 if (ArgTy->isMetadataTy()) { 6384 if (parseMetadataAsValue(V, PFS)) 6385 return true; 6386 } else { 6387 if (parseValue(ArgTy, V, PFS)) 6388 return true; 6389 } 6390 Args.push_back(V); 6391 } 6392 6393 Lex.Lex(); // Lex the ']'. 6394 return false; 6395 } 6396 6397 /// parseCleanupRet 6398 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue) 6399 bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) { 6400 Value *CleanupPad = nullptr; 6401 6402 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret")) 6403 return true; 6404 6405 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS)) 6406 return true; 6407 6408 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret")) 6409 return true; 6410 6411 BasicBlock *UnwindBB = nullptr; 6412 if (Lex.getKind() == lltok::kw_to) { 6413 Lex.Lex(); 6414 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret")) 6415 return true; 6416 } else { 6417 if (parseTypeAndBasicBlock(UnwindBB, PFS)) { 6418 return true; 6419 } 6420 } 6421 6422 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB); 6423 return false; 6424 } 6425 6426 /// parseCatchRet 6427 /// ::= 'catchret' from Parent Value 'to' TypeAndValue 6428 bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) { 6429 Value *CatchPad = nullptr; 6430 6431 if (parseToken(lltok::kw_from, "expected 'from' after catchret")) 6432 return true; 6433 6434 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS)) 6435 return true; 6436 6437 BasicBlock *BB; 6438 if (parseToken(lltok::kw_to, "expected 'to' in catchret") || 6439 parseTypeAndBasicBlock(BB, PFS)) 6440 return true; 6441 6442 Inst = CatchReturnInst::Create(CatchPad, BB); 6443 return false; 6444 } 6445 6446 /// parseCatchSwitch 6447 /// ::= 'catchswitch' within Parent 6448 bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) { 6449 Value *ParentPad; 6450 6451 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch")) 6452 return true; 6453 6454 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 6455 Lex.getKind() != lltok::LocalVarID) 6456 return tokError("expected scope value for catchswitch"); 6457 6458 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS)) 6459 return true; 6460 6461 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels")) 6462 return true; 6463 6464 SmallVector<BasicBlock *, 32> Table; 6465 do { 6466 BasicBlock *DestBB; 6467 if (parseTypeAndBasicBlock(DestBB, PFS)) 6468 return true; 6469 Table.push_back(DestBB); 6470 } while (EatIfPresent(lltok::comma)); 6471 6472 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels")) 6473 return true; 6474 6475 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope")) 6476 return true; 6477 6478 BasicBlock *UnwindBB = nullptr; 6479 if (EatIfPresent(lltok::kw_to)) { 6480 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch")) 6481 return true; 6482 } else { 6483 if (parseTypeAndBasicBlock(UnwindBB, PFS)) 6484 return true; 6485 } 6486 6487 auto *CatchSwitch = 6488 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size()); 6489 for (BasicBlock *DestBB : Table) 6490 CatchSwitch->addHandler(DestBB); 6491 Inst = CatchSwitch; 6492 return false; 6493 } 6494 6495 /// parseCatchPad 6496 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue 6497 bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) { 6498 Value *CatchSwitch = nullptr; 6499 6500 if (parseToken(lltok::kw_within, "expected 'within' after catchpad")) 6501 return true; 6502 6503 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID) 6504 return tokError("expected scope value for catchpad"); 6505 6506 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS)) 6507 return true; 6508 6509 SmallVector<Value *, 8> Args; 6510 if (parseExceptionArgs(Args, PFS)) 6511 return true; 6512 6513 Inst = CatchPadInst::Create(CatchSwitch, Args); 6514 return false; 6515 } 6516 6517 /// parseCleanupPad 6518 /// ::= 'cleanuppad' within Parent ParamList 6519 bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) { 6520 Value *ParentPad = nullptr; 6521 6522 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad")) 6523 return true; 6524 6525 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 6526 Lex.getKind() != lltok::LocalVarID) 6527 return tokError("expected scope value for cleanuppad"); 6528 6529 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS)) 6530 return true; 6531 6532 SmallVector<Value *, 8> Args; 6533 if (parseExceptionArgs(Args, PFS)) 6534 return true; 6535 6536 Inst = CleanupPadInst::Create(ParentPad, Args); 6537 return false; 6538 } 6539 6540 //===----------------------------------------------------------------------===// 6541 // Unary Operators. 6542 //===----------------------------------------------------------------------===// 6543 6544 /// parseUnaryOp 6545 /// ::= UnaryOp TypeAndValue ',' Value 6546 /// 6547 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp 6548 /// operand is allowed. 6549 bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS, 6550 unsigned Opc, bool IsFP) { 6551 LocTy Loc; Value *LHS; 6552 if (parseTypeAndValue(LHS, Loc, PFS)) 6553 return true; 6554 6555 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() 6556 : LHS->getType()->isIntOrIntVectorTy(); 6557 6558 if (!Valid) 6559 return error(Loc, "invalid operand type for instruction"); 6560 6561 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS); 6562 return false; 6563 } 6564 6565 /// parseCallBr 6566 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList 6567 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue 6568 /// '[' LabelList ']' 6569 bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) { 6570 LocTy CallLoc = Lex.getLoc(); 6571 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext()); 6572 std::vector<unsigned> FwdRefAttrGrps; 6573 LocTy NoBuiltinLoc; 6574 unsigned CC; 6575 Type *RetType = nullptr; 6576 LocTy RetTypeLoc; 6577 ValID CalleeID; 6578 SmallVector<ParamInfo, 16> ArgList; 6579 SmallVector<OperandBundleDef, 2> BundleList; 6580 6581 BasicBlock *DefaultDest; 6582 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 6583 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 6584 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) || 6585 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 6586 NoBuiltinLoc) || 6587 parseOptionalOperandBundles(BundleList, PFS) || 6588 parseToken(lltok::kw_to, "expected 'to' in callbr") || 6589 parseTypeAndBasicBlock(DefaultDest, PFS) || 6590 parseToken(lltok::lsquare, "expected '[' in callbr")) 6591 return true; 6592 6593 // parse the destination list. 6594 SmallVector<BasicBlock *, 16> IndirectDests; 6595 6596 if (Lex.getKind() != lltok::rsquare) { 6597 BasicBlock *DestBB; 6598 if (parseTypeAndBasicBlock(DestBB, PFS)) 6599 return true; 6600 IndirectDests.push_back(DestBB); 6601 6602 while (EatIfPresent(lltok::comma)) { 6603 if (parseTypeAndBasicBlock(DestBB, PFS)) 6604 return true; 6605 IndirectDests.push_back(DestBB); 6606 } 6607 } 6608 6609 if (parseToken(lltok::rsquare, "expected ']' at end of block list")) 6610 return true; 6611 6612 // If RetType is a non-function pointer type, then this is the short syntax 6613 // for the call, which means that RetType is just the return type. Infer the 6614 // rest of the function argument types from the arguments that are present. 6615 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 6616 if (!Ty) { 6617 // Pull out the types of all of the arguments... 6618 std::vector<Type *> ParamTypes; 6619 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 6620 ParamTypes.push_back(ArgList[i].V->getType()); 6621 6622 if (!FunctionType::isValidReturnType(RetType)) 6623 return error(RetTypeLoc, "Invalid result type for LLVM function"); 6624 6625 Ty = FunctionType::get(RetType, ParamTypes, false); 6626 } 6627 6628 CalleeID.FTy = Ty; 6629 6630 // Look up the callee. 6631 Value *Callee; 6632 if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS)) 6633 return true; 6634 6635 // Set up the Attribute for the function. 6636 SmallVector<Value *, 8> Args; 6637 SmallVector<AttributeSet, 8> ArgAttrs; 6638 6639 // Loop through FunctionType's arguments and ensure they are specified 6640 // correctly. Also, gather any parameter attributes. 6641 FunctionType::param_iterator I = Ty->param_begin(); 6642 FunctionType::param_iterator E = Ty->param_end(); 6643 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 6644 Type *ExpectedTy = nullptr; 6645 if (I != E) { 6646 ExpectedTy = *I++; 6647 } else if (!Ty->isVarArg()) { 6648 return error(ArgList[i].Loc, "too many arguments specified"); 6649 } 6650 6651 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 6652 return error(ArgList[i].Loc, "argument is not of expected type '" + 6653 getTypeString(ExpectedTy) + "'"); 6654 Args.push_back(ArgList[i].V); 6655 ArgAttrs.push_back(ArgList[i].Attrs); 6656 } 6657 6658 if (I != E) 6659 return error(CallLoc, "not enough parameters specified for call"); 6660 6661 if (FnAttrs.hasAlignmentAttr()) 6662 return error(CallLoc, "callbr instructions may not have an alignment"); 6663 6664 // Finish off the Attribute and check them 6665 AttributeList PAL = 6666 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 6667 AttributeSet::get(Context, RetAttrs), ArgAttrs); 6668 6669 CallBrInst *CBI = 6670 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args, 6671 BundleList); 6672 CBI->setCallingConv(CC); 6673 CBI->setAttributes(PAL); 6674 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps; 6675 Inst = CBI; 6676 return false; 6677 } 6678 6679 //===----------------------------------------------------------------------===// 6680 // Binary Operators. 6681 //===----------------------------------------------------------------------===// 6682 6683 /// parseArithmetic 6684 /// ::= ArithmeticOps TypeAndValue ',' Value 6685 /// 6686 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp 6687 /// operand is allowed. 6688 bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS, 6689 unsigned Opc, bool IsFP) { 6690 LocTy Loc; Value *LHS, *RHS; 6691 if (parseTypeAndValue(LHS, Loc, PFS) || 6692 parseToken(lltok::comma, "expected ',' in arithmetic operation") || 6693 parseValue(LHS->getType(), RHS, PFS)) 6694 return true; 6695 6696 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() 6697 : LHS->getType()->isIntOrIntVectorTy(); 6698 6699 if (!Valid) 6700 return error(Loc, "invalid operand type for instruction"); 6701 6702 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 6703 return false; 6704 } 6705 6706 /// parseLogical 6707 /// ::= ArithmeticOps TypeAndValue ',' Value { 6708 bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS, 6709 unsigned Opc) { 6710 LocTy Loc; Value *LHS, *RHS; 6711 if (parseTypeAndValue(LHS, Loc, PFS) || 6712 parseToken(lltok::comma, "expected ',' in logical operation") || 6713 parseValue(LHS->getType(), RHS, PFS)) 6714 return true; 6715 6716 if (!LHS->getType()->isIntOrIntVectorTy()) 6717 return error(Loc, 6718 "instruction requires integer or integer vector operands"); 6719 6720 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 6721 return false; 6722 } 6723 6724 /// parseCompare 6725 /// ::= 'icmp' IPredicates TypeAndValue ',' Value 6726 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value 6727 bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS, 6728 unsigned Opc) { 6729 // parse the integer/fp comparison predicate. 6730 LocTy Loc; 6731 unsigned Pred; 6732 Value *LHS, *RHS; 6733 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) || 6734 parseToken(lltok::comma, "expected ',' after compare value") || 6735 parseValue(LHS->getType(), RHS, PFS)) 6736 return true; 6737 6738 if (Opc == Instruction::FCmp) { 6739 if (!LHS->getType()->isFPOrFPVectorTy()) 6740 return error(Loc, "fcmp requires floating point operands"); 6741 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS); 6742 } else { 6743 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!"); 6744 if (!LHS->getType()->isIntOrIntVectorTy() && 6745 !LHS->getType()->isPtrOrPtrVectorTy()) 6746 return error(Loc, "icmp requires integer operands"); 6747 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS); 6748 } 6749 return false; 6750 } 6751 6752 //===----------------------------------------------------------------------===// 6753 // Other Instructions. 6754 //===----------------------------------------------------------------------===// 6755 6756 /// parseCast 6757 /// ::= CastOpc TypeAndValue 'to' Type 6758 bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS, 6759 unsigned Opc) { 6760 LocTy Loc; 6761 Value *Op; 6762 Type *DestTy = nullptr; 6763 if (parseTypeAndValue(Op, Loc, PFS) || 6764 parseToken(lltok::kw_to, "expected 'to' after cast value") || 6765 parseType(DestTy)) 6766 return true; 6767 6768 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) { 6769 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy); 6770 return error(Loc, "invalid cast opcode for cast from '" + 6771 getTypeString(Op->getType()) + "' to '" + 6772 getTypeString(DestTy) + "'"); 6773 } 6774 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy); 6775 return false; 6776 } 6777 6778 /// parseSelect 6779 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6780 bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) { 6781 LocTy Loc; 6782 Value *Op0, *Op1, *Op2; 6783 if (parseTypeAndValue(Op0, Loc, PFS) || 6784 parseToken(lltok::comma, "expected ',' after select condition") || 6785 parseTypeAndValue(Op1, PFS) || 6786 parseToken(lltok::comma, "expected ',' after select value") || 6787 parseTypeAndValue(Op2, PFS)) 6788 return true; 6789 6790 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2)) 6791 return error(Loc, Reason); 6792 6793 Inst = SelectInst::Create(Op0, Op1, Op2); 6794 return false; 6795 } 6796 6797 /// parseVAArg 6798 /// ::= 'va_arg' TypeAndValue ',' Type 6799 bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) { 6800 Value *Op; 6801 Type *EltTy = nullptr; 6802 LocTy TypeLoc; 6803 if (parseTypeAndValue(Op, PFS) || 6804 parseToken(lltok::comma, "expected ',' after vaarg operand") || 6805 parseType(EltTy, TypeLoc)) 6806 return true; 6807 6808 if (!EltTy->isFirstClassType()) 6809 return error(TypeLoc, "va_arg requires operand with first class type"); 6810 6811 Inst = new VAArgInst(Op, EltTy); 6812 return false; 6813 } 6814 6815 /// parseExtractElement 6816 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue 6817 bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) { 6818 LocTy Loc; 6819 Value *Op0, *Op1; 6820 if (parseTypeAndValue(Op0, Loc, PFS) || 6821 parseToken(lltok::comma, "expected ',' after extract value") || 6822 parseTypeAndValue(Op1, PFS)) 6823 return true; 6824 6825 if (!ExtractElementInst::isValidOperands(Op0, Op1)) 6826 return error(Loc, "invalid extractelement operands"); 6827 6828 Inst = ExtractElementInst::Create(Op0, Op1); 6829 return false; 6830 } 6831 6832 /// parseInsertElement 6833 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6834 bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) { 6835 LocTy Loc; 6836 Value *Op0, *Op1, *Op2; 6837 if (parseTypeAndValue(Op0, Loc, PFS) || 6838 parseToken(lltok::comma, "expected ',' after insertelement value") || 6839 parseTypeAndValue(Op1, PFS) || 6840 parseToken(lltok::comma, "expected ',' after insertelement value") || 6841 parseTypeAndValue(Op2, PFS)) 6842 return true; 6843 6844 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2)) 6845 return error(Loc, "invalid insertelement operands"); 6846 6847 Inst = InsertElementInst::Create(Op0, Op1, Op2); 6848 return false; 6849 } 6850 6851 /// parseShuffleVector 6852 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6853 bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) { 6854 LocTy Loc; 6855 Value *Op0, *Op1, *Op2; 6856 if (parseTypeAndValue(Op0, Loc, PFS) || 6857 parseToken(lltok::comma, "expected ',' after shuffle mask") || 6858 parseTypeAndValue(Op1, PFS) || 6859 parseToken(lltok::comma, "expected ',' after shuffle value") || 6860 parseTypeAndValue(Op2, PFS)) 6861 return true; 6862 6863 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2)) 6864 return error(Loc, "invalid shufflevector operands"); 6865 6866 Inst = new ShuffleVectorInst(Op0, Op1, Op2); 6867 return false; 6868 } 6869 6870 /// parsePHI 6871 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')* 6872 int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) { 6873 Type *Ty = nullptr; LocTy TypeLoc; 6874 Value *Op0, *Op1; 6875 6876 if (parseType(Ty, TypeLoc) || 6877 parseToken(lltok::lsquare, "expected '[' in phi value list") || 6878 parseValue(Ty, Op0, PFS) || 6879 parseToken(lltok::comma, "expected ',' after insertelement value") || 6880 parseValue(Type::getLabelTy(Context), Op1, PFS) || 6881 parseToken(lltok::rsquare, "expected ']' in phi value list")) 6882 return true; 6883 6884 bool AteExtraComma = false; 6885 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals; 6886 6887 while (true) { 6888 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1))); 6889 6890 if (!EatIfPresent(lltok::comma)) 6891 break; 6892 6893 if (Lex.getKind() == lltok::MetadataVar) { 6894 AteExtraComma = true; 6895 break; 6896 } 6897 6898 if (parseToken(lltok::lsquare, "expected '[' in phi value list") || 6899 parseValue(Ty, Op0, PFS) || 6900 parseToken(lltok::comma, "expected ',' after insertelement value") || 6901 parseValue(Type::getLabelTy(Context), Op1, PFS) || 6902 parseToken(lltok::rsquare, "expected ']' in phi value list")) 6903 return true; 6904 } 6905 6906 if (!Ty->isFirstClassType()) 6907 return error(TypeLoc, "phi node must have first class type"); 6908 6909 PHINode *PN = PHINode::Create(Ty, PHIVals.size()); 6910 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i) 6911 PN->addIncoming(PHIVals[i].first, PHIVals[i].second); 6912 Inst = PN; 6913 return AteExtraComma ? InstExtraComma : InstNormal; 6914 } 6915 6916 /// parseLandingPad 6917 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+ 6918 /// Clause 6919 /// ::= 'catch' TypeAndValue 6920 /// ::= 'filter' 6921 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )* 6922 bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) { 6923 Type *Ty = nullptr; LocTy TyLoc; 6924 6925 if (parseType(Ty, TyLoc)) 6926 return true; 6927 6928 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0)); 6929 LP->setCleanup(EatIfPresent(lltok::kw_cleanup)); 6930 6931 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){ 6932 LandingPadInst::ClauseType CT; 6933 if (EatIfPresent(lltok::kw_catch)) 6934 CT = LandingPadInst::Catch; 6935 else if (EatIfPresent(lltok::kw_filter)) 6936 CT = LandingPadInst::Filter; 6937 else 6938 return tokError("expected 'catch' or 'filter' clause type"); 6939 6940 Value *V; 6941 LocTy VLoc; 6942 if (parseTypeAndValue(V, VLoc, PFS)) 6943 return true; 6944 6945 // A 'catch' type expects a non-array constant. A filter clause expects an 6946 // array constant. 6947 if (CT == LandingPadInst::Catch) { 6948 if (isa<ArrayType>(V->getType())) 6949 error(VLoc, "'catch' clause has an invalid type"); 6950 } else { 6951 if (!isa<ArrayType>(V->getType())) 6952 error(VLoc, "'filter' clause has an invalid type"); 6953 } 6954 6955 Constant *CV = dyn_cast<Constant>(V); 6956 if (!CV) 6957 return error(VLoc, "clause argument must be a constant"); 6958 LP->addClause(CV); 6959 } 6960 6961 Inst = LP.release(); 6962 return false; 6963 } 6964 6965 /// parseFreeze 6966 /// ::= 'freeze' Type Value 6967 bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) { 6968 LocTy Loc; 6969 Value *Op; 6970 if (parseTypeAndValue(Op, Loc, PFS)) 6971 return true; 6972 6973 Inst = new FreezeInst(Op); 6974 return false; 6975 } 6976 6977 /// parseCall 6978 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv 6979 /// OptionalAttrs Type Value ParameterList OptionalAttrs 6980 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv 6981 /// OptionalAttrs Type Value ParameterList OptionalAttrs 6982 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv 6983 /// OptionalAttrs Type Value ParameterList OptionalAttrs 6984 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv 6985 /// OptionalAttrs Type Value ParameterList OptionalAttrs 6986 bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS, 6987 CallInst::TailCallKind TCK) { 6988 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext()); 6989 std::vector<unsigned> FwdRefAttrGrps; 6990 LocTy BuiltinLoc; 6991 unsigned CallAddrSpace; 6992 unsigned CC; 6993 Type *RetType = nullptr; 6994 LocTy RetTypeLoc; 6995 ValID CalleeID; 6996 SmallVector<ParamInfo, 16> ArgList; 6997 SmallVector<OperandBundleDef, 2> BundleList; 6998 LocTy CallLoc = Lex.getLoc(); 6999 7000 if (TCK != CallInst::TCK_None && 7001 parseToken(lltok::kw_call, 7002 "expected 'tail call', 'musttail call', or 'notail call'")) 7003 return true; 7004 7005 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 7006 7007 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 7008 parseOptionalProgramAddrSpace(CallAddrSpace) || 7009 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 7010 parseValID(CalleeID, &PFS) || 7011 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail, 7012 PFS.getFunction().isVarArg()) || 7013 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) || 7014 parseOptionalOperandBundles(BundleList, PFS)) 7015 return true; 7016 7017 // If RetType is a non-function pointer type, then this is the short syntax 7018 // for the call, which means that RetType is just the return type. Infer the 7019 // rest of the function argument types from the arguments that are present. 7020 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 7021 if (!Ty) { 7022 // Pull out the types of all of the arguments... 7023 std::vector<Type*> ParamTypes; 7024 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 7025 ParamTypes.push_back(ArgList[i].V->getType()); 7026 7027 if (!FunctionType::isValidReturnType(RetType)) 7028 return error(RetTypeLoc, "Invalid result type for LLVM function"); 7029 7030 Ty = FunctionType::get(RetType, ParamTypes, false); 7031 } 7032 7033 CalleeID.FTy = Ty; 7034 7035 // Look up the callee. 7036 Value *Callee; 7037 if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee, 7038 &PFS)) 7039 return true; 7040 7041 // Set up the Attribute for the function. 7042 SmallVector<AttributeSet, 8> Attrs; 7043 7044 SmallVector<Value*, 8> Args; 7045 7046 // Loop through FunctionType's arguments and ensure they are specified 7047 // correctly. Also, gather any parameter attributes. 7048 FunctionType::param_iterator I = Ty->param_begin(); 7049 FunctionType::param_iterator E = Ty->param_end(); 7050 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 7051 Type *ExpectedTy = nullptr; 7052 if (I != E) { 7053 ExpectedTy = *I++; 7054 } else if (!Ty->isVarArg()) { 7055 return error(ArgList[i].Loc, "too many arguments specified"); 7056 } 7057 7058 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 7059 return error(ArgList[i].Loc, "argument is not of expected type '" + 7060 getTypeString(ExpectedTy) + "'"); 7061 Args.push_back(ArgList[i].V); 7062 Attrs.push_back(ArgList[i].Attrs); 7063 } 7064 7065 if (I != E) 7066 return error(CallLoc, "not enough parameters specified for call"); 7067 7068 if (FnAttrs.hasAlignmentAttr()) 7069 return error(CallLoc, "call instructions may not have an alignment"); 7070 7071 // Finish off the Attribute and check them 7072 AttributeList PAL = 7073 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 7074 AttributeSet::get(Context, RetAttrs), Attrs); 7075 7076 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList); 7077 CI->setTailCallKind(TCK); 7078 CI->setCallingConv(CC); 7079 if (FMF.any()) { 7080 if (!isa<FPMathOperator>(CI)) { 7081 CI->deleteValue(); 7082 return error(CallLoc, "fast-math-flags specified for call without " 7083 "floating-point scalar or vector return type"); 7084 } 7085 CI->setFastMathFlags(FMF); 7086 } 7087 CI->setAttributes(PAL); 7088 ForwardRefAttrGroups[CI] = FwdRefAttrGrps; 7089 Inst = CI; 7090 return false; 7091 } 7092 7093 //===----------------------------------------------------------------------===// 7094 // Memory Instructions. 7095 //===----------------------------------------------------------------------===// 7096 7097 /// parseAlloc 7098 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)? 7099 /// (',' 'align' i32)? (',', 'addrspace(n))? 7100 int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) { 7101 Value *Size = nullptr; 7102 LocTy SizeLoc, TyLoc, ASLoc; 7103 MaybeAlign Alignment; 7104 unsigned AddrSpace = 0; 7105 Type *Ty = nullptr; 7106 7107 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca); 7108 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror); 7109 7110 if (parseType(Ty, TyLoc)) 7111 return true; 7112 7113 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty)) 7114 return error(TyLoc, "invalid type for alloca"); 7115 7116 bool AteExtraComma = false; 7117 if (EatIfPresent(lltok::comma)) { 7118 if (Lex.getKind() == lltok::kw_align) { 7119 if (parseOptionalAlignment(Alignment)) 7120 return true; 7121 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)) 7122 return true; 7123 } else if (Lex.getKind() == lltok::kw_addrspace) { 7124 ASLoc = Lex.getLoc(); 7125 if (parseOptionalAddrSpace(AddrSpace)) 7126 return true; 7127 } else if (Lex.getKind() == lltok::MetadataVar) { 7128 AteExtraComma = true; 7129 } else { 7130 if (parseTypeAndValue(Size, SizeLoc, PFS)) 7131 return true; 7132 if (EatIfPresent(lltok::comma)) { 7133 if (Lex.getKind() == lltok::kw_align) { 7134 if (parseOptionalAlignment(Alignment)) 7135 return true; 7136 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)) 7137 return true; 7138 } else if (Lex.getKind() == lltok::kw_addrspace) { 7139 ASLoc = Lex.getLoc(); 7140 if (parseOptionalAddrSpace(AddrSpace)) 7141 return true; 7142 } else if (Lex.getKind() == lltok::MetadataVar) { 7143 AteExtraComma = true; 7144 } 7145 } 7146 } 7147 } 7148 7149 if (Size && !Size->getType()->isIntegerTy()) 7150 return error(SizeLoc, "element count must have integer type"); 7151 7152 SmallPtrSet<Type *, 4> Visited; 7153 if (!Alignment && !Ty->isSized(&Visited)) 7154 return error(TyLoc, "Cannot allocate unsized type"); 7155 if (!Alignment) 7156 Alignment = M->getDataLayout().getPrefTypeAlign(Ty); 7157 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment); 7158 AI->setUsedWithInAlloca(IsInAlloca); 7159 AI->setSwiftError(IsSwiftError); 7160 Inst = AI; 7161 return AteExtraComma ? InstExtraComma : InstNormal; 7162 } 7163 7164 /// parseLoad 7165 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)? 7166 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue 7167 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 7168 int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) { 7169 Value *Val; LocTy Loc; 7170 MaybeAlign Alignment; 7171 bool AteExtraComma = false; 7172 bool isAtomic = false; 7173 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7174 SyncScope::ID SSID = SyncScope::System; 7175 7176 if (Lex.getKind() == lltok::kw_atomic) { 7177 isAtomic = true; 7178 Lex.Lex(); 7179 } 7180 7181 bool isVolatile = false; 7182 if (Lex.getKind() == lltok::kw_volatile) { 7183 isVolatile = true; 7184 Lex.Lex(); 7185 } 7186 7187 Type *Ty; 7188 LocTy ExplicitTypeLoc = Lex.getLoc(); 7189 if (parseType(Ty) || 7190 parseToken(lltok::comma, "expected comma after load's type") || 7191 parseTypeAndValue(Val, Loc, PFS) || 7192 parseScopeAndOrdering(isAtomic, SSID, Ordering) || 7193 parseOptionalCommaAlign(Alignment, AteExtraComma)) 7194 return true; 7195 7196 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType()) 7197 return error(Loc, "load operand must be a pointer to a first class type"); 7198 if (isAtomic && !Alignment) 7199 return error(Loc, "atomic load must have explicit non-zero alignment"); 7200 if (Ordering == AtomicOrdering::Release || 7201 Ordering == AtomicOrdering::AcquireRelease) 7202 return error(Loc, "atomic load cannot use Release ordering"); 7203 7204 if (!cast<PointerType>(Val->getType())->isOpaqueOrPointeeTypeMatches(Ty)) { 7205 return error( 7206 ExplicitTypeLoc, 7207 typeComparisonErrorMessage( 7208 "explicit pointee type doesn't match operand's pointee type", Ty, 7209 Val->getType()->getNonOpaquePointerElementType())); 7210 } 7211 SmallPtrSet<Type *, 4> Visited; 7212 if (!Alignment && !Ty->isSized(&Visited)) 7213 return error(ExplicitTypeLoc, "loading unsized types is not allowed"); 7214 if (!Alignment) 7215 Alignment = M->getDataLayout().getABITypeAlign(Ty); 7216 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID); 7217 return AteExtraComma ? InstExtraComma : InstNormal; 7218 } 7219 7220 /// parseStore 7221 7222 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)? 7223 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue 7224 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 7225 int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) { 7226 Value *Val, *Ptr; LocTy Loc, PtrLoc; 7227 MaybeAlign Alignment; 7228 bool AteExtraComma = false; 7229 bool isAtomic = false; 7230 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7231 SyncScope::ID SSID = SyncScope::System; 7232 7233 if (Lex.getKind() == lltok::kw_atomic) { 7234 isAtomic = true; 7235 Lex.Lex(); 7236 } 7237 7238 bool isVolatile = false; 7239 if (Lex.getKind() == lltok::kw_volatile) { 7240 isVolatile = true; 7241 Lex.Lex(); 7242 } 7243 7244 if (parseTypeAndValue(Val, Loc, PFS) || 7245 parseToken(lltok::comma, "expected ',' after store operand") || 7246 parseTypeAndValue(Ptr, PtrLoc, PFS) || 7247 parseScopeAndOrdering(isAtomic, SSID, Ordering) || 7248 parseOptionalCommaAlign(Alignment, AteExtraComma)) 7249 return true; 7250 7251 if (!Ptr->getType()->isPointerTy()) 7252 return error(PtrLoc, "store operand must be a pointer"); 7253 if (!Val->getType()->isFirstClassType()) 7254 return error(Loc, "store operand must be a first class value"); 7255 if (!cast<PointerType>(Ptr->getType()) 7256 ->isOpaqueOrPointeeTypeMatches(Val->getType())) 7257 return error(Loc, "stored value and pointer type do not match"); 7258 if (isAtomic && !Alignment) 7259 return error(Loc, "atomic store must have explicit non-zero alignment"); 7260 if (Ordering == AtomicOrdering::Acquire || 7261 Ordering == AtomicOrdering::AcquireRelease) 7262 return error(Loc, "atomic store cannot use Acquire ordering"); 7263 SmallPtrSet<Type *, 4> Visited; 7264 if (!Alignment && !Val->getType()->isSized(&Visited)) 7265 return error(Loc, "storing unsized types is not allowed"); 7266 if (!Alignment) 7267 Alignment = M->getDataLayout().getABITypeAlign(Val->getType()); 7268 7269 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID); 7270 return AteExtraComma ? InstExtraComma : InstNormal; 7271 } 7272 7273 /// parseCmpXchg 7274 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ',' 7275 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ',' 7276 /// 'Align'? 7277 int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) { 7278 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc; 7279 bool AteExtraComma = false; 7280 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic; 7281 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic; 7282 SyncScope::ID SSID = SyncScope::System; 7283 bool isVolatile = false; 7284 bool isWeak = false; 7285 MaybeAlign Alignment; 7286 7287 if (EatIfPresent(lltok::kw_weak)) 7288 isWeak = true; 7289 7290 if (EatIfPresent(lltok::kw_volatile)) 7291 isVolatile = true; 7292 7293 if (parseTypeAndValue(Ptr, PtrLoc, PFS) || 7294 parseToken(lltok::comma, "expected ',' after cmpxchg address") || 7295 parseTypeAndValue(Cmp, CmpLoc, PFS) || 7296 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") || 7297 parseTypeAndValue(New, NewLoc, PFS) || 7298 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) || 7299 parseOrdering(FailureOrdering) || 7300 parseOptionalCommaAlign(Alignment, AteExtraComma)) 7301 return true; 7302 7303 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering)) 7304 return tokError("invalid cmpxchg success ordering"); 7305 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering)) 7306 return tokError("invalid cmpxchg failure ordering"); 7307 if (!Ptr->getType()->isPointerTy()) 7308 return error(PtrLoc, "cmpxchg operand must be a pointer"); 7309 if (!cast<PointerType>(Ptr->getType()) 7310 ->isOpaqueOrPointeeTypeMatches(Cmp->getType())) 7311 return error(CmpLoc, "compare value and pointer type do not match"); 7312 if (!cast<PointerType>(Ptr->getType()) 7313 ->isOpaqueOrPointeeTypeMatches(New->getType())) 7314 return error(NewLoc, "new value and pointer type do not match"); 7315 if (Cmp->getType() != New->getType()) 7316 return error(NewLoc, "compare value and new value type do not match"); 7317 if (!New->getType()->isFirstClassType()) 7318 return error(NewLoc, "cmpxchg operand must be a first class value"); 7319 7320 const Align DefaultAlignment( 7321 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize( 7322 Cmp->getType())); 7323 7324 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst( 7325 Ptr, Cmp, New, Alignment.getValueOr(DefaultAlignment), SuccessOrdering, 7326 FailureOrdering, SSID); 7327 CXI->setVolatile(isVolatile); 7328 CXI->setWeak(isWeak); 7329 7330 Inst = CXI; 7331 return AteExtraComma ? InstExtraComma : InstNormal; 7332 } 7333 7334 /// parseAtomicRMW 7335 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue 7336 /// 'singlethread'? AtomicOrdering 7337 int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) { 7338 Value *Ptr, *Val; LocTy PtrLoc, ValLoc; 7339 bool AteExtraComma = false; 7340 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7341 SyncScope::ID SSID = SyncScope::System; 7342 bool isVolatile = false; 7343 bool IsFP = false; 7344 AtomicRMWInst::BinOp Operation; 7345 MaybeAlign Alignment; 7346 7347 if (EatIfPresent(lltok::kw_volatile)) 7348 isVolatile = true; 7349 7350 switch (Lex.getKind()) { 7351 default: 7352 return tokError("expected binary operation in atomicrmw"); 7353 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break; 7354 case lltok::kw_add: Operation = AtomicRMWInst::Add; break; 7355 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break; 7356 case lltok::kw_and: Operation = AtomicRMWInst::And; break; 7357 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break; 7358 case lltok::kw_or: Operation = AtomicRMWInst::Or; break; 7359 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break; 7360 case lltok::kw_max: Operation = AtomicRMWInst::Max; break; 7361 case lltok::kw_min: Operation = AtomicRMWInst::Min; break; 7362 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break; 7363 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break; 7364 case lltok::kw_fadd: 7365 Operation = AtomicRMWInst::FAdd; 7366 IsFP = true; 7367 break; 7368 case lltok::kw_fsub: 7369 Operation = AtomicRMWInst::FSub; 7370 IsFP = true; 7371 break; 7372 } 7373 Lex.Lex(); // Eat the operation. 7374 7375 if (parseTypeAndValue(Ptr, PtrLoc, PFS) || 7376 parseToken(lltok::comma, "expected ',' after atomicrmw address") || 7377 parseTypeAndValue(Val, ValLoc, PFS) || 7378 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) || 7379 parseOptionalCommaAlign(Alignment, AteExtraComma)) 7380 return true; 7381 7382 if (Ordering == AtomicOrdering::Unordered) 7383 return tokError("atomicrmw cannot be unordered"); 7384 if (!Ptr->getType()->isPointerTy()) 7385 return error(PtrLoc, "atomicrmw operand must be a pointer"); 7386 if (!cast<PointerType>(Ptr->getType()) 7387 ->isOpaqueOrPointeeTypeMatches(Val->getType())) 7388 return error(ValLoc, "atomicrmw value and pointer type do not match"); 7389 7390 if (Operation == AtomicRMWInst::Xchg) { 7391 if (!Val->getType()->isIntegerTy() && 7392 !Val->getType()->isFloatingPointTy()) { 7393 return error(ValLoc, 7394 "atomicrmw " + AtomicRMWInst::getOperationName(Operation) + 7395 " operand must be an integer or floating point type"); 7396 } 7397 } else if (IsFP) { 7398 if (!Val->getType()->isFloatingPointTy()) { 7399 return error(ValLoc, "atomicrmw " + 7400 AtomicRMWInst::getOperationName(Operation) + 7401 " operand must be a floating point type"); 7402 } 7403 } else { 7404 if (!Val->getType()->isIntegerTy()) { 7405 return error(ValLoc, "atomicrmw " + 7406 AtomicRMWInst::getOperationName(Operation) + 7407 " operand must be an integer"); 7408 } 7409 } 7410 7411 unsigned Size = Val->getType()->getPrimitiveSizeInBits(); 7412 if (Size < 8 || (Size & (Size - 1))) 7413 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized" 7414 " integer"); 7415 const Align DefaultAlignment( 7416 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize( 7417 Val->getType())); 7418 AtomicRMWInst *RMWI = 7419 new AtomicRMWInst(Operation, Ptr, Val, 7420 Alignment.getValueOr(DefaultAlignment), Ordering, SSID); 7421 RMWI->setVolatile(isVolatile); 7422 Inst = RMWI; 7423 return AteExtraComma ? InstExtraComma : InstNormal; 7424 } 7425 7426 /// parseFence 7427 /// ::= 'fence' 'singlethread'? AtomicOrdering 7428 int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) { 7429 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7430 SyncScope::ID SSID = SyncScope::System; 7431 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering)) 7432 return true; 7433 7434 if (Ordering == AtomicOrdering::Unordered) 7435 return tokError("fence cannot be unordered"); 7436 if (Ordering == AtomicOrdering::Monotonic) 7437 return tokError("fence cannot be monotonic"); 7438 7439 Inst = new FenceInst(Context, Ordering, SSID); 7440 return InstNormal; 7441 } 7442 7443 /// parseGetElementPtr 7444 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)* 7445 int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { 7446 Value *Ptr = nullptr; 7447 Value *Val = nullptr; 7448 LocTy Loc, EltLoc; 7449 7450 bool InBounds = EatIfPresent(lltok::kw_inbounds); 7451 7452 Type *Ty = nullptr; 7453 LocTy ExplicitTypeLoc = Lex.getLoc(); 7454 if (parseType(Ty) || 7455 parseToken(lltok::comma, "expected comma after getelementptr's type") || 7456 parseTypeAndValue(Ptr, Loc, PFS)) 7457 return true; 7458 7459 Type *BaseType = Ptr->getType(); 7460 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType()); 7461 if (!BasePointerType) 7462 return error(Loc, "base of getelementptr must be a pointer"); 7463 7464 if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) { 7465 return error( 7466 ExplicitTypeLoc, 7467 typeComparisonErrorMessage( 7468 "explicit pointee type doesn't match operand's pointee type", Ty, 7469 BasePointerType->getNonOpaquePointerElementType())); 7470 } 7471 7472 SmallVector<Value*, 16> Indices; 7473 bool AteExtraComma = false; 7474 // GEP returns a vector of pointers if at least one of parameters is a vector. 7475 // All vector parameters should have the same vector width. 7476 ElementCount GEPWidth = BaseType->isVectorTy() 7477 ? cast<VectorType>(BaseType)->getElementCount() 7478 : ElementCount::getFixed(0); 7479 7480 while (EatIfPresent(lltok::comma)) { 7481 if (Lex.getKind() == lltok::MetadataVar) { 7482 AteExtraComma = true; 7483 break; 7484 } 7485 if (parseTypeAndValue(Val, EltLoc, PFS)) 7486 return true; 7487 if (!Val->getType()->isIntOrIntVectorTy()) 7488 return error(EltLoc, "getelementptr index must be an integer"); 7489 7490 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) { 7491 ElementCount ValNumEl = ValVTy->getElementCount(); 7492 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl) 7493 return error( 7494 EltLoc, 7495 "getelementptr vector index has a wrong number of elements"); 7496 GEPWidth = ValNumEl; 7497 } 7498 Indices.push_back(Val); 7499 } 7500 7501 SmallPtrSet<Type*, 4> Visited; 7502 if (!Indices.empty() && !Ty->isSized(&Visited)) 7503 return error(Loc, "base element of getelementptr must be sized"); 7504 7505 if (!GetElementPtrInst::getIndexedType(Ty, Indices)) 7506 return error(Loc, "invalid getelementptr indices"); 7507 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices); 7508 if (InBounds) 7509 cast<GetElementPtrInst>(Inst)->setIsInBounds(true); 7510 return AteExtraComma ? InstExtraComma : InstNormal; 7511 } 7512 7513 /// parseExtractValue 7514 /// ::= 'extractvalue' TypeAndValue (',' uint32)+ 7515 int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) { 7516 Value *Val; LocTy Loc; 7517 SmallVector<unsigned, 4> Indices; 7518 bool AteExtraComma; 7519 if (parseTypeAndValue(Val, Loc, PFS) || 7520 parseIndexList(Indices, AteExtraComma)) 7521 return true; 7522 7523 if (!Val->getType()->isAggregateType()) 7524 return error(Loc, "extractvalue operand must be aggregate type"); 7525 7526 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 7527 return error(Loc, "invalid indices for extractvalue"); 7528 Inst = ExtractValueInst::Create(Val, Indices); 7529 return AteExtraComma ? InstExtraComma : InstNormal; 7530 } 7531 7532 /// parseInsertValue 7533 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+ 7534 int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { 7535 Value *Val0, *Val1; LocTy Loc0, Loc1; 7536 SmallVector<unsigned, 4> Indices; 7537 bool AteExtraComma; 7538 if (parseTypeAndValue(Val0, Loc0, PFS) || 7539 parseToken(lltok::comma, "expected comma after insertvalue operand") || 7540 parseTypeAndValue(Val1, Loc1, PFS) || 7541 parseIndexList(Indices, AteExtraComma)) 7542 return true; 7543 7544 if (!Val0->getType()->isAggregateType()) 7545 return error(Loc0, "insertvalue operand must be aggregate type"); 7546 7547 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices); 7548 if (!IndexedType) 7549 return error(Loc0, "invalid indices for insertvalue"); 7550 if (IndexedType != Val1->getType()) 7551 return error(Loc1, "insertvalue operand and field disagree in type: '" + 7552 getTypeString(Val1->getType()) + "' instead of '" + 7553 getTypeString(IndexedType) + "'"); 7554 Inst = InsertValueInst::Create(Val0, Val1, Indices); 7555 return AteExtraComma ? InstExtraComma : InstNormal; 7556 } 7557 7558 //===----------------------------------------------------------------------===// 7559 // Embedded metadata. 7560 //===----------------------------------------------------------------------===// 7561 7562 /// parseMDNodeVector 7563 /// ::= { Element (',' Element)* } 7564 /// Element 7565 /// ::= 'null' | TypeAndValue 7566 bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) { 7567 if (parseToken(lltok::lbrace, "expected '{' here")) 7568 return true; 7569 7570 // Check for an empty list. 7571 if (EatIfPresent(lltok::rbrace)) 7572 return false; 7573 7574 do { 7575 // Null is a special case since it is typeless. 7576 if (EatIfPresent(lltok::kw_null)) { 7577 Elts.push_back(nullptr); 7578 continue; 7579 } 7580 7581 Metadata *MD; 7582 if (parseMetadata(MD, nullptr)) 7583 return true; 7584 Elts.push_back(MD); 7585 } while (EatIfPresent(lltok::comma)); 7586 7587 return parseToken(lltok::rbrace, "expected end of metadata node"); 7588 } 7589 7590 //===----------------------------------------------------------------------===// 7591 // Use-list order directives. 7592 //===----------------------------------------------------------------------===// 7593 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, 7594 SMLoc Loc) { 7595 if (V->use_empty()) 7596 return error(Loc, "value has no uses"); 7597 7598 unsigned NumUses = 0; 7599 SmallDenseMap<const Use *, unsigned, 16> Order; 7600 for (const Use &U : V->uses()) { 7601 if (++NumUses > Indexes.size()) 7602 break; 7603 Order[&U] = Indexes[NumUses - 1]; 7604 } 7605 if (NumUses < 2) 7606 return error(Loc, "value only has one use"); 7607 if (Order.size() != Indexes.size() || NumUses > Indexes.size()) 7608 return error(Loc, 7609 "wrong number of indexes, expected " + Twine(V->getNumUses())); 7610 7611 V->sortUseList([&](const Use &L, const Use &R) { 7612 return Order.lookup(&L) < Order.lookup(&R); 7613 }); 7614 return false; 7615 } 7616 7617 /// parseUseListOrderIndexes 7618 /// ::= '{' uint32 (',' uint32)+ '}' 7619 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) { 7620 SMLoc Loc = Lex.getLoc(); 7621 if (parseToken(lltok::lbrace, "expected '{' here")) 7622 return true; 7623 if (Lex.getKind() == lltok::rbrace) 7624 return Lex.Error("expected non-empty list of uselistorder indexes"); 7625 7626 // Use Offset, Max, and IsOrdered to check consistency of indexes. The 7627 // indexes should be distinct numbers in the range [0, size-1], and should 7628 // not be in order. 7629 unsigned Offset = 0; 7630 unsigned Max = 0; 7631 bool IsOrdered = true; 7632 assert(Indexes.empty() && "Expected empty order vector"); 7633 do { 7634 unsigned Index; 7635 if (parseUInt32(Index)) 7636 return true; 7637 7638 // Update consistency checks. 7639 Offset += Index - Indexes.size(); 7640 Max = std::max(Max, Index); 7641 IsOrdered &= Index == Indexes.size(); 7642 7643 Indexes.push_back(Index); 7644 } while (EatIfPresent(lltok::comma)); 7645 7646 if (parseToken(lltok::rbrace, "expected '}' here")) 7647 return true; 7648 7649 if (Indexes.size() < 2) 7650 return error(Loc, "expected >= 2 uselistorder indexes"); 7651 if (Offset != 0 || Max >= Indexes.size()) 7652 return error(Loc, 7653 "expected distinct uselistorder indexes in range [0, size)"); 7654 if (IsOrdered) 7655 return error(Loc, "expected uselistorder indexes to change the order"); 7656 7657 return false; 7658 } 7659 7660 /// parseUseListOrder 7661 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes 7662 bool LLParser::parseUseListOrder(PerFunctionState *PFS) { 7663 SMLoc Loc = Lex.getLoc(); 7664 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive")) 7665 return true; 7666 7667 Value *V; 7668 SmallVector<unsigned, 16> Indexes; 7669 if (parseTypeAndValue(V, PFS) || 7670 parseToken(lltok::comma, "expected comma in uselistorder directive") || 7671 parseUseListOrderIndexes(Indexes)) 7672 return true; 7673 7674 return sortUseListOrder(V, Indexes, Loc); 7675 } 7676 7677 /// parseUseListOrderBB 7678 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes 7679 bool LLParser::parseUseListOrderBB() { 7680 assert(Lex.getKind() == lltok::kw_uselistorder_bb); 7681 SMLoc Loc = Lex.getLoc(); 7682 Lex.Lex(); 7683 7684 ValID Fn, Label; 7685 SmallVector<unsigned, 16> Indexes; 7686 if (parseValID(Fn, /*PFS=*/nullptr) || 7687 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 7688 parseValID(Label, /*PFS=*/nullptr) || 7689 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 7690 parseUseListOrderIndexes(Indexes)) 7691 return true; 7692 7693 // Check the function. 7694 GlobalValue *GV; 7695 if (Fn.Kind == ValID::t_GlobalName) 7696 GV = M->getNamedValue(Fn.StrVal); 7697 else if (Fn.Kind == ValID::t_GlobalID) 7698 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr; 7699 else 7700 return error(Fn.Loc, "expected function name in uselistorder_bb"); 7701 if (!GV) 7702 return error(Fn.Loc, 7703 "invalid function forward reference in uselistorder_bb"); 7704 auto *F = dyn_cast<Function>(GV); 7705 if (!F) 7706 return error(Fn.Loc, "expected function name in uselistorder_bb"); 7707 if (F->isDeclaration()) 7708 return error(Fn.Loc, "invalid declaration in uselistorder_bb"); 7709 7710 // Check the basic block. 7711 if (Label.Kind == ValID::t_LocalID) 7712 return error(Label.Loc, "invalid numeric label in uselistorder_bb"); 7713 if (Label.Kind != ValID::t_LocalName) 7714 return error(Label.Loc, "expected basic block name in uselistorder_bb"); 7715 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal); 7716 if (!V) 7717 return error(Label.Loc, "invalid basic block in uselistorder_bb"); 7718 if (!isa<BasicBlock>(V)) 7719 return error(Label.Loc, "expected basic block in uselistorder_bb"); 7720 7721 return sortUseListOrder(V, Indexes, Loc); 7722 } 7723 7724 /// ModuleEntry 7725 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')' 7726 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')' 7727 bool LLParser::parseModuleEntry(unsigned ID) { 7728 assert(Lex.getKind() == lltok::kw_module); 7729 Lex.Lex(); 7730 7731 std::string Path; 7732 if (parseToken(lltok::colon, "expected ':' here") || 7733 parseToken(lltok::lparen, "expected '(' here") || 7734 parseToken(lltok::kw_path, "expected 'path' here") || 7735 parseToken(lltok::colon, "expected ':' here") || 7736 parseStringConstant(Path) || 7737 parseToken(lltok::comma, "expected ',' here") || 7738 parseToken(lltok::kw_hash, "expected 'hash' here") || 7739 parseToken(lltok::colon, "expected ':' here") || 7740 parseToken(lltok::lparen, "expected '(' here")) 7741 return true; 7742 7743 ModuleHash Hash; 7744 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") || 7745 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") || 7746 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") || 7747 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") || 7748 parseUInt32(Hash[4])) 7749 return true; 7750 7751 if (parseToken(lltok::rparen, "expected ')' here") || 7752 parseToken(lltok::rparen, "expected ')' here")) 7753 return true; 7754 7755 auto ModuleEntry = Index->addModule(Path, ID, Hash); 7756 ModuleIdMap[ID] = ModuleEntry->first(); 7757 7758 return false; 7759 } 7760 7761 /// TypeIdEntry 7762 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')' 7763 bool LLParser::parseTypeIdEntry(unsigned ID) { 7764 assert(Lex.getKind() == lltok::kw_typeid); 7765 Lex.Lex(); 7766 7767 std::string Name; 7768 if (parseToken(lltok::colon, "expected ':' here") || 7769 parseToken(lltok::lparen, "expected '(' here") || 7770 parseToken(lltok::kw_name, "expected 'name' here") || 7771 parseToken(lltok::colon, "expected ':' here") || 7772 parseStringConstant(Name)) 7773 return true; 7774 7775 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name); 7776 if (parseToken(lltok::comma, "expected ',' here") || 7777 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here")) 7778 return true; 7779 7780 // Check if this ID was forward referenced, and if so, update the 7781 // corresponding GUIDs. 7782 auto FwdRefTIDs = ForwardRefTypeIds.find(ID); 7783 if (FwdRefTIDs != ForwardRefTypeIds.end()) { 7784 for (auto TIDRef : FwdRefTIDs->second) { 7785 assert(!*TIDRef.first && 7786 "Forward referenced type id GUID expected to be 0"); 7787 *TIDRef.first = GlobalValue::getGUID(Name); 7788 } 7789 ForwardRefTypeIds.erase(FwdRefTIDs); 7790 } 7791 7792 return false; 7793 } 7794 7795 /// TypeIdSummary 7796 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')' 7797 bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) { 7798 if (parseToken(lltok::kw_summary, "expected 'summary' here") || 7799 parseToken(lltok::colon, "expected ':' here") || 7800 parseToken(lltok::lparen, "expected '(' here") || 7801 parseTypeTestResolution(TIS.TTRes)) 7802 return true; 7803 7804 if (EatIfPresent(lltok::comma)) { 7805 // Expect optional wpdResolutions field 7806 if (parseOptionalWpdResolutions(TIS.WPDRes)) 7807 return true; 7808 } 7809 7810 if (parseToken(lltok::rparen, "expected ')' here")) 7811 return true; 7812 7813 return false; 7814 } 7815 7816 static ValueInfo EmptyVI = 7817 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8); 7818 7819 /// TypeIdCompatibleVtableEntry 7820 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ',' 7821 /// TypeIdCompatibleVtableInfo 7822 /// ')' 7823 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) { 7824 assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable); 7825 Lex.Lex(); 7826 7827 std::string Name; 7828 if (parseToken(lltok::colon, "expected ':' here") || 7829 parseToken(lltok::lparen, "expected '(' here") || 7830 parseToken(lltok::kw_name, "expected 'name' here") || 7831 parseToken(lltok::colon, "expected ':' here") || 7832 parseStringConstant(Name)) 7833 return true; 7834 7835 TypeIdCompatibleVtableInfo &TI = 7836 Index->getOrInsertTypeIdCompatibleVtableSummary(Name); 7837 if (parseToken(lltok::comma, "expected ',' here") || 7838 parseToken(lltok::kw_summary, "expected 'summary' here") || 7839 parseToken(lltok::colon, "expected ':' here") || 7840 parseToken(lltok::lparen, "expected '(' here")) 7841 return true; 7842 7843 IdToIndexMapType IdToIndexMap; 7844 // parse each call edge 7845 do { 7846 uint64_t Offset; 7847 if (parseToken(lltok::lparen, "expected '(' here") || 7848 parseToken(lltok::kw_offset, "expected 'offset' here") || 7849 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) || 7850 parseToken(lltok::comma, "expected ',' here")) 7851 return true; 7852 7853 LocTy Loc = Lex.getLoc(); 7854 unsigned GVId; 7855 ValueInfo VI; 7856 if (parseGVReference(VI, GVId)) 7857 return true; 7858 7859 // Keep track of the TypeIdCompatibleVtableInfo array index needing a 7860 // forward reference. We will save the location of the ValueInfo needing an 7861 // update, but can only do so once the std::vector is finalized. 7862 if (VI == EmptyVI) 7863 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc)); 7864 TI.push_back({Offset, VI}); 7865 7866 if (parseToken(lltok::rparen, "expected ')' in call")) 7867 return true; 7868 } while (EatIfPresent(lltok::comma)); 7869 7870 // Now that the TI vector is finalized, it is safe to save the locations 7871 // of any forward GV references that need updating later. 7872 for (auto I : IdToIndexMap) { 7873 auto &Infos = ForwardRefValueInfos[I.first]; 7874 for (auto P : I.second) { 7875 assert(TI[P.first].VTableVI == EmptyVI && 7876 "Forward referenced ValueInfo expected to be empty"); 7877 Infos.emplace_back(&TI[P.first].VTableVI, P.second); 7878 } 7879 } 7880 7881 if (parseToken(lltok::rparen, "expected ')' here") || 7882 parseToken(lltok::rparen, "expected ')' here")) 7883 return true; 7884 7885 // Check if this ID was forward referenced, and if so, update the 7886 // corresponding GUIDs. 7887 auto FwdRefTIDs = ForwardRefTypeIds.find(ID); 7888 if (FwdRefTIDs != ForwardRefTypeIds.end()) { 7889 for (auto TIDRef : FwdRefTIDs->second) { 7890 assert(!*TIDRef.first && 7891 "Forward referenced type id GUID expected to be 0"); 7892 *TIDRef.first = GlobalValue::getGUID(Name); 7893 } 7894 ForwardRefTypeIds.erase(FwdRefTIDs); 7895 } 7896 7897 return false; 7898 } 7899 7900 /// TypeTestResolution 7901 /// ::= 'typeTestRes' ':' '(' 'kind' ':' 7902 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ',' 7903 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]? 7904 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]? 7905 /// [',' 'inlinesBits' ':' UInt64]? ')' 7906 bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) { 7907 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") || 7908 parseToken(lltok::colon, "expected ':' here") || 7909 parseToken(lltok::lparen, "expected '(' here") || 7910 parseToken(lltok::kw_kind, "expected 'kind' here") || 7911 parseToken(lltok::colon, "expected ':' here")) 7912 return true; 7913 7914 switch (Lex.getKind()) { 7915 case lltok::kw_unknown: 7916 TTRes.TheKind = TypeTestResolution::Unknown; 7917 break; 7918 case lltok::kw_unsat: 7919 TTRes.TheKind = TypeTestResolution::Unsat; 7920 break; 7921 case lltok::kw_byteArray: 7922 TTRes.TheKind = TypeTestResolution::ByteArray; 7923 break; 7924 case lltok::kw_inline: 7925 TTRes.TheKind = TypeTestResolution::Inline; 7926 break; 7927 case lltok::kw_single: 7928 TTRes.TheKind = TypeTestResolution::Single; 7929 break; 7930 case lltok::kw_allOnes: 7931 TTRes.TheKind = TypeTestResolution::AllOnes; 7932 break; 7933 default: 7934 return error(Lex.getLoc(), "unexpected TypeTestResolution kind"); 7935 } 7936 Lex.Lex(); 7937 7938 if (parseToken(lltok::comma, "expected ',' here") || 7939 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") || 7940 parseToken(lltok::colon, "expected ':' here") || 7941 parseUInt32(TTRes.SizeM1BitWidth)) 7942 return true; 7943 7944 // parse optional fields 7945 while (EatIfPresent(lltok::comma)) { 7946 switch (Lex.getKind()) { 7947 case lltok::kw_alignLog2: 7948 Lex.Lex(); 7949 if (parseToken(lltok::colon, "expected ':'") || 7950 parseUInt64(TTRes.AlignLog2)) 7951 return true; 7952 break; 7953 case lltok::kw_sizeM1: 7954 Lex.Lex(); 7955 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1)) 7956 return true; 7957 break; 7958 case lltok::kw_bitMask: { 7959 unsigned Val; 7960 Lex.Lex(); 7961 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val)) 7962 return true; 7963 assert(Val <= 0xff); 7964 TTRes.BitMask = (uint8_t)Val; 7965 break; 7966 } 7967 case lltok::kw_inlineBits: 7968 Lex.Lex(); 7969 if (parseToken(lltok::colon, "expected ':'") || 7970 parseUInt64(TTRes.InlineBits)) 7971 return true; 7972 break; 7973 default: 7974 return error(Lex.getLoc(), "expected optional TypeTestResolution field"); 7975 } 7976 } 7977 7978 if (parseToken(lltok::rparen, "expected ')' here")) 7979 return true; 7980 7981 return false; 7982 } 7983 7984 /// OptionalWpdResolutions 7985 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')' 7986 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')' 7987 bool LLParser::parseOptionalWpdResolutions( 7988 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) { 7989 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") || 7990 parseToken(lltok::colon, "expected ':' here") || 7991 parseToken(lltok::lparen, "expected '(' here")) 7992 return true; 7993 7994 do { 7995 uint64_t Offset; 7996 WholeProgramDevirtResolution WPDRes; 7997 if (parseToken(lltok::lparen, "expected '(' here") || 7998 parseToken(lltok::kw_offset, "expected 'offset' here") || 7999 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) || 8000 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) || 8001 parseToken(lltok::rparen, "expected ')' here")) 8002 return true; 8003 WPDResMap[Offset] = WPDRes; 8004 } while (EatIfPresent(lltok::comma)); 8005 8006 if (parseToken(lltok::rparen, "expected ')' here")) 8007 return true; 8008 8009 return false; 8010 } 8011 8012 /// WpdRes 8013 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir' 8014 /// [',' OptionalResByArg]? ')' 8015 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl' 8016 /// ',' 'singleImplName' ':' STRINGCONSTANT ',' 8017 /// [',' OptionalResByArg]? ')' 8018 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel' 8019 /// [',' OptionalResByArg]? ')' 8020 bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) { 8021 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") || 8022 parseToken(lltok::colon, "expected ':' here") || 8023 parseToken(lltok::lparen, "expected '(' here") || 8024 parseToken(lltok::kw_kind, "expected 'kind' here") || 8025 parseToken(lltok::colon, "expected ':' here")) 8026 return true; 8027 8028 switch (Lex.getKind()) { 8029 case lltok::kw_indir: 8030 WPDRes.TheKind = WholeProgramDevirtResolution::Indir; 8031 break; 8032 case lltok::kw_singleImpl: 8033 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl; 8034 break; 8035 case lltok::kw_branchFunnel: 8036 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel; 8037 break; 8038 default: 8039 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind"); 8040 } 8041 Lex.Lex(); 8042 8043 // parse optional fields 8044 while (EatIfPresent(lltok::comma)) { 8045 switch (Lex.getKind()) { 8046 case lltok::kw_singleImplName: 8047 Lex.Lex(); 8048 if (parseToken(lltok::colon, "expected ':' here") || 8049 parseStringConstant(WPDRes.SingleImplName)) 8050 return true; 8051 break; 8052 case lltok::kw_resByArg: 8053 if (parseOptionalResByArg(WPDRes.ResByArg)) 8054 return true; 8055 break; 8056 default: 8057 return error(Lex.getLoc(), 8058 "expected optional WholeProgramDevirtResolution field"); 8059 } 8060 } 8061 8062 if (parseToken(lltok::rparen, "expected ')' here")) 8063 return true; 8064 8065 return false; 8066 } 8067 8068 /// OptionalResByArg 8069 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')' 8070 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':' 8071 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' | 8072 /// 'virtualConstProp' ) 8073 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]? 8074 /// [',' 'bit' ':' UInt32]? ')' 8075 bool LLParser::parseOptionalResByArg( 8076 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg> 8077 &ResByArg) { 8078 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") || 8079 parseToken(lltok::colon, "expected ':' here") || 8080 parseToken(lltok::lparen, "expected '(' here")) 8081 return true; 8082 8083 do { 8084 std::vector<uint64_t> Args; 8085 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") || 8086 parseToken(lltok::kw_byArg, "expected 'byArg here") || 8087 parseToken(lltok::colon, "expected ':' here") || 8088 parseToken(lltok::lparen, "expected '(' here") || 8089 parseToken(lltok::kw_kind, "expected 'kind' here") || 8090 parseToken(lltok::colon, "expected ':' here")) 8091 return true; 8092 8093 WholeProgramDevirtResolution::ByArg ByArg; 8094 switch (Lex.getKind()) { 8095 case lltok::kw_indir: 8096 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir; 8097 break; 8098 case lltok::kw_uniformRetVal: 8099 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal; 8100 break; 8101 case lltok::kw_uniqueRetVal: 8102 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal; 8103 break; 8104 case lltok::kw_virtualConstProp: 8105 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp; 8106 break; 8107 default: 8108 return error(Lex.getLoc(), 8109 "unexpected WholeProgramDevirtResolution::ByArg kind"); 8110 } 8111 Lex.Lex(); 8112 8113 // parse optional fields 8114 while (EatIfPresent(lltok::comma)) { 8115 switch (Lex.getKind()) { 8116 case lltok::kw_info: 8117 Lex.Lex(); 8118 if (parseToken(lltok::colon, "expected ':' here") || 8119 parseUInt64(ByArg.Info)) 8120 return true; 8121 break; 8122 case lltok::kw_byte: 8123 Lex.Lex(); 8124 if (parseToken(lltok::colon, "expected ':' here") || 8125 parseUInt32(ByArg.Byte)) 8126 return true; 8127 break; 8128 case lltok::kw_bit: 8129 Lex.Lex(); 8130 if (parseToken(lltok::colon, "expected ':' here") || 8131 parseUInt32(ByArg.Bit)) 8132 return true; 8133 break; 8134 default: 8135 return error(Lex.getLoc(), 8136 "expected optional whole program devirt field"); 8137 } 8138 } 8139 8140 if (parseToken(lltok::rparen, "expected ')' here")) 8141 return true; 8142 8143 ResByArg[Args] = ByArg; 8144 } while (EatIfPresent(lltok::comma)); 8145 8146 if (parseToken(lltok::rparen, "expected ')' here")) 8147 return true; 8148 8149 return false; 8150 } 8151 8152 /// OptionalResByArg 8153 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')' 8154 bool LLParser::parseArgs(std::vector<uint64_t> &Args) { 8155 if (parseToken(lltok::kw_args, "expected 'args' here") || 8156 parseToken(lltok::colon, "expected ':' here") || 8157 parseToken(lltok::lparen, "expected '(' here")) 8158 return true; 8159 8160 do { 8161 uint64_t Val; 8162 if (parseUInt64(Val)) 8163 return true; 8164 Args.push_back(Val); 8165 } while (EatIfPresent(lltok::comma)); 8166 8167 if (parseToken(lltok::rparen, "expected ')' here")) 8168 return true; 8169 8170 return false; 8171 } 8172 8173 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8; 8174 8175 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) { 8176 bool ReadOnly = Fwd->isReadOnly(); 8177 bool WriteOnly = Fwd->isWriteOnly(); 8178 assert(!(ReadOnly && WriteOnly)); 8179 *Fwd = Resolved; 8180 if (ReadOnly) 8181 Fwd->setReadOnly(); 8182 if (WriteOnly) 8183 Fwd->setWriteOnly(); 8184 } 8185 8186 /// Stores the given Name/GUID and associated summary into the Index. 8187 /// Also updates any forward references to the associated entry ID. 8188 void LLParser::addGlobalValueToIndex( 8189 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage, 8190 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) { 8191 // First create the ValueInfo utilizing the Name or GUID. 8192 ValueInfo VI; 8193 if (GUID != 0) { 8194 assert(Name.empty()); 8195 VI = Index->getOrInsertValueInfo(GUID); 8196 } else { 8197 assert(!Name.empty()); 8198 if (M) { 8199 auto *GV = M->getNamedValue(Name); 8200 assert(GV); 8201 VI = Index->getOrInsertValueInfo(GV); 8202 } else { 8203 assert( 8204 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) && 8205 "Need a source_filename to compute GUID for local"); 8206 GUID = GlobalValue::getGUID( 8207 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName)); 8208 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name)); 8209 } 8210 } 8211 8212 // Resolve forward references from calls/refs 8213 auto FwdRefVIs = ForwardRefValueInfos.find(ID); 8214 if (FwdRefVIs != ForwardRefValueInfos.end()) { 8215 for (auto VIRef : FwdRefVIs->second) { 8216 assert(VIRef.first->getRef() == FwdVIRef && 8217 "Forward referenced ValueInfo expected to be empty"); 8218 resolveFwdRef(VIRef.first, VI); 8219 } 8220 ForwardRefValueInfos.erase(FwdRefVIs); 8221 } 8222 8223 // Resolve forward references from aliases 8224 auto FwdRefAliasees = ForwardRefAliasees.find(ID); 8225 if (FwdRefAliasees != ForwardRefAliasees.end()) { 8226 for (auto AliaseeRef : FwdRefAliasees->second) { 8227 assert(!AliaseeRef.first->hasAliasee() && 8228 "Forward referencing alias already has aliasee"); 8229 assert(Summary && "Aliasee must be a definition"); 8230 AliaseeRef.first->setAliasee(VI, Summary.get()); 8231 } 8232 ForwardRefAliasees.erase(FwdRefAliasees); 8233 } 8234 8235 // Add the summary if one was provided. 8236 if (Summary) 8237 Index->addGlobalValueSummary(VI, std::move(Summary)); 8238 8239 // Save the associated ValueInfo for use in later references by ID. 8240 if (ID == NumberedValueInfos.size()) 8241 NumberedValueInfos.push_back(VI); 8242 else { 8243 // Handle non-continuous numbers (to make test simplification easier). 8244 if (ID > NumberedValueInfos.size()) 8245 NumberedValueInfos.resize(ID + 1); 8246 NumberedValueInfos[ID] = VI; 8247 } 8248 } 8249 8250 /// parseSummaryIndexFlags 8251 /// ::= 'flags' ':' UInt64 8252 bool LLParser::parseSummaryIndexFlags() { 8253 assert(Lex.getKind() == lltok::kw_flags); 8254 Lex.Lex(); 8255 8256 if (parseToken(lltok::colon, "expected ':' here")) 8257 return true; 8258 uint64_t Flags; 8259 if (parseUInt64(Flags)) 8260 return true; 8261 if (Index) 8262 Index->setFlags(Flags); 8263 return false; 8264 } 8265 8266 /// parseBlockCount 8267 /// ::= 'blockcount' ':' UInt64 8268 bool LLParser::parseBlockCount() { 8269 assert(Lex.getKind() == lltok::kw_blockcount); 8270 Lex.Lex(); 8271 8272 if (parseToken(lltok::colon, "expected ':' here")) 8273 return true; 8274 uint64_t BlockCount; 8275 if (parseUInt64(BlockCount)) 8276 return true; 8277 if (Index) 8278 Index->setBlockCount(BlockCount); 8279 return false; 8280 } 8281 8282 /// parseGVEntry 8283 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64) 8284 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')' 8285 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')' 8286 bool LLParser::parseGVEntry(unsigned ID) { 8287 assert(Lex.getKind() == lltok::kw_gv); 8288 Lex.Lex(); 8289 8290 if (parseToken(lltok::colon, "expected ':' here") || 8291 parseToken(lltok::lparen, "expected '(' here")) 8292 return true; 8293 8294 std::string Name; 8295 GlobalValue::GUID GUID = 0; 8296 switch (Lex.getKind()) { 8297 case lltok::kw_name: 8298 Lex.Lex(); 8299 if (parseToken(lltok::colon, "expected ':' here") || 8300 parseStringConstant(Name)) 8301 return true; 8302 // Can't create GUID/ValueInfo until we have the linkage. 8303 break; 8304 case lltok::kw_guid: 8305 Lex.Lex(); 8306 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID)) 8307 return true; 8308 break; 8309 default: 8310 return error(Lex.getLoc(), "expected name or guid tag"); 8311 } 8312 8313 if (!EatIfPresent(lltok::comma)) { 8314 // No summaries. Wrap up. 8315 if (parseToken(lltok::rparen, "expected ')' here")) 8316 return true; 8317 // This was created for a call to an external or indirect target. 8318 // A GUID with no summary came from a VALUE_GUID record, dummy GUID 8319 // created for indirect calls with VP. A Name with no GUID came from 8320 // an external definition. We pass ExternalLinkage since that is only 8321 // used when the GUID must be computed from Name, and in that case 8322 // the symbol must have external linkage. 8323 addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID, 8324 nullptr); 8325 return false; 8326 } 8327 8328 // Have a list of summaries 8329 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") || 8330 parseToken(lltok::colon, "expected ':' here") || 8331 parseToken(lltok::lparen, "expected '(' here")) 8332 return true; 8333 do { 8334 switch (Lex.getKind()) { 8335 case lltok::kw_function: 8336 if (parseFunctionSummary(Name, GUID, ID)) 8337 return true; 8338 break; 8339 case lltok::kw_variable: 8340 if (parseVariableSummary(Name, GUID, ID)) 8341 return true; 8342 break; 8343 case lltok::kw_alias: 8344 if (parseAliasSummary(Name, GUID, ID)) 8345 return true; 8346 break; 8347 default: 8348 return error(Lex.getLoc(), "expected summary type"); 8349 } 8350 } while (EatIfPresent(lltok::comma)); 8351 8352 if (parseToken(lltok::rparen, "expected ')' here") || 8353 parseToken(lltok::rparen, "expected ')' here")) 8354 return true; 8355 8356 return false; 8357 } 8358 8359 /// FunctionSummary 8360 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags 8361 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]? 8362 /// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]? 8363 /// [',' OptionalRefs]? ')' 8364 bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID, 8365 unsigned ID) { 8366 assert(Lex.getKind() == lltok::kw_function); 8367 Lex.Lex(); 8368 8369 StringRef ModulePath; 8370 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8371 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility, 8372 /*NotEligibleToImport=*/false, 8373 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8374 unsigned InstCount; 8375 std::vector<FunctionSummary::EdgeTy> Calls; 8376 FunctionSummary::TypeIdInfo TypeIdInfo; 8377 std::vector<FunctionSummary::ParamAccess> ParamAccesses; 8378 std::vector<ValueInfo> Refs; 8379 // Default is all-zeros (conservative values). 8380 FunctionSummary::FFlags FFlags = {}; 8381 if (parseToken(lltok::colon, "expected ':' here") || 8382 parseToken(lltok::lparen, "expected '(' here") || 8383 parseModuleReference(ModulePath) || 8384 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 8385 parseToken(lltok::comma, "expected ',' here") || 8386 parseToken(lltok::kw_insts, "expected 'insts' here") || 8387 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount)) 8388 return true; 8389 8390 // parse optional fields 8391 while (EatIfPresent(lltok::comma)) { 8392 switch (Lex.getKind()) { 8393 case lltok::kw_funcFlags: 8394 if (parseOptionalFFlags(FFlags)) 8395 return true; 8396 break; 8397 case lltok::kw_calls: 8398 if (parseOptionalCalls(Calls)) 8399 return true; 8400 break; 8401 case lltok::kw_typeIdInfo: 8402 if (parseOptionalTypeIdInfo(TypeIdInfo)) 8403 return true; 8404 break; 8405 case lltok::kw_refs: 8406 if (parseOptionalRefs(Refs)) 8407 return true; 8408 break; 8409 case lltok::kw_params: 8410 if (parseOptionalParamAccesses(ParamAccesses)) 8411 return true; 8412 break; 8413 default: 8414 return error(Lex.getLoc(), "expected optional function summary field"); 8415 } 8416 } 8417 8418 if (parseToken(lltok::rparen, "expected ')' here")) 8419 return true; 8420 8421 auto FS = std::make_unique<FunctionSummary>( 8422 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs), 8423 std::move(Calls), std::move(TypeIdInfo.TypeTests), 8424 std::move(TypeIdInfo.TypeTestAssumeVCalls), 8425 std::move(TypeIdInfo.TypeCheckedLoadVCalls), 8426 std::move(TypeIdInfo.TypeTestAssumeConstVCalls), 8427 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls), 8428 std::move(ParamAccesses)); 8429 8430 FS->setModulePath(ModulePath); 8431 8432 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8433 ID, std::move(FS)); 8434 8435 return false; 8436 } 8437 8438 /// VariableSummary 8439 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags 8440 /// [',' OptionalRefs]? ')' 8441 bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID, 8442 unsigned ID) { 8443 assert(Lex.getKind() == lltok::kw_variable); 8444 Lex.Lex(); 8445 8446 StringRef ModulePath; 8447 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8448 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility, 8449 /*NotEligibleToImport=*/false, 8450 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8451 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false, 8452 /* WriteOnly */ false, 8453 /* Constant */ false, 8454 GlobalObject::VCallVisibilityPublic); 8455 std::vector<ValueInfo> Refs; 8456 VTableFuncList VTableFuncs; 8457 if (parseToken(lltok::colon, "expected ':' here") || 8458 parseToken(lltok::lparen, "expected '(' here") || 8459 parseModuleReference(ModulePath) || 8460 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 8461 parseToken(lltok::comma, "expected ',' here") || 8462 parseGVarFlags(GVarFlags)) 8463 return true; 8464 8465 // parse optional fields 8466 while (EatIfPresent(lltok::comma)) { 8467 switch (Lex.getKind()) { 8468 case lltok::kw_vTableFuncs: 8469 if (parseOptionalVTableFuncs(VTableFuncs)) 8470 return true; 8471 break; 8472 case lltok::kw_refs: 8473 if (parseOptionalRefs(Refs)) 8474 return true; 8475 break; 8476 default: 8477 return error(Lex.getLoc(), "expected optional variable summary field"); 8478 } 8479 } 8480 8481 if (parseToken(lltok::rparen, "expected ')' here")) 8482 return true; 8483 8484 auto GS = 8485 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs)); 8486 8487 GS->setModulePath(ModulePath); 8488 GS->setVTableFuncs(std::move(VTableFuncs)); 8489 8490 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8491 ID, std::move(GS)); 8492 8493 return false; 8494 } 8495 8496 /// AliasSummary 8497 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ',' 8498 /// 'aliasee' ':' GVReference ')' 8499 bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID, 8500 unsigned ID) { 8501 assert(Lex.getKind() == lltok::kw_alias); 8502 LocTy Loc = Lex.getLoc(); 8503 Lex.Lex(); 8504 8505 StringRef ModulePath; 8506 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8507 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility, 8508 /*NotEligibleToImport=*/false, 8509 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8510 if (parseToken(lltok::colon, "expected ':' here") || 8511 parseToken(lltok::lparen, "expected '(' here") || 8512 parseModuleReference(ModulePath) || 8513 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 8514 parseToken(lltok::comma, "expected ',' here") || 8515 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") || 8516 parseToken(lltok::colon, "expected ':' here")) 8517 return true; 8518 8519 ValueInfo AliaseeVI; 8520 unsigned GVId; 8521 if (parseGVReference(AliaseeVI, GVId)) 8522 return true; 8523 8524 if (parseToken(lltok::rparen, "expected ')' here")) 8525 return true; 8526 8527 auto AS = std::make_unique<AliasSummary>(GVFlags); 8528 8529 AS->setModulePath(ModulePath); 8530 8531 // Record forward reference if the aliasee is not parsed yet. 8532 if (AliaseeVI.getRef() == FwdVIRef) { 8533 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc); 8534 } else { 8535 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath); 8536 assert(Summary && "Aliasee must be a definition"); 8537 AS->setAliasee(AliaseeVI, Summary); 8538 } 8539 8540 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8541 ID, std::move(AS)); 8542 8543 return false; 8544 } 8545 8546 /// Flag 8547 /// ::= [0|1] 8548 bool LLParser::parseFlag(unsigned &Val) { 8549 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 8550 return tokError("expected integer"); 8551 Val = (unsigned)Lex.getAPSIntVal().getBoolValue(); 8552 Lex.Lex(); 8553 return false; 8554 } 8555 8556 /// OptionalFFlags 8557 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]? 8558 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]? 8559 /// [',' 'returnDoesNotAlias' ':' Flag]? ')' 8560 /// [',' 'noInline' ':' Flag]? ')' 8561 /// [',' 'alwaysInline' ':' Flag]? ')' 8562 /// [',' 'noUnwind' ':' Flag]? ')' 8563 /// [',' 'mayThrow' ':' Flag]? ')' 8564 /// [',' 'hasUnknownCall' ':' Flag]? ')' 8565 /// [',' 'mustBeUnreachable' ':' Flag]? ')' 8566 8567 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) { 8568 assert(Lex.getKind() == lltok::kw_funcFlags); 8569 Lex.Lex(); 8570 8571 if (parseToken(lltok::colon, "expected ':' in funcFlags") || 8572 parseToken(lltok::lparen, "expected '(' in funcFlags")) 8573 return true; 8574 8575 do { 8576 unsigned Val = 0; 8577 switch (Lex.getKind()) { 8578 case lltok::kw_readNone: 8579 Lex.Lex(); 8580 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8581 return true; 8582 FFlags.ReadNone = Val; 8583 break; 8584 case lltok::kw_readOnly: 8585 Lex.Lex(); 8586 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8587 return true; 8588 FFlags.ReadOnly = Val; 8589 break; 8590 case lltok::kw_noRecurse: 8591 Lex.Lex(); 8592 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8593 return true; 8594 FFlags.NoRecurse = Val; 8595 break; 8596 case lltok::kw_returnDoesNotAlias: 8597 Lex.Lex(); 8598 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8599 return true; 8600 FFlags.ReturnDoesNotAlias = Val; 8601 break; 8602 case lltok::kw_noInline: 8603 Lex.Lex(); 8604 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8605 return true; 8606 FFlags.NoInline = Val; 8607 break; 8608 case lltok::kw_alwaysInline: 8609 Lex.Lex(); 8610 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8611 return true; 8612 FFlags.AlwaysInline = Val; 8613 break; 8614 case lltok::kw_noUnwind: 8615 Lex.Lex(); 8616 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8617 return true; 8618 FFlags.NoUnwind = Val; 8619 break; 8620 case lltok::kw_mayThrow: 8621 Lex.Lex(); 8622 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8623 return true; 8624 FFlags.MayThrow = Val; 8625 break; 8626 case lltok::kw_hasUnknownCall: 8627 Lex.Lex(); 8628 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8629 return true; 8630 FFlags.HasUnknownCall = Val; 8631 break; 8632 case lltok::kw_mustBeUnreachable: 8633 Lex.Lex(); 8634 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8635 return true; 8636 FFlags.MustBeUnreachable = Val; 8637 break; 8638 default: 8639 return error(Lex.getLoc(), "expected function flag type"); 8640 } 8641 } while (EatIfPresent(lltok::comma)); 8642 8643 if (parseToken(lltok::rparen, "expected ')' in funcFlags")) 8644 return true; 8645 8646 return false; 8647 } 8648 8649 /// OptionalCalls 8650 /// := 'calls' ':' '(' Call [',' Call]* ')' 8651 /// Call ::= '(' 'callee' ':' GVReference 8652 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')' 8653 bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) { 8654 assert(Lex.getKind() == lltok::kw_calls); 8655 Lex.Lex(); 8656 8657 if (parseToken(lltok::colon, "expected ':' in calls") || 8658 parseToken(lltok::lparen, "expected '(' in calls")) 8659 return true; 8660 8661 IdToIndexMapType IdToIndexMap; 8662 // parse each call edge 8663 do { 8664 ValueInfo VI; 8665 if (parseToken(lltok::lparen, "expected '(' in call") || 8666 parseToken(lltok::kw_callee, "expected 'callee' in call") || 8667 parseToken(lltok::colon, "expected ':'")) 8668 return true; 8669 8670 LocTy Loc = Lex.getLoc(); 8671 unsigned GVId; 8672 if (parseGVReference(VI, GVId)) 8673 return true; 8674 8675 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 8676 unsigned RelBF = 0; 8677 if (EatIfPresent(lltok::comma)) { 8678 // Expect either hotness or relbf 8679 if (EatIfPresent(lltok::kw_hotness)) { 8680 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness)) 8681 return true; 8682 } else { 8683 if (parseToken(lltok::kw_relbf, "expected relbf") || 8684 parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF)) 8685 return true; 8686 } 8687 } 8688 // Keep track of the Call array index needing a forward reference. 8689 // We will save the location of the ValueInfo needing an update, but 8690 // can only do so once the std::vector is finalized. 8691 if (VI.getRef() == FwdVIRef) 8692 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc)); 8693 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)}); 8694 8695 if (parseToken(lltok::rparen, "expected ')' in call")) 8696 return true; 8697 } while (EatIfPresent(lltok::comma)); 8698 8699 // Now that the Calls vector is finalized, it is safe to save the locations 8700 // of any forward GV references that need updating later. 8701 for (auto I : IdToIndexMap) { 8702 auto &Infos = ForwardRefValueInfos[I.first]; 8703 for (auto P : I.second) { 8704 assert(Calls[P.first].first.getRef() == FwdVIRef && 8705 "Forward referenced ValueInfo expected to be empty"); 8706 Infos.emplace_back(&Calls[P.first].first, P.second); 8707 } 8708 } 8709 8710 if (parseToken(lltok::rparen, "expected ')' in calls")) 8711 return true; 8712 8713 return false; 8714 } 8715 8716 /// Hotness 8717 /// := ('unknown'|'cold'|'none'|'hot'|'critical') 8718 bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) { 8719 switch (Lex.getKind()) { 8720 case lltok::kw_unknown: 8721 Hotness = CalleeInfo::HotnessType::Unknown; 8722 break; 8723 case lltok::kw_cold: 8724 Hotness = CalleeInfo::HotnessType::Cold; 8725 break; 8726 case lltok::kw_none: 8727 Hotness = CalleeInfo::HotnessType::None; 8728 break; 8729 case lltok::kw_hot: 8730 Hotness = CalleeInfo::HotnessType::Hot; 8731 break; 8732 case lltok::kw_critical: 8733 Hotness = CalleeInfo::HotnessType::Critical; 8734 break; 8735 default: 8736 return error(Lex.getLoc(), "invalid call edge hotness"); 8737 } 8738 Lex.Lex(); 8739 return false; 8740 } 8741 8742 /// OptionalVTableFuncs 8743 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')' 8744 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')' 8745 bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) { 8746 assert(Lex.getKind() == lltok::kw_vTableFuncs); 8747 Lex.Lex(); 8748 8749 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") || 8750 parseToken(lltok::lparen, "expected '(' in vTableFuncs")) 8751 return true; 8752 8753 IdToIndexMapType IdToIndexMap; 8754 // parse each virtual function pair 8755 do { 8756 ValueInfo VI; 8757 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") || 8758 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") || 8759 parseToken(lltok::colon, "expected ':'")) 8760 return true; 8761 8762 LocTy Loc = Lex.getLoc(); 8763 unsigned GVId; 8764 if (parseGVReference(VI, GVId)) 8765 return true; 8766 8767 uint64_t Offset; 8768 if (parseToken(lltok::comma, "expected comma") || 8769 parseToken(lltok::kw_offset, "expected offset") || 8770 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset)) 8771 return true; 8772 8773 // Keep track of the VTableFuncs array index needing a forward reference. 8774 // We will save the location of the ValueInfo needing an update, but 8775 // can only do so once the std::vector is finalized. 8776 if (VI == EmptyVI) 8777 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc)); 8778 VTableFuncs.push_back({VI, Offset}); 8779 8780 if (parseToken(lltok::rparen, "expected ')' in vTableFunc")) 8781 return true; 8782 } while (EatIfPresent(lltok::comma)); 8783 8784 // Now that the VTableFuncs vector is finalized, it is safe to save the 8785 // locations of any forward GV references that need updating later. 8786 for (auto I : IdToIndexMap) { 8787 auto &Infos = ForwardRefValueInfos[I.first]; 8788 for (auto P : I.second) { 8789 assert(VTableFuncs[P.first].FuncVI == EmptyVI && 8790 "Forward referenced ValueInfo expected to be empty"); 8791 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second); 8792 } 8793 } 8794 8795 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs")) 8796 return true; 8797 8798 return false; 8799 } 8800 8801 /// ParamNo := 'param' ':' UInt64 8802 bool LLParser::parseParamNo(uint64_t &ParamNo) { 8803 if (parseToken(lltok::kw_param, "expected 'param' here") || 8804 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo)) 8805 return true; 8806 return false; 8807 } 8808 8809 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']' 8810 bool LLParser::parseParamAccessOffset(ConstantRange &Range) { 8811 APSInt Lower; 8812 APSInt Upper; 8813 auto ParseAPSInt = [&](APSInt &Val) { 8814 if (Lex.getKind() != lltok::APSInt) 8815 return tokError("expected integer"); 8816 Val = Lex.getAPSIntVal(); 8817 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth); 8818 Val.setIsSigned(true); 8819 Lex.Lex(); 8820 return false; 8821 }; 8822 if (parseToken(lltok::kw_offset, "expected 'offset' here") || 8823 parseToken(lltok::colon, "expected ':' here") || 8824 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) || 8825 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) || 8826 parseToken(lltok::rsquare, "expected ']' here")) 8827 return true; 8828 8829 ++Upper; 8830 Range = 8831 (Lower == Upper && !Lower.isMaxValue()) 8832 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth) 8833 : ConstantRange(Lower, Upper); 8834 8835 return false; 8836 } 8837 8838 /// ParamAccessCall 8839 /// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')' 8840 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call, 8841 IdLocListType &IdLocList) { 8842 if (parseToken(lltok::lparen, "expected '(' here") || 8843 parseToken(lltok::kw_callee, "expected 'callee' here") || 8844 parseToken(lltok::colon, "expected ':' here")) 8845 return true; 8846 8847 unsigned GVId; 8848 ValueInfo VI; 8849 LocTy Loc = Lex.getLoc(); 8850 if (parseGVReference(VI, GVId)) 8851 return true; 8852 8853 Call.Callee = VI; 8854 IdLocList.emplace_back(GVId, Loc); 8855 8856 if (parseToken(lltok::comma, "expected ',' here") || 8857 parseParamNo(Call.ParamNo) || 8858 parseToken(lltok::comma, "expected ',' here") || 8859 parseParamAccessOffset(Call.Offsets)) 8860 return true; 8861 8862 if (parseToken(lltok::rparen, "expected ')' here")) 8863 return true; 8864 8865 return false; 8866 } 8867 8868 /// ParamAccess 8869 /// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')' 8870 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')' 8871 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param, 8872 IdLocListType &IdLocList) { 8873 if (parseToken(lltok::lparen, "expected '(' here") || 8874 parseParamNo(Param.ParamNo) || 8875 parseToken(lltok::comma, "expected ',' here") || 8876 parseParamAccessOffset(Param.Use)) 8877 return true; 8878 8879 if (EatIfPresent(lltok::comma)) { 8880 if (parseToken(lltok::kw_calls, "expected 'calls' here") || 8881 parseToken(lltok::colon, "expected ':' here") || 8882 parseToken(lltok::lparen, "expected '(' here")) 8883 return true; 8884 do { 8885 FunctionSummary::ParamAccess::Call Call; 8886 if (parseParamAccessCall(Call, IdLocList)) 8887 return true; 8888 Param.Calls.push_back(Call); 8889 } while (EatIfPresent(lltok::comma)); 8890 8891 if (parseToken(lltok::rparen, "expected ')' here")) 8892 return true; 8893 } 8894 8895 if (parseToken(lltok::rparen, "expected ')' here")) 8896 return true; 8897 8898 return false; 8899 } 8900 8901 /// OptionalParamAccesses 8902 /// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')' 8903 bool LLParser::parseOptionalParamAccesses( 8904 std::vector<FunctionSummary::ParamAccess> &Params) { 8905 assert(Lex.getKind() == lltok::kw_params); 8906 Lex.Lex(); 8907 8908 if (parseToken(lltok::colon, "expected ':' here") || 8909 parseToken(lltok::lparen, "expected '(' here")) 8910 return true; 8911 8912 IdLocListType VContexts; 8913 size_t CallsNum = 0; 8914 do { 8915 FunctionSummary::ParamAccess ParamAccess; 8916 if (parseParamAccess(ParamAccess, VContexts)) 8917 return true; 8918 CallsNum += ParamAccess.Calls.size(); 8919 assert(VContexts.size() == CallsNum); 8920 (void)CallsNum; 8921 Params.emplace_back(std::move(ParamAccess)); 8922 } while (EatIfPresent(lltok::comma)); 8923 8924 if (parseToken(lltok::rparen, "expected ')' here")) 8925 return true; 8926 8927 // Now that the Params is finalized, it is safe to save the locations 8928 // of any forward GV references that need updating later. 8929 IdLocListType::const_iterator ItContext = VContexts.begin(); 8930 for (auto &PA : Params) { 8931 for (auto &C : PA.Calls) { 8932 if (C.Callee.getRef() == FwdVIRef) 8933 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee, 8934 ItContext->second); 8935 ++ItContext; 8936 } 8937 } 8938 assert(ItContext == VContexts.end()); 8939 8940 return false; 8941 } 8942 8943 /// OptionalRefs 8944 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')' 8945 bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) { 8946 assert(Lex.getKind() == lltok::kw_refs); 8947 Lex.Lex(); 8948 8949 if (parseToken(lltok::colon, "expected ':' in refs") || 8950 parseToken(lltok::lparen, "expected '(' in refs")) 8951 return true; 8952 8953 struct ValueContext { 8954 ValueInfo VI; 8955 unsigned GVId; 8956 LocTy Loc; 8957 }; 8958 std::vector<ValueContext> VContexts; 8959 // parse each ref edge 8960 do { 8961 ValueContext VC; 8962 VC.Loc = Lex.getLoc(); 8963 if (parseGVReference(VC.VI, VC.GVId)) 8964 return true; 8965 VContexts.push_back(VC); 8966 } while (EatIfPresent(lltok::comma)); 8967 8968 // Sort value contexts so that ones with writeonly 8969 // and readonly ValueInfo are at the end of VContexts vector. 8970 // See FunctionSummary::specialRefCounts() 8971 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) { 8972 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier(); 8973 }); 8974 8975 IdToIndexMapType IdToIndexMap; 8976 for (auto &VC : VContexts) { 8977 // Keep track of the Refs array index needing a forward reference. 8978 // We will save the location of the ValueInfo needing an update, but 8979 // can only do so once the std::vector is finalized. 8980 if (VC.VI.getRef() == FwdVIRef) 8981 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc)); 8982 Refs.push_back(VC.VI); 8983 } 8984 8985 // Now that the Refs vector is finalized, it is safe to save the locations 8986 // of any forward GV references that need updating later. 8987 for (auto I : IdToIndexMap) { 8988 auto &Infos = ForwardRefValueInfos[I.first]; 8989 for (auto P : I.second) { 8990 assert(Refs[P.first].getRef() == FwdVIRef && 8991 "Forward referenced ValueInfo expected to be empty"); 8992 Infos.emplace_back(&Refs[P.first], P.second); 8993 } 8994 } 8995 8996 if (parseToken(lltok::rparen, "expected ')' in refs")) 8997 return true; 8998 8999 return false; 9000 } 9001 9002 /// OptionalTypeIdInfo 9003 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]? 9004 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]? 9005 /// [',' TypeCheckedLoadConstVCalls]? ')' 9006 bool LLParser::parseOptionalTypeIdInfo( 9007 FunctionSummary::TypeIdInfo &TypeIdInfo) { 9008 assert(Lex.getKind() == lltok::kw_typeIdInfo); 9009 Lex.Lex(); 9010 9011 if (parseToken(lltok::colon, "expected ':' here") || 9012 parseToken(lltok::lparen, "expected '(' in typeIdInfo")) 9013 return true; 9014 9015 do { 9016 switch (Lex.getKind()) { 9017 case lltok::kw_typeTests: 9018 if (parseTypeTests(TypeIdInfo.TypeTests)) 9019 return true; 9020 break; 9021 case lltok::kw_typeTestAssumeVCalls: 9022 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls, 9023 TypeIdInfo.TypeTestAssumeVCalls)) 9024 return true; 9025 break; 9026 case lltok::kw_typeCheckedLoadVCalls: 9027 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls, 9028 TypeIdInfo.TypeCheckedLoadVCalls)) 9029 return true; 9030 break; 9031 case lltok::kw_typeTestAssumeConstVCalls: 9032 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls, 9033 TypeIdInfo.TypeTestAssumeConstVCalls)) 9034 return true; 9035 break; 9036 case lltok::kw_typeCheckedLoadConstVCalls: 9037 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls, 9038 TypeIdInfo.TypeCheckedLoadConstVCalls)) 9039 return true; 9040 break; 9041 default: 9042 return error(Lex.getLoc(), "invalid typeIdInfo list type"); 9043 } 9044 } while (EatIfPresent(lltok::comma)); 9045 9046 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo")) 9047 return true; 9048 9049 return false; 9050 } 9051 9052 /// TypeTests 9053 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64) 9054 /// [',' (SummaryID | UInt64)]* ')' 9055 bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) { 9056 assert(Lex.getKind() == lltok::kw_typeTests); 9057 Lex.Lex(); 9058 9059 if (parseToken(lltok::colon, "expected ':' here") || 9060 parseToken(lltok::lparen, "expected '(' in typeIdInfo")) 9061 return true; 9062 9063 IdToIndexMapType IdToIndexMap; 9064 do { 9065 GlobalValue::GUID GUID = 0; 9066 if (Lex.getKind() == lltok::SummaryID) { 9067 unsigned ID = Lex.getUIntVal(); 9068 LocTy Loc = Lex.getLoc(); 9069 // Keep track of the TypeTests array index needing a forward reference. 9070 // We will save the location of the GUID needing an update, but 9071 // can only do so once the std::vector is finalized. 9072 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc)); 9073 Lex.Lex(); 9074 } else if (parseUInt64(GUID)) 9075 return true; 9076 TypeTests.push_back(GUID); 9077 } while (EatIfPresent(lltok::comma)); 9078 9079 // Now that the TypeTests vector is finalized, it is safe to save the 9080 // locations of any forward GV references that need updating later. 9081 for (auto I : IdToIndexMap) { 9082 auto &Ids = ForwardRefTypeIds[I.first]; 9083 for (auto P : I.second) { 9084 assert(TypeTests[P.first] == 0 && 9085 "Forward referenced type id GUID expected to be 0"); 9086 Ids.emplace_back(&TypeTests[P.first], P.second); 9087 } 9088 } 9089 9090 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo")) 9091 return true; 9092 9093 return false; 9094 } 9095 9096 /// VFuncIdList 9097 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')' 9098 bool LLParser::parseVFuncIdList( 9099 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) { 9100 assert(Lex.getKind() == Kind); 9101 Lex.Lex(); 9102 9103 if (parseToken(lltok::colon, "expected ':' here") || 9104 parseToken(lltok::lparen, "expected '(' here")) 9105 return true; 9106 9107 IdToIndexMapType IdToIndexMap; 9108 do { 9109 FunctionSummary::VFuncId VFuncId; 9110 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size())) 9111 return true; 9112 VFuncIdList.push_back(VFuncId); 9113 } while (EatIfPresent(lltok::comma)); 9114 9115 if (parseToken(lltok::rparen, "expected ')' here")) 9116 return true; 9117 9118 // Now that the VFuncIdList vector is finalized, it is safe to save the 9119 // locations of any forward GV references that need updating later. 9120 for (auto I : IdToIndexMap) { 9121 auto &Ids = ForwardRefTypeIds[I.first]; 9122 for (auto P : I.second) { 9123 assert(VFuncIdList[P.first].GUID == 0 && 9124 "Forward referenced type id GUID expected to be 0"); 9125 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second); 9126 } 9127 } 9128 9129 return false; 9130 } 9131 9132 /// ConstVCallList 9133 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')' 9134 bool LLParser::parseConstVCallList( 9135 lltok::Kind Kind, 9136 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) { 9137 assert(Lex.getKind() == Kind); 9138 Lex.Lex(); 9139 9140 if (parseToken(lltok::colon, "expected ':' here") || 9141 parseToken(lltok::lparen, "expected '(' here")) 9142 return true; 9143 9144 IdToIndexMapType IdToIndexMap; 9145 do { 9146 FunctionSummary::ConstVCall ConstVCall; 9147 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size())) 9148 return true; 9149 ConstVCallList.push_back(ConstVCall); 9150 } while (EatIfPresent(lltok::comma)); 9151 9152 if (parseToken(lltok::rparen, "expected ')' here")) 9153 return true; 9154 9155 // Now that the ConstVCallList vector is finalized, it is safe to save the 9156 // locations of any forward GV references that need updating later. 9157 for (auto I : IdToIndexMap) { 9158 auto &Ids = ForwardRefTypeIds[I.first]; 9159 for (auto P : I.second) { 9160 assert(ConstVCallList[P.first].VFunc.GUID == 0 && 9161 "Forward referenced type id GUID expected to be 0"); 9162 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second); 9163 } 9164 } 9165 9166 return false; 9167 } 9168 9169 /// ConstVCall 9170 /// ::= '(' VFuncId ',' Args ')' 9171 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall, 9172 IdToIndexMapType &IdToIndexMap, unsigned Index) { 9173 if (parseToken(lltok::lparen, "expected '(' here") || 9174 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index)) 9175 return true; 9176 9177 if (EatIfPresent(lltok::comma)) 9178 if (parseArgs(ConstVCall.Args)) 9179 return true; 9180 9181 if (parseToken(lltok::rparen, "expected ')' here")) 9182 return true; 9183 9184 return false; 9185 } 9186 9187 /// VFuncId 9188 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ',' 9189 /// 'offset' ':' UInt64 ')' 9190 bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId, 9191 IdToIndexMapType &IdToIndexMap, unsigned Index) { 9192 assert(Lex.getKind() == lltok::kw_vFuncId); 9193 Lex.Lex(); 9194 9195 if (parseToken(lltok::colon, "expected ':' here") || 9196 parseToken(lltok::lparen, "expected '(' here")) 9197 return true; 9198 9199 if (Lex.getKind() == lltok::SummaryID) { 9200 VFuncId.GUID = 0; 9201 unsigned ID = Lex.getUIntVal(); 9202 LocTy Loc = Lex.getLoc(); 9203 // Keep track of the array index needing a forward reference. 9204 // We will save the location of the GUID needing an update, but 9205 // can only do so once the caller's std::vector is finalized. 9206 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc)); 9207 Lex.Lex(); 9208 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") || 9209 parseToken(lltok::colon, "expected ':' here") || 9210 parseUInt64(VFuncId.GUID)) 9211 return true; 9212 9213 if (parseToken(lltok::comma, "expected ',' here") || 9214 parseToken(lltok::kw_offset, "expected 'offset' here") || 9215 parseToken(lltok::colon, "expected ':' here") || 9216 parseUInt64(VFuncId.Offset) || 9217 parseToken(lltok::rparen, "expected ')' here")) 9218 return true; 9219 9220 return false; 9221 } 9222 9223 /// GVFlags 9224 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ',' 9225 /// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ',' 9226 /// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ',' 9227 /// 'canAutoHide' ':' Flag ',' ')' 9228 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) { 9229 assert(Lex.getKind() == lltok::kw_flags); 9230 Lex.Lex(); 9231 9232 if (parseToken(lltok::colon, "expected ':' here") || 9233 parseToken(lltok::lparen, "expected '(' here")) 9234 return true; 9235 9236 do { 9237 unsigned Flag = 0; 9238 switch (Lex.getKind()) { 9239 case lltok::kw_linkage: 9240 Lex.Lex(); 9241 if (parseToken(lltok::colon, "expected ':'")) 9242 return true; 9243 bool HasLinkage; 9244 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage); 9245 assert(HasLinkage && "Linkage not optional in summary entry"); 9246 Lex.Lex(); 9247 break; 9248 case lltok::kw_visibility: 9249 Lex.Lex(); 9250 if (parseToken(lltok::colon, "expected ':'")) 9251 return true; 9252 parseOptionalVisibility(Flag); 9253 GVFlags.Visibility = Flag; 9254 break; 9255 case lltok::kw_notEligibleToImport: 9256 Lex.Lex(); 9257 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9258 return true; 9259 GVFlags.NotEligibleToImport = Flag; 9260 break; 9261 case lltok::kw_live: 9262 Lex.Lex(); 9263 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9264 return true; 9265 GVFlags.Live = Flag; 9266 break; 9267 case lltok::kw_dsoLocal: 9268 Lex.Lex(); 9269 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9270 return true; 9271 GVFlags.DSOLocal = Flag; 9272 break; 9273 case lltok::kw_canAutoHide: 9274 Lex.Lex(); 9275 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9276 return true; 9277 GVFlags.CanAutoHide = Flag; 9278 break; 9279 default: 9280 return error(Lex.getLoc(), "expected gv flag type"); 9281 } 9282 } while (EatIfPresent(lltok::comma)); 9283 9284 if (parseToken(lltok::rparen, "expected ')' here")) 9285 return true; 9286 9287 return false; 9288 } 9289 9290 /// GVarFlags 9291 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag 9292 /// ',' 'writeonly' ':' Flag 9293 /// ',' 'constant' ':' Flag ')' 9294 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) { 9295 assert(Lex.getKind() == lltok::kw_varFlags); 9296 Lex.Lex(); 9297 9298 if (parseToken(lltok::colon, "expected ':' here") || 9299 parseToken(lltok::lparen, "expected '(' here")) 9300 return true; 9301 9302 auto ParseRest = [this](unsigned int &Val) { 9303 Lex.Lex(); 9304 if (parseToken(lltok::colon, "expected ':'")) 9305 return true; 9306 return parseFlag(Val); 9307 }; 9308 9309 do { 9310 unsigned Flag = 0; 9311 switch (Lex.getKind()) { 9312 case lltok::kw_readonly: 9313 if (ParseRest(Flag)) 9314 return true; 9315 GVarFlags.MaybeReadOnly = Flag; 9316 break; 9317 case lltok::kw_writeonly: 9318 if (ParseRest(Flag)) 9319 return true; 9320 GVarFlags.MaybeWriteOnly = Flag; 9321 break; 9322 case lltok::kw_constant: 9323 if (ParseRest(Flag)) 9324 return true; 9325 GVarFlags.Constant = Flag; 9326 break; 9327 case lltok::kw_vcall_visibility: 9328 if (ParseRest(Flag)) 9329 return true; 9330 GVarFlags.VCallVisibility = Flag; 9331 break; 9332 default: 9333 return error(Lex.getLoc(), "expected gvar flag type"); 9334 } 9335 } while (EatIfPresent(lltok::comma)); 9336 return parseToken(lltok::rparen, "expected ')' here"); 9337 } 9338 9339 /// ModuleReference 9340 /// ::= 'module' ':' UInt 9341 bool LLParser::parseModuleReference(StringRef &ModulePath) { 9342 // parse module id. 9343 if (parseToken(lltok::kw_module, "expected 'module' here") || 9344 parseToken(lltok::colon, "expected ':' here") || 9345 parseToken(lltok::SummaryID, "expected module ID")) 9346 return true; 9347 9348 unsigned ModuleID = Lex.getUIntVal(); 9349 auto I = ModuleIdMap.find(ModuleID); 9350 // We should have already parsed all module IDs 9351 assert(I != ModuleIdMap.end()); 9352 ModulePath = I->second; 9353 return false; 9354 } 9355 9356 /// GVReference 9357 /// ::= SummaryID 9358 bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) { 9359 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly); 9360 if (!ReadOnly) 9361 WriteOnly = EatIfPresent(lltok::kw_writeonly); 9362 if (parseToken(lltok::SummaryID, "expected GV ID")) 9363 return true; 9364 9365 GVId = Lex.getUIntVal(); 9366 // Check if we already have a VI for this GV 9367 if (GVId < NumberedValueInfos.size()) { 9368 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef); 9369 VI = NumberedValueInfos[GVId]; 9370 } else 9371 // We will create a forward reference to the stored location. 9372 VI = ValueInfo(false, FwdVIRef); 9373 9374 if (ReadOnly) 9375 VI.setReadOnly(); 9376 if (WriteOnly) 9377 VI.setWriteOnly(); 9378 return false; 9379 } 9380