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