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