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