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