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