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