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