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