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