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