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