1 //===-- LLParser.cpp - Parser Class ---------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the parser class for .ll files. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "LLParser.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/None.h" 17 #include "llvm/ADT/Optional.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/AsmParser/SlotMapping.h" 21 #include "llvm/BinaryFormat/Dwarf.h" 22 #include "llvm/IR/Argument.h" 23 #include "llvm/IR/AutoUpgrade.h" 24 #include "llvm/IR/BasicBlock.h" 25 #include "llvm/IR/CallingConv.h" 26 #include "llvm/IR/Comdat.h" 27 #include "llvm/IR/Constants.h" 28 #include "llvm/IR/DebugInfoMetadata.h" 29 #include "llvm/IR/DerivedTypes.h" 30 #include "llvm/IR/Function.h" 31 #include "llvm/IR/GlobalIFunc.h" 32 #include "llvm/IR/GlobalObject.h" 33 #include "llvm/IR/InlineAsm.h" 34 #include "llvm/IR/Instruction.h" 35 #include "llvm/IR/Instructions.h" 36 #include "llvm/IR/Intrinsics.h" 37 #include "llvm/IR/LLVMContext.h" 38 #include "llvm/IR/Metadata.h" 39 #include "llvm/IR/Module.h" 40 #include "llvm/IR/Operator.h" 41 #include "llvm/IR/Type.h" 42 #include "llvm/IR/Value.h" 43 #include "llvm/IR/ValueSymbolTable.h" 44 #include "llvm/Support/Casting.h" 45 #include "llvm/Support/ErrorHandling.h" 46 #include "llvm/Support/MathExtras.h" 47 #include "llvm/Support/SaveAndRestore.h" 48 #include "llvm/Support/raw_ostream.h" 49 #include <algorithm> 50 #include <cassert> 51 #include <cstring> 52 #include <iterator> 53 #include <vector> 54 55 using namespace llvm; 56 57 static std::string getTypeString(Type *T) { 58 std::string Result; 59 raw_string_ostream Tmp(Result); 60 Tmp << *T; 61 return Tmp.str(); 62 } 63 64 /// Run: module ::= toplevelentity* 65 bool LLParser::Run() { 66 // Prime the lexer. 67 Lex.Lex(); 68 69 if (Context.shouldDiscardValueNames()) 70 return Error( 71 Lex.getLoc(), 72 "Can't read textual IR with a Context that discards named Values"); 73 74 return ParseTopLevelEntities() || 75 ValidateEndOfModule(); 76 } 77 78 bool LLParser::parseStandaloneConstantValue(Constant *&C, 79 const SlotMapping *Slots) { 80 restoreParsingState(Slots); 81 Lex.Lex(); 82 83 Type *Ty = nullptr; 84 if (ParseType(Ty) || parseConstantValue(Ty, C)) 85 return true; 86 if (Lex.getKind() != lltok::Eof) 87 return Error(Lex.getLoc(), "expected end of string"); 88 return false; 89 } 90 91 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read, 92 const SlotMapping *Slots) { 93 restoreParsingState(Slots); 94 Lex.Lex(); 95 96 Read = 0; 97 SMLoc Start = Lex.getLoc(); 98 Ty = nullptr; 99 if (ParseType(Ty)) 100 return true; 101 SMLoc End = Lex.getLoc(); 102 Read = End.getPointer() - Start.getPointer(); 103 104 return false; 105 } 106 107 void LLParser::restoreParsingState(const SlotMapping *Slots) { 108 if (!Slots) 109 return; 110 NumberedVals = Slots->GlobalValues; 111 NumberedMetadata = Slots->MetadataNodes; 112 for (const auto &I : Slots->NamedTypes) 113 NamedTypes.insert( 114 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy()))); 115 for (const auto &I : Slots->Types) 116 NumberedTypes.insert( 117 std::make_pair(I.first, std::make_pair(I.second, LocTy()))); 118 } 119 120 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the 121 /// module. 122 bool LLParser::ValidateEndOfModule() { 123 // Handle any function attribute group forward references. 124 for (const auto &RAG : ForwardRefAttrGroups) { 125 Value *V = RAG.first; 126 const std::vector<unsigned> &Attrs = RAG.second; 127 AttrBuilder B; 128 129 for (const auto &Attr : Attrs) 130 B.merge(NumberedAttrBuilders[Attr]); 131 132 if (Function *Fn = dyn_cast<Function>(V)) { 133 AttributeList AS = Fn->getAttributes(); 134 AttrBuilder FnAttrs(AS.getFnAttributes()); 135 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex); 136 137 FnAttrs.merge(B); 138 139 // If the alignment was parsed as an attribute, move to the alignment 140 // field. 141 if (FnAttrs.hasAlignmentAttr()) { 142 Fn->setAlignment(FnAttrs.getAlignment()); 143 FnAttrs.removeAttribute(Attribute::Alignment); 144 } 145 146 AS = AS.addAttributes(Context, AttributeList::FunctionIndex, 147 AttributeSet::get(Context, FnAttrs)); 148 Fn->setAttributes(AS); 149 } else if (CallInst *CI = dyn_cast<CallInst>(V)) { 150 AttributeList AS = CI->getAttributes(); 151 AttrBuilder FnAttrs(AS.getFnAttributes()); 152 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex); 153 FnAttrs.merge(B); 154 AS = AS.addAttributes(Context, AttributeList::FunctionIndex, 155 AttributeSet::get(Context, FnAttrs)); 156 CI->setAttributes(AS); 157 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) { 158 AttributeList AS = II->getAttributes(); 159 AttrBuilder FnAttrs(AS.getFnAttributes()); 160 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex); 161 FnAttrs.merge(B); 162 AS = AS.addAttributes(Context, AttributeList::FunctionIndex, 163 AttributeSet::get(Context, FnAttrs)); 164 II->setAttributes(AS); 165 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) { 166 AttrBuilder Attrs(GV->getAttributes()); 167 Attrs.merge(B); 168 GV->setAttributes(AttributeSet::get(Context,Attrs)); 169 } else { 170 llvm_unreachable("invalid object with forward attribute group reference"); 171 } 172 } 173 174 // If there are entries in ForwardRefBlockAddresses at this point, the 175 // function was never defined. 176 if (!ForwardRefBlockAddresses.empty()) 177 return Error(ForwardRefBlockAddresses.begin()->first.Loc, 178 "expected function name in blockaddress"); 179 180 for (const auto &NT : NumberedTypes) 181 if (NT.second.second.isValid()) 182 return Error(NT.second.second, 183 "use of undefined type '%" + Twine(NT.first) + "'"); 184 185 for (StringMap<std::pair<Type*, LocTy> >::iterator I = 186 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) 187 if (I->second.second.isValid()) 188 return Error(I->second.second, 189 "use of undefined type named '" + I->getKey() + "'"); 190 191 if (!ForwardRefComdats.empty()) 192 return Error(ForwardRefComdats.begin()->second, 193 "use of undefined comdat '$" + 194 ForwardRefComdats.begin()->first + "'"); 195 196 if (!ForwardRefVals.empty()) 197 return Error(ForwardRefVals.begin()->second.second, 198 "use of undefined value '@" + ForwardRefVals.begin()->first + 199 "'"); 200 201 if (!ForwardRefValIDs.empty()) 202 return Error(ForwardRefValIDs.begin()->second.second, 203 "use of undefined value '@" + 204 Twine(ForwardRefValIDs.begin()->first) + "'"); 205 206 if (!ForwardRefMDNodes.empty()) 207 return Error(ForwardRefMDNodes.begin()->second.second, 208 "use of undefined metadata '!" + 209 Twine(ForwardRefMDNodes.begin()->first) + "'"); 210 211 // Resolve metadata cycles. 212 for (auto &N : NumberedMetadata) { 213 if (N.second && !N.second->isResolved()) 214 N.second->resolveCycles(); 215 } 216 217 for (auto *Inst : InstsWithTBAATag) { 218 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa); 219 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag"); 220 auto *UpgradedMD = UpgradeTBAANode(*MD); 221 if (MD != UpgradedMD) 222 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD); 223 } 224 225 // Look for intrinsic functions and CallInst that need to be upgraded 226 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) 227 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove 228 229 // Some types could be renamed during loading if several modules are 230 // loaded in the same LLVMContext (LTO scenario). In this case we should 231 // remangle intrinsics names as well. 232 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) { 233 Function *F = &*FI++; 234 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) { 235 F->replaceAllUsesWith(Remangled.getValue()); 236 F->eraseFromParent(); 237 } 238 } 239 240 UpgradeDebugInfo(*M); 241 242 UpgradeModuleFlags(*M); 243 UpgradeSectionAttributes(*M); 244 245 if (!Slots) 246 return false; 247 // Initialize the slot mapping. 248 // Because by this point we've parsed and validated everything, we can "steal" 249 // the mapping from LLParser as it doesn't need it anymore. 250 Slots->GlobalValues = std::move(NumberedVals); 251 Slots->MetadataNodes = std::move(NumberedMetadata); 252 for (const auto &I : NamedTypes) 253 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first)); 254 for (const auto &I : NumberedTypes) 255 Slots->Types.insert(std::make_pair(I.first, I.second.first)); 256 257 return false; 258 } 259 260 //===----------------------------------------------------------------------===// 261 // Top-Level Entities 262 //===----------------------------------------------------------------------===// 263 264 bool LLParser::ParseTopLevelEntities() { 265 while (true) { 266 switch (Lex.getKind()) { 267 default: return TokError("expected top-level entity"); 268 case lltok::Eof: return false; 269 case lltok::kw_declare: if (ParseDeclare()) return true; break; 270 case lltok::kw_define: if (ParseDefine()) return true; break; 271 case lltok::kw_module: if (ParseModuleAsm()) return true; break; 272 case lltok::kw_target: if (ParseTargetDefinition()) return true; break; 273 case lltok::kw_source_filename: 274 if (ParseSourceFileName()) 275 return true; 276 break; 277 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break; 278 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break; 279 case lltok::LocalVar: if (ParseNamedType()) return true; break; 280 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break; 281 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break; 282 case lltok::ComdatVar: if (parseComdat()) return true; break; 283 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break; 284 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break; 285 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break; 286 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break; 287 case lltok::kw_uselistorder_bb: 288 if (ParseUseListOrderBB()) 289 return true; 290 break; 291 } 292 } 293 } 294 295 /// toplevelentity 296 /// ::= 'module' 'asm' STRINGCONSTANT 297 bool LLParser::ParseModuleAsm() { 298 assert(Lex.getKind() == lltok::kw_module); 299 Lex.Lex(); 300 301 std::string AsmStr; 302 if (ParseToken(lltok::kw_asm, "expected 'module asm'") || 303 ParseStringConstant(AsmStr)) return true; 304 305 M->appendModuleInlineAsm(AsmStr); 306 return false; 307 } 308 309 /// toplevelentity 310 /// ::= 'target' 'triple' '=' STRINGCONSTANT 311 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT 312 bool LLParser::ParseTargetDefinition() { 313 assert(Lex.getKind() == lltok::kw_target); 314 std::string Str; 315 switch (Lex.Lex()) { 316 default: return TokError("unknown target property"); 317 case lltok::kw_triple: 318 Lex.Lex(); 319 if (ParseToken(lltok::equal, "expected '=' after target triple") || 320 ParseStringConstant(Str)) 321 return true; 322 M->setTargetTriple(Str); 323 return false; 324 case lltok::kw_datalayout: 325 Lex.Lex(); 326 if (ParseToken(lltok::equal, "expected '=' after target datalayout") || 327 ParseStringConstant(Str)) 328 return true; 329 M->setDataLayout(Str); 330 return false; 331 } 332 } 333 334 /// toplevelentity 335 /// ::= 'source_filename' '=' STRINGCONSTANT 336 bool LLParser::ParseSourceFileName() { 337 assert(Lex.getKind() == lltok::kw_source_filename); 338 std::string Str; 339 Lex.Lex(); 340 if (ParseToken(lltok::equal, "expected '=' after source_filename") || 341 ParseStringConstant(Str)) 342 return true; 343 M->setSourceFileName(Str); 344 return false; 345 } 346 347 /// toplevelentity 348 /// ::= 'deplibs' '=' '[' ']' 349 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']' 350 /// FIXME: Remove in 4.0. Currently parse, but ignore. 351 bool LLParser::ParseDepLibs() { 352 assert(Lex.getKind() == lltok::kw_deplibs); 353 Lex.Lex(); 354 if (ParseToken(lltok::equal, "expected '=' after deplibs") || 355 ParseToken(lltok::lsquare, "expected '=' after deplibs")) 356 return true; 357 358 if (EatIfPresent(lltok::rsquare)) 359 return false; 360 361 do { 362 std::string Str; 363 if (ParseStringConstant(Str)) return true; 364 } while (EatIfPresent(lltok::comma)); 365 366 return ParseToken(lltok::rsquare, "expected ']' at end of list"); 367 } 368 369 /// ParseUnnamedType: 370 /// ::= LocalVarID '=' 'type' type 371 bool LLParser::ParseUnnamedType() { 372 LocTy TypeLoc = Lex.getLoc(); 373 unsigned TypeID = Lex.getUIntVal(); 374 Lex.Lex(); // eat LocalVarID; 375 376 if (ParseToken(lltok::equal, "expected '=' after name") || 377 ParseToken(lltok::kw_type, "expected 'type' after '='")) 378 return true; 379 380 Type *Result = nullptr; 381 if (ParseStructDefinition(TypeLoc, "", 382 NumberedTypes[TypeID], Result)) return true; 383 384 if (!isa<StructType>(Result)) { 385 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID]; 386 if (Entry.first) 387 return Error(TypeLoc, "non-struct types may not be recursive"); 388 Entry.first = Result; 389 Entry.second = SMLoc(); 390 } 391 392 return false; 393 } 394 395 /// toplevelentity 396 /// ::= LocalVar '=' 'type' type 397 bool LLParser::ParseNamedType() { 398 std::string Name = Lex.getStrVal(); 399 LocTy NameLoc = Lex.getLoc(); 400 Lex.Lex(); // eat LocalVar. 401 402 if (ParseToken(lltok::equal, "expected '=' after name") || 403 ParseToken(lltok::kw_type, "expected 'type' after name")) 404 return true; 405 406 Type *Result = nullptr; 407 if (ParseStructDefinition(NameLoc, Name, 408 NamedTypes[Name], Result)) return true; 409 410 if (!isa<StructType>(Result)) { 411 std::pair<Type*, LocTy> &Entry = NamedTypes[Name]; 412 if (Entry.first) 413 return Error(NameLoc, "non-struct types may not be recursive"); 414 Entry.first = Result; 415 Entry.second = SMLoc(); 416 } 417 418 return false; 419 } 420 421 /// toplevelentity 422 /// ::= 'declare' FunctionHeader 423 bool LLParser::ParseDeclare() { 424 assert(Lex.getKind() == lltok::kw_declare); 425 Lex.Lex(); 426 427 std::vector<std::pair<unsigned, MDNode *>> MDs; 428 while (Lex.getKind() == lltok::MetadataVar) { 429 unsigned MDK; 430 MDNode *N; 431 if (ParseMetadataAttachment(MDK, N)) 432 return true; 433 MDs.push_back({MDK, N}); 434 } 435 436 Function *F; 437 if (ParseFunctionHeader(F, false)) 438 return true; 439 for (auto &MD : MDs) 440 F->addMetadata(MD.first, *MD.second); 441 return false; 442 } 443 444 /// toplevelentity 445 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ... 446 bool LLParser::ParseDefine() { 447 assert(Lex.getKind() == lltok::kw_define); 448 Lex.Lex(); 449 450 Function *F; 451 return ParseFunctionHeader(F, true) || 452 ParseOptionalFunctionMetadata(*F) || 453 ParseFunctionBody(*F); 454 } 455 456 /// ParseGlobalType 457 /// ::= 'constant' 458 /// ::= 'global' 459 bool LLParser::ParseGlobalType(bool &IsConstant) { 460 if (Lex.getKind() == lltok::kw_constant) 461 IsConstant = true; 462 else if (Lex.getKind() == lltok::kw_global) 463 IsConstant = false; 464 else { 465 IsConstant = false; 466 return TokError("expected 'global' or 'constant'"); 467 } 468 Lex.Lex(); 469 return false; 470 } 471 472 bool LLParser::ParseOptionalUnnamedAddr( 473 GlobalVariable::UnnamedAddr &UnnamedAddr) { 474 if (EatIfPresent(lltok::kw_unnamed_addr)) 475 UnnamedAddr = GlobalValue::UnnamedAddr::Global; 476 else if (EatIfPresent(lltok::kw_local_unnamed_addr)) 477 UnnamedAddr = GlobalValue::UnnamedAddr::Local; 478 else 479 UnnamedAddr = GlobalValue::UnnamedAddr::None; 480 return false; 481 } 482 483 /// ParseUnnamedGlobal: 484 /// OptionalVisibility (ALIAS | IFUNC) ... 485 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass 486 /// ... -> global variable 487 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ... 488 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass 489 /// ... -> global variable 490 bool LLParser::ParseUnnamedGlobal() { 491 unsigned VarID = NumberedVals.size(); 492 std::string Name; 493 LocTy NameLoc = Lex.getLoc(); 494 495 // Handle the GlobalID form. 496 if (Lex.getKind() == lltok::GlobalID) { 497 if (Lex.getUIntVal() != VarID) 498 return Error(Lex.getLoc(), "variable expected to be numbered '%" + 499 Twine(VarID) + "'"); 500 Lex.Lex(); // eat GlobalID; 501 502 if (ParseToken(lltok::equal, "expected '=' after name")) 503 return true; 504 } 505 506 bool HasLinkage; 507 unsigned Linkage, Visibility, DLLStorageClass; 508 GlobalVariable::ThreadLocalMode TLM; 509 GlobalVariable::UnnamedAddr UnnamedAddr; 510 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) || 511 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr)) 512 return true; 513 514 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc) 515 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility, 516 DLLStorageClass, TLM, UnnamedAddr); 517 518 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility, 519 DLLStorageClass, TLM, UnnamedAddr); 520 } 521 522 /// ParseNamedGlobal: 523 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ... 524 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass 525 /// ... -> global variable 526 bool LLParser::ParseNamedGlobal() { 527 assert(Lex.getKind() == lltok::GlobalVar); 528 LocTy NameLoc = Lex.getLoc(); 529 std::string Name = Lex.getStrVal(); 530 Lex.Lex(); 531 532 bool HasLinkage; 533 unsigned Linkage, Visibility, DLLStorageClass; 534 GlobalVariable::ThreadLocalMode TLM; 535 GlobalVariable::UnnamedAddr UnnamedAddr; 536 if (ParseToken(lltok::equal, "expected '=' in global variable") || 537 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) || 538 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr)) 539 return true; 540 541 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc) 542 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility, 543 DLLStorageClass, TLM, UnnamedAddr); 544 545 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility, 546 DLLStorageClass, TLM, UnnamedAddr); 547 } 548 549 bool LLParser::parseComdat() { 550 assert(Lex.getKind() == lltok::ComdatVar); 551 std::string Name = Lex.getStrVal(); 552 LocTy NameLoc = Lex.getLoc(); 553 Lex.Lex(); 554 555 if (ParseToken(lltok::equal, "expected '=' here")) 556 return true; 557 558 if (ParseToken(lltok::kw_comdat, "expected comdat keyword")) 559 return TokError("expected comdat type"); 560 561 Comdat::SelectionKind SK; 562 switch (Lex.getKind()) { 563 default: 564 return TokError("unknown selection kind"); 565 case lltok::kw_any: 566 SK = Comdat::Any; 567 break; 568 case lltok::kw_exactmatch: 569 SK = Comdat::ExactMatch; 570 break; 571 case lltok::kw_largest: 572 SK = Comdat::Largest; 573 break; 574 case lltok::kw_noduplicates: 575 SK = Comdat::NoDuplicates; 576 break; 577 case lltok::kw_samesize: 578 SK = Comdat::SameSize; 579 break; 580 } 581 Lex.Lex(); 582 583 // See if the comdat was forward referenced, if so, use the comdat. 584 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable(); 585 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name); 586 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name)) 587 return Error(NameLoc, "redefinition of comdat '$" + Name + "'"); 588 589 Comdat *C; 590 if (I != ComdatSymTab.end()) 591 C = &I->second; 592 else 593 C = M->getOrInsertComdat(Name); 594 C->setSelectionKind(SK); 595 596 return false; 597 } 598 599 // MDString: 600 // ::= '!' STRINGCONSTANT 601 bool LLParser::ParseMDString(MDString *&Result) { 602 std::string Str; 603 if (ParseStringConstant(Str)) return true; 604 Result = MDString::get(Context, Str); 605 return false; 606 } 607 608 // MDNode: 609 // ::= '!' MDNodeNumber 610 bool LLParser::ParseMDNodeID(MDNode *&Result) { 611 // !{ ..., !42, ... } 612 LocTy IDLoc = Lex.getLoc(); 613 unsigned MID = 0; 614 if (ParseUInt32(MID)) 615 return true; 616 617 // If not a forward reference, just return it now. 618 if (NumberedMetadata.count(MID)) { 619 Result = NumberedMetadata[MID]; 620 return false; 621 } 622 623 // Otherwise, create MDNode forward reference. 624 auto &FwdRef = ForwardRefMDNodes[MID]; 625 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc); 626 627 Result = FwdRef.first.get(); 628 NumberedMetadata[MID].reset(Result); 629 return false; 630 } 631 632 /// ParseNamedMetadata: 633 /// !foo = !{ !1, !2 } 634 bool LLParser::ParseNamedMetadata() { 635 assert(Lex.getKind() == lltok::MetadataVar); 636 std::string Name = Lex.getStrVal(); 637 Lex.Lex(); 638 639 if (ParseToken(lltok::equal, "expected '=' here") || 640 ParseToken(lltok::exclaim, "Expected '!' here") || 641 ParseToken(lltok::lbrace, "Expected '{' here")) 642 return true; 643 644 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name); 645 if (Lex.getKind() != lltok::rbrace) 646 do { 647 if (ParseToken(lltok::exclaim, "Expected '!' here")) 648 return true; 649 650 MDNode *N = nullptr; 651 if (ParseMDNodeID(N)) return true; 652 NMD->addOperand(N); 653 } while (EatIfPresent(lltok::comma)); 654 655 return ParseToken(lltok::rbrace, "expected end of metadata node"); 656 } 657 658 /// ParseStandaloneMetadata: 659 /// !42 = !{...} 660 bool LLParser::ParseStandaloneMetadata() { 661 assert(Lex.getKind() == lltok::exclaim); 662 Lex.Lex(); 663 unsigned MetadataID = 0; 664 665 MDNode *Init; 666 if (ParseUInt32(MetadataID) || 667 ParseToken(lltok::equal, "expected '=' here")) 668 return true; 669 670 // Detect common error, from old metadata syntax. 671 if (Lex.getKind() == lltok::Type) 672 return TokError("unexpected type in metadata definition"); 673 674 bool IsDistinct = EatIfPresent(lltok::kw_distinct); 675 if (Lex.getKind() == lltok::MetadataVar) { 676 if (ParseSpecializedMDNode(Init, IsDistinct)) 677 return true; 678 } else if (ParseToken(lltok::exclaim, "Expected '!' here") || 679 ParseMDTuple(Init, IsDistinct)) 680 return true; 681 682 // See if this was forward referenced, if so, handle it. 683 auto FI = ForwardRefMDNodes.find(MetadataID); 684 if (FI != ForwardRefMDNodes.end()) { 685 FI->second.first->replaceAllUsesWith(Init); 686 ForwardRefMDNodes.erase(FI); 687 688 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work"); 689 } else { 690 if (NumberedMetadata.count(MetadataID)) 691 return TokError("Metadata id is already used"); 692 NumberedMetadata[MetadataID].reset(Init); 693 } 694 695 return false; 696 } 697 698 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) { 699 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) || 700 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility; 701 } 702 703 /// parseIndirectSymbol: 704 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility 705 /// OptionalDLLStorageClass OptionalThreadLocal 706 /// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol 707 /// 708 /// IndirectSymbol 709 /// ::= TypeAndValue 710 /// 711 /// Everything through OptionalUnnamedAddr has already been parsed. 712 /// 713 bool LLParser::parseIndirectSymbol( 714 const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility, 715 unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM, 716 GlobalVariable::UnnamedAddr UnnamedAddr) { 717 bool IsAlias; 718 if (Lex.getKind() == lltok::kw_alias) 719 IsAlias = true; 720 else if (Lex.getKind() == lltok::kw_ifunc) 721 IsAlias = false; 722 else 723 llvm_unreachable("Not an alias or ifunc!"); 724 Lex.Lex(); 725 726 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L; 727 728 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage)) 729 return Error(NameLoc, "invalid linkage type for alias"); 730 731 if (!isValidVisibilityForLinkage(Visibility, L)) 732 return Error(NameLoc, 733 "symbol with local linkage must have default visibility"); 734 735 Type *Ty; 736 LocTy ExplicitTypeLoc = Lex.getLoc(); 737 if (ParseType(Ty) || 738 ParseToken(lltok::comma, "expected comma after alias or ifunc's type")) 739 return true; 740 741 Constant *Aliasee; 742 LocTy AliaseeLoc = Lex.getLoc(); 743 if (Lex.getKind() != lltok::kw_bitcast && 744 Lex.getKind() != lltok::kw_getelementptr && 745 Lex.getKind() != lltok::kw_addrspacecast && 746 Lex.getKind() != lltok::kw_inttoptr) { 747 if (ParseGlobalTypeAndValue(Aliasee)) 748 return true; 749 } else { 750 // The bitcast dest type is not present, it is implied by the dest type. 751 ValID ID; 752 if (ParseValID(ID)) 753 return true; 754 if (ID.Kind != ValID::t_Constant) 755 return Error(AliaseeLoc, "invalid aliasee"); 756 Aliasee = ID.ConstantVal; 757 } 758 759 Type *AliaseeType = Aliasee->getType(); 760 auto *PTy = dyn_cast<PointerType>(AliaseeType); 761 if (!PTy) 762 return Error(AliaseeLoc, "An alias or ifunc must have pointer type"); 763 unsigned AddrSpace = PTy->getAddressSpace(); 764 765 if (IsAlias && Ty != PTy->getElementType()) 766 return Error( 767 ExplicitTypeLoc, 768 "explicit pointee type doesn't match operand's pointee type"); 769 770 if (!IsAlias && !PTy->getElementType()->isFunctionTy()) 771 return Error( 772 ExplicitTypeLoc, 773 "explicit pointee type should be a function type"); 774 775 GlobalValue *GVal = nullptr; 776 777 // See if the alias was forward referenced, if so, prepare to replace the 778 // forward reference. 779 if (!Name.empty()) { 780 GVal = M->getNamedValue(Name); 781 if (GVal) { 782 if (!ForwardRefVals.erase(Name)) 783 return Error(NameLoc, "redefinition of global '@" + Name + "'"); 784 } 785 } else { 786 auto I = ForwardRefValIDs.find(NumberedVals.size()); 787 if (I != ForwardRefValIDs.end()) { 788 GVal = I->second.first; 789 ForwardRefValIDs.erase(I); 790 } 791 } 792 793 // Okay, create the alias but do not insert it into the module yet. 794 std::unique_ptr<GlobalIndirectSymbol> GA; 795 if (IsAlias) 796 GA.reset(GlobalAlias::create(Ty, AddrSpace, 797 (GlobalValue::LinkageTypes)Linkage, Name, 798 Aliasee, /*Parent*/ nullptr)); 799 else 800 GA.reset(GlobalIFunc::create(Ty, AddrSpace, 801 (GlobalValue::LinkageTypes)Linkage, Name, 802 Aliasee, /*Parent*/ nullptr)); 803 GA->setThreadLocalMode(TLM); 804 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility); 805 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 806 GA->setUnnamedAddr(UnnamedAddr); 807 808 if (Name.empty()) 809 NumberedVals.push_back(GA.get()); 810 811 if (GVal) { 812 // Verify that types agree. 813 if (GVal->getType() != GA->getType()) 814 return Error( 815 ExplicitTypeLoc, 816 "forward reference and definition of alias have different types"); 817 818 // If they agree, just RAUW the old value with the alias and remove the 819 // forward ref info. 820 GVal->replaceAllUsesWith(GA.get()); 821 GVal->eraseFromParent(); 822 } 823 824 // Insert into the module, we know its name won't collide now. 825 if (IsAlias) 826 M->getAliasList().push_back(cast<GlobalAlias>(GA.get())); 827 else 828 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get())); 829 assert(GA->getName() == Name && "Should not be a name conflict!"); 830 831 // The module owns this now 832 GA.release(); 833 834 return false; 835 } 836 837 /// ParseGlobal 838 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass 839 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace 840 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs 841 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass 842 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace 843 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs 844 /// 845 /// Everything up to and including OptionalUnnamedAddr has been parsed 846 /// already. 847 /// 848 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc, 849 unsigned Linkage, bool HasLinkage, 850 unsigned Visibility, unsigned DLLStorageClass, 851 GlobalVariable::ThreadLocalMode TLM, 852 GlobalVariable::UnnamedAddr UnnamedAddr) { 853 if (!isValidVisibilityForLinkage(Visibility, Linkage)) 854 return Error(NameLoc, 855 "symbol with local linkage must have default visibility"); 856 857 unsigned AddrSpace; 858 bool IsConstant, IsExternallyInitialized; 859 LocTy IsExternallyInitializedLoc; 860 LocTy TyLoc; 861 862 Type *Ty = nullptr; 863 if (ParseOptionalAddrSpace(AddrSpace) || 864 ParseOptionalToken(lltok::kw_externally_initialized, 865 IsExternallyInitialized, 866 &IsExternallyInitializedLoc) || 867 ParseGlobalType(IsConstant) || 868 ParseType(Ty, TyLoc)) 869 return true; 870 871 // If the linkage is specified and is external, then no initializer is 872 // present. 873 Constant *Init = nullptr; 874 if (!HasLinkage || 875 !GlobalValue::isValidDeclarationLinkage( 876 (GlobalValue::LinkageTypes)Linkage)) { 877 if (ParseGlobalValue(Ty, Init)) 878 return true; 879 } 880 881 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty)) 882 return Error(TyLoc, "invalid type for global variable"); 883 884 GlobalValue *GVal = nullptr; 885 886 // See if the global was forward referenced, if so, use the global. 887 if (!Name.empty()) { 888 GVal = M->getNamedValue(Name); 889 if (GVal) { 890 if (!ForwardRefVals.erase(Name)) 891 return Error(NameLoc, "redefinition of global '@" + Name + "'"); 892 } 893 } else { 894 auto I = ForwardRefValIDs.find(NumberedVals.size()); 895 if (I != ForwardRefValIDs.end()) { 896 GVal = I->second.first; 897 ForwardRefValIDs.erase(I); 898 } 899 } 900 901 GlobalVariable *GV; 902 if (!GVal) { 903 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr, 904 Name, nullptr, GlobalVariable::NotThreadLocal, 905 AddrSpace); 906 } else { 907 if (GVal->getValueType() != Ty) 908 return Error(TyLoc, 909 "forward reference and definition of global have different types"); 910 911 GV = cast<GlobalVariable>(GVal); 912 913 // Move the forward-reference to the correct spot in the module. 914 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV); 915 } 916 917 if (Name.empty()) 918 NumberedVals.push_back(GV); 919 920 // Set the parsed properties on the global. 921 if (Init) 922 GV->setInitializer(Init); 923 GV->setConstant(IsConstant); 924 GV->setLinkage((GlobalValue::LinkageTypes)Linkage); 925 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility); 926 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 927 GV->setExternallyInitialized(IsExternallyInitialized); 928 GV->setThreadLocalMode(TLM); 929 GV->setUnnamedAddr(UnnamedAddr); 930 931 // Parse attributes on the global. 932 while (Lex.getKind() == lltok::comma) { 933 Lex.Lex(); 934 935 if (Lex.getKind() == lltok::kw_section) { 936 Lex.Lex(); 937 GV->setSection(Lex.getStrVal()); 938 if (ParseToken(lltok::StringConstant, "expected global section string")) 939 return true; 940 } else if (Lex.getKind() == lltok::kw_align) { 941 unsigned Alignment; 942 if (ParseOptionalAlignment(Alignment)) return true; 943 GV->setAlignment(Alignment); 944 } else if (Lex.getKind() == lltok::MetadataVar) { 945 if (ParseGlobalObjectMetadataAttachment(*GV)) 946 return true; 947 } else { 948 Comdat *C; 949 if (parseOptionalComdat(Name, C)) 950 return true; 951 if (C) 952 GV->setComdat(C); 953 else 954 return TokError("unknown global variable property!"); 955 } 956 } 957 958 AttrBuilder Attrs; 959 LocTy BuiltinLoc; 960 std::vector<unsigned> FwdRefAttrGrps; 961 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc)) 962 return true; 963 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) { 964 GV->setAttributes(AttributeSet::get(Context, Attrs)); 965 ForwardRefAttrGroups[GV] = FwdRefAttrGrps; 966 } 967 968 return false; 969 } 970 971 /// ParseUnnamedAttrGrp 972 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}' 973 bool LLParser::ParseUnnamedAttrGrp() { 974 assert(Lex.getKind() == lltok::kw_attributes); 975 LocTy AttrGrpLoc = Lex.getLoc(); 976 Lex.Lex(); 977 978 if (Lex.getKind() != lltok::AttrGrpID) 979 return TokError("expected attribute group id"); 980 981 unsigned VarID = Lex.getUIntVal(); 982 std::vector<unsigned> unused; 983 LocTy BuiltinLoc; 984 Lex.Lex(); 985 986 if (ParseToken(lltok::equal, "expected '=' here") || 987 ParseToken(lltok::lbrace, "expected '{' here") || 988 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true, 989 BuiltinLoc) || 990 ParseToken(lltok::rbrace, "expected end of attribute group")) 991 return true; 992 993 if (!NumberedAttrBuilders[VarID].hasAttributes()) 994 return Error(AttrGrpLoc, "attribute group has no attributes"); 995 996 return false; 997 } 998 999 /// ParseFnAttributeValuePairs 1000 /// ::= <attr> | <attr> '=' <value> 1001 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B, 1002 std::vector<unsigned> &FwdRefAttrGrps, 1003 bool inAttrGrp, LocTy &BuiltinLoc) { 1004 bool HaveError = false; 1005 1006 B.clear(); 1007 1008 while (true) { 1009 lltok::Kind Token = Lex.getKind(); 1010 if (Token == lltok::kw_builtin) 1011 BuiltinLoc = Lex.getLoc(); 1012 switch (Token) { 1013 default: 1014 if (!inAttrGrp) return HaveError; 1015 return Error(Lex.getLoc(), "unterminated attribute group"); 1016 case lltok::rbrace: 1017 // Finished. 1018 return false; 1019 1020 case lltok::AttrGrpID: { 1021 // Allow a function to reference an attribute group: 1022 // 1023 // define void @foo() #1 { ... } 1024 if (inAttrGrp) 1025 HaveError |= 1026 Error(Lex.getLoc(), 1027 "cannot have an attribute group reference in an attribute group"); 1028 1029 unsigned AttrGrpNum = Lex.getUIntVal(); 1030 if (inAttrGrp) break; 1031 1032 // Save the reference to the attribute group. We'll fill it in later. 1033 FwdRefAttrGrps.push_back(AttrGrpNum); 1034 break; 1035 } 1036 // Target-dependent attributes: 1037 case lltok::StringConstant: { 1038 if (ParseStringAttribute(B)) 1039 return true; 1040 continue; 1041 } 1042 1043 // Target-independent attributes: 1044 case lltok::kw_align: { 1045 // As a hack, we allow function alignment to be initially parsed as an 1046 // attribute on a function declaration/definition or added to an attribute 1047 // group and later moved to the alignment field. 1048 unsigned Alignment; 1049 if (inAttrGrp) { 1050 Lex.Lex(); 1051 if (ParseToken(lltok::equal, "expected '=' here") || 1052 ParseUInt32(Alignment)) 1053 return true; 1054 } else { 1055 if (ParseOptionalAlignment(Alignment)) 1056 return true; 1057 } 1058 B.addAlignmentAttr(Alignment); 1059 continue; 1060 } 1061 case lltok::kw_alignstack: { 1062 unsigned Alignment; 1063 if (inAttrGrp) { 1064 Lex.Lex(); 1065 if (ParseToken(lltok::equal, "expected '=' here") || 1066 ParseUInt32(Alignment)) 1067 return true; 1068 } else { 1069 if (ParseOptionalStackAlignment(Alignment)) 1070 return true; 1071 } 1072 B.addStackAlignmentAttr(Alignment); 1073 continue; 1074 } 1075 case lltok::kw_allocsize: { 1076 unsigned ElemSizeArg; 1077 Optional<unsigned> NumElemsArg; 1078 // inAttrGrp doesn't matter; we only support allocsize(a[, b]) 1079 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg)) 1080 return true; 1081 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg); 1082 continue; 1083 } 1084 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break; 1085 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break; 1086 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break; 1087 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break; 1088 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break; 1089 case lltok::kw_inaccessiblememonly: 1090 B.addAttribute(Attribute::InaccessibleMemOnly); break; 1091 case lltok::kw_inaccessiblemem_or_argmemonly: 1092 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break; 1093 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break; 1094 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break; 1095 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break; 1096 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break; 1097 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break; 1098 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break; 1099 case lltok::kw_noimplicitfloat: 1100 B.addAttribute(Attribute::NoImplicitFloat); break; 1101 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break; 1102 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break; 1103 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break; 1104 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break; 1105 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break; 1106 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break; 1107 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break; 1108 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break; 1109 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break; 1110 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break; 1111 case lltok::kw_returns_twice: 1112 B.addAttribute(Attribute::ReturnsTwice); break; 1113 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break; 1114 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break; 1115 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break; 1116 case lltok::kw_sspstrong: 1117 B.addAttribute(Attribute::StackProtectStrong); break; 1118 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break; 1119 case lltok::kw_sanitize_address: 1120 B.addAttribute(Attribute::SanitizeAddress); break; 1121 case lltok::kw_sanitize_thread: 1122 B.addAttribute(Attribute::SanitizeThread); break; 1123 case lltok::kw_sanitize_memory: 1124 B.addAttribute(Attribute::SanitizeMemory); break; 1125 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break; 1126 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break; 1127 1128 // Error handling. 1129 case lltok::kw_inreg: 1130 case lltok::kw_signext: 1131 case lltok::kw_zeroext: 1132 HaveError |= 1133 Error(Lex.getLoc(), 1134 "invalid use of attribute on a function"); 1135 break; 1136 case lltok::kw_byval: 1137 case lltok::kw_dereferenceable: 1138 case lltok::kw_dereferenceable_or_null: 1139 case lltok::kw_inalloca: 1140 case lltok::kw_nest: 1141 case lltok::kw_noalias: 1142 case lltok::kw_nocapture: 1143 case lltok::kw_nonnull: 1144 case lltok::kw_returned: 1145 case lltok::kw_sret: 1146 case lltok::kw_swifterror: 1147 case lltok::kw_swiftself: 1148 HaveError |= 1149 Error(Lex.getLoc(), 1150 "invalid use of parameter-only attribute on a function"); 1151 break; 1152 } 1153 1154 Lex.Lex(); 1155 } 1156 } 1157 1158 //===----------------------------------------------------------------------===// 1159 // GlobalValue Reference/Resolution Routines. 1160 //===----------------------------------------------------------------------===// 1161 1162 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy, 1163 const std::string &Name) { 1164 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType())) 1165 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M); 1166 else 1167 return new GlobalVariable(*M, PTy->getElementType(), false, 1168 GlobalValue::ExternalWeakLinkage, nullptr, Name, 1169 nullptr, GlobalVariable::NotThreadLocal, 1170 PTy->getAddressSpace()); 1171 } 1172 1173 /// GetGlobalVal - Get a value with the specified name or ID, creating a 1174 /// forward reference record if needed. This can return null if the value 1175 /// exists but does not have the right type. 1176 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty, 1177 LocTy Loc) { 1178 PointerType *PTy = dyn_cast<PointerType>(Ty); 1179 if (!PTy) { 1180 Error(Loc, "global variable reference must have pointer type"); 1181 return nullptr; 1182 } 1183 1184 // Look this name up in the normal function symbol table. 1185 GlobalValue *Val = 1186 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name)); 1187 1188 // If this is a forward reference for the value, see if we already created a 1189 // forward ref record. 1190 if (!Val) { 1191 auto I = ForwardRefVals.find(Name); 1192 if (I != ForwardRefVals.end()) 1193 Val = I->second.first; 1194 } 1195 1196 // If we have the value in the symbol table or fwd-ref table, return it. 1197 if (Val) { 1198 if (Val->getType() == Ty) return Val; 1199 Error(Loc, "'@" + Name + "' defined with type '" + 1200 getTypeString(Val->getType()) + "'"); 1201 return nullptr; 1202 } 1203 1204 // Otherwise, create a new forward reference for this value and remember it. 1205 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name); 1206 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 1207 return FwdVal; 1208 } 1209 1210 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) { 1211 PointerType *PTy = dyn_cast<PointerType>(Ty); 1212 if (!PTy) { 1213 Error(Loc, "global variable reference must have pointer type"); 1214 return nullptr; 1215 } 1216 1217 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr; 1218 1219 // If this is a forward reference for the value, see if we already created a 1220 // forward ref record. 1221 if (!Val) { 1222 auto I = ForwardRefValIDs.find(ID); 1223 if (I != ForwardRefValIDs.end()) 1224 Val = I->second.first; 1225 } 1226 1227 // If we have the value in the symbol table or fwd-ref table, return it. 1228 if (Val) { 1229 if (Val->getType() == Ty) return Val; 1230 Error(Loc, "'@" + Twine(ID) + "' defined with type '" + 1231 getTypeString(Val->getType()) + "'"); 1232 return nullptr; 1233 } 1234 1235 // Otherwise, create a new forward reference for this value and remember it. 1236 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, ""); 1237 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 1238 return FwdVal; 1239 } 1240 1241 //===----------------------------------------------------------------------===// 1242 // Comdat Reference/Resolution Routines. 1243 //===----------------------------------------------------------------------===// 1244 1245 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) { 1246 // Look this name up in the comdat symbol table. 1247 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable(); 1248 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name); 1249 if (I != ComdatSymTab.end()) 1250 return &I->second; 1251 1252 // Otherwise, create a new forward reference for this value and remember it. 1253 Comdat *C = M->getOrInsertComdat(Name); 1254 ForwardRefComdats[Name] = Loc; 1255 return C; 1256 } 1257 1258 //===----------------------------------------------------------------------===// 1259 // Helper Routines. 1260 //===----------------------------------------------------------------------===// 1261 1262 /// ParseToken - If the current token has the specified kind, eat it and return 1263 /// success. Otherwise, emit the specified error and return failure. 1264 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) { 1265 if (Lex.getKind() != T) 1266 return TokError(ErrMsg); 1267 Lex.Lex(); 1268 return false; 1269 } 1270 1271 /// ParseStringConstant 1272 /// ::= StringConstant 1273 bool LLParser::ParseStringConstant(std::string &Result) { 1274 if (Lex.getKind() != lltok::StringConstant) 1275 return TokError("expected string constant"); 1276 Result = Lex.getStrVal(); 1277 Lex.Lex(); 1278 return false; 1279 } 1280 1281 /// ParseUInt32 1282 /// ::= uint32 1283 bool LLParser::ParseUInt32(uint32_t &Val) { 1284 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 1285 return TokError("expected integer"); 1286 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1); 1287 if (Val64 != unsigned(Val64)) 1288 return TokError("expected 32-bit integer (too large)"); 1289 Val = Val64; 1290 Lex.Lex(); 1291 return false; 1292 } 1293 1294 /// ParseUInt64 1295 /// ::= uint64 1296 bool LLParser::ParseUInt64(uint64_t &Val) { 1297 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 1298 return TokError("expected integer"); 1299 Val = Lex.getAPSIntVal().getLimitedValue(); 1300 Lex.Lex(); 1301 return false; 1302 } 1303 1304 /// ParseTLSModel 1305 /// := 'localdynamic' 1306 /// := 'initialexec' 1307 /// := 'localexec' 1308 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) { 1309 switch (Lex.getKind()) { 1310 default: 1311 return TokError("expected localdynamic, initialexec or localexec"); 1312 case lltok::kw_localdynamic: 1313 TLM = GlobalVariable::LocalDynamicTLSModel; 1314 break; 1315 case lltok::kw_initialexec: 1316 TLM = GlobalVariable::InitialExecTLSModel; 1317 break; 1318 case lltok::kw_localexec: 1319 TLM = GlobalVariable::LocalExecTLSModel; 1320 break; 1321 } 1322 1323 Lex.Lex(); 1324 return false; 1325 } 1326 1327 /// ParseOptionalThreadLocal 1328 /// := /*empty*/ 1329 /// := 'thread_local' 1330 /// := 'thread_local' '(' tlsmodel ')' 1331 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) { 1332 TLM = GlobalVariable::NotThreadLocal; 1333 if (!EatIfPresent(lltok::kw_thread_local)) 1334 return false; 1335 1336 TLM = GlobalVariable::GeneralDynamicTLSModel; 1337 if (Lex.getKind() == lltok::lparen) { 1338 Lex.Lex(); 1339 return ParseTLSModel(TLM) || 1340 ParseToken(lltok::rparen, "expected ')' after thread local model"); 1341 } 1342 return false; 1343 } 1344 1345 /// ParseOptionalAddrSpace 1346 /// := /*empty*/ 1347 /// := 'addrspace' '(' uint32 ')' 1348 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) { 1349 AddrSpace = 0; 1350 if (!EatIfPresent(lltok::kw_addrspace)) 1351 return false; 1352 return ParseToken(lltok::lparen, "expected '(' in address space") || 1353 ParseUInt32(AddrSpace) || 1354 ParseToken(lltok::rparen, "expected ')' in address space"); 1355 } 1356 1357 /// ParseStringAttribute 1358 /// := StringConstant 1359 /// := StringConstant '=' StringConstant 1360 bool LLParser::ParseStringAttribute(AttrBuilder &B) { 1361 std::string Attr = Lex.getStrVal(); 1362 Lex.Lex(); 1363 std::string Val; 1364 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val)) 1365 return true; 1366 B.addAttribute(Attr, Val); 1367 return false; 1368 } 1369 1370 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes. 1371 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) { 1372 bool HaveError = false; 1373 1374 B.clear(); 1375 1376 while (true) { 1377 lltok::Kind Token = Lex.getKind(); 1378 switch (Token) { 1379 default: // End of attributes. 1380 return HaveError; 1381 case lltok::StringConstant: { 1382 if (ParseStringAttribute(B)) 1383 return true; 1384 continue; 1385 } 1386 case lltok::kw_align: { 1387 unsigned Alignment; 1388 if (ParseOptionalAlignment(Alignment)) 1389 return true; 1390 B.addAlignmentAttr(Alignment); 1391 continue; 1392 } 1393 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break; 1394 case lltok::kw_dereferenceable: { 1395 uint64_t Bytes; 1396 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes)) 1397 return true; 1398 B.addDereferenceableAttr(Bytes); 1399 continue; 1400 } 1401 case lltok::kw_dereferenceable_or_null: { 1402 uint64_t Bytes; 1403 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes)) 1404 return true; 1405 B.addDereferenceableOrNullAttr(Bytes); 1406 continue; 1407 } 1408 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break; 1409 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break; 1410 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break; 1411 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break; 1412 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break; 1413 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break; 1414 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break; 1415 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break; 1416 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break; 1417 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break; 1418 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break; 1419 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break; 1420 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break; 1421 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break; 1422 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break; 1423 1424 case lltok::kw_alignstack: 1425 case lltok::kw_alwaysinline: 1426 case lltok::kw_argmemonly: 1427 case lltok::kw_builtin: 1428 case lltok::kw_inlinehint: 1429 case lltok::kw_jumptable: 1430 case lltok::kw_minsize: 1431 case lltok::kw_naked: 1432 case lltok::kw_nobuiltin: 1433 case lltok::kw_noduplicate: 1434 case lltok::kw_noimplicitfloat: 1435 case lltok::kw_noinline: 1436 case lltok::kw_nonlazybind: 1437 case lltok::kw_noredzone: 1438 case lltok::kw_noreturn: 1439 case lltok::kw_nounwind: 1440 case lltok::kw_optnone: 1441 case lltok::kw_optsize: 1442 case lltok::kw_returns_twice: 1443 case lltok::kw_sanitize_address: 1444 case lltok::kw_sanitize_memory: 1445 case lltok::kw_sanitize_thread: 1446 case lltok::kw_ssp: 1447 case lltok::kw_sspreq: 1448 case lltok::kw_sspstrong: 1449 case lltok::kw_safestack: 1450 case lltok::kw_uwtable: 1451 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute"); 1452 break; 1453 } 1454 1455 Lex.Lex(); 1456 } 1457 } 1458 1459 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes. 1460 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) { 1461 bool HaveError = false; 1462 1463 B.clear(); 1464 1465 while (true) { 1466 lltok::Kind Token = Lex.getKind(); 1467 switch (Token) { 1468 default: // End of attributes. 1469 return HaveError; 1470 case lltok::StringConstant: { 1471 if (ParseStringAttribute(B)) 1472 return true; 1473 continue; 1474 } 1475 case lltok::kw_dereferenceable: { 1476 uint64_t Bytes; 1477 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes)) 1478 return true; 1479 B.addDereferenceableAttr(Bytes); 1480 continue; 1481 } 1482 case lltok::kw_dereferenceable_or_null: { 1483 uint64_t Bytes; 1484 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes)) 1485 return true; 1486 B.addDereferenceableOrNullAttr(Bytes); 1487 continue; 1488 } 1489 case lltok::kw_align: { 1490 unsigned Alignment; 1491 if (ParseOptionalAlignment(Alignment)) 1492 return true; 1493 B.addAlignmentAttr(Alignment); 1494 continue; 1495 } 1496 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break; 1497 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break; 1498 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break; 1499 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break; 1500 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break; 1501 1502 // Error handling. 1503 case lltok::kw_byval: 1504 case lltok::kw_inalloca: 1505 case lltok::kw_nest: 1506 case lltok::kw_nocapture: 1507 case lltok::kw_returned: 1508 case lltok::kw_sret: 1509 case lltok::kw_swifterror: 1510 case lltok::kw_swiftself: 1511 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute"); 1512 break; 1513 1514 case lltok::kw_alignstack: 1515 case lltok::kw_alwaysinline: 1516 case lltok::kw_argmemonly: 1517 case lltok::kw_builtin: 1518 case lltok::kw_cold: 1519 case lltok::kw_inlinehint: 1520 case lltok::kw_jumptable: 1521 case lltok::kw_minsize: 1522 case lltok::kw_naked: 1523 case lltok::kw_nobuiltin: 1524 case lltok::kw_noduplicate: 1525 case lltok::kw_noimplicitfloat: 1526 case lltok::kw_noinline: 1527 case lltok::kw_nonlazybind: 1528 case lltok::kw_noredzone: 1529 case lltok::kw_noreturn: 1530 case lltok::kw_nounwind: 1531 case lltok::kw_optnone: 1532 case lltok::kw_optsize: 1533 case lltok::kw_returns_twice: 1534 case lltok::kw_sanitize_address: 1535 case lltok::kw_sanitize_memory: 1536 case lltok::kw_sanitize_thread: 1537 case lltok::kw_ssp: 1538 case lltok::kw_sspreq: 1539 case lltok::kw_sspstrong: 1540 case lltok::kw_safestack: 1541 case lltok::kw_uwtable: 1542 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute"); 1543 break; 1544 1545 case lltok::kw_readnone: 1546 case lltok::kw_readonly: 1547 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type"); 1548 } 1549 1550 Lex.Lex(); 1551 } 1552 } 1553 1554 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) { 1555 HasLinkage = true; 1556 switch (Kind) { 1557 default: 1558 HasLinkage = false; 1559 return GlobalValue::ExternalLinkage; 1560 case lltok::kw_private: 1561 return GlobalValue::PrivateLinkage; 1562 case lltok::kw_internal: 1563 return GlobalValue::InternalLinkage; 1564 case lltok::kw_weak: 1565 return GlobalValue::WeakAnyLinkage; 1566 case lltok::kw_weak_odr: 1567 return GlobalValue::WeakODRLinkage; 1568 case lltok::kw_linkonce: 1569 return GlobalValue::LinkOnceAnyLinkage; 1570 case lltok::kw_linkonce_odr: 1571 return GlobalValue::LinkOnceODRLinkage; 1572 case lltok::kw_available_externally: 1573 return GlobalValue::AvailableExternallyLinkage; 1574 case lltok::kw_appending: 1575 return GlobalValue::AppendingLinkage; 1576 case lltok::kw_common: 1577 return GlobalValue::CommonLinkage; 1578 case lltok::kw_extern_weak: 1579 return GlobalValue::ExternalWeakLinkage; 1580 case lltok::kw_external: 1581 return GlobalValue::ExternalLinkage; 1582 } 1583 } 1584 1585 /// ParseOptionalLinkage 1586 /// ::= /*empty*/ 1587 /// ::= 'private' 1588 /// ::= 'internal' 1589 /// ::= 'weak' 1590 /// ::= 'weak_odr' 1591 /// ::= 'linkonce' 1592 /// ::= 'linkonce_odr' 1593 /// ::= 'available_externally' 1594 /// ::= 'appending' 1595 /// ::= 'common' 1596 /// ::= 'extern_weak' 1597 /// ::= 'external' 1598 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage, 1599 unsigned &Visibility, 1600 unsigned &DLLStorageClass) { 1601 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage); 1602 if (HasLinkage) 1603 Lex.Lex(); 1604 ParseOptionalVisibility(Visibility); 1605 ParseOptionalDLLStorageClass(DLLStorageClass); 1606 return false; 1607 } 1608 1609 /// ParseOptionalVisibility 1610 /// ::= /*empty*/ 1611 /// ::= 'default' 1612 /// ::= 'hidden' 1613 /// ::= 'protected' 1614 /// 1615 void LLParser::ParseOptionalVisibility(unsigned &Res) { 1616 switch (Lex.getKind()) { 1617 default: 1618 Res = GlobalValue::DefaultVisibility; 1619 return; 1620 case lltok::kw_default: 1621 Res = GlobalValue::DefaultVisibility; 1622 break; 1623 case lltok::kw_hidden: 1624 Res = GlobalValue::HiddenVisibility; 1625 break; 1626 case lltok::kw_protected: 1627 Res = GlobalValue::ProtectedVisibility; 1628 break; 1629 } 1630 Lex.Lex(); 1631 } 1632 1633 /// ParseOptionalDLLStorageClass 1634 /// ::= /*empty*/ 1635 /// ::= 'dllimport' 1636 /// ::= 'dllexport' 1637 /// 1638 void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) { 1639 switch (Lex.getKind()) { 1640 default: 1641 Res = GlobalValue::DefaultStorageClass; 1642 return; 1643 case lltok::kw_dllimport: 1644 Res = GlobalValue::DLLImportStorageClass; 1645 break; 1646 case lltok::kw_dllexport: 1647 Res = GlobalValue::DLLExportStorageClass; 1648 break; 1649 } 1650 Lex.Lex(); 1651 } 1652 1653 /// ParseOptionalCallingConv 1654 /// ::= /*empty*/ 1655 /// ::= 'ccc' 1656 /// ::= 'fastcc' 1657 /// ::= 'intel_ocl_bicc' 1658 /// ::= 'coldcc' 1659 /// ::= 'x86_stdcallcc' 1660 /// ::= 'x86_fastcallcc' 1661 /// ::= 'x86_thiscallcc' 1662 /// ::= 'x86_vectorcallcc' 1663 /// ::= 'arm_apcscc' 1664 /// ::= 'arm_aapcscc' 1665 /// ::= 'arm_aapcs_vfpcc' 1666 /// ::= 'msp430_intrcc' 1667 /// ::= 'avr_intrcc' 1668 /// ::= 'avr_signalcc' 1669 /// ::= 'ptx_kernel' 1670 /// ::= 'ptx_device' 1671 /// ::= 'spir_func' 1672 /// ::= 'spir_kernel' 1673 /// ::= 'x86_64_sysvcc' 1674 /// ::= 'win64cc' 1675 /// ::= 'webkit_jscc' 1676 /// ::= 'anyregcc' 1677 /// ::= 'preserve_mostcc' 1678 /// ::= 'preserve_allcc' 1679 /// ::= 'ghccc' 1680 /// ::= 'swiftcc' 1681 /// ::= 'x86_intrcc' 1682 /// ::= 'hhvmcc' 1683 /// ::= 'hhvm_ccc' 1684 /// ::= 'cxx_fast_tlscc' 1685 /// ::= 'amdgpu_vs' 1686 /// ::= 'amdgpu_hs' 1687 /// ::= 'amdgpu_gs' 1688 /// ::= 'amdgpu_ps' 1689 /// ::= 'amdgpu_cs' 1690 /// ::= 'amdgpu_kernel' 1691 /// ::= 'cc' UINT 1692 /// 1693 bool LLParser::ParseOptionalCallingConv(unsigned &CC) { 1694 switch (Lex.getKind()) { 1695 default: CC = CallingConv::C; return false; 1696 case lltok::kw_ccc: CC = CallingConv::C; break; 1697 case lltok::kw_fastcc: CC = CallingConv::Fast; break; 1698 case lltok::kw_coldcc: CC = CallingConv::Cold; break; 1699 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break; 1700 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break; 1701 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break; 1702 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break; 1703 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break; 1704 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break; 1705 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break; 1706 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break; 1707 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break; 1708 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break; 1709 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break; 1710 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break; 1711 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break; 1712 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break; 1713 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break; 1714 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break; 1715 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break; 1716 case lltok::kw_win64cc: CC = CallingConv::Win64; break; 1717 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break; 1718 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break; 1719 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break; 1720 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break; 1721 case lltok::kw_ghccc: CC = CallingConv::GHC; break; 1722 case lltok::kw_swiftcc: CC = CallingConv::Swift; break; 1723 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break; 1724 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break; 1725 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break; 1726 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break; 1727 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break; 1728 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break; 1729 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break; 1730 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break; 1731 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break; 1732 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break; 1733 case lltok::kw_cc: { 1734 Lex.Lex(); 1735 return ParseUInt32(CC); 1736 } 1737 } 1738 1739 Lex.Lex(); 1740 return false; 1741 } 1742 1743 /// ParseMetadataAttachment 1744 /// ::= !dbg !42 1745 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) { 1746 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment"); 1747 1748 std::string Name = Lex.getStrVal(); 1749 Kind = M->getMDKindID(Name); 1750 Lex.Lex(); 1751 1752 return ParseMDNode(MD); 1753 } 1754 1755 /// ParseInstructionMetadata 1756 /// ::= !dbg !42 (',' !dbg !57)* 1757 bool LLParser::ParseInstructionMetadata(Instruction &Inst) { 1758 do { 1759 if (Lex.getKind() != lltok::MetadataVar) 1760 return TokError("expected metadata after comma"); 1761 1762 unsigned MDK; 1763 MDNode *N; 1764 if (ParseMetadataAttachment(MDK, N)) 1765 return true; 1766 1767 Inst.setMetadata(MDK, N); 1768 if (MDK == LLVMContext::MD_tbaa) 1769 InstsWithTBAATag.push_back(&Inst); 1770 1771 // If this is the end of the list, we're done. 1772 } while (EatIfPresent(lltok::comma)); 1773 return false; 1774 } 1775 1776 /// ParseGlobalObjectMetadataAttachment 1777 /// ::= !dbg !57 1778 bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) { 1779 unsigned MDK; 1780 MDNode *N; 1781 if (ParseMetadataAttachment(MDK, N)) 1782 return true; 1783 1784 GO.addMetadata(MDK, *N); 1785 return false; 1786 } 1787 1788 /// ParseOptionalFunctionMetadata 1789 /// ::= (!dbg !57)* 1790 bool LLParser::ParseOptionalFunctionMetadata(Function &F) { 1791 while (Lex.getKind() == lltok::MetadataVar) 1792 if (ParseGlobalObjectMetadataAttachment(F)) 1793 return true; 1794 return false; 1795 } 1796 1797 /// ParseOptionalAlignment 1798 /// ::= /* empty */ 1799 /// ::= 'align' 4 1800 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) { 1801 Alignment = 0; 1802 if (!EatIfPresent(lltok::kw_align)) 1803 return false; 1804 LocTy AlignLoc = Lex.getLoc(); 1805 if (ParseUInt32(Alignment)) return true; 1806 if (!isPowerOf2_32(Alignment)) 1807 return Error(AlignLoc, "alignment is not a power of two"); 1808 if (Alignment > Value::MaximumAlignment) 1809 return Error(AlignLoc, "huge alignments are not supported yet"); 1810 return false; 1811 } 1812 1813 /// ParseOptionalDerefAttrBytes 1814 /// ::= /* empty */ 1815 /// ::= AttrKind '(' 4 ')' 1816 /// 1817 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'. 1818 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind, 1819 uint64_t &Bytes) { 1820 assert((AttrKind == lltok::kw_dereferenceable || 1821 AttrKind == lltok::kw_dereferenceable_or_null) && 1822 "contract!"); 1823 1824 Bytes = 0; 1825 if (!EatIfPresent(AttrKind)) 1826 return false; 1827 LocTy ParenLoc = Lex.getLoc(); 1828 if (!EatIfPresent(lltok::lparen)) 1829 return Error(ParenLoc, "expected '('"); 1830 LocTy DerefLoc = Lex.getLoc(); 1831 if (ParseUInt64(Bytes)) return true; 1832 ParenLoc = Lex.getLoc(); 1833 if (!EatIfPresent(lltok::rparen)) 1834 return Error(ParenLoc, "expected ')'"); 1835 if (!Bytes) 1836 return Error(DerefLoc, "dereferenceable bytes must be non-zero"); 1837 return false; 1838 } 1839 1840 /// ParseOptionalCommaAlign 1841 /// ::= 1842 /// ::= ',' align 4 1843 /// 1844 /// This returns with AteExtraComma set to true if it ate an excess comma at the 1845 /// end. 1846 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment, 1847 bool &AteExtraComma) { 1848 AteExtraComma = false; 1849 while (EatIfPresent(lltok::comma)) { 1850 // Metadata at the end is an early exit. 1851 if (Lex.getKind() == lltok::MetadataVar) { 1852 AteExtraComma = true; 1853 return false; 1854 } 1855 1856 if (Lex.getKind() != lltok::kw_align) 1857 return Error(Lex.getLoc(), "expected metadata or 'align'"); 1858 1859 if (ParseOptionalAlignment(Alignment)) return true; 1860 } 1861 1862 return false; 1863 } 1864 1865 /// ParseOptionalCommaAddrSpace 1866 /// ::= 1867 /// ::= ',' addrspace(1) 1868 /// 1869 /// This returns with AteExtraComma set to true if it ate an excess comma at the 1870 /// end. 1871 bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace, 1872 LocTy &Loc, 1873 bool &AteExtraComma) { 1874 AteExtraComma = false; 1875 while (EatIfPresent(lltok::comma)) { 1876 // Metadata at the end is an early exit. 1877 if (Lex.getKind() == lltok::MetadataVar) { 1878 AteExtraComma = true; 1879 return false; 1880 } 1881 1882 Loc = Lex.getLoc(); 1883 if (Lex.getKind() != lltok::kw_addrspace) 1884 return Error(Lex.getLoc(), "expected metadata or 'addrspace'"); 1885 1886 if (ParseOptionalAddrSpace(AddrSpace)) 1887 return true; 1888 } 1889 1890 return false; 1891 } 1892 1893 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg, 1894 Optional<unsigned> &HowManyArg) { 1895 Lex.Lex(); 1896 1897 auto StartParen = Lex.getLoc(); 1898 if (!EatIfPresent(lltok::lparen)) 1899 return Error(StartParen, "expected '('"); 1900 1901 if (ParseUInt32(BaseSizeArg)) 1902 return true; 1903 1904 if (EatIfPresent(lltok::comma)) { 1905 auto HowManyAt = Lex.getLoc(); 1906 unsigned HowMany; 1907 if (ParseUInt32(HowMany)) 1908 return true; 1909 if (HowMany == BaseSizeArg) 1910 return Error(HowManyAt, 1911 "'allocsize' indices can't refer to the same parameter"); 1912 HowManyArg = HowMany; 1913 } else 1914 HowManyArg = None; 1915 1916 auto EndParen = Lex.getLoc(); 1917 if (!EatIfPresent(lltok::rparen)) 1918 return Error(EndParen, "expected ')'"); 1919 return false; 1920 } 1921 1922 /// ParseScopeAndOrdering 1923 /// if isAtomic: ::= SyncScope? AtomicOrdering 1924 /// else: ::= 1925 /// 1926 /// This sets Scope and Ordering to the parsed values. 1927 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID, 1928 AtomicOrdering &Ordering) { 1929 if (!isAtomic) 1930 return false; 1931 1932 return ParseScope(SSID) || ParseOrdering(Ordering); 1933 } 1934 1935 /// ParseScope 1936 /// ::= syncscope("singlethread" | "<target scope>")? 1937 /// 1938 /// This sets synchronization scope ID to the ID of the parsed value. 1939 bool LLParser::ParseScope(SyncScope::ID &SSID) { 1940 SSID = SyncScope::System; 1941 if (EatIfPresent(lltok::kw_syncscope)) { 1942 auto StartParenAt = Lex.getLoc(); 1943 if (!EatIfPresent(lltok::lparen)) 1944 return Error(StartParenAt, "Expected '(' in syncscope"); 1945 1946 std::string SSN; 1947 auto SSNAt = Lex.getLoc(); 1948 if (ParseStringConstant(SSN)) 1949 return Error(SSNAt, "Expected synchronization scope name"); 1950 1951 auto EndParenAt = Lex.getLoc(); 1952 if (!EatIfPresent(lltok::rparen)) 1953 return Error(EndParenAt, "Expected ')' in syncscope"); 1954 1955 SSID = Context.getOrInsertSyncScopeID(SSN); 1956 } 1957 1958 return false; 1959 } 1960 1961 /// ParseOrdering 1962 /// ::= AtomicOrdering 1963 /// 1964 /// This sets Ordering to the parsed value. 1965 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) { 1966 switch (Lex.getKind()) { 1967 default: return TokError("Expected ordering on atomic instruction"); 1968 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break; 1969 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break; 1970 // Not specified yet: 1971 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break; 1972 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break; 1973 case lltok::kw_release: Ordering = AtomicOrdering::Release; break; 1974 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break; 1975 case lltok::kw_seq_cst: 1976 Ordering = AtomicOrdering::SequentiallyConsistent; 1977 break; 1978 } 1979 Lex.Lex(); 1980 return false; 1981 } 1982 1983 /// ParseOptionalStackAlignment 1984 /// ::= /* empty */ 1985 /// ::= 'alignstack' '(' 4 ')' 1986 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) { 1987 Alignment = 0; 1988 if (!EatIfPresent(lltok::kw_alignstack)) 1989 return false; 1990 LocTy ParenLoc = Lex.getLoc(); 1991 if (!EatIfPresent(lltok::lparen)) 1992 return Error(ParenLoc, "expected '('"); 1993 LocTy AlignLoc = Lex.getLoc(); 1994 if (ParseUInt32(Alignment)) return true; 1995 ParenLoc = Lex.getLoc(); 1996 if (!EatIfPresent(lltok::rparen)) 1997 return Error(ParenLoc, "expected ')'"); 1998 if (!isPowerOf2_32(Alignment)) 1999 return Error(AlignLoc, "stack alignment is not a power of two"); 2000 return false; 2001 } 2002 2003 /// ParseIndexList - This parses the index list for an insert/extractvalue 2004 /// instruction. This sets AteExtraComma in the case where we eat an extra 2005 /// comma at the end of the line and find that it is followed by metadata. 2006 /// Clients that don't allow metadata can call the version of this function that 2007 /// only takes one argument. 2008 /// 2009 /// ParseIndexList 2010 /// ::= (',' uint32)+ 2011 /// 2012 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices, 2013 bool &AteExtraComma) { 2014 AteExtraComma = false; 2015 2016 if (Lex.getKind() != lltok::comma) 2017 return TokError("expected ',' as start of index list"); 2018 2019 while (EatIfPresent(lltok::comma)) { 2020 if (Lex.getKind() == lltok::MetadataVar) { 2021 if (Indices.empty()) return TokError("expected index"); 2022 AteExtraComma = true; 2023 return false; 2024 } 2025 unsigned Idx = 0; 2026 if (ParseUInt32(Idx)) return true; 2027 Indices.push_back(Idx); 2028 } 2029 2030 return false; 2031 } 2032 2033 //===----------------------------------------------------------------------===// 2034 // Type Parsing. 2035 //===----------------------------------------------------------------------===// 2036 2037 /// ParseType - Parse a type. 2038 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) { 2039 SMLoc TypeLoc = Lex.getLoc(); 2040 switch (Lex.getKind()) { 2041 default: 2042 return TokError(Msg); 2043 case lltok::Type: 2044 // Type ::= 'float' | 'void' (etc) 2045 Result = Lex.getTyVal(); 2046 Lex.Lex(); 2047 break; 2048 case lltok::lbrace: 2049 // Type ::= StructType 2050 if (ParseAnonStructType(Result, false)) 2051 return true; 2052 break; 2053 case lltok::lsquare: 2054 // Type ::= '[' ... ']' 2055 Lex.Lex(); // eat the lsquare. 2056 if (ParseArrayVectorType(Result, false)) 2057 return true; 2058 break; 2059 case lltok::less: // Either vector or packed struct. 2060 // Type ::= '<' ... '>' 2061 Lex.Lex(); 2062 if (Lex.getKind() == lltok::lbrace) { 2063 if (ParseAnonStructType(Result, true) || 2064 ParseToken(lltok::greater, "expected '>' at end of packed struct")) 2065 return true; 2066 } else if (ParseArrayVectorType(Result, true)) 2067 return true; 2068 break; 2069 case lltok::LocalVar: { 2070 // Type ::= %foo 2071 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()]; 2072 2073 // If the type hasn't been defined yet, create a forward definition and 2074 // remember where that forward def'n was seen (in case it never is defined). 2075 if (!Entry.first) { 2076 Entry.first = StructType::create(Context, Lex.getStrVal()); 2077 Entry.second = Lex.getLoc(); 2078 } 2079 Result = Entry.first; 2080 Lex.Lex(); 2081 break; 2082 } 2083 2084 case lltok::LocalVarID: { 2085 // Type ::= %4 2086 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()]; 2087 2088 // If the type hasn't been defined yet, create a forward definition and 2089 // remember where that forward def'n was seen (in case it never is defined). 2090 if (!Entry.first) { 2091 Entry.first = StructType::create(Context); 2092 Entry.second = Lex.getLoc(); 2093 } 2094 Result = Entry.first; 2095 Lex.Lex(); 2096 break; 2097 } 2098 } 2099 2100 // Parse the type suffixes. 2101 while (true) { 2102 switch (Lex.getKind()) { 2103 // End of type. 2104 default: 2105 if (!AllowVoid && Result->isVoidTy()) 2106 return Error(TypeLoc, "void type only allowed for function results"); 2107 return false; 2108 2109 // Type ::= Type '*' 2110 case lltok::star: 2111 if (Result->isLabelTy()) 2112 return TokError("basic block pointers are invalid"); 2113 if (Result->isVoidTy()) 2114 return TokError("pointers to void are invalid - use i8* instead"); 2115 if (!PointerType::isValidElementType(Result)) 2116 return TokError("pointer to this type is invalid"); 2117 Result = PointerType::getUnqual(Result); 2118 Lex.Lex(); 2119 break; 2120 2121 // Type ::= Type 'addrspace' '(' uint32 ')' '*' 2122 case lltok::kw_addrspace: { 2123 if (Result->isLabelTy()) 2124 return TokError("basic block pointers are invalid"); 2125 if (Result->isVoidTy()) 2126 return TokError("pointers to void are invalid; use i8* instead"); 2127 if (!PointerType::isValidElementType(Result)) 2128 return TokError("pointer to this type is invalid"); 2129 unsigned AddrSpace; 2130 if (ParseOptionalAddrSpace(AddrSpace) || 2131 ParseToken(lltok::star, "expected '*' in address space")) 2132 return true; 2133 2134 Result = PointerType::get(Result, AddrSpace); 2135 break; 2136 } 2137 2138 /// Types '(' ArgTypeListI ')' OptFuncAttrs 2139 case lltok::lparen: 2140 if (ParseFunctionType(Result)) 2141 return true; 2142 break; 2143 } 2144 } 2145 } 2146 2147 /// ParseParameterList 2148 /// ::= '(' ')' 2149 /// ::= '(' Arg (',' Arg)* ')' 2150 /// Arg 2151 /// ::= Type OptionalAttributes Value OptionalAttributes 2152 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList, 2153 PerFunctionState &PFS, bool IsMustTailCall, 2154 bool InVarArgsFunc) { 2155 if (ParseToken(lltok::lparen, "expected '(' in call")) 2156 return true; 2157 2158 while (Lex.getKind() != lltok::rparen) { 2159 // If this isn't the first argument, we need a comma. 2160 if (!ArgList.empty() && 2161 ParseToken(lltok::comma, "expected ',' in argument list")) 2162 return true; 2163 2164 // Parse an ellipsis if this is a musttail call in a variadic function. 2165 if (Lex.getKind() == lltok::dotdotdot) { 2166 const char *Msg = "unexpected ellipsis in argument list for "; 2167 if (!IsMustTailCall) 2168 return TokError(Twine(Msg) + "non-musttail call"); 2169 if (!InVarArgsFunc) 2170 return TokError(Twine(Msg) + "musttail call in non-varargs function"); 2171 Lex.Lex(); // Lex the '...', it is purely for readability. 2172 return ParseToken(lltok::rparen, "expected ')' at end of argument list"); 2173 } 2174 2175 // Parse the argument. 2176 LocTy ArgLoc; 2177 Type *ArgTy = nullptr; 2178 AttrBuilder ArgAttrs; 2179 Value *V; 2180 if (ParseType(ArgTy, ArgLoc)) 2181 return true; 2182 2183 if (ArgTy->isMetadataTy()) { 2184 if (ParseMetadataAsValue(V, PFS)) 2185 return true; 2186 } else { 2187 // Otherwise, handle normal operands. 2188 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS)) 2189 return true; 2190 } 2191 ArgList.push_back(ParamInfo( 2192 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs))); 2193 } 2194 2195 if (IsMustTailCall && InVarArgsFunc) 2196 return TokError("expected '...' at end of argument list for musttail call " 2197 "in varargs function"); 2198 2199 Lex.Lex(); // Lex the ')'. 2200 return false; 2201 } 2202 2203 /// ParseOptionalOperandBundles 2204 /// ::= /*empty*/ 2205 /// ::= '[' OperandBundle [, OperandBundle ]* ']' 2206 /// 2207 /// OperandBundle 2208 /// ::= bundle-tag '(' ')' 2209 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')' 2210 /// 2211 /// bundle-tag ::= String Constant 2212 bool LLParser::ParseOptionalOperandBundles( 2213 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) { 2214 LocTy BeginLoc = Lex.getLoc(); 2215 if (!EatIfPresent(lltok::lsquare)) 2216 return false; 2217 2218 while (Lex.getKind() != lltok::rsquare) { 2219 // If this isn't the first operand bundle, we need a comma. 2220 if (!BundleList.empty() && 2221 ParseToken(lltok::comma, "expected ',' in input list")) 2222 return true; 2223 2224 std::string Tag; 2225 if (ParseStringConstant(Tag)) 2226 return true; 2227 2228 if (ParseToken(lltok::lparen, "expected '(' in operand bundle")) 2229 return true; 2230 2231 std::vector<Value *> Inputs; 2232 while (Lex.getKind() != lltok::rparen) { 2233 // If this isn't the first input, we need a comma. 2234 if (!Inputs.empty() && 2235 ParseToken(lltok::comma, "expected ',' in input list")) 2236 return true; 2237 2238 Type *Ty = nullptr; 2239 Value *Input = nullptr; 2240 if (ParseType(Ty) || ParseValue(Ty, Input, PFS)) 2241 return true; 2242 Inputs.push_back(Input); 2243 } 2244 2245 BundleList.emplace_back(std::move(Tag), std::move(Inputs)); 2246 2247 Lex.Lex(); // Lex the ')'. 2248 } 2249 2250 if (BundleList.empty()) 2251 return Error(BeginLoc, "operand bundle set must not be empty"); 2252 2253 Lex.Lex(); // Lex the ']'. 2254 return false; 2255 } 2256 2257 /// ParseArgumentList - Parse the argument list for a function type or function 2258 /// prototype. 2259 /// ::= '(' ArgTypeListI ')' 2260 /// ArgTypeListI 2261 /// ::= /*empty*/ 2262 /// ::= '...' 2263 /// ::= ArgTypeList ',' '...' 2264 /// ::= ArgType (',' ArgType)* 2265 /// 2266 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, 2267 bool &isVarArg){ 2268 isVarArg = false; 2269 assert(Lex.getKind() == lltok::lparen); 2270 Lex.Lex(); // eat the (. 2271 2272 if (Lex.getKind() == lltok::rparen) { 2273 // empty 2274 } else if (Lex.getKind() == lltok::dotdotdot) { 2275 isVarArg = true; 2276 Lex.Lex(); 2277 } else { 2278 LocTy TypeLoc = Lex.getLoc(); 2279 Type *ArgTy = nullptr; 2280 AttrBuilder Attrs; 2281 std::string Name; 2282 2283 if (ParseType(ArgTy) || 2284 ParseOptionalParamAttrs(Attrs)) return true; 2285 2286 if (ArgTy->isVoidTy()) 2287 return Error(TypeLoc, "argument can not have void type"); 2288 2289 if (Lex.getKind() == lltok::LocalVar) { 2290 Name = Lex.getStrVal(); 2291 Lex.Lex(); 2292 } 2293 2294 if (!FunctionType::isValidArgumentType(ArgTy)) 2295 return Error(TypeLoc, "invalid type for function argument"); 2296 2297 ArgList.emplace_back(TypeLoc, ArgTy, 2298 AttributeSet::get(ArgTy->getContext(), Attrs), 2299 std::move(Name)); 2300 2301 while (EatIfPresent(lltok::comma)) { 2302 // Handle ... at end of arg list. 2303 if (EatIfPresent(lltok::dotdotdot)) { 2304 isVarArg = true; 2305 break; 2306 } 2307 2308 // Otherwise must be an argument type. 2309 TypeLoc = Lex.getLoc(); 2310 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true; 2311 2312 if (ArgTy->isVoidTy()) 2313 return Error(TypeLoc, "argument can not have void type"); 2314 2315 if (Lex.getKind() == lltok::LocalVar) { 2316 Name = Lex.getStrVal(); 2317 Lex.Lex(); 2318 } else { 2319 Name = ""; 2320 } 2321 2322 if (!ArgTy->isFirstClassType()) 2323 return Error(TypeLoc, "invalid type for function argument"); 2324 2325 ArgList.emplace_back(TypeLoc, ArgTy, 2326 AttributeSet::get(ArgTy->getContext(), Attrs), 2327 std::move(Name)); 2328 } 2329 } 2330 2331 return ParseToken(lltok::rparen, "expected ')' at end of argument list"); 2332 } 2333 2334 /// ParseFunctionType 2335 /// ::= Type ArgumentList OptionalAttrs 2336 bool LLParser::ParseFunctionType(Type *&Result) { 2337 assert(Lex.getKind() == lltok::lparen); 2338 2339 if (!FunctionType::isValidReturnType(Result)) 2340 return TokError("invalid function return type"); 2341 2342 SmallVector<ArgInfo, 8> ArgList; 2343 bool isVarArg; 2344 if (ParseArgumentList(ArgList, isVarArg)) 2345 return true; 2346 2347 // Reject names on the arguments lists. 2348 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 2349 if (!ArgList[i].Name.empty()) 2350 return Error(ArgList[i].Loc, "argument name invalid in function type"); 2351 if (ArgList[i].Attrs.hasAttributes()) 2352 return Error(ArgList[i].Loc, 2353 "argument attributes invalid in function type"); 2354 } 2355 2356 SmallVector<Type*, 16> ArgListTy; 2357 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 2358 ArgListTy.push_back(ArgList[i].Ty); 2359 2360 Result = FunctionType::get(Result, ArgListTy, isVarArg); 2361 return false; 2362 } 2363 2364 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into 2365 /// other structs. 2366 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) { 2367 SmallVector<Type*, 8> Elts; 2368 if (ParseStructBody(Elts)) return true; 2369 2370 Result = StructType::get(Context, Elts, Packed); 2371 return false; 2372 } 2373 2374 /// ParseStructDefinition - Parse a struct in a 'type' definition. 2375 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name, 2376 std::pair<Type*, LocTy> &Entry, 2377 Type *&ResultTy) { 2378 // If the type was already defined, diagnose the redefinition. 2379 if (Entry.first && !Entry.second.isValid()) 2380 return Error(TypeLoc, "redefinition of type"); 2381 2382 // If we have opaque, just return without filling in the definition for the 2383 // struct. This counts as a definition as far as the .ll file goes. 2384 if (EatIfPresent(lltok::kw_opaque)) { 2385 // This type is being defined, so clear the location to indicate this. 2386 Entry.second = SMLoc(); 2387 2388 // If this type number has never been uttered, create it. 2389 if (!Entry.first) 2390 Entry.first = StructType::create(Context, Name); 2391 ResultTy = Entry.first; 2392 return false; 2393 } 2394 2395 // If the type starts with '<', then it is either a packed struct or a vector. 2396 bool isPacked = EatIfPresent(lltok::less); 2397 2398 // If we don't have a struct, then we have a random type alias, which we 2399 // accept for compatibility with old files. These types are not allowed to be 2400 // forward referenced and not allowed to be recursive. 2401 if (Lex.getKind() != lltok::lbrace) { 2402 if (Entry.first) 2403 return Error(TypeLoc, "forward references to non-struct type"); 2404 2405 ResultTy = nullptr; 2406 if (isPacked) 2407 return ParseArrayVectorType(ResultTy, true); 2408 return ParseType(ResultTy); 2409 } 2410 2411 // This type is being defined, so clear the location to indicate this. 2412 Entry.second = SMLoc(); 2413 2414 // If this type number has never been uttered, create it. 2415 if (!Entry.first) 2416 Entry.first = StructType::create(Context, Name); 2417 2418 StructType *STy = cast<StructType>(Entry.first); 2419 2420 SmallVector<Type*, 8> Body; 2421 if (ParseStructBody(Body) || 2422 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct"))) 2423 return true; 2424 2425 STy->setBody(Body, isPacked); 2426 ResultTy = STy; 2427 return false; 2428 } 2429 2430 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere. 2431 /// StructType 2432 /// ::= '{' '}' 2433 /// ::= '{' Type (',' Type)* '}' 2434 /// ::= '<' '{' '}' '>' 2435 /// ::= '<' '{' Type (',' Type)* '}' '>' 2436 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) { 2437 assert(Lex.getKind() == lltok::lbrace); 2438 Lex.Lex(); // Consume the '{' 2439 2440 // Handle the empty struct. 2441 if (EatIfPresent(lltok::rbrace)) 2442 return false; 2443 2444 LocTy EltTyLoc = Lex.getLoc(); 2445 Type *Ty = nullptr; 2446 if (ParseType(Ty)) return true; 2447 Body.push_back(Ty); 2448 2449 if (!StructType::isValidElementType(Ty)) 2450 return Error(EltTyLoc, "invalid element type for struct"); 2451 2452 while (EatIfPresent(lltok::comma)) { 2453 EltTyLoc = Lex.getLoc(); 2454 if (ParseType(Ty)) return true; 2455 2456 if (!StructType::isValidElementType(Ty)) 2457 return Error(EltTyLoc, "invalid element type for struct"); 2458 2459 Body.push_back(Ty); 2460 } 2461 2462 return ParseToken(lltok::rbrace, "expected '}' at end of struct"); 2463 } 2464 2465 /// ParseArrayVectorType - Parse an array or vector type, assuming the first 2466 /// token has already been consumed. 2467 /// Type 2468 /// ::= '[' APSINTVAL 'x' Types ']' 2469 /// ::= '<' APSINTVAL 'x' Types '>' 2470 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) { 2471 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() || 2472 Lex.getAPSIntVal().getBitWidth() > 64) 2473 return TokError("expected number in address space"); 2474 2475 LocTy SizeLoc = Lex.getLoc(); 2476 uint64_t Size = Lex.getAPSIntVal().getZExtValue(); 2477 Lex.Lex(); 2478 2479 if (ParseToken(lltok::kw_x, "expected 'x' after element count")) 2480 return true; 2481 2482 LocTy TypeLoc = Lex.getLoc(); 2483 Type *EltTy = nullptr; 2484 if (ParseType(EltTy)) return true; 2485 2486 if (ParseToken(isVector ? lltok::greater : lltok::rsquare, 2487 "expected end of sequential type")) 2488 return true; 2489 2490 if (isVector) { 2491 if (Size == 0) 2492 return Error(SizeLoc, "zero element vector is illegal"); 2493 if ((unsigned)Size != Size) 2494 return Error(SizeLoc, "size too large for vector"); 2495 if (!VectorType::isValidElementType(EltTy)) 2496 return Error(TypeLoc, "invalid vector element type"); 2497 Result = VectorType::get(EltTy, unsigned(Size)); 2498 } else { 2499 if (!ArrayType::isValidElementType(EltTy)) 2500 return Error(TypeLoc, "invalid array element type"); 2501 Result = ArrayType::get(EltTy, Size); 2502 } 2503 return false; 2504 } 2505 2506 //===----------------------------------------------------------------------===// 2507 // Function Semantic Analysis. 2508 //===----------------------------------------------------------------------===// 2509 2510 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f, 2511 int functionNumber) 2512 : P(p), F(f), FunctionNumber(functionNumber) { 2513 2514 // Insert unnamed arguments into the NumberedVals list. 2515 for (Argument &A : F.args()) 2516 if (!A.hasName()) 2517 NumberedVals.push_back(&A); 2518 } 2519 2520 LLParser::PerFunctionState::~PerFunctionState() { 2521 // If there were any forward referenced non-basicblock values, delete them. 2522 2523 for (const auto &P : ForwardRefVals) { 2524 if (isa<BasicBlock>(P.second.first)) 2525 continue; 2526 P.second.first->replaceAllUsesWith( 2527 UndefValue::get(P.second.first->getType())); 2528 P.second.first->deleteValue(); 2529 } 2530 2531 for (const auto &P : ForwardRefValIDs) { 2532 if (isa<BasicBlock>(P.second.first)) 2533 continue; 2534 P.second.first->replaceAllUsesWith( 2535 UndefValue::get(P.second.first->getType())); 2536 P.second.first->deleteValue(); 2537 } 2538 } 2539 2540 bool LLParser::PerFunctionState::FinishFunction() { 2541 if (!ForwardRefVals.empty()) 2542 return P.Error(ForwardRefVals.begin()->second.second, 2543 "use of undefined value '%" + ForwardRefVals.begin()->first + 2544 "'"); 2545 if (!ForwardRefValIDs.empty()) 2546 return P.Error(ForwardRefValIDs.begin()->second.second, 2547 "use of undefined value '%" + 2548 Twine(ForwardRefValIDs.begin()->first) + "'"); 2549 return false; 2550 } 2551 2552 /// GetVal - Get a value with the specified name or ID, creating a 2553 /// forward reference record if needed. This can return null if the value 2554 /// exists but does not have the right type. 2555 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty, 2556 LocTy Loc) { 2557 // Look this name up in the normal function symbol table. 2558 Value *Val = F.getValueSymbolTable()->lookup(Name); 2559 2560 // If this is a forward reference for the value, see if we already created a 2561 // forward ref record. 2562 if (!Val) { 2563 auto I = ForwardRefVals.find(Name); 2564 if (I != ForwardRefVals.end()) 2565 Val = I->second.first; 2566 } 2567 2568 // If we have the value in the symbol table or fwd-ref table, return it. 2569 if (Val) { 2570 if (Val->getType() == Ty) return Val; 2571 if (Ty->isLabelTy()) 2572 P.Error(Loc, "'%" + Name + "' is not a basic block"); 2573 else 2574 P.Error(Loc, "'%" + Name + "' defined with type '" + 2575 getTypeString(Val->getType()) + "'"); 2576 return nullptr; 2577 } 2578 2579 // Don't make placeholders with invalid type. 2580 if (!Ty->isFirstClassType()) { 2581 P.Error(Loc, "invalid use of a non-first-class type"); 2582 return nullptr; 2583 } 2584 2585 // Otherwise, create a new forward reference for this value and remember it. 2586 Value *FwdVal; 2587 if (Ty->isLabelTy()) { 2588 FwdVal = BasicBlock::Create(F.getContext(), Name, &F); 2589 } else { 2590 FwdVal = new Argument(Ty, Name); 2591 } 2592 2593 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 2594 return FwdVal; 2595 } 2596 2597 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) { 2598 // Look this name up in the normal function symbol table. 2599 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr; 2600 2601 // If this is a forward reference for the value, see if we already created a 2602 // forward ref record. 2603 if (!Val) { 2604 auto I = ForwardRefValIDs.find(ID); 2605 if (I != ForwardRefValIDs.end()) 2606 Val = I->second.first; 2607 } 2608 2609 // If we have the value in the symbol table or fwd-ref table, return it. 2610 if (Val) { 2611 if (Val->getType() == Ty) return Val; 2612 if (Ty->isLabelTy()) 2613 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block"); 2614 else 2615 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" + 2616 getTypeString(Val->getType()) + "'"); 2617 return nullptr; 2618 } 2619 2620 if (!Ty->isFirstClassType()) { 2621 P.Error(Loc, "invalid use of a non-first-class type"); 2622 return nullptr; 2623 } 2624 2625 // Otherwise, create a new forward reference for this value and remember it. 2626 Value *FwdVal; 2627 if (Ty->isLabelTy()) { 2628 FwdVal = BasicBlock::Create(F.getContext(), "", &F); 2629 } else { 2630 FwdVal = new Argument(Ty); 2631 } 2632 2633 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 2634 return FwdVal; 2635 } 2636 2637 /// SetInstName - After an instruction is parsed and inserted into its 2638 /// basic block, this installs its name. 2639 bool LLParser::PerFunctionState::SetInstName(int NameID, 2640 const std::string &NameStr, 2641 LocTy NameLoc, Instruction *Inst) { 2642 // If this instruction has void type, it cannot have a name or ID specified. 2643 if (Inst->getType()->isVoidTy()) { 2644 if (NameID != -1 || !NameStr.empty()) 2645 return P.Error(NameLoc, "instructions returning void cannot have a name"); 2646 return false; 2647 } 2648 2649 // If this was a numbered instruction, verify that the instruction is the 2650 // expected value and resolve any forward references. 2651 if (NameStr.empty()) { 2652 // If neither a name nor an ID was specified, just use the next ID. 2653 if (NameID == -1) 2654 NameID = NumberedVals.size(); 2655 2656 if (unsigned(NameID) != NumberedVals.size()) 2657 return P.Error(NameLoc, "instruction expected to be numbered '%" + 2658 Twine(NumberedVals.size()) + "'"); 2659 2660 auto FI = ForwardRefValIDs.find(NameID); 2661 if (FI != ForwardRefValIDs.end()) { 2662 Value *Sentinel = FI->second.first; 2663 if (Sentinel->getType() != Inst->getType()) 2664 return P.Error(NameLoc, "instruction forward referenced with type '" + 2665 getTypeString(FI->second.first->getType()) + "'"); 2666 2667 Sentinel->replaceAllUsesWith(Inst); 2668 Sentinel->deleteValue(); 2669 ForwardRefValIDs.erase(FI); 2670 } 2671 2672 NumberedVals.push_back(Inst); 2673 return false; 2674 } 2675 2676 // Otherwise, the instruction had a name. Resolve forward refs and set it. 2677 auto FI = ForwardRefVals.find(NameStr); 2678 if (FI != ForwardRefVals.end()) { 2679 Value *Sentinel = FI->second.first; 2680 if (Sentinel->getType() != Inst->getType()) 2681 return P.Error(NameLoc, "instruction forward referenced with type '" + 2682 getTypeString(FI->second.first->getType()) + "'"); 2683 2684 Sentinel->replaceAllUsesWith(Inst); 2685 Sentinel->deleteValue(); 2686 ForwardRefVals.erase(FI); 2687 } 2688 2689 // Set the name on the instruction. 2690 Inst->setName(NameStr); 2691 2692 if (Inst->getName() != NameStr) 2693 return P.Error(NameLoc, "multiple definition of local value named '" + 2694 NameStr + "'"); 2695 return false; 2696 } 2697 2698 /// GetBB - Get a basic block with the specified name or ID, creating a 2699 /// forward reference record if needed. 2700 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name, 2701 LocTy Loc) { 2702 return dyn_cast_or_null<BasicBlock>(GetVal(Name, 2703 Type::getLabelTy(F.getContext()), Loc)); 2704 } 2705 2706 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) { 2707 return dyn_cast_or_null<BasicBlock>(GetVal(ID, 2708 Type::getLabelTy(F.getContext()), Loc)); 2709 } 2710 2711 /// DefineBB - Define the specified basic block, which is either named or 2712 /// unnamed. If there is an error, this returns null otherwise it returns 2713 /// the block being defined. 2714 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name, 2715 LocTy Loc) { 2716 BasicBlock *BB; 2717 if (Name.empty()) 2718 BB = GetBB(NumberedVals.size(), Loc); 2719 else 2720 BB = GetBB(Name, Loc); 2721 if (!BB) return nullptr; // Already diagnosed error. 2722 2723 // Move the block to the end of the function. Forward ref'd blocks are 2724 // inserted wherever they happen to be referenced. 2725 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB); 2726 2727 // Remove the block from forward ref sets. 2728 if (Name.empty()) { 2729 ForwardRefValIDs.erase(NumberedVals.size()); 2730 NumberedVals.push_back(BB); 2731 } else { 2732 // BB forward references are already in the function symbol table. 2733 ForwardRefVals.erase(Name); 2734 } 2735 2736 return BB; 2737 } 2738 2739 //===----------------------------------------------------------------------===// 2740 // Constants. 2741 //===----------------------------------------------------------------------===// 2742 2743 /// ParseValID - Parse an abstract value that doesn't necessarily have a 2744 /// type implied. For example, if we parse "4" we don't know what integer type 2745 /// it has. The value will later be combined with its type and checked for 2746 /// sanity. PFS is used to convert function-local operands of metadata (since 2747 /// metadata operands are not just parsed here but also converted to values). 2748 /// PFS can be null when we are not parsing metadata values inside a function. 2749 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) { 2750 ID.Loc = Lex.getLoc(); 2751 switch (Lex.getKind()) { 2752 default: return TokError("expected value token"); 2753 case lltok::GlobalID: // @42 2754 ID.UIntVal = Lex.getUIntVal(); 2755 ID.Kind = ValID::t_GlobalID; 2756 break; 2757 case lltok::GlobalVar: // @foo 2758 ID.StrVal = Lex.getStrVal(); 2759 ID.Kind = ValID::t_GlobalName; 2760 break; 2761 case lltok::LocalVarID: // %42 2762 ID.UIntVal = Lex.getUIntVal(); 2763 ID.Kind = ValID::t_LocalID; 2764 break; 2765 case lltok::LocalVar: // %foo 2766 ID.StrVal = Lex.getStrVal(); 2767 ID.Kind = ValID::t_LocalName; 2768 break; 2769 case lltok::APSInt: 2770 ID.APSIntVal = Lex.getAPSIntVal(); 2771 ID.Kind = ValID::t_APSInt; 2772 break; 2773 case lltok::APFloat: 2774 ID.APFloatVal = Lex.getAPFloatVal(); 2775 ID.Kind = ValID::t_APFloat; 2776 break; 2777 case lltok::kw_true: 2778 ID.ConstantVal = ConstantInt::getTrue(Context); 2779 ID.Kind = ValID::t_Constant; 2780 break; 2781 case lltok::kw_false: 2782 ID.ConstantVal = ConstantInt::getFalse(Context); 2783 ID.Kind = ValID::t_Constant; 2784 break; 2785 case lltok::kw_null: ID.Kind = ValID::t_Null; break; 2786 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break; 2787 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break; 2788 case lltok::kw_none: ID.Kind = ValID::t_None; break; 2789 2790 case lltok::lbrace: { 2791 // ValID ::= '{' ConstVector '}' 2792 Lex.Lex(); 2793 SmallVector<Constant*, 16> Elts; 2794 if (ParseGlobalValueVector(Elts) || 2795 ParseToken(lltok::rbrace, "expected end of struct constant")) 2796 return true; 2797 2798 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size()); 2799 ID.UIntVal = Elts.size(); 2800 memcpy(ID.ConstantStructElts.get(), Elts.data(), 2801 Elts.size() * sizeof(Elts[0])); 2802 ID.Kind = ValID::t_ConstantStruct; 2803 return false; 2804 } 2805 case lltok::less: { 2806 // ValID ::= '<' ConstVector '>' --> Vector. 2807 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct. 2808 Lex.Lex(); 2809 bool isPackedStruct = EatIfPresent(lltok::lbrace); 2810 2811 SmallVector<Constant*, 16> Elts; 2812 LocTy FirstEltLoc = Lex.getLoc(); 2813 if (ParseGlobalValueVector(Elts) || 2814 (isPackedStruct && 2815 ParseToken(lltok::rbrace, "expected end of packed struct")) || 2816 ParseToken(lltok::greater, "expected end of constant")) 2817 return true; 2818 2819 if (isPackedStruct) { 2820 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size()); 2821 memcpy(ID.ConstantStructElts.get(), Elts.data(), 2822 Elts.size() * sizeof(Elts[0])); 2823 ID.UIntVal = Elts.size(); 2824 ID.Kind = ValID::t_PackedConstantStruct; 2825 return false; 2826 } 2827 2828 if (Elts.empty()) 2829 return Error(ID.Loc, "constant vector must not be empty"); 2830 2831 if (!Elts[0]->getType()->isIntegerTy() && 2832 !Elts[0]->getType()->isFloatingPointTy() && 2833 !Elts[0]->getType()->isPointerTy()) 2834 return Error(FirstEltLoc, 2835 "vector elements must have integer, pointer or floating point type"); 2836 2837 // Verify that all the vector elements have the same type. 2838 for (unsigned i = 1, e = Elts.size(); i != e; ++i) 2839 if (Elts[i]->getType() != Elts[0]->getType()) 2840 return Error(FirstEltLoc, 2841 "vector element #" + Twine(i) + 2842 " is not of type '" + getTypeString(Elts[0]->getType())); 2843 2844 ID.ConstantVal = ConstantVector::get(Elts); 2845 ID.Kind = ValID::t_Constant; 2846 return false; 2847 } 2848 case lltok::lsquare: { // Array Constant 2849 Lex.Lex(); 2850 SmallVector<Constant*, 16> Elts; 2851 LocTy FirstEltLoc = Lex.getLoc(); 2852 if (ParseGlobalValueVector(Elts) || 2853 ParseToken(lltok::rsquare, "expected end of array constant")) 2854 return true; 2855 2856 // Handle empty element. 2857 if (Elts.empty()) { 2858 // Use undef instead of an array because it's inconvenient to determine 2859 // the element type at this point, there being no elements to examine. 2860 ID.Kind = ValID::t_EmptyArray; 2861 return false; 2862 } 2863 2864 if (!Elts[0]->getType()->isFirstClassType()) 2865 return Error(FirstEltLoc, "invalid array element type: " + 2866 getTypeString(Elts[0]->getType())); 2867 2868 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size()); 2869 2870 // Verify all elements are correct type! 2871 for (unsigned i = 0, e = Elts.size(); i != e; ++i) { 2872 if (Elts[i]->getType() != Elts[0]->getType()) 2873 return Error(FirstEltLoc, 2874 "array element #" + Twine(i) + 2875 " is not of type '" + getTypeString(Elts[0]->getType())); 2876 } 2877 2878 ID.ConstantVal = ConstantArray::get(ATy, Elts); 2879 ID.Kind = ValID::t_Constant; 2880 return false; 2881 } 2882 case lltok::kw_c: // c "foo" 2883 Lex.Lex(); 2884 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(), 2885 false); 2886 if (ParseToken(lltok::StringConstant, "expected string")) return true; 2887 ID.Kind = ValID::t_Constant; 2888 return false; 2889 2890 case lltok::kw_asm: { 2891 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ',' 2892 // STRINGCONSTANT 2893 bool HasSideEffect, AlignStack, AsmDialect; 2894 Lex.Lex(); 2895 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) || 2896 ParseOptionalToken(lltok::kw_alignstack, AlignStack) || 2897 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) || 2898 ParseStringConstant(ID.StrVal) || 2899 ParseToken(lltok::comma, "expected comma in inline asm expression") || 2900 ParseToken(lltok::StringConstant, "expected constraint string")) 2901 return true; 2902 ID.StrVal2 = Lex.getStrVal(); 2903 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) | 2904 (unsigned(AsmDialect)<<2); 2905 ID.Kind = ValID::t_InlineAsm; 2906 return false; 2907 } 2908 2909 case lltok::kw_blockaddress: { 2910 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')' 2911 Lex.Lex(); 2912 2913 ValID Fn, Label; 2914 2915 if (ParseToken(lltok::lparen, "expected '(' in block address expression") || 2916 ParseValID(Fn) || 2917 ParseToken(lltok::comma, "expected comma in block address expression")|| 2918 ParseValID(Label) || 2919 ParseToken(lltok::rparen, "expected ')' in block address expression")) 2920 return true; 2921 2922 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName) 2923 return Error(Fn.Loc, "expected function name in blockaddress"); 2924 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName) 2925 return Error(Label.Loc, "expected basic block name in blockaddress"); 2926 2927 // Try to find the function (but skip it if it's forward-referenced). 2928 GlobalValue *GV = nullptr; 2929 if (Fn.Kind == ValID::t_GlobalID) { 2930 if (Fn.UIntVal < NumberedVals.size()) 2931 GV = NumberedVals[Fn.UIntVal]; 2932 } else if (!ForwardRefVals.count(Fn.StrVal)) { 2933 GV = M->getNamedValue(Fn.StrVal); 2934 } 2935 Function *F = nullptr; 2936 if (GV) { 2937 // Confirm that it's actually a function with a definition. 2938 if (!isa<Function>(GV)) 2939 return Error(Fn.Loc, "expected function name in blockaddress"); 2940 F = cast<Function>(GV); 2941 if (F->isDeclaration()) 2942 return Error(Fn.Loc, "cannot take blockaddress inside a declaration"); 2943 } 2944 2945 if (!F) { 2946 // Make a global variable as a placeholder for this reference. 2947 GlobalValue *&FwdRef = 2948 ForwardRefBlockAddresses.insert(std::make_pair( 2949 std::move(Fn), 2950 std::map<ValID, GlobalValue *>())) 2951 .first->second.insert(std::make_pair(std::move(Label), nullptr)) 2952 .first->second; 2953 if (!FwdRef) 2954 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false, 2955 GlobalValue::InternalLinkage, nullptr, ""); 2956 ID.ConstantVal = FwdRef; 2957 ID.Kind = ValID::t_Constant; 2958 return false; 2959 } 2960 2961 // We found the function; now find the basic block. Don't use PFS, since we 2962 // might be inside a constant expression. 2963 BasicBlock *BB; 2964 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) { 2965 if (Label.Kind == ValID::t_LocalID) 2966 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc); 2967 else 2968 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc); 2969 if (!BB) 2970 return Error(Label.Loc, "referenced value is not a basic block"); 2971 } else { 2972 if (Label.Kind == ValID::t_LocalID) 2973 return Error(Label.Loc, "cannot take address of numeric label after " 2974 "the function is defined"); 2975 BB = dyn_cast_or_null<BasicBlock>( 2976 F->getValueSymbolTable()->lookup(Label.StrVal)); 2977 if (!BB) 2978 return Error(Label.Loc, "referenced value is not a basic block"); 2979 } 2980 2981 ID.ConstantVal = BlockAddress::get(F, BB); 2982 ID.Kind = ValID::t_Constant; 2983 return false; 2984 } 2985 2986 case lltok::kw_trunc: 2987 case lltok::kw_zext: 2988 case lltok::kw_sext: 2989 case lltok::kw_fptrunc: 2990 case lltok::kw_fpext: 2991 case lltok::kw_bitcast: 2992 case lltok::kw_addrspacecast: 2993 case lltok::kw_uitofp: 2994 case lltok::kw_sitofp: 2995 case lltok::kw_fptoui: 2996 case lltok::kw_fptosi: 2997 case lltok::kw_inttoptr: 2998 case lltok::kw_ptrtoint: { 2999 unsigned Opc = Lex.getUIntVal(); 3000 Type *DestTy = nullptr; 3001 Constant *SrcVal; 3002 Lex.Lex(); 3003 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") || 3004 ParseGlobalTypeAndValue(SrcVal) || 3005 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") || 3006 ParseType(DestTy) || 3007 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast")) 3008 return true; 3009 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy)) 3010 return Error(ID.Loc, "invalid cast opcode for cast from '" + 3011 getTypeString(SrcVal->getType()) + "' to '" + 3012 getTypeString(DestTy) + "'"); 3013 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, 3014 SrcVal, DestTy); 3015 ID.Kind = ValID::t_Constant; 3016 return false; 3017 } 3018 case lltok::kw_extractvalue: { 3019 Lex.Lex(); 3020 Constant *Val; 3021 SmallVector<unsigned, 4> Indices; 3022 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")|| 3023 ParseGlobalTypeAndValue(Val) || 3024 ParseIndexList(Indices) || 3025 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr")) 3026 return true; 3027 3028 if (!Val->getType()->isAggregateType()) 3029 return Error(ID.Loc, "extractvalue operand must be aggregate type"); 3030 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 3031 return Error(ID.Loc, "invalid indices for extractvalue"); 3032 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices); 3033 ID.Kind = ValID::t_Constant; 3034 return false; 3035 } 3036 case lltok::kw_insertvalue: { 3037 Lex.Lex(); 3038 Constant *Val0, *Val1; 3039 SmallVector<unsigned, 4> Indices; 3040 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")|| 3041 ParseGlobalTypeAndValue(Val0) || 3042 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")|| 3043 ParseGlobalTypeAndValue(Val1) || 3044 ParseIndexList(Indices) || 3045 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr")) 3046 return true; 3047 if (!Val0->getType()->isAggregateType()) 3048 return Error(ID.Loc, "insertvalue operand must be aggregate type"); 3049 Type *IndexedType = 3050 ExtractValueInst::getIndexedType(Val0->getType(), Indices); 3051 if (!IndexedType) 3052 return Error(ID.Loc, "invalid indices for insertvalue"); 3053 if (IndexedType != Val1->getType()) 3054 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" + 3055 getTypeString(Val1->getType()) + 3056 "' instead of '" + getTypeString(IndexedType) + 3057 "'"); 3058 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices); 3059 ID.Kind = ValID::t_Constant; 3060 return false; 3061 } 3062 case lltok::kw_icmp: 3063 case lltok::kw_fcmp: { 3064 unsigned PredVal, Opc = Lex.getUIntVal(); 3065 Constant *Val0, *Val1; 3066 Lex.Lex(); 3067 if (ParseCmpPredicate(PredVal, Opc) || 3068 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") || 3069 ParseGlobalTypeAndValue(Val0) || 3070 ParseToken(lltok::comma, "expected comma in compare constantexpr") || 3071 ParseGlobalTypeAndValue(Val1) || 3072 ParseToken(lltok::rparen, "expected ')' in compare constantexpr")) 3073 return true; 3074 3075 if (Val0->getType() != Val1->getType()) 3076 return Error(ID.Loc, "compare operands must have the same type"); 3077 3078 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal; 3079 3080 if (Opc == Instruction::FCmp) { 3081 if (!Val0->getType()->isFPOrFPVectorTy()) 3082 return Error(ID.Loc, "fcmp requires floating point operands"); 3083 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1); 3084 } else { 3085 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!"); 3086 if (!Val0->getType()->isIntOrIntVectorTy() && 3087 !Val0->getType()->isPtrOrPtrVectorTy()) 3088 return Error(ID.Loc, "icmp requires pointer or integer operands"); 3089 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1); 3090 } 3091 ID.Kind = ValID::t_Constant; 3092 return false; 3093 } 3094 3095 // Binary Operators. 3096 case lltok::kw_add: 3097 case lltok::kw_fadd: 3098 case lltok::kw_sub: 3099 case lltok::kw_fsub: 3100 case lltok::kw_mul: 3101 case lltok::kw_fmul: 3102 case lltok::kw_udiv: 3103 case lltok::kw_sdiv: 3104 case lltok::kw_fdiv: 3105 case lltok::kw_urem: 3106 case lltok::kw_srem: 3107 case lltok::kw_frem: 3108 case lltok::kw_shl: 3109 case lltok::kw_lshr: 3110 case lltok::kw_ashr: { 3111 bool NUW = false; 3112 bool NSW = false; 3113 bool Exact = false; 3114 unsigned Opc = Lex.getUIntVal(); 3115 Constant *Val0, *Val1; 3116 Lex.Lex(); 3117 LocTy ModifierLoc = Lex.getLoc(); 3118 if (Opc == Instruction::Add || Opc == Instruction::Sub || 3119 Opc == Instruction::Mul || Opc == Instruction::Shl) { 3120 if (EatIfPresent(lltok::kw_nuw)) 3121 NUW = true; 3122 if (EatIfPresent(lltok::kw_nsw)) { 3123 NSW = true; 3124 if (EatIfPresent(lltok::kw_nuw)) 3125 NUW = true; 3126 } 3127 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv || 3128 Opc == Instruction::LShr || Opc == Instruction::AShr) { 3129 if (EatIfPresent(lltok::kw_exact)) 3130 Exact = true; 3131 } 3132 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") || 3133 ParseGlobalTypeAndValue(Val0) || 3134 ParseToken(lltok::comma, "expected comma in binary constantexpr") || 3135 ParseGlobalTypeAndValue(Val1) || 3136 ParseToken(lltok::rparen, "expected ')' in binary constantexpr")) 3137 return true; 3138 if (Val0->getType() != Val1->getType()) 3139 return Error(ID.Loc, "operands of constexpr must have same type"); 3140 if (!Val0->getType()->isIntOrIntVectorTy()) { 3141 if (NUW) 3142 return Error(ModifierLoc, "nuw only applies to integer operations"); 3143 if (NSW) 3144 return Error(ModifierLoc, "nsw only applies to integer operations"); 3145 } 3146 // Check that the type is valid for the operator. 3147 switch (Opc) { 3148 case Instruction::Add: 3149 case Instruction::Sub: 3150 case Instruction::Mul: 3151 case Instruction::UDiv: 3152 case Instruction::SDiv: 3153 case Instruction::URem: 3154 case Instruction::SRem: 3155 case Instruction::Shl: 3156 case Instruction::AShr: 3157 case Instruction::LShr: 3158 if (!Val0->getType()->isIntOrIntVectorTy()) 3159 return Error(ID.Loc, "constexpr requires integer operands"); 3160 break; 3161 case Instruction::FAdd: 3162 case Instruction::FSub: 3163 case Instruction::FMul: 3164 case Instruction::FDiv: 3165 case Instruction::FRem: 3166 if (!Val0->getType()->isFPOrFPVectorTy()) 3167 return Error(ID.Loc, "constexpr requires fp operands"); 3168 break; 3169 default: llvm_unreachable("Unknown binary operator!"); 3170 } 3171 unsigned Flags = 0; 3172 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 3173 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap; 3174 if (Exact) Flags |= PossiblyExactOperator::IsExact; 3175 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags); 3176 ID.ConstantVal = C; 3177 ID.Kind = ValID::t_Constant; 3178 return false; 3179 } 3180 3181 // Logical Operations 3182 case lltok::kw_and: 3183 case lltok::kw_or: 3184 case lltok::kw_xor: { 3185 unsigned Opc = Lex.getUIntVal(); 3186 Constant *Val0, *Val1; 3187 Lex.Lex(); 3188 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") || 3189 ParseGlobalTypeAndValue(Val0) || 3190 ParseToken(lltok::comma, "expected comma in logical constantexpr") || 3191 ParseGlobalTypeAndValue(Val1) || 3192 ParseToken(lltok::rparen, "expected ')' in logical constantexpr")) 3193 return true; 3194 if (Val0->getType() != Val1->getType()) 3195 return Error(ID.Loc, "operands of constexpr must have same type"); 3196 if (!Val0->getType()->isIntOrIntVectorTy()) 3197 return Error(ID.Loc, 3198 "constexpr requires integer or integer vector operands"); 3199 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1); 3200 ID.Kind = ValID::t_Constant; 3201 return false; 3202 } 3203 3204 case lltok::kw_getelementptr: 3205 case lltok::kw_shufflevector: 3206 case lltok::kw_insertelement: 3207 case lltok::kw_extractelement: 3208 case lltok::kw_select: { 3209 unsigned Opc = Lex.getUIntVal(); 3210 SmallVector<Constant*, 16> Elts; 3211 bool InBounds = false; 3212 Type *Ty; 3213 Lex.Lex(); 3214 3215 if (Opc == Instruction::GetElementPtr) 3216 InBounds = EatIfPresent(lltok::kw_inbounds); 3217 3218 if (ParseToken(lltok::lparen, "expected '(' in constantexpr")) 3219 return true; 3220 3221 LocTy ExplicitTypeLoc = Lex.getLoc(); 3222 if (Opc == Instruction::GetElementPtr) { 3223 if (ParseType(Ty) || 3224 ParseToken(lltok::comma, "expected comma after getelementptr's type")) 3225 return true; 3226 } 3227 3228 Optional<unsigned> InRangeOp; 3229 if (ParseGlobalValueVector( 3230 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) || 3231 ParseToken(lltok::rparen, "expected ')' in constantexpr")) 3232 return true; 3233 3234 if (Opc == Instruction::GetElementPtr) { 3235 if (Elts.size() == 0 || 3236 !Elts[0]->getType()->isPtrOrPtrVectorTy()) 3237 return Error(ID.Loc, "base of getelementptr must be a pointer"); 3238 3239 Type *BaseType = Elts[0]->getType(); 3240 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType()); 3241 if (Ty != BasePointerType->getElementType()) 3242 return Error( 3243 ExplicitTypeLoc, 3244 "explicit pointee type doesn't match operand's pointee type"); 3245 3246 unsigned GEPWidth = 3247 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0; 3248 3249 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 3250 for (Constant *Val : Indices) { 3251 Type *ValTy = Val->getType(); 3252 if (!ValTy->isIntOrIntVectorTy()) 3253 return Error(ID.Loc, "getelementptr index must be an integer"); 3254 if (ValTy->isVectorTy()) { 3255 unsigned ValNumEl = ValTy->getVectorNumElements(); 3256 if (GEPWidth && (ValNumEl != GEPWidth)) 3257 return Error( 3258 ID.Loc, 3259 "getelementptr vector index has a wrong number of elements"); 3260 // GEPWidth may have been unknown because the base is a scalar, 3261 // but it is known now. 3262 GEPWidth = ValNumEl; 3263 } 3264 } 3265 3266 SmallPtrSet<Type*, 4> Visited; 3267 if (!Indices.empty() && !Ty->isSized(&Visited)) 3268 return Error(ID.Loc, "base element of getelementptr must be sized"); 3269 3270 if (!GetElementPtrInst::getIndexedType(Ty, Indices)) 3271 return Error(ID.Loc, "invalid getelementptr indices"); 3272 3273 if (InRangeOp) { 3274 if (*InRangeOp == 0) 3275 return Error(ID.Loc, 3276 "inrange keyword may not appear on pointer operand"); 3277 --*InRangeOp; 3278 } 3279 3280 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, 3281 InBounds, InRangeOp); 3282 } else if (Opc == Instruction::Select) { 3283 if (Elts.size() != 3) 3284 return Error(ID.Loc, "expected three operands to select"); 3285 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1], 3286 Elts[2])) 3287 return Error(ID.Loc, Reason); 3288 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]); 3289 } else if (Opc == Instruction::ShuffleVector) { 3290 if (Elts.size() != 3) 3291 return Error(ID.Loc, "expected three operands to shufflevector"); 3292 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 3293 return Error(ID.Loc, "invalid operands to shufflevector"); 3294 ID.ConstantVal = 3295 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]); 3296 } else if (Opc == Instruction::ExtractElement) { 3297 if (Elts.size() != 2) 3298 return Error(ID.Loc, "expected two operands to extractelement"); 3299 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1])) 3300 return Error(ID.Loc, "invalid extractelement operands"); 3301 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]); 3302 } else { 3303 assert(Opc == Instruction::InsertElement && "Unknown opcode"); 3304 if (Elts.size() != 3) 3305 return Error(ID.Loc, "expected three operands to insertelement"); 3306 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 3307 return Error(ID.Loc, "invalid insertelement operands"); 3308 ID.ConstantVal = 3309 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]); 3310 } 3311 3312 ID.Kind = ValID::t_Constant; 3313 return false; 3314 } 3315 } 3316 3317 Lex.Lex(); 3318 return false; 3319 } 3320 3321 /// ParseGlobalValue - Parse a global value with the specified type. 3322 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) { 3323 C = nullptr; 3324 ValID ID; 3325 Value *V = nullptr; 3326 bool Parsed = ParseValID(ID) || 3327 ConvertValIDToValue(Ty, ID, V, nullptr); 3328 if (V && !(C = dyn_cast<Constant>(V))) 3329 return Error(ID.Loc, "global values must be constants"); 3330 return Parsed; 3331 } 3332 3333 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) { 3334 Type *Ty = nullptr; 3335 return ParseType(Ty) || 3336 ParseGlobalValue(Ty, V); 3337 } 3338 3339 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) { 3340 C = nullptr; 3341 3342 LocTy KwLoc = Lex.getLoc(); 3343 if (!EatIfPresent(lltok::kw_comdat)) 3344 return false; 3345 3346 if (EatIfPresent(lltok::lparen)) { 3347 if (Lex.getKind() != lltok::ComdatVar) 3348 return TokError("expected comdat variable"); 3349 C = getComdat(Lex.getStrVal(), Lex.getLoc()); 3350 Lex.Lex(); 3351 if (ParseToken(lltok::rparen, "expected ')' after comdat var")) 3352 return true; 3353 } else { 3354 if (GlobalName.empty()) 3355 return TokError("comdat cannot be unnamed"); 3356 C = getComdat(GlobalName, KwLoc); 3357 } 3358 3359 return false; 3360 } 3361 3362 /// ParseGlobalValueVector 3363 /// ::= /*empty*/ 3364 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)* 3365 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts, 3366 Optional<unsigned> *InRangeOp) { 3367 // Empty list. 3368 if (Lex.getKind() == lltok::rbrace || 3369 Lex.getKind() == lltok::rsquare || 3370 Lex.getKind() == lltok::greater || 3371 Lex.getKind() == lltok::rparen) 3372 return false; 3373 3374 do { 3375 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange)) 3376 *InRangeOp = Elts.size(); 3377 3378 Constant *C; 3379 if (ParseGlobalTypeAndValue(C)) return true; 3380 Elts.push_back(C); 3381 } while (EatIfPresent(lltok::comma)); 3382 3383 return false; 3384 } 3385 3386 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) { 3387 SmallVector<Metadata *, 16> Elts; 3388 if (ParseMDNodeVector(Elts)) 3389 return true; 3390 3391 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts); 3392 return false; 3393 } 3394 3395 /// MDNode: 3396 /// ::= !{ ... } 3397 /// ::= !7 3398 /// ::= !DILocation(...) 3399 bool LLParser::ParseMDNode(MDNode *&N) { 3400 if (Lex.getKind() == lltok::MetadataVar) 3401 return ParseSpecializedMDNode(N); 3402 3403 return ParseToken(lltok::exclaim, "expected '!' here") || 3404 ParseMDNodeTail(N); 3405 } 3406 3407 bool LLParser::ParseMDNodeTail(MDNode *&N) { 3408 // !{ ... } 3409 if (Lex.getKind() == lltok::lbrace) 3410 return ParseMDTuple(N); 3411 3412 // !42 3413 return ParseMDNodeID(N); 3414 } 3415 3416 namespace { 3417 3418 /// Structure to represent an optional metadata field. 3419 template <class FieldTy> struct MDFieldImpl { 3420 typedef MDFieldImpl ImplTy; 3421 FieldTy Val; 3422 bool Seen; 3423 3424 void assign(FieldTy Val) { 3425 Seen = true; 3426 this->Val = std::move(Val); 3427 } 3428 3429 explicit MDFieldImpl(FieldTy Default) 3430 : Val(std::move(Default)), Seen(false) {} 3431 }; 3432 3433 struct MDUnsignedField : public MDFieldImpl<uint64_t> { 3434 uint64_t Max; 3435 3436 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX) 3437 : ImplTy(Default), Max(Max) {} 3438 }; 3439 3440 struct LineField : public MDUnsignedField { 3441 LineField() : MDUnsignedField(0, UINT32_MAX) {} 3442 }; 3443 3444 struct ColumnField : public MDUnsignedField { 3445 ColumnField() : MDUnsignedField(0, UINT16_MAX) {} 3446 }; 3447 3448 struct DwarfTagField : public MDUnsignedField { 3449 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {} 3450 DwarfTagField(dwarf::Tag DefaultTag) 3451 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {} 3452 }; 3453 3454 struct DwarfMacinfoTypeField : public MDUnsignedField { 3455 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {} 3456 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType) 3457 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {} 3458 }; 3459 3460 struct DwarfAttEncodingField : public MDUnsignedField { 3461 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {} 3462 }; 3463 3464 struct DwarfVirtualityField : public MDUnsignedField { 3465 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {} 3466 }; 3467 3468 struct DwarfLangField : public MDUnsignedField { 3469 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {} 3470 }; 3471 3472 struct DwarfCCField : public MDUnsignedField { 3473 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {} 3474 }; 3475 3476 struct EmissionKindField : public MDUnsignedField { 3477 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {} 3478 }; 3479 3480 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> { 3481 DIFlagField() : MDFieldImpl(DINode::FlagZero) {} 3482 }; 3483 3484 struct MDSignedField : public MDFieldImpl<int64_t> { 3485 int64_t Min; 3486 int64_t Max; 3487 3488 MDSignedField(int64_t Default = 0) 3489 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {} 3490 MDSignedField(int64_t Default, int64_t Min, int64_t Max) 3491 : ImplTy(Default), Min(Min), Max(Max) {} 3492 }; 3493 3494 struct MDBoolField : public MDFieldImpl<bool> { 3495 MDBoolField(bool Default = false) : ImplTy(Default) {} 3496 }; 3497 3498 struct MDField : public MDFieldImpl<Metadata *> { 3499 bool AllowNull; 3500 3501 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {} 3502 }; 3503 3504 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> { 3505 MDConstant() : ImplTy(nullptr) {} 3506 }; 3507 3508 struct MDStringField : public MDFieldImpl<MDString *> { 3509 bool AllowEmpty; 3510 MDStringField(bool AllowEmpty = true) 3511 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {} 3512 }; 3513 3514 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> { 3515 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {} 3516 }; 3517 3518 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> { 3519 ChecksumKindField() : ImplTy(DIFile::CSK_None) {} 3520 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {} 3521 }; 3522 3523 } // end anonymous namespace 3524 3525 namespace llvm { 3526 3527 template <> 3528 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 3529 MDUnsignedField &Result) { 3530 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 3531 return TokError("expected unsigned integer"); 3532 3533 auto &U = Lex.getAPSIntVal(); 3534 if (U.ugt(Result.Max)) 3535 return TokError("value for '" + Name + "' too large, limit is " + 3536 Twine(Result.Max)); 3537 Result.assign(U.getZExtValue()); 3538 assert(Result.Val <= Result.Max && "Expected value in range"); 3539 Lex.Lex(); 3540 return false; 3541 } 3542 3543 template <> 3544 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) { 3545 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3546 } 3547 template <> 3548 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) { 3549 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3550 } 3551 3552 template <> 3553 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) { 3554 if (Lex.getKind() == lltok::APSInt) 3555 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3556 3557 if (Lex.getKind() != lltok::DwarfTag) 3558 return TokError("expected DWARF tag"); 3559 3560 unsigned Tag = dwarf::getTag(Lex.getStrVal()); 3561 if (Tag == dwarf::DW_TAG_invalid) 3562 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'"); 3563 assert(Tag <= Result.Max && "Expected valid DWARF tag"); 3564 3565 Result.assign(Tag); 3566 Lex.Lex(); 3567 return false; 3568 } 3569 3570 template <> 3571 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 3572 DwarfMacinfoTypeField &Result) { 3573 if (Lex.getKind() == lltok::APSInt) 3574 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3575 3576 if (Lex.getKind() != lltok::DwarfMacinfo) 3577 return TokError("expected DWARF macinfo type"); 3578 3579 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal()); 3580 if (Macinfo == dwarf::DW_MACINFO_invalid) 3581 return TokError( 3582 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'"); 3583 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type"); 3584 3585 Result.assign(Macinfo); 3586 Lex.Lex(); 3587 return false; 3588 } 3589 3590 template <> 3591 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 3592 DwarfVirtualityField &Result) { 3593 if (Lex.getKind() == lltok::APSInt) 3594 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3595 3596 if (Lex.getKind() != lltok::DwarfVirtuality) 3597 return TokError("expected DWARF virtuality code"); 3598 3599 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal()); 3600 if (Virtuality == dwarf::DW_VIRTUALITY_invalid) 3601 return TokError("invalid DWARF virtuality code" + Twine(" '") + 3602 Lex.getStrVal() + "'"); 3603 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code"); 3604 Result.assign(Virtuality); 3605 Lex.Lex(); 3606 return false; 3607 } 3608 3609 template <> 3610 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) { 3611 if (Lex.getKind() == lltok::APSInt) 3612 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3613 3614 if (Lex.getKind() != lltok::DwarfLang) 3615 return TokError("expected DWARF language"); 3616 3617 unsigned Lang = dwarf::getLanguage(Lex.getStrVal()); 3618 if (!Lang) 3619 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() + 3620 "'"); 3621 assert(Lang <= Result.Max && "Expected valid DWARF language"); 3622 Result.assign(Lang); 3623 Lex.Lex(); 3624 return false; 3625 } 3626 3627 template <> 3628 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) { 3629 if (Lex.getKind() == lltok::APSInt) 3630 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3631 3632 if (Lex.getKind() != lltok::DwarfCC) 3633 return TokError("expected DWARF calling convention"); 3634 3635 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal()); 3636 if (!CC) 3637 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() + 3638 "'"); 3639 assert(CC <= Result.Max && "Expected valid DWARF calling convention"); 3640 Result.assign(CC); 3641 Lex.Lex(); 3642 return false; 3643 } 3644 3645 template <> 3646 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) { 3647 if (Lex.getKind() == lltok::APSInt) 3648 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3649 3650 if (Lex.getKind() != lltok::EmissionKind) 3651 return TokError("expected emission kind"); 3652 3653 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal()); 3654 if (!Kind) 3655 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() + 3656 "'"); 3657 assert(*Kind <= Result.Max && "Expected valid emission kind"); 3658 Result.assign(*Kind); 3659 Lex.Lex(); 3660 return false; 3661 } 3662 3663 template <> 3664 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 3665 DwarfAttEncodingField &Result) { 3666 if (Lex.getKind() == lltok::APSInt) 3667 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3668 3669 if (Lex.getKind() != lltok::DwarfAttEncoding) 3670 return TokError("expected DWARF type attribute encoding"); 3671 3672 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal()); 3673 if (!Encoding) 3674 return TokError("invalid DWARF type attribute encoding" + Twine(" '") + 3675 Lex.getStrVal() + "'"); 3676 assert(Encoding <= Result.Max && "Expected valid DWARF language"); 3677 Result.assign(Encoding); 3678 Lex.Lex(); 3679 return false; 3680 } 3681 3682 /// DIFlagField 3683 /// ::= uint32 3684 /// ::= DIFlagVector 3685 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic 3686 template <> 3687 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) { 3688 3689 // Parser for a single flag. 3690 auto parseFlag = [&](DINode::DIFlags &Val) { 3691 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) { 3692 uint32_t TempVal = static_cast<uint32_t>(Val); 3693 bool Res = ParseUInt32(TempVal); 3694 Val = static_cast<DINode::DIFlags>(TempVal); 3695 return Res; 3696 } 3697 3698 if (Lex.getKind() != lltok::DIFlag) 3699 return TokError("expected debug info flag"); 3700 3701 Val = DINode::getFlag(Lex.getStrVal()); 3702 if (!Val) 3703 return TokError(Twine("invalid debug info flag flag '") + 3704 Lex.getStrVal() + "'"); 3705 Lex.Lex(); 3706 return false; 3707 }; 3708 3709 // Parse the flags and combine them together. 3710 DINode::DIFlags Combined = DINode::FlagZero; 3711 do { 3712 DINode::DIFlags Val; 3713 if (parseFlag(Val)) 3714 return true; 3715 Combined |= Val; 3716 } while (EatIfPresent(lltok::bar)); 3717 3718 Result.assign(Combined); 3719 return false; 3720 } 3721 3722 template <> 3723 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 3724 MDSignedField &Result) { 3725 if (Lex.getKind() != lltok::APSInt) 3726 return TokError("expected signed integer"); 3727 3728 auto &S = Lex.getAPSIntVal(); 3729 if (S < Result.Min) 3730 return TokError("value for '" + Name + "' too small, limit is " + 3731 Twine(Result.Min)); 3732 if (S > Result.Max) 3733 return TokError("value for '" + Name + "' too large, limit is " + 3734 Twine(Result.Max)); 3735 Result.assign(S.getExtValue()); 3736 assert(Result.Val >= Result.Min && "Expected value in range"); 3737 assert(Result.Val <= Result.Max && "Expected value in range"); 3738 Lex.Lex(); 3739 return false; 3740 } 3741 3742 template <> 3743 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) { 3744 switch (Lex.getKind()) { 3745 default: 3746 return TokError("expected 'true' or 'false'"); 3747 case lltok::kw_true: 3748 Result.assign(true); 3749 break; 3750 case lltok::kw_false: 3751 Result.assign(false); 3752 break; 3753 } 3754 Lex.Lex(); 3755 return false; 3756 } 3757 3758 template <> 3759 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) { 3760 if (Lex.getKind() == lltok::kw_null) { 3761 if (!Result.AllowNull) 3762 return TokError("'" + Name + "' cannot be null"); 3763 Lex.Lex(); 3764 Result.assign(nullptr); 3765 return false; 3766 } 3767 3768 Metadata *MD; 3769 if (ParseMetadata(MD, nullptr)) 3770 return true; 3771 3772 Result.assign(MD); 3773 return false; 3774 } 3775 3776 template <> 3777 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) { 3778 LocTy ValueLoc = Lex.getLoc(); 3779 std::string S; 3780 if (ParseStringConstant(S)) 3781 return true; 3782 3783 if (!Result.AllowEmpty && S.empty()) 3784 return Error(ValueLoc, "'" + Name + "' cannot be empty"); 3785 3786 Result.assign(S.empty() ? nullptr : MDString::get(Context, S)); 3787 return false; 3788 } 3789 3790 template <> 3791 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) { 3792 SmallVector<Metadata *, 4> MDs; 3793 if (ParseMDNodeVector(MDs)) 3794 return true; 3795 3796 Result.assign(std::move(MDs)); 3797 return false; 3798 } 3799 3800 template <> 3801 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, 3802 ChecksumKindField &Result) { 3803 if (Lex.getKind() != lltok::ChecksumKind) 3804 return TokError( 3805 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'"); 3806 3807 DIFile::ChecksumKind CSKind = DIFile::getChecksumKind(Lex.getStrVal()); 3808 3809 Result.assign(CSKind); 3810 Lex.Lex(); 3811 return false; 3812 } 3813 3814 } // end namespace llvm 3815 3816 template <class ParserTy> 3817 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) { 3818 do { 3819 if (Lex.getKind() != lltok::LabelStr) 3820 return TokError("expected field label here"); 3821 3822 if (parseField()) 3823 return true; 3824 } while (EatIfPresent(lltok::comma)); 3825 3826 return false; 3827 } 3828 3829 template <class ParserTy> 3830 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) { 3831 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 3832 Lex.Lex(); 3833 3834 if (ParseToken(lltok::lparen, "expected '(' here")) 3835 return true; 3836 if (Lex.getKind() != lltok::rparen) 3837 if (ParseMDFieldsImplBody(parseField)) 3838 return true; 3839 3840 ClosingLoc = Lex.getLoc(); 3841 return ParseToken(lltok::rparen, "expected ')' here"); 3842 } 3843 3844 template <class FieldTy> 3845 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) { 3846 if (Result.Seen) 3847 return TokError("field '" + Name + "' cannot be specified more than once"); 3848 3849 LocTy Loc = Lex.getLoc(); 3850 Lex.Lex(); 3851 return ParseMDField(Loc, Name, Result); 3852 } 3853 3854 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) { 3855 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 3856 3857 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \ 3858 if (Lex.getStrVal() == #CLASS) \ 3859 return Parse##CLASS(N, IsDistinct); 3860 #include "llvm/IR/Metadata.def" 3861 3862 return TokError("expected metadata type"); 3863 } 3864 3865 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT 3866 #define NOP_FIELD(NAME, TYPE, INIT) 3867 #define REQUIRE_FIELD(NAME, TYPE, INIT) \ 3868 if (!NAME.Seen) \ 3869 return Error(ClosingLoc, "missing required field '" #NAME "'"); 3870 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \ 3871 if (Lex.getStrVal() == #NAME) \ 3872 return ParseMDField(#NAME, NAME); 3873 #define PARSE_MD_FIELDS() \ 3874 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \ 3875 do { \ 3876 LocTy ClosingLoc; \ 3877 if (ParseMDFieldsImpl([&]() -> bool { \ 3878 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \ 3879 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \ 3880 }, ClosingLoc)) \ 3881 return true; \ 3882 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \ 3883 } while (false) 3884 #define GET_OR_DISTINCT(CLASS, ARGS) \ 3885 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS) 3886 3887 /// ParseDILocationFields: 3888 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6) 3889 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) { 3890 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 3891 OPTIONAL(line, LineField, ); \ 3892 OPTIONAL(column, ColumnField, ); \ 3893 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 3894 OPTIONAL(inlinedAt, MDField, ); 3895 PARSE_MD_FIELDS(); 3896 #undef VISIT_MD_FIELDS 3897 3898 Result = GET_OR_DISTINCT( 3899 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val)); 3900 return false; 3901 } 3902 3903 /// ParseGenericDINode: 3904 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...}) 3905 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) { 3906 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 3907 REQUIRED(tag, DwarfTagField, ); \ 3908 OPTIONAL(header, MDStringField, ); \ 3909 OPTIONAL(operands, MDFieldList, ); 3910 PARSE_MD_FIELDS(); 3911 #undef VISIT_MD_FIELDS 3912 3913 Result = GET_OR_DISTINCT(GenericDINode, 3914 (Context, tag.Val, header.Val, operands.Val)); 3915 return false; 3916 } 3917 3918 /// ParseDISubrange: 3919 /// ::= !DISubrange(count: 30, lowerBound: 2) 3920 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) { 3921 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 3922 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \ 3923 OPTIONAL(lowerBound, MDSignedField, ); 3924 PARSE_MD_FIELDS(); 3925 #undef VISIT_MD_FIELDS 3926 3927 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val)); 3928 return false; 3929 } 3930 3931 /// ParseDIEnumerator: 3932 /// ::= !DIEnumerator(value: 30, name: "SomeKind") 3933 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) { 3934 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 3935 REQUIRED(name, MDStringField, ); \ 3936 REQUIRED(value, MDSignedField, ); 3937 PARSE_MD_FIELDS(); 3938 #undef VISIT_MD_FIELDS 3939 3940 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val)); 3941 return false; 3942 } 3943 3944 /// ParseDIBasicType: 3945 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32) 3946 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) { 3947 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 3948 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \ 3949 OPTIONAL(name, MDStringField, ); \ 3950 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 3951 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 3952 OPTIONAL(encoding, DwarfAttEncodingField, ); 3953 PARSE_MD_FIELDS(); 3954 #undef VISIT_MD_FIELDS 3955 3956 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val, 3957 align.Val, encoding.Val)); 3958 return false; 3959 } 3960 3961 /// ParseDIDerivedType: 3962 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0, 3963 /// line: 7, scope: !1, baseType: !2, size: 32, 3964 /// align: 32, offset: 0, flags: 0, extraData: !3, 3965 /// dwarfAddressSpace: 3) 3966 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) { 3967 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 3968 REQUIRED(tag, DwarfTagField, ); \ 3969 OPTIONAL(name, MDStringField, ); \ 3970 OPTIONAL(file, MDField, ); \ 3971 OPTIONAL(line, LineField, ); \ 3972 OPTIONAL(scope, MDField, ); \ 3973 REQUIRED(baseType, MDField, ); \ 3974 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 3975 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 3976 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \ 3977 OPTIONAL(flags, DIFlagField, ); \ 3978 OPTIONAL(extraData, MDField, ); \ 3979 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); 3980 PARSE_MD_FIELDS(); 3981 #undef VISIT_MD_FIELDS 3982 3983 Optional<unsigned> DWARFAddressSpace; 3984 if (dwarfAddressSpace.Val != UINT32_MAX) 3985 DWARFAddressSpace = dwarfAddressSpace.Val; 3986 3987 Result = GET_OR_DISTINCT(DIDerivedType, 3988 (Context, tag.Val, name.Val, file.Val, line.Val, 3989 scope.Val, baseType.Val, size.Val, align.Val, 3990 offset.Val, DWARFAddressSpace, flags.Val, 3991 extraData.Val)); 3992 return false; 3993 } 3994 3995 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) { 3996 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 3997 REQUIRED(tag, DwarfTagField, ); \ 3998 OPTIONAL(name, MDStringField, ); \ 3999 OPTIONAL(file, MDField, ); \ 4000 OPTIONAL(line, LineField, ); \ 4001 OPTIONAL(scope, MDField, ); \ 4002 OPTIONAL(baseType, MDField, ); \ 4003 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4004 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4005 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \ 4006 OPTIONAL(flags, DIFlagField, ); \ 4007 OPTIONAL(elements, MDField, ); \ 4008 OPTIONAL(runtimeLang, DwarfLangField, ); \ 4009 OPTIONAL(vtableHolder, MDField, ); \ 4010 OPTIONAL(templateParams, MDField, ); \ 4011 OPTIONAL(identifier, MDStringField, ); 4012 PARSE_MD_FIELDS(); 4013 #undef VISIT_MD_FIELDS 4014 4015 // If this has an identifier try to build an ODR type. 4016 if (identifier.Val) 4017 if (auto *CT = DICompositeType::buildODRType( 4018 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val, 4019 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val, 4020 elements.Val, runtimeLang.Val, vtableHolder.Val, 4021 templateParams.Val)) { 4022 Result = CT; 4023 return false; 4024 } 4025 4026 // Create a new node, and save it in the context if it belongs in the type 4027 // map. 4028 Result = GET_OR_DISTINCT( 4029 DICompositeType, 4030 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val, 4031 size.Val, align.Val, offset.Val, flags.Val, elements.Val, 4032 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val)); 4033 return false; 4034 } 4035 4036 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) { 4037 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4038 OPTIONAL(flags, DIFlagField, ); \ 4039 OPTIONAL(cc, DwarfCCField, ); \ 4040 REQUIRED(types, MDField, ); 4041 PARSE_MD_FIELDS(); 4042 #undef VISIT_MD_FIELDS 4043 4044 Result = GET_OR_DISTINCT(DISubroutineType, 4045 (Context, flags.Val, cc.Val, types.Val)); 4046 return false; 4047 } 4048 4049 /// ParseDIFileType: 4050 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir" 4051 /// checksumkind: CSK_MD5, 4052 /// checksum: "000102030405060708090a0b0c0d0e0f") 4053 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) { 4054 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4055 REQUIRED(filename, MDStringField, ); \ 4056 REQUIRED(directory, MDStringField, ); \ 4057 OPTIONAL(checksumkind, ChecksumKindField, ); \ 4058 OPTIONAL(checksum, MDStringField, ); 4059 PARSE_MD_FIELDS(); 4060 #undef VISIT_MD_FIELDS 4061 4062 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val, 4063 checksumkind.Val, checksum.Val)); 4064 return false; 4065 } 4066 4067 /// ParseDICompileUnit: 4068 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang", 4069 /// isOptimized: true, flags: "-O2", runtimeVersion: 1, 4070 /// splitDebugFilename: "abc.debug", 4071 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2, 4072 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd) 4073 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) { 4074 if (!IsDistinct) 4075 return Lex.Error("missing 'distinct', required for !DICompileUnit"); 4076 4077 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4078 REQUIRED(language, DwarfLangField, ); \ 4079 REQUIRED(file, MDField, (/* AllowNull */ false)); \ 4080 OPTIONAL(producer, MDStringField, ); \ 4081 OPTIONAL(isOptimized, MDBoolField, ); \ 4082 OPTIONAL(flags, MDStringField, ); \ 4083 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \ 4084 OPTIONAL(splitDebugFilename, MDStringField, ); \ 4085 OPTIONAL(emissionKind, EmissionKindField, ); \ 4086 OPTIONAL(enums, MDField, ); \ 4087 OPTIONAL(retainedTypes, MDField, ); \ 4088 OPTIONAL(globals, MDField, ); \ 4089 OPTIONAL(imports, MDField, ); \ 4090 OPTIONAL(macros, MDField, ); \ 4091 OPTIONAL(dwoId, MDUnsignedField, ); \ 4092 OPTIONAL(splitDebugInlining, MDBoolField, = true); \ 4093 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); 4094 PARSE_MD_FIELDS(); 4095 #undef VISIT_MD_FIELDS 4096 4097 Result = DICompileUnit::getDistinct( 4098 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val, 4099 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val, 4100 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val, 4101 splitDebugInlining.Val, debugInfoForProfiling.Val); 4102 return false; 4103 } 4104 4105 /// ParseDISubprogram: 4106 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo", 4107 /// file: !1, line: 7, type: !2, isLocal: false, 4108 /// isDefinition: true, scopeLine: 8, containingType: !3, 4109 /// virtuality: DW_VIRTUALTIY_pure_virtual, 4110 /// virtualIndex: 10, thisAdjustment: 4, flags: 11, 4111 /// isOptimized: false, templateParams: !4, declaration: !5, 4112 /// variables: !6, thrownTypes: !7) 4113 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) { 4114 auto Loc = Lex.getLoc(); 4115 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4116 OPTIONAL(scope, MDField, ); \ 4117 OPTIONAL(name, MDStringField, ); \ 4118 OPTIONAL(linkageName, MDStringField, ); \ 4119 OPTIONAL(file, MDField, ); \ 4120 OPTIONAL(line, LineField, ); \ 4121 OPTIONAL(type, MDField, ); \ 4122 OPTIONAL(isLocal, MDBoolField, ); \ 4123 OPTIONAL(isDefinition, MDBoolField, (true)); \ 4124 OPTIONAL(scopeLine, LineField, ); \ 4125 OPTIONAL(containingType, MDField, ); \ 4126 OPTIONAL(virtuality, DwarfVirtualityField, ); \ 4127 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \ 4128 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \ 4129 OPTIONAL(flags, DIFlagField, ); \ 4130 OPTIONAL(isOptimized, MDBoolField, ); \ 4131 OPTIONAL(unit, MDField, ); \ 4132 OPTIONAL(templateParams, MDField, ); \ 4133 OPTIONAL(declaration, MDField, ); \ 4134 OPTIONAL(variables, MDField, ); \ 4135 OPTIONAL(thrownTypes, MDField, ); 4136 PARSE_MD_FIELDS(); 4137 #undef VISIT_MD_FIELDS 4138 4139 if (isDefinition.Val && !IsDistinct) 4140 return Lex.Error( 4141 Loc, 4142 "missing 'distinct', required for !DISubprogram when 'isDefinition'"); 4143 4144 Result = GET_OR_DISTINCT( 4145 DISubprogram, 4146 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val, 4147 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val, 4148 containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val, 4149 flags.Val, isOptimized.Val, unit.Val, templateParams.Val, 4150 declaration.Val, variables.Val, thrownTypes.Val)); 4151 return false; 4152 } 4153 4154 /// ParseDILexicalBlock: 4155 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9) 4156 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) { 4157 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4158 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4159 OPTIONAL(file, MDField, ); \ 4160 OPTIONAL(line, LineField, ); \ 4161 OPTIONAL(column, ColumnField, ); 4162 PARSE_MD_FIELDS(); 4163 #undef VISIT_MD_FIELDS 4164 4165 Result = GET_OR_DISTINCT( 4166 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val)); 4167 return false; 4168 } 4169 4170 /// ParseDILexicalBlockFile: 4171 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9) 4172 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) { 4173 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4174 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4175 OPTIONAL(file, MDField, ); \ 4176 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX)); 4177 PARSE_MD_FIELDS(); 4178 #undef VISIT_MD_FIELDS 4179 4180 Result = GET_OR_DISTINCT(DILexicalBlockFile, 4181 (Context, scope.Val, file.Val, discriminator.Val)); 4182 return false; 4183 } 4184 4185 /// ParseDINamespace: 4186 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9) 4187 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) { 4188 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4189 REQUIRED(scope, MDField, ); \ 4190 OPTIONAL(name, MDStringField, ); \ 4191 OPTIONAL(exportSymbols, MDBoolField, ); 4192 PARSE_MD_FIELDS(); 4193 #undef VISIT_MD_FIELDS 4194 4195 Result = GET_OR_DISTINCT(DINamespace, 4196 (Context, scope.Val, name.Val, exportSymbols.Val)); 4197 return false; 4198 } 4199 4200 /// ParseDIMacro: 4201 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue") 4202 bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) { 4203 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4204 REQUIRED(type, DwarfMacinfoTypeField, ); \ 4205 OPTIONAL(line, LineField, ); \ 4206 REQUIRED(name, MDStringField, ); \ 4207 OPTIONAL(value, MDStringField, ); 4208 PARSE_MD_FIELDS(); 4209 #undef VISIT_MD_FIELDS 4210 4211 Result = GET_OR_DISTINCT(DIMacro, 4212 (Context, type.Val, line.Val, name.Val, value.Val)); 4213 return false; 4214 } 4215 4216 /// ParseDIMacroFile: 4217 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3) 4218 bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) { 4219 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4220 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \ 4221 OPTIONAL(line, LineField, ); \ 4222 REQUIRED(file, MDField, ); \ 4223 OPTIONAL(nodes, MDField, ); 4224 PARSE_MD_FIELDS(); 4225 #undef VISIT_MD_FIELDS 4226 4227 Result = GET_OR_DISTINCT(DIMacroFile, 4228 (Context, type.Val, line.Val, file.Val, nodes.Val)); 4229 return false; 4230 } 4231 4232 /// ParseDIModule: 4233 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG", 4234 /// includePath: "/usr/include", isysroot: "/") 4235 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) { 4236 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4237 REQUIRED(scope, MDField, ); \ 4238 REQUIRED(name, MDStringField, ); \ 4239 OPTIONAL(configMacros, MDStringField, ); \ 4240 OPTIONAL(includePath, MDStringField, ); \ 4241 OPTIONAL(isysroot, MDStringField, ); 4242 PARSE_MD_FIELDS(); 4243 #undef VISIT_MD_FIELDS 4244 4245 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val, 4246 configMacros.Val, includePath.Val, isysroot.Val)); 4247 return false; 4248 } 4249 4250 /// ParseDITemplateTypeParameter: 4251 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1) 4252 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) { 4253 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4254 OPTIONAL(name, MDStringField, ); \ 4255 REQUIRED(type, MDField, ); 4256 PARSE_MD_FIELDS(); 4257 #undef VISIT_MD_FIELDS 4258 4259 Result = 4260 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val)); 4261 return false; 4262 } 4263 4264 /// ParseDITemplateValueParameter: 4265 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter, 4266 /// name: "V", type: !1, value: i32 7) 4267 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) { 4268 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4269 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \ 4270 OPTIONAL(name, MDStringField, ); \ 4271 OPTIONAL(type, MDField, ); \ 4272 REQUIRED(value, MDField, ); 4273 PARSE_MD_FIELDS(); 4274 #undef VISIT_MD_FIELDS 4275 4276 Result = GET_OR_DISTINCT(DITemplateValueParameter, 4277 (Context, tag.Val, name.Val, type.Val, value.Val)); 4278 return false; 4279 } 4280 4281 /// ParseDIGlobalVariable: 4282 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo", 4283 /// file: !1, line: 7, type: !2, isLocal: false, 4284 /// isDefinition: true, declaration: !3, align: 8) 4285 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) { 4286 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4287 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \ 4288 OPTIONAL(scope, MDField, ); \ 4289 OPTIONAL(linkageName, MDStringField, ); \ 4290 OPTIONAL(file, MDField, ); \ 4291 OPTIONAL(line, LineField, ); \ 4292 OPTIONAL(type, MDField, ); \ 4293 OPTIONAL(isLocal, MDBoolField, ); \ 4294 OPTIONAL(isDefinition, MDBoolField, (true)); \ 4295 OPTIONAL(declaration, MDField, ); \ 4296 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); 4297 PARSE_MD_FIELDS(); 4298 #undef VISIT_MD_FIELDS 4299 4300 Result = GET_OR_DISTINCT(DIGlobalVariable, 4301 (Context, scope.Val, name.Val, linkageName.Val, 4302 file.Val, line.Val, type.Val, isLocal.Val, 4303 isDefinition.Val, declaration.Val, align.Val)); 4304 return false; 4305 } 4306 4307 /// ParseDILocalVariable: 4308 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo", 4309 /// file: !1, line: 7, type: !2, arg: 2, flags: 7, 4310 /// align: 8) 4311 /// ::= !DILocalVariable(scope: !0, name: "foo", 4312 /// file: !1, line: 7, type: !2, arg: 2, flags: 7, 4313 /// align: 8) 4314 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) { 4315 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4316 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4317 OPTIONAL(name, MDStringField, ); \ 4318 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \ 4319 OPTIONAL(file, MDField, ); \ 4320 OPTIONAL(line, LineField, ); \ 4321 OPTIONAL(type, MDField, ); \ 4322 OPTIONAL(flags, DIFlagField, ); \ 4323 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); 4324 PARSE_MD_FIELDS(); 4325 #undef VISIT_MD_FIELDS 4326 4327 Result = GET_OR_DISTINCT(DILocalVariable, 4328 (Context, scope.Val, name.Val, file.Val, line.Val, 4329 type.Val, arg.Val, flags.Val, align.Val)); 4330 return false; 4331 } 4332 4333 /// ParseDIExpression: 4334 /// ::= !DIExpression(0, 7, -1) 4335 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) { 4336 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 4337 Lex.Lex(); 4338 4339 if (ParseToken(lltok::lparen, "expected '(' here")) 4340 return true; 4341 4342 SmallVector<uint64_t, 8> Elements; 4343 if (Lex.getKind() != lltok::rparen) 4344 do { 4345 if (Lex.getKind() == lltok::DwarfOp) { 4346 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) { 4347 Lex.Lex(); 4348 Elements.push_back(Op); 4349 continue; 4350 } 4351 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'"); 4352 } 4353 4354 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 4355 return TokError("expected unsigned integer"); 4356 4357 auto &U = Lex.getAPSIntVal(); 4358 if (U.ugt(UINT64_MAX)) 4359 return TokError("element too large, limit is " + Twine(UINT64_MAX)); 4360 Elements.push_back(U.getZExtValue()); 4361 Lex.Lex(); 4362 } while (EatIfPresent(lltok::comma)); 4363 4364 if (ParseToken(lltok::rparen, "expected ')' here")) 4365 return true; 4366 4367 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements)); 4368 return false; 4369 } 4370 4371 /// ParseDIGlobalVariableExpression: 4372 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1) 4373 bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result, 4374 bool IsDistinct) { 4375 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4376 REQUIRED(var, MDField, ); \ 4377 OPTIONAL(expr, MDField, ); 4378 PARSE_MD_FIELDS(); 4379 #undef VISIT_MD_FIELDS 4380 4381 Result = 4382 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val)); 4383 return false; 4384 } 4385 4386 /// ParseDIObjCProperty: 4387 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo", 4388 /// getter: "getFoo", attributes: 7, type: !2) 4389 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) { 4390 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4391 OPTIONAL(name, MDStringField, ); \ 4392 OPTIONAL(file, MDField, ); \ 4393 OPTIONAL(line, LineField, ); \ 4394 OPTIONAL(setter, MDStringField, ); \ 4395 OPTIONAL(getter, MDStringField, ); \ 4396 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \ 4397 OPTIONAL(type, MDField, ); 4398 PARSE_MD_FIELDS(); 4399 #undef VISIT_MD_FIELDS 4400 4401 Result = GET_OR_DISTINCT(DIObjCProperty, 4402 (Context, name.Val, file.Val, line.Val, setter.Val, 4403 getter.Val, attributes.Val, type.Val)); 4404 return false; 4405 } 4406 4407 /// ParseDIImportedEntity: 4408 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1, 4409 /// line: 7, name: "foo") 4410 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) { 4411 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4412 REQUIRED(tag, DwarfTagField, ); \ 4413 REQUIRED(scope, MDField, ); \ 4414 OPTIONAL(entity, MDField, ); \ 4415 OPTIONAL(file, MDField, ); \ 4416 OPTIONAL(line, LineField, ); \ 4417 OPTIONAL(name, MDStringField, ); 4418 PARSE_MD_FIELDS(); 4419 #undef VISIT_MD_FIELDS 4420 4421 Result = GET_OR_DISTINCT( 4422 DIImportedEntity, 4423 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val)); 4424 return false; 4425 } 4426 4427 #undef PARSE_MD_FIELD 4428 #undef NOP_FIELD 4429 #undef REQUIRE_FIELD 4430 #undef DECLARE_FIELD 4431 4432 /// ParseMetadataAsValue 4433 /// ::= metadata i32 %local 4434 /// ::= metadata i32 @global 4435 /// ::= metadata i32 7 4436 /// ::= metadata !0 4437 /// ::= metadata !{...} 4438 /// ::= metadata !"string" 4439 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) { 4440 // Note: the type 'metadata' has already been parsed. 4441 Metadata *MD; 4442 if (ParseMetadata(MD, &PFS)) 4443 return true; 4444 4445 V = MetadataAsValue::get(Context, MD); 4446 return false; 4447 } 4448 4449 /// ParseValueAsMetadata 4450 /// ::= i32 %local 4451 /// ::= i32 @global 4452 /// ::= i32 7 4453 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg, 4454 PerFunctionState *PFS) { 4455 Type *Ty; 4456 LocTy Loc; 4457 if (ParseType(Ty, TypeMsg, Loc)) 4458 return true; 4459 if (Ty->isMetadataTy()) 4460 return Error(Loc, "invalid metadata-value-metadata roundtrip"); 4461 4462 Value *V; 4463 if (ParseValue(Ty, V, PFS)) 4464 return true; 4465 4466 MD = ValueAsMetadata::get(V); 4467 return false; 4468 } 4469 4470 /// ParseMetadata 4471 /// ::= i32 %local 4472 /// ::= i32 @global 4473 /// ::= i32 7 4474 /// ::= !42 4475 /// ::= !{...} 4476 /// ::= !"string" 4477 /// ::= !DILocation(...) 4478 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) { 4479 if (Lex.getKind() == lltok::MetadataVar) { 4480 MDNode *N; 4481 if (ParseSpecializedMDNode(N)) 4482 return true; 4483 MD = N; 4484 return false; 4485 } 4486 4487 // ValueAsMetadata: 4488 // <type> <value> 4489 if (Lex.getKind() != lltok::exclaim) 4490 return ParseValueAsMetadata(MD, "expected metadata operand", PFS); 4491 4492 // '!'. 4493 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here"); 4494 Lex.Lex(); 4495 4496 // MDString: 4497 // ::= '!' STRINGCONSTANT 4498 if (Lex.getKind() == lltok::StringConstant) { 4499 MDString *S; 4500 if (ParseMDString(S)) 4501 return true; 4502 MD = S; 4503 return false; 4504 } 4505 4506 // MDNode: 4507 // !{ ... } 4508 // !7 4509 MDNode *N; 4510 if (ParseMDNodeTail(N)) 4511 return true; 4512 MD = N; 4513 return false; 4514 } 4515 4516 //===----------------------------------------------------------------------===// 4517 // Function Parsing. 4518 //===----------------------------------------------------------------------===// 4519 4520 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V, 4521 PerFunctionState *PFS) { 4522 if (Ty->isFunctionTy()) 4523 return Error(ID.Loc, "functions are not values, refer to them as pointers"); 4524 4525 switch (ID.Kind) { 4526 case ValID::t_LocalID: 4527 if (!PFS) return Error(ID.Loc, "invalid use of function-local name"); 4528 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc); 4529 return V == nullptr; 4530 case ValID::t_LocalName: 4531 if (!PFS) return Error(ID.Loc, "invalid use of function-local name"); 4532 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc); 4533 return V == nullptr; 4534 case ValID::t_InlineAsm: { 4535 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2)) 4536 return Error(ID.Loc, "invalid type for inline asm constraint string"); 4537 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, 4538 (ID.UIntVal >> 1) & 1, 4539 (InlineAsm::AsmDialect(ID.UIntVal >> 2))); 4540 return false; 4541 } 4542 case ValID::t_GlobalName: 4543 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc); 4544 return V == nullptr; 4545 case ValID::t_GlobalID: 4546 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc); 4547 return V == nullptr; 4548 case ValID::t_APSInt: 4549 if (!Ty->isIntegerTy()) 4550 return Error(ID.Loc, "integer constant must have integer type"); 4551 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits()); 4552 V = ConstantInt::get(Context, ID.APSIntVal); 4553 return false; 4554 case ValID::t_APFloat: 4555 if (!Ty->isFloatingPointTy() || 4556 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal)) 4557 return Error(ID.Loc, "floating point constant invalid for type"); 4558 4559 // The lexer has no type info, so builds all half, float, and double FP 4560 // constants as double. Fix this here. Long double does not need this. 4561 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) { 4562 bool Ignored; 4563 if (Ty->isHalfTy()) 4564 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, 4565 &Ignored); 4566 else if (Ty->isFloatTy()) 4567 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 4568 &Ignored); 4569 } 4570 V = ConstantFP::get(Context, ID.APFloatVal); 4571 4572 if (V->getType() != Ty) 4573 return Error(ID.Loc, "floating point constant does not have type '" + 4574 getTypeString(Ty) + "'"); 4575 4576 return false; 4577 case ValID::t_Null: 4578 if (!Ty->isPointerTy()) 4579 return Error(ID.Loc, "null must be a pointer type"); 4580 V = ConstantPointerNull::get(cast<PointerType>(Ty)); 4581 return false; 4582 case ValID::t_Undef: 4583 // FIXME: LabelTy should not be a first-class type. 4584 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 4585 return Error(ID.Loc, "invalid type for undef constant"); 4586 V = UndefValue::get(Ty); 4587 return false; 4588 case ValID::t_EmptyArray: 4589 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0) 4590 return Error(ID.Loc, "invalid empty array initializer"); 4591 V = UndefValue::get(Ty); 4592 return false; 4593 case ValID::t_Zero: 4594 // FIXME: LabelTy should not be a first-class type. 4595 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 4596 return Error(ID.Loc, "invalid type for null constant"); 4597 V = Constant::getNullValue(Ty); 4598 return false; 4599 case ValID::t_None: 4600 if (!Ty->isTokenTy()) 4601 return Error(ID.Loc, "invalid type for none constant"); 4602 V = Constant::getNullValue(Ty); 4603 return false; 4604 case ValID::t_Constant: 4605 if (ID.ConstantVal->getType() != Ty) 4606 return Error(ID.Loc, "constant expression type mismatch"); 4607 4608 V = ID.ConstantVal; 4609 return false; 4610 case ValID::t_ConstantStruct: 4611 case ValID::t_PackedConstantStruct: 4612 if (StructType *ST = dyn_cast<StructType>(Ty)) { 4613 if (ST->getNumElements() != ID.UIntVal) 4614 return Error(ID.Loc, 4615 "initializer with struct type has wrong # elements"); 4616 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct)) 4617 return Error(ID.Loc, "packed'ness of initializer and type don't match"); 4618 4619 // Verify that the elements are compatible with the structtype. 4620 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i) 4621 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i)) 4622 return Error(ID.Loc, "element " + Twine(i) + 4623 " of struct initializer doesn't match struct element type"); 4624 4625 V = ConstantStruct::get( 4626 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal)); 4627 } else 4628 return Error(ID.Loc, "constant expression type mismatch"); 4629 return false; 4630 } 4631 llvm_unreachable("Invalid ValID"); 4632 } 4633 4634 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) { 4635 C = nullptr; 4636 ValID ID; 4637 auto Loc = Lex.getLoc(); 4638 if (ParseValID(ID, /*PFS=*/nullptr)) 4639 return true; 4640 switch (ID.Kind) { 4641 case ValID::t_APSInt: 4642 case ValID::t_APFloat: 4643 case ValID::t_Undef: 4644 case ValID::t_Constant: 4645 case ValID::t_ConstantStruct: 4646 case ValID::t_PackedConstantStruct: { 4647 Value *V; 4648 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr)) 4649 return true; 4650 assert(isa<Constant>(V) && "Expected a constant value"); 4651 C = cast<Constant>(V); 4652 return false; 4653 } 4654 case ValID::t_Null: 4655 C = Constant::getNullValue(Ty); 4656 return false; 4657 default: 4658 return Error(Loc, "expected a constant value"); 4659 } 4660 } 4661 4662 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) { 4663 V = nullptr; 4664 ValID ID; 4665 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS); 4666 } 4667 4668 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) { 4669 Type *Ty = nullptr; 4670 return ParseType(Ty) || 4671 ParseValue(Ty, V, PFS); 4672 } 4673 4674 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc, 4675 PerFunctionState &PFS) { 4676 Value *V; 4677 Loc = Lex.getLoc(); 4678 if (ParseTypeAndValue(V, PFS)) return true; 4679 if (!isa<BasicBlock>(V)) 4680 return Error(Loc, "expected a basic block"); 4681 BB = cast<BasicBlock>(V); 4682 return false; 4683 } 4684 4685 /// FunctionHeader 4686 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs 4687 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection 4688 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn 4689 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) { 4690 // Parse the linkage. 4691 LocTy LinkageLoc = Lex.getLoc(); 4692 unsigned Linkage; 4693 4694 unsigned Visibility; 4695 unsigned DLLStorageClass; 4696 AttrBuilder RetAttrs; 4697 unsigned CC; 4698 bool HasLinkage; 4699 Type *RetType = nullptr; 4700 LocTy RetTypeLoc = Lex.getLoc(); 4701 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) || 4702 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) || 4703 ParseType(RetType, RetTypeLoc, true /*void allowed*/)) 4704 return true; 4705 4706 // Verify that the linkage is ok. 4707 switch ((GlobalValue::LinkageTypes)Linkage) { 4708 case GlobalValue::ExternalLinkage: 4709 break; // always ok. 4710 case GlobalValue::ExternalWeakLinkage: 4711 if (isDefine) 4712 return Error(LinkageLoc, "invalid linkage for function definition"); 4713 break; 4714 case GlobalValue::PrivateLinkage: 4715 case GlobalValue::InternalLinkage: 4716 case GlobalValue::AvailableExternallyLinkage: 4717 case GlobalValue::LinkOnceAnyLinkage: 4718 case GlobalValue::LinkOnceODRLinkage: 4719 case GlobalValue::WeakAnyLinkage: 4720 case GlobalValue::WeakODRLinkage: 4721 if (!isDefine) 4722 return Error(LinkageLoc, "invalid linkage for function declaration"); 4723 break; 4724 case GlobalValue::AppendingLinkage: 4725 case GlobalValue::CommonLinkage: 4726 return Error(LinkageLoc, "invalid function linkage type"); 4727 } 4728 4729 if (!isValidVisibilityForLinkage(Visibility, Linkage)) 4730 return Error(LinkageLoc, 4731 "symbol with local linkage must have default visibility"); 4732 4733 if (!FunctionType::isValidReturnType(RetType)) 4734 return Error(RetTypeLoc, "invalid function return type"); 4735 4736 LocTy NameLoc = Lex.getLoc(); 4737 4738 std::string FunctionName; 4739 if (Lex.getKind() == lltok::GlobalVar) { 4740 FunctionName = Lex.getStrVal(); 4741 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok. 4742 unsigned NameID = Lex.getUIntVal(); 4743 4744 if (NameID != NumberedVals.size()) 4745 return TokError("function expected to be numbered '%" + 4746 Twine(NumberedVals.size()) + "'"); 4747 } else { 4748 return TokError("expected function name"); 4749 } 4750 4751 Lex.Lex(); 4752 4753 if (Lex.getKind() != lltok::lparen) 4754 return TokError("expected '(' in function argument list"); 4755 4756 SmallVector<ArgInfo, 8> ArgList; 4757 bool isVarArg; 4758 AttrBuilder FuncAttrs; 4759 std::vector<unsigned> FwdRefAttrGrps; 4760 LocTy BuiltinLoc; 4761 std::string Section; 4762 unsigned Alignment; 4763 std::string GC; 4764 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 4765 LocTy UnnamedAddrLoc; 4766 Constant *Prefix = nullptr; 4767 Constant *Prologue = nullptr; 4768 Constant *PersonalityFn = nullptr; 4769 Comdat *C; 4770 4771 if (ParseArgumentList(ArgList, isVarArg) || 4772 ParseOptionalUnnamedAddr(UnnamedAddr) || 4773 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false, 4774 BuiltinLoc) || 4775 (EatIfPresent(lltok::kw_section) && 4776 ParseStringConstant(Section)) || 4777 parseOptionalComdat(FunctionName, C) || 4778 ParseOptionalAlignment(Alignment) || 4779 (EatIfPresent(lltok::kw_gc) && 4780 ParseStringConstant(GC)) || 4781 (EatIfPresent(lltok::kw_prefix) && 4782 ParseGlobalTypeAndValue(Prefix)) || 4783 (EatIfPresent(lltok::kw_prologue) && 4784 ParseGlobalTypeAndValue(Prologue)) || 4785 (EatIfPresent(lltok::kw_personality) && 4786 ParseGlobalTypeAndValue(PersonalityFn))) 4787 return true; 4788 4789 if (FuncAttrs.contains(Attribute::Builtin)) 4790 return Error(BuiltinLoc, "'builtin' attribute not valid on function"); 4791 4792 // If the alignment was parsed as an attribute, move to the alignment field. 4793 if (FuncAttrs.hasAlignmentAttr()) { 4794 Alignment = FuncAttrs.getAlignment(); 4795 FuncAttrs.removeAttribute(Attribute::Alignment); 4796 } 4797 4798 // Okay, if we got here, the function is syntactically valid. Convert types 4799 // and do semantic checks. 4800 std::vector<Type*> ParamTypeList; 4801 SmallVector<AttributeSet, 8> Attrs; 4802 4803 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 4804 ParamTypeList.push_back(ArgList[i].Ty); 4805 Attrs.push_back(ArgList[i].Attrs); 4806 } 4807 4808 AttributeList PAL = 4809 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs), 4810 AttributeSet::get(Context, RetAttrs), Attrs); 4811 4812 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy()) 4813 return Error(RetTypeLoc, "functions with 'sret' argument must return void"); 4814 4815 FunctionType *FT = 4816 FunctionType::get(RetType, ParamTypeList, isVarArg); 4817 PointerType *PFT = PointerType::getUnqual(FT); 4818 4819 Fn = nullptr; 4820 if (!FunctionName.empty()) { 4821 // If this was a definition of a forward reference, remove the definition 4822 // from the forward reference table and fill in the forward ref. 4823 auto FRVI = ForwardRefVals.find(FunctionName); 4824 if (FRVI != ForwardRefVals.end()) { 4825 Fn = M->getFunction(FunctionName); 4826 if (!Fn) 4827 return Error(FRVI->second.second, "invalid forward reference to " 4828 "function as global value!"); 4829 if (Fn->getType() != PFT) 4830 return Error(FRVI->second.second, "invalid forward reference to " 4831 "function '" + FunctionName + "' with wrong type!"); 4832 4833 ForwardRefVals.erase(FRVI); 4834 } else if ((Fn = M->getFunction(FunctionName))) { 4835 // Reject redefinitions. 4836 return Error(NameLoc, "invalid redefinition of function '" + 4837 FunctionName + "'"); 4838 } else if (M->getNamedValue(FunctionName)) { 4839 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'"); 4840 } 4841 4842 } else { 4843 // If this is a definition of a forward referenced function, make sure the 4844 // types agree. 4845 auto I = ForwardRefValIDs.find(NumberedVals.size()); 4846 if (I != ForwardRefValIDs.end()) { 4847 Fn = cast<Function>(I->second.first); 4848 if (Fn->getType() != PFT) 4849 return Error(NameLoc, "type of definition and forward reference of '@" + 4850 Twine(NumberedVals.size()) + "' disagree"); 4851 ForwardRefValIDs.erase(I); 4852 } 4853 } 4854 4855 if (!Fn) 4856 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M); 4857 else // Move the forward-reference to the correct spot in the module. 4858 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn); 4859 4860 if (FunctionName.empty()) 4861 NumberedVals.push_back(Fn); 4862 4863 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage); 4864 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility); 4865 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 4866 Fn->setCallingConv(CC); 4867 Fn->setAttributes(PAL); 4868 Fn->setUnnamedAddr(UnnamedAddr); 4869 Fn->setAlignment(Alignment); 4870 Fn->setSection(Section); 4871 Fn->setComdat(C); 4872 Fn->setPersonalityFn(PersonalityFn); 4873 if (!GC.empty()) Fn->setGC(GC); 4874 Fn->setPrefixData(Prefix); 4875 Fn->setPrologueData(Prologue); 4876 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps; 4877 4878 // Add all of the arguments we parsed to the function. 4879 Function::arg_iterator ArgIt = Fn->arg_begin(); 4880 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) { 4881 // If the argument has a name, insert it into the argument symbol table. 4882 if (ArgList[i].Name.empty()) continue; 4883 4884 // Set the name, if it conflicted, it will be auto-renamed. 4885 ArgIt->setName(ArgList[i].Name); 4886 4887 if (ArgIt->getName() != ArgList[i].Name) 4888 return Error(ArgList[i].Loc, "redefinition of argument '%" + 4889 ArgList[i].Name + "'"); 4890 } 4891 4892 if (isDefine) 4893 return false; 4894 4895 // Check the declaration has no block address forward references. 4896 ValID ID; 4897 if (FunctionName.empty()) { 4898 ID.Kind = ValID::t_GlobalID; 4899 ID.UIntVal = NumberedVals.size() - 1; 4900 } else { 4901 ID.Kind = ValID::t_GlobalName; 4902 ID.StrVal = FunctionName; 4903 } 4904 auto Blocks = ForwardRefBlockAddresses.find(ID); 4905 if (Blocks != ForwardRefBlockAddresses.end()) 4906 return Error(Blocks->first.Loc, 4907 "cannot take blockaddress inside a declaration"); 4908 return false; 4909 } 4910 4911 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() { 4912 ValID ID; 4913 if (FunctionNumber == -1) { 4914 ID.Kind = ValID::t_GlobalName; 4915 ID.StrVal = F.getName(); 4916 } else { 4917 ID.Kind = ValID::t_GlobalID; 4918 ID.UIntVal = FunctionNumber; 4919 } 4920 4921 auto Blocks = P.ForwardRefBlockAddresses.find(ID); 4922 if (Blocks == P.ForwardRefBlockAddresses.end()) 4923 return false; 4924 4925 for (const auto &I : Blocks->second) { 4926 const ValID &BBID = I.first; 4927 GlobalValue *GV = I.second; 4928 4929 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) && 4930 "Expected local id or name"); 4931 BasicBlock *BB; 4932 if (BBID.Kind == ValID::t_LocalName) 4933 BB = GetBB(BBID.StrVal, BBID.Loc); 4934 else 4935 BB = GetBB(BBID.UIntVal, BBID.Loc); 4936 if (!BB) 4937 return P.Error(BBID.Loc, "referenced value is not a basic block"); 4938 4939 GV->replaceAllUsesWith(BlockAddress::get(&F, BB)); 4940 GV->eraseFromParent(); 4941 } 4942 4943 P.ForwardRefBlockAddresses.erase(Blocks); 4944 return false; 4945 } 4946 4947 /// ParseFunctionBody 4948 /// ::= '{' BasicBlock+ UseListOrderDirective* '}' 4949 bool LLParser::ParseFunctionBody(Function &Fn) { 4950 if (Lex.getKind() != lltok::lbrace) 4951 return TokError("expected '{' in function body"); 4952 Lex.Lex(); // eat the {. 4953 4954 int FunctionNumber = -1; 4955 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1; 4956 4957 PerFunctionState PFS(*this, Fn, FunctionNumber); 4958 4959 // Resolve block addresses and allow basic blocks to be forward-declared 4960 // within this function. 4961 if (PFS.resolveForwardRefBlockAddresses()) 4962 return true; 4963 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS); 4964 4965 // We need at least one basic block. 4966 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder) 4967 return TokError("function body requires at least one basic block"); 4968 4969 while (Lex.getKind() != lltok::rbrace && 4970 Lex.getKind() != lltok::kw_uselistorder) 4971 if (ParseBasicBlock(PFS)) return true; 4972 4973 while (Lex.getKind() != lltok::rbrace) 4974 if (ParseUseListOrder(&PFS)) 4975 return true; 4976 4977 // Eat the }. 4978 Lex.Lex(); 4979 4980 // Verify function is ok. 4981 return PFS.FinishFunction(); 4982 } 4983 4984 /// ParseBasicBlock 4985 /// ::= LabelStr? Instruction* 4986 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) { 4987 // If this basic block starts out with a name, remember it. 4988 std::string Name; 4989 LocTy NameLoc = Lex.getLoc(); 4990 if (Lex.getKind() == lltok::LabelStr) { 4991 Name = Lex.getStrVal(); 4992 Lex.Lex(); 4993 } 4994 4995 BasicBlock *BB = PFS.DefineBB(Name, NameLoc); 4996 if (!BB) 4997 return Error(NameLoc, 4998 "unable to create block named '" + Name + "'"); 4999 5000 std::string NameStr; 5001 5002 // Parse the instructions in this block until we get a terminator. 5003 Instruction *Inst; 5004 do { 5005 // This instruction may have three possibilities for a name: a) none 5006 // specified, b) name specified "%foo =", c) number specified: "%4 =". 5007 LocTy NameLoc = Lex.getLoc(); 5008 int NameID = -1; 5009 NameStr = ""; 5010 5011 if (Lex.getKind() == lltok::LocalVarID) { 5012 NameID = Lex.getUIntVal(); 5013 Lex.Lex(); 5014 if (ParseToken(lltok::equal, "expected '=' after instruction id")) 5015 return true; 5016 } else if (Lex.getKind() == lltok::LocalVar) { 5017 NameStr = Lex.getStrVal(); 5018 Lex.Lex(); 5019 if (ParseToken(lltok::equal, "expected '=' after instruction name")) 5020 return true; 5021 } 5022 5023 switch (ParseInstruction(Inst, BB, PFS)) { 5024 default: llvm_unreachable("Unknown ParseInstruction result!"); 5025 case InstError: return true; 5026 case InstNormal: 5027 BB->getInstList().push_back(Inst); 5028 5029 // With a normal result, we check to see if the instruction is followed by 5030 // a comma and metadata. 5031 if (EatIfPresent(lltok::comma)) 5032 if (ParseInstructionMetadata(*Inst)) 5033 return true; 5034 break; 5035 case InstExtraComma: 5036 BB->getInstList().push_back(Inst); 5037 5038 // If the instruction parser ate an extra comma at the end of it, it 5039 // *must* be followed by metadata. 5040 if (ParseInstructionMetadata(*Inst)) 5041 return true; 5042 break; 5043 } 5044 5045 // Set the name on the instruction. 5046 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true; 5047 } while (!isa<TerminatorInst>(Inst)); 5048 5049 return false; 5050 } 5051 5052 //===----------------------------------------------------------------------===// 5053 // Instruction Parsing. 5054 //===----------------------------------------------------------------------===// 5055 5056 /// ParseInstruction - Parse one of the many different instructions. 5057 /// 5058 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB, 5059 PerFunctionState &PFS) { 5060 lltok::Kind Token = Lex.getKind(); 5061 if (Token == lltok::Eof) 5062 return TokError("found end of file when expecting more instructions"); 5063 LocTy Loc = Lex.getLoc(); 5064 unsigned KeywordVal = Lex.getUIntVal(); 5065 Lex.Lex(); // Eat the keyword. 5066 5067 switch (Token) { 5068 default: return Error(Loc, "expected instruction opcode"); 5069 // Terminator Instructions. 5070 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false; 5071 case lltok::kw_ret: return ParseRet(Inst, BB, PFS); 5072 case lltok::kw_br: return ParseBr(Inst, PFS); 5073 case lltok::kw_switch: return ParseSwitch(Inst, PFS); 5074 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS); 5075 case lltok::kw_invoke: return ParseInvoke(Inst, PFS); 5076 case lltok::kw_resume: return ParseResume(Inst, PFS); 5077 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS); 5078 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS); 5079 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS); 5080 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS); 5081 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS); 5082 // Binary Operators. 5083 case lltok::kw_add: 5084 case lltok::kw_sub: 5085 case lltok::kw_mul: 5086 case lltok::kw_shl: { 5087 bool NUW = EatIfPresent(lltok::kw_nuw); 5088 bool NSW = EatIfPresent(lltok::kw_nsw); 5089 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw); 5090 5091 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true; 5092 5093 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true); 5094 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true); 5095 return false; 5096 } 5097 case lltok::kw_fadd: 5098 case lltok::kw_fsub: 5099 case lltok::kw_fmul: 5100 case lltok::kw_fdiv: 5101 case lltok::kw_frem: { 5102 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5103 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2); 5104 if (Res != 0) 5105 return Res; 5106 if (FMF.any()) 5107 Inst->setFastMathFlags(FMF); 5108 return 0; 5109 } 5110 5111 case lltok::kw_sdiv: 5112 case lltok::kw_udiv: 5113 case lltok::kw_lshr: 5114 case lltok::kw_ashr: { 5115 bool Exact = EatIfPresent(lltok::kw_exact); 5116 5117 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true; 5118 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true); 5119 return false; 5120 } 5121 5122 case lltok::kw_urem: 5123 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1); 5124 case lltok::kw_and: 5125 case lltok::kw_or: 5126 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal); 5127 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal); 5128 case lltok::kw_fcmp: { 5129 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5130 int Res = ParseCompare(Inst, PFS, KeywordVal); 5131 if (Res != 0) 5132 return Res; 5133 if (FMF.any()) 5134 Inst->setFastMathFlags(FMF); 5135 return 0; 5136 } 5137 5138 // Casts. 5139 case lltok::kw_trunc: 5140 case lltok::kw_zext: 5141 case lltok::kw_sext: 5142 case lltok::kw_fptrunc: 5143 case lltok::kw_fpext: 5144 case lltok::kw_bitcast: 5145 case lltok::kw_addrspacecast: 5146 case lltok::kw_uitofp: 5147 case lltok::kw_sitofp: 5148 case lltok::kw_fptoui: 5149 case lltok::kw_fptosi: 5150 case lltok::kw_inttoptr: 5151 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal); 5152 // Other. 5153 case lltok::kw_select: return ParseSelect(Inst, PFS); 5154 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS); 5155 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS); 5156 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS); 5157 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS); 5158 case lltok::kw_phi: return ParsePHI(Inst, PFS); 5159 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS); 5160 // Call. 5161 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None); 5162 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail); 5163 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail); 5164 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail); 5165 // Memory. 5166 case lltok::kw_alloca: return ParseAlloc(Inst, PFS); 5167 case lltok::kw_load: return ParseLoad(Inst, PFS); 5168 case lltok::kw_store: return ParseStore(Inst, PFS); 5169 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS); 5170 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS); 5171 case lltok::kw_fence: return ParseFence(Inst, PFS); 5172 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS); 5173 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS); 5174 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS); 5175 } 5176 } 5177 5178 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind. 5179 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) { 5180 if (Opc == Instruction::FCmp) { 5181 switch (Lex.getKind()) { 5182 default: return TokError("expected fcmp predicate (e.g. 'oeq')"); 5183 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break; 5184 case lltok::kw_one: P = CmpInst::FCMP_ONE; break; 5185 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break; 5186 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break; 5187 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break; 5188 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break; 5189 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break; 5190 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break; 5191 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break; 5192 case lltok::kw_une: P = CmpInst::FCMP_UNE; break; 5193 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break; 5194 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break; 5195 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break; 5196 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break; 5197 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break; 5198 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break; 5199 } 5200 } else { 5201 switch (Lex.getKind()) { 5202 default: return TokError("expected icmp predicate (e.g. 'eq')"); 5203 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break; 5204 case lltok::kw_ne: P = CmpInst::ICMP_NE; break; 5205 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break; 5206 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break; 5207 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break; 5208 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break; 5209 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break; 5210 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break; 5211 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break; 5212 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break; 5213 } 5214 } 5215 Lex.Lex(); 5216 return false; 5217 } 5218 5219 //===----------------------------------------------------------------------===// 5220 // Terminator Instructions. 5221 //===----------------------------------------------------------------------===// 5222 5223 /// ParseRet - Parse a return instruction. 5224 /// ::= 'ret' void (',' !dbg, !1)* 5225 /// ::= 'ret' TypeAndValue (',' !dbg, !1)* 5226 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB, 5227 PerFunctionState &PFS) { 5228 SMLoc TypeLoc = Lex.getLoc(); 5229 Type *Ty = nullptr; 5230 if (ParseType(Ty, true /*void allowed*/)) return true; 5231 5232 Type *ResType = PFS.getFunction().getReturnType(); 5233 5234 if (Ty->isVoidTy()) { 5235 if (!ResType->isVoidTy()) 5236 return Error(TypeLoc, "value doesn't match function result type '" + 5237 getTypeString(ResType) + "'"); 5238 5239 Inst = ReturnInst::Create(Context); 5240 return false; 5241 } 5242 5243 Value *RV; 5244 if (ParseValue(Ty, RV, PFS)) return true; 5245 5246 if (ResType != RV->getType()) 5247 return Error(TypeLoc, "value doesn't match function result type '" + 5248 getTypeString(ResType) + "'"); 5249 5250 Inst = ReturnInst::Create(Context, RV); 5251 return false; 5252 } 5253 5254 /// ParseBr 5255 /// ::= 'br' TypeAndValue 5256 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue 5257 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) { 5258 LocTy Loc, Loc2; 5259 Value *Op0; 5260 BasicBlock *Op1, *Op2; 5261 if (ParseTypeAndValue(Op0, Loc, PFS)) return true; 5262 5263 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) { 5264 Inst = BranchInst::Create(BB); 5265 return false; 5266 } 5267 5268 if (Op0->getType() != Type::getInt1Ty(Context)) 5269 return Error(Loc, "branch condition must have 'i1' type"); 5270 5271 if (ParseToken(lltok::comma, "expected ',' after branch condition") || 5272 ParseTypeAndBasicBlock(Op1, Loc, PFS) || 5273 ParseToken(lltok::comma, "expected ',' after true destination") || 5274 ParseTypeAndBasicBlock(Op2, Loc2, PFS)) 5275 return true; 5276 5277 Inst = BranchInst::Create(Op1, Op2, Op0); 5278 return false; 5279 } 5280 5281 /// ParseSwitch 5282 /// Instruction 5283 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']' 5284 /// JumpTable 5285 /// ::= (TypeAndValue ',' TypeAndValue)* 5286 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) { 5287 LocTy CondLoc, BBLoc; 5288 Value *Cond; 5289 BasicBlock *DefaultBB; 5290 if (ParseTypeAndValue(Cond, CondLoc, PFS) || 5291 ParseToken(lltok::comma, "expected ',' after switch condition") || 5292 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) || 5293 ParseToken(lltok::lsquare, "expected '[' with switch table")) 5294 return true; 5295 5296 if (!Cond->getType()->isIntegerTy()) 5297 return Error(CondLoc, "switch condition must have integer type"); 5298 5299 // Parse the jump table pairs. 5300 SmallPtrSet<Value*, 32> SeenCases; 5301 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table; 5302 while (Lex.getKind() != lltok::rsquare) { 5303 Value *Constant; 5304 BasicBlock *DestBB; 5305 5306 if (ParseTypeAndValue(Constant, CondLoc, PFS) || 5307 ParseToken(lltok::comma, "expected ',' after case value") || 5308 ParseTypeAndBasicBlock(DestBB, PFS)) 5309 return true; 5310 5311 if (!SeenCases.insert(Constant).second) 5312 return Error(CondLoc, "duplicate case value in switch"); 5313 if (!isa<ConstantInt>(Constant)) 5314 return Error(CondLoc, "case value is not a constant integer"); 5315 5316 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB)); 5317 } 5318 5319 Lex.Lex(); // Eat the ']'. 5320 5321 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size()); 5322 for (unsigned i = 0, e = Table.size(); i != e; ++i) 5323 SI->addCase(Table[i].first, Table[i].second); 5324 Inst = SI; 5325 return false; 5326 } 5327 5328 /// ParseIndirectBr 5329 /// Instruction 5330 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']' 5331 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) { 5332 LocTy AddrLoc; 5333 Value *Address; 5334 if (ParseTypeAndValue(Address, AddrLoc, PFS) || 5335 ParseToken(lltok::comma, "expected ',' after indirectbr address") || 5336 ParseToken(lltok::lsquare, "expected '[' with indirectbr")) 5337 return true; 5338 5339 if (!Address->getType()->isPointerTy()) 5340 return Error(AddrLoc, "indirectbr address must have pointer type"); 5341 5342 // Parse the destination list. 5343 SmallVector<BasicBlock*, 16> DestList; 5344 5345 if (Lex.getKind() != lltok::rsquare) { 5346 BasicBlock *DestBB; 5347 if (ParseTypeAndBasicBlock(DestBB, PFS)) 5348 return true; 5349 DestList.push_back(DestBB); 5350 5351 while (EatIfPresent(lltok::comma)) { 5352 if (ParseTypeAndBasicBlock(DestBB, PFS)) 5353 return true; 5354 DestList.push_back(DestBB); 5355 } 5356 } 5357 5358 if (ParseToken(lltok::rsquare, "expected ']' at end of block list")) 5359 return true; 5360 5361 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size()); 5362 for (unsigned i = 0, e = DestList.size(); i != e; ++i) 5363 IBI->addDestination(DestList[i]); 5364 Inst = IBI; 5365 return false; 5366 } 5367 5368 /// ParseInvoke 5369 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList 5370 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue 5371 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) { 5372 LocTy CallLoc = Lex.getLoc(); 5373 AttrBuilder RetAttrs, FnAttrs; 5374 std::vector<unsigned> FwdRefAttrGrps; 5375 LocTy NoBuiltinLoc; 5376 unsigned CC; 5377 Type *RetType = nullptr; 5378 LocTy RetTypeLoc; 5379 ValID CalleeID; 5380 SmallVector<ParamInfo, 16> ArgList; 5381 SmallVector<OperandBundleDef, 2> BundleList; 5382 5383 BasicBlock *NormalBB, *UnwindBB; 5384 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) || 5385 ParseType(RetType, RetTypeLoc, true /*void allowed*/) || 5386 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) || 5387 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 5388 NoBuiltinLoc) || 5389 ParseOptionalOperandBundles(BundleList, PFS) || 5390 ParseToken(lltok::kw_to, "expected 'to' in invoke") || 5391 ParseTypeAndBasicBlock(NormalBB, PFS) || 5392 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") || 5393 ParseTypeAndBasicBlock(UnwindBB, PFS)) 5394 return true; 5395 5396 // If RetType is a non-function pointer type, then this is the short syntax 5397 // for the call, which means that RetType is just the return type. Infer the 5398 // rest of the function argument types from the arguments that are present. 5399 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 5400 if (!Ty) { 5401 // Pull out the types of all of the arguments... 5402 std::vector<Type*> ParamTypes; 5403 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 5404 ParamTypes.push_back(ArgList[i].V->getType()); 5405 5406 if (!FunctionType::isValidReturnType(RetType)) 5407 return Error(RetTypeLoc, "Invalid result type for LLVM function"); 5408 5409 Ty = FunctionType::get(RetType, ParamTypes, false); 5410 } 5411 5412 CalleeID.FTy = Ty; 5413 5414 // Look up the callee. 5415 Value *Callee; 5416 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS)) 5417 return true; 5418 5419 // Set up the Attribute for the function. 5420 SmallVector<Value *, 8> Args; 5421 SmallVector<AttributeSet, 8> ArgAttrs; 5422 5423 // Loop through FunctionType's arguments and ensure they are specified 5424 // correctly. Also, gather any parameter attributes. 5425 FunctionType::param_iterator I = Ty->param_begin(); 5426 FunctionType::param_iterator E = Ty->param_end(); 5427 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 5428 Type *ExpectedTy = nullptr; 5429 if (I != E) { 5430 ExpectedTy = *I++; 5431 } else if (!Ty->isVarArg()) { 5432 return Error(ArgList[i].Loc, "too many arguments specified"); 5433 } 5434 5435 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 5436 return Error(ArgList[i].Loc, "argument is not of expected type '" + 5437 getTypeString(ExpectedTy) + "'"); 5438 Args.push_back(ArgList[i].V); 5439 ArgAttrs.push_back(ArgList[i].Attrs); 5440 } 5441 5442 if (I != E) 5443 return Error(CallLoc, "not enough parameters specified for call"); 5444 5445 if (FnAttrs.hasAlignmentAttr()) 5446 return Error(CallLoc, "invoke instructions may not have an alignment"); 5447 5448 // Finish off the Attribute and check them 5449 AttributeList PAL = 5450 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 5451 AttributeSet::get(Context, RetAttrs), ArgAttrs); 5452 5453 InvokeInst *II = 5454 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList); 5455 II->setCallingConv(CC); 5456 II->setAttributes(PAL); 5457 ForwardRefAttrGroups[II] = FwdRefAttrGrps; 5458 Inst = II; 5459 return false; 5460 } 5461 5462 /// ParseResume 5463 /// ::= 'resume' TypeAndValue 5464 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) { 5465 Value *Exn; LocTy ExnLoc; 5466 if (ParseTypeAndValue(Exn, ExnLoc, PFS)) 5467 return true; 5468 5469 ResumeInst *RI = ResumeInst::Create(Exn); 5470 Inst = RI; 5471 return false; 5472 } 5473 5474 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args, 5475 PerFunctionState &PFS) { 5476 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad")) 5477 return true; 5478 5479 while (Lex.getKind() != lltok::rsquare) { 5480 // If this isn't the first argument, we need a comma. 5481 if (!Args.empty() && 5482 ParseToken(lltok::comma, "expected ',' in argument list")) 5483 return true; 5484 5485 // Parse the argument. 5486 LocTy ArgLoc; 5487 Type *ArgTy = nullptr; 5488 if (ParseType(ArgTy, ArgLoc)) 5489 return true; 5490 5491 Value *V; 5492 if (ArgTy->isMetadataTy()) { 5493 if (ParseMetadataAsValue(V, PFS)) 5494 return true; 5495 } else { 5496 if (ParseValue(ArgTy, V, PFS)) 5497 return true; 5498 } 5499 Args.push_back(V); 5500 } 5501 5502 Lex.Lex(); // Lex the ']'. 5503 return false; 5504 } 5505 5506 /// ParseCleanupRet 5507 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue) 5508 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) { 5509 Value *CleanupPad = nullptr; 5510 5511 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret")) 5512 return true; 5513 5514 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS)) 5515 return true; 5516 5517 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret")) 5518 return true; 5519 5520 BasicBlock *UnwindBB = nullptr; 5521 if (Lex.getKind() == lltok::kw_to) { 5522 Lex.Lex(); 5523 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret")) 5524 return true; 5525 } else { 5526 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) { 5527 return true; 5528 } 5529 } 5530 5531 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB); 5532 return false; 5533 } 5534 5535 /// ParseCatchRet 5536 /// ::= 'catchret' from Parent Value 'to' TypeAndValue 5537 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) { 5538 Value *CatchPad = nullptr; 5539 5540 if (ParseToken(lltok::kw_from, "expected 'from' after catchret")) 5541 return true; 5542 5543 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS)) 5544 return true; 5545 5546 BasicBlock *BB; 5547 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") || 5548 ParseTypeAndBasicBlock(BB, PFS)) 5549 return true; 5550 5551 Inst = CatchReturnInst::Create(CatchPad, BB); 5552 return false; 5553 } 5554 5555 /// ParseCatchSwitch 5556 /// ::= 'catchswitch' within Parent 5557 bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) { 5558 Value *ParentPad; 5559 LocTy BBLoc; 5560 5561 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch")) 5562 return true; 5563 5564 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 5565 Lex.getKind() != lltok::LocalVarID) 5566 return TokError("expected scope value for catchswitch"); 5567 5568 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS)) 5569 return true; 5570 5571 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels")) 5572 return true; 5573 5574 SmallVector<BasicBlock *, 32> Table; 5575 do { 5576 BasicBlock *DestBB; 5577 if (ParseTypeAndBasicBlock(DestBB, PFS)) 5578 return true; 5579 Table.push_back(DestBB); 5580 } while (EatIfPresent(lltok::comma)); 5581 5582 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels")) 5583 return true; 5584 5585 if (ParseToken(lltok::kw_unwind, 5586 "expected 'unwind' after catchswitch scope")) 5587 return true; 5588 5589 BasicBlock *UnwindBB = nullptr; 5590 if (EatIfPresent(lltok::kw_to)) { 5591 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch")) 5592 return true; 5593 } else { 5594 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) 5595 return true; 5596 } 5597 5598 auto *CatchSwitch = 5599 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size()); 5600 for (BasicBlock *DestBB : Table) 5601 CatchSwitch->addHandler(DestBB); 5602 Inst = CatchSwitch; 5603 return false; 5604 } 5605 5606 /// ParseCatchPad 5607 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue 5608 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) { 5609 Value *CatchSwitch = nullptr; 5610 5611 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad")) 5612 return true; 5613 5614 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID) 5615 return TokError("expected scope value for catchpad"); 5616 5617 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS)) 5618 return true; 5619 5620 SmallVector<Value *, 8> Args; 5621 if (ParseExceptionArgs(Args, PFS)) 5622 return true; 5623 5624 Inst = CatchPadInst::Create(CatchSwitch, Args); 5625 return false; 5626 } 5627 5628 /// ParseCleanupPad 5629 /// ::= 'cleanuppad' within Parent ParamList 5630 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) { 5631 Value *ParentPad = nullptr; 5632 5633 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad")) 5634 return true; 5635 5636 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 5637 Lex.getKind() != lltok::LocalVarID) 5638 return TokError("expected scope value for cleanuppad"); 5639 5640 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS)) 5641 return true; 5642 5643 SmallVector<Value *, 8> Args; 5644 if (ParseExceptionArgs(Args, PFS)) 5645 return true; 5646 5647 Inst = CleanupPadInst::Create(ParentPad, Args); 5648 return false; 5649 } 5650 5651 //===----------------------------------------------------------------------===// 5652 // Binary Operators. 5653 //===----------------------------------------------------------------------===// 5654 5655 /// ParseArithmetic 5656 /// ::= ArithmeticOps TypeAndValue ',' Value 5657 /// 5658 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1, 5659 /// then any integer operand is allowed, if it is 2, any fp operand is allowed. 5660 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS, 5661 unsigned Opc, unsigned OperandType) { 5662 LocTy Loc; Value *LHS, *RHS; 5663 if (ParseTypeAndValue(LHS, Loc, PFS) || 5664 ParseToken(lltok::comma, "expected ',' in arithmetic operation") || 5665 ParseValue(LHS->getType(), RHS, PFS)) 5666 return true; 5667 5668 bool Valid; 5669 switch (OperandType) { 5670 default: llvm_unreachable("Unknown operand type!"); 5671 case 0: // int or FP. 5672 Valid = LHS->getType()->isIntOrIntVectorTy() || 5673 LHS->getType()->isFPOrFPVectorTy(); 5674 break; 5675 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break; 5676 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break; 5677 } 5678 5679 if (!Valid) 5680 return Error(Loc, "invalid operand type for instruction"); 5681 5682 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 5683 return false; 5684 } 5685 5686 /// ParseLogical 5687 /// ::= ArithmeticOps TypeAndValue ',' Value { 5688 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS, 5689 unsigned Opc) { 5690 LocTy Loc; Value *LHS, *RHS; 5691 if (ParseTypeAndValue(LHS, Loc, PFS) || 5692 ParseToken(lltok::comma, "expected ',' in logical operation") || 5693 ParseValue(LHS->getType(), RHS, PFS)) 5694 return true; 5695 5696 if (!LHS->getType()->isIntOrIntVectorTy()) 5697 return Error(Loc,"instruction requires integer or integer vector operands"); 5698 5699 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 5700 return false; 5701 } 5702 5703 /// ParseCompare 5704 /// ::= 'icmp' IPredicates TypeAndValue ',' Value 5705 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value 5706 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS, 5707 unsigned Opc) { 5708 // Parse the integer/fp comparison predicate. 5709 LocTy Loc; 5710 unsigned Pred; 5711 Value *LHS, *RHS; 5712 if (ParseCmpPredicate(Pred, Opc) || 5713 ParseTypeAndValue(LHS, Loc, PFS) || 5714 ParseToken(lltok::comma, "expected ',' after compare value") || 5715 ParseValue(LHS->getType(), RHS, PFS)) 5716 return true; 5717 5718 if (Opc == Instruction::FCmp) { 5719 if (!LHS->getType()->isFPOrFPVectorTy()) 5720 return Error(Loc, "fcmp requires floating point operands"); 5721 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS); 5722 } else { 5723 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!"); 5724 if (!LHS->getType()->isIntOrIntVectorTy() && 5725 !LHS->getType()->isPtrOrPtrVectorTy()) 5726 return Error(Loc, "icmp requires integer operands"); 5727 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS); 5728 } 5729 return false; 5730 } 5731 5732 //===----------------------------------------------------------------------===// 5733 // Other Instructions. 5734 //===----------------------------------------------------------------------===// 5735 5736 5737 /// ParseCast 5738 /// ::= CastOpc TypeAndValue 'to' Type 5739 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS, 5740 unsigned Opc) { 5741 LocTy Loc; 5742 Value *Op; 5743 Type *DestTy = nullptr; 5744 if (ParseTypeAndValue(Op, Loc, PFS) || 5745 ParseToken(lltok::kw_to, "expected 'to' after cast value") || 5746 ParseType(DestTy)) 5747 return true; 5748 5749 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) { 5750 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy); 5751 return Error(Loc, "invalid cast opcode for cast from '" + 5752 getTypeString(Op->getType()) + "' to '" + 5753 getTypeString(DestTy) + "'"); 5754 } 5755 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy); 5756 return false; 5757 } 5758 5759 /// ParseSelect 5760 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue 5761 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) { 5762 LocTy Loc; 5763 Value *Op0, *Op1, *Op2; 5764 if (ParseTypeAndValue(Op0, Loc, PFS) || 5765 ParseToken(lltok::comma, "expected ',' after select condition") || 5766 ParseTypeAndValue(Op1, PFS) || 5767 ParseToken(lltok::comma, "expected ',' after select value") || 5768 ParseTypeAndValue(Op2, PFS)) 5769 return true; 5770 5771 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2)) 5772 return Error(Loc, Reason); 5773 5774 Inst = SelectInst::Create(Op0, Op1, Op2); 5775 return false; 5776 } 5777 5778 /// ParseVA_Arg 5779 /// ::= 'va_arg' TypeAndValue ',' Type 5780 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) { 5781 Value *Op; 5782 Type *EltTy = nullptr; 5783 LocTy TypeLoc; 5784 if (ParseTypeAndValue(Op, PFS) || 5785 ParseToken(lltok::comma, "expected ',' after vaarg operand") || 5786 ParseType(EltTy, TypeLoc)) 5787 return true; 5788 5789 if (!EltTy->isFirstClassType()) 5790 return Error(TypeLoc, "va_arg requires operand with first class type"); 5791 5792 Inst = new VAArgInst(Op, EltTy); 5793 return false; 5794 } 5795 5796 /// ParseExtractElement 5797 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue 5798 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) { 5799 LocTy Loc; 5800 Value *Op0, *Op1; 5801 if (ParseTypeAndValue(Op0, Loc, PFS) || 5802 ParseToken(lltok::comma, "expected ',' after extract value") || 5803 ParseTypeAndValue(Op1, PFS)) 5804 return true; 5805 5806 if (!ExtractElementInst::isValidOperands(Op0, Op1)) 5807 return Error(Loc, "invalid extractelement operands"); 5808 5809 Inst = ExtractElementInst::Create(Op0, Op1); 5810 return false; 5811 } 5812 5813 /// ParseInsertElement 5814 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue 5815 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) { 5816 LocTy Loc; 5817 Value *Op0, *Op1, *Op2; 5818 if (ParseTypeAndValue(Op0, Loc, PFS) || 5819 ParseToken(lltok::comma, "expected ',' after insertelement value") || 5820 ParseTypeAndValue(Op1, PFS) || 5821 ParseToken(lltok::comma, "expected ',' after insertelement value") || 5822 ParseTypeAndValue(Op2, PFS)) 5823 return true; 5824 5825 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2)) 5826 return Error(Loc, "invalid insertelement operands"); 5827 5828 Inst = InsertElementInst::Create(Op0, Op1, Op2); 5829 return false; 5830 } 5831 5832 /// ParseShuffleVector 5833 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue 5834 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) { 5835 LocTy Loc; 5836 Value *Op0, *Op1, *Op2; 5837 if (ParseTypeAndValue(Op0, Loc, PFS) || 5838 ParseToken(lltok::comma, "expected ',' after shuffle mask") || 5839 ParseTypeAndValue(Op1, PFS) || 5840 ParseToken(lltok::comma, "expected ',' after shuffle value") || 5841 ParseTypeAndValue(Op2, PFS)) 5842 return true; 5843 5844 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2)) 5845 return Error(Loc, "invalid shufflevector operands"); 5846 5847 Inst = new ShuffleVectorInst(Op0, Op1, Op2); 5848 return false; 5849 } 5850 5851 /// ParsePHI 5852 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')* 5853 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) { 5854 Type *Ty = nullptr; LocTy TypeLoc; 5855 Value *Op0, *Op1; 5856 5857 if (ParseType(Ty, TypeLoc) || 5858 ParseToken(lltok::lsquare, "expected '[' in phi value list") || 5859 ParseValue(Ty, Op0, PFS) || 5860 ParseToken(lltok::comma, "expected ',' after insertelement value") || 5861 ParseValue(Type::getLabelTy(Context), Op1, PFS) || 5862 ParseToken(lltok::rsquare, "expected ']' in phi value list")) 5863 return true; 5864 5865 bool AteExtraComma = false; 5866 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals; 5867 5868 while (true) { 5869 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1))); 5870 5871 if (!EatIfPresent(lltok::comma)) 5872 break; 5873 5874 if (Lex.getKind() == lltok::MetadataVar) { 5875 AteExtraComma = true; 5876 break; 5877 } 5878 5879 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") || 5880 ParseValue(Ty, Op0, PFS) || 5881 ParseToken(lltok::comma, "expected ',' after insertelement value") || 5882 ParseValue(Type::getLabelTy(Context), Op1, PFS) || 5883 ParseToken(lltok::rsquare, "expected ']' in phi value list")) 5884 return true; 5885 } 5886 5887 if (!Ty->isFirstClassType()) 5888 return Error(TypeLoc, "phi node must have first class type"); 5889 5890 PHINode *PN = PHINode::Create(Ty, PHIVals.size()); 5891 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i) 5892 PN->addIncoming(PHIVals[i].first, PHIVals[i].second); 5893 Inst = PN; 5894 return AteExtraComma ? InstExtraComma : InstNormal; 5895 } 5896 5897 /// ParseLandingPad 5898 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+ 5899 /// Clause 5900 /// ::= 'catch' TypeAndValue 5901 /// ::= 'filter' 5902 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )* 5903 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) { 5904 Type *Ty = nullptr; LocTy TyLoc; 5905 5906 if (ParseType(Ty, TyLoc)) 5907 return true; 5908 5909 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0)); 5910 LP->setCleanup(EatIfPresent(lltok::kw_cleanup)); 5911 5912 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){ 5913 LandingPadInst::ClauseType CT; 5914 if (EatIfPresent(lltok::kw_catch)) 5915 CT = LandingPadInst::Catch; 5916 else if (EatIfPresent(lltok::kw_filter)) 5917 CT = LandingPadInst::Filter; 5918 else 5919 return TokError("expected 'catch' or 'filter' clause type"); 5920 5921 Value *V; 5922 LocTy VLoc; 5923 if (ParseTypeAndValue(V, VLoc, PFS)) 5924 return true; 5925 5926 // A 'catch' type expects a non-array constant. A filter clause expects an 5927 // array constant. 5928 if (CT == LandingPadInst::Catch) { 5929 if (isa<ArrayType>(V->getType())) 5930 Error(VLoc, "'catch' clause has an invalid type"); 5931 } else { 5932 if (!isa<ArrayType>(V->getType())) 5933 Error(VLoc, "'filter' clause has an invalid type"); 5934 } 5935 5936 Constant *CV = dyn_cast<Constant>(V); 5937 if (!CV) 5938 return Error(VLoc, "clause argument must be a constant"); 5939 LP->addClause(CV); 5940 } 5941 5942 Inst = LP.release(); 5943 return false; 5944 } 5945 5946 /// ParseCall 5947 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv 5948 /// OptionalAttrs Type Value ParameterList OptionalAttrs 5949 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv 5950 /// OptionalAttrs Type Value ParameterList OptionalAttrs 5951 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv 5952 /// OptionalAttrs Type Value ParameterList OptionalAttrs 5953 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv 5954 /// OptionalAttrs Type Value ParameterList OptionalAttrs 5955 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS, 5956 CallInst::TailCallKind TCK) { 5957 AttrBuilder RetAttrs, FnAttrs; 5958 std::vector<unsigned> FwdRefAttrGrps; 5959 LocTy BuiltinLoc; 5960 unsigned CC; 5961 Type *RetType = nullptr; 5962 LocTy RetTypeLoc; 5963 ValID CalleeID; 5964 SmallVector<ParamInfo, 16> ArgList; 5965 SmallVector<OperandBundleDef, 2> BundleList; 5966 LocTy CallLoc = Lex.getLoc(); 5967 5968 if (TCK != CallInst::TCK_None && 5969 ParseToken(lltok::kw_call, 5970 "expected 'tail call', 'musttail call', or 'notail call'")) 5971 return true; 5972 5973 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5974 5975 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) || 5976 ParseType(RetType, RetTypeLoc, true /*void allowed*/) || 5977 ParseValID(CalleeID) || 5978 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail, 5979 PFS.getFunction().isVarArg()) || 5980 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) || 5981 ParseOptionalOperandBundles(BundleList, PFS)) 5982 return true; 5983 5984 if (FMF.any() && !RetType->isFPOrFPVectorTy()) 5985 return Error(CallLoc, "fast-math-flags specified for call without " 5986 "floating-point scalar or vector return type"); 5987 5988 // If RetType is a non-function pointer type, then this is the short syntax 5989 // for the call, which means that RetType is just the return type. Infer the 5990 // rest of the function argument types from the arguments that are present. 5991 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 5992 if (!Ty) { 5993 // Pull out the types of all of the arguments... 5994 std::vector<Type*> ParamTypes; 5995 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 5996 ParamTypes.push_back(ArgList[i].V->getType()); 5997 5998 if (!FunctionType::isValidReturnType(RetType)) 5999 return Error(RetTypeLoc, "Invalid result type for LLVM function"); 6000 6001 Ty = FunctionType::get(RetType, ParamTypes, false); 6002 } 6003 6004 CalleeID.FTy = Ty; 6005 6006 // Look up the callee. 6007 Value *Callee; 6008 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS)) 6009 return true; 6010 6011 // Set up the Attribute for the function. 6012 SmallVector<AttributeSet, 8> Attrs; 6013 6014 SmallVector<Value*, 8> Args; 6015 6016 // Loop through FunctionType's arguments and ensure they are specified 6017 // correctly. Also, gather any parameter attributes. 6018 FunctionType::param_iterator I = Ty->param_begin(); 6019 FunctionType::param_iterator E = Ty->param_end(); 6020 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 6021 Type *ExpectedTy = nullptr; 6022 if (I != E) { 6023 ExpectedTy = *I++; 6024 } else if (!Ty->isVarArg()) { 6025 return Error(ArgList[i].Loc, "too many arguments specified"); 6026 } 6027 6028 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 6029 return Error(ArgList[i].Loc, "argument is not of expected type '" + 6030 getTypeString(ExpectedTy) + "'"); 6031 Args.push_back(ArgList[i].V); 6032 Attrs.push_back(ArgList[i].Attrs); 6033 } 6034 6035 if (I != E) 6036 return Error(CallLoc, "not enough parameters specified for call"); 6037 6038 if (FnAttrs.hasAlignmentAttr()) 6039 return Error(CallLoc, "call instructions may not have an alignment"); 6040 6041 // Finish off the Attribute and check them 6042 AttributeList PAL = 6043 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 6044 AttributeSet::get(Context, RetAttrs), Attrs); 6045 6046 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList); 6047 CI->setTailCallKind(TCK); 6048 CI->setCallingConv(CC); 6049 if (FMF.any()) 6050 CI->setFastMathFlags(FMF); 6051 CI->setAttributes(PAL); 6052 ForwardRefAttrGroups[CI] = FwdRefAttrGrps; 6053 Inst = CI; 6054 return false; 6055 } 6056 6057 //===----------------------------------------------------------------------===// 6058 // Memory Instructions. 6059 //===----------------------------------------------------------------------===// 6060 6061 /// ParseAlloc 6062 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)? 6063 /// (',' 'align' i32)? 6064 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) { 6065 Value *Size = nullptr; 6066 LocTy SizeLoc, TyLoc, ASLoc; 6067 unsigned Alignment = 0; 6068 unsigned AddrSpace = 0; 6069 Type *Ty = nullptr; 6070 6071 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca); 6072 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror); 6073 6074 if (ParseType(Ty, TyLoc)) return true; 6075 6076 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty)) 6077 return Error(TyLoc, "invalid type for alloca"); 6078 6079 bool AteExtraComma = false; 6080 if (EatIfPresent(lltok::comma)) { 6081 if (Lex.getKind() == lltok::kw_align) { 6082 if (ParseOptionalAlignment(Alignment)) 6083 return true; 6084 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)) 6085 return true; 6086 } else if (Lex.getKind() == lltok::kw_addrspace) { 6087 ASLoc = Lex.getLoc(); 6088 if (ParseOptionalAddrSpace(AddrSpace)) 6089 return true; 6090 } else if (Lex.getKind() == lltok::MetadataVar) { 6091 AteExtraComma = true; 6092 } else { 6093 if (ParseTypeAndValue(Size, SizeLoc, PFS) || 6094 ParseOptionalCommaAlign(Alignment, AteExtraComma) || 6095 (!AteExtraComma && 6096 ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))) 6097 return true; 6098 } 6099 } 6100 6101 if (Size && !Size->getType()->isIntegerTy()) 6102 return Error(SizeLoc, "element count must have integer type"); 6103 6104 const DataLayout &DL = M->getDataLayout(); 6105 unsigned AS = DL.getAllocaAddrSpace(); 6106 if (AS != AddrSpace) { 6107 // TODO: In the future it should be possible to specify addrspace per-alloca. 6108 return Error(ASLoc, "address space must match datalayout"); 6109 } 6110 6111 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Alignment); 6112 AI->setUsedWithInAlloca(IsInAlloca); 6113 AI->setSwiftError(IsSwiftError); 6114 Inst = AI; 6115 return AteExtraComma ? InstExtraComma : InstNormal; 6116 } 6117 6118 /// ParseLoad 6119 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)? 6120 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue 6121 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 6122 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) { 6123 Value *Val; LocTy Loc; 6124 unsigned Alignment = 0; 6125 bool AteExtraComma = false; 6126 bool isAtomic = false; 6127 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 6128 SyncScope::ID SSID = SyncScope::System; 6129 6130 if (Lex.getKind() == lltok::kw_atomic) { 6131 isAtomic = true; 6132 Lex.Lex(); 6133 } 6134 6135 bool isVolatile = false; 6136 if (Lex.getKind() == lltok::kw_volatile) { 6137 isVolatile = true; 6138 Lex.Lex(); 6139 } 6140 6141 Type *Ty; 6142 LocTy ExplicitTypeLoc = Lex.getLoc(); 6143 if (ParseType(Ty) || 6144 ParseToken(lltok::comma, "expected comma after load's type") || 6145 ParseTypeAndValue(Val, Loc, PFS) || 6146 ParseScopeAndOrdering(isAtomic, SSID, Ordering) || 6147 ParseOptionalCommaAlign(Alignment, AteExtraComma)) 6148 return true; 6149 6150 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType()) 6151 return Error(Loc, "load operand must be a pointer to a first class type"); 6152 if (isAtomic && !Alignment) 6153 return Error(Loc, "atomic load must have explicit non-zero alignment"); 6154 if (Ordering == AtomicOrdering::Release || 6155 Ordering == AtomicOrdering::AcquireRelease) 6156 return Error(Loc, "atomic load cannot use Release ordering"); 6157 6158 if (Ty != cast<PointerType>(Val->getType())->getElementType()) 6159 return Error(ExplicitTypeLoc, 6160 "explicit pointee type doesn't match operand's pointee type"); 6161 6162 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID); 6163 return AteExtraComma ? InstExtraComma : InstNormal; 6164 } 6165 6166 /// ParseStore 6167 6168 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)? 6169 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue 6170 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 6171 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) { 6172 Value *Val, *Ptr; LocTy Loc, PtrLoc; 6173 unsigned Alignment = 0; 6174 bool AteExtraComma = false; 6175 bool isAtomic = false; 6176 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 6177 SyncScope::ID SSID = SyncScope::System; 6178 6179 if (Lex.getKind() == lltok::kw_atomic) { 6180 isAtomic = true; 6181 Lex.Lex(); 6182 } 6183 6184 bool isVolatile = false; 6185 if (Lex.getKind() == lltok::kw_volatile) { 6186 isVolatile = true; 6187 Lex.Lex(); 6188 } 6189 6190 if (ParseTypeAndValue(Val, Loc, PFS) || 6191 ParseToken(lltok::comma, "expected ',' after store operand") || 6192 ParseTypeAndValue(Ptr, PtrLoc, PFS) || 6193 ParseScopeAndOrdering(isAtomic, SSID, Ordering) || 6194 ParseOptionalCommaAlign(Alignment, AteExtraComma)) 6195 return true; 6196 6197 if (!Ptr->getType()->isPointerTy()) 6198 return Error(PtrLoc, "store operand must be a pointer"); 6199 if (!Val->getType()->isFirstClassType()) 6200 return Error(Loc, "store operand must be a first class value"); 6201 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType()) 6202 return Error(Loc, "stored value and pointer type do not match"); 6203 if (isAtomic && !Alignment) 6204 return Error(Loc, "atomic store must have explicit non-zero alignment"); 6205 if (Ordering == AtomicOrdering::Acquire || 6206 Ordering == AtomicOrdering::AcquireRelease) 6207 return Error(Loc, "atomic store cannot use Acquire ordering"); 6208 6209 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID); 6210 return AteExtraComma ? InstExtraComma : InstNormal; 6211 } 6212 6213 /// ParseCmpXchg 6214 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ',' 6215 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering 6216 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) { 6217 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc; 6218 bool AteExtraComma = false; 6219 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic; 6220 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic; 6221 SyncScope::ID SSID = SyncScope::System; 6222 bool isVolatile = false; 6223 bool isWeak = false; 6224 6225 if (EatIfPresent(lltok::kw_weak)) 6226 isWeak = true; 6227 6228 if (EatIfPresent(lltok::kw_volatile)) 6229 isVolatile = true; 6230 6231 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) || 6232 ParseToken(lltok::comma, "expected ',' after cmpxchg address") || 6233 ParseTypeAndValue(Cmp, CmpLoc, PFS) || 6234 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") || 6235 ParseTypeAndValue(New, NewLoc, PFS) || 6236 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) || 6237 ParseOrdering(FailureOrdering)) 6238 return true; 6239 6240 if (SuccessOrdering == AtomicOrdering::Unordered || 6241 FailureOrdering == AtomicOrdering::Unordered) 6242 return TokError("cmpxchg cannot be unordered"); 6243 if (isStrongerThan(FailureOrdering, SuccessOrdering)) 6244 return TokError("cmpxchg failure argument shall be no stronger than the " 6245 "success argument"); 6246 if (FailureOrdering == AtomicOrdering::Release || 6247 FailureOrdering == AtomicOrdering::AcquireRelease) 6248 return TokError( 6249 "cmpxchg failure ordering cannot include release semantics"); 6250 if (!Ptr->getType()->isPointerTy()) 6251 return Error(PtrLoc, "cmpxchg operand must be a pointer"); 6252 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType()) 6253 return Error(CmpLoc, "compare value and pointer type do not match"); 6254 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType()) 6255 return Error(NewLoc, "new value and pointer type do not match"); 6256 if (!New->getType()->isFirstClassType()) 6257 return Error(NewLoc, "cmpxchg operand must be a first class value"); 6258 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst( 6259 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID); 6260 CXI->setVolatile(isVolatile); 6261 CXI->setWeak(isWeak); 6262 Inst = CXI; 6263 return AteExtraComma ? InstExtraComma : InstNormal; 6264 } 6265 6266 /// ParseAtomicRMW 6267 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue 6268 /// 'singlethread'? AtomicOrdering 6269 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) { 6270 Value *Ptr, *Val; LocTy PtrLoc, ValLoc; 6271 bool AteExtraComma = false; 6272 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 6273 SyncScope::ID SSID = SyncScope::System; 6274 bool isVolatile = false; 6275 AtomicRMWInst::BinOp Operation; 6276 6277 if (EatIfPresent(lltok::kw_volatile)) 6278 isVolatile = true; 6279 6280 switch (Lex.getKind()) { 6281 default: return TokError("expected binary operation in atomicrmw"); 6282 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break; 6283 case lltok::kw_add: Operation = AtomicRMWInst::Add; break; 6284 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break; 6285 case lltok::kw_and: Operation = AtomicRMWInst::And; break; 6286 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break; 6287 case lltok::kw_or: Operation = AtomicRMWInst::Or; break; 6288 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break; 6289 case lltok::kw_max: Operation = AtomicRMWInst::Max; break; 6290 case lltok::kw_min: Operation = AtomicRMWInst::Min; break; 6291 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break; 6292 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break; 6293 } 6294 Lex.Lex(); // Eat the operation. 6295 6296 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) || 6297 ParseToken(lltok::comma, "expected ',' after atomicrmw address") || 6298 ParseTypeAndValue(Val, ValLoc, PFS) || 6299 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering)) 6300 return true; 6301 6302 if (Ordering == AtomicOrdering::Unordered) 6303 return TokError("atomicrmw cannot be unordered"); 6304 if (!Ptr->getType()->isPointerTy()) 6305 return Error(PtrLoc, "atomicrmw operand must be a pointer"); 6306 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType()) 6307 return Error(ValLoc, "atomicrmw value and pointer type do not match"); 6308 if (!Val->getType()->isIntegerTy()) 6309 return Error(ValLoc, "atomicrmw operand must be an integer"); 6310 unsigned Size = Val->getType()->getPrimitiveSizeInBits(); 6311 if (Size < 8 || (Size & (Size - 1))) 6312 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized" 6313 " integer"); 6314 6315 AtomicRMWInst *RMWI = 6316 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID); 6317 RMWI->setVolatile(isVolatile); 6318 Inst = RMWI; 6319 return AteExtraComma ? InstExtraComma : InstNormal; 6320 } 6321 6322 /// ParseFence 6323 /// ::= 'fence' 'singlethread'? AtomicOrdering 6324 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) { 6325 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 6326 SyncScope::ID SSID = SyncScope::System; 6327 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering)) 6328 return true; 6329 6330 if (Ordering == AtomicOrdering::Unordered) 6331 return TokError("fence cannot be unordered"); 6332 if (Ordering == AtomicOrdering::Monotonic) 6333 return TokError("fence cannot be monotonic"); 6334 6335 Inst = new FenceInst(Context, Ordering, SSID); 6336 return InstNormal; 6337 } 6338 6339 /// ParseGetElementPtr 6340 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)* 6341 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { 6342 Value *Ptr = nullptr; 6343 Value *Val = nullptr; 6344 LocTy Loc, EltLoc; 6345 6346 bool InBounds = EatIfPresent(lltok::kw_inbounds); 6347 6348 Type *Ty = nullptr; 6349 LocTy ExplicitTypeLoc = Lex.getLoc(); 6350 if (ParseType(Ty) || 6351 ParseToken(lltok::comma, "expected comma after getelementptr's type") || 6352 ParseTypeAndValue(Ptr, Loc, PFS)) 6353 return true; 6354 6355 Type *BaseType = Ptr->getType(); 6356 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType()); 6357 if (!BasePointerType) 6358 return Error(Loc, "base of getelementptr must be a pointer"); 6359 6360 if (Ty != BasePointerType->getElementType()) 6361 return Error(ExplicitTypeLoc, 6362 "explicit pointee type doesn't match operand's pointee type"); 6363 6364 SmallVector<Value*, 16> Indices; 6365 bool AteExtraComma = false; 6366 // GEP returns a vector of pointers if at least one of parameters is a vector. 6367 // All vector parameters should have the same vector width. 6368 unsigned GEPWidth = BaseType->isVectorTy() ? 6369 BaseType->getVectorNumElements() : 0; 6370 6371 while (EatIfPresent(lltok::comma)) { 6372 if (Lex.getKind() == lltok::MetadataVar) { 6373 AteExtraComma = true; 6374 break; 6375 } 6376 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true; 6377 if (!Val->getType()->isIntOrIntVectorTy()) 6378 return Error(EltLoc, "getelementptr index must be an integer"); 6379 6380 if (Val->getType()->isVectorTy()) { 6381 unsigned ValNumEl = Val->getType()->getVectorNumElements(); 6382 if (GEPWidth && GEPWidth != ValNumEl) 6383 return Error(EltLoc, 6384 "getelementptr vector index has a wrong number of elements"); 6385 GEPWidth = ValNumEl; 6386 } 6387 Indices.push_back(Val); 6388 } 6389 6390 SmallPtrSet<Type*, 4> Visited; 6391 if (!Indices.empty() && !Ty->isSized(&Visited)) 6392 return Error(Loc, "base element of getelementptr must be sized"); 6393 6394 if (!GetElementPtrInst::getIndexedType(Ty, Indices)) 6395 return Error(Loc, "invalid getelementptr indices"); 6396 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices); 6397 if (InBounds) 6398 cast<GetElementPtrInst>(Inst)->setIsInBounds(true); 6399 return AteExtraComma ? InstExtraComma : InstNormal; 6400 } 6401 6402 /// ParseExtractValue 6403 /// ::= 'extractvalue' TypeAndValue (',' uint32)+ 6404 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) { 6405 Value *Val; LocTy Loc; 6406 SmallVector<unsigned, 4> Indices; 6407 bool AteExtraComma; 6408 if (ParseTypeAndValue(Val, Loc, PFS) || 6409 ParseIndexList(Indices, AteExtraComma)) 6410 return true; 6411 6412 if (!Val->getType()->isAggregateType()) 6413 return Error(Loc, "extractvalue operand must be aggregate type"); 6414 6415 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 6416 return Error(Loc, "invalid indices for extractvalue"); 6417 Inst = ExtractValueInst::Create(Val, Indices); 6418 return AteExtraComma ? InstExtraComma : InstNormal; 6419 } 6420 6421 /// ParseInsertValue 6422 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+ 6423 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { 6424 Value *Val0, *Val1; LocTy Loc0, Loc1; 6425 SmallVector<unsigned, 4> Indices; 6426 bool AteExtraComma; 6427 if (ParseTypeAndValue(Val0, Loc0, PFS) || 6428 ParseToken(lltok::comma, "expected comma after insertvalue operand") || 6429 ParseTypeAndValue(Val1, Loc1, PFS) || 6430 ParseIndexList(Indices, AteExtraComma)) 6431 return true; 6432 6433 if (!Val0->getType()->isAggregateType()) 6434 return Error(Loc0, "insertvalue operand must be aggregate type"); 6435 6436 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices); 6437 if (!IndexedType) 6438 return Error(Loc0, "invalid indices for insertvalue"); 6439 if (IndexedType != Val1->getType()) 6440 return Error(Loc1, "insertvalue operand and field disagree in type: '" + 6441 getTypeString(Val1->getType()) + "' instead of '" + 6442 getTypeString(IndexedType) + "'"); 6443 Inst = InsertValueInst::Create(Val0, Val1, Indices); 6444 return AteExtraComma ? InstExtraComma : InstNormal; 6445 } 6446 6447 //===----------------------------------------------------------------------===// 6448 // Embedded metadata. 6449 //===----------------------------------------------------------------------===// 6450 6451 /// ParseMDNodeVector 6452 /// ::= { Element (',' Element)* } 6453 /// Element 6454 /// ::= 'null' | TypeAndValue 6455 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) { 6456 if (ParseToken(lltok::lbrace, "expected '{' here")) 6457 return true; 6458 6459 // Check for an empty list. 6460 if (EatIfPresent(lltok::rbrace)) 6461 return false; 6462 6463 do { 6464 // Null is a special case since it is typeless. 6465 if (EatIfPresent(lltok::kw_null)) { 6466 Elts.push_back(nullptr); 6467 continue; 6468 } 6469 6470 Metadata *MD; 6471 if (ParseMetadata(MD, nullptr)) 6472 return true; 6473 Elts.push_back(MD); 6474 } while (EatIfPresent(lltok::comma)); 6475 6476 return ParseToken(lltok::rbrace, "expected end of metadata node"); 6477 } 6478 6479 //===----------------------------------------------------------------------===// 6480 // Use-list order directives. 6481 //===----------------------------------------------------------------------===// 6482 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, 6483 SMLoc Loc) { 6484 if (V->use_empty()) 6485 return Error(Loc, "value has no uses"); 6486 6487 unsigned NumUses = 0; 6488 SmallDenseMap<const Use *, unsigned, 16> Order; 6489 for (const Use &U : V->uses()) { 6490 if (++NumUses > Indexes.size()) 6491 break; 6492 Order[&U] = Indexes[NumUses - 1]; 6493 } 6494 if (NumUses < 2) 6495 return Error(Loc, "value only has one use"); 6496 if (Order.size() != Indexes.size() || NumUses > Indexes.size()) 6497 return Error(Loc, "wrong number of indexes, expected " + 6498 Twine(std::distance(V->use_begin(), V->use_end()))); 6499 6500 V->sortUseList([&](const Use &L, const Use &R) { 6501 return Order.lookup(&L) < Order.lookup(&R); 6502 }); 6503 return false; 6504 } 6505 6506 /// ParseUseListOrderIndexes 6507 /// ::= '{' uint32 (',' uint32)+ '}' 6508 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) { 6509 SMLoc Loc = Lex.getLoc(); 6510 if (ParseToken(lltok::lbrace, "expected '{' here")) 6511 return true; 6512 if (Lex.getKind() == lltok::rbrace) 6513 return Lex.Error("expected non-empty list of uselistorder indexes"); 6514 6515 // Use Offset, Max, and IsOrdered to check consistency of indexes. The 6516 // indexes should be distinct numbers in the range [0, size-1], and should 6517 // not be in order. 6518 unsigned Offset = 0; 6519 unsigned Max = 0; 6520 bool IsOrdered = true; 6521 assert(Indexes.empty() && "Expected empty order vector"); 6522 do { 6523 unsigned Index; 6524 if (ParseUInt32(Index)) 6525 return true; 6526 6527 // Update consistency checks. 6528 Offset += Index - Indexes.size(); 6529 Max = std::max(Max, Index); 6530 IsOrdered &= Index == Indexes.size(); 6531 6532 Indexes.push_back(Index); 6533 } while (EatIfPresent(lltok::comma)); 6534 6535 if (ParseToken(lltok::rbrace, "expected '}' here")) 6536 return true; 6537 6538 if (Indexes.size() < 2) 6539 return Error(Loc, "expected >= 2 uselistorder indexes"); 6540 if (Offset != 0 || Max >= Indexes.size()) 6541 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)"); 6542 if (IsOrdered) 6543 return Error(Loc, "expected uselistorder indexes to change the order"); 6544 6545 return false; 6546 } 6547 6548 /// ParseUseListOrder 6549 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes 6550 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) { 6551 SMLoc Loc = Lex.getLoc(); 6552 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive")) 6553 return true; 6554 6555 Value *V; 6556 SmallVector<unsigned, 16> Indexes; 6557 if (ParseTypeAndValue(V, PFS) || 6558 ParseToken(lltok::comma, "expected comma in uselistorder directive") || 6559 ParseUseListOrderIndexes(Indexes)) 6560 return true; 6561 6562 return sortUseListOrder(V, Indexes, Loc); 6563 } 6564 6565 /// ParseUseListOrderBB 6566 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes 6567 bool LLParser::ParseUseListOrderBB() { 6568 assert(Lex.getKind() == lltok::kw_uselistorder_bb); 6569 SMLoc Loc = Lex.getLoc(); 6570 Lex.Lex(); 6571 6572 ValID Fn, Label; 6573 SmallVector<unsigned, 16> Indexes; 6574 if (ParseValID(Fn) || 6575 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 6576 ParseValID(Label) || 6577 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 6578 ParseUseListOrderIndexes(Indexes)) 6579 return true; 6580 6581 // Check the function. 6582 GlobalValue *GV; 6583 if (Fn.Kind == ValID::t_GlobalName) 6584 GV = M->getNamedValue(Fn.StrVal); 6585 else if (Fn.Kind == ValID::t_GlobalID) 6586 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr; 6587 else 6588 return Error(Fn.Loc, "expected function name in uselistorder_bb"); 6589 if (!GV) 6590 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb"); 6591 auto *F = dyn_cast<Function>(GV); 6592 if (!F) 6593 return Error(Fn.Loc, "expected function name in uselistorder_bb"); 6594 if (F->isDeclaration()) 6595 return Error(Fn.Loc, "invalid declaration in uselistorder_bb"); 6596 6597 // Check the basic block. 6598 if (Label.Kind == ValID::t_LocalID) 6599 return Error(Label.Loc, "invalid numeric label in uselistorder_bb"); 6600 if (Label.Kind != ValID::t_LocalName) 6601 return Error(Label.Loc, "expected basic block name in uselistorder_bb"); 6602 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal); 6603 if (!V) 6604 return Error(Label.Loc, "invalid basic block in uselistorder_bb"); 6605 if (!isa<BasicBlock>(V)) 6606 return Error(Label.Loc, "expected basic block in uselistorder_bb"); 6607 6608 return sortUseListOrder(V, Indexes, Loc); 6609 } 6610