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