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