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