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