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