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