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