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