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