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