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