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