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 = 3592 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0; 3593 3594 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 3595 for (Constant *Val : Indices) { 3596 Type *ValTy = Val->getType(); 3597 if (!ValTy->isIntOrIntVectorTy()) 3598 return Error(ID.Loc, "getelementptr index must be an integer"); 3599 if (ValTy->isVectorTy()) { 3600 unsigned ValNumEl = ValTy->getVectorNumElements(); 3601 if (GEPWidth && (ValNumEl != GEPWidth)) 3602 return Error( 3603 ID.Loc, 3604 "getelementptr vector index has a wrong number of elements"); 3605 // GEPWidth may have been unknown because the base is a scalar, 3606 // but it is known now. 3607 GEPWidth = ValNumEl; 3608 } 3609 } 3610 3611 SmallPtrSet<Type*, 4> Visited; 3612 if (!Indices.empty() && !Ty->isSized(&Visited)) 3613 return Error(ID.Loc, "base element of getelementptr must be sized"); 3614 3615 if (!GetElementPtrInst::getIndexedType(Ty, Indices)) 3616 return Error(ID.Loc, "invalid getelementptr indices"); 3617 3618 if (InRangeOp) { 3619 if (*InRangeOp == 0) 3620 return Error(ID.Loc, 3621 "inrange keyword may not appear on pointer operand"); 3622 --*InRangeOp; 3623 } 3624 3625 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, 3626 InBounds, InRangeOp); 3627 } else if (Opc == Instruction::Select) { 3628 if (Elts.size() != 3) 3629 return Error(ID.Loc, "expected three operands to select"); 3630 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1], 3631 Elts[2])) 3632 return Error(ID.Loc, Reason); 3633 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]); 3634 } else if (Opc == Instruction::ShuffleVector) { 3635 if (Elts.size() != 3) 3636 return Error(ID.Loc, "expected three operands to shufflevector"); 3637 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 3638 return Error(ID.Loc, "invalid operands to shufflevector"); 3639 ID.ConstantVal = 3640 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]); 3641 } else if (Opc == Instruction::ExtractElement) { 3642 if (Elts.size() != 2) 3643 return Error(ID.Loc, "expected two operands to extractelement"); 3644 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1])) 3645 return Error(ID.Loc, "invalid extractelement operands"); 3646 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]); 3647 } else { 3648 assert(Opc == Instruction::InsertElement && "Unknown opcode"); 3649 if (Elts.size() != 3) 3650 return Error(ID.Loc, "expected three operands to insertelement"); 3651 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 3652 return Error(ID.Loc, "invalid insertelement operands"); 3653 ID.ConstantVal = 3654 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]); 3655 } 3656 3657 ID.Kind = ValID::t_Constant; 3658 return false; 3659 } 3660 } 3661 3662 Lex.Lex(); 3663 return false; 3664 } 3665 3666 /// ParseGlobalValue - Parse a global value with the specified type. 3667 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) { 3668 C = nullptr; 3669 ValID ID; 3670 Value *V = nullptr; 3671 bool Parsed = ParseValID(ID) || 3672 ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false); 3673 if (V && !(C = dyn_cast<Constant>(V))) 3674 return Error(ID.Loc, "global values must be constants"); 3675 return Parsed; 3676 } 3677 3678 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) { 3679 Type *Ty = nullptr; 3680 return ParseType(Ty) || 3681 ParseGlobalValue(Ty, V); 3682 } 3683 3684 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) { 3685 C = nullptr; 3686 3687 LocTy KwLoc = Lex.getLoc(); 3688 if (!EatIfPresent(lltok::kw_comdat)) 3689 return false; 3690 3691 if (EatIfPresent(lltok::lparen)) { 3692 if (Lex.getKind() != lltok::ComdatVar) 3693 return TokError("expected comdat variable"); 3694 C = getComdat(Lex.getStrVal(), Lex.getLoc()); 3695 Lex.Lex(); 3696 if (ParseToken(lltok::rparen, "expected ')' after comdat var")) 3697 return true; 3698 } else { 3699 if (GlobalName.empty()) 3700 return TokError("comdat cannot be unnamed"); 3701 C = getComdat(std::string(GlobalName), KwLoc); 3702 } 3703 3704 return false; 3705 } 3706 3707 /// ParseGlobalValueVector 3708 /// ::= /*empty*/ 3709 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)* 3710 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts, 3711 Optional<unsigned> *InRangeOp) { 3712 // Empty list. 3713 if (Lex.getKind() == lltok::rbrace || 3714 Lex.getKind() == lltok::rsquare || 3715 Lex.getKind() == lltok::greater || 3716 Lex.getKind() == lltok::rparen) 3717 return false; 3718 3719 do { 3720 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange)) 3721 *InRangeOp = Elts.size(); 3722 3723 Constant *C; 3724 if (ParseGlobalTypeAndValue(C)) return true; 3725 Elts.push_back(C); 3726 } while (EatIfPresent(lltok::comma)); 3727 3728 return false; 3729 } 3730 3731 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) { 3732 SmallVector<Metadata *, 16> Elts; 3733 if (ParseMDNodeVector(Elts)) 3734 return true; 3735 3736 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts); 3737 return false; 3738 } 3739 3740 /// MDNode: 3741 /// ::= !{ ... } 3742 /// ::= !7 3743 /// ::= !DILocation(...) 3744 bool LLParser::ParseMDNode(MDNode *&N) { 3745 if (Lex.getKind() == lltok::MetadataVar) 3746 return ParseSpecializedMDNode(N); 3747 3748 return ParseToken(lltok::exclaim, "expected '!' here") || 3749 ParseMDNodeTail(N); 3750 } 3751 3752 bool LLParser::ParseMDNodeTail(MDNode *&N) { 3753 // !{ ... } 3754 if (Lex.getKind() == lltok::lbrace) 3755 return ParseMDTuple(N); 3756 3757 // !42 3758 return ParseMDNodeID(N); 3759 } 3760 3761 namespace { 3762 3763 /// Structure to represent an optional metadata field. 3764 template <class FieldTy> struct MDFieldImpl { 3765 typedef MDFieldImpl ImplTy; 3766 FieldTy Val; 3767 bool Seen; 3768 3769 void assign(FieldTy Val) { 3770 Seen = true; 3771 this->Val = std::move(Val); 3772 } 3773 3774 explicit MDFieldImpl(FieldTy Default) 3775 : Val(std::move(Default)), Seen(false) {} 3776 }; 3777 3778 /// Structure to represent an optional metadata field that 3779 /// can be of either type (A or B) and encapsulates the 3780 /// MD<typeofA>Field and MD<typeofB>Field structs, so not 3781 /// to reimplement the specifics for representing each Field. 3782 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl { 3783 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy; 3784 FieldTypeA A; 3785 FieldTypeB B; 3786 bool Seen; 3787 3788 enum { 3789 IsInvalid = 0, 3790 IsTypeA = 1, 3791 IsTypeB = 2 3792 } WhatIs; 3793 3794 void assign(FieldTypeA A) { 3795 Seen = true; 3796 this->A = std::move(A); 3797 WhatIs = IsTypeA; 3798 } 3799 3800 void assign(FieldTypeB B) { 3801 Seen = true; 3802 this->B = std::move(B); 3803 WhatIs = IsTypeB; 3804 } 3805 3806 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB) 3807 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false), 3808 WhatIs(IsInvalid) {} 3809 }; 3810 3811 struct MDUnsignedField : public MDFieldImpl<uint64_t> { 3812 uint64_t Max; 3813 3814 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX) 3815 : ImplTy(Default), Max(Max) {} 3816 }; 3817 3818 struct LineField : public MDUnsignedField { 3819 LineField() : MDUnsignedField(0, UINT32_MAX) {} 3820 }; 3821 3822 struct ColumnField : public MDUnsignedField { 3823 ColumnField() : MDUnsignedField(0, UINT16_MAX) {} 3824 }; 3825 3826 struct DwarfTagField : public MDUnsignedField { 3827 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {} 3828 DwarfTagField(dwarf::Tag DefaultTag) 3829 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {} 3830 }; 3831 3832 struct DwarfMacinfoTypeField : public MDUnsignedField { 3833 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {} 3834 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType) 3835 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {} 3836 }; 3837 3838 struct DwarfAttEncodingField : public MDUnsignedField { 3839 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {} 3840 }; 3841 3842 struct DwarfVirtualityField : public MDUnsignedField { 3843 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {} 3844 }; 3845 3846 struct DwarfLangField : public MDUnsignedField { 3847 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {} 3848 }; 3849 3850 struct DwarfCCField : public MDUnsignedField { 3851 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {} 3852 }; 3853 3854 struct EmissionKindField : public MDUnsignedField { 3855 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {} 3856 }; 3857 3858 struct NameTableKindField : public MDUnsignedField { 3859 NameTableKindField() 3860 : MDUnsignedField( 3861 0, (unsigned) 3862 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {} 3863 }; 3864 3865 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> { 3866 DIFlagField() : MDFieldImpl(DINode::FlagZero) {} 3867 }; 3868 3869 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> { 3870 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {} 3871 }; 3872 3873 struct MDSignedField : public MDFieldImpl<int64_t> { 3874 int64_t Min; 3875 int64_t Max; 3876 3877 MDSignedField(int64_t Default = 0) 3878 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {} 3879 MDSignedField(int64_t Default, int64_t Min, int64_t Max) 3880 : ImplTy(Default), Min(Min), Max(Max) {} 3881 }; 3882 3883 struct MDBoolField : public MDFieldImpl<bool> { 3884 MDBoolField(bool Default = false) : ImplTy(Default) {} 3885 }; 3886 3887 struct MDField : public MDFieldImpl<Metadata *> { 3888 bool AllowNull; 3889 3890 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {} 3891 }; 3892 3893 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> { 3894 MDConstant() : ImplTy(nullptr) {} 3895 }; 3896 3897 struct MDStringField : public MDFieldImpl<MDString *> { 3898 bool AllowEmpty; 3899 MDStringField(bool AllowEmpty = true) 3900 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {} 3901 }; 3902 3903 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> { 3904 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {} 3905 }; 3906 3907 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> { 3908 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {} 3909 }; 3910 3911 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> { 3912 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true) 3913 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {} 3914 3915 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max, 3916 bool AllowNull = true) 3917 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {} 3918 3919 bool isMDSignedField() const { return WhatIs == IsTypeA; } 3920 bool isMDField() const { return WhatIs == IsTypeB; } 3921 int64_t getMDSignedValue() const { 3922 assert(isMDSignedField() && "Wrong field type"); 3923 return A.Val; 3924 } 3925 Metadata *getMDFieldValue() const { 3926 assert(isMDField() && "Wrong field type"); 3927 return B.Val; 3928 } 3929 }; 3930 3931 struct MDSignedOrUnsignedField 3932 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> { 3933 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {} 3934 3935 bool isMDSignedField() const { return WhatIs == IsTypeA; } 3936 bool isMDUnsignedField() const { return WhatIs == IsTypeB; } 3937 int64_t getMDSignedValue() const { 3938 assert(isMDSignedField() && "Wrong field type"); 3939 return A.Val; 3940 } 3941 uint64_t getMDUnsignedValue() const { 3942 assert(isMDUnsignedField() && "Wrong field type"); 3943 return B.Val; 3944 } 3945 }; 3946 3947 } // end anonymous namespace 3948 3949 namespace llvm { 3950 3951 template <> 3952 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 3953 MDUnsignedField &Result) { 3954 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 3955 return TokError("expected unsigned integer"); 3956 3957 auto &U = Lex.getAPSIntVal(); 3958 if (U.ugt(Result.Max)) 3959 return TokError("value for '" + Name + "' too large, limit is " + 3960 Twine(Result.Max)); 3961 Result.assign(U.getZExtValue()); 3962 assert(Result.Val <= Result.Max && "Expected value in range"); 3963 Lex.Lex(); 3964 return false; 3965 } 3966 3967 template <> 3968 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) { 3969 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3970 } 3971 template <> 3972 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) { 3973 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3974 } 3975 3976 template <> 3977 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) { 3978 if (Lex.getKind() == lltok::APSInt) 3979 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3980 3981 if (Lex.getKind() != lltok::DwarfTag) 3982 return TokError("expected DWARF tag"); 3983 3984 unsigned Tag = dwarf::getTag(Lex.getStrVal()); 3985 if (Tag == dwarf::DW_TAG_invalid) 3986 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'"); 3987 assert(Tag <= Result.Max && "Expected valid DWARF tag"); 3988 3989 Result.assign(Tag); 3990 Lex.Lex(); 3991 return false; 3992 } 3993 3994 template <> 3995 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 3996 DwarfMacinfoTypeField &Result) { 3997 if (Lex.getKind() == lltok::APSInt) 3998 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3999 4000 if (Lex.getKind() != lltok::DwarfMacinfo) 4001 return TokError("expected DWARF macinfo type"); 4002 4003 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal()); 4004 if (Macinfo == dwarf::DW_MACINFO_invalid) 4005 return TokError( 4006 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'"); 4007 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type"); 4008 4009 Result.assign(Macinfo); 4010 Lex.Lex(); 4011 return false; 4012 } 4013 4014 template <> 4015 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 4016 DwarfVirtualityField &Result) { 4017 if (Lex.getKind() == lltok::APSInt) 4018 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4019 4020 if (Lex.getKind() != lltok::DwarfVirtuality) 4021 return TokError("expected DWARF virtuality code"); 4022 4023 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal()); 4024 if (Virtuality == dwarf::DW_VIRTUALITY_invalid) 4025 return TokError("invalid DWARF virtuality code" + Twine(" '") + 4026 Lex.getStrVal() + "'"); 4027 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code"); 4028 Result.assign(Virtuality); 4029 Lex.Lex(); 4030 return false; 4031 } 4032 4033 template <> 4034 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) { 4035 if (Lex.getKind() == lltok::APSInt) 4036 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4037 4038 if (Lex.getKind() != lltok::DwarfLang) 4039 return TokError("expected DWARF language"); 4040 4041 unsigned Lang = dwarf::getLanguage(Lex.getStrVal()); 4042 if (!Lang) 4043 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() + 4044 "'"); 4045 assert(Lang <= Result.Max && "Expected valid DWARF language"); 4046 Result.assign(Lang); 4047 Lex.Lex(); 4048 return false; 4049 } 4050 4051 template <> 4052 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) { 4053 if (Lex.getKind() == lltok::APSInt) 4054 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4055 4056 if (Lex.getKind() != lltok::DwarfCC) 4057 return TokError("expected DWARF calling convention"); 4058 4059 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal()); 4060 if (!CC) 4061 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() + 4062 "'"); 4063 assert(CC <= Result.Max && "Expected valid DWARF calling convention"); 4064 Result.assign(CC); 4065 Lex.Lex(); 4066 return false; 4067 } 4068 4069 template <> 4070 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) { 4071 if (Lex.getKind() == lltok::APSInt) 4072 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4073 4074 if (Lex.getKind() != lltok::EmissionKind) 4075 return TokError("expected emission kind"); 4076 4077 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal()); 4078 if (!Kind) 4079 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() + 4080 "'"); 4081 assert(*Kind <= Result.Max && "Expected valid emission kind"); 4082 Result.assign(*Kind); 4083 Lex.Lex(); 4084 return false; 4085 } 4086 4087 template <> 4088 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 4089 NameTableKindField &Result) { 4090 if (Lex.getKind() == lltok::APSInt) 4091 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4092 4093 if (Lex.getKind() != lltok::NameTableKind) 4094 return TokError("expected nameTable kind"); 4095 4096 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal()); 4097 if (!Kind) 4098 return TokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() + 4099 "'"); 4100 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind"); 4101 Result.assign((unsigned)*Kind); 4102 Lex.Lex(); 4103 return false; 4104 } 4105 4106 template <> 4107 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 4108 DwarfAttEncodingField &Result) { 4109 if (Lex.getKind() == lltok::APSInt) 4110 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4111 4112 if (Lex.getKind() != lltok::DwarfAttEncoding) 4113 return TokError("expected DWARF type attribute encoding"); 4114 4115 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal()); 4116 if (!Encoding) 4117 return TokError("invalid DWARF type attribute encoding" + Twine(" '") + 4118 Lex.getStrVal() + "'"); 4119 assert(Encoding <= Result.Max && "Expected valid DWARF language"); 4120 Result.assign(Encoding); 4121 Lex.Lex(); 4122 return false; 4123 } 4124 4125 /// DIFlagField 4126 /// ::= uint32 4127 /// ::= DIFlagVector 4128 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic 4129 template <> 4130 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) { 4131 4132 // Parser for a single flag. 4133 auto parseFlag = [&](DINode::DIFlags &Val) { 4134 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) { 4135 uint32_t TempVal = static_cast<uint32_t>(Val); 4136 bool Res = ParseUInt32(TempVal); 4137 Val = static_cast<DINode::DIFlags>(TempVal); 4138 return Res; 4139 } 4140 4141 if (Lex.getKind() != lltok::DIFlag) 4142 return TokError("expected debug info flag"); 4143 4144 Val = DINode::getFlag(Lex.getStrVal()); 4145 if (!Val) 4146 return TokError(Twine("invalid debug info flag flag '") + 4147 Lex.getStrVal() + "'"); 4148 Lex.Lex(); 4149 return false; 4150 }; 4151 4152 // Parse the flags and combine them together. 4153 DINode::DIFlags Combined = DINode::FlagZero; 4154 do { 4155 DINode::DIFlags Val; 4156 if (parseFlag(Val)) 4157 return true; 4158 Combined |= Val; 4159 } while (EatIfPresent(lltok::bar)); 4160 4161 Result.assign(Combined); 4162 return false; 4163 } 4164 4165 /// DISPFlagField 4166 /// ::= uint32 4167 /// ::= DISPFlagVector 4168 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32 4169 template <> 4170 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) { 4171 4172 // Parser for a single flag. 4173 auto parseFlag = [&](DISubprogram::DISPFlags &Val) { 4174 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) { 4175 uint32_t TempVal = static_cast<uint32_t>(Val); 4176 bool Res = ParseUInt32(TempVal); 4177 Val = static_cast<DISubprogram::DISPFlags>(TempVal); 4178 return Res; 4179 } 4180 4181 if (Lex.getKind() != lltok::DISPFlag) 4182 return TokError("expected debug info flag"); 4183 4184 Val = DISubprogram::getFlag(Lex.getStrVal()); 4185 if (!Val) 4186 return TokError(Twine("invalid subprogram debug info flag '") + 4187 Lex.getStrVal() + "'"); 4188 Lex.Lex(); 4189 return false; 4190 }; 4191 4192 // Parse the flags and combine them together. 4193 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero; 4194 do { 4195 DISubprogram::DISPFlags Val; 4196 if (parseFlag(Val)) 4197 return true; 4198 Combined |= Val; 4199 } while (EatIfPresent(lltok::bar)); 4200 4201 Result.assign(Combined); 4202 return false; 4203 } 4204 4205 template <> 4206 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 4207 MDSignedField &Result) { 4208 if (Lex.getKind() != lltok::APSInt) 4209 return TokError("expected signed integer"); 4210 4211 auto &S = Lex.getAPSIntVal(); 4212 if (S < Result.Min) 4213 return TokError("value for '" + Name + "' too small, limit is " + 4214 Twine(Result.Min)); 4215 if (S > Result.Max) 4216 return TokError("value for '" + Name + "' too large, limit is " + 4217 Twine(Result.Max)); 4218 Result.assign(S.getExtValue()); 4219 assert(Result.Val >= Result.Min && "Expected value in range"); 4220 assert(Result.Val <= Result.Max && "Expected value in range"); 4221 Lex.Lex(); 4222 return false; 4223 } 4224 4225 template <> 4226 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) { 4227 switch (Lex.getKind()) { 4228 default: 4229 return TokError("expected 'true' or 'false'"); 4230 case lltok::kw_true: 4231 Result.assign(true); 4232 break; 4233 case lltok::kw_false: 4234 Result.assign(false); 4235 break; 4236 } 4237 Lex.Lex(); 4238 return false; 4239 } 4240 4241 template <> 4242 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) { 4243 if (Lex.getKind() == lltok::kw_null) { 4244 if (!Result.AllowNull) 4245 return TokError("'" + Name + "' cannot be null"); 4246 Lex.Lex(); 4247 Result.assign(nullptr); 4248 return false; 4249 } 4250 4251 Metadata *MD; 4252 if (ParseMetadata(MD, nullptr)) 4253 return true; 4254 4255 Result.assign(MD); 4256 return false; 4257 } 4258 4259 template <> 4260 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 4261 MDSignedOrMDField &Result) { 4262 // Try to parse a signed int. 4263 if (Lex.getKind() == lltok::APSInt) { 4264 MDSignedField Res = Result.A; 4265 if (!ParseMDField(Loc, Name, Res)) { 4266 Result.assign(Res); 4267 return false; 4268 } 4269 return true; 4270 } 4271 4272 // Otherwise, try to parse as an MDField. 4273 MDField Res = Result.B; 4274 if (!ParseMDField(Loc, Name, Res)) { 4275 Result.assign(Res); 4276 return false; 4277 } 4278 4279 return true; 4280 } 4281 4282 template <> 4283 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 4284 MDSignedOrUnsignedField &Result) { 4285 if (Lex.getKind() != lltok::APSInt) 4286 return false; 4287 4288 if (Lex.getAPSIntVal().isSigned()) { 4289 MDSignedField Res = Result.A; 4290 if (ParseMDField(Loc, Name, Res)) 4291 return true; 4292 Result.assign(Res); 4293 return false; 4294 } 4295 4296 MDUnsignedField Res = Result.B; 4297 if (ParseMDField(Loc, Name, Res)) 4298 return true; 4299 Result.assign(Res); 4300 return false; 4301 } 4302 4303 template <> 4304 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) { 4305 LocTy ValueLoc = Lex.getLoc(); 4306 std::string S; 4307 if (ParseStringConstant(S)) 4308 return true; 4309 4310 if (!Result.AllowEmpty && S.empty()) 4311 return Error(ValueLoc, "'" + Name + "' cannot be empty"); 4312 4313 Result.assign(S.empty() ? nullptr : MDString::get(Context, S)); 4314 return false; 4315 } 4316 4317 template <> 4318 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) { 4319 SmallVector<Metadata *, 4> MDs; 4320 if (ParseMDNodeVector(MDs)) 4321 return true; 4322 4323 Result.assign(std::move(MDs)); 4324 return false; 4325 } 4326 4327 template <> 4328 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 4329 ChecksumKindField &Result) { 4330 Optional<DIFile::ChecksumKind> CSKind = 4331 DIFile::getChecksumKind(Lex.getStrVal()); 4332 4333 if (Lex.getKind() != lltok::ChecksumKind || !CSKind) 4334 return TokError( 4335 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'"); 4336 4337 Result.assign(*CSKind); 4338 Lex.Lex(); 4339 return false; 4340 } 4341 4342 } // end namespace llvm 4343 4344 template <class ParserTy> 4345 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) { 4346 do { 4347 if (Lex.getKind() != lltok::LabelStr) 4348 return TokError("expected field label here"); 4349 4350 if (parseField()) 4351 return true; 4352 } while (EatIfPresent(lltok::comma)); 4353 4354 return false; 4355 } 4356 4357 template <class ParserTy> 4358 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) { 4359 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 4360 Lex.Lex(); 4361 4362 if (ParseToken(lltok::lparen, "expected '(' here")) 4363 return true; 4364 if (Lex.getKind() != lltok::rparen) 4365 if (ParseMDFieldsImplBody(parseField)) 4366 return true; 4367 4368 ClosingLoc = Lex.getLoc(); 4369 return ParseToken(lltok::rparen, "expected ')' here"); 4370 } 4371 4372 template <class FieldTy> 4373 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) { 4374 if (Result.Seen) 4375 return TokError("field '" + Name + "' cannot be specified more than once"); 4376 4377 LocTy Loc = Lex.getLoc(); 4378 Lex.Lex(); 4379 return ParseMDField(Loc, Name, Result); 4380 } 4381 4382 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) { 4383 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 4384 4385 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \ 4386 if (Lex.getStrVal() == #CLASS) \ 4387 return Parse##CLASS(N, IsDistinct); 4388 #include "llvm/IR/Metadata.def" 4389 4390 return TokError("expected metadata type"); 4391 } 4392 4393 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT 4394 #define NOP_FIELD(NAME, TYPE, INIT) 4395 #define REQUIRE_FIELD(NAME, TYPE, INIT) \ 4396 if (!NAME.Seen) \ 4397 return Error(ClosingLoc, "missing required field '" #NAME "'"); 4398 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \ 4399 if (Lex.getStrVal() == #NAME) \ 4400 return ParseMDField(#NAME, NAME); 4401 #define PARSE_MD_FIELDS() \ 4402 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \ 4403 do { \ 4404 LocTy ClosingLoc; \ 4405 if (ParseMDFieldsImpl([&]() -> bool { \ 4406 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \ 4407 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \ 4408 }, ClosingLoc)) \ 4409 return true; \ 4410 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \ 4411 } while (false) 4412 #define GET_OR_DISTINCT(CLASS, ARGS) \ 4413 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS) 4414 4415 /// ParseDILocationFields: 4416 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6, 4417 /// isImplicitCode: true) 4418 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) { 4419 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4420 OPTIONAL(line, LineField, ); \ 4421 OPTIONAL(column, ColumnField, ); \ 4422 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4423 OPTIONAL(inlinedAt, MDField, ); \ 4424 OPTIONAL(isImplicitCode, MDBoolField, (false)); 4425 PARSE_MD_FIELDS(); 4426 #undef VISIT_MD_FIELDS 4427 4428 Result = 4429 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val, 4430 inlinedAt.Val, isImplicitCode.Val)); 4431 return false; 4432 } 4433 4434 /// ParseGenericDINode: 4435 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...}) 4436 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) { 4437 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4438 REQUIRED(tag, DwarfTagField, ); \ 4439 OPTIONAL(header, MDStringField, ); \ 4440 OPTIONAL(operands, MDFieldList, ); 4441 PARSE_MD_FIELDS(); 4442 #undef VISIT_MD_FIELDS 4443 4444 Result = GET_OR_DISTINCT(GenericDINode, 4445 (Context, tag.Val, header.Val, operands.Val)); 4446 return false; 4447 } 4448 4449 /// ParseDISubrange: 4450 /// ::= !DISubrange(count: 30, lowerBound: 2) 4451 /// ::= !DISubrange(count: !node, lowerBound: 2) 4452 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) { 4453 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4454 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \ 4455 OPTIONAL(lowerBound, MDSignedField, ); 4456 PARSE_MD_FIELDS(); 4457 #undef VISIT_MD_FIELDS 4458 4459 if (count.isMDSignedField()) 4460 Result = GET_OR_DISTINCT( 4461 DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val)); 4462 else if (count.isMDField()) 4463 Result = GET_OR_DISTINCT( 4464 DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val)); 4465 else 4466 return true; 4467 4468 return false; 4469 } 4470 4471 /// ParseDIEnumerator: 4472 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind") 4473 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) { 4474 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4475 REQUIRED(name, MDStringField, ); \ 4476 REQUIRED(value, MDSignedOrUnsignedField, ); \ 4477 OPTIONAL(isUnsigned, MDBoolField, (false)); 4478 PARSE_MD_FIELDS(); 4479 #undef VISIT_MD_FIELDS 4480 4481 if (isUnsigned.Val && value.isMDSignedField()) 4482 return TokError("unsigned enumerator with negative value"); 4483 4484 int64_t Value = value.isMDSignedField() 4485 ? value.getMDSignedValue() 4486 : static_cast<int64_t>(value.getMDUnsignedValue()); 4487 Result = 4488 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val)); 4489 4490 return false; 4491 } 4492 4493 /// ParseDIBasicType: 4494 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32, 4495 /// encoding: DW_ATE_encoding, flags: 0) 4496 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) { 4497 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4498 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \ 4499 OPTIONAL(name, MDStringField, ); \ 4500 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4501 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4502 OPTIONAL(encoding, DwarfAttEncodingField, ); \ 4503 OPTIONAL(flags, DIFlagField, ); 4504 PARSE_MD_FIELDS(); 4505 #undef VISIT_MD_FIELDS 4506 4507 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val, 4508 align.Val, encoding.Val, flags.Val)); 4509 return false; 4510 } 4511 4512 /// ParseDIDerivedType: 4513 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0, 4514 /// line: 7, scope: !1, baseType: !2, size: 32, 4515 /// align: 32, offset: 0, flags: 0, extraData: !3, 4516 /// dwarfAddressSpace: 3) 4517 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) { 4518 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4519 REQUIRED(tag, DwarfTagField, ); \ 4520 OPTIONAL(name, MDStringField, ); \ 4521 OPTIONAL(file, MDField, ); \ 4522 OPTIONAL(line, LineField, ); \ 4523 OPTIONAL(scope, MDField, ); \ 4524 REQUIRED(baseType, MDField, ); \ 4525 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4526 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4527 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \ 4528 OPTIONAL(flags, DIFlagField, ); \ 4529 OPTIONAL(extraData, MDField, ); \ 4530 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); 4531 PARSE_MD_FIELDS(); 4532 #undef VISIT_MD_FIELDS 4533 4534 Optional<unsigned> DWARFAddressSpace; 4535 if (dwarfAddressSpace.Val != UINT32_MAX) 4536 DWARFAddressSpace = dwarfAddressSpace.Val; 4537 4538 Result = GET_OR_DISTINCT(DIDerivedType, 4539 (Context, tag.Val, name.Val, file.Val, line.Val, 4540 scope.Val, baseType.Val, size.Val, align.Val, 4541 offset.Val, DWARFAddressSpace, flags.Val, 4542 extraData.Val)); 4543 return false; 4544 } 4545 4546 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) { 4547 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4548 REQUIRED(tag, DwarfTagField, ); \ 4549 OPTIONAL(name, MDStringField, ); \ 4550 OPTIONAL(file, MDField, ); \ 4551 OPTIONAL(line, LineField, ); \ 4552 OPTIONAL(scope, MDField, ); \ 4553 OPTIONAL(baseType, MDField, ); \ 4554 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4555 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4556 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \ 4557 OPTIONAL(flags, DIFlagField, ); \ 4558 OPTIONAL(elements, MDField, ); \ 4559 OPTIONAL(runtimeLang, DwarfLangField, ); \ 4560 OPTIONAL(vtableHolder, MDField, ); \ 4561 OPTIONAL(templateParams, MDField, ); \ 4562 OPTIONAL(identifier, MDStringField, ); \ 4563 OPTIONAL(discriminator, MDField, ); 4564 PARSE_MD_FIELDS(); 4565 #undef VISIT_MD_FIELDS 4566 4567 // If this has an identifier try to build an ODR type. 4568 if (identifier.Val) 4569 if (auto *CT = DICompositeType::buildODRType( 4570 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val, 4571 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val, 4572 elements.Val, runtimeLang.Val, vtableHolder.Val, 4573 templateParams.Val, discriminator.Val)) { 4574 Result = CT; 4575 return false; 4576 } 4577 4578 // Create a new node, and save it in the context if it belongs in the type 4579 // map. 4580 Result = GET_OR_DISTINCT( 4581 DICompositeType, 4582 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val, 4583 size.Val, align.Val, offset.Val, flags.Val, elements.Val, 4584 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val, 4585 discriminator.Val)); 4586 return false; 4587 } 4588 4589 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) { 4590 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4591 OPTIONAL(flags, DIFlagField, ); \ 4592 OPTIONAL(cc, DwarfCCField, ); \ 4593 REQUIRED(types, MDField, ); 4594 PARSE_MD_FIELDS(); 4595 #undef VISIT_MD_FIELDS 4596 4597 Result = GET_OR_DISTINCT(DISubroutineType, 4598 (Context, flags.Val, cc.Val, types.Val)); 4599 return false; 4600 } 4601 4602 /// ParseDIFileType: 4603 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir", 4604 /// checksumkind: CSK_MD5, 4605 /// checksum: "000102030405060708090a0b0c0d0e0f", 4606 /// source: "source file contents") 4607 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) { 4608 // The default constructed value for checksumkind is required, but will never 4609 // be used, as the parser checks if the field was actually Seen before using 4610 // the Val. 4611 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4612 REQUIRED(filename, MDStringField, ); \ 4613 REQUIRED(directory, MDStringField, ); \ 4614 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \ 4615 OPTIONAL(checksum, MDStringField, ); \ 4616 OPTIONAL(source, MDStringField, ); 4617 PARSE_MD_FIELDS(); 4618 #undef VISIT_MD_FIELDS 4619 4620 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum; 4621 if (checksumkind.Seen && checksum.Seen) 4622 OptChecksum.emplace(checksumkind.Val, checksum.Val); 4623 else if (checksumkind.Seen || checksum.Seen) 4624 return Lex.Error("'checksumkind' and 'checksum' must be provided together"); 4625 4626 Optional<MDString *> OptSource; 4627 if (source.Seen) 4628 OptSource = source.Val; 4629 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val, 4630 OptChecksum, OptSource)); 4631 return false; 4632 } 4633 4634 /// ParseDICompileUnit: 4635 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang", 4636 /// isOptimized: true, flags: "-O2", runtimeVersion: 1, 4637 /// splitDebugFilename: "abc.debug", 4638 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2, 4639 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd, 4640 /// sysroot: "/") 4641 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) { 4642 if (!IsDistinct) 4643 return Lex.Error("missing 'distinct', required for !DICompileUnit"); 4644 4645 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4646 REQUIRED(language, DwarfLangField, ); \ 4647 REQUIRED(file, MDField, (/* AllowNull */ false)); \ 4648 OPTIONAL(producer, MDStringField, ); \ 4649 OPTIONAL(isOptimized, MDBoolField, ); \ 4650 OPTIONAL(flags, MDStringField, ); \ 4651 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \ 4652 OPTIONAL(splitDebugFilename, MDStringField, ); \ 4653 OPTIONAL(emissionKind, EmissionKindField, ); \ 4654 OPTIONAL(enums, MDField, ); \ 4655 OPTIONAL(retainedTypes, MDField, ); \ 4656 OPTIONAL(globals, MDField, ); \ 4657 OPTIONAL(imports, MDField, ); \ 4658 OPTIONAL(macros, MDField, ); \ 4659 OPTIONAL(dwoId, MDUnsignedField, ); \ 4660 OPTIONAL(splitDebugInlining, MDBoolField, = true); \ 4661 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \ 4662 OPTIONAL(nameTableKind, NameTableKindField, ); \ 4663 OPTIONAL(debugBaseAddress, MDBoolField, = false); \ 4664 OPTIONAL(sysroot, MDStringField, ); 4665 PARSE_MD_FIELDS(); 4666 #undef VISIT_MD_FIELDS 4667 4668 Result = DICompileUnit::getDistinct( 4669 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val, 4670 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val, 4671 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val, 4672 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val, 4673 debugBaseAddress.Val, sysroot.Val); 4674 return false; 4675 } 4676 4677 /// ParseDISubprogram: 4678 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo", 4679 /// file: !1, line: 7, type: !2, isLocal: false, 4680 /// isDefinition: true, scopeLine: 8, containingType: !3, 4681 /// virtuality: DW_VIRTUALTIY_pure_virtual, 4682 /// virtualIndex: 10, thisAdjustment: 4, flags: 11, 4683 /// spFlags: 10, isOptimized: false, templateParams: !4, 4684 /// declaration: !5, retainedNodes: !6, thrownTypes: !7) 4685 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) { 4686 auto Loc = Lex.getLoc(); 4687 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4688 OPTIONAL(scope, MDField, ); \ 4689 OPTIONAL(name, MDStringField, ); \ 4690 OPTIONAL(linkageName, MDStringField, ); \ 4691 OPTIONAL(file, MDField, ); \ 4692 OPTIONAL(line, LineField, ); \ 4693 OPTIONAL(type, MDField, ); \ 4694 OPTIONAL(isLocal, MDBoolField, ); \ 4695 OPTIONAL(isDefinition, MDBoolField, (true)); \ 4696 OPTIONAL(scopeLine, LineField, ); \ 4697 OPTIONAL(containingType, MDField, ); \ 4698 OPTIONAL(virtuality, DwarfVirtualityField, ); \ 4699 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \ 4700 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \ 4701 OPTIONAL(flags, DIFlagField, ); \ 4702 OPTIONAL(spFlags, DISPFlagField, ); \ 4703 OPTIONAL(isOptimized, MDBoolField, ); \ 4704 OPTIONAL(unit, MDField, ); \ 4705 OPTIONAL(templateParams, MDField, ); \ 4706 OPTIONAL(declaration, MDField, ); \ 4707 OPTIONAL(retainedNodes, MDField, ); \ 4708 OPTIONAL(thrownTypes, MDField, ); 4709 PARSE_MD_FIELDS(); 4710 #undef VISIT_MD_FIELDS 4711 4712 // An explicit spFlags field takes precedence over individual fields in 4713 // older IR versions. 4714 DISubprogram::DISPFlags SPFlags = 4715 spFlags.Seen ? spFlags.Val 4716 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val, 4717 isOptimized.Val, virtuality.Val); 4718 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct) 4719 return Lex.Error( 4720 Loc, 4721 "missing 'distinct', required for !DISubprogram that is a Definition"); 4722 Result = GET_OR_DISTINCT( 4723 DISubprogram, 4724 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val, 4725 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val, 4726 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val, 4727 declaration.Val, retainedNodes.Val, thrownTypes.Val)); 4728 return false; 4729 } 4730 4731 /// ParseDILexicalBlock: 4732 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9) 4733 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) { 4734 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4735 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4736 OPTIONAL(file, MDField, ); \ 4737 OPTIONAL(line, LineField, ); \ 4738 OPTIONAL(column, ColumnField, ); 4739 PARSE_MD_FIELDS(); 4740 #undef VISIT_MD_FIELDS 4741 4742 Result = GET_OR_DISTINCT( 4743 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val)); 4744 return false; 4745 } 4746 4747 /// ParseDILexicalBlockFile: 4748 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9) 4749 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) { 4750 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4751 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4752 OPTIONAL(file, MDField, ); \ 4753 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX)); 4754 PARSE_MD_FIELDS(); 4755 #undef VISIT_MD_FIELDS 4756 4757 Result = GET_OR_DISTINCT(DILexicalBlockFile, 4758 (Context, scope.Val, file.Val, discriminator.Val)); 4759 return false; 4760 } 4761 4762 /// ParseDICommonBlock: 4763 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9) 4764 bool LLParser::ParseDICommonBlock(MDNode *&Result, bool IsDistinct) { 4765 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4766 REQUIRED(scope, MDField, ); \ 4767 OPTIONAL(declaration, MDField, ); \ 4768 OPTIONAL(name, MDStringField, ); \ 4769 OPTIONAL(file, MDField, ); \ 4770 OPTIONAL(line, LineField, ); 4771 PARSE_MD_FIELDS(); 4772 #undef VISIT_MD_FIELDS 4773 4774 Result = GET_OR_DISTINCT(DICommonBlock, 4775 (Context, scope.Val, declaration.Val, name.Val, 4776 file.Val, line.Val)); 4777 return false; 4778 } 4779 4780 /// ParseDINamespace: 4781 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9) 4782 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) { 4783 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4784 REQUIRED(scope, MDField, ); \ 4785 OPTIONAL(name, MDStringField, ); \ 4786 OPTIONAL(exportSymbols, MDBoolField, ); 4787 PARSE_MD_FIELDS(); 4788 #undef VISIT_MD_FIELDS 4789 4790 Result = GET_OR_DISTINCT(DINamespace, 4791 (Context, scope.Val, name.Val, exportSymbols.Val)); 4792 return false; 4793 } 4794 4795 /// ParseDIMacro: 4796 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue") 4797 bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) { 4798 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4799 REQUIRED(type, DwarfMacinfoTypeField, ); \ 4800 OPTIONAL(line, LineField, ); \ 4801 REQUIRED(name, MDStringField, ); \ 4802 OPTIONAL(value, MDStringField, ); 4803 PARSE_MD_FIELDS(); 4804 #undef VISIT_MD_FIELDS 4805 4806 Result = GET_OR_DISTINCT(DIMacro, 4807 (Context, type.Val, line.Val, name.Val, value.Val)); 4808 return false; 4809 } 4810 4811 /// ParseDIMacroFile: 4812 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3) 4813 bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) { 4814 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4815 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \ 4816 OPTIONAL(line, LineField, ); \ 4817 REQUIRED(file, MDField, ); \ 4818 OPTIONAL(nodes, MDField, ); 4819 PARSE_MD_FIELDS(); 4820 #undef VISIT_MD_FIELDS 4821 4822 Result = GET_OR_DISTINCT(DIMacroFile, 4823 (Context, type.Val, line.Val, file.Val, nodes.Val)); 4824 return false; 4825 } 4826 4827 /// ParseDIModule: 4828 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG", 4829 /// includePath: "/usr/include") 4830 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) { 4831 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4832 REQUIRED(scope, MDField, ); \ 4833 REQUIRED(name, MDStringField, ); \ 4834 OPTIONAL(configMacros, MDStringField, ); \ 4835 OPTIONAL(includePath, MDStringField, ); 4836 PARSE_MD_FIELDS(); 4837 #undef VISIT_MD_FIELDS 4838 4839 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val, 4840 configMacros.Val, includePath.Val)); 4841 return false; 4842 } 4843 4844 /// ParseDITemplateTypeParameter: 4845 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false) 4846 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) { 4847 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4848 OPTIONAL(name, MDStringField, ); \ 4849 REQUIRED(type, MDField, ); \ 4850 OPTIONAL(defaulted, MDBoolField, ); 4851 PARSE_MD_FIELDS(); 4852 #undef VISIT_MD_FIELDS 4853 4854 Result = GET_OR_DISTINCT(DITemplateTypeParameter, 4855 (Context, name.Val, type.Val, defaulted.Val)); 4856 return false; 4857 } 4858 4859 /// ParseDITemplateValueParameter: 4860 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter, 4861 /// name: "V", type: !1, defaulted: false, 4862 /// value: i32 7) 4863 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) { 4864 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4865 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \ 4866 OPTIONAL(name, MDStringField, ); \ 4867 OPTIONAL(type, MDField, ); \ 4868 OPTIONAL(defaulted, MDBoolField, ); \ 4869 REQUIRED(value, MDField, ); 4870 4871 PARSE_MD_FIELDS(); 4872 #undef VISIT_MD_FIELDS 4873 4874 Result = GET_OR_DISTINCT( 4875 DITemplateValueParameter, 4876 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val)); 4877 return false; 4878 } 4879 4880 /// ParseDIGlobalVariable: 4881 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo", 4882 /// file: !1, line: 7, type: !2, isLocal: false, 4883 /// isDefinition: true, templateParams: !3, 4884 /// declaration: !4, align: 8) 4885 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) { 4886 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4887 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \ 4888 OPTIONAL(scope, MDField, ); \ 4889 OPTIONAL(linkageName, MDStringField, ); \ 4890 OPTIONAL(file, MDField, ); \ 4891 OPTIONAL(line, LineField, ); \ 4892 OPTIONAL(type, MDField, ); \ 4893 OPTIONAL(isLocal, MDBoolField, ); \ 4894 OPTIONAL(isDefinition, MDBoolField, (true)); \ 4895 OPTIONAL(templateParams, MDField, ); \ 4896 OPTIONAL(declaration, MDField, ); \ 4897 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); 4898 PARSE_MD_FIELDS(); 4899 #undef VISIT_MD_FIELDS 4900 4901 Result = 4902 GET_OR_DISTINCT(DIGlobalVariable, 4903 (Context, scope.Val, name.Val, linkageName.Val, file.Val, 4904 line.Val, type.Val, isLocal.Val, isDefinition.Val, 4905 declaration.Val, templateParams.Val, align.Val)); 4906 return false; 4907 } 4908 4909 /// ParseDILocalVariable: 4910 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo", 4911 /// file: !1, line: 7, type: !2, arg: 2, flags: 7, 4912 /// align: 8) 4913 /// ::= !DILocalVariable(scope: !0, name: "foo", 4914 /// file: !1, line: 7, type: !2, arg: 2, flags: 7, 4915 /// align: 8) 4916 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) { 4917 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4918 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4919 OPTIONAL(name, MDStringField, ); \ 4920 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \ 4921 OPTIONAL(file, MDField, ); \ 4922 OPTIONAL(line, LineField, ); \ 4923 OPTIONAL(type, MDField, ); \ 4924 OPTIONAL(flags, DIFlagField, ); \ 4925 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); 4926 PARSE_MD_FIELDS(); 4927 #undef VISIT_MD_FIELDS 4928 4929 Result = GET_OR_DISTINCT(DILocalVariable, 4930 (Context, scope.Val, name.Val, file.Val, line.Val, 4931 type.Val, arg.Val, flags.Val, align.Val)); 4932 return false; 4933 } 4934 4935 /// ParseDILabel: 4936 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7) 4937 bool LLParser::ParseDILabel(MDNode *&Result, bool IsDistinct) { 4938 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4939 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4940 REQUIRED(name, MDStringField, ); \ 4941 REQUIRED(file, MDField, ); \ 4942 REQUIRED(line, LineField, ); 4943 PARSE_MD_FIELDS(); 4944 #undef VISIT_MD_FIELDS 4945 4946 Result = GET_OR_DISTINCT(DILabel, 4947 (Context, scope.Val, name.Val, file.Val, line.Val)); 4948 return false; 4949 } 4950 4951 /// ParseDIExpression: 4952 /// ::= !DIExpression(0, 7, -1) 4953 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) { 4954 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 4955 Lex.Lex(); 4956 4957 if (ParseToken(lltok::lparen, "expected '(' here")) 4958 return true; 4959 4960 SmallVector<uint64_t, 8> Elements; 4961 if (Lex.getKind() != lltok::rparen) 4962 do { 4963 if (Lex.getKind() == lltok::DwarfOp) { 4964 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) { 4965 Lex.Lex(); 4966 Elements.push_back(Op); 4967 continue; 4968 } 4969 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'"); 4970 } 4971 4972 if (Lex.getKind() == lltok::DwarfAttEncoding) { 4973 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) { 4974 Lex.Lex(); 4975 Elements.push_back(Op); 4976 continue; 4977 } 4978 return TokError(Twine("invalid DWARF attribute encoding '") + Lex.getStrVal() + "'"); 4979 } 4980 4981 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 4982 return TokError("expected unsigned integer"); 4983 4984 auto &U = Lex.getAPSIntVal(); 4985 if (U.ugt(UINT64_MAX)) 4986 return TokError("element too large, limit is " + Twine(UINT64_MAX)); 4987 Elements.push_back(U.getZExtValue()); 4988 Lex.Lex(); 4989 } while (EatIfPresent(lltok::comma)); 4990 4991 if (ParseToken(lltok::rparen, "expected ')' here")) 4992 return true; 4993 4994 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements)); 4995 return false; 4996 } 4997 4998 /// ParseDIGlobalVariableExpression: 4999 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1) 5000 bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result, 5001 bool IsDistinct) { 5002 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5003 REQUIRED(var, MDField, ); \ 5004 REQUIRED(expr, MDField, ); 5005 PARSE_MD_FIELDS(); 5006 #undef VISIT_MD_FIELDS 5007 5008 Result = 5009 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val)); 5010 return false; 5011 } 5012 5013 /// ParseDIObjCProperty: 5014 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo", 5015 /// getter: "getFoo", attributes: 7, type: !2) 5016 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) { 5017 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5018 OPTIONAL(name, MDStringField, ); \ 5019 OPTIONAL(file, MDField, ); \ 5020 OPTIONAL(line, LineField, ); \ 5021 OPTIONAL(setter, MDStringField, ); \ 5022 OPTIONAL(getter, MDStringField, ); \ 5023 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \ 5024 OPTIONAL(type, MDField, ); 5025 PARSE_MD_FIELDS(); 5026 #undef VISIT_MD_FIELDS 5027 5028 Result = GET_OR_DISTINCT(DIObjCProperty, 5029 (Context, name.Val, file.Val, line.Val, setter.Val, 5030 getter.Val, attributes.Val, type.Val)); 5031 return false; 5032 } 5033 5034 /// ParseDIImportedEntity: 5035 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1, 5036 /// line: 7, name: "foo") 5037 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) { 5038 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5039 REQUIRED(tag, DwarfTagField, ); \ 5040 REQUIRED(scope, MDField, ); \ 5041 OPTIONAL(entity, MDField, ); \ 5042 OPTIONAL(file, MDField, ); \ 5043 OPTIONAL(line, LineField, ); \ 5044 OPTIONAL(name, MDStringField, ); 5045 PARSE_MD_FIELDS(); 5046 #undef VISIT_MD_FIELDS 5047 5048 Result = GET_OR_DISTINCT( 5049 DIImportedEntity, 5050 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val)); 5051 return false; 5052 } 5053 5054 #undef PARSE_MD_FIELD 5055 #undef NOP_FIELD 5056 #undef REQUIRE_FIELD 5057 #undef DECLARE_FIELD 5058 5059 /// ParseMetadataAsValue 5060 /// ::= metadata i32 %local 5061 /// ::= metadata i32 @global 5062 /// ::= metadata i32 7 5063 /// ::= metadata !0 5064 /// ::= metadata !{...} 5065 /// ::= metadata !"string" 5066 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) { 5067 // Note: the type 'metadata' has already been parsed. 5068 Metadata *MD; 5069 if (ParseMetadata(MD, &PFS)) 5070 return true; 5071 5072 V = MetadataAsValue::get(Context, MD); 5073 return false; 5074 } 5075 5076 /// ParseValueAsMetadata 5077 /// ::= i32 %local 5078 /// ::= i32 @global 5079 /// ::= i32 7 5080 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg, 5081 PerFunctionState *PFS) { 5082 Type *Ty; 5083 LocTy Loc; 5084 if (ParseType(Ty, TypeMsg, Loc)) 5085 return true; 5086 if (Ty->isMetadataTy()) 5087 return Error(Loc, "invalid metadata-value-metadata roundtrip"); 5088 5089 Value *V; 5090 if (ParseValue(Ty, V, PFS)) 5091 return true; 5092 5093 MD = ValueAsMetadata::get(V); 5094 return false; 5095 } 5096 5097 /// ParseMetadata 5098 /// ::= i32 %local 5099 /// ::= i32 @global 5100 /// ::= i32 7 5101 /// ::= !42 5102 /// ::= !{...} 5103 /// ::= !"string" 5104 /// ::= !DILocation(...) 5105 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) { 5106 if (Lex.getKind() == lltok::MetadataVar) { 5107 MDNode *N; 5108 if (ParseSpecializedMDNode(N)) 5109 return true; 5110 MD = N; 5111 return false; 5112 } 5113 5114 // ValueAsMetadata: 5115 // <type> <value> 5116 if (Lex.getKind() != lltok::exclaim) 5117 return ParseValueAsMetadata(MD, "expected metadata operand", PFS); 5118 5119 // '!'. 5120 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here"); 5121 Lex.Lex(); 5122 5123 // MDString: 5124 // ::= '!' STRINGCONSTANT 5125 if (Lex.getKind() == lltok::StringConstant) { 5126 MDString *S; 5127 if (ParseMDString(S)) 5128 return true; 5129 MD = S; 5130 return false; 5131 } 5132 5133 // MDNode: 5134 // !{ ... } 5135 // !7 5136 MDNode *N; 5137 if (ParseMDNodeTail(N)) 5138 return true; 5139 MD = N; 5140 return false; 5141 } 5142 5143 //===----------------------------------------------------------------------===// 5144 // Function Parsing. 5145 //===----------------------------------------------------------------------===// 5146 5147 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V, 5148 PerFunctionState *PFS, bool IsCall) { 5149 if (Ty->isFunctionTy()) 5150 return Error(ID.Loc, "functions are not values, refer to them as pointers"); 5151 5152 switch (ID.Kind) { 5153 case ValID::t_LocalID: 5154 if (!PFS) return Error(ID.Loc, "invalid use of function-local name"); 5155 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall); 5156 return V == nullptr; 5157 case ValID::t_LocalName: 5158 if (!PFS) return Error(ID.Loc, "invalid use of function-local name"); 5159 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, IsCall); 5160 return V == nullptr; 5161 case ValID::t_InlineAsm: { 5162 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2)) 5163 return Error(ID.Loc, "invalid type for inline asm constraint string"); 5164 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, 5165 (ID.UIntVal >> 1) & 1, 5166 (InlineAsm::AsmDialect(ID.UIntVal >> 2))); 5167 return false; 5168 } 5169 case ValID::t_GlobalName: 5170 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall); 5171 return V == nullptr; 5172 case ValID::t_GlobalID: 5173 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall); 5174 return V == nullptr; 5175 case ValID::t_APSInt: 5176 if (!Ty->isIntegerTy()) 5177 return Error(ID.Loc, "integer constant must have integer type"); 5178 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits()); 5179 V = ConstantInt::get(Context, ID.APSIntVal); 5180 return false; 5181 case ValID::t_APFloat: 5182 if (!Ty->isFloatingPointTy() || 5183 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal)) 5184 return Error(ID.Loc, "floating point constant invalid for type"); 5185 5186 // The lexer has no type info, so builds all half, float, and double FP 5187 // constants as double. Fix this here. Long double does not need this. 5188 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) { 5189 bool Ignored; 5190 if (Ty->isHalfTy()) 5191 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, 5192 &Ignored); 5193 else if (Ty->isFloatTy()) 5194 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 5195 &Ignored); 5196 } 5197 V = ConstantFP::get(Context, ID.APFloatVal); 5198 5199 if (V->getType() != Ty) 5200 return Error(ID.Loc, "floating point constant does not have type '" + 5201 getTypeString(Ty) + "'"); 5202 5203 return false; 5204 case ValID::t_Null: 5205 if (!Ty->isPointerTy()) 5206 return Error(ID.Loc, "null must be a pointer type"); 5207 V = ConstantPointerNull::get(cast<PointerType>(Ty)); 5208 return false; 5209 case ValID::t_Undef: 5210 // FIXME: LabelTy should not be a first-class type. 5211 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 5212 return Error(ID.Loc, "invalid type for undef constant"); 5213 V = UndefValue::get(Ty); 5214 return false; 5215 case ValID::t_EmptyArray: 5216 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0) 5217 return Error(ID.Loc, "invalid empty array initializer"); 5218 V = UndefValue::get(Ty); 5219 return false; 5220 case ValID::t_Zero: 5221 // FIXME: LabelTy should not be a first-class type. 5222 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 5223 return Error(ID.Loc, "invalid type for null constant"); 5224 V = Constant::getNullValue(Ty); 5225 return false; 5226 case ValID::t_None: 5227 if (!Ty->isTokenTy()) 5228 return Error(ID.Loc, "invalid type for none constant"); 5229 V = Constant::getNullValue(Ty); 5230 return false; 5231 case ValID::t_Constant: 5232 if (ID.ConstantVal->getType() != Ty) 5233 return Error(ID.Loc, "constant expression type mismatch"); 5234 5235 V = ID.ConstantVal; 5236 return false; 5237 case ValID::t_ConstantStruct: 5238 case ValID::t_PackedConstantStruct: 5239 if (StructType *ST = dyn_cast<StructType>(Ty)) { 5240 if (ST->getNumElements() != ID.UIntVal) 5241 return Error(ID.Loc, 5242 "initializer with struct type has wrong # elements"); 5243 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct)) 5244 return Error(ID.Loc, "packed'ness of initializer and type don't match"); 5245 5246 // Verify that the elements are compatible with the structtype. 5247 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i) 5248 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i)) 5249 return Error(ID.Loc, "element " + Twine(i) + 5250 " of struct initializer doesn't match struct element type"); 5251 5252 V = ConstantStruct::get( 5253 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal)); 5254 } else 5255 return Error(ID.Loc, "constant expression type mismatch"); 5256 return false; 5257 } 5258 llvm_unreachable("Invalid ValID"); 5259 } 5260 5261 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) { 5262 C = nullptr; 5263 ValID ID; 5264 auto Loc = Lex.getLoc(); 5265 if (ParseValID(ID, /*PFS=*/nullptr)) 5266 return true; 5267 switch (ID.Kind) { 5268 case ValID::t_APSInt: 5269 case ValID::t_APFloat: 5270 case ValID::t_Undef: 5271 case ValID::t_Constant: 5272 case ValID::t_ConstantStruct: 5273 case ValID::t_PackedConstantStruct: { 5274 Value *V; 5275 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false)) 5276 return true; 5277 assert(isa<Constant>(V) && "Expected a constant value"); 5278 C = cast<Constant>(V); 5279 return false; 5280 } 5281 case ValID::t_Null: 5282 C = Constant::getNullValue(Ty); 5283 return false; 5284 default: 5285 return Error(Loc, "expected a constant value"); 5286 } 5287 } 5288 5289 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) { 5290 V = nullptr; 5291 ValID ID; 5292 return ParseValID(ID, PFS) || 5293 ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false); 5294 } 5295 5296 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) { 5297 Type *Ty = nullptr; 5298 return ParseType(Ty) || 5299 ParseValue(Ty, V, PFS); 5300 } 5301 5302 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc, 5303 PerFunctionState &PFS) { 5304 Value *V; 5305 Loc = Lex.getLoc(); 5306 if (ParseTypeAndValue(V, PFS)) return true; 5307 if (!isa<BasicBlock>(V)) 5308 return Error(Loc, "expected a basic block"); 5309 BB = cast<BasicBlock>(V); 5310 return false; 5311 } 5312 5313 /// FunctionHeader 5314 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility 5315 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName 5316 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign 5317 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn 5318 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { 5319 // Parse the linkage. 5320 LocTy LinkageLoc = Lex.getLoc(); 5321 unsigned Linkage; 5322 unsigned Visibility; 5323 unsigned DLLStorageClass; 5324 bool DSOLocal; 5325 AttrBuilder RetAttrs; 5326 unsigned CC; 5327 bool HasLinkage; 5328 Type *RetType = nullptr; 5329 LocTy RetTypeLoc = Lex.getLoc(); 5330 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass, 5331 DSOLocal) || 5332 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) || 5333 ParseType(RetType, RetTypeLoc, true /*void allowed*/)) 5334 return true; 5335 5336 // Verify that the linkage is ok. 5337 switch ((GlobalValue::LinkageTypes)Linkage) { 5338 case GlobalValue::ExternalLinkage: 5339 break; // always ok. 5340 case GlobalValue::ExternalWeakLinkage: 5341 if (isDefine) 5342 return Error(LinkageLoc, "invalid linkage for function definition"); 5343 break; 5344 case GlobalValue::PrivateLinkage: 5345 case GlobalValue::InternalLinkage: 5346 case GlobalValue::AvailableExternallyLinkage: 5347 case GlobalValue::LinkOnceAnyLinkage: 5348 case GlobalValue::LinkOnceODRLinkage: 5349 case GlobalValue::WeakAnyLinkage: 5350 case GlobalValue::WeakODRLinkage: 5351 if (!isDefine) 5352 return Error(LinkageLoc, "invalid linkage for function declaration"); 5353 break; 5354 case GlobalValue::AppendingLinkage: 5355 case GlobalValue::CommonLinkage: 5356 return Error(LinkageLoc, "invalid function linkage type"); 5357 } 5358 5359 if (!isValidVisibilityForLinkage(Visibility, Linkage)) 5360 return Error(LinkageLoc, 5361 "symbol with local linkage must have default visibility"); 5362 5363 if (!FunctionType::isValidReturnType(RetType)) 5364 return Error(RetTypeLoc, "invalid function return type"); 5365 5366 LocTy NameLoc = Lex.getLoc(); 5367 5368 std::string FunctionName; 5369 if (Lex.getKind() == lltok::GlobalVar) { 5370 FunctionName = Lex.getStrVal(); 5371 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok. 5372 unsigned NameID = Lex.getUIntVal(); 5373 5374 if (NameID != NumberedVals.size()) 5375 return TokError("function expected to be numbered '%" + 5376 Twine(NumberedVals.size()) + "'"); 5377 } else { 5378 return TokError("expected function name"); 5379 } 5380 5381 Lex.Lex(); 5382 5383 if (Lex.getKind() != lltok::lparen) 5384 return TokError("expected '(' in function argument list"); 5385 5386 SmallVector<ArgInfo, 8> ArgList; 5387 bool isVarArg; 5388 AttrBuilder FuncAttrs; 5389 std::vector<unsigned> FwdRefAttrGrps; 5390 LocTy BuiltinLoc; 5391 std::string Section; 5392 std::string Partition; 5393 MaybeAlign Alignment; 5394 std::string GC; 5395 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 5396 unsigned AddrSpace = 0; 5397 Constant *Prefix = nullptr; 5398 Constant *Prologue = nullptr; 5399 Constant *PersonalityFn = nullptr; 5400 Comdat *C; 5401 5402 if (ParseArgumentList(ArgList, isVarArg) || 5403 ParseOptionalUnnamedAddr(UnnamedAddr) || 5404 ParseOptionalProgramAddrSpace(AddrSpace) || 5405 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false, 5406 BuiltinLoc) || 5407 (EatIfPresent(lltok::kw_section) && 5408 ParseStringConstant(Section)) || 5409 (EatIfPresent(lltok::kw_partition) && 5410 ParseStringConstant(Partition)) || 5411 parseOptionalComdat(FunctionName, C) || 5412 ParseOptionalAlignment(Alignment) || 5413 (EatIfPresent(lltok::kw_gc) && 5414 ParseStringConstant(GC)) || 5415 (EatIfPresent(lltok::kw_prefix) && 5416 ParseGlobalTypeAndValue(Prefix)) || 5417 (EatIfPresent(lltok::kw_prologue) && 5418 ParseGlobalTypeAndValue(Prologue)) || 5419 (EatIfPresent(lltok::kw_personality) && 5420 ParseGlobalTypeAndValue(PersonalityFn))) 5421 return true; 5422 5423 if (FuncAttrs.contains(Attribute::Builtin)) 5424 return Error(BuiltinLoc, "'builtin' attribute not valid on function"); 5425 5426 // If the alignment was parsed as an attribute, move to the alignment field. 5427 if (FuncAttrs.hasAlignmentAttr()) { 5428 Alignment = FuncAttrs.getAlignment(); 5429 FuncAttrs.removeAttribute(Attribute::Alignment); 5430 } 5431 5432 // Okay, if we got here, the function is syntactically valid. Convert types 5433 // and do semantic checks. 5434 std::vector<Type*> ParamTypeList; 5435 SmallVector<AttributeSet, 8> Attrs; 5436 5437 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 5438 ParamTypeList.push_back(ArgList[i].Ty); 5439 Attrs.push_back(ArgList[i].Attrs); 5440 } 5441 5442 AttributeList PAL = 5443 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs), 5444 AttributeSet::get(Context, RetAttrs), Attrs); 5445 5446 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy()) 5447 return Error(RetTypeLoc, "functions with 'sret' argument must return void"); 5448 5449 FunctionType *FT = 5450 FunctionType::get(RetType, ParamTypeList, isVarArg); 5451 PointerType *PFT = PointerType::get(FT, AddrSpace); 5452 5453 Fn = nullptr; 5454 if (!FunctionName.empty()) { 5455 // If this was a definition of a forward reference, remove the definition 5456 // from the forward reference table and fill in the forward ref. 5457 auto FRVI = ForwardRefVals.find(FunctionName); 5458 if (FRVI != ForwardRefVals.end()) { 5459 Fn = M->getFunction(FunctionName); 5460 if (!Fn) 5461 return Error(FRVI->second.second, "invalid forward reference to " 5462 "function as global value!"); 5463 if (Fn->getType() != PFT) 5464 return Error(FRVI->second.second, "invalid forward reference to " 5465 "function '" + FunctionName + "' with wrong type: " 5466 "expected '" + getTypeString(PFT) + "' but was '" + 5467 getTypeString(Fn->getType()) + "'"); 5468 ForwardRefVals.erase(FRVI); 5469 } else if ((Fn = M->getFunction(FunctionName))) { 5470 // Reject redefinitions. 5471 return Error(NameLoc, "invalid redefinition of function '" + 5472 FunctionName + "'"); 5473 } else if (M->getNamedValue(FunctionName)) { 5474 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'"); 5475 } 5476 5477 } else { 5478 // If this is a definition of a forward referenced function, make sure the 5479 // types agree. 5480 auto I = ForwardRefValIDs.find(NumberedVals.size()); 5481 if (I != ForwardRefValIDs.end()) { 5482 Fn = cast<Function>(I->second.first); 5483 if (Fn->getType() != PFT) 5484 return Error(NameLoc, "type of definition and forward reference of '@" + 5485 Twine(NumberedVals.size()) + "' disagree: " 5486 "expected '" + getTypeString(PFT) + "' but was '" + 5487 getTypeString(Fn->getType()) + "'"); 5488 ForwardRefValIDs.erase(I); 5489 } 5490 } 5491 5492 if (!Fn) 5493 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace, 5494 FunctionName, M); 5495 else // Move the forward-reference to the correct spot in the module. 5496 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn); 5497 5498 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS"); 5499 5500 if (FunctionName.empty()) 5501 NumberedVals.push_back(Fn); 5502 5503 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage); 5504 maybeSetDSOLocal(DSOLocal, *Fn); 5505 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility); 5506 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 5507 Fn->setCallingConv(CC); 5508 Fn->setAttributes(PAL); 5509 Fn->setUnnamedAddr(UnnamedAddr); 5510 Fn->setAlignment(MaybeAlign(Alignment)); 5511 Fn->setSection(Section); 5512 Fn->setPartition(Partition); 5513 Fn->setComdat(C); 5514 Fn->setPersonalityFn(PersonalityFn); 5515 if (!GC.empty()) Fn->setGC(GC); 5516 Fn->setPrefixData(Prefix); 5517 Fn->setPrologueData(Prologue); 5518 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps; 5519 5520 // Add all of the arguments we parsed to the function. 5521 Function::arg_iterator ArgIt = Fn->arg_begin(); 5522 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) { 5523 // If the argument has a name, insert it into the argument symbol table. 5524 if (ArgList[i].Name.empty()) continue; 5525 5526 // Set the name, if it conflicted, it will be auto-renamed. 5527 ArgIt->setName(ArgList[i].Name); 5528 5529 if (ArgIt->getName() != ArgList[i].Name) 5530 return Error(ArgList[i].Loc, "redefinition of argument '%" + 5531 ArgList[i].Name + "'"); 5532 } 5533 5534 if (isDefine) 5535 return false; 5536 5537 // Check the declaration has no block address forward references. 5538 ValID ID; 5539 if (FunctionName.empty()) { 5540 ID.Kind = ValID::t_GlobalID; 5541 ID.UIntVal = NumberedVals.size() - 1; 5542 } else { 5543 ID.Kind = ValID::t_GlobalName; 5544 ID.StrVal = FunctionName; 5545 } 5546 auto Blocks = ForwardRefBlockAddresses.find(ID); 5547 if (Blocks != ForwardRefBlockAddresses.end()) 5548 return Error(Blocks->first.Loc, 5549 "cannot take blockaddress inside a declaration"); 5550 return false; 5551 } 5552 5553 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() { 5554 ValID ID; 5555 if (FunctionNumber == -1) { 5556 ID.Kind = ValID::t_GlobalName; 5557 ID.StrVal = std::string(F.getName()); 5558 } else { 5559 ID.Kind = ValID::t_GlobalID; 5560 ID.UIntVal = FunctionNumber; 5561 } 5562 5563 auto Blocks = P.ForwardRefBlockAddresses.find(ID); 5564 if (Blocks == P.ForwardRefBlockAddresses.end()) 5565 return false; 5566 5567 for (const auto &I : Blocks->second) { 5568 const ValID &BBID = I.first; 5569 GlobalValue *GV = I.second; 5570 5571 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) && 5572 "Expected local id or name"); 5573 BasicBlock *BB; 5574 if (BBID.Kind == ValID::t_LocalName) 5575 BB = GetBB(BBID.StrVal, BBID.Loc); 5576 else 5577 BB = GetBB(BBID.UIntVal, BBID.Loc); 5578 if (!BB) 5579 return P.Error(BBID.Loc, "referenced value is not a basic block"); 5580 5581 GV->replaceAllUsesWith(BlockAddress::get(&F, BB)); 5582 GV->eraseFromParent(); 5583 } 5584 5585 P.ForwardRefBlockAddresses.erase(Blocks); 5586 return false; 5587 } 5588 5589 /// ParseFunctionBody 5590 /// ::= '{' BasicBlock+ UseListOrderDirective* '}' 5591 bool LLParser::ParseFunctionBody(Function &Fn) { 5592 if (Lex.getKind() != lltok::lbrace) 5593 return TokError("expected '{' in function body"); 5594 Lex.Lex(); // eat the {. 5595 5596 int FunctionNumber = -1; 5597 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1; 5598 5599 PerFunctionState PFS(*this, Fn, FunctionNumber); 5600 5601 // Resolve block addresses and allow basic blocks to be forward-declared 5602 // within this function. 5603 if (PFS.resolveForwardRefBlockAddresses()) 5604 return true; 5605 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS); 5606 5607 // We need at least one basic block. 5608 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder) 5609 return TokError("function body requires at least one basic block"); 5610 5611 while (Lex.getKind() != lltok::rbrace && 5612 Lex.getKind() != lltok::kw_uselistorder) 5613 if (ParseBasicBlock(PFS)) return true; 5614 5615 while (Lex.getKind() != lltok::rbrace) 5616 if (ParseUseListOrder(&PFS)) 5617 return true; 5618 5619 // Eat the }. 5620 Lex.Lex(); 5621 5622 // Verify function is ok. 5623 return PFS.FinishFunction(); 5624 } 5625 5626 /// ParseBasicBlock 5627 /// ::= (LabelStr|LabelID)? Instruction* 5628 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) { 5629 // If this basic block starts out with a name, remember it. 5630 std::string Name; 5631 int NameID = -1; 5632 LocTy NameLoc = Lex.getLoc(); 5633 if (Lex.getKind() == lltok::LabelStr) { 5634 Name = Lex.getStrVal(); 5635 Lex.Lex(); 5636 } else if (Lex.getKind() == lltok::LabelID) { 5637 NameID = Lex.getUIntVal(); 5638 Lex.Lex(); 5639 } 5640 5641 BasicBlock *BB = PFS.DefineBB(Name, NameID, NameLoc); 5642 if (!BB) 5643 return true; 5644 5645 std::string NameStr; 5646 5647 // Parse the instructions in this block until we get a terminator. 5648 Instruction *Inst; 5649 do { 5650 // This instruction may have three possibilities for a name: a) none 5651 // specified, b) name specified "%foo =", c) number specified: "%4 =". 5652 LocTy NameLoc = Lex.getLoc(); 5653 int NameID = -1; 5654 NameStr = ""; 5655 5656 if (Lex.getKind() == lltok::LocalVarID) { 5657 NameID = Lex.getUIntVal(); 5658 Lex.Lex(); 5659 if (ParseToken(lltok::equal, "expected '=' after instruction id")) 5660 return true; 5661 } else if (Lex.getKind() == lltok::LocalVar) { 5662 NameStr = Lex.getStrVal(); 5663 Lex.Lex(); 5664 if (ParseToken(lltok::equal, "expected '=' after instruction name")) 5665 return true; 5666 } 5667 5668 switch (ParseInstruction(Inst, BB, PFS)) { 5669 default: llvm_unreachable("Unknown ParseInstruction result!"); 5670 case InstError: return true; 5671 case InstNormal: 5672 BB->getInstList().push_back(Inst); 5673 5674 // With a normal result, we check to see if the instruction is followed by 5675 // a comma and metadata. 5676 if (EatIfPresent(lltok::comma)) 5677 if (ParseInstructionMetadata(*Inst)) 5678 return true; 5679 break; 5680 case InstExtraComma: 5681 BB->getInstList().push_back(Inst); 5682 5683 // If the instruction parser ate an extra comma at the end of it, it 5684 // *must* be followed by metadata. 5685 if (ParseInstructionMetadata(*Inst)) 5686 return true; 5687 break; 5688 } 5689 5690 // Set the name on the instruction. 5691 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true; 5692 } while (!Inst->isTerminator()); 5693 5694 return false; 5695 } 5696 5697 //===----------------------------------------------------------------------===// 5698 // Instruction Parsing. 5699 //===----------------------------------------------------------------------===// 5700 5701 /// ParseInstruction - Parse one of the many different instructions. 5702 /// 5703 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB, 5704 PerFunctionState &PFS) { 5705 lltok::Kind Token = Lex.getKind(); 5706 if (Token == lltok::Eof) 5707 return TokError("found end of file when expecting more instructions"); 5708 LocTy Loc = Lex.getLoc(); 5709 unsigned KeywordVal = Lex.getUIntVal(); 5710 Lex.Lex(); // Eat the keyword. 5711 5712 switch (Token) { 5713 default: return Error(Loc, "expected instruction opcode"); 5714 // Terminator Instructions. 5715 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false; 5716 case lltok::kw_ret: return ParseRet(Inst, BB, PFS); 5717 case lltok::kw_br: return ParseBr(Inst, PFS); 5718 case lltok::kw_switch: return ParseSwitch(Inst, PFS); 5719 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS); 5720 case lltok::kw_invoke: return ParseInvoke(Inst, PFS); 5721 case lltok::kw_resume: return ParseResume(Inst, PFS); 5722 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS); 5723 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS); 5724 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS); 5725 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS); 5726 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS); 5727 case lltok::kw_callbr: return ParseCallBr(Inst, PFS); 5728 // Unary Operators. 5729 case lltok::kw_fneg: { 5730 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5731 int Res = ParseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/true); 5732 if (Res != 0) 5733 return Res; 5734 if (FMF.any()) 5735 Inst->setFastMathFlags(FMF); 5736 return false; 5737 } 5738 // Binary Operators. 5739 case lltok::kw_add: 5740 case lltok::kw_sub: 5741 case lltok::kw_mul: 5742 case lltok::kw_shl: { 5743 bool NUW = EatIfPresent(lltok::kw_nuw); 5744 bool NSW = EatIfPresent(lltok::kw_nsw); 5745 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw); 5746 5747 if (ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/false)) return true; 5748 5749 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true); 5750 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true); 5751 return false; 5752 } 5753 case lltok::kw_fadd: 5754 case lltok::kw_fsub: 5755 case lltok::kw_fmul: 5756 case lltok::kw_fdiv: 5757 case lltok::kw_frem: { 5758 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5759 int Res = ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/true); 5760 if (Res != 0) 5761 return Res; 5762 if (FMF.any()) 5763 Inst->setFastMathFlags(FMF); 5764 return 0; 5765 } 5766 5767 case lltok::kw_sdiv: 5768 case lltok::kw_udiv: 5769 case lltok::kw_lshr: 5770 case lltok::kw_ashr: { 5771 bool Exact = EatIfPresent(lltok::kw_exact); 5772 5773 if (ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/false)) return true; 5774 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true); 5775 return false; 5776 } 5777 5778 case lltok::kw_urem: 5779 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 5780 /*IsFP*/false); 5781 case lltok::kw_and: 5782 case lltok::kw_or: 5783 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal); 5784 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal); 5785 case lltok::kw_fcmp: { 5786 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5787 int Res = ParseCompare(Inst, PFS, KeywordVal); 5788 if (Res != 0) 5789 return Res; 5790 if (FMF.any()) 5791 Inst->setFastMathFlags(FMF); 5792 return 0; 5793 } 5794 5795 // Casts. 5796 case lltok::kw_trunc: 5797 case lltok::kw_zext: 5798 case lltok::kw_sext: 5799 case lltok::kw_fptrunc: 5800 case lltok::kw_fpext: 5801 case lltok::kw_bitcast: 5802 case lltok::kw_addrspacecast: 5803 case lltok::kw_uitofp: 5804 case lltok::kw_sitofp: 5805 case lltok::kw_fptoui: 5806 case lltok::kw_fptosi: 5807 case lltok::kw_inttoptr: 5808 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal); 5809 // Other. 5810 case lltok::kw_select: { 5811 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5812 int Res = ParseSelect(Inst, PFS); 5813 if (Res != 0) 5814 return Res; 5815 if (FMF.any()) { 5816 if (!isa<FPMathOperator>(Inst)) 5817 return Error(Loc, "fast-math-flags specified for select without " 5818 "floating-point scalar or vector return type"); 5819 Inst->setFastMathFlags(FMF); 5820 } 5821 return 0; 5822 } 5823 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS); 5824 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS); 5825 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS); 5826 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS); 5827 case lltok::kw_phi: { 5828 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5829 int Res = ParsePHI(Inst, PFS); 5830 if (Res != 0) 5831 return Res; 5832 if (FMF.any()) { 5833 if (!isa<FPMathOperator>(Inst)) 5834 return Error(Loc, "fast-math-flags specified for phi without " 5835 "floating-point scalar or vector return type"); 5836 Inst->setFastMathFlags(FMF); 5837 } 5838 return 0; 5839 } 5840 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS); 5841 case lltok::kw_freeze: return ParseFreeze(Inst, PFS); 5842 // Call. 5843 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None); 5844 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail); 5845 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail); 5846 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail); 5847 // Memory. 5848 case lltok::kw_alloca: return ParseAlloc(Inst, PFS); 5849 case lltok::kw_load: return ParseLoad(Inst, PFS); 5850 case lltok::kw_store: return ParseStore(Inst, PFS); 5851 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS); 5852 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS); 5853 case lltok::kw_fence: return ParseFence(Inst, PFS); 5854 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS); 5855 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS); 5856 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS); 5857 } 5858 } 5859 5860 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind. 5861 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) { 5862 if (Opc == Instruction::FCmp) { 5863 switch (Lex.getKind()) { 5864 default: return TokError("expected fcmp predicate (e.g. 'oeq')"); 5865 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break; 5866 case lltok::kw_one: P = CmpInst::FCMP_ONE; break; 5867 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break; 5868 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break; 5869 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break; 5870 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break; 5871 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break; 5872 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break; 5873 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break; 5874 case lltok::kw_une: P = CmpInst::FCMP_UNE; break; 5875 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break; 5876 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break; 5877 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break; 5878 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break; 5879 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break; 5880 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break; 5881 } 5882 } else { 5883 switch (Lex.getKind()) { 5884 default: return TokError("expected icmp predicate (e.g. 'eq')"); 5885 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break; 5886 case lltok::kw_ne: P = CmpInst::ICMP_NE; break; 5887 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break; 5888 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break; 5889 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break; 5890 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break; 5891 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break; 5892 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break; 5893 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break; 5894 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break; 5895 } 5896 } 5897 Lex.Lex(); 5898 return false; 5899 } 5900 5901 //===----------------------------------------------------------------------===// 5902 // Terminator Instructions. 5903 //===----------------------------------------------------------------------===// 5904 5905 /// ParseRet - Parse a return instruction. 5906 /// ::= 'ret' void (',' !dbg, !1)* 5907 /// ::= 'ret' TypeAndValue (',' !dbg, !1)* 5908 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB, 5909 PerFunctionState &PFS) { 5910 SMLoc TypeLoc = Lex.getLoc(); 5911 Type *Ty = nullptr; 5912 if (ParseType(Ty, true /*void allowed*/)) return true; 5913 5914 Type *ResType = PFS.getFunction().getReturnType(); 5915 5916 if (Ty->isVoidTy()) { 5917 if (!ResType->isVoidTy()) 5918 return Error(TypeLoc, "value doesn't match function result type '" + 5919 getTypeString(ResType) + "'"); 5920 5921 Inst = ReturnInst::Create(Context); 5922 return false; 5923 } 5924 5925 Value *RV; 5926 if (ParseValue(Ty, RV, PFS)) return true; 5927 5928 if (ResType != RV->getType()) 5929 return Error(TypeLoc, "value doesn't match function result type '" + 5930 getTypeString(ResType) + "'"); 5931 5932 Inst = ReturnInst::Create(Context, RV); 5933 return false; 5934 } 5935 5936 /// ParseBr 5937 /// ::= 'br' TypeAndValue 5938 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue 5939 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) { 5940 LocTy Loc, Loc2; 5941 Value *Op0; 5942 BasicBlock *Op1, *Op2; 5943 if (ParseTypeAndValue(Op0, Loc, PFS)) return true; 5944 5945 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) { 5946 Inst = BranchInst::Create(BB); 5947 return false; 5948 } 5949 5950 if (Op0->getType() != Type::getInt1Ty(Context)) 5951 return Error(Loc, "branch condition must have 'i1' type"); 5952 5953 if (ParseToken(lltok::comma, "expected ',' after branch condition") || 5954 ParseTypeAndBasicBlock(Op1, Loc, PFS) || 5955 ParseToken(lltok::comma, "expected ',' after true destination") || 5956 ParseTypeAndBasicBlock(Op2, Loc2, PFS)) 5957 return true; 5958 5959 Inst = BranchInst::Create(Op1, Op2, Op0); 5960 return false; 5961 } 5962 5963 /// ParseSwitch 5964 /// Instruction 5965 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']' 5966 /// JumpTable 5967 /// ::= (TypeAndValue ',' TypeAndValue)* 5968 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) { 5969 LocTy CondLoc, BBLoc; 5970 Value *Cond; 5971 BasicBlock *DefaultBB; 5972 if (ParseTypeAndValue(Cond, CondLoc, PFS) || 5973 ParseToken(lltok::comma, "expected ',' after switch condition") || 5974 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) || 5975 ParseToken(lltok::lsquare, "expected '[' with switch table")) 5976 return true; 5977 5978 if (!Cond->getType()->isIntegerTy()) 5979 return Error(CondLoc, "switch condition must have integer type"); 5980 5981 // Parse the jump table pairs. 5982 SmallPtrSet<Value*, 32> SeenCases; 5983 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table; 5984 while (Lex.getKind() != lltok::rsquare) { 5985 Value *Constant; 5986 BasicBlock *DestBB; 5987 5988 if (ParseTypeAndValue(Constant, CondLoc, PFS) || 5989 ParseToken(lltok::comma, "expected ',' after case value") || 5990 ParseTypeAndBasicBlock(DestBB, PFS)) 5991 return true; 5992 5993 if (!SeenCases.insert(Constant).second) 5994 return Error(CondLoc, "duplicate case value in switch"); 5995 if (!isa<ConstantInt>(Constant)) 5996 return Error(CondLoc, "case value is not a constant integer"); 5997 5998 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB)); 5999 } 6000 6001 Lex.Lex(); // Eat the ']'. 6002 6003 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size()); 6004 for (unsigned i = 0, e = Table.size(); i != e; ++i) 6005 SI->addCase(Table[i].first, Table[i].second); 6006 Inst = SI; 6007 return false; 6008 } 6009 6010 /// ParseIndirectBr 6011 /// Instruction 6012 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']' 6013 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) { 6014 LocTy AddrLoc; 6015 Value *Address; 6016 if (ParseTypeAndValue(Address, AddrLoc, PFS) || 6017 ParseToken(lltok::comma, "expected ',' after indirectbr address") || 6018 ParseToken(lltok::lsquare, "expected '[' with indirectbr")) 6019 return true; 6020 6021 if (!Address->getType()->isPointerTy()) 6022 return Error(AddrLoc, "indirectbr address must have pointer type"); 6023 6024 // Parse the destination list. 6025 SmallVector<BasicBlock*, 16> DestList; 6026 6027 if (Lex.getKind() != lltok::rsquare) { 6028 BasicBlock *DestBB; 6029 if (ParseTypeAndBasicBlock(DestBB, PFS)) 6030 return true; 6031 DestList.push_back(DestBB); 6032 6033 while (EatIfPresent(lltok::comma)) { 6034 if (ParseTypeAndBasicBlock(DestBB, PFS)) 6035 return true; 6036 DestList.push_back(DestBB); 6037 } 6038 } 6039 6040 if (ParseToken(lltok::rsquare, "expected ']' at end of block list")) 6041 return true; 6042 6043 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size()); 6044 for (unsigned i = 0, e = DestList.size(); i != e; ++i) 6045 IBI->addDestination(DestList[i]); 6046 Inst = IBI; 6047 return false; 6048 } 6049 6050 /// ParseInvoke 6051 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList 6052 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue 6053 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) { 6054 LocTy CallLoc = Lex.getLoc(); 6055 AttrBuilder RetAttrs, FnAttrs; 6056 std::vector<unsigned> FwdRefAttrGrps; 6057 LocTy NoBuiltinLoc; 6058 unsigned CC; 6059 unsigned InvokeAddrSpace; 6060 Type *RetType = nullptr; 6061 LocTy RetTypeLoc; 6062 ValID CalleeID; 6063 SmallVector<ParamInfo, 16> ArgList; 6064 SmallVector<OperandBundleDef, 2> BundleList; 6065 6066 BasicBlock *NormalBB, *UnwindBB; 6067 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) || 6068 ParseOptionalProgramAddrSpace(InvokeAddrSpace) || 6069 ParseType(RetType, RetTypeLoc, true /*void allowed*/) || 6070 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) || 6071 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 6072 NoBuiltinLoc) || 6073 ParseOptionalOperandBundles(BundleList, PFS) || 6074 ParseToken(lltok::kw_to, "expected 'to' in invoke") || 6075 ParseTypeAndBasicBlock(NormalBB, PFS) || 6076 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") || 6077 ParseTypeAndBasicBlock(UnwindBB, PFS)) 6078 return true; 6079 6080 // If RetType is a non-function pointer type, then this is the short syntax 6081 // for the call, which means that RetType is just the return type. Infer the 6082 // rest of the function argument types from the arguments that are present. 6083 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 6084 if (!Ty) { 6085 // Pull out the types of all of the arguments... 6086 std::vector<Type*> ParamTypes; 6087 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 6088 ParamTypes.push_back(ArgList[i].V->getType()); 6089 6090 if (!FunctionType::isValidReturnType(RetType)) 6091 return Error(RetTypeLoc, "Invalid result type for LLVM function"); 6092 6093 Ty = FunctionType::get(RetType, ParamTypes, false); 6094 } 6095 6096 CalleeID.FTy = Ty; 6097 6098 // Look up the callee. 6099 Value *Callee; 6100 if (ConvertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID, 6101 Callee, &PFS, /*IsCall=*/true)) 6102 return true; 6103 6104 // Set up the Attribute for the function. 6105 SmallVector<Value *, 8> Args; 6106 SmallVector<AttributeSet, 8> ArgAttrs; 6107 6108 // Loop through FunctionType's arguments and ensure they are specified 6109 // correctly. Also, gather any parameter attributes. 6110 FunctionType::param_iterator I = Ty->param_begin(); 6111 FunctionType::param_iterator E = Ty->param_end(); 6112 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 6113 Type *ExpectedTy = nullptr; 6114 if (I != E) { 6115 ExpectedTy = *I++; 6116 } else if (!Ty->isVarArg()) { 6117 return Error(ArgList[i].Loc, "too many arguments specified"); 6118 } 6119 6120 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 6121 return Error(ArgList[i].Loc, "argument is not of expected type '" + 6122 getTypeString(ExpectedTy) + "'"); 6123 Args.push_back(ArgList[i].V); 6124 ArgAttrs.push_back(ArgList[i].Attrs); 6125 } 6126 6127 if (I != E) 6128 return Error(CallLoc, "not enough parameters specified for call"); 6129 6130 if (FnAttrs.hasAlignmentAttr()) 6131 return Error(CallLoc, "invoke instructions may not have an alignment"); 6132 6133 // Finish off the Attribute and check them 6134 AttributeList PAL = 6135 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 6136 AttributeSet::get(Context, RetAttrs), ArgAttrs); 6137 6138 InvokeInst *II = 6139 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList); 6140 II->setCallingConv(CC); 6141 II->setAttributes(PAL); 6142 ForwardRefAttrGroups[II] = FwdRefAttrGrps; 6143 Inst = II; 6144 return false; 6145 } 6146 6147 /// ParseResume 6148 /// ::= 'resume' TypeAndValue 6149 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) { 6150 Value *Exn; LocTy ExnLoc; 6151 if (ParseTypeAndValue(Exn, ExnLoc, PFS)) 6152 return true; 6153 6154 ResumeInst *RI = ResumeInst::Create(Exn); 6155 Inst = RI; 6156 return false; 6157 } 6158 6159 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args, 6160 PerFunctionState &PFS) { 6161 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad")) 6162 return true; 6163 6164 while (Lex.getKind() != lltok::rsquare) { 6165 // If this isn't the first argument, we need a comma. 6166 if (!Args.empty() && 6167 ParseToken(lltok::comma, "expected ',' in argument list")) 6168 return true; 6169 6170 // Parse the argument. 6171 LocTy ArgLoc; 6172 Type *ArgTy = nullptr; 6173 if (ParseType(ArgTy, ArgLoc)) 6174 return true; 6175 6176 Value *V; 6177 if (ArgTy->isMetadataTy()) { 6178 if (ParseMetadataAsValue(V, PFS)) 6179 return true; 6180 } else { 6181 if (ParseValue(ArgTy, V, PFS)) 6182 return true; 6183 } 6184 Args.push_back(V); 6185 } 6186 6187 Lex.Lex(); // Lex the ']'. 6188 return false; 6189 } 6190 6191 /// ParseCleanupRet 6192 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue) 6193 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) { 6194 Value *CleanupPad = nullptr; 6195 6196 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret")) 6197 return true; 6198 6199 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS)) 6200 return true; 6201 6202 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret")) 6203 return true; 6204 6205 BasicBlock *UnwindBB = nullptr; 6206 if (Lex.getKind() == lltok::kw_to) { 6207 Lex.Lex(); 6208 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret")) 6209 return true; 6210 } else { 6211 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) { 6212 return true; 6213 } 6214 } 6215 6216 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB); 6217 return false; 6218 } 6219 6220 /// ParseCatchRet 6221 /// ::= 'catchret' from Parent Value 'to' TypeAndValue 6222 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) { 6223 Value *CatchPad = nullptr; 6224 6225 if (ParseToken(lltok::kw_from, "expected 'from' after catchret")) 6226 return true; 6227 6228 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS)) 6229 return true; 6230 6231 BasicBlock *BB; 6232 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") || 6233 ParseTypeAndBasicBlock(BB, PFS)) 6234 return true; 6235 6236 Inst = CatchReturnInst::Create(CatchPad, BB); 6237 return false; 6238 } 6239 6240 /// ParseCatchSwitch 6241 /// ::= 'catchswitch' within Parent 6242 bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) { 6243 Value *ParentPad; 6244 6245 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch")) 6246 return true; 6247 6248 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 6249 Lex.getKind() != lltok::LocalVarID) 6250 return TokError("expected scope value for catchswitch"); 6251 6252 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS)) 6253 return true; 6254 6255 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels")) 6256 return true; 6257 6258 SmallVector<BasicBlock *, 32> Table; 6259 do { 6260 BasicBlock *DestBB; 6261 if (ParseTypeAndBasicBlock(DestBB, PFS)) 6262 return true; 6263 Table.push_back(DestBB); 6264 } while (EatIfPresent(lltok::comma)); 6265 6266 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels")) 6267 return true; 6268 6269 if (ParseToken(lltok::kw_unwind, 6270 "expected 'unwind' after catchswitch scope")) 6271 return true; 6272 6273 BasicBlock *UnwindBB = nullptr; 6274 if (EatIfPresent(lltok::kw_to)) { 6275 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch")) 6276 return true; 6277 } else { 6278 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) 6279 return true; 6280 } 6281 6282 auto *CatchSwitch = 6283 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size()); 6284 for (BasicBlock *DestBB : Table) 6285 CatchSwitch->addHandler(DestBB); 6286 Inst = CatchSwitch; 6287 return false; 6288 } 6289 6290 /// ParseCatchPad 6291 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue 6292 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) { 6293 Value *CatchSwitch = nullptr; 6294 6295 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad")) 6296 return true; 6297 6298 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID) 6299 return TokError("expected scope value for catchpad"); 6300 6301 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS)) 6302 return true; 6303 6304 SmallVector<Value *, 8> Args; 6305 if (ParseExceptionArgs(Args, PFS)) 6306 return true; 6307 6308 Inst = CatchPadInst::Create(CatchSwitch, Args); 6309 return false; 6310 } 6311 6312 /// ParseCleanupPad 6313 /// ::= 'cleanuppad' within Parent ParamList 6314 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) { 6315 Value *ParentPad = nullptr; 6316 6317 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad")) 6318 return true; 6319 6320 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 6321 Lex.getKind() != lltok::LocalVarID) 6322 return TokError("expected scope value for cleanuppad"); 6323 6324 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS)) 6325 return true; 6326 6327 SmallVector<Value *, 8> Args; 6328 if (ParseExceptionArgs(Args, PFS)) 6329 return true; 6330 6331 Inst = CleanupPadInst::Create(ParentPad, Args); 6332 return false; 6333 } 6334 6335 //===----------------------------------------------------------------------===// 6336 // Unary Operators. 6337 //===----------------------------------------------------------------------===// 6338 6339 /// ParseUnaryOp 6340 /// ::= UnaryOp TypeAndValue ',' Value 6341 /// 6342 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp 6343 /// operand is allowed. 6344 bool LLParser::ParseUnaryOp(Instruction *&Inst, PerFunctionState &PFS, 6345 unsigned Opc, bool IsFP) { 6346 LocTy Loc; Value *LHS; 6347 if (ParseTypeAndValue(LHS, Loc, PFS)) 6348 return true; 6349 6350 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() 6351 : LHS->getType()->isIntOrIntVectorTy(); 6352 6353 if (!Valid) 6354 return Error(Loc, "invalid operand type for instruction"); 6355 6356 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS); 6357 return false; 6358 } 6359 6360 /// ParseCallBr 6361 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList 6362 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue 6363 /// '[' LabelList ']' 6364 bool LLParser::ParseCallBr(Instruction *&Inst, PerFunctionState &PFS) { 6365 LocTy CallLoc = Lex.getLoc(); 6366 AttrBuilder RetAttrs, FnAttrs; 6367 std::vector<unsigned> FwdRefAttrGrps; 6368 LocTy NoBuiltinLoc; 6369 unsigned CC; 6370 Type *RetType = nullptr; 6371 LocTy RetTypeLoc; 6372 ValID CalleeID; 6373 SmallVector<ParamInfo, 16> ArgList; 6374 SmallVector<OperandBundleDef, 2> BundleList; 6375 6376 BasicBlock *DefaultDest; 6377 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) || 6378 ParseType(RetType, RetTypeLoc, true /*void allowed*/) || 6379 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) || 6380 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 6381 NoBuiltinLoc) || 6382 ParseOptionalOperandBundles(BundleList, PFS) || 6383 ParseToken(lltok::kw_to, "expected 'to' in callbr") || 6384 ParseTypeAndBasicBlock(DefaultDest, PFS) || 6385 ParseToken(lltok::lsquare, "expected '[' in callbr")) 6386 return true; 6387 6388 // Parse the destination list. 6389 SmallVector<BasicBlock *, 16> IndirectDests; 6390 6391 if (Lex.getKind() != lltok::rsquare) { 6392 BasicBlock *DestBB; 6393 if (ParseTypeAndBasicBlock(DestBB, PFS)) 6394 return true; 6395 IndirectDests.push_back(DestBB); 6396 6397 while (EatIfPresent(lltok::comma)) { 6398 if (ParseTypeAndBasicBlock(DestBB, PFS)) 6399 return true; 6400 IndirectDests.push_back(DestBB); 6401 } 6402 } 6403 6404 if (ParseToken(lltok::rsquare, "expected ']' at end of block list")) 6405 return true; 6406 6407 // If RetType is a non-function pointer type, then this is the short syntax 6408 // for the call, which means that RetType is just the return type. Infer the 6409 // rest of the function argument types from the arguments that are present. 6410 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 6411 if (!Ty) { 6412 // Pull out the types of all of the arguments... 6413 std::vector<Type *> ParamTypes; 6414 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 6415 ParamTypes.push_back(ArgList[i].V->getType()); 6416 6417 if (!FunctionType::isValidReturnType(RetType)) 6418 return Error(RetTypeLoc, "Invalid result type for LLVM function"); 6419 6420 Ty = FunctionType::get(RetType, ParamTypes, false); 6421 } 6422 6423 CalleeID.FTy = Ty; 6424 6425 // Look up the callee. 6426 Value *Callee; 6427 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS, 6428 /*IsCall=*/true)) 6429 return true; 6430 6431 // Set up the Attribute for the function. 6432 SmallVector<Value *, 8> Args; 6433 SmallVector<AttributeSet, 8> ArgAttrs; 6434 6435 // Loop through FunctionType's arguments and ensure they are specified 6436 // correctly. Also, gather any parameter attributes. 6437 FunctionType::param_iterator I = Ty->param_begin(); 6438 FunctionType::param_iterator E = Ty->param_end(); 6439 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 6440 Type *ExpectedTy = nullptr; 6441 if (I != E) { 6442 ExpectedTy = *I++; 6443 } else if (!Ty->isVarArg()) { 6444 return Error(ArgList[i].Loc, "too many arguments specified"); 6445 } 6446 6447 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 6448 return Error(ArgList[i].Loc, "argument is not of expected type '" + 6449 getTypeString(ExpectedTy) + "'"); 6450 Args.push_back(ArgList[i].V); 6451 ArgAttrs.push_back(ArgList[i].Attrs); 6452 } 6453 6454 if (I != E) 6455 return Error(CallLoc, "not enough parameters specified for call"); 6456 6457 if (FnAttrs.hasAlignmentAttr()) 6458 return Error(CallLoc, "callbr instructions may not have an alignment"); 6459 6460 // Finish off the Attribute and check them 6461 AttributeList PAL = 6462 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 6463 AttributeSet::get(Context, RetAttrs), ArgAttrs); 6464 6465 CallBrInst *CBI = 6466 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args, 6467 BundleList); 6468 CBI->setCallingConv(CC); 6469 CBI->setAttributes(PAL); 6470 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps; 6471 Inst = CBI; 6472 return false; 6473 } 6474 6475 //===----------------------------------------------------------------------===// 6476 // Binary Operators. 6477 //===----------------------------------------------------------------------===// 6478 6479 /// ParseArithmetic 6480 /// ::= ArithmeticOps TypeAndValue ',' Value 6481 /// 6482 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp 6483 /// operand is allowed. 6484 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS, 6485 unsigned Opc, bool IsFP) { 6486 LocTy Loc; Value *LHS, *RHS; 6487 if (ParseTypeAndValue(LHS, Loc, PFS) || 6488 ParseToken(lltok::comma, "expected ',' in arithmetic operation") || 6489 ParseValue(LHS->getType(), RHS, PFS)) 6490 return true; 6491 6492 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() 6493 : LHS->getType()->isIntOrIntVectorTy(); 6494 6495 if (!Valid) 6496 return Error(Loc, "invalid operand type for instruction"); 6497 6498 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 6499 return false; 6500 } 6501 6502 /// ParseLogical 6503 /// ::= ArithmeticOps TypeAndValue ',' Value { 6504 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS, 6505 unsigned Opc) { 6506 LocTy Loc; Value *LHS, *RHS; 6507 if (ParseTypeAndValue(LHS, Loc, PFS) || 6508 ParseToken(lltok::comma, "expected ',' in logical operation") || 6509 ParseValue(LHS->getType(), RHS, PFS)) 6510 return true; 6511 6512 if (!LHS->getType()->isIntOrIntVectorTy()) 6513 return Error(Loc,"instruction requires integer or integer vector operands"); 6514 6515 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 6516 return false; 6517 } 6518 6519 /// ParseCompare 6520 /// ::= 'icmp' IPredicates TypeAndValue ',' Value 6521 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value 6522 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS, 6523 unsigned Opc) { 6524 // Parse the integer/fp comparison predicate. 6525 LocTy Loc; 6526 unsigned Pred; 6527 Value *LHS, *RHS; 6528 if (ParseCmpPredicate(Pred, Opc) || 6529 ParseTypeAndValue(LHS, Loc, PFS) || 6530 ParseToken(lltok::comma, "expected ',' after compare value") || 6531 ParseValue(LHS->getType(), RHS, PFS)) 6532 return true; 6533 6534 if (Opc == Instruction::FCmp) { 6535 if (!LHS->getType()->isFPOrFPVectorTy()) 6536 return Error(Loc, "fcmp requires floating point operands"); 6537 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS); 6538 } else { 6539 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!"); 6540 if (!LHS->getType()->isIntOrIntVectorTy() && 6541 !LHS->getType()->isPtrOrPtrVectorTy()) 6542 return Error(Loc, "icmp requires integer operands"); 6543 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS); 6544 } 6545 return false; 6546 } 6547 6548 //===----------------------------------------------------------------------===// 6549 // Other Instructions. 6550 //===----------------------------------------------------------------------===// 6551 6552 6553 /// ParseCast 6554 /// ::= CastOpc TypeAndValue 'to' Type 6555 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS, 6556 unsigned Opc) { 6557 LocTy Loc; 6558 Value *Op; 6559 Type *DestTy = nullptr; 6560 if (ParseTypeAndValue(Op, Loc, PFS) || 6561 ParseToken(lltok::kw_to, "expected 'to' after cast value") || 6562 ParseType(DestTy)) 6563 return true; 6564 6565 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) { 6566 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy); 6567 return Error(Loc, "invalid cast opcode for cast from '" + 6568 getTypeString(Op->getType()) + "' to '" + 6569 getTypeString(DestTy) + "'"); 6570 } 6571 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy); 6572 return false; 6573 } 6574 6575 /// ParseSelect 6576 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6577 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) { 6578 LocTy Loc; 6579 Value *Op0, *Op1, *Op2; 6580 if (ParseTypeAndValue(Op0, Loc, PFS) || 6581 ParseToken(lltok::comma, "expected ',' after select condition") || 6582 ParseTypeAndValue(Op1, PFS) || 6583 ParseToken(lltok::comma, "expected ',' after select value") || 6584 ParseTypeAndValue(Op2, PFS)) 6585 return true; 6586 6587 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2)) 6588 return Error(Loc, Reason); 6589 6590 Inst = SelectInst::Create(Op0, Op1, Op2); 6591 return false; 6592 } 6593 6594 /// ParseVA_Arg 6595 /// ::= 'va_arg' TypeAndValue ',' Type 6596 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) { 6597 Value *Op; 6598 Type *EltTy = nullptr; 6599 LocTy TypeLoc; 6600 if (ParseTypeAndValue(Op, PFS) || 6601 ParseToken(lltok::comma, "expected ',' after vaarg operand") || 6602 ParseType(EltTy, TypeLoc)) 6603 return true; 6604 6605 if (!EltTy->isFirstClassType()) 6606 return Error(TypeLoc, "va_arg requires operand with first class type"); 6607 6608 Inst = new VAArgInst(Op, EltTy); 6609 return false; 6610 } 6611 6612 /// ParseExtractElement 6613 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue 6614 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) { 6615 LocTy Loc; 6616 Value *Op0, *Op1; 6617 if (ParseTypeAndValue(Op0, Loc, PFS) || 6618 ParseToken(lltok::comma, "expected ',' after extract value") || 6619 ParseTypeAndValue(Op1, PFS)) 6620 return true; 6621 6622 if (!ExtractElementInst::isValidOperands(Op0, Op1)) 6623 return Error(Loc, "invalid extractelement operands"); 6624 6625 Inst = ExtractElementInst::Create(Op0, Op1); 6626 return false; 6627 } 6628 6629 /// ParseInsertElement 6630 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6631 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) { 6632 LocTy Loc; 6633 Value *Op0, *Op1, *Op2; 6634 if (ParseTypeAndValue(Op0, Loc, PFS) || 6635 ParseToken(lltok::comma, "expected ',' after insertelement value") || 6636 ParseTypeAndValue(Op1, PFS) || 6637 ParseToken(lltok::comma, "expected ',' after insertelement value") || 6638 ParseTypeAndValue(Op2, PFS)) 6639 return true; 6640 6641 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2)) 6642 return Error(Loc, "invalid insertelement operands"); 6643 6644 Inst = InsertElementInst::Create(Op0, Op1, Op2); 6645 return false; 6646 } 6647 6648 /// ParseShuffleVector 6649 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6650 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) { 6651 LocTy Loc; 6652 Value *Op0, *Op1, *Op2; 6653 if (ParseTypeAndValue(Op0, Loc, PFS) || 6654 ParseToken(lltok::comma, "expected ',' after shuffle mask") || 6655 ParseTypeAndValue(Op1, PFS) || 6656 ParseToken(lltok::comma, "expected ',' after shuffle value") || 6657 ParseTypeAndValue(Op2, PFS)) 6658 return true; 6659 6660 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2)) 6661 return Error(Loc, "invalid shufflevector operands"); 6662 6663 Inst = new ShuffleVectorInst(Op0, Op1, Op2); 6664 return false; 6665 } 6666 6667 /// ParsePHI 6668 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')* 6669 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) { 6670 Type *Ty = nullptr; LocTy TypeLoc; 6671 Value *Op0, *Op1; 6672 6673 if (ParseType(Ty, TypeLoc) || 6674 ParseToken(lltok::lsquare, "expected '[' in phi value list") || 6675 ParseValue(Ty, Op0, PFS) || 6676 ParseToken(lltok::comma, "expected ',' after insertelement value") || 6677 ParseValue(Type::getLabelTy(Context), Op1, PFS) || 6678 ParseToken(lltok::rsquare, "expected ']' in phi value list")) 6679 return true; 6680 6681 bool AteExtraComma = false; 6682 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals; 6683 6684 while (true) { 6685 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1))); 6686 6687 if (!EatIfPresent(lltok::comma)) 6688 break; 6689 6690 if (Lex.getKind() == lltok::MetadataVar) { 6691 AteExtraComma = true; 6692 break; 6693 } 6694 6695 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") || 6696 ParseValue(Ty, Op0, PFS) || 6697 ParseToken(lltok::comma, "expected ',' after insertelement value") || 6698 ParseValue(Type::getLabelTy(Context), Op1, PFS) || 6699 ParseToken(lltok::rsquare, "expected ']' in phi value list")) 6700 return true; 6701 } 6702 6703 if (!Ty->isFirstClassType()) 6704 return Error(TypeLoc, "phi node must have first class type"); 6705 6706 PHINode *PN = PHINode::Create(Ty, PHIVals.size()); 6707 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i) 6708 PN->addIncoming(PHIVals[i].first, PHIVals[i].second); 6709 Inst = PN; 6710 return AteExtraComma ? InstExtraComma : InstNormal; 6711 } 6712 6713 /// ParseLandingPad 6714 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+ 6715 /// Clause 6716 /// ::= 'catch' TypeAndValue 6717 /// ::= 'filter' 6718 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )* 6719 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) { 6720 Type *Ty = nullptr; LocTy TyLoc; 6721 6722 if (ParseType(Ty, TyLoc)) 6723 return true; 6724 6725 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0)); 6726 LP->setCleanup(EatIfPresent(lltok::kw_cleanup)); 6727 6728 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){ 6729 LandingPadInst::ClauseType CT; 6730 if (EatIfPresent(lltok::kw_catch)) 6731 CT = LandingPadInst::Catch; 6732 else if (EatIfPresent(lltok::kw_filter)) 6733 CT = LandingPadInst::Filter; 6734 else 6735 return TokError("expected 'catch' or 'filter' clause type"); 6736 6737 Value *V; 6738 LocTy VLoc; 6739 if (ParseTypeAndValue(V, VLoc, PFS)) 6740 return true; 6741 6742 // A 'catch' type expects a non-array constant. A filter clause expects an 6743 // array constant. 6744 if (CT == LandingPadInst::Catch) { 6745 if (isa<ArrayType>(V->getType())) 6746 Error(VLoc, "'catch' clause has an invalid type"); 6747 } else { 6748 if (!isa<ArrayType>(V->getType())) 6749 Error(VLoc, "'filter' clause has an invalid type"); 6750 } 6751 6752 Constant *CV = dyn_cast<Constant>(V); 6753 if (!CV) 6754 return Error(VLoc, "clause argument must be a constant"); 6755 LP->addClause(CV); 6756 } 6757 6758 Inst = LP.release(); 6759 return false; 6760 } 6761 6762 /// ParseFreeze 6763 /// ::= 'freeze' Type Value 6764 bool LLParser::ParseFreeze(Instruction *&Inst, PerFunctionState &PFS) { 6765 LocTy Loc; 6766 Value *Op; 6767 if (ParseTypeAndValue(Op, Loc, PFS)) 6768 return true; 6769 6770 Inst = new FreezeInst(Op); 6771 return false; 6772 } 6773 6774 /// ParseCall 6775 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv 6776 /// OptionalAttrs Type Value ParameterList OptionalAttrs 6777 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv 6778 /// OptionalAttrs Type Value ParameterList OptionalAttrs 6779 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv 6780 /// OptionalAttrs Type Value ParameterList OptionalAttrs 6781 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv 6782 /// OptionalAttrs Type Value ParameterList OptionalAttrs 6783 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, 6784 CallInst::TailCallKind TCK) { 6785 AttrBuilder RetAttrs, FnAttrs; 6786 std::vector<unsigned> FwdRefAttrGrps; 6787 LocTy BuiltinLoc; 6788 unsigned CallAddrSpace; 6789 unsigned CC; 6790 Type *RetType = nullptr; 6791 LocTy RetTypeLoc; 6792 ValID CalleeID; 6793 SmallVector<ParamInfo, 16> ArgList; 6794 SmallVector<OperandBundleDef, 2> BundleList; 6795 LocTy CallLoc = Lex.getLoc(); 6796 6797 if (TCK != CallInst::TCK_None && 6798 ParseToken(lltok::kw_call, 6799 "expected 'tail call', 'musttail call', or 'notail call'")) 6800 return true; 6801 6802 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6803 6804 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) || 6805 ParseOptionalProgramAddrSpace(CallAddrSpace) || 6806 ParseType(RetType, RetTypeLoc, true /*void allowed*/) || 6807 ParseValID(CalleeID) || 6808 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail, 6809 PFS.getFunction().isVarArg()) || 6810 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) || 6811 ParseOptionalOperandBundles(BundleList, PFS)) 6812 return true; 6813 6814 // If RetType is a non-function pointer type, then this is the short syntax 6815 // for the call, which means that RetType is just the return type. Infer the 6816 // rest of the function argument types from the arguments that are present. 6817 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 6818 if (!Ty) { 6819 // Pull out the types of all of the arguments... 6820 std::vector<Type*> ParamTypes; 6821 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 6822 ParamTypes.push_back(ArgList[i].V->getType()); 6823 6824 if (!FunctionType::isValidReturnType(RetType)) 6825 return Error(RetTypeLoc, "Invalid result type for LLVM function"); 6826 6827 Ty = FunctionType::get(RetType, ParamTypes, false); 6828 } 6829 6830 CalleeID.FTy = Ty; 6831 6832 // Look up the callee. 6833 Value *Callee; 6834 if (ConvertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee, 6835 &PFS, /*IsCall=*/true)) 6836 return true; 6837 6838 // Set up the Attribute for the function. 6839 SmallVector<AttributeSet, 8> Attrs; 6840 6841 SmallVector<Value*, 8> Args; 6842 6843 // Loop through FunctionType's arguments and ensure they are specified 6844 // correctly. Also, gather any parameter attributes. 6845 FunctionType::param_iterator I = Ty->param_begin(); 6846 FunctionType::param_iterator E = Ty->param_end(); 6847 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 6848 Type *ExpectedTy = nullptr; 6849 if (I != E) { 6850 ExpectedTy = *I++; 6851 } else if (!Ty->isVarArg()) { 6852 return Error(ArgList[i].Loc, "too many arguments specified"); 6853 } 6854 6855 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 6856 return Error(ArgList[i].Loc, "argument is not of expected type '" + 6857 getTypeString(ExpectedTy) + "'"); 6858 Args.push_back(ArgList[i].V); 6859 Attrs.push_back(ArgList[i].Attrs); 6860 } 6861 6862 if (I != E) 6863 return Error(CallLoc, "not enough parameters specified for call"); 6864 6865 if (FnAttrs.hasAlignmentAttr()) 6866 return Error(CallLoc, "call instructions may not have an alignment"); 6867 6868 // Finish off the Attribute and check them 6869 AttributeList PAL = 6870 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 6871 AttributeSet::get(Context, RetAttrs), Attrs); 6872 6873 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList); 6874 CI->setTailCallKind(TCK); 6875 CI->setCallingConv(CC); 6876 if (FMF.any()) { 6877 if (!isa<FPMathOperator>(CI)) 6878 return Error(CallLoc, "fast-math-flags specified for call without " 6879 "floating-point scalar or vector return type"); 6880 CI->setFastMathFlags(FMF); 6881 } 6882 CI->setAttributes(PAL); 6883 ForwardRefAttrGroups[CI] = FwdRefAttrGrps; 6884 Inst = CI; 6885 return false; 6886 } 6887 6888 //===----------------------------------------------------------------------===// 6889 // Memory Instructions. 6890 //===----------------------------------------------------------------------===// 6891 6892 /// ParseAlloc 6893 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)? 6894 /// (',' 'align' i32)? (',', 'addrspace(n))? 6895 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) { 6896 Value *Size = nullptr; 6897 LocTy SizeLoc, TyLoc, ASLoc; 6898 MaybeAlign Alignment; 6899 unsigned AddrSpace = 0; 6900 Type *Ty = nullptr; 6901 6902 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca); 6903 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror); 6904 6905 if (ParseType(Ty, TyLoc)) return true; 6906 6907 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty)) 6908 return Error(TyLoc, "invalid type for alloca"); 6909 6910 bool AteExtraComma = false; 6911 if (EatIfPresent(lltok::comma)) { 6912 if (Lex.getKind() == lltok::kw_align) { 6913 if (ParseOptionalAlignment(Alignment)) 6914 return true; 6915 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)) 6916 return true; 6917 } else if (Lex.getKind() == lltok::kw_addrspace) { 6918 ASLoc = Lex.getLoc(); 6919 if (ParseOptionalAddrSpace(AddrSpace)) 6920 return true; 6921 } else if (Lex.getKind() == lltok::MetadataVar) { 6922 AteExtraComma = true; 6923 } else { 6924 if (ParseTypeAndValue(Size, SizeLoc, PFS)) 6925 return true; 6926 if (EatIfPresent(lltok::comma)) { 6927 if (Lex.getKind() == lltok::kw_align) { 6928 if (ParseOptionalAlignment(Alignment)) 6929 return true; 6930 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)) 6931 return true; 6932 } else if (Lex.getKind() == lltok::kw_addrspace) { 6933 ASLoc = Lex.getLoc(); 6934 if (ParseOptionalAddrSpace(AddrSpace)) 6935 return true; 6936 } else if (Lex.getKind() == lltok::MetadataVar) { 6937 AteExtraComma = true; 6938 } 6939 } 6940 } 6941 } 6942 6943 if (Size && !Size->getType()->isIntegerTy()) 6944 return Error(SizeLoc, "element count must have integer type"); 6945 6946 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, Alignment); 6947 AI->setUsedWithInAlloca(IsInAlloca); 6948 AI->setSwiftError(IsSwiftError); 6949 Inst = AI; 6950 return AteExtraComma ? InstExtraComma : InstNormal; 6951 } 6952 6953 /// ParseLoad 6954 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)? 6955 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue 6956 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 6957 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) { 6958 Value *Val; LocTy Loc; 6959 MaybeAlign Alignment; 6960 bool AteExtraComma = false; 6961 bool isAtomic = false; 6962 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 6963 SyncScope::ID SSID = SyncScope::System; 6964 6965 if (Lex.getKind() == lltok::kw_atomic) { 6966 isAtomic = true; 6967 Lex.Lex(); 6968 } 6969 6970 bool isVolatile = false; 6971 if (Lex.getKind() == lltok::kw_volatile) { 6972 isVolatile = true; 6973 Lex.Lex(); 6974 } 6975 6976 Type *Ty; 6977 LocTy ExplicitTypeLoc = Lex.getLoc(); 6978 if (ParseType(Ty) || 6979 ParseToken(lltok::comma, "expected comma after load's type") || 6980 ParseTypeAndValue(Val, Loc, PFS) || 6981 ParseScopeAndOrdering(isAtomic, SSID, Ordering) || 6982 ParseOptionalCommaAlign(Alignment, AteExtraComma)) 6983 return true; 6984 6985 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType()) 6986 return Error(Loc, "load operand must be a pointer to a first class type"); 6987 if (isAtomic && !Alignment) 6988 return Error(Loc, "atomic load must have explicit non-zero alignment"); 6989 if (Ordering == AtomicOrdering::Release || 6990 Ordering == AtomicOrdering::AcquireRelease) 6991 return Error(Loc, "atomic load cannot use Release ordering"); 6992 6993 if (Ty != cast<PointerType>(Val->getType())->getElementType()) 6994 return Error(ExplicitTypeLoc, 6995 "explicit pointee type doesn't match operand's pointee type"); 6996 6997 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID); 6998 return AteExtraComma ? InstExtraComma : InstNormal; 6999 } 7000 7001 /// ParseStore 7002 7003 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)? 7004 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue 7005 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 7006 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) { 7007 Value *Val, *Ptr; LocTy Loc, PtrLoc; 7008 MaybeAlign Alignment; 7009 bool AteExtraComma = false; 7010 bool isAtomic = false; 7011 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7012 SyncScope::ID SSID = SyncScope::System; 7013 7014 if (Lex.getKind() == lltok::kw_atomic) { 7015 isAtomic = true; 7016 Lex.Lex(); 7017 } 7018 7019 bool isVolatile = false; 7020 if (Lex.getKind() == lltok::kw_volatile) { 7021 isVolatile = true; 7022 Lex.Lex(); 7023 } 7024 7025 if (ParseTypeAndValue(Val, Loc, PFS) || 7026 ParseToken(lltok::comma, "expected ',' after store operand") || 7027 ParseTypeAndValue(Ptr, PtrLoc, PFS) || 7028 ParseScopeAndOrdering(isAtomic, SSID, Ordering) || 7029 ParseOptionalCommaAlign(Alignment, AteExtraComma)) 7030 return true; 7031 7032 if (!Ptr->getType()->isPointerTy()) 7033 return Error(PtrLoc, "store operand must be a pointer"); 7034 if (!Val->getType()->isFirstClassType()) 7035 return Error(Loc, "store operand must be a first class value"); 7036 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType()) 7037 return Error(Loc, "stored value and pointer type do not match"); 7038 if (isAtomic && !Alignment) 7039 return Error(Loc, "atomic store must have explicit non-zero alignment"); 7040 if (Ordering == AtomicOrdering::Acquire || 7041 Ordering == AtomicOrdering::AcquireRelease) 7042 return Error(Loc, "atomic store cannot use Acquire ordering"); 7043 7044 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID); 7045 return AteExtraComma ? InstExtraComma : InstNormal; 7046 } 7047 7048 /// ParseCmpXchg 7049 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ',' 7050 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering 7051 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) { 7052 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc; 7053 bool AteExtraComma = false; 7054 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic; 7055 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic; 7056 SyncScope::ID SSID = SyncScope::System; 7057 bool isVolatile = false; 7058 bool isWeak = false; 7059 7060 if (EatIfPresent(lltok::kw_weak)) 7061 isWeak = true; 7062 7063 if (EatIfPresent(lltok::kw_volatile)) 7064 isVolatile = true; 7065 7066 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) || 7067 ParseToken(lltok::comma, "expected ',' after cmpxchg address") || 7068 ParseTypeAndValue(Cmp, CmpLoc, PFS) || 7069 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") || 7070 ParseTypeAndValue(New, NewLoc, PFS) || 7071 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) || 7072 ParseOrdering(FailureOrdering)) 7073 return true; 7074 7075 if (SuccessOrdering == AtomicOrdering::Unordered || 7076 FailureOrdering == AtomicOrdering::Unordered) 7077 return TokError("cmpxchg cannot be unordered"); 7078 if (isStrongerThan(FailureOrdering, SuccessOrdering)) 7079 return TokError("cmpxchg failure argument shall be no stronger than the " 7080 "success argument"); 7081 if (FailureOrdering == AtomicOrdering::Release || 7082 FailureOrdering == AtomicOrdering::AcquireRelease) 7083 return TokError( 7084 "cmpxchg failure ordering cannot include release semantics"); 7085 if (!Ptr->getType()->isPointerTy()) 7086 return Error(PtrLoc, "cmpxchg operand must be a pointer"); 7087 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType()) 7088 return Error(CmpLoc, "compare value and pointer type do not match"); 7089 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType()) 7090 return Error(NewLoc, "new value and pointer type do not match"); 7091 if (!New->getType()->isFirstClassType()) 7092 return Error(NewLoc, "cmpxchg operand must be a first class value"); 7093 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst( 7094 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID); 7095 CXI->setVolatile(isVolatile); 7096 CXI->setWeak(isWeak); 7097 Inst = CXI; 7098 return AteExtraComma ? InstExtraComma : InstNormal; 7099 } 7100 7101 /// ParseAtomicRMW 7102 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue 7103 /// 'singlethread'? AtomicOrdering 7104 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) { 7105 Value *Ptr, *Val; LocTy PtrLoc, ValLoc; 7106 bool AteExtraComma = false; 7107 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7108 SyncScope::ID SSID = SyncScope::System; 7109 bool isVolatile = false; 7110 bool IsFP = false; 7111 AtomicRMWInst::BinOp Operation; 7112 7113 if (EatIfPresent(lltok::kw_volatile)) 7114 isVolatile = true; 7115 7116 switch (Lex.getKind()) { 7117 default: return TokError("expected binary operation in atomicrmw"); 7118 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break; 7119 case lltok::kw_add: Operation = AtomicRMWInst::Add; break; 7120 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break; 7121 case lltok::kw_and: Operation = AtomicRMWInst::And; break; 7122 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break; 7123 case lltok::kw_or: Operation = AtomicRMWInst::Or; break; 7124 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break; 7125 case lltok::kw_max: Operation = AtomicRMWInst::Max; break; 7126 case lltok::kw_min: Operation = AtomicRMWInst::Min; break; 7127 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break; 7128 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break; 7129 case lltok::kw_fadd: 7130 Operation = AtomicRMWInst::FAdd; 7131 IsFP = true; 7132 break; 7133 case lltok::kw_fsub: 7134 Operation = AtomicRMWInst::FSub; 7135 IsFP = true; 7136 break; 7137 } 7138 Lex.Lex(); // Eat the operation. 7139 7140 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) || 7141 ParseToken(lltok::comma, "expected ',' after atomicrmw address") || 7142 ParseTypeAndValue(Val, ValLoc, PFS) || 7143 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering)) 7144 return true; 7145 7146 if (Ordering == AtomicOrdering::Unordered) 7147 return TokError("atomicrmw cannot be unordered"); 7148 if (!Ptr->getType()->isPointerTy()) 7149 return Error(PtrLoc, "atomicrmw operand must be a pointer"); 7150 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType()) 7151 return Error(ValLoc, "atomicrmw value and pointer type do not match"); 7152 7153 if (Operation == AtomicRMWInst::Xchg) { 7154 if (!Val->getType()->isIntegerTy() && 7155 !Val->getType()->isFloatingPointTy()) { 7156 return Error(ValLoc, "atomicrmw " + 7157 AtomicRMWInst::getOperationName(Operation) + 7158 " operand must be an integer or floating point type"); 7159 } 7160 } else if (IsFP) { 7161 if (!Val->getType()->isFloatingPointTy()) { 7162 return Error(ValLoc, "atomicrmw " + 7163 AtomicRMWInst::getOperationName(Operation) + 7164 " operand must be a floating point type"); 7165 } 7166 } else { 7167 if (!Val->getType()->isIntegerTy()) { 7168 return Error(ValLoc, "atomicrmw " + 7169 AtomicRMWInst::getOperationName(Operation) + 7170 " operand must be an integer"); 7171 } 7172 } 7173 7174 unsigned Size = Val->getType()->getPrimitiveSizeInBits(); 7175 if (Size < 8 || (Size & (Size - 1))) 7176 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized" 7177 " integer"); 7178 7179 AtomicRMWInst *RMWI = 7180 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID); 7181 RMWI->setVolatile(isVolatile); 7182 Inst = RMWI; 7183 return AteExtraComma ? InstExtraComma : InstNormal; 7184 } 7185 7186 /// ParseFence 7187 /// ::= 'fence' 'singlethread'? AtomicOrdering 7188 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) { 7189 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7190 SyncScope::ID SSID = SyncScope::System; 7191 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering)) 7192 return true; 7193 7194 if (Ordering == AtomicOrdering::Unordered) 7195 return TokError("fence cannot be unordered"); 7196 if (Ordering == AtomicOrdering::Monotonic) 7197 return TokError("fence cannot be monotonic"); 7198 7199 Inst = new FenceInst(Context, Ordering, SSID); 7200 return InstNormal; 7201 } 7202 7203 /// ParseGetElementPtr 7204 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)* 7205 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { 7206 Value *Ptr = nullptr; 7207 Value *Val = nullptr; 7208 LocTy Loc, EltLoc; 7209 7210 bool InBounds = EatIfPresent(lltok::kw_inbounds); 7211 7212 Type *Ty = nullptr; 7213 LocTy ExplicitTypeLoc = Lex.getLoc(); 7214 if (ParseType(Ty) || 7215 ParseToken(lltok::comma, "expected comma after getelementptr's type") || 7216 ParseTypeAndValue(Ptr, Loc, PFS)) 7217 return true; 7218 7219 Type *BaseType = Ptr->getType(); 7220 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType()); 7221 if (!BasePointerType) 7222 return Error(Loc, "base of getelementptr must be a pointer"); 7223 7224 if (Ty != BasePointerType->getElementType()) 7225 return Error(ExplicitTypeLoc, 7226 "explicit pointee type doesn't match operand's pointee type"); 7227 7228 SmallVector<Value*, 16> Indices; 7229 bool AteExtraComma = false; 7230 // GEP returns a vector of pointers if at least one of parameters is a vector. 7231 // All vector parameters should have the same vector width. 7232 ElementCount GEPWidth = BaseType->isVectorTy() ? 7233 BaseType->getVectorElementCount() : ElementCount(0, false); 7234 7235 while (EatIfPresent(lltok::comma)) { 7236 if (Lex.getKind() == lltok::MetadataVar) { 7237 AteExtraComma = true; 7238 break; 7239 } 7240 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true; 7241 if (!Val->getType()->isIntOrIntVectorTy()) 7242 return Error(EltLoc, "getelementptr index must be an integer"); 7243 7244 if (Val->getType()->isVectorTy()) { 7245 ElementCount ValNumEl = Val->getType()->getVectorElementCount(); 7246 if (GEPWidth != ElementCount(0, false) && GEPWidth != ValNumEl) 7247 return Error(EltLoc, 7248 "getelementptr vector index has a wrong number of elements"); 7249 GEPWidth = ValNumEl; 7250 } 7251 Indices.push_back(Val); 7252 } 7253 7254 SmallPtrSet<Type*, 4> Visited; 7255 if (!Indices.empty() && !Ty->isSized(&Visited)) 7256 return Error(Loc, "base element of getelementptr must be sized"); 7257 7258 if (!GetElementPtrInst::getIndexedType(Ty, Indices)) 7259 return Error(Loc, "invalid getelementptr indices"); 7260 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices); 7261 if (InBounds) 7262 cast<GetElementPtrInst>(Inst)->setIsInBounds(true); 7263 return AteExtraComma ? InstExtraComma : InstNormal; 7264 } 7265 7266 /// ParseExtractValue 7267 /// ::= 'extractvalue' TypeAndValue (',' uint32)+ 7268 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) { 7269 Value *Val; LocTy Loc; 7270 SmallVector<unsigned, 4> Indices; 7271 bool AteExtraComma; 7272 if (ParseTypeAndValue(Val, Loc, PFS) || 7273 ParseIndexList(Indices, AteExtraComma)) 7274 return true; 7275 7276 if (!Val->getType()->isAggregateType()) 7277 return Error(Loc, "extractvalue operand must be aggregate type"); 7278 7279 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 7280 return Error(Loc, "invalid indices for extractvalue"); 7281 Inst = ExtractValueInst::Create(Val, Indices); 7282 return AteExtraComma ? InstExtraComma : InstNormal; 7283 } 7284 7285 /// ParseInsertValue 7286 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+ 7287 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { 7288 Value *Val0, *Val1; LocTy Loc0, Loc1; 7289 SmallVector<unsigned, 4> Indices; 7290 bool AteExtraComma; 7291 if (ParseTypeAndValue(Val0, Loc0, PFS) || 7292 ParseToken(lltok::comma, "expected comma after insertvalue operand") || 7293 ParseTypeAndValue(Val1, Loc1, PFS) || 7294 ParseIndexList(Indices, AteExtraComma)) 7295 return true; 7296 7297 if (!Val0->getType()->isAggregateType()) 7298 return Error(Loc0, "insertvalue operand must be aggregate type"); 7299 7300 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices); 7301 if (!IndexedType) 7302 return Error(Loc0, "invalid indices for insertvalue"); 7303 if (IndexedType != Val1->getType()) 7304 return Error(Loc1, "insertvalue operand and field disagree in type: '" + 7305 getTypeString(Val1->getType()) + "' instead of '" + 7306 getTypeString(IndexedType) + "'"); 7307 Inst = InsertValueInst::Create(Val0, Val1, Indices); 7308 return AteExtraComma ? InstExtraComma : InstNormal; 7309 } 7310 7311 //===----------------------------------------------------------------------===// 7312 // Embedded metadata. 7313 //===----------------------------------------------------------------------===// 7314 7315 /// ParseMDNodeVector 7316 /// ::= { Element (',' Element)* } 7317 /// Element 7318 /// ::= 'null' | TypeAndValue 7319 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) { 7320 if (ParseToken(lltok::lbrace, "expected '{' here")) 7321 return true; 7322 7323 // Check for an empty list. 7324 if (EatIfPresent(lltok::rbrace)) 7325 return false; 7326 7327 do { 7328 // Null is a special case since it is typeless. 7329 if (EatIfPresent(lltok::kw_null)) { 7330 Elts.push_back(nullptr); 7331 continue; 7332 } 7333 7334 Metadata *MD; 7335 if (ParseMetadata(MD, nullptr)) 7336 return true; 7337 Elts.push_back(MD); 7338 } while (EatIfPresent(lltok::comma)); 7339 7340 return ParseToken(lltok::rbrace, "expected end of metadata node"); 7341 } 7342 7343 //===----------------------------------------------------------------------===// 7344 // Use-list order directives. 7345 //===----------------------------------------------------------------------===// 7346 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, 7347 SMLoc Loc) { 7348 if (V->use_empty()) 7349 return Error(Loc, "value has no uses"); 7350 7351 unsigned NumUses = 0; 7352 SmallDenseMap<const Use *, unsigned, 16> Order; 7353 for (const Use &U : V->uses()) { 7354 if (++NumUses > Indexes.size()) 7355 break; 7356 Order[&U] = Indexes[NumUses - 1]; 7357 } 7358 if (NumUses < 2) 7359 return Error(Loc, "value only has one use"); 7360 if (Order.size() != Indexes.size() || NumUses > Indexes.size()) 7361 return Error(Loc, 7362 "wrong number of indexes, expected " + Twine(V->getNumUses())); 7363 7364 V->sortUseList([&](const Use &L, const Use &R) { 7365 return Order.lookup(&L) < Order.lookup(&R); 7366 }); 7367 return false; 7368 } 7369 7370 /// ParseUseListOrderIndexes 7371 /// ::= '{' uint32 (',' uint32)+ '}' 7372 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) { 7373 SMLoc Loc = Lex.getLoc(); 7374 if (ParseToken(lltok::lbrace, "expected '{' here")) 7375 return true; 7376 if (Lex.getKind() == lltok::rbrace) 7377 return Lex.Error("expected non-empty list of uselistorder indexes"); 7378 7379 // Use Offset, Max, and IsOrdered to check consistency of indexes. The 7380 // indexes should be distinct numbers in the range [0, size-1], and should 7381 // not be in order. 7382 unsigned Offset = 0; 7383 unsigned Max = 0; 7384 bool IsOrdered = true; 7385 assert(Indexes.empty() && "Expected empty order vector"); 7386 do { 7387 unsigned Index; 7388 if (ParseUInt32(Index)) 7389 return true; 7390 7391 // Update consistency checks. 7392 Offset += Index - Indexes.size(); 7393 Max = std::max(Max, Index); 7394 IsOrdered &= Index == Indexes.size(); 7395 7396 Indexes.push_back(Index); 7397 } while (EatIfPresent(lltok::comma)); 7398 7399 if (ParseToken(lltok::rbrace, "expected '}' here")) 7400 return true; 7401 7402 if (Indexes.size() < 2) 7403 return Error(Loc, "expected >= 2 uselistorder indexes"); 7404 if (Offset != 0 || Max >= Indexes.size()) 7405 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)"); 7406 if (IsOrdered) 7407 return Error(Loc, "expected uselistorder indexes to change the order"); 7408 7409 return false; 7410 } 7411 7412 /// ParseUseListOrder 7413 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes 7414 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) { 7415 SMLoc Loc = Lex.getLoc(); 7416 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive")) 7417 return true; 7418 7419 Value *V; 7420 SmallVector<unsigned, 16> Indexes; 7421 if (ParseTypeAndValue(V, PFS) || 7422 ParseToken(lltok::comma, "expected comma in uselistorder directive") || 7423 ParseUseListOrderIndexes(Indexes)) 7424 return true; 7425 7426 return sortUseListOrder(V, Indexes, Loc); 7427 } 7428 7429 /// ParseUseListOrderBB 7430 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes 7431 bool LLParser::ParseUseListOrderBB() { 7432 assert(Lex.getKind() == lltok::kw_uselistorder_bb); 7433 SMLoc Loc = Lex.getLoc(); 7434 Lex.Lex(); 7435 7436 ValID Fn, Label; 7437 SmallVector<unsigned, 16> Indexes; 7438 if (ParseValID(Fn) || 7439 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 7440 ParseValID(Label) || 7441 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 7442 ParseUseListOrderIndexes(Indexes)) 7443 return true; 7444 7445 // Check the function. 7446 GlobalValue *GV; 7447 if (Fn.Kind == ValID::t_GlobalName) 7448 GV = M->getNamedValue(Fn.StrVal); 7449 else if (Fn.Kind == ValID::t_GlobalID) 7450 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr; 7451 else 7452 return Error(Fn.Loc, "expected function name in uselistorder_bb"); 7453 if (!GV) 7454 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb"); 7455 auto *F = dyn_cast<Function>(GV); 7456 if (!F) 7457 return Error(Fn.Loc, "expected function name in uselistorder_bb"); 7458 if (F->isDeclaration()) 7459 return Error(Fn.Loc, "invalid declaration in uselistorder_bb"); 7460 7461 // Check the basic block. 7462 if (Label.Kind == ValID::t_LocalID) 7463 return Error(Label.Loc, "invalid numeric label in uselistorder_bb"); 7464 if (Label.Kind != ValID::t_LocalName) 7465 return Error(Label.Loc, "expected basic block name in uselistorder_bb"); 7466 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal); 7467 if (!V) 7468 return Error(Label.Loc, "invalid basic block in uselistorder_bb"); 7469 if (!isa<BasicBlock>(V)) 7470 return Error(Label.Loc, "expected basic block in uselistorder_bb"); 7471 7472 return sortUseListOrder(V, Indexes, Loc); 7473 } 7474 7475 /// ModuleEntry 7476 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')' 7477 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')' 7478 bool LLParser::ParseModuleEntry(unsigned ID) { 7479 assert(Lex.getKind() == lltok::kw_module); 7480 Lex.Lex(); 7481 7482 std::string Path; 7483 if (ParseToken(lltok::colon, "expected ':' here") || 7484 ParseToken(lltok::lparen, "expected '(' here") || 7485 ParseToken(lltok::kw_path, "expected 'path' here") || 7486 ParseToken(lltok::colon, "expected ':' here") || 7487 ParseStringConstant(Path) || 7488 ParseToken(lltok::comma, "expected ',' here") || 7489 ParseToken(lltok::kw_hash, "expected 'hash' here") || 7490 ParseToken(lltok::colon, "expected ':' here") || 7491 ParseToken(lltok::lparen, "expected '(' here")) 7492 return true; 7493 7494 ModuleHash Hash; 7495 if (ParseUInt32(Hash[0]) || ParseToken(lltok::comma, "expected ',' here") || 7496 ParseUInt32(Hash[1]) || ParseToken(lltok::comma, "expected ',' here") || 7497 ParseUInt32(Hash[2]) || ParseToken(lltok::comma, "expected ',' here") || 7498 ParseUInt32(Hash[3]) || ParseToken(lltok::comma, "expected ',' here") || 7499 ParseUInt32(Hash[4])) 7500 return true; 7501 7502 if (ParseToken(lltok::rparen, "expected ')' here") || 7503 ParseToken(lltok::rparen, "expected ')' here")) 7504 return true; 7505 7506 auto ModuleEntry = Index->addModule(Path, ID, Hash); 7507 ModuleIdMap[ID] = ModuleEntry->first(); 7508 7509 return false; 7510 } 7511 7512 /// TypeIdEntry 7513 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')' 7514 bool LLParser::ParseTypeIdEntry(unsigned ID) { 7515 assert(Lex.getKind() == lltok::kw_typeid); 7516 Lex.Lex(); 7517 7518 std::string Name; 7519 if (ParseToken(lltok::colon, "expected ':' here") || 7520 ParseToken(lltok::lparen, "expected '(' here") || 7521 ParseToken(lltok::kw_name, "expected 'name' here") || 7522 ParseToken(lltok::colon, "expected ':' here") || 7523 ParseStringConstant(Name)) 7524 return true; 7525 7526 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name); 7527 if (ParseToken(lltok::comma, "expected ',' here") || 7528 ParseTypeIdSummary(TIS) || ParseToken(lltok::rparen, "expected ')' here")) 7529 return true; 7530 7531 // Check if this ID was forward referenced, and if so, update the 7532 // corresponding GUIDs. 7533 auto FwdRefTIDs = ForwardRefTypeIds.find(ID); 7534 if (FwdRefTIDs != ForwardRefTypeIds.end()) { 7535 for (auto TIDRef : FwdRefTIDs->second) { 7536 assert(!*TIDRef.first && 7537 "Forward referenced type id GUID expected to be 0"); 7538 *TIDRef.first = GlobalValue::getGUID(Name); 7539 } 7540 ForwardRefTypeIds.erase(FwdRefTIDs); 7541 } 7542 7543 return false; 7544 } 7545 7546 /// TypeIdSummary 7547 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')' 7548 bool LLParser::ParseTypeIdSummary(TypeIdSummary &TIS) { 7549 if (ParseToken(lltok::kw_summary, "expected 'summary' here") || 7550 ParseToken(lltok::colon, "expected ':' here") || 7551 ParseToken(lltok::lparen, "expected '(' here") || 7552 ParseTypeTestResolution(TIS.TTRes)) 7553 return true; 7554 7555 if (EatIfPresent(lltok::comma)) { 7556 // Expect optional wpdResolutions field 7557 if (ParseOptionalWpdResolutions(TIS.WPDRes)) 7558 return true; 7559 } 7560 7561 if (ParseToken(lltok::rparen, "expected ')' here")) 7562 return true; 7563 7564 return false; 7565 } 7566 7567 static ValueInfo EmptyVI = 7568 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8); 7569 7570 /// TypeIdCompatibleVtableEntry 7571 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ',' 7572 /// TypeIdCompatibleVtableInfo 7573 /// ')' 7574 bool LLParser::ParseTypeIdCompatibleVtableEntry(unsigned ID) { 7575 assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable); 7576 Lex.Lex(); 7577 7578 std::string Name; 7579 if (ParseToken(lltok::colon, "expected ':' here") || 7580 ParseToken(lltok::lparen, "expected '(' here") || 7581 ParseToken(lltok::kw_name, "expected 'name' here") || 7582 ParseToken(lltok::colon, "expected ':' here") || 7583 ParseStringConstant(Name)) 7584 return true; 7585 7586 TypeIdCompatibleVtableInfo &TI = 7587 Index->getOrInsertTypeIdCompatibleVtableSummary(Name); 7588 if (ParseToken(lltok::comma, "expected ',' here") || 7589 ParseToken(lltok::kw_summary, "expected 'summary' here") || 7590 ParseToken(lltok::colon, "expected ':' here") || 7591 ParseToken(lltok::lparen, "expected '(' here")) 7592 return true; 7593 7594 IdToIndexMapType IdToIndexMap; 7595 // Parse each call edge 7596 do { 7597 uint64_t Offset; 7598 if (ParseToken(lltok::lparen, "expected '(' here") || 7599 ParseToken(lltok::kw_offset, "expected 'offset' here") || 7600 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) || 7601 ParseToken(lltok::comma, "expected ',' here")) 7602 return true; 7603 7604 LocTy Loc = Lex.getLoc(); 7605 unsigned GVId; 7606 ValueInfo VI; 7607 if (ParseGVReference(VI, GVId)) 7608 return true; 7609 7610 // Keep track of the TypeIdCompatibleVtableInfo array index needing a 7611 // forward reference. We will save the location of the ValueInfo needing an 7612 // update, but can only do so once the std::vector is finalized. 7613 if (VI == EmptyVI) 7614 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc)); 7615 TI.push_back({Offset, VI}); 7616 7617 if (ParseToken(lltok::rparen, "expected ')' in call")) 7618 return true; 7619 } while (EatIfPresent(lltok::comma)); 7620 7621 // Now that the TI vector is finalized, it is safe to save the locations 7622 // of any forward GV references that need updating later. 7623 for (auto I : IdToIndexMap) { 7624 for (auto P : I.second) { 7625 assert(TI[P.first].VTableVI == EmptyVI && 7626 "Forward referenced ValueInfo expected to be empty"); 7627 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair( 7628 I.first, std::vector<std::pair<ValueInfo *, LocTy>>())); 7629 FwdRef.first->second.push_back( 7630 std::make_pair(&TI[P.first].VTableVI, P.second)); 7631 } 7632 } 7633 7634 if (ParseToken(lltok::rparen, "expected ')' here") || 7635 ParseToken(lltok::rparen, "expected ')' here")) 7636 return true; 7637 7638 // Check if this ID was forward referenced, and if so, update the 7639 // corresponding GUIDs. 7640 auto FwdRefTIDs = ForwardRefTypeIds.find(ID); 7641 if (FwdRefTIDs != ForwardRefTypeIds.end()) { 7642 for (auto TIDRef : FwdRefTIDs->second) { 7643 assert(!*TIDRef.first && 7644 "Forward referenced type id GUID expected to be 0"); 7645 *TIDRef.first = GlobalValue::getGUID(Name); 7646 } 7647 ForwardRefTypeIds.erase(FwdRefTIDs); 7648 } 7649 7650 return false; 7651 } 7652 7653 /// TypeTestResolution 7654 /// ::= 'typeTestRes' ':' '(' 'kind' ':' 7655 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ',' 7656 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]? 7657 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]? 7658 /// [',' 'inlinesBits' ':' UInt64]? ')' 7659 bool LLParser::ParseTypeTestResolution(TypeTestResolution &TTRes) { 7660 if (ParseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") || 7661 ParseToken(lltok::colon, "expected ':' here") || 7662 ParseToken(lltok::lparen, "expected '(' here") || 7663 ParseToken(lltok::kw_kind, "expected 'kind' here") || 7664 ParseToken(lltok::colon, "expected ':' here")) 7665 return true; 7666 7667 switch (Lex.getKind()) { 7668 case lltok::kw_unsat: 7669 TTRes.TheKind = TypeTestResolution::Unsat; 7670 break; 7671 case lltok::kw_byteArray: 7672 TTRes.TheKind = TypeTestResolution::ByteArray; 7673 break; 7674 case lltok::kw_inline: 7675 TTRes.TheKind = TypeTestResolution::Inline; 7676 break; 7677 case lltok::kw_single: 7678 TTRes.TheKind = TypeTestResolution::Single; 7679 break; 7680 case lltok::kw_allOnes: 7681 TTRes.TheKind = TypeTestResolution::AllOnes; 7682 break; 7683 default: 7684 return Error(Lex.getLoc(), "unexpected TypeTestResolution kind"); 7685 } 7686 Lex.Lex(); 7687 7688 if (ParseToken(lltok::comma, "expected ',' here") || 7689 ParseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") || 7690 ParseToken(lltok::colon, "expected ':' here") || 7691 ParseUInt32(TTRes.SizeM1BitWidth)) 7692 return true; 7693 7694 // Parse optional fields 7695 while (EatIfPresent(lltok::comma)) { 7696 switch (Lex.getKind()) { 7697 case lltok::kw_alignLog2: 7698 Lex.Lex(); 7699 if (ParseToken(lltok::colon, "expected ':'") || 7700 ParseUInt64(TTRes.AlignLog2)) 7701 return true; 7702 break; 7703 case lltok::kw_sizeM1: 7704 Lex.Lex(); 7705 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt64(TTRes.SizeM1)) 7706 return true; 7707 break; 7708 case lltok::kw_bitMask: { 7709 unsigned Val; 7710 Lex.Lex(); 7711 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt32(Val)) 7712 return true; 7713 assert(Val <= 0xff); 7714 TTRes.BitMask = (uint8_t)Val; 7715 break; 7716 } 7717 case lltok::kw_inlineBits: 7718 Lex.Lex(); 7719 if (ParseToken(lltok::colon, "expected ':'") || 7720 ParseUInt64(TTRes.InlineBits)) 7721 return true; 7722 break; 7723 default: 7724 return Error(Lex.getLoc(), "expected optional TypeTestResolution field"); 7725 } 7726 } 7727 7728 if (ParseToken(lltok::rparen, "expected ')' here")) 7729 return true; 7730 7731 return false; 7732 } 7733 7734 /// OptionalWpdResolutions 7735 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')' 7736 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')' 7737 bool LLParser::ParseOptionalWpdResolutions( 7738 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) { 7739 if (ParseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") || 7740 ParseToken(lltok::colon, "expected ':' here") || 7741 ParseToken(lltok::lparen, "expected '(' here")) 7742 return true; 7743 7744 do { 7745 uint64_t Offset; 7746 WholeProgramDevirtResolution WPDRes; 7747 if (ParseToken(lltok::lparen, "expected '(' here") || 7748 ParseToken(lltok::kw_offset, "expected 'offset' here") || 7749 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) || 7750 ParseToken(lltok::comma, "expected ',' here") || ParseWpdRes(WPDRes) || 7751 ParseToken(lltok::rparen, "expected ')' here")) 7752 return true; 7753 WPDResMap[Offset] = WPDRes; 7754 } while (EatIfPresent(lltok::comma)); 7755 7756 if (ParseToken(lltok::rparen, "expected ')' here")) 7757 return true; 7758 7759 return false; 7760 } 7761 7762 /// WpdRes 7763 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir' 7764 /// [',' OptionalResByArg]? ')' 7765 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl' 7766 /// ',' 'singleImplName' ':' STRINGCONSTANT ',' 7767 /// [',' OptionalResByArg]? ')' 7768 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel' 7769 /// [',' OptionalResByArg]? ')' 7770 bool LLParser::ParseWpdRes(WholeProgramDevirtResolution &WPDRes) { 7771 if (ParseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") || 7772 ParseToken(lltok::colon, "expected ':' here") || 7773 ParseToken(lltok::lparen, "expected '(' here") || 7774 ParseToken(lltok::kw_kind, "expected 'kind' here") || 7775 ParseToken(lltok::colon, "expected ':' here")) 7776 return true; 7777 7778 switch (Lex.getKind()) { 7779 case lltok::kw_indir: 7780 WPDRes.TheKind = WholeProgramDevirtResolution::Indir; 7781 break; 7782 case lltok::kw_singleImpl: 7783 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl; 7784 break; 7785 case lltok::kw_branchFunnel: 7786 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel; 7787 break; 7788 default: 7789 return Error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind"); 7790 } 7791 Lex.Lex(); 7792 7793 // Parse optional fields 7794 while (EatIfPresent(lltok::comma)) { 7795 switch (Lex.getKind()) { 7796 case lltok::kw_singleImplName: 7797 Lex.Lex(); 7798 if (ParseToken(lltok::colon, "expected ':' here") || 7799 ParseStringConstant(WPDRes.SingleImplName)) 7800 return true; 7801 break; 7802 case lltok::kw_resByArg: 7803 if (ParseOptionalResByArg(WPDRes.ResByArg)) 7804 return true; 7805 break; 7806 default: 7807 return Error(Lex.getLoc(), 7808 "expected optional WholeProgramDevirtResolution field"); 7809 } 7810 } 7811 7812 if (ParseToken(lltok::rparen, "expected ')' here")) 7813 return true; 7814 7815 return false; 7816 } 7817 7818 /// OptionalResByArg 7819 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')' 7820 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':' 7821 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' | 7822 /// 'virtualConstProp' ) 7823 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]? 7824 /// [',' 'bit' ':' UInt32]? ')' 7825 bool LLParser::ParseOptionalResByArg( 7826 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg> 7827 &ResByArg) { 7828 if (ParseToken(lltok::kw_resByArg, "expected 'resByArg' here") || 7829 ParseToken(lltok::colon, "expected ':' here") || 7830 ParseToken(lltok::lparen, "expected '(' here")) 7831 return true; 7832 7833 do { 7834 std::vector<uint64_t> Args; 7835 if (ParseArgs(Args) || ParseToken(lltok::comma, "expected ',' here") || 7836 ParseToken(lltok::kw_byArg, "expected 'byArg here") || 7837 ParseToken(lltok::colon, "expected ':' here") || 7838 ParseToken(lltok::lparen, "expected '(' here") || 7839 ParseToken(lltok::kw_kind, "expected 'kind' here") || 7840 ParseToken(lltok::colon, "expected ':' here")) 7841 return true; 7842 7843 WholeProgramDevirtResolution::ByArg ByArg; 7844 switch (Lex.getKind()) { 7845 case lltok::kw_indir: 7846 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir; 7847 break; 7848 case lltok::kw_uniformRetVal: 7849 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal; 7850 break; 7851 case lltok::kw_uniqueRetVal: 7852 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal; 7853 break; 7854 case lltok::kw_virtualConstProp: 7855 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp; 7856 break; 7857 default: 7858 return Error(Lex.getLoc(), 7859 "unexpected WholeProgramDevirtResolution::ByArg kind"); 7860 } 7861 Lex.Lex(); 7862 7863 // Parse optional fields 7864 while (EatIfPresent(lltok::comma)) { 7865 switch (Lex.getKind()) { 7866 case lltok::kw_info: 7867 Lex.Lex(); 7868 if (ParseToken(lltok::colon, "expected ':' here") || 7869 ParseUInt64(ByArg.Info)) 7870 return true; 7871 break; 7872 case lltok::kw_byte: 7873 Lex.Lex(); 7874 if (ParseToken(lltok::colon, "expected ':' here") || 7875 ParseUInt32(ByArg.Byte)) 7876 return true; 7877 break; 7878 case lltok::kw_bit: 7879 Lex.Lex(); 7880 if (ParseToken(lltok::colon, "expected ':' here") || 7881 ParseUInt32(ByArg.Bit)) 7882 return true; 7883 break; 7884 default: 7885 return Error(Lex.getLoc(), 7886 "expected optional whole program devirt field"); 7887 } 7888 } 7889 7890 if (ParseToken(lltok::rparen, "expected ')' here")) 7891 return true; 7892 7893 ResByArg[Args] = ByArg; 7894 } while (EatIfPresent(lltok::comma)); 7895 7896 if (ParseToken(lltok::rparen, "expected ')' here")) 7897 return true; 7898 7899 return false; 7900 } 7901 7902 /// OptionalResByArg 7903 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')' 7904 bool LLParser::ParseArgs(std::vector<uint64_t> &Args) { 7905 if (ParseToken(lltok::kw_args, "expected 'args' here") || 7906 ParseToken(lltok::colon, "expected ':' here") || 7907 ParseToken(lltok::lparen, "expected '(' here")) 7908 return true; 7909 7910 do { 7911 uint64_t Val; 7912 if (ParseUInt64(Val)) 7913 return true; 7914 Args.push_back(Val); 7915 } while (EatIfPresent(lltok::comma)); 7916 7917 if (ParseToken(lltok::rparen, "expected ')' here")) 7918 return true; 7919 7920 return false; 7921 } 7922 7923 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8; 7924 7925 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) { 7926 bool ReadOnly = Fwd->isReadOnly(); 7927 bool WriteOnly = Fwd->isWriteOnly(); 7928 assert(!(ReadOnly && WriteOnly)); 7929 *Fwd = Resolved; 7930 if (ReadOnly) 7931 Fwd->setReadOnly(); 7932 if (WriteOnly) 7933 Fwd->setWriteOnly(); 7934 } 7935 7936 /// Stores the given Name/GUID and associated summary into the Index. 7937 /// Also updates any forward references to the associated entry ID. 7938 void LLParser::AddGlobalValueToIndex( 7939 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage, 7940 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) { 7941 // First create the ValueInfo utilizing the Name or GUID. 7942 ValueInfo VI; 7943 if (GUID != 0) { 7944 assert(Name.empty()); 7945 VI = Index->getOrInsertValueInfo(GUID); 7946 } else { 7947 assert(!Name.empty()); 7948 if (M) { 7949 auto *GV = M->getNamedValue(Name); 7950 assert(GV); 7951 VI = Index->getOrInsertValueInfo(GV); 7952 } else { 7953 assert( 7954 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) && 7955 "Need a source_filename to compute GUID for local"); 7956 GUID = GlobalValue::getGUID( 7957 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName)); 7958 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name)); 7959 } 7960 } 7961 7962 // Resolve forward references from calls/refs 7963 auto FwdRefVIs = ForwardRefValueInfos.find(ID); 7964 if (FwdRefVIs != ForwardRefValueInfos.end()) { 7965 for (auto VIRef : FwdRefVIs->second) { 7966 assert(VIRef.first->getRef() == FwdVIRef && 7967 "Forward referenced ValueInfo expected to be empty"); 7968 resolveFwdRef(VIRef.first, VI); 7969 } 7970 ForwardRefValueInfos.erase(FwdRefVIs); 7971 } 7972 7973 // Resolve forward references from aliases 7974 auto FwdRefAliasees = ForwardRefAliasees.find(ID); 7975 if (FwdRefAliasees != ForwardRefAliasees.end()) { 7976 for (auto AliaseeRef : FwdRefAliasees->second) { 7977 assert(!AliaseeRef.first->hasAliasee() && 7978 "Forward referencing alias already has aliasee"); 7979 assert(Summary && "Aliasee must be a definition"); 7980 AliaseeRef.first->setAliasee(VI, Summary.get()); 7981 } 7982 ForwardRefAliasees.erase(FwdRefAliasees); 7983 } 7984 7985 // Add the summary if one was provided. 7986 if (Summary) 7987 Index->addGlobalValueSummary(VI, std::move(Summary)); 7988 7989 // Save the associated ValueInfo for use in later references by ID. 7990 if (ID == NumberedValueInfos.size()) 7991 NumberedValueInfos.push_back(VI); 7992 else { 7993 // Handle non-continuous numbers (to make test simplification easier). 7994 if (ID > NumberedValueInfos.size()) 7995 NumberedValueInfos.resize(ID + 1); 7996 NumberedValueInfos[ID] = VI; 7997 } 7998 } 7999 8000 /// ParseSummaryIndexFlags 8001 /// ::= 'flags' ':' UInt64 8002 bool LLParser::ParseSummaryIndexFlags() { 8003 assert(Lex.getKind() == lltok::kw_flags); 8004 Lex.Lex(); 8005 8006 if (ParseToken(lltok::colon, "expected ':' here")) 8007 return true; 8008 uint64_t Flags; 8009 if (ParseUInt64(Flags)) 8010 return true; 8011 Index->setFlags(Flags); 8012 return false; 8013 } 8014 8015 /// ParseGVEntry 8016 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64) 8017 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')' 8018 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')' 8019 bool LLParser::ParseGVEntry(unsigned ID) { 8020 assert(Lex.getKind() == lltok::kw_gv); 8021 Lex.Lex(); 8022 8023 if (ParseToken(lltok::colon, "expected ':' here") || 8024 ParseToken(lltok::lparen, "expected '(' here")) 8025 return true; 8026 8027 std::string Name; 8028 GlobalValue::GUID GUID = 0; 8029 switch (Lex.getKind()) { 8030 case lltok::kw_name: 8031 Lex.Lex(); 8032 if (ParseToken(lltok::colon, "expected ':' here") || 8033 ParseStringConstant(Name)) 8034 return true; 8035 // Can't create GUID/ValueInfo until we have the linkage. 8036 break; 8037 case lltok::kw_guid: 8038 Lex.Lex(); 8039 if (ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(GUID)) 8040 return true; 8041 break; 8042 default: 8043 return Error(Lex.getLoc(), "expected name or guid tag"); 8044 } 8045 8046 if (!EatIfPresent(lltok::comma)) { 8047 // No summaries. Wrap up. 8048 if (ParseToken(lltok::rparen, "expected ')' here")) 8049 return true; 8050 // This was created for a call to an external or indirect target. 8051 // A GUID with no summary came from a VALUE_GUID record, dummy GUID 8052 // created for indirect calls with VP. A Name with no GUID came from 8053 // an external definition. We pass ExternalLinkage since that is only 8054 // used when the GUID must be computed from Name, and in that case 8055 // the symbol must have external linkage. 8056 AddGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID, 8057 nullptr); 8058 return false; 8059 } 8060 8061 // Have a list of summaries 8062 if (ParseToken(lltok::kw_summaries, "expected 'summaries' here") || 8063 ParseToken(lltok::colon, "expected ':' here") || 8064 ParseToken(lltok::lparen, "expected '(' here")) 8065 return true; 8066 do { 8067 switch (Lex.getKind()) { 8068 case lltok::kw_function: 8069 if (ParseFunctionSummary(Name, GUID, ID)) 8070 return true; 8071 break; 8072 case lltok::kw_variable: 8073 if (ParseVariableSummary(Name, GUID, ID)) 8074 return true; 8075 break; 8076 case lltok::kw_alias: 8077 if (ParseAliasSummary(Name, GUID, ID)) 8078 return true; 8079 break; 8080 default: 8081 return Error(Lex.getLoc(), "expected summary type"); 8082 } 8083 } while (EatIfPresent(lltok::comma)); 8084 8085 if (ParseToken(lltok::rparen, "expected ')' here") || 8086 ParseToken(lltok::rparen, "expected ')' here")) 8087 return true; 8088 8089 return false; 8090 } 8091 8092 /// FunctionSummary 8093 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags 8094 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]? 8095 /// [',' OptionalTypeIdInfo]? [',' OptionalRefs]? ')' 8096 bool LLParser::ParseFunctionSummary(std::string Name, GlobalValue::GUID GUID, 8097 unsigned ID) { 8098 assert(Lex.getKind() == lltok::kw_function); 8099 Lex.Lex(); 8100 8101 StringRef ModulePath; 8102 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8103 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false, 8104 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8105 unsigned InstCount; 8106 std::vector<FunctionSummary::EdgeTy> Calls; 8107 FunctionSummary::TypeIdInfo TypeIdInfo; 8108 std::vector<ValueInfo> Refs; 8109 // Default is all-zeros (conservative values). 8110 FunctionSummary::FFlags FFlags = {}; 8111 if (ParseToken(lltok::colon, "expected ':' here") || 8112 ParseToken(lltok::lparen, "expected '(' here") || 8113 ParseModuleReference(ModulePath) || 8114 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) || 8115 ParseToken(lltok::comma, "expected ',' here") || 8116 ParseToken(lltok::kw_insts, "expected 'insts' here") || 8117 ParseToken(lltok::colon, "expected ':' here") || ParseUInt32(InstCount)) 8118 return true; 8119 8120 // Parse optional fields 8121 while (EatIfPresent(lltok::comma)) { 8122 switch (Lex.getKind()) { 8123 case lltok::kw_funcFlags: 8124 if (ParseOptionalFFlags(FFlags)) 8125 return true; 8126 break; 8127 case lltok::kw_calls: 8128 if (ParseOptionalCalls(Calls)) 8129 return true; 8130 break; 8131 case lltok::kw_typeIdInfo: 8132 if (ParseOptionalTypeIdInfo(TypeIdInfo)) 8133 return true; 8134 break; 8135 case lltok::kw_refs: 8136 if (ParseOptionalRefs(Refs)) 8137 return true; 8138 break; 8139 default: 8140 return Error(Lex.getLoc(), "expected optional function summary field"); 8141 } 8142 } 8143 8144 if (ParseToken(lltok::rparen, "expected ')' here")) 8145 return true; 8146 8147 auto FS = std::make_unique<FunctionSummary>( 8148 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs), 8149 std::move(Calls), std::move(TypeIdInfo.TypeTests), 8150 std::move(TypeIdInfo.TypeTestAssumeVCalls), 8151 std::move(TypeIdInfo.TypeCheckedLoadVCalls), 8152 std::move(TypeIdInfo.TypeTestAssumeConstVCalls), 8153 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls)); 8154 8155 FS->setModulePath(ModulePath); 8156 8157 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8158 ID, std::move(FS)); 8159 8160 return false; 8161 } 8162 8163 /// VariableSummary 8164 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags 8165 /// [',' OptionalRefs]? ')' 8166 bool LLParser::ParseVariableSummary(std::string Name, GlobalValue::GUID GUID, 8167 unsigned ID) { 8168 assert(Lex.getKind() == lltok::kw_variable); 8169 Lex.Lex(); 8170 8171 StringRef ModulePath; 8172 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8173 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false, 8174 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8175 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false, 8176 /* WriteOnly */ false, 8177 /* Constant */ false, 8178 GlobalObject::VCallVisibilityPublic); 8179 std::vector<ValueInfo> Refs; 8180 VTableFuncList VTableFuncs; 8181 if (ParseToken(lltok::colon, "expected ':' here") || 8182 ParseToken(lltok::lparen, "expected '(' here") || 8183 ParseModuleReference(ModulePath) || 8184 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) || 8185 ParseToken(lltok::comma, "expected ',' here") || 8186 ParseGVarFlags(GVarFlags)) 8187 return true; 8188 8189 // Parse optional fields 8190 while (EatIfPresent(lltok::comma)) { 8191 switch (Lex.getKind()) { 8192 case lltok::kw_vTableFuncs: 8193 if (ParseOptionalVTableFuncs(VTableFuncs)) 8194 return true; 8195 break; 8196 case lltok::kw_refs: 8197 if (ParseOptionalRefs(Refs)) 8198 return true; 8199 break; 8200 default: 8201 return Error(Lex.getLoc(), "expected optional variable summary field"); 8202 } 8203 } 8204 8205 if (ParseToken(lltok::rparen, "expected ')' here")) 8206 return true; 8207 8208 auto GS = 8209 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs)); 8210 8211 GS->setModulePath(ModulePath); 8212 GS->setVTableFuncs(std::move(VTableFuncs)); 8213 8214 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8215 ID, std::move(GS)); 8216 8217 return false; 8218 } 8219 8220 /// AliasSummary 8221 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ',' 8222 /// 'aliasee' ':' GVReference ')' 8223 bool LLParser::ParseAliasSummary(std::string Name, GlobalValue::GUID GUID, 8224 unsigned ID) { 8225 assert(Lex.getKind() == lltok::kw_alias); 8226 LocTy Loc = Lex.getLoc(); 8227 Lex.Lex(); 8228 8229 StringRef ModulePath; 8230 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8231 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false, 8232 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8233 if (ParseToken(lltok::colon, "expected ':' here") || 8234 ParseToken(lltok::lparen, "expected '(' here") || 8235 ParseModuleReference(ModulePath) || 8236 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) || 8237 ParseToken(lltok::comma, "expected ',' here") || 8238 ParseToken(lltok::kw_aliasee, "expected 'aliasee' here") || 8239 ParseToken(lltok::colon, "expected ':' here")) 8240 return true; 8241 8242 ValueInfo AliaseeVI; 8243 unsigned GVId; 8244 if (ParseGVReference(AliaseeVI, GVId)) 8245 return true; 8246 8247 if (ParseToken(lltok::rparen, "expected ')' here")) 8248 return true; 8249 8250 auto AS = std::make_unique<AliasSummary>(GVFlags); 8251 8252 AS->setModulePath(ModulePath); 8253 8254 // Record forward reference if the aliasee is not parsed yet. 8255 if (AliaseeVI.getRef() == FwdVIRef) { 8256 auto FwdRef = ForwardRefAliasees.insert( 8257 std::make_pair(GVId, std::vector<std::pair<AliasSummary *, LocTy>>())); 8258 FwdRef.first->second.push_back(std::make_pair(AS.get(), Loc)); 8259 } else { 8260 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath); 8261 assert(Summary && "Aliasee must be a definition"); 8262 AS->setAliasee(AliaseeVI, Summary); 8263 } 8264 8265 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8266 ID, std::move(AS)); 8267 8268 return false; 8269 } 8270 8271 /// Flag 8272 /// ::= [0|1] 8273 bool LLParser::ParseFlag(unsigned &Val) { 8274 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 8275 return TokError("expected integer"); 8276 Val = (unsigned)Lex.getAPSIntVal().getBoolValue(); 8277 Lex.Lex(); 8278 return false; 8279 } 8280 8281 /// OptionalFFlags 8282 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]? 8283 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]? 8284 /// [',' 'returnDoesNotAlias' ':' Flag]? ')' 8285 /// [',' 'noInline' ':' Flag]? ')' 8286 /// [',' 'alwaysInline' ':' Flag]? ')' 8287 8288 bool LLParser::ParseOptionalFFlags(FunctionSummary::FFlags &FFlags) { 8289 assert(Lex.getKind() == lltok::kw_funcFlags); 8290 Lex.Lex(); 8291 8292 if (ParseToken(lltok::colon, "expected ':' in funcFlags") | 8293 ParseToken(lltok::lparen, "expected '(' in funcFlags")) 8294 return true; 8295 8296 do { 8297 unsigned Val = 0; 8298 switch (Lex.getKind()) { 8299 case lltok::kw_readNone: 8300 Lex.Lex(); 8301 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val)) 8302 return true; 8303 FFlags.ReadNone = Val; 8304 break; 8305 case lltok::kw_readOnly: 8306 Lex.Lex(); 8307 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val)) 8308 return true; 8309 FFlags.ReadOnly = Val; 8310 break; 8311 case lltok::kw_noRecurse: 8312 Lex.Lex(); 8313 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val)) 8314 return true; 8315 FFlags.NoRecurse = Val; 8316 break; 8317 case lltok::kw_returnDoesNotAlias: 8318 Lex.Lex(); 8319 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val)) 8320 return true; 8321 FFlags.ReturnDoesNotAlias = Val; 8322 break; 8323 case lltok::kw_noInline: 8324 Lex.Lex(); 8325 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val)) 8326 return true; 8327 FFlags.NoInline = Val; 8328 break; 8329 case lltok::kw_alwaysInline: 8330 Lex.Lex(); 8331 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val)) 8332 return true; 8333 FFlags.AlwaysInline = Val; 8334 break; 8335 default: 8336 return Error(Lex.getLoc(), "expected function flag type"); 8337 } 8338 } while (EatIfPresent(lltok::comma)); 8339 8340 if (ParseToken(lltok::rparen, "expected ')' in funcFlags")) 8341 return true; 8342 8343 return false; 8344 } 8345 8346 /// OptionalCalls 8347 /// := 'calls' ':' '(' Call [',' Call]* ')' 8348 /// Call ::= '(' 'callee' ':' GVReference 8349 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')' 8350 bool LLParser::ParseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) { 8351 assert(Lex.getKind() == lltok::kw_calls); 8352 Lex.Lex(); 8353 8354 if (ParseToken(lltok::colon, "expected ':' in calls") | 8355 ParseToken(lltok::lparen, "expected '(' in calls")) 8356 return true; 8357 8358 IdToIndexMapType IdToIndexMap; 8359 // Parse each call edge 8360 do { 8361 ValueInfo VI; 8362 if (ParseToken(lltok::lparen, "expected '(' in call") || 8363 ParseToken(lltok::kw_callee, "expected 'callee' in call") || 8364 ParseToken(lltok::colon, "expected ':'")) 8365 return true; 8366 8367 LocTy Loc = Lex.getLoc(); 8368 unsigned GVId; 8369 if (ParseGVReference(VI, GVId)) 8370 return true; 8371 8372 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 8373 unsigned RelBF = 0; 8374 if (EatIfPresent(lltok::comma)) { 8375 // Expect either hotness or relbf 8376 if (EatIfPresent(lltok::kw_hotness)) { 8377 if (ParseToken(lltok::colon, "expected ':'") || ParseHotness(Hotness)) 8378 return true; 8379 } else { 8380 if (ParseToken(lltok::kw_relbf, "expected relbf") || 8381 ParseToken(lltok::colon, "expected ':'") || ParseUInt32(RelBF)) 8382 return true; 8383 } 8384 } 8385 // Keep track of the Call array index needing a forward reference. 8386 // We will save the location of the ValueInfo needing an update, but 8387 // can only do so once the std::vector is finalized. 8388 if (VI.getRef() == FwdVIRef) 8389 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc)); 8390 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)}); 8391 8392 if (ParseToken(lltok::rparen, "expected ')' in call")) 8393 return true; 8394 } while (EatIfPresent(lltok::comma)); 8395 8396 // Now that the Calls vector is finalized, it is safe to save the locations 8397 // of any forward GV references that need updating later. 8398 for (auto I : IdToIndexMap) { 8399 for (auto P : I.second) { 8400 assert(Calls[P.first].first.getRef() == FwdVIRef && 8401 "Forward referenced ValueInfo expected to be empty"); 8402 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair( 8403 I.first, std::vector<std::pair<ValueInfo *, LocTy>>())); 8404 FwdRef.first->second.push_back( 8405 std::make_pair(&Calls[P.first].first, P.second)); 8406 } 8407 } 8408 8409 if (ParseToken(lltok::rparen, "expected ')' in calls")) 8410 return true; 8411 8412 return false; 8413 } 8414 8415 /// Hotness 8416 /// := ('unknown'|'cold'|'none'|'hot'|'critical') 8417 bool LLParser::ParseHotness(CalleeInfo::HotnessType &Hotness) { 8418 switch (Lex.getKind()) { 8419 case lltok::kw_unknown: 8420 Hotness = CalleeInfo::HotnessType::Unknown; 8421 break; 8422 case lltok::kw_cold: 8423 Hotness = CalleeInfo::HotnessType::Cold; 8424 break; 8425 case lltok::kw_none: 8426 Hotness = CalleeInfo::HotnessType::None; 8427 break; 8428 case lltok::kw_hot: 8429 Hotness = CalleeInfo::HotnessType::Hot; 8430 break; 8431 case lltok::kw_critical: 8432 Hotness = CalleeInfo::HotnessType::Critical; 8433 break; 8434 default: 8435 return Error(Lex.getLoc(), "invalid call edge hotness"); 8436 } 8437 Lex.Lex(); 8438 return false; 8439 } 8440 8441 /// OptionalVTableFuncs 8442 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')' 8443 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')' 8444 bool LLParser::ParseOptionalVTableFuncs(VTableFuncList &VTableFuncs) { 8445 assert(Lex.getKind() == lltok::kw_vTableFuncs); 8446 Lex.Lex(); 8447 8448 if (ParseToken(lltok::colon, "expected ':' in vTableFuncs") | 8449 ParseToken(lltok::lparen, "expected '(' in vTableFuncs")) 8450 return true; 8451 8452 IdToIndexMapType IdToIndexMap; 8453 // Parse each virtual function pair 8454 do { 8455 ValueInfo VI; 8456 if (ParseToken(lltok::lparen, "expected '(' in vTableFunc") || 8457 ParseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") || 8458 ParseToken(lltok::colon, "expected ':'")) 8459 return true; 8460 8461 LocTy Loc = Lex.getLoc(); 8462 unsigned GVId; 8463 if (ParseGVReference(VI, GVId)) 8464 return true; 8465 8466 uint64_t Offset; 8467 if (ParseToken(lltok::comma, "expected comma") || 8468 ParseToken(lltok::kw_offset, "expected offset") || 8469 ParseToken(lltok::colon, "expected ':'") || ParseUInt64(Offset)) 8470 return true; 8471 8472 // Keep track of the VTableFuncs array index needing a forward reference. 8473 // We will save the location of the ValueInfo needing an update, but 8474 // can only do so once the std::vector is finalized. 8475 if (VI == EmptyVI) 8476 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc)); 8477 VTableFuncs.push_back({VI, Offset}); 8478 8479 if (ParseToken(lltok::rparen, "expected ')' in vTableFunc")) 8480 return true; 8481 } while (EatIfPresent(lltok::comma)); 8482 8483 // Now that the VTableFuncs vector is finalized, it is safe to save the 8484 // locations of any forward GV references that need updating later. 8485 for (auto I : IdToIndexMap) { 8486 for (auto P : I.second) { 8487 assert(VTableFuncs[P.first].FuncVI == EmptyVI && 8488 "Forward referenced ValueInfo expected to be empty"); 8489 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair( 8490 I.first, std::vector<std::pair<ValueInfo *, LocTy>>())); 8491 FwdRef.first->second.push_back( 8492 std::make_pair(&VTableFuncs[P.first].FuncVI, P.second)); 8493 } 8494 } 8495 8496 if (ParseToken(lltok::rparen, "expected ')' in vTableFuncs")) 8497 return true; 8498 8499 return false; 8500 } 8501 8502 /// OptionalRefs 8503 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')' 8504 bool LLParser::ParseOptionalRefs(std::vector<ValueInfo> &Refs) { 8505 assert(Lex.getKind() == lltok::kw_refs); 8506 Lex.Lex(); 8507 8508 if (ParseToken(lltok::colon, "expected ':' in refs") | 8509 ParseToken(lltok::lparen, "expected '(' in refs")) 8510 return true; 8511 8512 struct ValueContext { 8513 ValueInfo VI; 8514 unsigned GVId; 8515 LocTy Loc; 8516 }; 8517 std::vector<ValueContext> VContexts; 8518 // Parse each ref edge 8519 do { 8520 ValueContext VC; 8521 VC.Loc = Lex.getLoc(); 8522 if (ParseGVReference(VC.VI, VC.GVId)) 8523 return true; 8524 VContexts.push_back(VC); 8525 } while (EatIfPresent(lltok::comma)); 8526 8527 // Sort value contexts so that ones with writeonly 8528 // and readonly ValueInfo are at the end of VContexts vector. 8529 // See FunctionSummary::specialRefCounts() 8530 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) { 8531 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier(); 8532 }); 8533 8534 IdToIndexMapType IdToIndexMap; 8535 for (auto &VC : VContexts) { 8536 // Keep track of the Refs array index needing a forward reference. 8537 // We will save the location of the ValueInfo needing an update, but 8538 // can only do so once the std::vector is finalized. 8539 if (VC.VI.getRef() == FwdVIRef) 8540 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc)); 8541 Refs.push_back(VC.VI); 8542 } 8543 8544 // Now that the Refs vector is finalized, it is safe to save the locations 8545 // of any forward GV references that need updating later. 8546 for (auto I : IdToIndexMap) { 8547 for (auto P : I.second) { 8548 assert(Refs[P.first].getRef() == FwdVIRef && 8549 "Forward referenced ValueInfo expected to be empty"); 8550 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair( 8551 I.first, std::vector<std::pair<ValueInfo *, LocTy>>())); 8552 FwdRef.first->second.push_back(std::make_pair(&Refs[P.first], P.second)); 8553 } 8554 } 8555 8556 if (ParseToken(lltok::rparen, "expected ')' in refs")) 8557 return true; 8558 8559 return false; 8560 } 8561 8562 /// OptionalTypeIdInfo 8563 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]? 8564 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]? 8565 /// [',' TypeCheckedLoadConstVCalls]? ')' 8566 bool LLParser::ParseOptionalTypeIdInfo( 8567 FunctionSummary::TypeIdInfo &TypeIdInfo) { 8568 assert(Lex.getKind() == lltok::kw_typeIdInfo); 8569 Lex.Lex(); 8570 8571 if (ParseToken(lltok::colon, "expected ':' here") || 8572 ParseToken(lltok::lparen, "expected '(' in typeIdInfo")) 8573 return true; 8574 8575 do { 8576 switch (Lex.getKind()) { 8577 case lltok::kw_typeTests: 8578 if (ParseTypeTests(TypeIdInfo.TypeTests)) 8579 return true; 8580 break; 8581 case lltok::kw_typeTestAssumeVCalls: 8582 if (ParseVFuncIdList(lltok::kw_typeTestAssumeVCalls, 8583 TypeIdInfo.TypeTestAssumeVCalls)) 8584 return true; 8585 break; 8586 case lltok::kw_typeCheckedLoadVCalls: 8587 if (ParseVFuncIdList(lltok::kw_typeCheckedLoadVCalls, 8588 TypeIdInfo.TypeCheckedLoadVCalls)) 8589 return true; 8590 break; 8591 case lltok::kw_typeTestAssumeConstVCalls: 8592 if (ParseConstVCallList(lltok::kw_typeTestAssumeConstVCalls, 8593 TypeIdInfo.TypeTestAssumeConstVCalls)) 8594 return true; 8595 break; 8596 case lltok::kw_typeCheckedLoadConstVCalls: 8597 if (ParseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls, 8598 TypeIdInfo.TypeCheckedLoadConstVCalls)) 8599 return true; 8600 break; 8601 default: 8602 return Error(Lex.getLoc(), "invalid typeIdInfo list type"); 8603 } 8604 } while (EatIfPresent(lltok::comma)); 8605 8606 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo")) 8607 return true; 8608 8609 return false; 8610 } 8611 8612 /// TypeTests 8613 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64) 8614 /// [',' (SummaryID | UInt64)]* ')' 8615 bool LLParser::ParseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) { 8616 assert(Lex.getKind() == lltok::kw_typeTests); 8617 Lex.Lex(); 8618 8619 if (ParseToken(lltok::colon, "expected ':' here") || 8620 ParseToken(lltok::lparen, "expected '(' in typeIdInfo")) 8621 return true; 8622 8623 IdToIndexMapType IdToIndexMap; 8624 do { 8625 GlobalValue::GUID GUID = 0; 8626 if (Lex.getKind() == lltok::SummaryID) { 8627 unsigned ID = Lex.getUIntVal(); 8628 LocTy Loc = Lex.getLoc(); 8629 // Keep track of the TypeTests array index needing a forward reference. 8630 // We will save the location of the GUID needing an update, but 8631 // can only do so once the std::vector is finalized. 8632 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc)); 8633 Lex.Lex(); 8634 } else if (ParseUInt64(GUID)) 8635 return true; 8636 TypeTests.push_back(GUID); 8637 } while (EatIfPresent(lltok::comma)); 8638 8639 // Now that the TypeTests vector is finalized, it is safe to save the 8640 // locations of any forward GV references that need updating later. 8641 for (auto I : IdToIndexMap) { 8642 for (auto P : I.second) { 8643 assert(TypeTests[P.first] == 0 && 8644 "Forward referenced type id GUID expected to be 0"); 8645 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair( 8646 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>())); 8647 FwdRef.first->second.push_back( 8648 std::make_pair(&TypeTests[P.first], P.second)); 8649 } 8650 } 8651 8652 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo")) 8653 return true; 8654 8655 return false; 8656 } 8657 8658 /// VFuncIdList 8659 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')' 8660 bool LLParser::ParseVFuncIdList( 8661 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) { 8662 assert(Lex.getKind() == Kind); 8663 Lex.Lex(); 8664 8665 if (ParseToken(lltok::colon, "expected ':' here") || 8666 ParseToken(lltok::lparen, "expected '(' here")) 8667 return true; 8668 8669 IdToIndexMapType IdToIndexMap; 8670 do { 8671 FunctionSummary::VFuncId VFuncId; 8672 if (ParseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size())) 8673 return true; 8674 VFuncIdList.push_back(VFuncId); 8675 } while (EatIfPresent(lltok::comma)); 8676 8677 if (ParseToken(lltok::rparen, "expected ')' here")) 8678 return true; 8679 8680 // Now that the VFuncIdList vector is finalized, it is safe to save the 8681 // locations of any forward GV references that need updating later. 8682 for (auto I : IdToIndexMap) { 8683 for (auto P : I.second) { 8684 assert(VFuncIdList[P.first].GUID == 0 && 8685 "Forward referenced type id GUID expected to be 0"); 8686 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair( 8687 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>())); 8688 FwdRef.first->second.push_back( 8689 std::make_pair(&VFuncIdList[P.first].GUID, P.second)); 8690 } 8691 } 8692 8693 return false; 8694 } 8695 8696 /// ConstVCallList 8697 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')' 8698 bool LLParser::ParseConstVCallList( 8699 lltok::Kind Kind, 8700 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) { 8701 assert(Lex.getKind() == Kind); 8702 Lex.Lex(); 8703 8704 if (ParseToken(lltok::colon, "expected ':' here") || 8705 ParseToken(lltok::lparen, "expected '(' here")) 8706 return true; 8707 8708 IdToIndexMapType IdToIndexMap; 8709 do { 8710 FunctionSummary::ConstVCall ConstVCall; 8711 if (ParseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size())) 8712 return true; 8713 ConstVCallList.push_back(ConstVCall); 8714 } while (EatIfPresent(lltok::comma)); 8715 8716 if (ParseToken(lltok::rparen, "expected ')' here")) 8717 return true; 8718 8719 // Now that the ConstVCallList vector is finalized, it is safe to save the 8720 // locations of any forward GV references that need updating later. 8721 for (auto I : IdToIndexMap) { 8722 for (auto P : I.second) { 8723 assert(ConstVCallList[P.first].VFunc.GUID == 0 && 8724 "Forward referenced type id GUID expected to be 0"); 8725 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair( 8726 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>())); 8727 FwdRef.first->second.push_back( 8728 std::make_pair(&ConstVCallList[P.first].VFunc.GUID, P.second)); 8729 } 8730 } 8731 8732 return false; 8733 } 8734 8735 /// ConstVCall 8736 /// ::= '(' VFuncId ',' Args ')' 8737 bool LLParser::ParseConstVCall(FunctionSummary::ConstVCall &ConstVCall, 8738 IdToIndexMapType &IdToIndexMap, unsigned Index) { 8739 if (ParseToken(lltok::lparen, "expected '(' here") || 8740 ParseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index)) 8741 return true; 8742 8743 if (EatIfPresent(lltok::comma)) 8744 if (ParseArgs(ConstVCall.Args)) 8745 return true; 8746 8747 if (ParseToken(lltok::rparen, "expected ')' here")) 8748 return true; 8749 8750 return false; 8751 } 8752 8753 /// VFuncId 8754 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ',' 8755 /// 'offset' ':' UInt64 ')' 8756 bool LLParser::ParseVFuncId(FunctionSummary::VFuncId &VFuncId, 8757 IdToIndexMapType &IdToIndexMap, unsigned Index) { 8758 assert(Lex.getKind() == lltok::kw_vFuncId); 8759 Lex.Lex(); 8760 8761 if (ParseToken(lltok::colon, "expected ':' here") || 8762 ParseToken(lltok::lparen, "expected '(' here")) 8763 return true; 8764 8765 if (Lex.getKind() == lltok::SummaryID) { 8766 VFuncId.GUID = 0; 8767 unsigned ID = Lex.getUIntVal(); 8768 LocTy Loc = Lex.getLoc(); 8769 // Keep track of the array index needing a forward reference. 8770 // We will save the location of the GUID needing an update, but 8771 // can only do so once the caller's std::vector is finalized. 8772 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc)); 8773 Lex.Lex(); 8774 } else if (ParseToken(lltok::kw_guid, "expected 'guid' here") || 8775 ParseToken(lltok::colon, "expected ':' here") || 8776 ParseUInt64(VFuncId.GUID)) 8777 return true; 8778 8779 if (ParseToken(lltok::comma, "expected ',' here") || 8780 ParseToken(lltok::kw_offset, "expected 'offset' here") || 8781 ParseToken(lltok::colon, "expected ':' here") || 8782 ParseUInt64(VFuncId.Offset) || 8783 ParseToken(lltok::rparen, "expected ')' here")) 8784 return true; 8785 8786 return false; 8787 } 8788 8789 /// GVFlags 8790 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ',' 8791 /// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ',' 8792 /// 'dsoLocal' ':' Flag ',' 'canAutoHide' ':' Flag ')' 8793 bool LLParser::ParseGVFlags(GlobalValueSummary::GVFlags &GVFlags) { 8794 assert(Lex.getKind() == lltok::kw_flags); 8795 Lex.Lex(); 8796 8797 if (ParseToken(lltok::colon, "expected ':' here") || 8798 ParseToken(lltok::lparen, "expected '(' here")) 8799 return true; 8800 8801 do { 8802 unsigned Flag = 0; 8803 switch (Lex.getKind()) { 8804 case lltok::kw_linkage: 8805 Lex.Lex(); 8806 if (ParseToken(lltok::colon, "expected ':'")) 8807 return true; 8808 bool HasLinkage; 8809 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage); 8810 assert(HasLinkage && "Linkage not optional in summary entry"); 8811 Lex.Lex(); 8812 break; 8813 case lltok::kw_notEligibleToImport: 8814 Lex.Lex(); 8815 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag)) 8816 return true; 8817 GVFlags.NotEligibleToImport = Flag; 8818 break; 8819 case lltok::kw_live: 8820 Lex.Lex(); 8821 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag)) 8822 return true; 8823 GVFlags.Live = Flag; 8824 break; 8825 case lltok::kw_dsoLocal: 8826 Lex.Lex(); 8827 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag)) 8828 return true; 8829 GVFlags.DSOLocal = Flag; 8830 break; 8831 case lltok::kw_canAutoHide: 8832 Lex.Lex(); 8833 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag)) 8834 return true; 8835 GVFlags.CanAutoHide = Flag; 8836 break; 8837 default: 8838 return Error(Lex.getLoc(), "expected gv flag type"); 8839 } 8840 } while (EatIfPresent(lltok::comma)); 8841 8842 if (ParseToken(lltok::rparen, "expected ')' here")) 8843 return true; 8844 8845 return false; 8846 } 8847 8848 /// GVarFlags 8849 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag 8850 /// ',' 'writeonly' ':' Flag 8851 /// ',' 'constant' ':' Flag ')' 8852 bool LLParser::ParseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) { 8853 assert(Lex.getKind() == lltok::kw_varFlags); 8854 Lex.Lex(); 8855 8856 if (ParseToken(lltok::colon, "expected ':' here") || 8857 ParseToken(lltok::lparen, "expected '(' here")) 8858 return true; 8859 8860 auto ParseRest = [this](unsigned int &Val) { 8861 Lex.Lex(); 8862 if (ParseToken(lltok::colon, "expected ':'")) 8863 return true; 8864 return ParseFlag(Val); 8865 }; 8866 8867 do { 8868 unsigned Flag = 0; 8869 switch (Lex.getKind()) { 8870 case lltok::kw_readonly: 8871 if (ParseRest(Flag)) 8872 return true; 8873 GVarFlags.MaybeReadOnly = Flag; 8874 break; 8875 case lltok::kw_writeonly: 8876 if (ParseRest(Flag)) 8877 return true; 8878 GVarFlags.MaybeWriteOnly = Flag; 8879 break; 8880 case lltok::kw_constant: 8881 if (ParseRest(Flag)) 8882 return true; 8883 GVarFlags.Constant = Flag; 8884 break; 8885 case lltok::kw_vcall_visibility: 8886 if (ParseRest(Flag)) 8887 return true; 8888 GVarFlags.VCallVisibility = Flag; 8889 break; 8890 default: 8891 return Error(Lex.getLoc(), "expected gvar flag type"); 8892 } 8893 } while (EatIfPresent(lltok::comma)); 8894 return ParseToken(lltok::rparen, "expected ')' here"); 8895 } 8896 8897 /// ModuleReference 8898 /// ::= 'module' ':' UInt 8899 bool LLParser::ParseModuleReference(StringRef &ModulePath) { 8900 // Parse module id. 8901 if (ParseToken(lltok::kw_module, "expected 'module' here") || 8902 ParseToken(lltok::colon, "expected ':' here") || 8903 ParseToken(lltok::SummaryID, "expected module ID")) 8904 return true; 8905 8906 unsigned ModuleID = Lex.getUIntVal(); 8907 auto I = ModuleIdMap.find(ModuleID); 8908 // We should have already parsed all module IDs 8909 assert(I != ModuleIdMap.end()); 8910 ModulePath = I->second; 8911 return false; 8912 } 8913 8914 /// GVReference 8915 /// ::= SummaryID 8916 bool LLParser::ParseGVReference(ValueInfo &VI, unsigned &GVId) { 8917 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly); 8918 if (!ReadOnly) 8919 WriteOnly = EatIfPresent(lltok::kw_writeonly); 8920 if (ParseToken(lltok::SummaryID, "expected GV ID")) 8921 return true; 8922 8923 GVId = Lex.getUIntVal(); 8924 // Check if we already have a VI for this GV 8925 if (GVId < NumberedValueInfos.size()) { 8926 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef); 8927 VI = NumberedValueInfos[GVId]; 8928 } else 8929 // We will create a forward reference to the stored location. 8930 VI = ValueInfo(false, FwdVIRef); 8931 8932 if (ReadOnly) 8933 VI.setReadOnly(); 8934 if (WriteOnly) 8935 VI.setWriteOnly(); 8936 return false; 8937 } 8938