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