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