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