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