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