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