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