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/Operator.h" 41 #include "llvm/IR/Value.h" 42 #include "llvm/IR/ValueSymbolTable.h" 43 #include "llvm/Support/Casting.h" 44 #include "llvm/Support/ErrorHandling.h" 45 #include "llvm/Support/MathExtras.h" 46 #include "llvm/Support/SaveAndRestore.h" 47 #include "llvm/Support/raw_ostream.h" 48 #include <algorithm> 49 #include <cassert> 50 #include <cstring> 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() != Ty->getPointerTo(AddrSpace)) 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 '") + Lex.getStrVal() + 4171 "'"); 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 !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 ForwardRefVals.erase(FRVI); 5643 } else if ((Fn = M->getFunction(FunctionName))) { 5644 // Reject redefinitions. 5645 return error(NameLoc, 5646 "invalid redefinition of function '" + FunctionName + "'"); 5647 } else if (M->getNamedValue(FunctionName)) { 5648 return error(NameLoc, "redefinition of function '@" + FunctionName + "'"); 5649 } 5650 5651 } else { 5652 // If this is a definition of a forward referenced function, make sure the 5653 // types agree. 5654 auto I = ForwardRefValIDs.find(NumberedVals.size()); 5655 if (I != ForwardRefValIDs.end()) { 5656 FwdFn = I->second.first; 5657 if (FwdFn->getType() != PFT) 5658 return error(NameLoc, "type of definition and forward reference of '@" + 5659 Twine(NumberedVals.size()) + 5660 "' disagree: " 5661 "expected '" + 5662 getTypeString(PFT) + "' but was '" + 5663 getTypeString(FwdFn->getType()) + "'"); 5664 ForwardRefValIDs.erase(I); 5665 } 5666 } 5667 5668 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace, 5669 FunctionName, M); 5670 5671 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS"); 5672 5673 if (FunctionName.empty()) 5674 NumberedVals.push_back(Fn); 5675 5676 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage); 5677 maybeSetDSOLocal(DSOLocal, *Fn); 5678 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility); 5679 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 5680 Fn->setCallingConv(CC); 5681 Fn->setAttributes(PAL); 5682 Fn->setUnnamedAddr(UnnamedAddr); 5683 Fn->setAlignment(MaybeAlign(Alignment)); 5684 Fn->setSection(Section); 5685 Fn->setPartition(Partition); 5686 Fn->setComdat(C); 5687 Fn->setPersonalityFn(PersonalityFn); 5688 if (!GC.empty()) Fn->setGC(GC); 5689 Fn->setPrefixData(Prefix); 5690 Fn->setPrologueData(Prologue); 5691 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps; 5692 5693 // Add all of the arguments we parsed to the function. 5694 Function::arg_iterator ArgIt = Fn->arg_begin(); 5695 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) { 5696 // If the argument has a name, insert it into the argument symbol table. 5697 if (ArgList[i].Name.empty()) continue; 5698 5699 // Set the name, if it conflicted, it will be auto-renamed. 5700 ArgIt->setName(ArgList[i].Name); 5701 5702 if (ArgIt->getName() != ArgList[i].Name) 5703 return error(ArgList[i].Loc, 5704 "redefinition of argument '%" + ArgList[i].Name + "'"); 5705 } 5706 5707 if (FwdFn) { 5708 FwdFn->replaceAllUsesWith(Fn); 5709 FwdFn->eraseFromParent(); 5710 } 5711 5712 if (IsDefine) 5713 return false; 5714 5715 // Check the declaration has no block address forward references. 5716 ValID ID; 5717 if (FunctionName.empty()) { 5718 ID.Kind = ValID::t_GlobalID; 5719 ID.UIntVal = NumberedVals.size() - 1; 5720 } else { 5721 ID.Kind = ValID::t_GlobalName; 5722 ID.StrVal = FunctionName; 5723 } 5724 auto Blocks = ForwardRefBlockAddresses.find(ID); 5725 if (Blocks != ForwardRefBlockAddresses.end()) 5726 return error(Blocks->first.Loc, 5727 "cannot take blockaddress inside a declaration"); 5728 return false; 5729 } 5730 5731 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() { 5732 ValID ID; 5733 if (FunctionNumber == -1) { 5734 ID.Kind = ValID::t_GlobalName; 5735 ID.StrVal = std::string(F.getName()); 5736 } else { 5737 ID.Kind = ValID::t_GlobalID; 5738 ID.UIntVal = FunctionNumber; 5739 } 5740 5741 auto Blocks = P.ForwardRefBlockAddresses.find(ID); 5742 if (Blocks == P.ForwardRefBlockAddresses.end()) 5743 return false; 5744 5745 for (const auto &I : Blocks->second) { 5746 const ValID &BBID = I.first; 5747 GlobalValue *GV = I.second; 5748 5749 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) && 5750 "Expected local id or name"); 5751 BasicBlock *BB; 5752 if (BBID.Kind == ValID::t_LocalName) 5753 BB = getBB(BBID.StrVal, BBID.Loc); 5754 else 5755 BB = getBB(BBID.UIntVal, BBID.Loc); 5756 if (!BB) 5757 return P.error(BBID.Loc, "referenced value is not a basic block"); 5758 5759 Value *ResolvedVal = BlockAddress::get(&F, BB); 5760 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(), 5761 ResolvedVal); 5762 if (!ResolvedVal) 5763 return true; 5764 GV->replaceAllUsesWith(ResolvedVal); 5765 GV->eraseFromParent(); 5766 } 5767 5768 P.ForwardRefBlockAddresses.erase(Blocks); 5769 return false; 5770 } 5771 5772 /// parseFunctionBody 5773 /// ::= '{' BasicBlock+ UseListOrderDirective* '}' 5774 bool LLParser::parseFunctionBody(Function &Fn) { 5775 if (Lex.getKind() != lltok::lbrace) 5776 return tokError("expected '{' in function body"); 5777 Lex.Lex(); // eat the {. 5778 5779 int FunctionNumber = -1; 5780 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1; 5781 5782 PerFunctionState PFS(*this, Fn, FunctionNumber); 5783 5784 // Resolve block addresses and allow basic blocks to be forward-declared 5785 // within this function. 5786 if (PFS.resolveForwardRefBlockAddresses()) 5787 return true; 5788 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS); 5789 5790 // We need at least one basic block. 5791 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder) 5792 return tokError("function body requires at least one basic block"); 5793 5794 while (Lex.getKind() != lltok::rbrace && 5795 Lex.getKind() != lltok::kw_uselistorder) 5796 if (parseBasicBlock(PFS)) 5797 return true; 5798 5799 while (Lex.getKind() != lltok::rbrace) 5800 if (parseUseListOrder(&PFS)) 5801 return true; 5802 5803 // Eat the }. 5804 Lex.Lex(); 5805 5806 // Verify function is ok. 5807 return PFS.finishFunction(); 5808 } 5809 5810 /// parseBasicBlock 5811 /// ::= (LabelStr|LabelID)? Instruction* 5812 bool LLParser::parseBasicBlock(PerFunctionState &PFS) { 5813 // If this basic block starts out with a name, remember it. 5814 std::string Name; 5815 int NameID = -1; 5816 LocTy NameLoc = Lex.getLoc(); 5817 if (Lex.getKind() == lltok::LabelStr) { 5818 Name = Lex.getStrVal(); 5819 Lex.Lex(); 5820 } else if (Lex.getKind() == lltok::LabelID) { 5821 NameID = Lex.getUIntVal(); 5822 Lex.Lex(); 5823 } 5824 5825 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc); 5826 if (!BB) 5827 return true; 5828 5829 std::string NameStr; 5830 5831 // parse the instructions in this block until we get a terminator. 5832 Instruction *Inst; 5833 do { 5834 // This instruction may have three possibilities for a name: a) none 5835 // specified, b) name specified "%foo =", c) number specified: "%4 =". 5836 LocTy NameLoc = Lex.getLoc(); 5837 int NameID = -1; 5838 NameStr = ""; 5839 5840 if (Lex.getKind() == lltok::LocalVarID) { 5841 NameID = Lex.getUIntVal(); 5842 Lex.Lex(); 5843 if (parseToken(lltok::equal, "expected '=' after instruction id")) 5844 return true; 5845 } else if (Lex.getKind() == lltok::LocalVar) { 5846 NameStr = Lex.getStrVal(); 5847 Lex.Lex(); 5848 if (parseToken(lltok::equal, "expected '=' after instruction name")) 5849 return true; 5850 } 5851 5852 switch (parseInstruction(Inst, BB, PFS)) { 5853 default: 5854 llvm_unreachable("Unknown parseInstruction result!"); 5855 case InstError: return true; 5856 case InstNormal: 5857 BB->getInstList().push_back(Inst); 5858 5859 // With a normal result, we check to see if the instruction is followed by 5860 // a comma and metadata. 5861 if (EatIfPresent(lltok::comma)) 5862 if (parseInstructionMetadata(*Inst)) 5863 return true; 5864 break; 5865 case InstExtraComma: 5866 BB->getInstList().push_back(Inst); 5867 5868 // If the instruction parser ate an extra comma at the end of it, it 5869 // *must* be followed by metadata. 5870 if (parseInstructionMetadata(*Inst)) 5871 return true; 5872 break; 5873 } 5874 5875 // Set the name on the instruction. 5876 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst)) 5877 return true; 5878 } while (!Inst->isTerminator()); 5879 5880 return false; 5881 } 5882 5883 //===----------------------------------------------------------------------===// 5884 // Instruction Parsing. 5885 //===----------------------------------------------------------------------===// 5886 5887 /// parseInstruction - parse one of the many different instructions. 5888 /// 5889 int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB, 5890 PerFunctionState &PFS) { 5891 lltok::Kind Token = Lex.getKind(); 5892 if (Token == lltok::Eof) 5893 return tokError("found end of file when expecting more instructions"); 5894 LocTy Loc = Lex.getLoc(); 5895 unsigned KeywordVal = Lex.getUIntVal(); 5896 Lex.Lex(); // Eat the keyword. 5897 5898 switch (Token) { 5899 default: 5900 return error(Loc, "expected instruction opcode"); 5901 // Terminator Instructions. 5902 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false; 5903 case lltok::kw_ret: 5904 return parseRet(Inst, BB, PFS); 5905 case lltok::kw_br: 5906 return parseBr(Inst, PFS); 5907 case lltok::kw_switch: 5908 return parseSwitch(Inst, PFS); 5909 case lltok::kw_indirectbr: 5910 return parseIndirectBr(Inst, PFS); 5911 case lltok::kw_invoke: 5912 return parseInvoke(Inst, PFS); 5913 case lltok::kw_resume: 5914 return parseResume(Inst, PFS); 5915 case lltok::kw_cleanupret: 5916 return parseCleanupRet(Inst, PFS); 5917 case lltok::kw_catchret: 5918 return parseCatchRet(Inst, PFS); 5919 case lltok::kw_catchswitch: 5920 return parseCatchSwitch(Inst, PFS); 5921 case lltok::kw_catchpad: 5922 return parseCatchPad(Inst, PFS); 5923 case lltok::kw_cleanuppad: 5924 return parseCleanupPad(Inst, PFS); 5925 case lltok::kw_callbr: 5926 return parseCallBr(Inst, PFS); 5927 // Unary Operators. 5928 case lltok::kw_fneg: { 5929 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5930 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true); 5931 if (Res != 0) 5932 return Res; 5933 if (FMF.any()) 5934 Inst->setFastMathFlags(FMF); 5935 return false; 5936 } 5937 // Binary Operators. 5938 case lltok::kw_add: 5939 case lltok::kw_sub: 5940 case lltok::kw_mul: 5941 case lltok::kw_shl: { 5942 bool NUW = EatIfPresent(lltok::kw_nuw); 5943 bool NSW = EatIfPresent(lltok::kw_nsw); 5944 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw); 5945 5946 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false)) 5947 return true; 5948 5949 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true); 5950 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true); 5951 return false; 5952 } 5953 case lltok::kw_fadd: 5954 case lltok::kw_fsub: 5955 case lltok::kw_fmul: 5956 case lltok::kw_fdiv: 5957 case lltok::kw_frem: { 5958 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5959 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true); 5960 if (Res != 0) 5961 return Res; 5962 if (FMF.any()) 5963 Inst->setFastMathFlags(FMF); 5964 return 0; 5965 } 5966 5967 case lltok::kw_sdiv: 5968 case lltok::kw_udiv: 5969 case lltok::kw_lshr: 5970 case lltok::kw_ashr: { 5971 bool Exact = EatIfPresent(lltok::kw_exact); 5972 5973 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false)) 5974 return true; 5975 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true); 5976 return false; 5977 } 5978 5979 case lltok::kw_urem: 5980 case lltok::kw_srem: 5981 return parseArithmetic(Inst, PFS, KeywordVal, 5982 /*IsFP*/ false); 5983 case lltok::kw_and: 5984 case lltok::kw_or: 5985 case lltok::kw_xor: 5986 return parseLogical(Inst, PFS, KeywordVal); 5987 case lltok::kw_icmp: 5988 return parseCompare(Inst, PFS, KeywordVal); 5989 case lltok::kw_fcmp: { 5990 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5991 int Res = parseCompare(Inst, PFS, KeywordVal); 5992 if (Res != 0) 5993 return Res; 5994 if (FMF.any()) 5995 Inst->setFastMathFlags(FMF); 5996 return 0; 5997 } 5998 5999 // Casts. 6000 case lltok::kw_trunc: 6001 case lltok::kw_zext: 6002 case lltok::kw_sext: 6003 case lltok::kw_fptrunc: 6004 case lltok::kw_fpext: 6005 case lltok::kw_bitcast: 6006 case lltok::kw_addrspacecast: 6007 case lltok::kw_uitofp: 6008 case lltok::kw_sitofp: 6009 case lltok::kw_fptoui: 6010 case lltok::kw_fptosi: 6011 case lltok::kw_inttoptr: 6012 case lltok::kw_ptrtoint: 6013 return parseCast(Inst, PFS, KeywordVal); 6014 // Other. 6015 case lltok::kw_select: { 6016 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6017 int Res = parseSelect(Inst, PFS); 6018 if (Res != 0) 6019 return Res; 6020 if (FMF.any()) { 6021 if (!isa<FPMathOperator>(Inst)) 6022 return error(Loc, "fast-math-flags specified for select without " 6023 "floating-point scalar or vector return type"); 6024 Inst->setFastMathFlags(FMF); 6025 } 6026 return 0; 6027 } 6028 case lltok::kw_va_arg: 6029 return parseVAArg(Inst, PFS); 6030 case lltok::kw_extractelement: 6031 return parseExtractElement(Inst, PFS); 6032 case lltok::kw_insertelement: 6033 return parseInsertElement(Inst, PFS); 6034 case lltok::kw_shufflevector: 6035 return parseShuffleVector(Inst, PFS); 6036 case lltok::kw_phi: { 6037 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6038 int Res = parsePHI(Inst, PFS); 6039 if (Res != 0) 6040 return Res; 6041 if (FMF.any()) { 6042 if (!isa<FPMathOperator>(Inst)) 6043 return error(Loc, "fast-math-flags specified for phi without " 6044 "floating-point scalar or vector return type"); 6045 Inst->setFastMathFlags(FMF); 6046 } 6047 return 0; 6048 } 6049 case lltok::kw_landingpad: 6050 return parseLandingPad(Inst, PFS); 6051 case lltok::kw_freeze: 6052 return parseFreeze(Inst, PFS); 6053 // Call. 6054 case lltok::kw_call: 6055 return parseCall(Inst, PFS, CallInst::TCK_None); 6056 case lltok::kw_tail: 6057 return parseCall(Inst, PFS, CallInst::TCK_Tail); 6058 case lltok::kw_musttail: 6059 return parseCall(Inst, PFS, CallInst::TCK_MustTail); 6060 case lltok::kw_notail: 6061 return parseCall(Inst, PFS, CallInst::TCK_NoTail); 6062 // Memory. 6063 case lltok::kw_alloca: 6064 return parseAlloc(Inst, PFS); 6065 case lltok::kw_load: 6066 return parseLoad(Inst, PFS); 6067 case lltok::kw_store: 6068 return parseStore(Inst, PFS); 6069 case lltok::kw_cmpxchg: 6070 return parseCmpXchg(Inst, PFS); 6071 case lltok::kw_atomicrmw: 6072 return parseAtomicRMW(Inst, PFS); 6073 case lltok::kw_fence: 6074 return parseFence(Inst, PFS); 6075 case lltok::kw_getelementptr: 6076 return parseGetElementPtr(Inst, PFS); 6077 case lltok::kw_extractvalue: 6078 return parseExtractValue(Inst, PFS); 6079 case lltok::kw_insertvalue: 6080 return parseInsertValue(Inst, PFS); 6081 } 6082 } 6083 6084 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind. 6085 bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) { 6086 if (Opc == Instruction::FCmp) { 6087 switch (Lex.getKind()) { 6088 default: 6089 return tokError("expected fcmp predicate (e.g. 'oeq')"); 6090 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break; 6091 case lltok::kw_one: P = CmpInst::FCMP_ONE; break; 6092 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break; 6093 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break; 6094 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break; 6095 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break; 6096 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break; 6097 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break; 6098 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break; 6099 case lltok::kw_une: P = CmpInst::FCMP_UNE; break; 6100 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break; 6101 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break; 6102 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break; 6103 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break; 6104 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break; 6105 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break; 6106 } 6107 } else { 6108 switch (Lex.getKind()) { 6109 default: 6110 return tokError("expected icmp predicate (e.g. 'eq')"); 6111 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break; 6112 case lltok::kw_ne: P = CmpInst::ICMP_NE; break; 6113 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break; 6114 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break; 6115 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break; 6116 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break; 6117 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break; 6118 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break; 6119 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break; 6120 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break; 6121 } 6122 } 6123 Lex.Lex(); 6124 return false; 6125 } 6126 6127 //===----------------------------------------------------------------------===// 6128 // Terminator Instructions. 6129 //===----------------------------------------------------------------------===// 6130 6131 /// parseRet - parse a return instruction. 6132 /// ::= 'ret' void (',' !dbg, !1)* 6133 /// ::= 'ret' TypeAndValue (',' !dbg, !1)* 6134 bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB, 6135 PerFunctionState &PFS) { 6136 SMLoc TypeLoc = Lex.getLoc(); 6137 Type *Ty = nullptr; 6138 if (parseType(Ty, true /*void allowed*/)) 6139 return true; 6140 6141 Type *ResType = PFS.getFunction().getReturnType(); 6142 6143 if (Ty->isVoidTy()) { 6144 if (!ResType->isVoidTy()) 6145 return error(TypeLoc, "value doesn't match function result type '" + 6146 getTypeString(ResType) + "'"); 6147 6148 Inst = ReturnInst::Create(Context); 6149 return false; 6150 } 6151 6152 Value *RV; 6153 if (parseValue(Ty, RV, PFS)) 6154 return true; 6155 6156 if (ResType != RV->getType()) 6157 return error(TypeLoc, "value doesn't match function result type '" + 6158 getTypeString(ResType) + "'"); 6159 6160 Inst = ReturnInst::Create(Context, RV); 6161 return false; 6162 } 6163 6164 /// parseBr 6165 /// ::= 'br' TypeAndValue 6166 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6167 bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) { 6168 LocTy Loc, Loc2; 6169 Value *Op0; 6170 BasicBlock *Op1, *Op2; 6171 if (parseTypeAndValue(Op0, Loc, PFS)) 6172 return true; 6173 6174 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) { 6175 Inst = BranchInst::Create(BB); 6176 return false; 6177 } 6178 6179 if (Op0->getType() != Type::getInt1Ty(Context)) 6180 return error(Loc, "branch condition must have 'i1' type"); 6181 6182 if (parseToken(lltok::comma, "expected ',' after branch condition") || 6183 parseTypeAndBasicBlock(Op1, Loc, PFS) || 6184 parseToken(lltok::comma, "expected ',' after true destination") || 6185 parseTypeAndBasicBlock(Op2, Loc2, PFS)) 6186 return true; 6187 6188 Inst = BranchInst::Create(Op1, Op2, Op0); 6189 return false; 6190 } 6191 6192 /// parseSwitch 6193 /// Instruction 6194 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']' 6195 /// JumpTable 6196 /// ::= (TypeAndValue ',' TypeAndValue)* 6197 bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) { 6198 LocTy CondLoc, BBLoc; 6199 Value *Cond; 6200 BasicBlock *DefaultBB; 6201 if (parseTypeAndValue(Cond, CondLoc, PFS) || 6202 parseToken(lltok::comma, "expected ',' after switch condition") || 6203 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) || 6204 parseToken(lltok::lsquare, "expected '[' with switch table")) 6205 return true; 6206 6207 if (!Cond->getType()->isIntegerTy()) 6208 return error(CondLoc, "switch condition must have integer type"); 6209 6210 // parse the jump table pairs. 6211 SmallPtrSet<Value*, 32> SeenCases; 6212 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table; 6213 while (Lex.getKind() != lltok::rsquare) { 6214 Value *Constant; 6215 BasicBlock *DestBB; 6216 6217 if (parseTypeAndValue(Constant, CondLoc, PFS) || 6218 parseToken(lltok::comma, "expected ',' after case value") || 6219 parseTypeAndBasicBlock(DestBB, PFS)) 6220 return true; 6221 6222 if (!SeenCases.insert(Constant).second) 6223 return error(CondLoc, "duplicate case value in switch"); 6224 if (!isa<ConstantInt>(Constant)) 6225 return error(CondLoc, "case value is not a constant integer"); 6226 6227 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB)); 6228 } 6229 6230 Lex.Lex(); // Eat the ']'. 6231 6232 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size()); 6233 for (unsigned i = 0, e = Table.size(); i != e; ++i) 6234 SI->addCase(Table[i].first, Table[i].second); 6235 Inst = SI; 6236 return false; 6237 } 6238 6239 /// parseIndirectBr 6240 /// Instruction 6241 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']' 6242 bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) { 6243 LocTy AddrLoc; 6244 Value *Address; 6245 if (parseTypeAndValue(Address, AddrLoc, PFS) || 6246 parseToken(lltok::comma, "expected ',' after indirectbr address") || 6247 parseToken(lltok::lsquare, "expected '[' with indirectbr")) 6248 return true; 6249 6250 if (!Address->getType()->isPointerTy()) 6251 return error(AddrLoc, "indirectbr address must have pointer type"); 6252 6253 // parse the destination list. 6254 SmallVector<BasicBlock*, 16> DestList; 6255 6256 if (Lex.getKind() != lltok::rsquare) { 6257 BasicBlock *DestBB; 6258 if (parseTypeAndBasicBlock(DestBB, PFS)) 6259 return true; 6260 DestList.push_back(DestBB); 6261 6262 while (EatIfPresent(lltok::comma)) { 6263 if (parseTypeAndBasicBlock(DestBB, PFS)) 6264 return true; 6265 DestList.push_back(DestBB); 6266 } 6267 } 6268 6269 if (parseToken(lltok::rsquare, "expected ']' at end of block list")) 6270 return true; 6271 6272 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size()); 6273 for (unsigned i = 0, e = DestList.size(); i != e; ++i) 6274 IBI->addDestination(DestList[i]); 6275 Inst = IBI; 6276 return false; 6277 } 6278 6279 /// parseInvoke 6280 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList 6281 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue 6282 bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) { 6283 LocTy CallLoc = Lex.getLoc(); 6284 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext()); 6285 std::vector<unsigned> FwdRefAttrGrps; 6286 LocTy NoBuiltinLoc; 6287 unsigned CC; 6288 unsigned InvokeAddrSpace; 6289 Type *RetType = nullptr; 6290 LocTy RetTypeLoc; 6291 ValID CalleeID; 6292 SmallVector<ParamInfo, 16> ArgList; 6293 SmallVector<OperandBundleDef, 2> BundleList; 6294 6295 BasicBlock *NormalBB, *UnwindBB; 6296 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 6297 parseOptionalProgramAddrSpace(InvokeAddrSpace) || 6298 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 6299 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) || 6300 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 6301 NoBuiltinLoc) || 6302 parseOptionalOperandBundles(BundleList, PFS) || 6303 parseToken(lltok::kw_to, "expected 'to' in invoke") || 6304 parseTypeAndBasicBlock(NormalBB, PFS) || 6305 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") || 6306 parseTypeAndBasicBlock(UnwindBB, PFS)) 6307 return true; 6308 6309 // If RetType is a non-function pointer type, then this is the short syntax 6310 // for the call, which means that RetType is just the return type. Infer the 6311 // rest of the function argument types from the arguments that are present. 6312 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 6313 if (!Ty) { 6314 // Pull out the types of all of the arguments... 6315 std::vector<Type*> ParamTypes; 6316 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 6317 ParamTypes.push_back(ArgList[i].V->getType()); 6318 6319 if (!FunctionType::isValidReturnType(RetType)) 6320 return error(RetTypeLoc, "Invalid result type for LLVM function"); 6321 6322 Ty = FunctionType::get(RetType, ParamTypes, false); 6323 } 6324 6325 CalleeID.FTy = Ty; 6326 6327 // Look up the callee. 6328 Value *Callee; 6329 if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID, 6330 Callee, &PFS)) 6331 return true; 6332 6333 // Set up the Attribute for the function. 6334 SmallVector<Value *, 8> Args; 6335 SmallVector<AttributeSet, 8> ArgAttrs; 6336 6337 // Loop through FunctionType's arguments and ensure they are specified 6338 // correctly. Also, gather any parameter attributes. 6339 FunctionType::param_iterator I = Ty->param_begin(); 6340 FunctionType::param_iterator E = Ty->param_end(); 6341 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 6342 Type *ExpectedTy = nullptr; 6343 if (I != E) { 6344 ExpectedTy = *I++; 6345 } else if (!Ty->isVarArg()) { 6346 return error(ArgList[i].Loc, "too many arguments specified"); 6347 } 6348 6349 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 6350 return error(ArgList[i].Loc, "argument is not of expected type '" + 6351 getTypeString(ExpectedTy) + "'"); 6352 Args.push_back(ArgList[i].V); 6353 ArgAttrs.push_back(ArgList[i].Attrs); 6354 } 6355 6356 if (I != E) 6357 return error(CallLoc, "not enough parameters specified for call"); 6358 6359 if (FnAttrs.hasAlignmentAttr()) 6360 return error(CallLoc, "invoke instructions may not have an alignment"); 6361 6362 // Finish off the Attribute and check them 6363 AttributeList PAL = 6364 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 6365 AttributeSet::get(Context, RetAttrs), ArgAttrs); 6366 6367 InvokeInst *II = 6368 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList); 6369 II->setCallingConv(CC); 6370 II->setAttributes(PAL); 6371 ForwardRefAttrGroups[II] = FwdRefAttrGrps; 6372 Inst = II; 6373 return false; 6374 } 6375 6376 /// parseResume 6377 /// ::= 'resume' TypeAndValue 6378 bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) { 6379 Value *Exn; LocTy ExnLoc; 6380 if (parseTypeAndValue(Exn, ExnLoc, PFS)) 6381 return true; 6382 6383 ResumeInst *RI = ResumeInst::Create(Exn); 6384 Inst = RI; 6385 return false; 6386 } 6387 6388 bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args, 6389 PerFunctionState &PFS) { 6390 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad")) 6391 return true; 6392 6393 while (Lex.getKind() != lltok::rsquare) { 6394 // If this isn't the first argument, we need a comma. 6395 if (!Args.empty() && 6396 parseToken(lltok::comma, "expected ',' in argument list")) 6397 return true; 6398 6399 // parse the argument. 6400 LocTy ArgLoc; 6401 Type *ArgTy = nullptr; 6402 if (parseType(ArgTy, ArgLoc)) 6403 return true; 6404 6405 Value *V; 6406 if (ArgTy->isMetadataTy()) { 6407 if (parseMetadataAsValue(V, PFS)) 6408 return true; 6409 } else { 6410 if (parseValue(ArgTy, V, PFS)) 6411 return true; 6412 } 6413 Args.push_back(V); 6414 } 6415 6416 Lex.Lex(); // Lex the ']'. 6417 return false; 6418 } 6419 6420 /// parseCleanupRet 6421 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue) 6422 bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) { 6423 Value *CleanupPad = nullptr; 6424 6425 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret")) 6426 return true; 6427 6428 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS)) 6429 return true; 6430 6431 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret")) 6432 return true; 6433 6434 BasicBlock *UnwindBB = nullptr; 6435 if (Lex.getKind() == lltok::kw_to) { 6436 Lex.Lex(); 6437 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret")) 6438 return true; 6439 } else { 6440 if (parseTypeAndBasicBlock(UnwindBB, PFS)) { 6441 return true; 6442 } 6443 } 6444 6445 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB); 6446 return false; 6447 } 6448 6449 /// parseCatchRet 6450 /// ::= 'catchret' from Parent Value 'to' TypeAndValue 6451 bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) { 6452 Value *CatchPad = nullptr; 6453 6454 if (parseToken(lltok::kw_from, "expected 'from' after catchret")) 6455 return true; 6456 6457 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS)) 6458 return true; 6459 6460 BasicBlock *BB; 6461 if (parseToken(lltok::kw_to, "expected 'to' in catchret") || 6462 parseTypeAndBasicBlock(BB, PFS)) 6463 return true; 6464 6465 Inst = CatchReturnInst::Create(CatchPad, BB); 6466 return false; 6467 } 6468 6469 /// parseCatchSwitch 6470 /// ::= 'catchswitch' within Parent 6471 bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) { 6472 Value *ParentPad; 6473 6474 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch")) 6475 return true; 6476 6477 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 6478 Lex.getKind() != lltok::LocalVarID) 6479 return tokError("expected scope value for catchswitch"); 6480 6481 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS)) 6482 return true; 6483 6484 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels")) 6485 return true; 6486 6487 SmallVector<BasicBlock *, 32> Table; 6488 do { 6489 BasicBlock *DestBB; 6490 if (parseTypeAndBasicBlock(DestBB, PFS)) 6491 return true; 6492 Table.push_back(DestBB); 6493 } while (EatIfPresent(lltok::comma)); 6494 6495 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels")) 6496 return true; 6497 6498 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope")) 6499 return true; 6500 6501 BasicBlock *UnwindBB = nullptr; 6502 if (EatIfPresent(lltok::kw_to)) { 6503 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch")) 6504 return true; 6505 } else { 6506 if (parseTypeAndBasicBlock(UnwindBB, PFS)) 6507 return true; 6508 } 6509 6510 auto *CatchSwitch = 6511 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size()); 6512 for (BasicBlock *DestBB : Table) 6513 CatchSwitch->addHandler(DestBB); 6514 Inst = CatchSwitch; 6515 return false; 6516 } 6517 6518 /// parseCatchPad 6519 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue 6520 bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) { 6521 Value *CatchSwitch = nullptr; 6522 6523 if (parseToken(lltok::kw_within, "expected 'within' after catchpad")) 6524 return true; 6525 6526 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID) 6527 return tokError("expected scope value for catchpad"); 6528 6529 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS)) 6530 return true; 6531 6532 SmallVector<Value *, 8> Args; 6533 if (parseExceptionArgs(Args, PFS)) 6534 return true; 6535 6536 Inst = CatchPadInst::Create(CatchSwitch, Args); 6537 return false; 6538 } 6539 6540 /// parseCleanupPad 6541 /// ::= 'cleanuppad' within Parent ParamList 6542 bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) { 6543 Value *ParentPad = nullptr; 6544 6545 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad")) 6546 return true; 6547 6548 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 6549 Lex.getKind() != lltok::LocalVarID) 6550 return tokError("expected scope value for cleanuppad"); 6551 6552 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS)) 6553 return true; 6554 6555 SmallVector<Value *, 8> Args; 6556 if (parseExceptionArgs(Args, PFS)) 6557 return true; 6558 6559 Inst = CleanupPadInst::Create(ParentPad, Args); 6560 return false; 6561 } 6562 6563 //===----------------------------------------------------------------------===// 6564 // Unary Operators. 6565 //===----------------------------------------------------------------------===// 6566 6567 /// parseUnaryOp 6568 /// ::= UnaryOp TypeAndValue ',' Value 6569 /// 6570 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp 6571 /// operand is allowed. 6572 bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS, 6573 unsigned Opc, bool IsFP) { 6574 LocTy Loc; Value *LHS; 6575 if (parseTypeAndValue(LHS, Loc, PFS)) 6576 return true; 6577 6578 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() 6579 : LHS->getType()->isIntOrIntVectorTy(); 6580 6581 if (!Valid) 6582 return error(Loc, "invalid operand type for instruction"); 6583 6584 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS); 6585 return false; 6586 } 6587 6588 /// parseCallBr 6589 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList 6590 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue 6591 /// '[' LabelList ']' 6592 bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) { 6593 LocTy CallLoc = Lex.getLoc(); 6594 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext()); 6595 std::vector<unsigned> FwdRefAttrGrps; 6596 LocTy NoBuiltinLoc; 6597 unsigned CC; 6598 Type *RetType = nullptr; 6599 LocTy RetTypeLoc; 6600 ValID CalleeID; 6601 SmallVector<ParamInfo, 16> ArgList; 6602 SmallVector<OperandBundleDef, 2> BundleList; 6603 6604 BasicBlock *DefaultDest; 6605 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 6606 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 6607 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) || 6608 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 6609 NoBuiltinLoc) || 6610 parseOptionalOperandBundles(BundleList, PFS) || 6611 parseToken(lltok::kw_to, "expected 'to' in callbr") || 6612 parseTypeAndBasicBlock(DefaultDest, PFS) || 6613 parseToken(lltok::lsquare, "expected '[' in callbr")) 6614 return true; 6615 6616 // parse the destination list. 6617 SmallVector<BasicBlock *, 16> IndirectDests; 6618 6619 if (Lex.getKind() != lltok::rsquare) { 6620 BasicBlock *DestBB; 6621 if (parseTypeAndBasicBlock(DestBB, PFS)) 6622 return true; 6623 IndirectDests.push_back(DestBB); 6624 6625 while (EatIfPresent(lltok::comma)) { 6626 if (parseTypeAndBasicBlock(DestBB, PFS)) 6627 return true; 6628 IndirectDests.push_back(DestBB); 6629 } 6630 } 6631 6632 if (parseToken(lltok::rsquare, "expected ']' at end of block list")) 6633 return true; 6634 6635 // If RetType is a non-function pointer type, then this is the short syntax 6636 // for the call, which means that RetType is just the return type. Infer the 6637 // rest of the function argument types from the arguments that are present. 6638 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 6639 if (!Ty) { 6640 // Pull out the types of all of the arguments... 6641 std::vector<Type *> ParamTypes; 6642 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 6643 ParamTypes.push_back(ArgList[i].V->getType()); 6644 6645 if (!FunctionType::isValidReturnType(RetType)) 6646 return error(RetTypeLoc, "Invalid result type for LLVM function"); 6647 6648 Ty = FunctionType::get(RetType, ParamTypes, false); 6649 } 6650 6651 CalleeID.FTy = Ty; 6652 6653 // Look up the callee. 6654 Value *Callee; 6655 if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS)) 6656 return true; 6657 6658 // Set up the Attribute for the function. 6659 SmallVector<Value *, 8> Args; 6660 SmallVector<AttributeSet, 8> ArgAttrs; 6661 6662 // Loop through FunctionType's arguments and ensure they are specified 6663 // correctly. Also, gather any parameter attributes. 6664 FunctionType::param_iterator I = Ty->param_begin(); 6665 FunctionType::param_iterator E = Ty->param_end(); 6666 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 6667 Type *ExpectedTy = nullptr; 6668 if (I != E) { 6669 ExpectedTy = *I++; 6670 } else if (!Ty->isVarArg()) { 6671 return error(ArgList[i].Loc, "too many arguments specified"); 6672 } 6673 6674 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 6675 return error(ArgList[i].Loc, "argument is not of expected type '" + 6676 getTypeString(ExpectedTy) + "'"); 6677 Args.push_back(ArgList[i].V); 6678 ArgAttrs.push_back(ArgList[i].Attrs); 6679 } 6680 6681 if (I != E) 6682 return error(CallLoc, "not enough parameters specified for call"); 6683 6684 if (FnAttrs.hasAlignmentAttr()) 6685 return error(CallLoc, "callbr instructions may not have an alignment"); 6686 6687 // Finish off the Attribute and check them 6688 AttributeList PAL = 6689 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 6690 AttributeSet::get(Context, RetAttrs), ArgAttrs); 6691 6692 CallBrInst *CBI = 6693 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args, 6694 BundleList); 6695 CBI->setCallingConv(CC); 6696 CBI->setAttributes(PAL); 6697 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps; 6698 Inst = CBI; 6699 return false; 6700 } 6701 6702 //===----------------------------------------------------------------------===// 6703 // Binary Operators. 6704 //===----------------------------------------------------------------------===// 6705 6706 /// parseArithmetic 6707 /// ::= ArithmeticOps TypeAndValue ',' Value 6708 /// 6709 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp 6710 /// operand is allowed. 6711 bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS, 6712 unsigned Opc, bool IsFP) { 6713 LocTy Loc; Value *LHS, *RHS; 6714 if (parseTypeAndValue(LHS, Loc, PFS) || 6715 parseToken(lltok::comma, "expected ',' in arithmetic operation") || 6716 parseValue(LHS->getType(), RHS, PFS)) 6717 return true; 6718 6719 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() 6720 : LHS->getType()->isIntOrIntVectorTy(); 6721 6722 if (!Valid) 6723 return error(Loc, "invalid operand type for instruction"); 6724 6725 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 6726 return false; 6727 } 6728 6729 /// parseLogical 6730 /// ::= ArithmeticOps TypeAndValue ',' Value { 6731 bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS, 6732 unsigned Opc) { 6733 LocTy Loc; Value *LHS, *RHS; 6734 if (parseTypeAndValue(LHS, Loc, PFS) || 6735 parseToken(lltok::comma, "expected ',' in logical operation") || 6736 parseValue(LHS->getType(), RHS, PFS)) 6737 return true; 6738 6739 if (!LHS->getType()->isIntOrIntVectorTy()) 6740 return error(Loc, 6741 "instruction requires integer or integer vector operands"); 6742 6743 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 6744 return false; 6745 } 6746 6747 /// parseCompare 6748 /// ::= 'icmp' IPredicates TypeAndValue ',' Value 6749 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value 6750 bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS, 6751 unsigned Opc) { 6752 // parse the integer/fp comparison predicate. 6753 LocTy Loc; 6754 unsigned Pred; 6755 Value *LHS, *RHS; 6756 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) || 6757 parseToken(lltok::comma, "expected ',' after compare value") || 6758 parseValue(LHS->getType(), RHS, PFS)) 6759 return true; 6760 6761 if (Opc == Instruction::FCmp) { 6762 if (!LHS->getType()->isFPOrFPVectorTy()) 6763 return error(Loc, "fcmp requires floating point operands"); 6764 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS); 6765 } else { 6766 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!"); 6767 if (!LHS->getType()->isIntOrIntVectorTy() && 6768 !LHS->getType()->isPtrOrPtrVectorTy()) 6769 return error(Loc, "icmp requires integer operands"); 6770 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS); 6771 } 6772 return false; 6773 } 6774 6775 //===----------------------------------------------------------------------===// 6776 // Other Instructions. 6777 //===----------------------------------------------------------------------===// 6778 6779 /// parseCast 6780 /// ::= CastOpc TypeAndValue 'to' Type 6781 bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS, 6782 unsigned Opc) { 6783 LocTy Loc; 6784 Value *Op; 6785 Type *DestTy = nullptr; 6786 if (parseTypeAndValue(Op, Loc, PFS) || 6787 parseToken(lltok::kw_to, "expected 'to' after cast value") || 6788 parseType(DestTy)) 6789 return true; 6790 6791 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) { 6792 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy); 6793 return error(Loc, "invalid cast opcode for cast from '" + 6794 getTypeString(Op->getType()) + "' to '" + 6795 getTypeString(DestTy) + "'"); 6796 } 6797 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy); 6798 return false; 6799 } 6800 6801 /// parseSelect 6802 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6803 bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) { 6804 LocTy Loc; 6805 Value *Op0, *Op1, *Op2; 6806 if (parseTypeAndValue(Op0, Loc, PFS) || 6807 parseToken(lltok::comma, "expected ',' after select condition") || 6808 parseTypeAndValue(Op1, PFS) || 6809 parseToken(lltok::comma, "expected ',' after select value") || 6810 parseTypeAndValue(Op2, PFS)) 6811 return true; 6812 6813 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2)) 6814 return error(Loc, Reason); 6815 6816 Inst = SelectInst::Create(Op0, Op1, Op2); 6817 return false; 6818 } 6819 6820 /// parseVAArg 6821 /// ::= 'va_arg' TypeAndValue ',' Type 6822 bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) { 6823 Value *Op; 6824 Type *EltTy = nullptr; 6825 LocTy TypeLoc; 6826 if (parseTypeAndValue(Op, PFS) || 6827 parseToken(lltok::comma, "expected ',' after vaarg operand") || 6828 parseType(EltTy, TypeLoc)) 6829 return true; 6830 6831 if (!EltTy->isFirstClassType()) 6832 return error(TypeLoc, "va_arg requires operand with first class type"); 6833 6834 Inst = new VAArgInst(Op, EltTy); 6835 return false; 6836 } 6837 6838 /// parseExtractElement 6839 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue 6840 bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) { 6841 LocTy Loc; 6842 Value *Op0, *Op1; 6843 if (parseTypeAndValue(Op0, Loc, PFS) || 6844 parseToken(lltok::comma, "expected ',' after extract value") || 6845 parseTypeAndValue(Op1, PFS)) 6846 return true; 6847 6848 if (!ExtractElementInst::isValidOperands(Op0, Op1)) 6849 return error(Loc, "invalid extractelement operands"); 6850 6851 Inst = ExtractElementInst::Create(Op0, Op1); 6852 return false; 6853 } 6854 6855 /// parseInsertElement 6856 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6857 bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) { 6858 LocTy Loc; 6859 Value *Op0, *Op1, *Op2; 6860 if (parseTypeAndValue(Op0, Loc, PFS) || 6861 parseToken(lltok::comma, "expected ',' after insertelement value") || 6862 parseTypeAndValue(Op1, PFS) || 6863 parseToken(lltok::comma, "expected ',' after insertelement value") || 6864 parseTypeAndValue(Op2, PFS)) 6865 return true; 6866 6867 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2)) 6868 return error(Loc, "invalid insertelement operands"); 6869 6870 Inst = InsertElementInst::Create(Op0, Op1, Op2); 6871 return false; 6872 } 6873 6874 /// parseShuffleVector 6875 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6876 bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) { 6877 LocTy Loc; 6878 Value *Op0, *Op1, *Op2; 6879 if (parseTypeAndValue(Op0, Loc, PFS) || 6880 parseToken(lltok::comma, "expected ',' after shuffle mask") || 6881 parseTypeAndValue(Op1, PFS) || 6882 parseToken(lltok::comma, "expected ',' after shuffle value") || 6883 parseTypeAndValue(Op2, PFS)) 6884 return true; 6885 6886 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2)) 6887 return error(Loc, "invalid shufflevector operands"); 6888 6889 Inst = new ShuffleVectorInst(Op0, Op1, Op2); 6890 return false; 6891 } 6892 6893 /// parsePHI 6894 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')* 6895 int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) { 6896 Type *Ty = nullptr; LocTy TypeLoc; 6897 Value *Op0, *Op1; 6898 6899 if (parseType(Ty, TypeLoc) || 6900 parseToken(lltok::lsquare, "expected '[' in phi value list") || 6901 parseValue(Ty, Op0, PFS) || 6902 parseToken(lltok::comma, "expected ',' after insertelement value") || 6903 parseValue(Type::getLabelTy(Context), Op1, PFS) || 6904 parseToken(lltok::rsquare, "expected ']' in phi value list")) 6905 return true; 6906 6907 bool AteExtraComma = false; 6908 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals; 6909 6910 while (true) { 6911 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1))); 6912 6913 if (!EatIfPresent(lltok::comma)) 6914 break; 6915 6916 if (Lex.getKind() == lltok::MetadataVar) { 6917 AteExtraComma = true; 6918 break; 6919 } 6920 6921 if (parseToken(lltok::lsquare, "expected '[' in phi value list") || 6922 parseValue(Ty, Op0, PFS) || 6923 parseToken(lltok::comma, "expected ',' after insertelement value") || 6924 parseValue(Type::getLabelTy(Context), Op1, PFS) || 6925 parseToken(lltok::rsquare, "expected ']' in phi value list")) 6926 return true; 6927 } 6928 6929 if (!Ty->isFirstClassType()) 6930 return error(TypeLoc, "phi node must have first class type"); 6931 6932 PHINode *PN = PHINode::Create(Ty, PHIVals.size()); 6933 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i) 6934 PN->addIncoming(PHIVals[i].first, PHIVals[i].second); 6935 Inst = PN; 6936 return AteExtraComma ? InstExtraComma : InstNormal; 6937 } 6938 6939 /// parseLandingPad 6940 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+ 6941 /// Clause 6942 /// ::= 'catch' TypeAndValue 6943 /// ::= 'filter' 6944 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )* 6945 bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) { 6946 Type *Ty = nullptr; LocTy TyLoc; 6947 6948 if (parseType(Ty, TyLoc)) 6949 return true; 6950 6951 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0)); 6952 LP->setCleanup(EatIfPresent(lltok::kw_cleanup)); 6953 6954 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){ 6955 LandingPadInst::ClauseType CT; 6956 if (EatIfPresent(lltok::kw_catch)) 6957 CT = LandingPadInst::Catch; 6958 else if (EatIfPresent(lltok::kw_filter)) 6959 CT = LandingPadInst::Filter; 6960 else 6961 return tokError("expected 'catch' or 'filter' clause type"); 6962 6963 Value *V; 6964 LocTy VLoc; 6965 if (parseTypeAndValue(V, VLoc, PFS)) 6966 return true; 6967 6968 // A 'catch' type expects a non-array constant. A filter clause expects an 6969 // array constant. 6970 if (CT == LandingPadInst::Catch) { 6971 if (isa<ArrayType>(V->getType())) 6972 error(VLoc, "'catch' clause has an invalid type"); 6973 } else { 6974 if (!isa<ArrayType>(V->getType())) 6975 error(VLoc, "'filter' clause has an invalid type"); 6976 } 6977 6978 Constant *CV = dyn_cast<Constant>(V); 6979 if (!CV) 6980 return error(VLoc, "clause argument must be a constant"); 6981 LP->addClause(CV); 6982 } 6983 6984 Inst = LP.release(); 6985 return false; 6986 } 6987 6988 /// parseFreeze 6989 /// ::= 'freeze' Type Value 6990 bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) { 6991 LocTy Loc; 6992 Value *Op; 6993 if (parseTypeAndValue(Op, Loc, PFS)) 6994 return true; 6995 6996 Inst = new FreezeInst(Op); 6997 return false; 6998 } 6999 7000 /// parseCall 7001 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv 7002 /// OptionalAttrs Type Value ParameterList OptionalAttrs 7003 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv 7004 /// OptionalAttrs Type Value ParameterList OptionalAttrs 7005 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv 7006 /// OptionalAttrs Type Value ParameterList OptionalAttrs 7007 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv 7008 /// OptionalAttrs Type Value ParameterList OptionalAttrs 7009 bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS, 7010 CallInst::TailCallKind TCK) { 7011 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext()); 7012 std::vector<unsigned> FwdRefAttrGrps; 7013 LocTy BuiltinLoc; 7014 unsigned CallAddrSpace; 7015 unsigned CC; 7016 Type *RetType = nullptr; 7017 LocTy RetTypeLoc; 7018 ValID CalleeID; 7019 SmallVector<ParamInfo, 16> ArgList; 7020 SmallVector<OperandBundleDef, 2> BundleList; 7021 LocTy CallLoc = Lex.getLoc(); 7022 7023 if (TCK != CallInst::TCK_None && 7024 parseToken(lltok::kw_call, 7025 "expected 'tail call', 'musttail call', or 'notail call'")) 7026 return true; 7027 7028 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 7029 7030 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 7031 parseOptionalProgramAddrSpace(CallAddrSpace) || 7032 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 7033 parseValID(CalleeID, &PFS) || 7034 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail, 7035 PFS.getFunction().isVarArg()) || 7036 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) || 7037 parseOptionalOperandBundles(BundleList, PFS)) 7038 return true; 7039 7040 // If RetType is a non-function pointer type, then this is the short syntax 7041 // for the call, which means that RetType is just the return type. Infer the 7042 // rest of the function argument types from the arguments that are present. 7043 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 7044 if (!Ty) { 7045 // Pull out the types of all of the arguments... 7046 std::vector<Type*> ParamTypes; 7047 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 7048 ParamTypes.push_back(ArgList[i].V->getType()); 7049 7050 if (!FunctionType::isValidReturnType(RetType)) 7051 return error(RetTypeLoc, "Invalid result type for LLVM function"); 7052 7053 Ty = FunctionType::get(RetType, ParamTypes, false); 7054 } 7055 7056 CalleeID.FTy = Ty; 7057 7058 // Look up the callee. 7059 Value *Callee; 7060 if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee, 7061 &PFS)) 7062 return true; 7063 7064 // Set up the Attribute for the function. 7065 SmallVector<AttributeSet, 8> Attrs; 7066 7067 SmallVector<Value*, 8> Args; 7068 7069 // Loop through FunctionType's arguments and ensure they are specified 7070 // correctly. Also, gather any parameter attributes. 7071 FunctionType::param_iterator I = Ty->param_begin(); 7072 FunctionType::param_iterator E = Ty->param_end(); 7073 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 7074 Type *ExpectedTy = nullptr; 7075 if (I != E) { 7076 ExpectedTy = *I++; 7077 } else if (!Ty->isVarArg()) { 7078 return error(ArgList[i].Loc, "too many arguments specified"); 7079 } 7080 7081 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 7082 return error(ArgList[i].Loc, "argument is not of expected type '" + 7083 getTypeString(ExpectedTy) + "'"); 7084 Args.push_back(ArgList[i].V); 7085 Attrs.push_back(ArgList[i].Attrs); 7086 } 7087 7088 if (I != E) 7089 return error(CallLoc, "not enough parameters specified for call"); 7090 7091 if (FnAttrs.hasAlignmentAttr()) 7092 return error(CallLoc, "call instructions may not have an alignment"); 7093 7094 // Finish off the Attribute and check them 7095 AttributeList PAL = 7096 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 7097 AttributeSet::get(Context, RetAttrs), Attrs); 7098 7099 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList); 7100 CI->setTailCallKind(TCK); 7101 CI->setCallingConv(CC); 7102 if (FMF.any()) { 7103 if (!isa<FPMathOperator>(CI)) { 7104 CI->deleteValue(); 7105 return error(CallLoc, "fast-math-flags specified for call without " 7106 "floating-point scalar or vector return type"); 7107 } 7108 CI->setFastMathFlags(FMF); 7109 } 7110 CI->setAttributes(PAL); 7111 ForwardRefAttrGroups[CI] = FwdRefAttrGrps; 7112 Inst = CI; 7113 return false; 7114 } 7115 7116 //===----------------------------------------------------------------------===// 7117 // Memory Instructions. 7118 //===----------------------------------------------------------------------===// 7119 7120 /// parseAlloc 7121 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)? 7122 /// (',' 'align' i32)? (',', 'addrspace(n))? 7123 int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) { 7124 Value *Size = nullptr; 7125 LocTy SizeLoc, TyLoc, ASLoc; 7126 MaybeAlign Alignment; 7127 unsigned AddrSpace = 0; 7128 Type *Ty = nullptr; 7129 7130 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca); 7131 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror); 7132 7133 if (parseType(Ty, TyLoc)) 7134 return true; 7135 7136 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty)) 7137 return error(TyLoc, "invalid type for alloca"); 7138 7139 bool AteExtraComma = false; 7140 if (EatIfPresent(lltok::comma)) { 7141 if (Lex.getKind() == lltok::kw_align) { 7142 if (parseOptionalAlignment(Alignment)) 7143 return true; 7144 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)) 7145 return true; 7146 } else if (Lex.getKind() == lltok::kw_addrspace) { 7147 ASLoc = Lex.getLoc(); 7148 if (parseOptionalAddrSpace(AddrSpace)) 7149 return true; 7150 } else if (Lex.getKind() == lltok::MetadataVar) { 7151 AteExtraComma = true; 7152 } else { 7153 if (parseTypeAndValue(Size, SizeLoc, PFS)) 7154 return true; 7155 if (EatIfPresent(lltok::comma)) { 7156 if (Lex.getKind() == lltok::kw_align) { 7157 if (parseOptionalAlignment(Alignment)) 7158 return true; 7159 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)) 7160 return true; 7161 } else if (Lex.getKind() == lltok::kw_addrspace) { 7162 ASLoc = Lex.getLoc(); 7163 if (parseOptionalAddrSpace(AddrSpace)) 7164 return true; 7165 } else if (Lex.getKind() == lltok::MetadataVar) { 7166 AteExtraComma = true; 7167 } 7168 } 7169 } 7170 } 7171 7172 if (Size && !Size->getType()->isIntegerTy()) 7173 return error(SizeLoc, "element count must have integer type"); 7174 7175 SmallPtrSet<Type *, 4> Visited; 7176 if (!Alignment && !Ty->isSized(&Visited)) 7177 return error(TyLoc, "Cannot allocate unsized type"); 7178 if (!Alignment) 7179 Alignment = M->getDataLayout().getPrefTypeAlign(Ty); 7180 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment); 7181 AI->setUsedWithInAlloca(IsInAlloca); 7182 AI->setSwiftError(IsSwiftError); 7183 Inst = AI; 7184 return AteExtraComma ? InstExtraComma : InstNormal; 7185 } 7186 7187 /// parseLoad 7188 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)? 7189 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue 7190 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 7191 int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) { 7192 Value *Val; LocTy Loc; 7193 MaybeAlign Alignment; 7194 bool AteExtraComma = false; 7195 bool isAtomic = false; 7196 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7197 SyncScope::ID SSID = SyncScope::System; 7198 7199 if (Lex.getKind() == lltok::kw_atomic) { 7200 isAtomic = true; 7201 Lex.Lex(); 7202 } 7203 7204 bool isVolatile = false; 7205 if (Lex.getKind() == lltok::kw_volatile) { 7206 isVolatile = true; 7207 Lex.Lex(); 7208 } 7209 7210 Type *Ty; 7211 LocTy ExplicitTypeLoc = Lex.getLoc(); 7212 if (parseType(Ty) || 7213 parseToken(lltok::comma, "expected comma after load's type") || 7214 parseTypeAndValue(Val, Loc, PFS) || 7215 parseScopeAndOrdering(isAtomic, SSID, Ordering) || 7216 parseOptionalCommaAlign(Alignment, AteExtraComma)) 7217 return true; 7218 7219 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType()) 7220 return error(Loc, "load operand must be a pointer to a first class type"); 7221 if (isAtomic && !Alignment) 7222 return error(Loc, "atomic load must have explicit non-zero alignment"); 7223 if (Ordering == AtomicOrdering::Release || 7224 Ordering == AtomicOrdering::AcquireRelease) 7225 return error(Loc, "atomic load cannot use Release ordering"); 7226 7227 if (!cast<PointerType>(Val->getType())->isOpaqueOrPointeeTypeMatches(Ty)) { 7228 return error( 7229 ExplicitTypeLoc, 7230 typeComparisonErrorMessage( 7231 "explicit pointee type doesn't match operand's pointee type", Ty, 7232 Val->getType()->getNonOpaquePointerElementType())); 7233 } 7234 SmallPtrSet<Type *, 4> Visited; 7235 if (!Alignment && !Ty->isSized(&Visited)) 7236 return error(ExplicitTypeLoc, "loading unsized types is not allowed"); 7237 if (!Alignment) 7238 Alignment = M->getDataLayout().getABITypeAlign(Ty); 7239 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID); 7240 return AteExtraComma ? InstExtraComma : InstNormal; 7241 } 7242 7243 /// parseStore 7244 7245 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)? 7246 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue 7247 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 7248 int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) { 7249 Value *Val, *Ptr; LocTy Loc, PtrLoc; 7250 MaybeAlign Alignment; 7251 bool AteExtraComma = false; 7252 bool isAtomic = false; 7253 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7254 SyncScope::ID SSID = SyncScope::System; 7255 7256 if (Lex.getKind() == lltok::kw_atomic) { 7257 isAtomic = true; 7258 Lex.Lex(); 7259 } 7260 7261 bool isVolatile = false; 7262 if (Lex.getKind() == lltok::kw_volatile) { 7263 isVolatile = true; 7264 Lex.Lex(); 7265 } 7266 7267 if (parseTypeAndValue(Val, Loc, PFS) || 7268 parseToken(lltok::comma, "expected ',' after store operand") || 7269 parseTypeAndValue(Ptr, PtrLoc, PFS) || 7270 parseScopeAndOrdering(isAtomic, SSID, Ordering) || 7271 parseOptionalCommaAlign(Alignment, AteExtraComma)) 7272 return true; 7273 7274 if (!Ptr->getType()->isPointerTy()) 7275 return error(PtrLoc, "store operand must be a pointer"); 7276 if (!Val->getType()->isFirstClassType()) 7277 return error(Loc, "store operand must be a first class value"); 7278 if (!cast<PointerType>(Ptr->getType()) 7279 ->isOpaqueOrPointeeTypeMatches(Val->getType())) 7280 return error(Loc, "stored value and pointer type do not match"); 7281 if (isAtomic && !Alignment) 7282 return error(Loc, "atomic store must have explicit non-zero alignment"); 7283 if (Ordering == AtomicOrdering::Acquire || 7284 Ordering == AtomicOrdering::AcquireRelease) 7285 return error(Loc, "atomic store cannot use Acquire ordering"); 7286 SmallPtrSet<Type *, 4> Visited; 7287 if (!Alignment && !Val->getType()->isSized(&Visited)) 7288 return error(Loc, "storing unsized types is not allowed"); 7289 if (!Alignment) 7290 Alignment = M->getDataLayout().getABITypeAlign(Val->getType()); 7291 7292 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID); 7293 return AteExtraComma ? InstExtraComma : InstNormal; 7294 } 7295 7296 /// parseCmpXchg 7297 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ',' 7298 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ',' 7299 /// 'Align'? 7300 int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) { 7301 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc; 7302 bool AteExtraComma = false; 7303 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic; 7304 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic; 7305 SyncScope::ID SSID = SyncScope::System; 7306 bool isVolatile = false; 7307 bool isWeak = false; 7308 MaybeAlign Alignment; 7309 7310 if (EatIfPresent(lltok::kw_weak)) 7311 isWeak = true; 7312 7313 if (EatIfPresent(lltok::kw_volatile)) 7314 isVolatile = true; 7315 7316 if (parseTypeAndValue(Ptr, PtrLoc, PFS) || 7317 parseToken(lltok::comma, "expected ',' after cmpxchg address") || 7318 parseTypeAndValue(Cmp, CmpLoc, PFS) || 7319 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") || 7320 parseTypeAndValue(New, NewLoc, PFS) || 7321 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) || 7322 parseOrdering(FailureOrdering) || 7323 parseOptionalCommaAlign(Alignment, AteExtraComma)) 7324 return true; 7325 7326 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering)) 7327 return tokError("invalid cmpxchg success ordering"); 7328 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering)) 7329 return tokError("invalid cmpxchg failure ordering"); 7330 if (!Ptr->getType()->isPointerTy()) 7331 return error(PtrLoc, "cmpxchg operand must be a pointer"); 7332 if (!cast<PointerType>(Ptr->getType()) 7333 ->isOpaqueOrPointeeTypeMatches(Cmp->getType())) 7334 return error(CmpLoc, "compare value and pointer type do not match"); 7335 if (!cast<PointerType>(Ptr->getType()) 7336 ->isOpaqueOrPointeeTypeMatches(New->getType())) 7337 return error(NewLoc, "new value and pointer type do not match"); 7338 if (Cmp->getType() != New->getType()) 7339 return error(NewLoc, "compare value and new value type do not match"); 7340 if (!New->getType()->isFirstClassType()) 7341 return error(NewLoc, "cmpxchg operand must be a first class value"); 7342 7343 const Align DefaultAlignment( 7344 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize( 7345 Cmp->getType())); 7346 7347 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst( 7348 Ptr, Cmp, New, Alignment.getValueOr(DefaultAlignment), SuccessOrdering, 7349 FailureOrdering, SSID); 7350 CXI->setVolatile(isVolatile); 7351 CXI->setWeak(isWeak); 7352 7353 Inst = CXI; 7354 return AteExtraComma ? InstExtraComma : InstNormal; 7355 } 7356 7357 /// parseAtomicRMW 7358 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue 7359 /// 'singlethread'? AtomicOrdering 7360 int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) { 7361 Value *Ptr, *Val; LocTy PtrLoc, ValLoc; 7362 bool AteExtraComma = false; 7363 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7364 SyncScope::ID SSID = SyncScope::System; 7365 bool isVolatile = false; 7366 bool IsFP = false; 7367 AtomicRMWInst::BinOp Operation; 7368 MaybeAlign Alignment; 7369 7370 if (EatIfPresent(lltok::kw_volatile)) 7371 isVolatile = true; 7372 7373 switch (Lex.getKind()) { 7374 default: 7375 return tokError("expected binary operation in atomicrmw"); 7376 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break; 7377 case lltok::kw_add: Operation = AtomicRMWInst::Add; break; 7378 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break; 7379 case lltok::kw_and: Operation = AtomicRMWInst::And; break; 7380 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break; 7381 case lltok::kw_or: Operation = AtomicRMWInst::Or; break; 7382 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break; 7383 case lltok::kw_max: Operation = AtomicRMWInst::Max; break; 7384 case lltok::kw_min: Operation = AtomicRMWInst::Min; break; 7385 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break; 7386 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break; 7387 case lltok::kw_fadd: 7388 Operation = AtomicRMWInst::FAdd; 7389 IsFP = true; 7390 break; 7391 case lltok::kw_fsub: 7392 Operation = AtomicRMWInst::FSub; 7393 IsFP = true; 7394 break; 7395 } 7396 Lex.Lex(); // Eat the operation. 7397 7398 if (parseTypeAndValue(Ptr, PtrLoc, PFS) || 7399 parseToken(lltok::comma, "expected ',' after atomicrmw address") || 7400 parseTypeAndValue(Val, ValLoc, PFS) || 7401 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) || 7402 parseOptionalCommaAlign(Alignment, AteExtraComma)) 7403 return true; 7404 7405 if (Ordering == AtomicOrdering::Unordered) 7406 return tokError("atomicrmw cannot be unordered"); 7407 if (!Ptr->getType()->isPointerTy()) 7408 return error(PtrLoc, "atomicrmw operand must be a pointer"); 7409 if (!cast<PointerType>(Ptr->getType()) 7410 ->isOpaqueOrPointeeTypeMatches(Val->getType())) 7411 return error(ValLoc, "atomicrmw value and pointer type do not match"); 7412 7413 if (Operation == AtomicRMWInst::Xchg) { 7414 if (!Val->getType()->isIntegerTy() && 7415 !Val->getType()->isFloatingPointTy()) { 7416 return error(ValLoc, 7417 "atomicrmw " + AtomicRMWInst::getOperationName(Operation) + 7418 " operand must be an integer or floating point type"); 7419 } 7420 } else if (IsFP) { 7421 if (!Val->getType()->isFloatingPointTy()) { 7422 return error(ValLoc, "atomicrmw " + 7423 AtomicRMWInst::getOperationName(Operation) + 7424 " operand must be a floating point type"); 7425 } 7426 } else { 7427 if (!Val->getType()->isIntegerTy()) { 7428 return error(ValLoc, "atomicrmw " + 7429 AtomicRMWInst::getOperationName(Operation) + 7430 " operand must be an integer"); 7431 } 7432 } 7433 7434 unsigned Size = Val->getType()->getPrimitiveSizeInBits(); 7435 if (Size < 8 || (Size & (Size - 1))) 7436 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized" 7437 " integer"); 7438 const Align DefaultAlignment( 7439 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize( 7440 Val->getType())); 7441 AtomicRMWInst *RMWI = 7442 new AtomicRMWInst(Operation, Ptr, Val, 7443 Alignment.getValueOr(DefaultAlignment), Ordering, SSID); 7444 RMWI->setVolatile(isVolatile); 7445 Inst = RMWI; 7446 return AteExtraComma ? InstExtraComma : InstNormal; 7447 } 7448 7449 /// parseFence 7450 /// ::= 'fence' 'singlethread'? AtomicOrdering 7451 int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) { 7452 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7453 SyncScope::ID SSID = SyncScope::System; 7454 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering)) 7455 return true; 7456 7457 if (Ordering == AtomicOrdering::Unordered) 7458 return tokError("fence cannot be unordered"); 7459 if (Ordering == AtomicOrdering::Monotonic) 7460 return tokError("fence cannot be monotonic"); 7461 7462 Inst = new FenceInst(Context, Ordering, SSID); 7463 return InstNormal; 7464 } 7465 7466 /// parseGetElementPtr 7467 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)* 7468 int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { 7469 Value *Ptr = nullptr; 7470 Value *Val = nullptr; 7471 LocTy Loc, EltLoc; 7472 7473 bool InBounds = EatIfPresent(lltok::kw_inbounds); 7474 7475 Type *Ty = nullptr; 7476 LocTy ExplicitTypeLoc = Lex.getLoc(); 7477 if (parseType(Ty) || 7478 parseToken(lltok::comma, "expected comma after getelementptr's type") || 7479 parseTypeAndValue(Ptr, Loc, PFS)) 7480 return true; 7481 7482 Type *BaseType = Ptr->getType(); 7483 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType()); 7484 if (!BasePointerType) 7485 return error(Loc, "base of getelementptr must be a pointer"); 7486 7487 if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) { 7488 return error( 7489 ExplicitTypeLoc, 7490 typeComparisonErrorMessage( 7491 "explicit pointee type doesn't match operand's pointee type", Ty, 7492 BasePointerType->getNonOpaquePointerElementType())); 7493 } 7494 7495 SmallVector<Value*, 16> Indices; 7496 bool AteExtraComma = false; 7497 // GEP returns a vector of pointers if at least one of parameters is a vector. 7498 // All vector parameters should have the same vector width. 7499 ElementCount GEPWidth = BaseType->isVectorTy() 7500 ? cast<VectorType>(BaseType)->getElementCount() 7501 : ElementCount::getFixed(0); 7502 7503 while (EatIfPresent(lltok::comma)) { 7504 if (Lex.getKind() == lltok::MetadataVar) { 7505 AteExtraComma = true; 7506 break; 7507 } 7508 if (parseTypeAndValue(Val, EltLoc, PFS)) 7509 return true; 7510 if (!Val->getType()->isIntOrIntVectorTy()) 7511 return error(EltLoc, "getelementptr index must be an integer"); 7512 7513 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) { 7514 ElementCount ValNumEl = ValVTy->getElementCount(); 7515 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl) 7516 return error( 7517 EltLoc, 7518 "getelementptr vector index has a wrong number of elements"); 7519 GEPWidth = ValNumEl; 7520 } 7521 Indices.push_back(Val); 7522 } 7523 7524 SmallPtrSet<Type*, 4> Visited; 7525 if (!Indices.empty() && !Ty->isSized(&Visited)) 7526 return error(Loc, "base element of getelementptr must be sized"); 7527 7528 if (!GetElementPtrInst::getIndexedType(Ty, Indices)) 7529 return error(Loc, "invalid getelementptr indices"); 7530 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices); 7531 if (InBounds) 7532 cast<GetElementPtrInst>(Inst)->setIsInBounds(true); 7533 return AteExtraComma ? InstExtraComma : InstNormal; 7534 } 7535 7536 /// parseExtractValue 7537 /// ::= 'extractvalue' TypeAndValue (',' uint32)+ 7538 int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) { 7539 Value *Val; LocTy Loc; 7540 SmallVector<unsigned, 4> Indices; 7541 bool AteExtraComma; 7542 if (parseTypeAndValue(Val, Loc, PFS) || 7543 parseIndexList(Indices, AteExtraComma)) 7544 return true; 7545 7546 if (!Val->getType()->isAggregateType()) 7547 return error(Loc, "extractvalue operand must be aggregate type"); 7548 7549 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 7550 return error(Loc, "invalid indices for extractvalue"); 7551 Inst = ExtractValueInst::Create(Val, Indices); 7552 return AteExtraComma ? InstExtraComma : InstNormal; 7553 } 7554 7555 /// parseInsertValue 7556 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+ 7557 int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { 7558 Value *Val0, *Val1; LocTy Loc0, Loc1; 7559 SmallVector<unsigned, 4> Indices; 7560 bool AteExtraComma; 7561 if (parseTypeAndValue(Val0, Loc0, PFS) || 7562 parseToken(lltok::comma, "expected comma after insertvalue operand") || 7563 parseTypeAndValue(Val1, Loc1, PFS) || 7564 parseIndexList(Indices, AteExtraComma)) 7565 return true; 7566 7567 if (!Val0->getType()->isAggregateType()) 7568 return error(Loc0, "insertvalue operand must be aggregate type"); 7569 7570 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices); 7571 if (!IndexedType) 7572 return error(Loc0, "invalid indices for insertvalue"); 7573 if (IndexedType != Val1->getType()) 7574 return error(Loc1, "insertvalue operand and field disagree in type: '" + 7575 getTypeString(Val1->getType()) + "' instead of '" + 7576 getTypeString(IndexedType) + "'"); 7577 Inst = InsertValueInst::Create(Val0, Val1, Indices); 7578 return AteExtraComma ? InstExtraComma : InstNormal; 7579 } 7580 7581 //===----------------------------------------------------------------------===// 7582 // Embedded metadata. 7583 //===----------------------------------------------------------------------===// 7584 7585 /// parseMDNodeVector 7586 /// ::= { Element (',' Element)* } 7587 /// Element 7588 /// ::= 'null' | TypeAndValue 7589 bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) { 7590 if (parseToken(lltok::lbrace, "expected '{' here")) 7591 return true; 7592 7593 // Check for an empty list. 7594 if (EatIfPresent(lltok::rbrace)) 7595 return false; 7596 7597 do { 7598 // Null is a special case since it is typeless. 7599 if (EatIfPresent(lltok::kw_null)) { 7600 Elts.push_back(nullptr); 7601 continue; 7602 } 7603 7604 Metadata *MD; 7605 if (parseMetadata(MD, nullptr)) 7606 return true; 7607 Elts.push_back(MD); 7608 } while (EatIfPresent(lltok::comma)); 7609 7610 return parseToken(lltok::rbrace, "expected end of metadata node"); 7611 } 7612 7613 //===----------------------------------------------------------------------===// 7614 // Use-list order directives. 7615 //===----------------------------------------------------------------------===// 7616 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, 7617 SMLoc Loc) { 7618 if (V->use_empty()) 7619 return error(Loc, "value has no uses"); 7620 7621 unsigned NumUses = 0; 7622 SmallDenseMap<const Use *, unsigned, 16> Order; 7623 for (const Use &U : V->uses()) { 7624 if (++NumUses > Indexes.size()) 7625 break; 7626 Order[&U] = Indexes[NumUses - 1]; 7627 } 7628 if (NumUses < 2) 7629 return error(Loc, "value only has one use"); 7630 if (Order.size() != Indexes.size() || NumUses > Indexes.size()) 7631 return error(Loc, 7632 "wrong number of indexes, expected " + Twine(V->getNumUses())); 7633 7634 V->sortUseList([&](const Use &L, const Use &R) { 7635 return Order.lookup(&L) < Order.lookup(&R); 7636 }); 7637 return false; 7638 } 7639 7640 /// parseUseListOrderIndexes 7641 /// ::= '{' uint32 (',' uint32)+ '}' 7642 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) { 7643 SMLoc Loc = Lex.getLoc(); 7644 if (parseToken(lltok::lbrace, "expected '{' here")) 7645 return true; 7646 if (Lex.getKind() == lltok::rbrace) 7647 return Lex.Error("expected non-empty list of uselistorder indexes"); 7648 7649 // Use Offset, Max, and IsOrdered to check consistency of indexes. The 7650 // indexes should be distinct numbers in the range [0, size-1], and should 7651 // not be in order. 7652 unsigned Offset = 0; 7653 unsigned Max = 0; 7654 bool IsOrdered = true; 7655 assert(Indexes.empty() && "Expected empty order vector"); 7656 do { 7657 unsigned Index; 7658 if (parseUInt32(Index)) 7659 return true; 7660 7661 // Update consistency checks. 7662 Offset += Index - Indexes.size(); 7663 Max = std::max(Max, Index); 7664 IsOrdered &= Index == Indexes.size(); 7665 7666 Indexes.push_back(Index); 7667 } while (EatIfPresent(lltok::comma)); 7668 7669 if (parseToken(lltok::rbrace, "expected '}' here")) 7670 return true; 7671 7672 if (Indexes.size() < 2) 7673 return error(Loc, "expected >= 2 uselistorder indexes"); 7674 if (Offset != 0 || Max >= Indexes.size()) 7675 return error(Loc, 7676 "expected distinct uselistorder indexes in range [0, size)"); 7677 if (IsOrdered) 7678 return error(Loc, "expected uselistorder indexes to change the order"); 7679 7680 return false; 7681 } 7682 7683 /// parseUseListOrder 7684 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes 7685 bool LLParser::parseUseListOrder(PerFunctionState *PFS) { 7686 SMLoc Loc = Lex.getLoc(); 7687 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive")) 7688 return true; 7689 7690 Value *V; 7691 SmallVector<unsigned, 16> Indexes; 7692 if (parseTypeAndValue(V, PFS) || 7693 parseToken(lltok::comma, "expected comma in uselistorder directive") || 7694 parseUseListOrderIndexes(Indexes)) 7695 return true; 7696 7697 return sortUseListOrder(V, Indexes, Loc); 7698 } 7699 7700 /// parseUseListOrderBB 7701 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes 7702 bool LLParser::parseUseListOrderBB() { 7703 assert(Lex.getKind() == lltok::kw_uselistorder_bb); 7704 SMLoc Loc = Lex.getLoc(); 7705 Lex.Lex(); 7706 7707 ValID Fn, Label; 7708 SmallVector<unsigned, 16> Indexes; 7709 if (parseValID(Fn, /*PFS=*/nullptr) || 7710 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 7711 parseValID(Label, /*PFS=*/nullptr) || 7712 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 7713 parseUseListOrderIndexes(Indexes)) 7714 return true; 7715 7716 // Check the function. 7717 GlobalValue *GV; 7718 if (Fn.Kind == ValID::t_GlobalName) 7719 GV = M->getNamedValue(Fn.StrVal); 7720 else if (Fn.Kind == ValID::t_GlobalID) 7721 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr; 7722 else 7723 return error(Fn.Loc, "expected function name in uselistorder_bb"); 7724 if (!GV) 7725 return error(Fn.Loc, 7726 "invalid function forward reference in uselistorder_bb"); 7727 auto *F = dyn_cast<Function>(GV); 7728 if (!F) 7729 return error(Fn.Loc, "expected function name in uselistorder_bb"); 7730 if (F->isDeclaration()) 7731 return error(Fn.Loc, "invalid declaration in uselistorder_bb"); 7732 7733 // Check the basic block. 7734 if (Label.Kind == ValID::t_LocalID) 7735 return error(Label.Loc, "invalid numeric label in uselistorder_bb"); 7736 if (Label.Kind != ValID::t_LocalName) 7737 return error(Label.Loc, "expected basic block name in uselistorder_bb"); 7738 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal); 7739 if (!V) 7740 return error(Label.Loc, "invalid basic block in uselistorder_bb"); 7741 if (!isa<BasicBlock>(V)) 7742 return error(Label.Loc, "expected basic block in uselistorder_bb"); 7743 7744 return sortUseListOrder(V, Indexes, Loc); 7745 } 7746 7747 /// ModuleEntry 7748 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')' 7749 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')' 7750 bool LLParser::parseModuleEntry(unsigned ID) { 7751 assert(Lex.getKind() == lltok::kw_module); 7752 Lex.Lex(); 7753 7754 std::string Path; 7755 if (parseToken(lltok::colon, "expected ':' here") || 7756 parseToken(lltok::lparen, "expected '(' here") || 7757 parseToken(lltok::kw_path, "expected 'path' here") || 7758 parseToken(lltok::colon, "expected ':' here") || 7759 parseStringConstant(Path) || 7760 parseToken(lltok::comma, "expected ',' here") || 7761 parseToken(lltok::kw_hash, "expected 'hash' here") || 7762 parseToken(lltok::colon, "expected ':' here") || 7763 parseToken(lltok::lparen, "expected '(' here")) 7764 return true; 7765 7766 ModuleHash Hash; 7767 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") || 7768 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") || 7769 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") || 7770 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") || 7771 parseUInt32(Hash[4])) 7772 return true; 7773 7774 if (parseToken(lltok::rparen, "expected ')' here") || 7775 parseToken(lltok::rparen, "expected ')' here")) 7776 return true; 7777 7778 auto ModuleEntry = Index->addModule(Path, ID, Hash); 7779 ModuleIdMap[ID] = ModuleEntry->first(); 7780 7781 return false; 7782 } 7783 7784 /// TypeIdEntry 7785 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')' 7786 bool LLParser::parseTypeIdEntry(unsigned ID) { 7787 assert(Lex.getKind() == lltok::kw_typeid); 7788 Lex.Lex(); 7789 7790 std::string Name; 7791 if (parseToken(lltok::colon, "expected ':' here") || 7792 parseToken(lltok::lparen, "expected '(' here") || 7793 parseToken(lltok::kw_name, "expected 'name' here") || 7794 parseToken(lltok::colon, "expected ':' here") || 7795 parseStringConstant(Name)) 7796 return true; 7797 7798 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name); 7799 if (parseToken(lltok::comma, "expected ',' here") || 7800 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here")) 7801 return true; 7802 7803 // Check if this ID was forward referenced, and if so, update the 7804 // corresponding GUIDs. 7805 auto FwdRefTIDs = ForwardRefTypeIds.find(ID); 7806 if (FwdRefTIDs != ForwardRefTypeIds.end()) { 7807 for (auto TIDRef : FwdRefTIDs->second) { 7808 assert(!*TIDRef.first && 7809 "Forward referenced type id GUID expected to be 0"); 7810 *TIDRef.first = GlobalValue::getGUID(Name); 7811 } 7812 ForwardRefTypeIds.erase(FwdRefTIDs); 7813 } 7814 7815 return false; 7816 } 7817 7818 /// TypeIdSummary 7819 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')' 7820 bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) { 7821 if (parseToken(lltok::kw_summary, "expected 'summary' here") || 7822 parseToken(lltok::colon, "expected ':' here") || 7823 parseToken(lltok::lparen, "expected '(' here") || 7824 parseTypeTestResolution(TIS.TTRes)) 7825 return true; 7826 7827 if (EatIfPresent(lltok::comma)) { 7828 // Expect optional wpdResolutions field 7829 if (parseOptionalWpdResolutions(TIS.WPDRes)) 7830 return true; 7831 } 7832 7833 if (parseToken(lltok::rparen, "expected ')' here")) 7834 return true; 7835 7836 return false; 7837 } 7838 7839 static ValueInfo EmptyVI = 7840 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8); 7841 7842 /// TypeIdCompatibleVtableEntry 7843 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ',' 7844 /// TypeIdCompatibleVtableInfo 7845 /// ')' 7846 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) { 7847 assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable); 7848 Lex.Lex(); 7849 7850 std::string Name; 7851 if (parseToken(lltok::colon, "expected ':' here") || 7852 parseToken(lltok::lparen, "expected '(' here") || 7853 parseToken(lltok::kw_name, "expected 'name' here") || 7854 parseToken(lltok::colon, "expected ':' here") || 7855 parseStringConstant(Name)) 7856 return true; 7857 7858 TypeIdCompatibleVtableInfo &TI = 7859 Index->getOrInsertTypeIdCompatibleVtableSummary(Name); 7860 if (parseToken(lltok::comma, "expected ',' here") || 7861 parseToken(lltok::kw_summary, "expected 'summary' here") || 7862 parseToken(lltok::colon, "expected ':' here") || 7863 parseToken(lltok::lparen, "expected '(' here")) 7864 return true; 7865 7866 IdToIndexMapType IdToIndexMap; 7867 // parse each call edge 7868 do { 7869 uint64_t Offset; 7870 if (parseToken(lltok::lparen, "expected '(' here") || 7871 parseToken(lltok::kw_offset, "expected 'offset' here") || 7872 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) || 7873 parseToken(lltok::comma, "expected ',' here")) 7874 return true; 7875 7876 LocTy Loc = Lex.getLoc(); 7877 unsigned GVId; 7878 ValueInfo VI; 7879 if (parseGVReference(VI, GVId)) 7880 return true; 7881 7882 // Keep track of the TypeIdCompatibleVtableInfo array index needing a 7883 // forward reference. We will save the location of the ValueInfo needing an 7884 // update, but can only do so once the std::vector is finalized. 7885 if (VI == EmptyVI) 7886 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc)); 7887 TI.push_back({Offset, VI}); 7888 7889 if (parseToken(lltok::rparen, "expected ')' in call")) 7890 return true; 7891 } while (EatIfPresent(lltok::comma)); 7892 7893 // Now that the TI vector is finalized, it is safe to save the locations 7894 // of any forward GV references that need updating later. 7895 for (auto I : IdToIndexMap) { 7896 auto &Infos = ForwardRefValueInfos[I.first]; 7897 for (auto P : I.second) { 7898 assert(TI[P.first].VTableVI == EmptyVI && 7899 "Forward referenced ValueInfo expected to be empty"); 7900 Infos.emplace_back(&TI[P.first].VTableVI, P.second); 7901 } 7902 } 7903 7904 if (parseToken(lltok::rparen, "expected ')' here") || 7905 parseToken(lltok::rparen, "expected ')' here")) 7906 return true; 7907 7908 // Check if this ID was forward referenced, and if so, update the 7909 // corresponding GUIDs. 7910 auto FwdRefTIDs = ForwardRefTypeIds.find(ID); 7911 if (FwdRefTIDs != ForwardRefTypeIds.end()) { 7912 for (auto TIDRef : FwdRefTIDs->second) { 7913 assert(!*TIDRef.first && 7914 "Forward referenced type id GUID expected to be 0"); 7915 *TIDRef.first = GlobalValue::getGUID(Name); 7916 } 7917 ForwardRefTypeIds.erase(FwdRefTIDs); 7918 } 7919 7920 return false; 7921 } 7922 7923 /// TypeTestResolution 7924 /// ::= 'typeTestRes' ':' '(' 'kind' ':' 7925 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ',' 7926 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]? 7927 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]? 7928 /// [',' 'inlinesBits' ':' UInt64]? ')' 7929 bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) { 7930 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") || 7931 parseToken(lltok::colon, "expected ':' here") || 7932 parseToken(lltok::lparen, "expected '(' here") || 7933 parseToken(lltok::kw_kind, "expected 'kind' here") || 7934 parseToken(lltok::colon, "expected ':' here")) 7935 return true; 7936 7937 switch (Lex.getKind()) { 7938 case lltok::kw_unknown: 7939 TTRes.TheKind = TypeTestResolution::Unknown; 7940 break; 7941 case lltok::kw_unsat: 7942 TTRes.TheKind = TypeTestResolution::Unsat; 7943 break; 7944 case lltok::kw_byteArray: 7945 TTRes.TheKind = TypeTestResolution::ByteArray; 7946 break; 7947 case lltok::kw_inline: 7948 TTRes.TheKind = TypeTestResolution::Inline; 7949 break; 7950 case lltok::kw_single: 7951 TTRes.TheKind = TypeTestResolution::Single; 7952 break; 7953 case lltok::kw_allOnes: 7954 TTRes.TheKind = TypeTestResolution::AllOnes; 7955 break; 7956 default: 7957 return error(Lex.getLoc(), "unexpected TypeTestResolution kind"); 7958 } 7959 Lex.Lex(); 7960 7961 if (parseToken(lltok::comma, "expected ',' here") || 7962 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") || 7963 parseToken(lltok::colon, "expected ':' here") || 7964 parseUInt32(TTRes.SizeM1BitWidth)) 7965 return true; 7966 7967 // parse optional fields 7968 while (EatIfPresent(lltok::comma)) { 7969 switch (Lex.getKind()) { 7970 case lltok::kw_alignLog2: 7971 Lex.Lex(); 7972 if (parseToken(lltok::colon, "expected ':'") || 7973 parseUInt64(TTRes.AlignLog2)) 7974 return true; 7975 break; 7976 case lltok::kw_sizeM1: 7977 Lex.Lex(); 7978 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1)) 7979 return true; 7980 break; 7981 case lltok::kw_bitMask: { 7982 unsigned Val; 7983 Lex.Lex(); 7984 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val)) 7985 return true; 7986 assert(Val <= 0xff); 7987 TTRes.BitMask = (uint8_t)Val; 7988 break; 7989 } 7990 case lltok::kw_inlineBits: 7991 Lex.Lex(); 7992 if (parseToken(lltok::colon, "expected ':'") || 7993 parseUInt64(TTRes.InlineBits)) 7994 return true; 7995 break; 7996 default: 7997 return error(Lex.getLoc(), "expected optional TypeTestResolution field"); 7998 } 7999 } 8000 8001 if (parseToken(lltok::rparen, "expected ')' here")) 8002 return true; 8003 8004 return false; 8005 } 8006 8007 /// OptionalWpdResolutions 8008 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')' 8009 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')' 8010 bool LLParser::parseOptionalWpdResolutions( 8011 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) { 8012 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") || 8013 parseToken(lltok::colon, "expected ':' here") || 8014 parseToken(lltok::lparen, "expected '(' here")) 8015 return true; 8016 8017 do { 8018 uint64_t Offset; 8019 WholeProgramDevirtResolution WPDRes; 8020 if (parseToken(lltok::lparen, "expected '(' here") || 8021 parseToken(lltok::kw_offset, "expected 'offset' here") || 8022 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) || 8023 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) || 8024 parseToken(lltok::rparen, "expected ')' here")) 8025 return true; 8026 WPDResMap[Offset] = WPDRes; 8027 } while (EatIfPresent(lltok::comma)); 8028 8029 if (parseToken(lltok::rparen, "expected ')' here")) 8030 return true; 8031 8032 return false; 8033 } 8034 8035 /// WpdRes 8036 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir' 8037 /// [',' OptionalResByArg]? ')' 8038 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl' 8039 /// ',' 'singleImplName' ':' STRINGCONSTANT ',' 8040 /// [',' OptionalResByArg]? ')' 8041 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel' 8042 /// [',' OptionalResByArg]? ')' 8043 bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) { 8044 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") || 8045 parseToken(lltok::colon, "expected ':' here") || 8046 parseToken(lltok::lparen, "expected '(' here") || 8047 parseToken(lltok::kw_kind, "expected 'kind' here") || 8048 parseToken(lltok::colon, "expected ':' here")) 8049 return true; 8050 8051 switch (Lex.getKind()) { 8052 case lltok::kw_indir: 8053 WPDRes.TheKind = WholeProgramDevirtResolution::Indir; 8054 break; 8055 case lltok::kw_singleImpl: 8056 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl; 8057 break; 8058 case lltok::kw_branchFunnel: 8059 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel; 8060 break; 8061 default: 8062 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind"); 8063 } 8064 Lex.Lex(); 8065 8066 // parse optional fields 8067 while (EatIfPresent(lltok::comma)) { 8068 switch (Lex.getKind()) { 8069 case lltok::kw_singleImplName: 8070 Lex.Lex(); 8071 if (parseToken(lltok::colon, "expected ':' here") || 8072 parseStringConstant(WPDRes.SingleImplName)) 8073 return true; 8074 break; 8075 case lltok::kw_resByArg: 8076 if (parseOptionalResByArg(WPDRes.ResByArg)) 8077 return true; 8078 break; 8079 default: 8080 return error(Lex.getLoc(), 8081 "expected optional WholeProgramDevirtResolution field"); 8082 } 8083 } 8084 8085 if (parseToken(lltok::rparen, "expected ')' here")) 8086 return true; 8087 8088 return false; 8089 } 8090 8091 /// OptionalResByArg 8092 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')' 8093 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':' 8094 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' | 8095 /// 'virtualConstProp' ) 8096 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]? 8097 /// [',' 'bit' ':' UInt32]? ')' 8098 bool LLParser::parseOptionalResByArg( 8099 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg> 8100 &ResByArg) { 8101 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") || 8102 parseToken(lltok::colon, "expected ':' here") || 8103 parseToken(lltok::lparen, "expected '(' here")) 8104 return true; 8105 8106 do { 8107 std::vector<uint64_t> Args; 8108 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") || 8109 parseToken(lltok::kw_byArg, "expected 'byArg here") || 8110 parseToken(lltok::colon, "expected ':' here") || 8111 parseToken(lltok::lparen, "expected '(' here") || 8112 parseToken(lltok::kw_kind, "expected 'kind' here") || 8113 parseToken(lltok::colon, "expected ':' here")) 8114 return true; 8115 8116 WholeProgramDevirtResolution::ByArg ByArg; 8117 switch (Lex.getKind()) { 8118 case lltok::kw_indir: 8119 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir; 8120 break; 8121 case lltok::kw_uniformRetVal: 8122 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal; 8123 break; 8124 case lltok::kw_uniqueRetVal: 8125 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal; 8126 break; 8127 case lltok::kw_virtualConstProp: 8128 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp; 8129 break; 8130 default: 8131 return error(Lex.getLoc(), 8132 "unexpected WholeProgramDevirtResolution::ByArg kind"); 8133 } 8134 Lex.Lex(); 8135 8136 // parse optional fields 8137 while (EatIfPresent(lltok::comma)) { 8138 switch (Lex.getKind()) { 8139 case lltok::kw_info: 8140 Lex.Lex(); 8141 if (parseToken(lltok::colon, "expected ':' here") || 8142 parseUInt64(ByArg.Info)) 8143 return true; 8144 break; 8145 case lltok::kw_byte: 8146 Lex.Lex(); 8147 if (parseToken(lltok::colon, "expected ':' here") || 8148 parseUInt32(ByArg.Byte)) 8149 return true; 8150 break; 8151 case lltok::kw_bit: 8152 Lex.Lex(); 8153 if (parseToken(lltok::colon, "expected ':' here") || 8154 parseUInt32(ByArg.Bit)) 8155 return true; 8156 break; 8157 default: 8158 return error(Lex.getLoc(), 8159 "expected optional whole program devirt field"); 8160 } 8161 } 8162 8163 if (parseToken(lltok::rparen, "expected ')' here")) 8164 return true; 8165 8166 ResByArg[Args] = ByArg; 8167 } while (EatIfPresent(lltok::comma)); 8168 8169 if (parseToken(lltok::rparen, "expected ')' here")) 8170 return true; 8171 8172 return false; 8173 } 8174 8175 /// OptionalResByArg 8176 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')' 8177 bool LLParser::parseArgs(std::vector<uint64_t> &Args) { 8178 if (parseToken(lltok::kw_args, "expected 'args' here") || 8179 parseToken(lltok::colon, "expected ':' here") || 8180 parseToken(lltok::lparen, "expected '(' here")) 8181 return true; 8182 8183 do { 8184 uint64_t Val; 8185 if (parseUInt64(Val)) 8186 return true; 8187 Args.push_back(Val); 8188 } while (EatIfPresent(lltok::comma)); 8189 8190 if (parseToken(lltok::rparen, "expected ')' here")) 8191 return true; 8192 8193 return false; 8194 } 8195 8196 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8; 8197 8198 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) { 8199 bool ReadOnly = Fwd->isReadOnly(); 8200 bool WriteOnly = Fwd->isWriteOnly(); 8201 assert(!(ReadOnly && WriteOnly)); 8202 *Fwd = Resolved; 8203 if (ReadOnly) 8204 Fwd->setReadOnly(); 8205 if (WriteOnly) 8206 Fwd->setWriteOnly(); 8207 } 8208 8209 /// Stores the given Name/GUID and associated summary into the Index. 8210 /// Also updates any forward references to the associated entry ID. 8211 void LLParser::addGlobalValueToIndex( 8212 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage, 8213 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) { 8214 // First create the ValueInfo utilizing the Name or GUID. 8215 ValueInfo VI; 8216 if (GUID != 0) { 8217 assert(Name.empty()); 8218 VI = Index->getOrInsertValueInfo(GUID); 8219 } else { 8220 assert(!Name.empty()); 8221 if (M) { 8222 auto *GV = M->getNamedValue(Name); 8223 assert(GV); 8224 VI = Index->getOrInsertValueInfo(GV); 8225 } else { 8226 assert( 8227 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) && 8228 "Need a source_filename to compute GUID for local"); 8229 GUID = GlobalValue::getGUID( 8230 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName)); 8231 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name)); 8232 } 8233 } 8234 8235 // Resolve forward references from calls/refs 8236 auto FwdRefVIs = ForwardRefValueInfos.find(ID); 8237 if (FwdRefVIs != ForwardRefValueInfos.end()) { 8238 for (auto VIRef : FwdRefVIs->second) { 8239 assert(VIRef.first->getRef() == FwdVIRef && 8240 "Forward referenced ValueInfo expected to be empty"); 8241 resolveFwdRef(VIRef.first, VI); 8242 } 8243 ForwardRefValueInfos.erase(FwdRefVIs); 8244 } 8245 8246 // Resolve forward references from aliases 8247 auto FwdRefAliasees = ForwardRefAliasees.find(ID); 8248 if (FwdRefAliasees != ForwardRefAliasees.end()) { 8249 for (auto AliaseeRef : FwdRefAliasees->second) { 8250 assert(!AliaseeRef.first->hasAliasee() && 8251 "Forward referencing alias already has aliasee"); 8252 assert(Summary && "Aliasee must be a definition"); 8253 AliaseeRef.first->setAliasee(VI, Summary.get()); 8254 } 8255 ForwardRefAliasees.erase(FwdRefAliasees); 8256 } 8257 8258 // Add the summary if one was provided. 8259 if (Summary) 8260 Index->addGlobalValueSummary(VI, std::move(Summary)); 8261 8262 // Save the associated ValueInfo for use in later references by ID. 8263 if (ID == NumberedValueInfos.size()) 8264 NumberedValueInfos.push_back(VI); 8265 else { 8266 // Handle non-continuous numbers (to make test simplification easier). 8267 if (ID > NumberedValueInfos.size()) 8268 NumberedValueInfos.resize(ID + 1); 8269 NumberedValueInfos[ID] = VI; 8270 } 8271 } 8272 8273 /// parseSummaryIndexFlags 8274 /// ::= 'flags' ':' UInt64 8275 bool LLParser::parseSummaryIndexFlags() { 8276 assert(Lex.getKind() == lltok::kw_flags); 8277 Lex.Lex(); 8278 8279 if (parseToken(lltok::colon, "expected ':' here")) 8280 return true; 8281 uint64_t Flags; 8282 if (parseUInt64(Flags)) 8283 return true; 8284 if (Index) 8285 Index->setFlags(Flags); 8286 return false; 8287 } 8288 8289 /// parseBlockCount 8290 /// ::= 'blockcount' ':' UInt64 8291 bool LLParser::parseBlockCount() { 8292 assert(Lex.getKind() == lltok::kw_blockcount); 8293 Lex.Lex(); 8294 8295 if (parseToken(lltok::colon, "expected ':' here")) 8296 return true; 8297 uint64_t BlockCount; 8298 if (parseUInt64(BlockCount)) 8299 return true; 8300 if (Index) 8301 Index->setBlockCount(BlockCount); 8302 return false; 8303 } 8304 8305 /// parseGVEntry 8306 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64) 8307 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')' 8308 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')' 8309 bool LLParser::parseGVEntry(unsigned ID) { 8310 assert(Lex.getKind() == lltok::kw_gv); 8311 Lex.Lex(); 8312 8313 if (parseToken(lltok::colon, "expected ':' here") || 8314 parseToken(lltok::lparen, "expected '(' here")) 8315 return true; 8316 8317 std::string Name; 8318 GlobalValue::GUID GUID = 0; 8319 switch (Lex.getKind()) { 8320 case lltok::kw_name: 8321 Lex.Lex(); 8322 if (parseToken(lltok::colon, "expected ':' here") || 8323 parseStringConstant(Name)) 8324 return true; 8325 // Can't create GUID/ValueInfo until we have the linkage. 8326 break; 8327 case lltok::kw_guid: 8328 Lex.Lex(); 8329 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID)) 8330 return true; 8331 break; 8332 default: 8333 return error(Lex.getLoc(), "expected name or guid tag"); 8334 } 8335 8336 if (!EatIfPresent(lltok::comma)) { 8337 // No summaries. Wrap up. 8338 if (parseToken(lltok::rparen, "expected ')' here")) 8339 return true; 8340 // This was created for a call to an external or indirect target. 8341 // A GUID with no summary came from a VALUE_GUID record, dummy GUID 8342 // created for indirect calls with VP. A Name with no GUID came from 8343 // an external definition. We pass ExternalLinkage since that is only 8344 // used when the GUID must be computed from Name, and in that case 8345 // the symbol must have external linkage. 8346 addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID, 8347 nullptr); 8348 return false; 8349 } 8350 8351 // Have a list of summaries 8352 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") || 8353 parseToken(lltok::colon, "expected ':' here") || 8354 parseToken(lltok::lparen, "expected '(' here")) 8355 return true; 8356 do { 8357 switch (Lex.getKind()) { 8358 case lltok::kw_function: 8359 if (parseFunctionSummary(Name, GUID, ID)) 8360 return true; 8361 break; 8362 case lltok::kw_variable: 8363 if (parseVariableSummary(Name, GUID, ID)) 8364 return true; 8365 break; 8366 case lltok::kw_alias: 8367 if (parseAliasSummary(Name, GUID, ID)) 8368 return true; 8369 break; 8370 default: 8371 return error(Lex.getLoc(), "expected summary type"); 8372 } 8373 } while (EatIfPresent(lltok::comma)); 8374 8375 if (parseToken(lltok::rparen, "expected ')' here") || 8376 parseToken(lltok::rparen, "expected ')' here")) 8377 return true; 8378 8379 return false; 8380 } 8381 8382 /// FunctionSummary 8383 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags 8384 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]? 8385 /// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]? 8386 /// [',' OptionalRefs]? ')' 8387 bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID, 8388 unsigned ID) { 8389 assert(Lex.getKind() == lltok::kw_function); 8390 Lex.Lex(); 8391 8392 StringRef ModulePath; 8393 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8394 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility, 8395 /*NotEligibleToImport=*/false, 8396 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8397 unsigned InstCount; 8398 std::vector<FunctionSummary::EdgeTy> Calls; 8399 FunctionSummary::TypeIdInfo TypeIdInfo; 8400 std::vector<FunctionSummary::ParamAccess> ParamAccesses; 8401 std::vector<ValueInfo> Refs; 8402 // Default is all-zeros (conservative values). 8403 FunctionSummary::FFlags FFlags = {}; 8404 if (parseToken(lltok::colon, "expected ':' here") || 8405 parseToken(lltok::lparen, "expected '(' here") || 8406 parseModuleReference(ModulePath) || 8407 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 8408 parseToken(lltok::comma, "expected ',' here") || 8409 parseToken(lltok::kw_insts, "expected 'insts' here") || 8410 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount)) 8411 return true; 8412 8413 // parse optional fields 8414 while (EatIfPresent(lltok::comma)) { 8415 switch (Lex.getKind()) { 8416 case lltok::kw_funcFlags: 8417 if (parseOptionalFFlags(FFlags)) 8418 return true; 8419 break; 8420 case lltok::kw_calls: 8421 if (parseOptionalCalls(Calls)) 8422 return true; 8423 break; 8424 case lltok::kw_typeIdInfo: 8425 if (parseOptionalTypeIdInfo(TypeIdInfo)) 8426 return true; 8427 break; 8428 case lltok::kw_refs: 8429 if (parseOptionalRefs(Refs)) 8430 return true; 8431 break; 8432 case lltok::kw_params: 8433 if (parseOptionalParamAccesses(ParamAccesses)) 8434 return true; 8435 break; 8436 default: 8437 return error(Lex.getLoc(), "expected optional function summary field"); 8438 } 8439 } 8440 8441 if (parseToken(lltok::rparen, "expected ')' here")) 8442 return true; 8443 8444 auto FS = std::make_unique<FunctionSummary>( 8445 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs), 8446 std::move(Calls), std::move(TypeIdInfo.TypeTests), 8447 std::move(TypeIdInfo.TypeTestAssumeVCalls), 8448 std::move(TypeIdInfo.TypeCheckedLoadVCalls), 8449 std::move(TypeIdInfo.TypeTestAssumeConstVCalls), 8450 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls), 8451 std::move(ParamAccesses)); 8452 8453 FS->setModulePath(ModulePath); 8454 8455 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8456 ID, std::move(FS)); 8457 8458 return false; 8459 } 8460 8461 /// VariableSummary 8462 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags 8463 /// [',' OptionalRefs]? ')' 8464 bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID, 8465 unsigned ID) { 8466 assert(Lex.getKind() == lltok::kw_variable); 8467 Lex.Lex(); 8468 8469 StringRef ModulePath; 8470 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8471 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility, 8472 /*NotEligibleToImport=*/false, 8473 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8474 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false, 8475 /* WriteOnly */ false, 8476 /* Constant */ false, 8477 GlobalObject::VCallVisibilityPublic); 8478 std::vector<ValueInfo> Refs; 8479 VTableFuncList VTableFuncs; 8480 if (parseToken(lltok::colon, "expected ':' here") || 8481 parseToken(lltok::lparen, "expected '(' here") || 8482 parseModuleReference(ModulePath) || 8483 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 8484 parseToken(lltok::comma, "expected ',' here") || 8485 parseGVarFlags(GVarFlags)) 8486 return true; 8487 8488 // parse optional fields 8489 while (EatIfPresent(lltok::comma)) { 8490 switch (Lex.getKind()) { 8491 case lltok::kw_vTableFuncs: 8492 if (parseOptionalVTableFuncs(VTableFuncs)) 8493 return true; 8494 break; 8495 case lltok::kw_refs: 8496 if (parseOptionalRefs(Refs)) 8497 return true; 8498 break; 8499 default: 8500 return error(Lex.getLoc(), "expected optional variable summary field"); 8501 } 8502 } 8503 8504 if (parseToken(lltok::rparen, "expected ')' here")) 8505 return true; 8506 8507 auto GS = 8508 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs)); 8509 8510 GS->setModulePath(ModulePath); 8511 GS->setVTableFuncs(std::move(VTableFuncs)); 8512 8513 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8514 ID, std::move(GS)); 8515 8516 return false; 8517 } 8518 8519 /// AliasSummary 8520 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ',' 8521 /// 'aliasee' ':' GVReference ')' 8522 bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID, 8523 unsigned ID) { 8524 assert(Lex.getKind() == lltok::kw_alias); 8525 LocTy Loc = Lex.getLoc(); 8526 Lex.Lex(); 8527 8528 StringRef ModulePath; 8529 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8530 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility, 8531 /*NotEligibleToImport=*/false, 8532 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8533 if (parseToken(lltok::colon, "expected ':' here") || 8534 parseToken(lltok::lparen, "expected '(' here") || 8535 parseModuleReference(ModulePath) || 8536 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 8537 parseToken(lltok::comma, "expected ',' here") || 8538 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") || 8539 parseToken(lltok::colon, "expected ':' here")) 8540 return true; 8541 8542 ValueInfo AliaseeVI; 8543 unsigned GVId; 8544 if (parseGVReference(AliaseeVI, GVId)) 8545 return true; 8546 8547 if (parseToken(lltok::rparen, "expected ')' here")) 8548 return true; 8549 8550 auto AS = std::make_unique<AliasSummary>(GVFlags); 8551 8552 AS->setModulePath(ModulePath); 8553 8554 // Record forward reference if the aliasee is not parsed yet. 8555 if (AliaseeVI.getRef() == FwdVIRef) { 8556 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc); 8557 } else { 8558 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath); 8559 assert(Summary && "Aliasee must be a definition"); 8560 AS->setAliasee(AliaseeVI, Summary); 8561 } 8562 8563 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8564 ID, std::move(AS)); 8565 8566 return false; 8567 } 8568 8569 /// Flag 8570 /// ::= [0|1] 8571 bool LLParser::parseFlag(unsigned &Val) { 8572 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 8573 return tokError("expected integer"); 8574 Val = (unsigned)Lex.getAPSIntVal().getBoolValue(); 8575 Lex.Lex(); 8576 return false; 8577 } 8578 8579 /// OptionalFFlags 8580 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]? 8581 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]? 8582 /// [',' 'returnDoesNotAlias' ':' Flag]? ')' 8583 /// [',' 'noInline' ':' Flag]? ')' 8584 /// [',' 'alwaysInline' ':' Flag]? ')' 8585 /// [',' 'noUnwind' ':' Flag]? ')' 8586 /// [',' 'mayThrow' ':' Flag]? ')' 8587 /// [',' 'hasUnknownCall' ':' Flag]? ')' 8588 /// [',' 'mustBeUnreachable' ':' Flag]? ')' 8589 8590 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) { 8591 assert(Lex.getKind() == lltok::kw_funcFlags); 8592 Lex.Lex(); 8593 8594 if (parseToken(lltok::colon, "expected ':' in funcFlags") || 8595 parseToken(lltok::lparen, "expected '(' in funcFlags")) 8596 return true; 8597 8598 do { 8599 unsigned Val = 0; 8600 switch (Lex.getKind()) { 8601 case lltok::kw_readNone: 8602 Lex.Lex(); 8603 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8604 return true; 8605 FFlags.ReadNone = Val; 8606 break; 8607 case lltok::kw_readOnly: 8608 Lex.Lex(); 8609 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8610 return true; 8611 FFlags.ReadOnly = Val; 8612 break; 8613 case lltok::kw_noRecurse: 8614 Lex.Lex(); 8615 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8616 return true; 8617 FFlags.NoRecurse = Val; 8618 break; 8619 case lltok::kw_returnDoesNotAlias: 8620 Lex.Lex(); 8621 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8622 return true; 8623 FFlags.ReturnDoesNotAlias = Val; 8624 break; 8625 case lltok::kw_noInline: 8626 Lex.Lex(); 8627 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8628 return true; 8629 FFlags.NoInline = Val; 8630 break; 8631 case lltok::kw_alwaysInline: 8632 Lex.Lex(); 8633 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8634 return true; 8635 FFlags.AlwaysInline = Val; 8636 break; 8637 case lltok::kw_noUnwind: 8638 Lex.Lex(); 8639 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8640 return true; 8641 FFlags.NoUnwind = Val; 8642 break; 8643 case lltok::kw_mayThrow: 8644 Lex.Lex(); 8645 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8646 return true; 8647 FFlags.MayThrow = Val; 8648 break; 8649 case lltok::kw_hasUnknownCall: 8650 Lex.Lex(); 8651 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8652 return true; 8653 FFlags.HasUnknownCall = Val; 8654 break; 8655 case lltok::kw_mustBeUnreachable: 8656 Lex.Lex(); 8657 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8658 return true; 8659 FFlags.MustBeUnreachable = Val; 8660 break; 8661 default: 8662 return error(Lex.getLoc(), "expected function flag type"); 8663 } 8664 } while (EatIfPresent(lltok::comma)); 8665 8666 if (parseToken(lltok::rparen, "expected ')' in funcFlags")) 8667 return true; 8668 8669 return false; 8670 } 8671 8672 /// OptionalCalls 8673 /// := 'calls' ':' '(' Call [',' Call]* ')' 8674 /// Call ::= '(' 'callee' ':' GVReference 8675 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')' 8676 bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) { 8677 assert(Lex.getKind() == lltok::kw_calls); 8678 Lex.Lex(); 8679 8680 if (parseToken(lltok::colon, "expected ':' in calls") || 8681 parseToken(lltok::lparen, "expected '(' in calls")) 8682 return true; 8683 8684 IdToIndexMapType IdToIndexMap; 8685 // parse each call edge 8686 do { 8687 ValueInfo VI; 8688 if (parseToken(lltok::lparen, "expected '(' in call") || 8689 parseToken(lltok::kw_callee, "expected 'callee' in call") || 8690 parseToken(lltok::colon, "expected ':'")) 8691 return true; 8692 8693 LocTy Loc = Lex.getLoc(); 8694 unsigned GVId; 8695 if (parseGVReference(VI, GVId)) 8696 return true; 8697 8698 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 8699 unsigned RelBF = 0; 8700 if (EatIfPresent(lltok::comma)) { 8701 // Expect either hotness or relbf 8702 if (EatIfPresent(lltok::kw_hotness)) { 8703 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness)) 8704 return true; 8705 } else { 8706 if (parseToken(lltok::kw_relbf, "expected relbf") || 8707 parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF)) 8708 return true; 8709 } 8710 } 8711 // Keep track of the Call array index needing a forward reference. 8712 // We will save the location of the ValueInfo needing an update, but 8713 // can only do so once the std::vector is finalized. 8714 if (VI.getRef() == FwdVIRef) 8715 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc)); 8716 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)}); 8717 8718 if (parseToken(lltok::rparen, "expected ')' in call")) 8719 return true; 8720 } while (EatIfPresent(lltok::comma)); 8721 8722 // Now that the Calls vector is finalized, it is safe to save the locations 8723 // of any forward GV references that need updating later. 8724 for (auto I : IdToIndexMap) { 8725 auto &Infos = ForwardRefValueInfos[I.first]; 8726 for (auto P : I.second) { 8727 assert(Calls[P.first].first.getRef() == FwdVIRef && 8728 "Forward referenced ValueInfo expected to be empty"); 8729 Infos.emplace_back(&Calls[P.first].first, P.second); 8730 } 8731 } 8732 8733 if (parseToken(lltok::rparen, "expected ')' in calls")) 8734 return true; 8735 8736 return false; 8737 } 8738 8739 /// Hotness 8740 /// := ('unknown'|'cold'|'none'|'hot'|'critical') 8741 bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) { 8742 switch (Lex.getKind()) { 8743 case lltok::kw_unknown: 8744 Hotness = CalleeInfo::HotnessType::Unknown; 8745 break; 8746 case lltok::kw_cold: 8747 Hotness = CalleeInfo::HotnessType::Cold; 8748 break; 8749 case lltok::kw_none: 8750 Hotness = CalleeInfo::HotnessType::None; 8751 break; 8752 case lltok::kw_hot: 8753 Hotness = CalleeInfo::HotnessType::Hot; 8754 break; 8755 case lltok::kw_critical: 8756 Hotness = CalleeInfo::HotnessType::Critical; 8757 break; 8758 default: 8759 return error(Lex.getLoc(), "invalid call edge hotness"); 8760 } 8761 Lex.Lex(); 8762 return false; 8763 } 8764 8765 /// OptionalVTableFuncs 8766 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')' 8767 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')' 8768 bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) { 8769 assert(Lex.getKind() == lltok::kw_vTableFuncs); 8770 Lex.Lex(); 8771 8772 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") || 8773 parseToken(lltok::lparen, "expected '(' in vTableFuncs")) 8774 return true; 8775 8776 IdToIndexMapType IdToIndexMap; 8777 // parse each virtual function pair 8778 do { 8779 ValueInfo VI; 8780 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") || 8781 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") || 8782 parseToken(lltok::colon, "expected ':'")) 8783 return true; 8784 8785 LocTy Loc = Lex.getLoc(); 8786 unsigned GVId; 8787 if (parseGVReference(VI, GVId)) 8788 return true; 8789 8790 uint64_t Offset; 8791 if (parseToken(lltok::comma, "expected comma") || 8792 parseToken(lltok::kw_offset, "expected offset") || 8793 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset)) 8794 return true; 8795 8796 // Keep track of the VTableFuncs array index needing a forward reference. 8797 // We will save the location of the ValueInfo needing an update, but 8798 // can only do so once the std::vector is finalized. 8799 if (VI == EmptyVI) 8800 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc)); 8801 VTableFuncs.push_back({VI, Offset}); 8802 8803 if (parseToken(lltok::rparen, "expected ')' in vTableFunc")) 8804 return true; 8805 } while (EatIfPresent(lltok::comma)); 8806 8807 // Now that the VTableFuncs vector is finalized, it is safe to save the 8808 // locations of any forward GV references that need updating later. 8809 for (auto I : IdToIndexMap) { 8810 auto &Infos = ForwardRefValueInfos[I.first]; 8811 for (auto P : I.second) { 8812 assert(VTableFuncs[P.first].FuncVI == EmptyVI && 8813 "Forward referenced ValueInfo expected to be empty"); 8814 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second); 8815 } 8816 } 8817 8818 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs")) 8819 return true; 8820 8821 return false; 8822 } 8823 8824 /// ParamNo := 'param' ':' UInt64 8825 bool LLParser::parseParamNo(uint64_t &ParamNo) { 8826 if (parseToken(lltok::kw_param, "expected 'param' here") || 8827 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo)) 8828 return true; 8829 return false; 8830 } 8831 8832 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']' 8833 bool LLParser::parseParamAccessOffset(ConstantRange &Range) { 8834 APSInt Lower; 8835 APSInt Upper; 8836 auto ParseAPSInt = [&](APSInt &Val) { 8837 if (Lex.getKind() != lltok::APSInt) 8838 return tokError("expected integer"); 8839 Val = Lex.getAPSIntVal(); 8840 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth); 8841 Val.setIsSigned(true); 8842 Lex.Lex(); 8843 return false; 8844 }; 8845 if (parseToken(lltok::kw_offset, "expected 'offset' here") || 8846 parseToken(lltok::colon, "expected ':' here") || 8847 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) || 8848 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) || 8849 parseToken(lltok::rsquare, "expected ']' here")) 8850 return true; 8851 8852 ++Upper; 8853 Range = 8854 (Lower == Upper && !Lower.isMaxValue()) 8855 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth) 8856 : ConstantRange(Lower, Upper); 8857 8858 return false; 8859 } 8860 8861 /// ParamAccessCall 8862 /// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')' 8863 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call, 8864 IdLocListType &IdLocList) { 8865 if (parseToken(lltok::lparen, "expected '(' here") || 8866 parseToken(lltok::kw_callee, "expected 'callee' here") || 8867 parseToken(lltok::colon, "expected ':' here")) 8868 return true; 8869 8870 unsigned GVId; 8871 ValueInfo VI; 8872 LocTy Loc = Lex.getLoc(); 8873 if (parseGVReference(VI, GVId)) 8874 return true; 8875 8876 Call.Callee = VI; 8877 IdLocList.emplace_back(GVId, Loc); 8878 8879 if (parseToken(lltok::comma, "expected ',' here") || 8880 parseParamNo(Call.ParamNo) || 8881 parseToken(lltok::comma, "expected ',' here") || 8882 parseParamAccessOffset(Call.Offsets)) 8883 return true; 8884 8885 if (parseToken(lltok::rparen, "expected ')' here")) 8886 return true; 8887 8888 return false; 8889 } 8890 8891 /// ParamAccess 8892 /// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')' 8893 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')' 8894 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param, 8895 IdLocListType &IdLocList) { 8896 if (parseToken(lltok::lparen, "expected '(' here") || 8897 parseParamNo(Param.ParamNo) || 8898 parseToken(lltok::comma, "expected ',' here") || 8899 parseParamAccessOffset(Param.Use)) 8900 return true; 8901 8902 if (EatIfPresent(lltok::comma)) { 8903 if (parseToken(lltok::kw_calls, "expected 'calls' here") || 8904 parseToken(lltok::colon, "expected ':' here") || 8905 parseToken(lltok::lparen, "expected '(' here")) 8906 return true; 8907 do { 8908 FunctionSummary::ParamAccess::Call Call; 8909 if (parseParamAccessCall(Call, IdLocList)) 8910 return true; 8911 Param.Calls.push_back(Call); 8912 } while (EatIfPresent(lltok::comma)); 8913 8914 if (parseToken(lltok::rparen, "expected ')' here")) 8915 return true; 8916 } 8917 8918 if (parseToken(lltok::rparen, "expected ')' here")) 8919 return true; 8920 8921 return false; 8922 } 8923 8924 /// OptionalParamAccesses 8925 /// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')' 8926 bool LLParser::parseOptionalParamAccesses( 8927 std::vector<FunctionSummary::ParamAccess> &Params) { 8928 assert(Lex.getKind() == lltok::kw_params); 8929 Lex.Lex(); 8930 8931 if (parseToken(lltok::colon, "expected ':' here") || 8932 parseToken(lltok::lparen, "expected '(' here")) 8933 return true; 8934 8935 IdLocListType VContexts; 8936 size_t CallsNum = 0; 8937 do { 8938 FunctionSummary::ParamAccess ParamAccess; 8939 if (parseParamAccess(ParamAccess, VContexts)) 8940 return true; 8941 CallsNum += ParamAccess.Calls.size(); 8942 assert(VContexts.size() == CallsNum); 8943 (void)CallsNum; 8944 Params.emplace_back(std::move(ParamAccess)); 8945 } while (EatIfPresent(lltok::comma)); 8946 8947 if (parseToken(lltok::rparen, "expected ')' here")) 8948 return true; 8949 8950 // Now that the Params is finalized, it is safe to save the locations 8951 // of any forward GV references that need updating later. 8952 IdLocListType::const_iterator ItContext = VContexts.begin(); 8953 for (auto &PA : Params) { 8954 for (auto &C : PA.Calls) { 8955 if (C.Callee.getRef() == FwdVIRef) 8956 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee, 8957 ItContext->second); 8958 ++ItContext; 8959 } 8960 } 8961 assert(ItContext == VContexts.end()); 8962 8963 return false; 8964 } 8965 8966 /// OptionalRefs 8967 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')' 8968 bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) { 8969 assert(Lex.getKind() == lltok::kw_refs); 8970 Lex.Lex(); 8971 8972 if (parseToken(lltok::colon, "expected ':' in refs") || 8973 parseToken(lltok::lparen, "expected '(' in refs")) 8974 return true; 8975 8976 struct ValueContext { 8977 ValueInfo VI; 8978 unsigned GVId; 8979 LocTy Loc; 8980 }; 8981 std::vector<ValueContext> VContexts; 8982 // parse each ref edge 8983 do { 8984 ValueContext VC; 8985 VC.Loc = Lex.getLoc(); 8986 if (parseGVReference(VC.VI, VC.GVId)) 8987 return true; 8988 VContexts.push_back(VC); 8989 } while (EatIfPresent(lltok::comma)); 8990 8991 // Sort value contexts so that ones with writeonly 8992 // and readonly ValueInfo are at the end of VContexts vector. 8993 // See FunctionSummary::specialRefCounts() 8994 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) { 8995 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier(); 8996 }); 8997 8998 IdToIndexMapType IdToIndexMap; 8999 for (auto &VC : VContexts) { 9000 // Keep track of the Refs array index needing a forward reference. 9001 // We will save the location of the ValueInfo needing an update, but 9002 // can only do so once the std::vector is finalized. 9003 if (VC.VI.getRef() == FwdVIRef) 9004 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc)); 9005 Refs.push_back(VC.VI); 9006 } 9007 9008 // Now that the Refs vector is finalized, it is safe to save the locations 9009 // of any forward GV references that need updating later. 9010 for (auto I : IdToIndexMap) { 9011 auto &Infos = ForwardRefValueInfos[I.first]; 9012 for (auto P : I.second) { 9013 assert(Refs[P.first].getRef() == FwdVIRef && 9014 "Forward referenced ValueInfo expected to be empty"); 9015 Infos.emplace_back(&Refs[P.first], P.second); 9016 } 9017 } 9018 9019 if (parseToken(lltok::rparen, "expected ')' in refs")) 9020 return true; 9021 9022 return false; 9023 } 9024 9025 /// OptionalTypeIdInfo 9026 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]? 9027 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]? 9028 /// [',' TypeCheckedLoadConstVCalls]? ')' 9029 bool LLParser::parseOptionalTypeIdInfo( 9030 FunctionSummary::TypeIdInfo &TypeIdInfo) { 9031 assert(Lex.getKind() == lltok::kw_typeIdInfo); 9032 Lex.Lex(); 9033 9034 if (parseToken(lltok::colon, "expected ':' here") || 9035 parseToken(lltok::lparen, "expected '(' in typeIdInfo")) 9036 return true; 9037 9038 do { 9039 switch (Lex.getKind()) { 9040 case lltok::kw_typeTests: 9041 if (parseTypeTests(TypeIdInfo.TypeTests)) 9042 return true; 9043 break; 9044 case lltok::kw_typeTestAssumeVCalls: 9045 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls, 9046 TypeIdInfo.TypeTestAssumeVCalls)) 9047 return true; 9048 break; 9049 case lltok::kw_typeCheckedLoadVCalls: 9050 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls, 9051 TypeIdInfo.TypeCheckedLoadVCalls)) 9052 return true; 9053 break; 9054 case lltok::kw_typeTestAssumeConstVCalls: 9055 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls, 9056 TypeIdInfo.TypeTestAssumeConstVCalls)) 9057 return true; 9058 break; 9059 case lltok::kw_typeCheckedLoadConstVCalls: 9060 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls, 9061 TypeIdInfo.TypeCheckedLoadConstVCalls)) 9062 return true; 9063 break; 9064 default: 9065 return error(Lex.getLoc(), "invalid typeIdInfo list type"); 9066 } 9067 } while (EatIfPresent(lltok::comma)); 9068 9069 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo")) 9070 return true; 9071 9072 return false; 9073 } 9074 9075 /// TypeTests 9076 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64) 9077 /// [',' (SummaryID | UInt64)]* ')' 9078 bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) { 9079 assert(Lex.getKind() == lltok::kw_typeTests); 9080 Lex.Lex(); 9081 9082 if (parseToken(lltok::colon, "expected ':' here") || 9083 parseToken(lltok::lparen, "expected '(' in typeIdInfo")) 9084 return true; 9085 9086 IdToIndexMapType IdToIndexMap; 9087 do { 9088 GlobalValue::GUID GUID = 0; 9089 if (Lex.getKind() == lltok::SummaryID) { 9090 unsigned ID = Lex.getUIntVal(); 9091 LocTy Loc = Lex.getLoc(); 9092 // Keep track of the TypeTests array index needing a forward reference. 9093 // We will save the location of the GUID needing an update, but 9094 // can only do so once the std::vector is finalized. 9095 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc)); 9096 Lex.Lex(); 9097 } else if (parseUInt64(GUID)) 9098 return true; 9099 TypeTests.push_back(GUID); 9100 } while (EatIfPresent(lltok::comma)); 9101 9102 // Now that the TypeTests vector is finalized, it is safe to save the 9103 // locations of any forward GV references that need updating later. 9104 for (auto I : IdToIndexMap) { 9105 auto &Ids = ForwardRefTypeIds[I.first]; 9106 for (auto P : I.second) { 9107 assert(TypeTests[P.first] == 0 && 9108 "Forward referenced type id GUID expected to be 0"); 9109 Ids.emplace_back(&TypeTests[P.first], P.second); 9110 } 9111 } 9112 9113 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo")) 9114 return true; 9115 9116 return false; 9117 } 9118 9119 /// VFuncIdList 9120 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')' 9121 bool LLParser::parseVFuncIdList( 9122 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) { 9123 assert(Lex.getKind() == Kind); 9124 Lex.Lex(); 9125 9126 if (parseToken(lltok::colon, "expected ':' here") || 9127 parseToken(lltok::lparen, "expected '(' here")) 9128 return true; 9129 9130 IdToIndexMapType IdToIndexMap; 9131 do { 9132 FunctionSummary::VFuncId VFuncId; 9133 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size())) 9134 return true; 9135 VFuncIdList.push_back(VFuncId); 9136 } while (EatIfPresent(lltok::comma)); 9137 9138 if (parseToken(lltok::rparen, "expected ')' here")) 9139 return true; 9140 9141 // Now that the VFuncIdList vector is finalized, it is safe to save the 9142 // locations of any forward GV references that need updating later. 9143 for (auto I : IdToIndexMap) { 9144 auto &Ids = ForwardRefTypeIds[I.first]; 9145 for (auto P : I.second) { 9146 assert(VFuncIdList[P.first].GUID == 0 && 9147 "Forward referenced type id GUID expected to be 0"); 9148 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second); 9149 } 9150 } 9151 9152 return false; 9153 } 9154 9155 /// ConstVCallList 9156 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')' 9157 bool LLParser::parseConstVCallList( 9158 lltok::Kind Kind, 9159 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) { 9160 assert(Lex.getKind() == Kind); 9161 Lex.Lex(); 9162 9163 if (parseToken(lltok::colon, "expected ':' here") || 9164 parseToken(lltok::lparen, "expected '(' here")) 9165 return true; 9166 9167 IdToIndexMapType IdToIndexMap; 9168 do { 9169 FunctionSummary::ConstVCall ConstVCall; 9170 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size())) 9171 return true; 9172 ConstVCallList.push_back(ConstVCall); 9173 } while (EatIfPresent(lltok::comma)); 9174 9175 if (parseToken(lltok::rparen, "expected ')' here")) 9176 return true; 9177 9178 // Now that the ConstVCallList vector is finalized, it is safe to save the 9179 // locations of any forward GV references that need updating later. 9180 for (auto I : IdToIndexMap) { 9181 auto &Ids = ForwardRefTypeIds[I.first]; 9182 for (auto P : I.second) { 9183 assert(ConstVCallList[P.first].VFunc.GUID == 0 && 9184 "Forward referenced type id GUID expected to be 0"); 9185 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second); 9186 } 9187 } 9188 9189 return false; 9190 } 9191 9192 /// ConstVCall 9193 /// ::= '(' VFuncId ',' Args ')' 9194 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall, 9195 IdToIndexMapType &IdToIndexMap, unsigned Index) { 9196 if (parseToken(lltok::lparen, "expected '(' here") || 9197 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index)) 9198 return true; 9199 9200 if (EatIfPresent(lltok::comma)) 9201 if (parseArgs(ConstVCall.Args)) 9202 return true; 9203 9204 if (parseToken(lltok::rparen, "expected ')' here")) 9205 return true; 9206 9207 return false; 9208 } 9209 9210 /// VFuncId 9211 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ',' 9212 /// 'offset' ':' UInt64 ')' 9213 bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId, 9214 IdToIndexMapType &IdToIndexMap, unsigned Index) { 9215 assert(Lex.getKind() == lltok::kw_vFuncId); 9216 Lex.Lex(); 9217 9218 if (parseToken(lltok::colon, "expected ':' here") || 9219 parseToken(lltok::lparen, "expected '(' here")) 9220 return true; 9221 9222 if (Lex.getKind() == lltok::SummaryID) { 9223 VFuncId.GUID = 0; 9224 unsigned ID = Lex.getUIntVal(); 9225 LocTy Loc = Lex.getLoc(); 9226 // Keep track of the array index needing a forward reference. 9227 // We will save the location of the GUID needing an update, but 9228 // can only do so once the caller's std::vector is finalized. 9229 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc)); 9230 Lex.Lex(); 9231 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") || 9232 parseToken(lltok::colon, "expected ':' here") || 9233 parseUInt64(VFuncId.GUID)) 9234 return true; 9235 9236 if (parseToken(lltok::comma, "expected ',' here") || 9237 parseToken(lltok::kw_offset, "expected 'offset' here") || 9238 parseToken(lltok::colon, "expected ':' here") || 9239 parseUInt64(VFuncId.Offset) || 9240 parseToken(lltok::rparen, "expected ')' here")) 9241 return true; 9242 9243 return false; 9244 } 9245 9246 /// GVFlags 9247 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ',' 9248 /// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ',' 9249 /// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ',' 9250 /// 'canAutoHide' ':' Flag ',' ')' 9251 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) { 9252 assert(Lex.getKind() == lltok::kw_flags); 9253 Lex.Lex(); 9254 9255 if (parseToken(lltok::colon, "expected ':' here") || 9256 parseToken(lltok::lparen, "expected '(' here")) 9257 return true; 9258 9259 do { 9260 unsigned Flag = 0; 9261 switch (Lex.getKind()) { 9262 case lltok::kw_linkage: 9263 Lex.Lex(); 9264 if (parseToken(lltok::colon, "expected ':'")) 9265 return true; 9266 bool HasLinkage; 9267 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage); 9268 assert(HasLinkage && "Linkage not optional in summary entry"); 9269 Lex.Lex(); 9270 break; 9271 case lltok::kw_visibility: 9272 Lex.Lex(); 9273 if (parseToken(lltok::colon, "expected ':'")) 9274 return true; 9275 parseOptionalVisibility(Flag); 9276 GVFlags.Visibility = Flag; 9277 break; 9278 case lltok::kw_notEligibleToImport: 9279 Lex.Lex(); 9280 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9281 return true; 9282 GVFlags.NotEligibleToImport = Flag; 9283 break; 9284 case lltok::kw_live: 9285 Lex.Lex(); 9286 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9287 return true; 9288 GVFlags.Live = Flag; 9289 break; 9290 case lltok::kw_dsoLocal: 9291 Lex.Lex(); 9292 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9293 return true; 9294 GVFlags.DSOLocal = Flag; 9295 break; 9296 case lltok::kw_canAutoHide: 9297 Lex.Lex(); 9298 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9299 return true; 9300 GVFlags.CanAutoHide = Flag; 9301 break; 9302 default: 9303 return error(Lex.getLoc(), "expected gv flag type"); 9304 } 9305 } while (EatIfPresent(lltok::comma)); 9306 9307 if (parseToken(lltok::rparen, "expected ')' here")) 9308 return true; 9309 9310 return false; 9311 } 9312 9313 /// GVarFlags 9314 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag 9315 /// ',' 'writeonly' ':' Flag 9316 /// ',' 'constant' ':' Flag ')' 9317 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) { 9318 assert(Lex.getKind() == lltok::kw_varFlags); 9319 Lex.Lex(); 9320 9321 if (parseToken(lltok::colon, "expected ':' here") || 9322 parseToken(lltok::lparen, "expected '(' here")) 9323 return true; 9324 9325 auto ParseRest = [this](unsigned int &Val) { 9326 Lex.Lex(); 9327 if (parseToken(lltok::colon, "expected ':'")) 9328 return true; 9329 return parseFlag(Val); 9330 }; 9331 9332 do { 9333 unsigned Flag = 0; 9334 switch (Lex.getKind()) { 9335 case lltok::kw_readonly: 9336 if (ParseRest(Flag)) 9337 return true; 9338 GVarFlags.MaybeReadOnly = Flag; 9339 break; 9340 case lltok::kw_writeonly: 9341 if (ParseRest(Flag)) 9342 return true; 9343 GVarFlags.MaybeWriteOnly = Flag; 9344 break; 9345 case lltok::kw_constant: 9346 if (ParseRest(Flag)) 9347 return true; 9348 GVarFlags.Constant = Flag; 9349 break; 9350 case lltok::kw_vcall_visibility: 9351 if (ParseRest(Flag)) 9352 return true; 9353 GVarFlags.VCallVisibility = Flag; 9354 break; 9355 default: 9356 return error(Lex.getLoc(), "expected gvar flag type"); 9357 } 9358 } while (EatIfPresent(lltok::comma)); 9359 return parseToken(lltok::rparen, "expected ')' here"); 9360 } 9361 9362 /// ModuleReference 9363 /// ::= 'module' ':' UInt 9364 bool LLParser::parseModuleReference(StringRef &ModulePath) { 9365 // parse module id. 9366 if (parseToken(lltok::kw_module, "expected 'module' here") || 9367 parseToken(lltok::colon, "expected ':' here") || 9368 parseToken(lltok::SummaryID, "expected module ID")) 9369 return true; 9370 9371 unsigned ModuleID = Lex.getUIntVal(); 9372 auto I = ModuleIdMap.find(ModuleID); 9373 // We should have already parsed all module IDs 9374 assert(I != ModuleIdMap.end()); 9375 ModulePath = I->second; 9376 return false; 9377 } 9378 9379 /// GVReference 9380 /// ::= SummaryID 9381 bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) { 9382 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly); 9383 if (!ReadOnly) 9384 WriteOnly = EatIfPresent(lltok::kw_writeonly); 9385 if (parseToken(lltok::SummaryID, "expected GV ID")) 9386 return true; 9387 9388 GVId = Lex.getUIntVal(); 9389 // Check if we already have a VI for this GV 9390 if (GVId < NumberedValueInfos.size()) { 9391 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef); 9392 VI = NumberedValueInfos[GVId]; 9393 } else 9394 // We will create a forward reference to the stored location. 9395 VI = ValueInfo(false, FwdVIRef); 9396 9397 if (ReadOnly) 9398 VI.setReadOnly(); 9399 if (WriteOnly) 9400 VI.setWriteOnly(); 9401 return false; 9402 } 9403