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