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