AsmMatcherEmitter.cpp revision ec6f096c36f4144ff9b3b24c2939720cdcbb7bcc
1//===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===// 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 tablegen backend emits a target specifier matcher for converting parsed 11// assembly operands in the MCInst structures. 12// 13// The input to the target specific matcher is a list of literal tokens and 14// operands. The target specific parser should generally eliminate any syntax 15// which is not relevant for matching; for example, comma tokens should have 16// already been consumed and eliminated by the parser. Most instructions will 17// end up with a single literal token (the instruction name) and some number of 18// operands. 19// 20// Some example inputs, for X86: 21// 'addl' (immediate ...) (register ...) 22// 'add' (immediate ...) (memory ...) 23// 'call' '*' %epc 24// 25// The assembly matcher is responsible for converting this input into a precise 26// machine instruction (i.e., an instruction with a well defined encoding). This 27// mapping has several properties which complicate matching: 28// 29// - It may be ambiguous; many architectures can legally encode particular 30// variants of an instruction in different ways (for example, using a smaller 31// encoding for small immediates). Such ambiguities should never be 32// arbitrarily resolved by the assembler, the assembler is always responsible 33// for choosing the "best" available instruction. 34// 35// - It may depend on the subtarget or the assembler context. Instructions 36// which are invalid for the current mode, but otherwise unambiguous (e.g., 37// an SSE instruction in a file being assembled for i486) should be accepted 38// and rejected by the assembler front end. However, if the proper encoding 39// for an instruction is dependent on the assembler context then the matcher 40// is responsible for selecting the correct machine instruction for the 41// current mode. 42// 43// The core matching algorithm attempts to exploit the regularity in most 44// instruction sets to quickly determine the set of possibly matching 45// instructions, and the simplify the generated code. Additionally, this helps 46// to ensure that the ambiguities are intentionally resolved by the user. 47// 48// The matching is divided into two distinct phases: 49// 50// 1. Classification: Each operand is mapped to the unique set which (a) 51// contains it, and (b) is the largest such subset for which a single 52// instruction could match all members. 53// 54// For register classes, we can generate these subgroups automatically. For 55// arbitrary operands, we expect the user to define the classes and their 56// relations to one another (for example, 8-bit signed immediates as a 57// subset of 32-bit immediates). 58// 59// By partitioning the operands in this way, we guarantee that for any 60// tuple of classes, any single instruction must match either all or none 61// of the sets of operands which could classify to that tuple. 62// 63// In addition, the subset relation amongst classes induces a partial order 64// on such tuples, which we use to resolve ambiguities. 65// 66// FIXME: What do we do if a crazy case shows up where this is the wrong 67// resolution? 68// 69// 2. The input can now be treated as a tuple of classes (static tokens are 70// simple singleton sets). Each such tuple should generally map to a single 71// instruction (we currently ignore cases where this isn't true, whee!!!), 72// which we can emit a simple matcher for. 73// 74//===----------------------------------------------------------------------===// 75 76#include "AsmMatcherEmitter.h" 77#include "CodeGenTarget.h" 78#include "Record.h" 79#include "StringMatcher.h" 80#include "llvm/ADT/OwningPtr.h" 81#include "llvm/ADT/SmallPtrSet.h" 82#include "llvm/ADT/SmallVector.h" 83#include "llvm/ADT/STLExtras.h" 84#include "llvm/ADT/StringExtras.h" 85#include "llvm/Support/CommandLine.h" 86#include "llvm/Support/Debug.h" 87#include <list> 88#include <map> 89#include <set> 90using namespace llvm; 91 92static cl::opt<std::string> 93MatchPrefix("match-prefix", cl::init(""), 94 cl::desc("Only match instructions with the given prefix")); 95 96 97namespace { 98 class AsmMatcherInfo; 99struct SubtargetFeatureInfo; 100 101/// ClassInfo - Helper class for storing the information about a particular 102/// class of operands which can be matched. 103struct ClassInfo { 104 enum ClassInfoKind { 105 /// Invalid kind, for use as a sentinel value. 106 Invalid = 0, 107 108 /// The class for a particular token. 109 Token, 110 111 /// The (first) register class, subsequent register classes are 112 /// RegisterClass0+1, and so on. 113 RegisterClass0, 114 115 /// The (first) user defined class, subsequent user defined classes are 116 /// UserClass0+1, and so on. 117 UserClass0 = 1<<16 118 }; 119 120 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 + 121 /// N) for the Nth user defined class. 122 unsigned Kind; 123 124 /// SuperClasses - The super classes of this class. Note that for simplicities 125 /// sake user operands only record their immediate super class, while register 126 /// operands include all superclasses. 127 std::vector<ClassInfo*> SuperClasses; 128 129 /// Name - The full class name, suitable for use in an enum. 130 std::string Name; 131 132 /// ClassName - The unadorned generic name for this class (e.g., Token). 133 std::string ClassName; 134 135 /// ValueName - The name of the value this class represents; for a token this 136 /// is the literal token string, for an operand it is the TableGen class (or 137 /// empty if this is a derived class). 138 std::string ValueName; 139 140 /// PredicateMethod - The name of the operand method to test whether the 141 /// operand matches this class; this is not valid for Token or register kinds. 142 std::string PredicateMethod; 143 144 /// RenderMethod - The name of the operand method to add this operand to an 145 /// MCInst; this is not valid for Token or register kinds. 146 std::string RenderMethod; 147 148 /// For register classes, the records for all the registers in this class. 149 std::set<Record*> Registers; 150 151public: 152 /// isRegisterClass() - Check if this is a register class. 153 bool isRegisterClass() const { 154 return Kind >= RegisterClass0 && Kind < UserClass0; 155 } 156 157 /// isUserClass() - Check if this is a user defined class. 158 bool isUserClass() const { 159 return Kind >= UserClass0; 160 } 161 162 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes 163 /// are related if they are in the same class hierarchy. 164 bool isRelatedTo(const ClassInfo &RHS) const { 165 // Tokens are only related to tokens. 166 if (Kind == Token || RHS.Kind == Token) 167 return Kind == Token && RHS.Kind == Token; 168 169 // Registers classes are only related to registers classes, and only if 170 // their intersection is non-empty. 171 if (isRegisterClass() || RHS.isRegisterClass()) { 172 if (!isRegisterClass() || !RHS.isRegisterClass()) 173 return false; 174 175 std::set<Record*> Tmp; 176 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin()); 177 std::set_intersection(Registers.begin(), Registers.end(), 178 RHS.Registers.begin(), RHS.Registers.end(), 179 II); 180 181 return !Tmp.empty(); 182 } 183 184 // Otherwise we have two users operands; they are related if they are in the 185 // same class hierarchy. 186 // 187 // FIXME: This is an oversimplification, they should only be related if they 188 // intersect, however we don't have that information. 189 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!"); 190 const ClassInfo *Root = this; 191 while (!Root->SuperClasses.empty()) 192 Root = Root->SuperClasses.front(); 193 194 const ClassInfo *RHSRoot = &RHS; 195 while (!RHSRoot->SuperClasses.empty()) 196 RHSRoot = RHSRoot->SuperClasses.front(); 197 198 return Root == RHSRoot; 199 } 200 201 /// isSubsetOf - Test whether this class is a subset of \arg RHS; 202 bool isSubsetOf(const ClassInfo &RHS) const { 203 // This is a subset of RHS if it is the same class... 204 if (this == &RHS) 205 return true; 206 207 // ... or if any of its super classes are a subset of RHS. 208 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(), 209 ie = SuperClasses.end(); it != ie; ++it) 210 if ((*it)->isSubsetOf(RHS)) 211 return true; 212 213 return false; 214 } 215 216 /// operator< - Compare two classes. 217 bool operator<(const ClassInfo &RHS) const { 218 if (this == &RHS) 219 return false; 220 221 // Unrelated classes can be ordered by kind. 222 if (!isRelatedTo(RHS)) 223 return Kind < RHS.Kind; 224 225 switch (Kind) { 226 case Invalid: 227 assert(0 && "Invalid kind!"); 228 case Token: 229 // Tokens are comparable by value. 230 // 231 // FIXME: Compare by enum value. 232 return ValueName < RHS.ValueName; 233 234 default: 235 // This class preceeds the RHS if it is a proper subset of the RHS. 236 if (isSubsetOf(RHS)) 237 return true; 238 if (RHS.isSubsetOf(*this)) 239 return false; 240 241 // Otherwise, order by name to ensure we have a total ordering. 242 return ValueName < RHS.ValueName; 243 } 244 } 245}; 246 247/// MatchableInfo - Helper class for storing the necessary information for an 248/// instruction or alias which is capable of being matched. 249struct MatchableInfo { 250 struct Operand { 251 /// Token - This is the token that the operand came from. 252 StringRef Token; 253 254 /// The unique class instance this operand should match. 255 ClassInfo *Class; 256 257 /// The original operand this corresponds to. This is unset for singleton 258 /// registers and tokens, because they don't have a list in the ins/outs 259 /// list. If an operand is tied ($a=$b), this refers to source operand: $b. 260 const CGIOperandList::OperandInfo *OperandInfo; 261 262 explicit Operand(StringRef T) : Token(T), Class(0), OperandInfo(0) {} 263 }; 264 265 /// InstrName - The target name for this instruction. 266 std::string InstrName; 267 268 /// TheDef - This is the definition of the instruction or InstAlias that this 269 /// matchable came from. 270 Record *const TheDef; 271 272 /// OperandList - This is the operand list that came from the (ins) and (outs) 273 /// list of the alias or instruction. 274 const CGIOperandList &OperandList; 275 276 /// AsmString - The assembly string for this instruction (with variants 277 /// removed), e.g. "movsx $src, $dst". 278 std::string AsmString; 279 280 /// Mnemonic - This is the first token of the matched instruction, its 281 /// mnemonic. 282 StringRef Mnemonic; 283 284 /// AsmOperands - The textual operands that this instruction matches, 285 /// annotated with a class and where in the OperandList they were defined. 286 /// This directly corresponds to the tokenized AsmString after the mnemonic is 287 /// removed. 288 SmallVector<Operand, 4> AsmOperands; 289 290 /// Predicates - The required subtarget features to match this instruction. 291 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures; 292 293 /// ConversionFnKind - The enum value which is passed to the generated 294 /// ConvertToMCInst to convert parsed operands into an MCInst for this 295 /// function. 296 std::string ConversionFnKind; 297 298 MatchableInfo(const CodeGenInstruction &CGI) 299 : TheDef(CGI.TheDef), OperandList(CGI.Operands), AsmString(CGI.AsmString) { 300 InstrName = TheDef->getName(); 301 } 302 303 MatchableInfo(const CodeGenInstAlias *Alias) 304 : TheDef(Alias->TheDef), OperandList(Alias->Operands), 305 AsmString(Alias->AsmString) { 306 307 // FIXME: Huge hack. 308 DefInit *DI = dynamic_cast<DefInit*>(Alias->Result->getOperator()); 309 assert(DI); 310 311 InstrName = DI->getDef()->getName(); 312 } 313 314 void Initialize(const AsmMatcherInfo &Info, 315 SmallPtrSet<Record*, 16> &SingletonRegisters); 316 317 /// Validate - Return true if this matchable is a valid thing to match against 318 /// and perform a bunch of validity checking. 319 bool Validate(StringRef CommentDelimiter, bool Hack) const; 320 321 /// getSingletonRegisterForAsmOperand - If the specified token is a singleton 322 /// register, return the Record for it, otherwise return null. 323 Record *getSingletonRegisterForAsmOperand(unsigned i, 324 const AsmMatcherInfo &Info) const; 325 326 /// operator< - Compare two matchables. 327 bool operator<(const MatchableInfo &RHS) const { 328 // The primary comparator is the instruction mnemonic. 329 if (Mnemonic != RHS.Mnemonic) 330 return Mnemonic < RHS.Mnemonic; 331 332 if (AsmOperands.size() != RHS.AsmOperands.size()) 333 return AsmOperands.size() < RHS.AsmOperands.size(); 334 335 // Compare lexicographically by operand. The matcher validates that other 336 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith(). 337 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 338 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class) 339 return true; 340 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class) 341 return false; 342 } 343 344 return false; 345 } 346 347 /// CouldMatchAmiguouslyWith - Check whether this matchable could 348 /// ambiguously match the same set of operands as \arg RHS (without being a 349 /// strictly superior match). 350 bool CouldMatchAmiguouslyWith(const MatchableInfo &RHS) { 351 // The primary comparator is the instruction mnemonic. 352 if (Mnemonic != RHS.Mnemonic) 353 return false; 354 355 // The number of operands is unambiguous. 356 if (AsmOperands.size() != RHS.AsmOperands.size()) 357 return false; 358 359 // Otherwise, make sure the ordering of the two instructions is unambiguous 360 // by checking that either (a) a token or operand kind discriminates them, 361 // or (b) the ordering among equivalent kinds is consistent. 362 363 // Tokens and operand kinds are unambiguous (assuming a correct target 364 // specific parser). 365 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) 366 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind || 367 AsmOperands[i].Class->Kind == ClassInfo::Token) 368 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class || 369 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class) 370 return false; 371 372 // Otherwise, this operand could commute if all operands are equivalent, or 373 // there is a pair of operands that compare less than and a pair that 374 // compare greater than. 375 bool HasLT = false, HasGT = false; 376 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 377 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class) 378 HasLT = true; 379 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class) 380 HasGT = true; 381 } 382 383 return !(HasLT ^ HasGT); 384 } 385 386 void dump(); 387 388private: 389 void TokenizeAsmString(const AsmMatcherInfo &Info); 390}; 391 392/// SubtargetFeatureInfo - Helper class for storing information on a subtarget 393/// feature which participates in instruction matching. 394struct SubtargetFeatureInfo { 395 /// \brief The predicate record for this feature. 396 Record *TheDef; 397 398 /// \brief An unique index assigned to represent this feature. 399 unsigned Index; 400 401 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {} 402 403 /// \brief The name of the enumerated constant identifying this feature. 404 std::string getEnumName() const { 405 return "Feature_" + TheDef->getName(); 406 } 407}; 408 409class AsmMatcherInfo { 410public: 411 /// The tablegen AsmParser record. 412 Record *AsmParser; 413 414 /// Target - The target information. 415 CodeGenTarget &Target; 416 417 /// The AsmParser "RegisterPrefix" value. 418 std::string RegisterPrefix; 419 420 /// The classes which are needed for matching. 421 std::vector<ClassInfo*> Classes; 422 423 /// The information on the matchables to match. 424 std::vector<MatchableInfo*> Matchables; 425 426 /// Map of Register records to their class information. 427 std::map<Record*, ClassInfo*> RegisterClasses; 428 429 /// Map of Predicate records to their subtarget information. 430 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures; 431 432private: 433 /// Map of token to class information which has already been constructed. 434 std::map<std::string, ClassInfo*> TokenClasses; 435 436 /// Map of RegisterClass records to their class information. 437 std::map<Record*, ClassInfo*> RegisterClassClasses; 438 439 /// Map of AsmOperandClass records to their class information. 440 std::map<Record*, ClassInfo*> AsmOperandClasses; 441 442private: 443 /// getTokenClass - Lookup or create the class for the given token. 444 ClassInfo *getTokenClass(StringRef Token); 445 446 /// getOperandClass - Lookup or create the class for the given operand. 447 ClassInfo *getOperandClass(StringRef Token, 448 const CGIOperandList::OperandInfo &OI); 449 450 /// BuildRegisterClasses - Build the ClassInfo* instances for register 451 /// classes. 452 void BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters); 453 454 /// BuildOperandClasses - Build the ClassInfo* instances for user defined 455 /// operand classes. 456 void BuildOperandClasses(); 457 458public: 459 AsmMatcherInfo(Record *AsmParser, CodeGenTarget &Target); 460 461 /// BuildInfo - Construct the various tables used during matching. 462 void BuildInfo(); 463 464 /// getSubtargetFeature - Lookup or create the subtarget feature info for the 465 /// given operand. 466 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const { 467 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!"); 468 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I = 469 SubtargetFeatures.find(Def); 470 return I == SubtargetFeatures.end() ? 0 : I->second; 471 } 472}; 473 474} 475 476void MatchableInfo::dump() { 477 errs() << InstrName << " -- " << "flattened:\"" << AsmString << "\"\n"; 478 479 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 480 Operand &Op = AsmOperands[i]; 481 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - "; 482 if (Op.Class->Kind == ClassInfo::Token) { 483 errs() << '\"' << Op.Token << "\"\n"; 484 continue; 485 } 486 487 if (!Op.OperandInfo) { 488 errs() << "(singleton register)\n"; 489 continue; 490 } 491 492 const CGIOperandList::OperandInfo &OI = *Op.OperandInfo; 493 errs() << OI.Name << " " << OI.Rec->getName() 494 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n"; 495 } 496} 497 498void MatchableInfo::Initialize(const AsmMatcherInfo &Info, 499 SmallPtrSet<Record*, 16> &SingletonRegisters) { 500 // TODO: Eventually support asmparser for Variant != 0. 501 AsmString = CodeGenInstruction::FlattenAsmStringVariants(AsmString, 0); 502 503 TokenizeAsmString(Info); 504 505 // Compute the require features. 506 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates"); 507 for (unsigned i = 0, e = Predicates.size(); i != e; ++i) 508 if (SubtargetFeatureInfo *Feature = 509 Info.getSubtargetFeature(Predicates[i])) 510 RequiredFeatures.push_back(Feature); 511 512 // Collect singleton registers, if used. 513 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 514 if (Record *Reg = getSingletonRegisterForAsmOperand(i, Info)) 515 SingletonRegisters.insert(Reg); 516 } 517} 518 519/// TokenizeAsmString - Tokenize a simplified assembly string. 520void MatchableInfo::TokenizeAsmString(const AsmMatcherInfo &Info) { 521 StringRef String = AsmString; 522 unsigned Prev = 0; 523 bool InTok = true; 524 for (unsigned i = 0, e = String.size(); i != e; ++i) { 525 switch (String[i]) { 526 case '[': 527 case ']': 528 case '*': 529 case '!': 530 case ' ': 531 case '\t': 532 case ',': 533 if (InTok) { 534 AsmOperands.push_back(Operand(String.slice(Prev, i))); 535 InTok = false; 536 } 537 if (!isspace(String[i]) && String[i] != ',') 538 AsmOperands.push_back(Operand(String.substr(i, 1))); 539 Prev = i + 1; 540 break; 541 542 case '\\': 543 if (InTok) { 544 AsmOperands.push_back(Operand(String.slice(Prev, i))); 545 InTok = false; 546 } 547 ++i; 548 assert(i != String.size() && "Invalid quoted character"); 549 AsmOperands.push_back(Operand(String.substr(i, 1))); 550 Prev = i + 1; 551 break; 552 553 case '$': { 554 // If this isn't "${", treat like a normal token. 555 if (i + 1 == String.size() || String[i + 1] != '{') { 556 if (InTok) { 557 AsmOperands.push_back(Operand(String.slice(Prev, i))); 558 InTok = false; 559 } 560 Prev = i; 561 break; 562 } 563 564 if (InTok) { 565 AsmOperands.push_back(Operand(String.slice(Prev, i))); 566 InTok = false; 567 } 568 569 StringRef::iterator End = std::find(String.begin() + i, String.end(),'}'); 570 assert(End != String.end() && "Missing brace in operand reference!"); 571 size_t EndPos = End - String.begin(); 572 AsmOperands.push_back(Operand(String.slice(i, EndPos+1))); 573 Prev = EndPos + 1; 574 i = EndPos; 575 break; 576 } 577 578 case '.': 579 if (InTok) 580 AsmOperands.push_back(Operand(String.slice(Prev, i))); 581 Prev = i; 582 InTok = true; 583 break; 584 585 default: 586 InTok = true; 587 } 588 } 589 if (InTok && Prev != String.size()) 590 AsmOperands.push_back(Operand(String.substr(Prev))); 591 592 // The first token of the instruction is the mnemonic, which must be a 593 // simple string, not a $foo variable or a singleton register. 594 assert(!AsmOperands.empty() && "Instruction has no tokens?"); 595 Mnemonic = AsmOperands[0].Token; 596 if (Mnemonic[0] == '$' || getSingletonRegisterForAsmOperand(0, Info)) 597 throw TGError(TheDef->getLoc(), 598 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!"); 599 600 // Remove the first operand, it is tracked in the mnemonic field. 601 AsmOperands.erase(AsmOperands.begin()); 602} 603 604 605 606bool MatchableInfo::Validate(StringRef CommentDelimiter, bool Hack) const { 607 // Reject matchables with no .s string. 608 if (AsmString.empty()) 609 throw TGError(TheDef->getLoc(), "instruction with empty asm string"); 610 611 // Reject any matchables with a newline in them, they should be marked 612 // isCodeGenOnly if they are pseudo instructions. 613 if (AsmString.find('\n') != std::string::npos) 614 throw TGError(TheDef->getLoc(), 615 "multiline instruction is not valid for the asmparser, " 616 "mark it isCodeGenOnly"); 617 618 // Remove comments from the asm string. We know that the asmstring only 619 // has one line. 620 if (!CommentDelimiter.empty() && 621 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos) 622 throw TGError(TheDef->getLoc(), 623 "asmstring for instruction has comment character in it, " 624 "mark it isCodeGenOnly"); 625 626 // Reject matchables with operand modifiers, these aren't something we can 627 /// handle, the target should be refactored to use operands instead of 628 /// modifiers. 629 // 630 // Also, check for instructions which reference the operand multiple times; 631 // this implies a constraint we would not honor. 632 std::set<std::string> OperandNames; 633 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 634 StringRef Tok = AsmOperands[i].Token; 635 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos) 636 throw TGError(TheDef->getLoc(), 637 "matchable with operand modifier '" + Tok.str() + 638 "' not supported by asm matcher. Mark isCodeGenOnly!"); 639 640 // Verify that any operand is only mentioned once. 641 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) { 642 if (!Hack) 643 throw TGError(TheDef->getLoc(), 644 "ERROR: matchable with tied operand '" + Tok.str() + 645 "' can never be matched!"); 646 // FIXME: Should reject these. The ARM backend hits this with $lane in a 647 // bunch of instructions. It is unclear what the right answer is. 648 DEBUG({ 649 errs() << "warning: '" << InstrName << "': " 650 << "ignoring instruction with tied operand '" 651 << Tok.str() << "'\n"; 652 }); 653 return false; 654 } 655 } 656 657 return true; 658} 659 660 661/// getSingletonRegisterForAsmOperand - If the specified token is a singleton 662/// register, return the register name, otherwise return a null StringRef. 663Record *MatchableInfo:: 664getSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info) const{ 665 StringRef Tok = AsmOperands[i].Token; 666 if (!Tok.startswith(Info.RegisterPrefix)) 667 return 0; 668 669 StringRef RegName = Tok.substr(Info.RegisterPrefix.size()); 670 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName)) 671 return Reg->TheDef; 672 673 // If there is no register prefix (i.e. "%" in "%eax"), then this may 674 // be some random non-register token, just ignore it. 675 if (Info.RegisterPrefix.empty()) 676 return 0; 677 678 // Otherwise, we have something invalid prefixed with the register prefix, 679 // such as %foo. 680 std::string Err = "unable to find register for '" + RegName.str() + 681 "' (which matches register prefix)"; 682 throw TGError(TheDef->getLoc(), Err); 683} 684 685 686static std::string getEnumNameForToken(StringRef Str) { 687 std::string Res; 688 689 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) { 690 switch (*it) { 691 case '*': Res += "_STAR_"; break; 692 case '%': Res += "_PCT_"; break; 693 case ':': Res += "_COLON_"; break; 694 default: 695 if (isalnum(*it)) 696 Res += *it; 697 else 698 Res += "_" + utostr((unsigned) *it) + "_"; 699 } 700 } 701 702 return Res; 703} 704 705ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) { 706 ClassInfo *&Entry = TokenClasses[Token]; 707 708 if (!Entry) { 709 Entry = new ClassInfo(); 710 Entry->Kind = ClassInfo::Token; 711 Entry->ClassName = "Token"; 712 Entry->Name = "MCK_" + getEnumNameForToken(Token); 713 Entry->ValueName = Token; 714 Entry->PredicateMethod = "<invalid>"; 715 Entry->RenderMethod = "<invalid>"; 716 Classes.push_back(Entry); 717 } 718 719 return Entry; 720} 721 722ClassInfo * 723AsmMatcherInfo::getOperandClass(StringRef Token, 724 const CGIOperandList::OperandInfo &OI) { 725 if (OI.Rec->isSubClassOf("RegisterClass")) { 726 if (ClassInfo *CI = RegisterClassClasses[OI.Rec]) 727 return CI; 728 throw TGError(OI.Rec->getLoc(), "register class has no class info!"); 729 } 730 731 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!"); 732 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass"); 733 if (ClassInfo *CI = AsmOperandClasses[MatchClass]) 734 return CI; 735 736 throw TGError(OI.Rec->getLoc(), "operand has no match class!"); 737} 738 739void AsmMatcherInfo:: 740BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) { 741 const std::vector<CodeGenRegister> &Registers = Target.getRegisters(); 742 const std::vector<CodeGenRegisterClass> &RegClassList = 743 Target.getRegisterClasses(); 744 745 // The register sets used for matching. 746 std::set< std::set<Record*> > RegisterSets; 747 748 // Gather the defined sets. 749 for (std::vector<CodeGenRegisterClass>::const_iterator it = 750 RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) 751 RegisterSets.insert(std::set<Record*>(it->Elements.begin(), 752 it->Elements.end())); 753 754 // Add any required singleton sets. 755 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(), 756 ie = SingletonRegisters.end(); it != ie; ++it) { 757 Record *Rec = *it; 758 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1)); 759 } 760 761 // Introduce derived sets where necessary (when a register does not determine 762 // a unique register set class), and build the mapping of registers to the set 763 // they should classify to. 764 std::map<Record*, std::set<Record*> > RegisterMap; 765 for (std::vector<CodeGenRegister>::const_iterator it = Registers.begin(), 766 ie = Registers.end(); it != ie; ++it) { 767 const CodeGenRegister &CGR = *it; 768 // Compute the intersection of all sets containing this register. 769 std::set<Record*> ContainingSet; 770 771 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(), 772 ie = RegisterSets.end(); it != ie; ++it) { 773 if (!it->count(CGR.TheDef)) 774 continue; 775 776 if (ContainingSet.empty()) { 777 ContainingSet = *it; 778 continue; 779 } 780 781 std::set<Record*> Tmp; 782 std::swap(Tmp, ContainingSet); 783 std::insert_iterator< std::set<Record*> > II(ContainingSet, 784 ContainingSet.begin()); 785 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(), II); 786 } 787 788 if (!ContainingSet.empty()) { 789 RegisterSets.insert(ContainingSet); 790 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet)); 791 } 792 } 793 794 // Construct the register classes. 795 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses; 796 unsigned Index = 0; 797 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(), 798 ie = RegisterSets.end(); it != ie; ++it, ++Index) { 799 ClassInfo *CI = new ClassInfo(); 800 CI->Kind = ClassInfo::RegisterClass0 + Index; 801 CI->ClassName = "Reg" + utostr(Index); 802 CI->Name = "MCK_Reg" + utostr(Index); 803 CI->ValueName = ""; 804 CI->PredicateMethod = ""; // unused 805 CI->RenderMethod = "addRegOperands"; 806 CI->Registers = *it; 807 Classes.push_back(CI); 808 RegisterSetClasses.insert(std::make_pair(*it, CI)); 809 } 810 811 // Find the superclasses; we could compute only the subgroup lattice edges, 812 // but there isn't really a point. 813 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(), 814 ie = RegisterSets.end(); it != ie; ++it) { 815 ClassInfo *CI = RegisterSetClasses[*it]; 816 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(), 817 ie2 = RegisterSets.end(); it2 != ie2; ++it2) 818 if (*it != *it2 && 819 std::includes(it2->begin(), it2->end(), it->begin(), it->end())) 820 CI->SuperClasses.push_back(RegisterSetClasses[*it2]); 821 } 822 823 // Name the register classes which correspond to a user defined RegisterClass. 824 for (std::vector<CodeGenRegisterClass>::const_iterator 825 it = RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) { 826 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(), 827 it->Elements.end())]; 828 if (CI->ValueName.empty()) { 829 CI->ClassName = it->getName(); 830 CI->Name = "MCK_" + it->getName(); 831 CI->ValueName = it->getName(); 832 } else 833 CI->ValueName = CI->ValueName + "," + it->getName(); 834 835 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI)); 836 } 837 838 // Populate the map for individual registers. 839 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(), 840 ie = RegisterMap.end(); it != ie; ++it) 841 RegisterClasses[it->first] = RegisterSetClasses[it->second]; 842 843 // Name the register classes which correspond to singleton registers. 844 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(), 845 ie = SingletonRegisters.end(); it != ie; ++it) { 846 Record *Rec = *it; 847 ClassInfo *CI = RegisterClasses[Rec]; 848 assert(CI && "Missing singleton register class info!"); 849 850 if (CI->ValueName.empty()) { 851 CI->ClassName = Rec->getName(); 852 CI->Name = "MCK_" + Rec->getName(); 853 CI->ValueName = Rec->getName(); 854 } else 855 CI->ValueName = CI->ValueName + "," + Rec->getName(); 856 } 857} 858 859void AsmMatcherInfo::BuildOperandClasses() { 860 std::vector<Record*> AsmOperands = 861 Records.getAllDerivedDefinitions("AsmOperandClass"); 862 863 // Pre-populate AsmOperandClasses map. 864 for (std::vector<Record*>::iterator it = AsmOperands.begin(), 865 ie = AsmOperands.end(); it != ie; ++it) 866 AsmOperandClasses[*it] = new ClassInfo(); 867 868 unsigned Index = 0; 869 for (std::vector<Record*>::iterator it = AsmOperands.begin(), 870 ie = AsmOperands.end(); it != ie; ++it, ++Index) { 871 ClassInfo *CI = AsmOperandClasses[*it]; 872 CI->Kind = ClassInfo::UserClass0 + Index; 873 874 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses"); 875 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) { 876 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i)); 877 if (!DI) { 878 PrintError((*it)->getLoc(), "Invalid super class reference!"); 879 continue; 880 } 881 882 ClassInfo *SC = AsmOperandClasses[DI->getDef()]; 883 if (!SC) 884 PrintError((*it)->getLoc(), "Invalid super class reference!"); 885 else 886 CI->SuperClasses.push_back(SC); 887 } 888 CI->ClassName = (*it)->getValueAsString("Name"); 889 CI->Name = "MCK_" + CI->ClassName; 890 CI->ValueName = (*it)->getName(); 891 892 // Get or construct the predicate method name. 893 Init *PMName = (*it)->getValueInit("PredicateMethod"); 894 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) { 895 CI->PredicateMethod = SI->getValue(); 896 } else { 897 assert(dynamic_cast<UnsetInit*>(PMName) && 898 "Unexpected PredicateMethod field!"); 899 CI->PredicateMethod = "is" + CI->ClassName; 900 } 901 902 // Get or construct the render method name. 903 Init *RMName = (*it)->getValueInit("RenderMethod"); 904 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) { 905 CI->RenderMethod = SI->getValue(); 906 } else { 907 assert(dynamic_cast<UnsetInit*>(RMName) && 908 "Unexpected RenderMethod field!"); 909 CI->RenderMethod = "add" + CI->ClassName + "Operands"; 910 } 911 912 AsmOperandClasses[*it] = CI; 913 Classes.push_back(CI); 914 } 915} 916 917AsmMatcherInfo::AsmMatcherInfo(Record *asmParser, CodeGenTarget &target) 918 : AsmParser(asmParser), Target(target), 919 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix")) { 920} 921 922 923void AsmMatcherInfo::BuildInfo() { 924 // Build information about all of the AssemblerPredicates. 925 std::vector<Record*> AllPredicates = 926 Records.getAllDerivedDefinitions("Predicate"); 927 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) { 928 Record *Pred = AllPredicates[i]; 929 // Ignore predicates that are not intended for the assembler. 930 if (!Pred->getValueAsBit("AssemblerMatcherPredicate")) 931 continue; 932 933 if (Pred->getName().empty()) 934 throw TGError(Pred->getLoc(), "Predicate has no name!"); 935 936 unsigned FeatureNo = SubtargetFeatures.size(); 937 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo); 938 assert(FeatureNo < 32 && "Too many subtarget features!"); 939 } 940 941 StringRef CommentDelimiter = AsmParser->getValueAsString("CommentDelimiter"); 942 943 // Parse the instructions; we need to do this first so that we can gather the 944 // singleton register classes. 945 SmallPtrSet<Record*, 16> SingletonRegisters; 946 for (CodeGenTarget::inst_iterator I = Target.inst_begin(), 947 E = Target.inst_end(); I != E; ++I) { 948 const CodeGenInstruction &CGI = **I; 949 950 // If the tblgen -match-prefix option is specified (for tblgen hackers), 951 // filter the set of instructions we consider. 952 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix)) 953 continue; 954 955 // Ignore "codegen only" instructions. 956 if (CGI.TheDef->getValueAsBit("isCodeGenOnly")) 957 continue; 958 959 OwningPtr<MatchableInfo> II(new MatchableInfo(CGI)); 960 961 II->Initialize(*this, SingletonRegisters); 962 963 // Ignore instructions which shouldn't be matched and diagnose invalid 964 // instruction definitions with an error. 965 if (!II->Validate(CommentDelimiter, true)) 966 continue; 967 968 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases. 969 // 970 // FIXME: This is a total hack. 971 if (StringRef(II->InstrName).startswith("Int_") || 972 StringRef(II->InstrName).endswith("_Int")) 973 continue; 974 975 Matchables.push_back(II.take()); 976 } 977 978 // Parse all of the InstAlias definitions and stick them in the list of 979 // matchables. 980 std::vector<Record*> AllInstAliases = 981 Records.getAllDerivedDefinitions("InstAlias"); 982 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) { 983 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i]); 984 985 OwningPtr<MatchableInfo> II(new MatchableInfo(Alias)); 986 987 II->Initialize(*this, SingletonRegisters); 988 989 // Validate the alias definitions. 990 II->Validate(CommentDelimiter, false); 991 992 Matchables.push_back(II.take()); 993 } 994 995 // Build info for the register classes. 996 BuildRegisterClasses(SingletonRegisters); 997 998 // Build info for the user defined assembly operand classes. 999 BuildOperandClasses(); 1000 1001 // Build the information about matchables. 1002 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(), 1003 ie = Matchables.end(); it != ie; ++it) { 1004 MatchableInfo *II = *it; 1005 1006 // Parse the tokens after the mnemonic. 1007 for (unsigned i = 0, e = II->AsmOperands.size(); i != e; ++i) { 1008 MatchableInfo::Operand &Op = II->AsmOperands[i]; 1009 StringRef Token = Op.Token; 1010 1011 // Check for singleton registers. 1012 if (Record *RegRecord = II->getSingletonRegisterForAsmOperand(i, *this)) { 1013 Op.Class = RegisterClasses[RegRecord]; 1014 assert(Op.Class && Op.Class->Registers.size() == 1 && 1015 "Unexpected class for singleton register"); 1016 continue; 1017 } 1018 1019 // Check for simple tokens. 1020 if (Token[0] != '$') { 1021 Op.Class = getTokenClass(Token); 1022 continue; 1023 } 1024 1025 // Otherwise this is an operand reference. 1026 StringRef OperandName; 1027 if (Token[1] == '{') 1028 OperandName = Token.substr(2, Token.size() - 3); 1029 else 1030 OperandName = Token.substr(1); 1031 1032 // Map this token to an operand. FIXME: Move elsewhere. 1033 unsigned Idx; 1034 if (!II->OperandList.hasOperandNamed(OperandName, Idx)) 1035 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" + 1036 OperandName.str() + "'"); 1037 1038 // FIXME: This is annoying, the named operand may be tied (e.g., 1039 // XCHG8rm). What we want is the untied operand, which we now have to 1040 // grovel for. Only worry about this for single entry operands, we have to 1041 // clean this up anyway. 1042 const CGIOperandList::OperandInfo *OI = &II->OperandList[Idx]; 1043 if (OI->Constraints[0].isTied()) { 1044 unsigned TiedOp = OI->Constraints[0].getTiedOperand(); 1045 1046 // The tied operand index is an MIOperand index, find the operand that 1047 // contains it. 1048 for (unsigned i = 0, e = II->OperandList.size(); i != e; ++i) { 1049 if (II->OperandList[i].MIOperandNo == TiedOp) { 1050 OI = &II->OperandList[i]; 1051 break; 1052 } 1053 } 1054 1055 assert(OI && "Unable to find tied operand target!"); 1056 } 1057 1058 Op.Class = getOperandClass(Token, *OI); 1059 Op.OperandInfo = OI; 1060 } 1061 } 1062 1063 // Reorder classes so that classes preceed super classes. 1064 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>()); 1065} 1066 1067static std::pair<unsigned, unsigned> * 1068GetTiedOperandAtIndex(SmallVectorImpl<std::pair<unsigned, unsigned> > &List, 1069 unsigned Index) { 1070 for (unsigned i = 0, e = List.size(); i != e; ++i) 1071 if (Index == List[i].first) 1072 return &List[i]; 1073 1074 return 0; 1075} 1076 1077static void EmitConvertToMCInst(CodeGenTarget &Target, 1078 std::vector<MatchableInfo*> &Infos, 1079 raw_ostream &OS) { 1080 // Write the convert function to a separate stream, so we can drop it after 1081 // the enum. 1082 std::string ConvertFnBody; 1083 raw_string_ostream CvtOS(ConvertFnBody); 1084 1085 // Function we have already generated. 1086 std::set<std::string> GeneratedFns; 1087 1088 // Start the unified conversion function. 1089 1090 CvtOS << "static void ConvertToMCInst(ConversionKind Kind, MCInst &Inst, " 1091 << "unsigned Opcode,\n" 1092 << " const SmallVectorImpl<MCParsedAsmOperand*" 1093 << "> &Operands) {\n"; 1094 CvtOS << " Inst.setOpcode(Opcode);\n"; 1095 CvtOS << " switch (Kind) {\n"; 1096 CvtOS << " default:\n"; 1097 1098 // Start the enum, which we will generate inline. 1099 1100 OS << "// Unified function for converting operants to MCInst instances.\n\n"; 1101 OS << "enum ConversionKind {\n"; 1102 1103 // TargetOperandClass - This is the target's operand class, like X86Operand. 1104 std::string TargetOperandClass = Target.getName() + "Operand"; 1105 1106 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(), 1107 ie = Infos.end(); it != ie; ++it) { 1108 MatchableInfo &II = **it; 1109 1110 // Order the (class) operands by the order to convert them into an MCInst. 1111 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList; 1112 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) { 1113 MatchableInfo::Operand &Op = II.AsmOperands[i]; 1114 if (Op.OperandInfo) 1115 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i)); 1116 } 1117 1118 // Find any tied operands. 1119 SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands; 1120 for (unsigned i = 0, e = II.OperandList.size(); i != e; ++i) { 1121 const CGIOperandList::OperandInfo &OpInfo = II.OperandList[i]; 1122 for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) { 1123 const CGIOperandList::ConstraintInfo &CI = OpInfo.Constraints[j]; 1124 if (!CI.isTied()) continue; 1125 TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo, 1126 CI.getTiedOperand())); 1127 } 1128 } 1129 1130 array_pod_sort(MIOperandList.begin(), MIOperandList.end()); 1131 1132 // Compute the total number of operands. 1133 unsigned NumMIOperands = 0; 1134 for (unsigned i = 0, e = II.OperandList.size(); i != e; ++i) { 1135 const CGIOperandList::OperandInfo &OI = II.OperandList[i]; 1136 NumMIOperands = std::max(NumMIOperands, OI.MIOperandNo+OI.MINumOperands); 1137 } 1138 1139 // Build the conversion function signature. 1140 std::string Signature = "Convert"; 1141 unsigned CurIndex = 0; 1142 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) { 1143 MatchableInfo::Operand &Op = II.AsmOperands[MIOperandList[i].second]; 1144 assert(CurIndex <= Op.OperandInfo->MIOperandNo && 1145 "Duplicate match for instruction operand!"); 1146 1147 // Skip operands which weren't matched by anything, this occurs when the 1148 // .td file encodes "implicit" operands as explicit ones. 1149 // 1150 // FIXME: This should be removed from the MCInst structure. 1151 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) { 1152 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands, 1153 CurIndex); 1154 if (!Tie) 1155 Signature += "__Imp"; 1156 else 1157 Signature += "__Tie" + utostr(Tie->second); 1158 } 1159 1160 Signature += "__"; 1161 1162 // Registers are always converted the same, don't duplicate the conversion 1163 // function based on them. 1164 // 1165 // FIXME: We could generalize this based on the render method, if it 1166 // mattered. 1167 if (Op.Class->isRegisterClass()) 1168 Signature += "Reg"; 1169 else 1170 Signature += Op.Class->ClassName; 1171 Signature += utostr(Op.OperandInfo->MINumOperands); 1172 Signature += "_" + utostr(MIOperandList[i].second); 1173 1174 CurIndex += Op.OperandInfo->MINumOperands; 1175 } 1176 1177 // Add any trailing implicit operands. 1178 for (; CurIndex != NumMIOperands; ++CurIndex) { 1179 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands, 1180 CurIndex); 1181 if (!Tie) 1182 Signature += "__Imp"; 1183 else 1184 Signature += "__Tie" + utostr(Tie->second); 1185 } 1186 1187 II.ConversionFnKind = Signature; 1188 1189 // Check if we have already generated this signature. 1190 if (!GeneratedFns.insert(Signature).second) 1191 continue; 1192 1193 // If not, emit it now. 1194 1195 // Add to the enum list. 1196 OS << " " << Signature << ",\n"; 1197 1198 // And to the convert function. 1199 CvtOS << " case " << Signature << ":\n"; 1200 CurIndex = 0; 1201 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) { 1202 MatchableInfo::Operand &Op = II.AsmOperands[MIOperandList[i].second]; 1203 1204 // Add the implicit operands. 1205 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) { 1206 // See if this is a tied operand. 1207 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands, 1208 CurIndex); 1209 1210 if (!Tie) { 1211 // If not, this is some implicit operand. Just assume it is a register 1212 // for now. 1213 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n"; 1214 } else { 1215 // Copy the tied operand. 1216 assert(Tie->first>Tie->second && "Tied operand preceeds its target!"); 1217 CvtOS << " Inst.addOperand(Inst.getOperand(" 1218 << Tie->second << "));\n"; 1219 } 1220 } 1221 1222 CvtOS << " ((" << TargetOperandClass << "*)Operands[" 1223 << MIOperandList[i].second 1224 << "+1])->" << Op.Class->RenderMethod 1225 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n"; 1226 CurIndex += Op.OperandInfo->MINumOperands; 1227 } 1228 1229 // And add trailing implicit operands. 1230 for (; CurIndex != NumMIOperands; ++CurIndex) { 1231 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands, 1232 CurIndex); 1233 1234 if (!Tie) { 1235 // If not, this is some implicit operand. Just assume it is a register 1236 // for now. 1237 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n"; 1238 } else { 1239 // Copy the tied operand. 1240 assert(Tie->first>Tie->second && "Tied operand preceeds its target!"); 1241 CvtOS << " Inst.addOperand(Inst.getOperand(" 1242 << Tie->second << "));\n"; 1243 } 1244 } 1245 1246 CvtOS << " return;\n"; 1247 } 1248 1249 // Finish the convert function. 1250 1251 CvtOS << " }\n"; 1252 CvtOS << "}\n\n"; 1253 1254 // Finish the enum, and drop the convert function after it. 1255 1256 OS << " NumConversionVariants\n"; 1257 OS << "};\n\n"; 1258 1259 OS << CvtOS.str(); 1260} 1261 1262/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds. 1263static void EmitMatchClassEnumeration(CodeGenTarget &Target, 1264 std::vector<ClassInfo*> &Infos, 1265 raw_ostream &OS) { 1266 OS << "namespace {\n\n"; 1267 1268 OS << "/// MatchClassKind - The kinds of classes which participate in\n" 1269 << "/// instruction matching.\n"; 1270 OS << "enum MatchClassKind {\n"; 1271 OS << " InvalidMatchClass = 0,\n"; 1272 for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 1273 ie = Infos.end(); it != ie; ++it) { 1274 ClassInfo &CI = **it; 1275 OS << " " << CI.Name << ", // "; 1276 if (CI.Kind == ClassInfo::Token) { 1277 OS << "'" << CI.ValueName << "'\n"; 1278 } else if (CI.isRegisterClass()) { 1279 if (!CI.ValueName.empty()) 1280 OS << "register class '" << CI.ValueName << "'\n"; 1281 else 1282 OS << "derived register class\n"; 1283 } else { 1284 OS << "user defined class '" << CI.ValueName << "'\n"; 1285 } 1286 } 1287 OS << " NumMatchClassKinds\n"; 1288 OS << "};\n\n"; 1289 1290 OS << "}\n\n"; 1291} 1292 1293/// EmitClassifyOperand - Emit the function to classify an operand. 1294static void EmitClassifyOperand(AsmMatcherInfo &Info, 1295 raw_ostream &OS) { 1296 OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n" 1297 << " " << Info.Target.getName() << "Operand &Operand = *(" 1298 << Info.Target.getName() << "Operand*)GOp;\n"; 1299 1300 // Classify tokens. 1301 OS << " if (Operand.isToken())\n"; 1302 OS << " return MatchTokenString(Operand.getToken());\n\n"; 1303 1304 // Classify registers. 1305 // 1306 // FIXME: Don't hardcode isReg, getReg. 1307 OS << " if (Operand.isReg()) {\n"; 1308 OS << " switch (Operand.getReg()) {\n"; 1309 OS << " default: return InvalidMatchClass;\n"; 1310 for (std::map<Record*, ClassInfo*>::iterator 1311 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end(); 1312 it != ie; ++it) 1313 OS << " case " << Info.Target.getName() << "::" 1314 << it->first->getName() << ": return " << it->second->Name << ";\n"; 1315 OS << " }\n"; 1316 OS << " }\n\n"; 1317 1318 // Classify user defined operands. 1319 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(), 1320 ie = Info.Classes.end(); it != ie; ++it) { 1321 ClassInfo &CI = **it; 1322 1323 if (!CI.isUserClass()) 1324 continue; 1325 1326 OS << " // '" << CI.ClassName << "' class"; 1327 if (!CI.SuperClasses.empty()) { 1328 OS << ", subclass of "; 1329 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) { 1330 if (i) OS << ", "; 1331 OS << "'" << CI.SuperClasses[i]->ClassName << "'"; 1332 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!"); 1333 } 1334 } 1335 OS << "\n"; 1336 1337 OS << " if (Operand." << CI.PredicateMethod << "()) {\n"; 1338 1339 // Validate subclass relationships. 1340 if (!CI.SuperClasses.empty()) { 1341 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) 1342 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod 1343 << "() && \"Invalid class relationship!\");\n"; 1344 } 1345 1346 OS << " return " << CI.Name << ";\n"; 1347 OS << " }\n\n"; 1348 } 1349 OS << " return InvalidMatchClass;\n"; 1350 OS << "}\n\n"; 1351} 1352 1353/// EmitIsSubclass - Emit the subclass predicate function. 1354static void EmitIsSubclass(CodeGenTarget &Target, 1355 std::vector<ClassInfo*> &Infos, 1356 raw_ostream &OS) { 1357 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n"; 1358 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n"; 1359 OS << " if (A == B)\n"; 1360 OS << " return true;\n\n"; 1361 1362 OS << " switch (A) {\n"; 1363 OS << " default:\n"; 1364 OS << " return false;\n"; 1365 for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 1366 ie = Infos.end(); it != ie; ++it) { 1367 ClassInfo &A = **it; 1368 1369 if (A.Kind != ClassInfo::Token) { 1370 std::vector<StringRef> SuperClasses; 1371 for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 1372 ie = Infos.end(); it != ie; ++it) { 1373 ClassInfo &B = **it; 1374 1375 if (&A != &B && A.isSubsetOf(B)) 1376 SuperClasses.push_back(B.Name); 1377 } 1378 1379 if (SuperClasses.empty()) 1380 continue; 1381 1382 OS << "\n case " << A.Name << ":\n"; 1383 1384 if (SuperClasses.size() == 1) { 1385 OS << " return B == " << SuperClasses.back() << ";\n"; 1386 continue; 1387 } 1388 1389 OS << " switch (B) {\n"; 1390 OS << " default: return false;\n"; 1391 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i) 1392 OS << " case " << SuperClasses[i] << ": return true;\n"; 1393 OS << " }\n"; 1394 } 1395 } 1396 OS << " }\n"; 1397 OS << "}\n\n"; 1398} 1399 1400 1401 1402/// EmitMatchTokenString - Emit the function to match a token string to the 1403/// appropriate match class value. 1404static void EmitMatchTokenString(CodeGenTarget &Target, 1405 std::vector<ClassInfo*> &Infos, 1406 raw_ostream &OS) { 1407 // Construct the match list. 1408 std::vector<StringMatcher::StringPair> Matches; 1409 for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 1410 ie = Infos.end(); it != ie; ++it) { 1411 ClassInfo &CI = **it; 1412 1413 if (CI.Kind == ClassInfo::Token) 1414 Matches.push_back(StringMatcher::StringPair(CI.ValueName, 1415 "return " + CI.Name + ";")); 1416 } 1417 1418 OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n"; 1419 1420 StringMatcher("Name", Matches, OS).Emit(); 1421 1422 OS << " return InvalidMatchClass;\n"; 1423 OS << "}\n\n"; 1424} 1425 1426/// EmitMatchRegisterName - Emit the function to match a string to the target 1427/// specific register enum. 1428static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser, 1429 raw_ostream &OS) { 1430 // Construct the match list. 1431 std::vector<StringMatcher::StringPair> Matches; 1432 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) { 1433 const CodeGenRegister &Reg = Target.getRegisters()[i]; 1434 if (Reg.TheDef->getValueAsString("AsmName").empty()) 1435 continue; 1436 1437 Matches.push_back(StringMatcher::StringPair( 1438 Reg.TheDef->getValueAsString("AsmName"), 1439 "return " + utostr(i + 1) + ";")); 1440 } 1441 1442 OS << "static unsigned MatchRegisterName(StringRef Name) {\n"; 1443 1444 StringMatcher("Name", Matches, OS).Emit(); 1445 1446 OS << " return 0;\n"; 1447 OS << "}\n\n"; 1448} 1449 1450/// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag 1451/// definitions. 1452static void EmitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info, 1453 raw_ostream &OS) { 1454 OS << "// Flags for subtarget features that participate in " 1455 << "instruction matching.\n"; 1456 OS << "enum SubtargetFeatureFlag {\n"; 1457 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator 1458 it = Info.SubtargetFeatures.begin(), 1459 ie = Info.SubtargetFeatures.end(); it != ie; ++it) { 1460 SubtargetFeatureInfo &SFI = *it->second; 1461 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n"; 1462 } 1463 OS << " Feature_None = 0\n"; 1464 OS << "};\n\n"; 1465} 1466 1467/// EmitComputeAvailableFeatures - Emit the function to compute the list of 1468/// available features given a subtarget. 1469static void EmitComputeAvailableFeatures(AsmMatcherInfo &Info, 1470 raw_ostream &OS) { 1471 std::string ClassName = 1472 Info.AsmParser->getValueAsString("AsmParserClassName"); 1473 1474 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n" 1475 << "ComputeAvailableFeatures(const " << Info.Target.getName() 1476 << "Subtarget *Subtarget) const {\n"; 1477 OS << " unsigned Features = 0;\n"; 1478 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator 1479 it = Info.SubtargetFeatures.begin(), 1480 ie = Info.SubtargetFeatures.end(); it != ie; ++it) { 1481 SubtargetFeatureInfo &SFI = *it->second; 1482 OS << " if (" << SFI.TheDef->getValueAsString("CondString") 1483 << ")\n"; 1484 OS << " Features |= " << SFI.getEnumName() << ";\n"; 1485 } 1486 OS << " return Features;\n"; 1487 OS << "}\n\n"; 1488} 1489 1490static std::string GetAliasRequiredFeatures(Record *R, 1491 const AsmMatcherInfo &Info) { 1492 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates"); 1493 std::string Result; 1494 unsigned NumFeatures = 0; 1495 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) { 1496 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]); 1497 1498 if (F == 0) 1499 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() + 1500 "' is not marked as an AssemblerPredicate!"); 1501 1502 if (NumFeatures) 1503 Result += '|'; 1504 1505 Result += F->getEnumName(); 1506 ++NumFeatures; 1507 } 1508 1509 if (NumFeatures > 1) 1510 Result = '(' + Result + ')'; 1511 return Result; 1512} 1513 1514/// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions, 1515/// emit a function for them and return true, otherwise return false. 1516static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) { 1517 std::vector<Record*> Aliases = 1518 Records.getAllDerivedDefinitions("MnemonicAlias"); 1519 if (Aliases.empty()) return false; 1520 1521 OS << "static void ApplyMnemonicAliases(StringRef &Mnemonic, " 1522 "unsigned Features) {\n"; 1523 1524 // Keep track of all the aliases from a mnemonic. Use an std::map so that the 1525 // iteration order of the map is stable. 1526 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic; 1527 1528 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) { 1529 Record *R = Aliases[i]; 1530 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R); 1531 } 1532 1533 // Process each alias a "from" mnemonic at a time, building the code executed 1534 // by the string remapper. 1535 std::vector<StringMatcher::StringPair> Cases; 1536 for (std::map<std::string, std::vector<Record*> >::iterator 1537 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end(); 1538 I != E; ++I) { 1539 const std::vector<Record*> &ToVec = I->second; 1540 1541 // Loop through each alias and emit code that handles each case. If there 1542 // are two instructions without predicates, emit an error. If there is one, 1543 // emit it last. 1544 std::string MatchCode; 1545 int AliasWithNoPredicate = -1; 1546 1547 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) { 1548 Record *R = ToVec[i]; 1549 std::string FeatureMask = GetAliasRequiredFeatures(R, Info); 1550 1551 // If this unconditionally matches, remember it for later and diagnose 1552 // duplicates. 1553 if (FeatureMask.empty()) { 1554 if (AliasWithNoPredicate != -1) { 1555 // We can't have two aliases from the same mnemonic with no predicate. 1556 PrintError(ToVec[AliasWithNoPredicate]->getLoc(), 1557 "two MnemonicAliases with the same 'from' mnemonic!"); 1558 throw TGError(R->getLoc(), "this is the other MnemonicAlias."); 1559 } 1560 1561 AliasWithNoPredicate = i; 1562 continue; 1563 } 1564 1565 if (!MatchCode.empty()) 1566 MatchCode += "else "; 1567 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n"; 1568 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n"; 1569 } 1570 1571 if (AliasWithNoPredicate != -1) { 1572 Record *R = ToVec[AliasWithNoPredicate]; 1573 if (!MatchCode.empty()) 1574 MatchCode += "else\n "; 1575 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n"; 1576 } 1577 1578 MatchCode += "return;"; 1579 1580 Cases.push_back(std::make_pair(I->first, MatchCode)); 1581 } 1582 1583 1584 StringMatcher("Mnemonic", Cases, OS).Emit(); 1585 OS << "}\n"; 1586 1587 return true; 1588} 1589 1590void AsmMatcherEmitter::run(raw_ostream &OS) { 1591 CodeGenTarget Target; 1592 Record *AsmParser = Target.getAsmParser(); 1593 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName"); 1594 1595 // Compute the information on the instructions to match. 1596 AsmMatcherInfo Info(AsmParser, Target); 1597 Info.BuildInfo(); 1598 1599 // Sort the instruction table using the partial order on classes. We use 1600 // stable_sort to ensure that ambiguous instructions are still 1601 // deterministically ordered. 1602 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(), 1603 less_ptr<MatchableInfo>()); 1604 1605 DEBUG_WITH_TYPE("instruction_info", { 1606 for (std::vector<MatchableInfo*>::iterator 1607 it = Info.Matchables.begin(), ie = Info.Matchables.end(); 1608 it != ie; ++it) 1609 (*it)->dump(); 1610 }); 1611 1612 // Check for ambiguous matchables. 1613 DEBUG_WITH_TYPE("ambiguous_instrs", { 1614 unsigned NumAmbiguous = 0; 1615 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) { 1616 for (unsigned j = i + 1; j != e; ++j) { 1617 MatchableInfo &A = *Info.Matchables[i]; 1618 MatchableInfo &B = *Info.Matchables[j]; 1619 1620 if (A.CouldMatchAmiguouslyWith(B)) { 1621 errs() << "warning: ambiguous matchables:\n"; 1622 A.dump(); 1623 errs() << "\nis incomparable with:\n"; 1624 B.dump(); 1625 errs() << "\n\n"; 1626 ++NumAmbiguous; 1627 } 1628 } 1629 } 1630 if (NumAmbiguous) 1631 errs() << "warning: " << NumAmbiguous 1632 << " ambiguous matchables!\n"; 1633 }); 1634 1635 // Write the output. 1636 1637 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS); 1638 1639 // Information for the class declaration. 1640 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n"; 1641 OS << "#undef GET_ASSEMBLER_HEADER\n"; 1642 OS << " // This should be included into the middle of the declaration of \n"; 1643 OS << " // your subclasses implementation of TargetAsmParser.\n"; 1644 OS << " unsigned ComputeAvailableFeatures(const " << 1645 Target.getName() << "Subtarget *Subtarget) const;\n"; 1646 OS << " enum MatchResultTy {\n"; 1647 OS << " Match_Success, Match_MnemonicFail, Match_InvalidOperand,\n"; 1648 OS << " Match_MissingFeature\n"; 1649 OS << " };\n"; 1650 OS << " MatchResultTy MatchInstructionImpl(const " 1651 << "SmallVectorImpl<MCParsedAsmOperand*>" 1652 << " &Operands, MCInst &Inst, unsigned &ErrorInfo);\n\n"; 1653 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n"; 1654 1655 1656 1657 1658 OS << "\n#ifdef GET_REGISTER_MATCHER\n"; 1659 OS << "#undef GET_REGISTER_MATCHER\n\n"; 1660 1661 // Emit the subtarget feature enumeration. 1662 EmitSubtargetFeatureFlagEnumeration(Info, OS); 1663 1664 // Emit the function to match a register name to number. 1665 EmitMatchRegisterName(Target, AsmParser, OS); 1666 1667 OS << "#endif // GET_REGISTER_MATCHER\n\n"; 1668 1669 1670 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n"; 1671 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n"; 1672 1673 // Generate the function that remaps for mnemonic aliases. 1674 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info); 1675 1676 // Generate the unified function to convert operands into an MCInst. 1677 EmitConvertToMCInst(Target, Info.Matchables, OS); 1678 1679 // Emit the enumeration for classes which participate in matching. 1680 EmitMatchClassEnumeration(Target, Info.Classes, OS); 1681 1682 // Emit the routine to match token strings to their match class. 1683 EmitMatchTokenString(Target, Info.Classes, OS); 1684 1685 // Emit the routine to classify an operand. 1686 EmitClassifyOperand(Info, OS); 1687 1688 // Emit the subclass predicate routine. 1689 EmitIsSubclass(Target, Info.Classes, OS); 1690 1691 // Emit the available features compute function. 1692 EmitComputeAvailableFeatures(Info, OS); 1693 1694 1695 size_t MaxNumOperands = 0; 1696 for (std::vector<MatchableInfo*>::const_iterator it = 1697 Info.Matchables.begin(), ie = Info.Matchables.end(); 1698 it != ie; ++it) 1699 MaxNumOperands = std::max(MaxNumOperands, (*it)->AsmOperands.size()); 1700 1701 1702 // Emit the static match table; unused classes get initalized to 0 which is 1703 // guaranteed to be InvalidMatchClass. 1704 // 1705 // FIXME: We can reduce the size of this table very easily. First, we change 1706 // it so that store the kinds in separate bit-fields for each index, which 1707 // only needs to be the max width used for classes at that index (we also need 1708 // to reject based on this during classification). If we then make sure to 1709 // order the match kinds appropriately (putting mnemonics last), then we 1710 // should only end up using a few bits for each class, especially the ones 1711 // following the mnemonic. 1712 OS << "namespace {\n"; 1713 OS << " struct MatchEntry {\n"; 1714 OS << " unsigned Opcode;\n"; 1715 OS << " const char *Mnemonic;\n"; 1716 OS << " ConversionKind ConvertFn;\n"; 1717 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n"; 1718 OS << " unsigned RequiredFeatures;\n"; 1719 OS << " };\n\n"; 1720 1721 OS << "// Predicate for searching for an opcode.\n"; 1722 OS << " struct LessOpcode {\n"; 1723 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n"; 1724 OS << " return StringRef(LHS.Mnemonic) < RHS;\n"; 1725 OS << " }\n"; 1726 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n"; 1727 OS << " return LHS < StringRef(RHS.Mnemonic);\n"; 1728 OS << " }\n"; 1729 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n"; 1730 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n"; 1731 OS << " }\n"; 1732 OS << " };\n"; 1733 1734 OS << "} // end anonymous namespace.\n\n"; 1735 1736 OS << "static const MatchEntry MatchTable[" 1737 << Info.Matchables.size() << "] = {\n"; 1738 1739 for (std::vector<MatchableInfo*>::const_iterator it = 1740 Info.Matchables.begin(), ie = Info.Matchables.end(); 1741 it != ie; ++it) { 1742 MatchableInfo &II = **it; 1743 1744 OS << " { " << Target.getName() << "::" << II.InstrName 1745 << ", \"" << II.Mnemonic << "\"" 1746 << ", " << II.ConversionFnKind << ", { "; 1747 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) { 1748 MatchableInfo::Operand &Op = II.AsmOperands[i]; 1749 1750 if (i) OS << ", "; 1751 OS << Op.Class->Name; 1752 } 1753 OS << " }, "; 1754 1755 // Write the required features mask. 1756 if (!II.RequiredFeatures.empty()) { 1757 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) { 1758 if (i) OS << "|"; 1759 OS << II.RequiredFeatures[i]->getEnumName(); 1760 } 1761 } else 1762 OS << "0"; 1763 1764 OS << "},\n"; 1765 } 1766 1767 OS << "};\n\n"; 1768 1769 // Finally, build the match function. 1770 OS << Target.getName() << ClassName << "::MatchResultTy " 1771 << Target.getName() << ClassName << "::\n" 1772 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>" 1773 << " &Operands,\n"; 1774 OS << " MCInst &Inst, unsigned &ErrorInfo) {\n"; 1775 1776 // Emit code to get the available features. 1777 OS << " // Get the current feature set.\n"; 1778 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n"; 1779 1780 OS << " // Get the instruction mnemonic, which is the first token.\n"; 1781 OS << " StringRef Mnemonic = ((" << Target.getName() 1782 << "Operand*)Operands[0])->getToken();\n\n"; 1783 1784 if (HasMnemonicAliases) { 1785 OS << " // Process all MnemonicAliases to remap the mnemonic.\n"; 1786 OS << " ApplyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n"; 1787 } 1788 1789 // Emit code to compute the class list for this operand vector. 1790 OS << " // Eliminate obvious mismatches.\n"; 1791 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n"; 1792 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n"; 1793 OS << " return Match_InvalidOperand;\n"; 1794 OS << " }\n\n"; 1795 1796 OS << " // Compute the class list for this operand vector.\n"; 1797 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n"; 1798 OS << " for (unsigned i = 1, e = Operands.size(); i != e; ++i) {\n"; 1799 OS << " Classes[i-1] = ClassifyOperand(Operands[i]);\n\n"; 1800 1801 OS << " // Check for invalid operands before matching.\n"; 1802 OS << " if (Classes[i-1] == InvalidMatchClass) {\n"; 1803 OS << " ErrorInfo = i;\n"; 1804 OS << " return Match_InvalidOperand;\n"; 1805 OS << " }\n"; 1806 OS << " }\n\n"; 1807 1808 OS << " // Mark unused classes.\n"; 1809 OS << " for (unsigned i = Operands.size()-1, e = " << MaxNumOperands << "; " 1810 << "i != e; ++i)\n"; 1811 OS << " Classes[i] = InvalidMatchClass;\n\n"; 1812 1813 OS << " // Some state to try to produce better error messages.\n"; 1814 OS << " bool HadMatchOtherThanFeatures = false;\n\n"; 1815 OS << " // Set ErrorInfo to the operand that mismatches if it is \n"; 1816 OS << " // wrong for all instances of the instruction.\n"; 1817 OS << " ErrorInfo = ~0U;\n"; 1818 1819 // Emit code to search the table. 1820 OS << " // Search the table.\n"; 1821 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n"; 1822 OS << " std::equal_range(MatchTable, MatchTable+" 1823 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n"; 1824 1825 OS << " // Return a more specific error code if no mnemonics match.\n"; 1826 OS << " if (MnemonicRange.first == MnemonicRange.second)\n"; 1827 OS << " return Match_MnemonicFail;\n\n"; 1828 1829 OS << " for (const MatchEntry *it = MnemonicRange.first, " 1830 << "*ie = MnemonicRange.second;\n"; 1831 OS << " it != ie; ++it) {\n"; 1832 1833 OS << " // equal_range guarantees that instruction mnemonic matches.\n"; 1834 OS << " assert(Mnemonic == it->Mnemonic);\n"; 1835 1836 // Emit check that the subclasses match. 1837 OS << " bool OperandsValid = true;\n"; 1838 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n"; 1839 OS << " if (IsSubclass(Classes[i], it->Classes[i]))\n"; 1840 OS << " continue;\n"; 1841 OS << " // If this operand is broken for all of the instances of this\n"; 1842 OS << " // mnemonic, keep track of it so we can report loc info.\n"; 1843 OS << " if (it == MnemonicRange.first || ErrorInfo == i+1)\n"; 1844 OS << " ErrorInfo = i+1;\n"; 1845 OS << " else\n"; 1846 OS << " ErrorInfo = ~0U;"; 1847 OS << " // Otherwise, just reject this instance of the mnemonic.\n"; 1848 OS << " OperandsValid = false;\n"; 1849 OS << " break;\n"; 1850 OS << " }\n\n"; 1851 1852 OS << " if (!OperandsValid) continue;\n"; 1853 1854 // Emit check that the required features are available. 1855 OS << " if ((AvailableFeatures & it->RequiredFeatures) " 1856 << "!= it->RequiredFeatures) {\n"; 1857 OS << " HadMatchOtherThanFeatures = true;\n"; 1858 OS << " continue;\n"; 1859 OS << " }\n"; 1860 1861 OS << "\n"; 1862 OS << " ConvertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n"; 1863 1864 // Call the post-processing function, if used. 1865 std::string InsnCleanupFn = 1866 AsmParser->getValueAsString("AsmParserInstCleanup"); 1867 if (!InsnCleanupFn.empty()) 1868 OS << " " << InsnCleanupFn << "(Inst);\n"; 1869 1870 OS << " return Match_Success;\n"; 1871 OS << " }\n\n"; 1872 1873 OS << " // Okay, we had no match. Try to return a useful error code.\n"; 1874 OS << " if (HadMatchOtherThanFeatures) return Match_MissingFeature;\n"; 1875 OS << " return Match_InvalidOperand;\n"; 1876 OS << "}\n\n"; 1877 1878 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n"; 1879} 1880