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