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