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