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