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