AsmMatcherEmitter.cpp revision 63faf82d0377f0a878d643ca2aacc02c35811b3e
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. It also emits a matcher for 12// custom operand parsing. 13// 14// Converting assembly operands into MCInst structures 15// --------------------------------------------------- 16// 17// The input to the target specific matcher is a list of literal tokens and 18// operands. The target specific parser should generally eliminate any syntax 19// which is not relevant for matching; for example, comma tokens should have 20// already been consumed and eliminated by the parser. Most instructions will 21// end up with a single literal token (the instruction name) and some number of 22// operands. 23// 24// Some example inputs, for X86: 25// 'addl' (immediate ...) (register ...) 26// 'add' (immediate ...) (memory ...) 27// 'call' '*' %epc 28// 29// The assembly matcher is responsible for converting this input into a precise 30// machine instruction (i.e., an instruction with a well defined encoding). This 31// mapping has several properties which complicate matching: 32// 33// - It may be ambiguous; many architectures can legally encode particular 34// variants of an instruction in different ways (for example, using a smaller 35// encoding for small immediates). Such ambiguities should never be 36// arbitrarily resolved by the assembler, the assembler is always responsible 37// for choosing the "best" available instruction. 38// 39// - It may depend on the subtarget or the assembler context. Instructions 40// which are invalid for the current mode, but otherwise unambiguous (e.g., 41// an SSE instruction in a file being assembled for i486) should be accepted 42// and rejected by the assembler front end. However, if the proper encoding 43// for an instruction is dependent on the assembler context then the matcher 44// is responsible for selecting the correct machine instruction for the 45// current mode. 46// 47// The core matching algorithm attempts to exploit the regularity in most 48// instruction sets to quickly determine the set of possibly matching 49// instructions, and the simplify the generated code. Additionally, this helps 50// to ensure that the ambiguities are intentionally resolved by the user. 51// 52// The matching is divided into two distinct phases: 53// 54// 1. Classification: Each operand is mapped to the unique set which (a) 55// contains it, and (b) is the largest such subset for which a single 56// instruction could match all members. 57// 58// For register classes, we can generate these subgroups automatically. For 59// arbitrary operands, we expect the user to define the classes and their 60// relations to one another (for example, 8-bit signed immediates as a 61// subset of 32-bit immediates). 62// 63// By partitioning the operands in this way, we guarantee that for any 64// tuple of classes, any single instruction must match either all or none 65// of the sets of operands which could classify to that tuple. 66// 67// In addition, the subset relation amongst classes induces a partial order 68// on such tuples, which we use to resolve ambiguities. 69// 70// 2. The input can now be treated as a tuple of classes (static tokens are 71// simple singleton sets). Each such tuple should generally map to a single 72// instruction (we currently ignore cases where this isn't true, whee!!!), 73// which we can emit a simple matcher for. 74// 75// Custom Operand Parsing 76// ---------------------- 77// 78// Some targets need a custom way to parse operands, some specific instructions 79// can contain arguments that can represent processor flags and other kinds of 80// identifiers that need to be mapped to specific valeus in the final encoded 81// instructions. The target specific custom operand parsing works in the 82// following way: 83// 84// 1. A operand match table is built, each entry contains a mnemonic, an 85// operand class, a mask for all operand positions for that same 86// class/mnemonic and target features to be checked while trying to match. 87// 88// 2. The operand matcher will try every possible entry with the same 89// mnemonic and will check if the target feature for this mnemonic also 90// matches. After that, if the operand to be matched has its index 91// present in the mask, a successful match occurs. Otherwise, fallback 92// to the regular operand parsing. 93// 94// 3. For a match success, each operand class that has a 'ParserMethod' 95// becomes part of a switch from where the custom method is called. 96// 97//===----------------------------------------------------------------------===// 98 99#include "AsmMatcherEmitter.h" 100#include "CodeGenTarget.h" 101#include "StringMatcher.h" 102#include "llvm/ADT/OwningPtr.h" 103#include "llvm/ADT/PointerUnion.h" 104#include "llvm/ADT/SmallPtrSet.h" 105#include "llvm/ADT/SmallVector.h" 106#include "llvm/ADT/STLExtras.h" 107#include "llvm/ADT/StringExtras.h" 108#include "llvm/Support/CommandLine.h" 109#include "llvm/Support/Debug.h" 110#include "llvm/TableGen/Error.h" 111#include "llvm/TableGen/Record.h" 112#include <map> 113#include <set> 114using namespace llvm; 115 116static cl::opt<std::string> 117MatchPrefix("match-prefix", cl::init(""), 118 cl::desc("Only match instructions with the given prefix")); 119 120namespace { 121class AsmMatcherInfo; 122struct SubtargetFeatureInfo; 123 124/// ClassInfo - Helper class for storing the information about a particular 125/// class of operands which can be matched. 126struct ClassInfo { 127 enum ClassInfoKind { 128 /// Invalid kind, for use as a sentinel value. 129 Invalid = 0, 130 131 /// The class for a particular token. 132 Token, 133 134 /// The (first) register class, subsequent register classes are 135 /// RegisterClass0+1, and so on. 136 RegisterClass0, 137 138 /// The (first) user defined class, subsequent user defined classes are 139 /// UserClass0+1, and so on. 140 UserClass0 = 1<<16 141 }; 142 143 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 + 144 /// N) for the Nth user defined class. 145 unsigned Kind; 146 147 /// SuperClasses - The super classes of this class. Note that for simplicities 148 /// sake user operands only record their immediate super class, while register 149 /// operands include all superclasses. 150 std::vector<ClassInfo*> SuperClasses; 151 152 /// Name - The full class name, suitable for use in an enum. 153 std::string Name; 154 155 /// ClassName - The unadorned generic name for this class (e.g., Token). 156 std::string ClassName; 157 158 /// ValueName - The name of the value this class represents; for a token this 159 /// is the literal token string, for an operand it is the TableGen class (or 160 /// empty if this is a derived class). 161 std::string ValueName; 162 163 /// PredicateMethod - The name of the operand method to test whether the 164 /// operand matches this class; this is not valid for Token or register kinds. 165 std::string PredicateMethod; 166 167 /// RenderMethod - The name of the operand method to add this operand to an 168 /// MCInst; this is not valid for Token or register kinds. 169 std::string RenderMethod; 170 171 /// ParserMethod - The name of the operand method to do a target specific 172 /// parsing on the operand. 173 std::string ParserMethod; 174 175 /// For register classes, the records for all the registers in this class. 176 std::set<Record*> Registers; 177 178public: 179 /// isRegisterClass() - Check if this is a register class. 180 bool isRegisterClass() const { 181 return Kind >= RegisterClass0 && Kind < UserClass0; 182 } 183 184 /// isUserClass() - Check if this is a user defined class. 185 bool isUserClass() const { 186 return Kind >= UserClass0; 187 } 188 189 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes 190 /// are related if they are in the same class hierarchy. 191 bool isRelatedTo(const ClassInfo &RHS) const { 192 // Tokens are only related to tokens. 193 if (Kind == Token || RHS.Kind == Token) 194 return Kind == Token && RHS.Kind == Token; 195 196 // Registers classes are only related to registers classes, and only if 197 // their intersection is non-empty. 198 if (isRegisterClass() || RHS.isRegisterClass()) { 199 if (!isRegisterClass() || !RHS.isRegisterClass()) 200 return false; 201 202 std::set<Record*> Tmp; 203 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin()); 204 std::set_intersection(Registers.begin(), Registers.end(), 205 RHS.Registers.begin(), RHS.Registers.end(), 206 II); 207 208 return !Tmp.empty(); 209 } 210 211 // Otherwise we have two users operands; they are related if they are in the 212 // same class hierarchy. 213 // 214 // FIXME: This is an oversimplification, they should only be related if they 215 // intersect, however we don't have that information. 216 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!"); 217 const ClassInfo *Root = this; 218 while (!Root->SuperClasses.empty()) 219 Root = Root->SuperClasses.front(); 220 221 const ClassInfo *RHSRoot = &RHS; 222 while (!RHSRoot->SuperClasses.empty()) 223 RHSRoot = RHSRoot->SuperClasses.front(); 224 225 return Root == RHSRoot; 226 } 227 228 /// isSubsetOf - Test whether this class is a subset of \arg RHS; 229 bool isSubsetOf(const ClassInfo &RHS) const { 230 // This is a subset of RHS if it is the same class... 231 if (this == &RHS) 232 return true; 233 234 // ... or if any of its super classes are a subset of RHS. 235 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(), 236 ie = SuperClasses.end(); it != ie; ++it) 237 if ((*it)->isSubsetOf(RHS)) 238 return true; 239 240 return false; 241 } 242 243 /// operator< - Compare two classes. 244 bool operator<(const ClassInfo &RHS) const { 245 if (this == &RHS) 246 return false; 247 248 // Unrelated classes can be ordered by kind. 249 if (!isRelatedTo(RHS)) 250 return Kind < RHS.Kind; 251 252 switch (Kind) { 253 case Invalid: 254 assert(0 && "Invalid kind!"); 255 256 default: 257 // This class precedes the RHS if it is a proper subset of the RHS. 258 if (isSubsetOf(RHS)) 259 return true; 260 if (RHS.isSubsetOf(*this)) 261 return false; 262 263 // Otherwise, order by name to ensure we have a total ordering. 264 return ValueName < RHS.ValueName; 265 } 266 } 267}; 268 269/// MatchableInfo - Helper class for storing the necessary information for an 270/// instruction or alias which is capable of being matched. 271struct MatchableInfo { 272 struct AsmOperand { 273 /// Token - This is the token that the operand came from. 274 StringRef Token; 275 276 /// The unique class instance this operand should match. 277 ClassInfo *Class; 278 279 /// The operand name this is, if anything. 280 StringRef SrcOpName; 281 282 /// The suboperand index within SrcOpName, or -1 for the entire operand. 283 int SubOpIdx; 284 285 /// Register record if this token is singleton register. 286 Record *SingletonReg; 287 288 explicit AsmOperand(StringRef T) : Token(T), Class(0), SubOpIdx(-1), 289 SingletonReg(0) {} 290 }; 291 292 /// ResOperand - This represents a single operand in the result instruction 293 /// generated by the match. In cases (like addressing modes) where a single 294 /// assembler operand expands to multiple MCOperands, this represents the 295 /// single assembler operand, not the MCOperand. 296 struct ResOperand { 297 enum { 298 /// RenderAsmOperand - This represents an operand result that is 299 /// generated by calling the render method on the assembly operand. The 300 /// corresponding AsmOperand is specified by AsmOperandNum. 301 RenderAsmOperand, 302 303 /// TiedOperand - This represents a result operand that is a duplicate of 304 /// a previous result operand. 305 TiedOperand, 306 307 /// ImmOperand - This represents an immediate value that is dumped into 308 /// the operand. 309 ImmOperand, 310 311 /// RegOperand - This represents a fixed register that is dumped in. 312 RegOperand 313 } Kind; 314 315 union { 316 /// This is the operand # in the AsmOperands list that this should be 317 /// copied from. 318 unsigned AsmOperandNum; 319 320 /// TiedOperandNum - This is the (earlier) result operand that should be 321 /// copied from. 322 unsigned TiedOperandNum; 323 324 /// ImmVal - This is the immediate value added to the instruction. 325 int64_t ImmVal; 326 327 /// Register - This is the register record. 328 Record *Register; 329 }; 330 331 /// MINumOperands - The number of MCInst operands populated by this 332 /// operand. 333 unsigned MINumOperands; 334 335 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) { 336 ResOperand X; 337 X.Kind = RenderAsmOperand; 338 X.AsmOperandNum = AsmOpNum; 339 X.MINumOperands = NumOperands; 340 return X; 341 } 342 343 static ResOperand getTiedOp(unsigned TiedOperandNum) { 344 ResOperand X; 345 X.Kind = TiedOperand; 346 X.TiedOperandNum = TiedOperandNum; 347 X.MINumOperands = 1; 348 return X; 349 } 350 351 static ResOperand getImmOp(int64_t Val) { 352 ResOperand X; 353 X.Kind = ImmOperand; 354 X.ImmVal = Val; 355 X.MINumOperands = 1; 356 return X; 357 } 358 359 static ResOperand getRegOp(Record *Reg) { 360 ResOperand X; 361 X.Kind = RegOperand; 362 X.Register = Reg; 363 X.MINumOperands = 1; 364 return X; 365 } 366 }; 367 368 /// TheDef - This is the definition of the instruction or InstAlias that this 369 /// matchable came from. 370 Record *const TheDef; 371 372 /// DefRec - This is the definition that it came from. 373 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec; 374 375 const CodeGenInstruction *getResultInst() const { 376 if (DefRec.is<const CodeGenInstruction*>()) 377 return DefRec.get<const CodeGenInstruction*>(); 378 return DefRec.get<const CodeGenInstAlias*>()->ResultInst; 379 } 380 381 /// ResOperands - This is the operand list that should be built for the result 382 /// MCInst. 383 std::vector<ResOperand> ResOperands; 384 385 /// AsmString - The assembly string for this instruction (with variants 386 /// removed), e.g. "movsx $src, $dst". 387 std::string AsmString; 388 389 /// Mnemonic - This is the first token of the matched instruction, its 390 /// mnemonic. 391 StringRef Mnemonic; 392 393 /// AsmOperands - The textual operands that this instruction matches, 394 /// annotated with a class and where in the OperandList they were defined. 395 /// This directly corresponds to the tokenized AsmString after the mnemonic is 396 /// removed. 397 SmallVector<AsmOperand, 4> AsmOperands; 398 399 /// Predicates - The required subtarget features to match this instruction. 400 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures; 401 402 /// ConversionFnKind - The enum value which is passed to the generated 403 /// ConvertToMCInst to convert parsed operands into an MCInst for this 404 /// function. 405 std::string ConversionFnKind; 406 407 MatchableInfo(const CodeGenInstruction &CGI) 408 : TheDef(CGI.TheDef), DefRec(&CGI), AsmString(CGI.AsmString) { 409 } 410 411 MatchableInfo(const CodeGenInstAlias *Alias) 412 : TheDef(Alias->TheDef), DefRec(Alias), AsmString(Alias->AsmString) { 413 } 414 415 void Initialize(const AsmMatcherInfo &Info, 416 SmallPtrSet<Record*, 16> &SingletonRegisters, 417 int AsmVariantNo, std::string &RegisterPrefix); 418 419 /// Validate - Return true if this matchable is a valid thing to match against 420 /// and perform a bunch of validity checking. 421 bool Validate(StringRef CommentDelimiter, bool Hack) const; 422 423 /// extractSingletonRegisterForAsmOperand - Extract singleton register, 424 /// if present, from specified token. 425 void 426 extractSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info, 427 std::string &RegisterPrefix); 428 429 /// FindAsmOperand - Find the AsmOperand with the specified name and 430 /// suboperand index. 431 int FindAsmOperand(StringRef N, int SubOpIdx) const { 432 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) 433 if (N == AsmOperands[i].SrcOpName && 434 SubOpIdx == AsmOperands[i].SubOpIdx) 435 return i; 436 return -1; 437 } 438 439 /// FindAsmOperandNamed - Find the first AsmOperand with the specified name. 440 /// This does not check the suboperand index. 441 int FindAsmOperandNamed(StringRef N) const { 442 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) 443 if (N == AsmOperands[i].SrcOpName) 444 return i; 445 return -1; 446 } 447 448 void BuildInstructionResultOperands(); 449 void BuildAliasResultOperands(); 450 451 /// operator< - Compare two matchables. 452 bool operator<(const MatchableInfo &RHS) const { 453 // The primary comparator is the instruction mnemonic. 454 if (Mnemonic != RHS.Mnemonic) 455 return Mnemonic < RHS.Mnemonic; 456 457 if (AsmOperands.size() != RHS.AsmOperands.size()) 458 return AsmOperands.size() < RHS.AsmOperands.size(); 459 460 // Compare lexicographically by operand. The matcher validates that other 461 // orderings wouldn't be ambiguous using \see CouldMatchAmbiguouslyWith(). 462 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 463 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class) 464 return true; 465 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class) 466 return false; 467 } 468 469 return false; 470 } 471 472 /// CouldMatchAmbiguouslyWith - Check whether this matchable could 473 /// ambiguously match the same set of operands as \arg RHS (without being a 474 /// strictly superior match). 475 bool CouldMatchAmbiguouslyWith(const MatchableInfo &RHS) { 476 // The primary comparator is the instruction mnemonic. 477 if (Mnemonic != RHS.Mnemonic) 478 return false; 479 480 // The number of operands is unambiguous. 481 if (AsmOperands.size() != RHS.AsmOperands.size()) 482 return false; 483 484 // Otherwise, make sure the ordering of the two instructions is unambiguous 485 // by checking that either (a) a token or operand kind discriminates them, 486 // or (b) the ordering among equivalent kinds is consistent. 487 488 // Tokens and operand kinds are unambiguous (assuming a correct target 489 // specific parser). 490 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) 491 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind || 492 AsmOperands[i].Class->Kind == ClassInfo::Token) 493 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class || 494 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class) 495 return false; 496 497 // Otherwise, this operand could commute if all operands are equivalent, or 498 // there is a pair of operands that compare less than and a pair that 499 // compare greater than. 500 bool HasLT = false, HasGT = false; 501 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 502 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class) 503 HasLT = true; 504 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class) 505 HasGT = true; 506 } 507 508 return !(HasLT ^ HasGT); 509 } 510 511 void dump(); 512 513private: 514 void TokenizeAsmString(const AsmMatcherInfo &Info); 515}; 516 517/// SubtargetFeatureInfo - Helper class for storing information on a subtarget 518/// feature which participates in instruction matching. 519struct SubtargetFeatureInfo { 520 /// \brief The predicate record for this feature. 521 Record *TheDef; 522 523 /// \brief An unique index assigned to represent this feature. 524 unsigned Index; 525 526 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {} 527 528 /// \brief The name of the enumerated constant identifying this feature. 529 std::string getEnumName() const { 530 return "Feature_" + TheDef->getName(); 531 } 532}; 533 534struct OperandMatchEntry { 535 unsigned OperandMask; 536 MatchableInfo* MI; 537 ClassInfo *CI; 538 539 static OperandMatchEntry Create(MatchableInfo* mi, ClassInfo *ci, 540 unsigned opMask) { 541 OperandMatchEntry X; 542 X.OperandMask = opMask; 543 X.CI = ci; 544 X.MI = mi; 545 return X; 546 } 547}; 548 549 550class AsmMatcherInfo { 551public: 552 /// Tracked Records 553 RecordKeeper &Records; 554 555 /// The tablegen AsmParser record. 556 Record *AsmParser; 557 558 /// Target - The target information. 559 CodeGenTarget &Target; 560 561 /// The classes which are needed for matching. 562 std::vector<ClassInfo*> Classes; 563 564 /// The information on the matchables to match. 565 std::vector<MatchableInfo*> Matchables; 566 567 /// Info for custom matching operands by user defined methods. 568 std::vector<OperandMatchEntry> OperandMatchInfo; 569 570 /// Map of Register records to their class information. 571 std::map<Record*, ClassInfo*> RegisterClasses; 572 573 /// Map of Predicate records to their subtarget information. 574 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures; 575 576private: 577 /// Map of token to class information which has already been constructed. 578 std::map<std::string, ClassInfo*> TokenClasses; 579 580 /// Map of RegisterClass records to their class information. 581 std::map<Record*, ClassInfo*> RegisterClassClasses; 582 583 /// Map of AsmOperandClass records to their class information. 584 std::map<Record*, ClassInfo*> AsmOperandClasses; 585 586private: 587 /// getTokenClass - Lookup or create the class for the given token. 588 ClassInfo *getTokenClass(StringRef Token); 589 590 /// getOperandClass - Lookup or create the class for the given operand. 591 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI, 592 int SubOpIdx); 593 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx); 594 595 /// BuildRegisterClasses - Build the ClassInfo* instances for register 596 /// classes. 597 void BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters); 598 599 /// BuildOperandClasses - Build the ClassInfo* instances for user defined 600 /// operand classes. 601 void BuildOperandClasses(); 602 603 void BuildInstructionOperandReference(MatchableInfo *II, StringRef OpName, 604 unsigned AsmOpIdx); 605 void BuildAliasOperandReference(MatchableInfo *II, StringRef OpName, 606 MatchableInfo::AsmOperand &Op); 607 608public: 609 AsmMatcherInfo(Record *AsmParser, 610 CodeGenTarget &Target, 611 RecordKeeper &Records); 612 613 /// BuildInfo - Construct the various tables used during matching. 614 void BuildInfo(); 615 616 /// BuildOperandMatchInfo - Build the necessary information to handle user 617 /// defined operand parsing methods. 618 void BuildOperandMatchInfo(); 619 620 /// getSubtargetFeature - Lookup or create the subtarget feature info for the 621 /// given operand. 622 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const { 623 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!"); 624 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I = 625 SubtargetFeatures.find(Def); 626 return I == SubtargetFeatures.end() ? 0 : I->second; 627 } 628 629 RecordKeeper &getRecords() const { 630 return Records; 631 } 632}; 633 634} 635 636void MatchableInfo::dump() { 637 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n"; 638 639 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 640 AsmOperand &Op = AsmOperands[i]; 641 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - "; 642 errs() << '\"' << Op.Token << "\"\n"; 643 } 644} 645 646void MatchableInfo::Initialize(const AsmMatcherInfo &Info, 647 SmallPtrSet<Record*, 16> &SingletonRegisters, 648 int AsmVariantNo, std::string &RegisterPrefix) { 649 // TODO: Eventually support asmparser for Variant != 0. 650 AsmString = 651 CodeGenInstruction::FlattenAsmStringVariants(AsmString, AsmVariantNo); 652 653 TokenizeAsmString(Info); 654 655 // Compute the require features. 656 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates"); 657 for (unsigned i = 0, e = Predicates.size(); i != e; ++i) 658 if (SubtargetFeatureInfo *Feature = 659 Info.getSubtargetFeature(Predicates[i])) 660 RequiredFeatures.push_back(Feature); 661 662 // Collect singleton registers, if used. 663 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 664 extractSingletonRegisterForAsmOperand(i, Info, RegisterPrefix); 665 if (Record *Reg = AsmOperands[i].SingletonReg) 666 SingletonRegisters.insert(Reg); 667 } 668} 669 670/// TokenizeAsmString - Tokenize a simplified assembly string. 671void MatchableInfo::TokenizeAsmString(const AsmMatcherInfo &Info) { 672 StringRef String = AsmString; 673 unsigned Prev = 0; 674 bool InTok = true; 675 for (unsigned i = 0, e = String.size(); i != e; ++i) { 676 switch (String[i]) { 677 case '[': 678 case ']': 679 case '*': 680 case '!': 681 case ' ': 682 case '\t': 683 case ',': 684 if (InTok) { 685 AsmOperands.push_back(AsmOperand(String.slice(Prev, i))); 686 InTok = false; 687 } 688 if (!isspace(String[i]) && String[i] != ',') 689 AsmOperands.push_back(AsmOperand(String.substr(i, 1))); 690 Prev = i + 1; 691 break; 692 693 case '\\': 694 if (InTok) { 695 AsmOperands.push_back(AsmOperand(String.slice(Prev, i))); 696 InTok = false; 697 } 698 ++i; 699 assert(i != String.size() && "Invalid quoted character"); 700 AsmOperands.push_back(AsmOperand(String.substr(i, 1))); 701 Prev = i + 1; 702 break; 703 704 case '$': { 705 if (InTok) { 706 AsmOperands.push_back(AsmOperand(String.slice(Prev, i))); 707 InTok = false; 708 } 709 710 // If this isn't "${", treat like a normal token. 711 if (i + 1 == String.size() || String[i + 1] != '{') { 712 Prev = i; 713 break; 714 } 715 716 StringRef::iterator End = std::find(String.begin() + i, String.end(),'}'); 717 assert(End != String.end() && "Missing brace in operand reference!"); 718 size_t EndPos = End - String.begin(); 719 AsmOperands.push_back(AsmOperand(String.slice(i, EndPos+1))); 720 Prev = EndPos + 1; 721 i = EndPos; 722 break; 723 } 724 725 case '.': 726 if (InTok) 727 AsmOperands.push_back(AsmOperand(String.slice(Prev, i))); 728 Prev = i; 729 InTok = true; 730 break; 731 732 default: 733 InTok = true; 734 } 735 } 736 if (InTok && Prev != String.size()) 737 AsmOperands.push_back(AsmOperand(String.substr(Prev))); 738 739 // The first token of the instruction is the mnemonic, which must be a 740 // simple string, not a $foo variable or a singleton register. 741 if (AsmOperands.empty()) 742 throw TGError(TheDef->getLoc(), 743 "Instruction '" + TheDef->getName() + "' has no tokens"); 744 Mnemonic = AsmOperands[0].Token; 745 // FIXME : Check and raise an error if it is a register. 746 if (Mnemonic[0] == '$') 747 throw TGError(TheDef->getLoc(), 748 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!"); 749 750 // Remove the first operand, it is tracked in the mnemonic field. 751 AsmOperands.erase(AsmOperands.begin()); 752} 753 754bool MatchableInfo::Validate(StringRef CommentDelimiter, bool Hack) const { 755 // Reject matchables with no .s string. 756 if (AsmString.empty()) 757 throw TGError(TheDef->getLoc(), "instruction with empty asm string"); 758 759 // Reject any matchables with a newline in them, they should be marked 760 // isCodeGenOnly if they are pseudo instructions. 761 if (AsmString.find('\n') != std::string::npos) 762 throw TGError(TheDef->getLoc(), 763 "multiline instruction is not valid for the asmparser, " 764 "mark it isCodeGenOnly"); 765 766 // Remove comments from the asm string. We know that the asmstring only 767 // has one line. 768 if (!CommentDelimiter.empty() && 769 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos) 770 throw TGError(TheDef->getLoc(), 771 "asmstring for instruction has comment character in it, " 772 "mark it isCodeGenOnly"); 773 774 // Reject matchables with operand modifiers, these aren't something we can 775 // handle, the target should be refactored to use operands instead of 776 // modifiers. 777 // 778 // Also, check for instructions which reference the operand multiple times; 779 // this implies a constraint we would not honor. 780 std::set<std::string> OperandNames; 781 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) { 782 StringRef Tok = AsmOperands[i].Token; 783 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos) 784 throw TGError(TheDef->getLoc(), 785 "matchable with operand modifier '" + Tok.str() + 786 "' not supported by asm matcher. Mark isCodeGenOnly!"); 787 788 // Verify that any operand is only mentioned once. 789 // We reject aliases and ignore instructions for now. 790 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) { 791 if (!Hack) 792 throw TGError(TheDef->getLoc(), 793 "ERROR: matchable with tied operand '" + Tok.str() + 794 "' can never be matched!"); 795 // FIXME: Should reject these. The ARM backend hits this with $lane in a 796 // bunch of instructions. It is unclear what the right answer is. 797 DEBUG({ 798 errs() << "warning: '" << TheDef->getName() << "': " 799 << "ignoring instruction with tied operand '" 800 << Tok.str() << "'\n"; 801 }); 802 return false; 803 } 804 } 805 806 return true; 807} 808 809/// extractSingletonRegisterForAsmOperand - Extract singleton register, if present, 810/// from specified token. 811void MatchableInfo:: 812extractSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info, 813 std::string &RegisterPrefix) { 814 StringRef Tok = AsmOperands[i].Token; 815 if (RegisterPrefix.empty()) { 816 if (i) { 817 std::string LoweredTok = Tok.lower(); 818 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok)) 819 AsmOperands[i].SingletonReg = Reg->TheDef; 820 } else 821 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(Tok)) 822 AsmOperands[i].SingletonReg = Reg->TheDef; 823 return; 824 } 825 826 if (!Tok.startswith(RegisterPrefix)) 827 return; 828 829 StringRef RegName = Tok.substr(RegisterPrefix.size()); 830 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName)) 831 AsmOperands[i].SingletonReg = Reg->TheDef; 832 833 // If there is no register prefix (i.e. "%" in "%eax"), then this may 834 // be some random non-register token, just ignore it. 835 return; 836} 837 838static std::string getEnumNameForToken(StringRef Str) { 839 std::string Res; 840 841 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) { 842 switch (*it) { 843 case '*': Res += "_STAR_"; break; 844 case '%': Res += "_PCT_"; break; 845 case ':': Res += "_COLON_"; break; 846 case '!': Res += "_EXCLAIM_"; break; 847 case '.': Res += "_DOT_"; break; 848 default: 849 if (isalnum(*it)) 850 Res += *it; 851 else 852 Res += "_" + utostr((unsigned) *it) + "_"; 853 } 854 } 855 856 return Res; 857} 858 859ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) { 860 ClassInfo *&Entry = TokenClasses[Token]; 861 862 if (!Entry) { 863 Entry = new ClassInfo(); 864 Entry->Kind = ClassInfo::Token; 865 Entry->ClassName = "Token"; 866 Entry->Name = "MCK_" + getEnumNameForToken(Token); 867 Entry->ValueName = Token; 868 Entry->PredicateMethod = "<invalid>"; 869 Entry->RenderMethod = "<invalid>"; 870 Entry->ParserMethod = ""; 871 Classes.push_back(Entry); 872 } 873 874 return Entry; 875} 876 877ClassInfo * 878AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI, 879 int SubOpIdx) { 880 Record *Rec = OI.Rec; 881 if (SubOpIdx != -1) 882 Rec = dynamic_cast<DefInit*>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef(); 883 return getOperandClass(Rec, SubOpIdx); 884} 885 886ClassInfo * 887AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) { 888 if (Rec->isSubClassOf("RegisterOperand")) { 889 // RegisterOperand may have an associated ParserMatchClass. If it does, 890 // use it, else just fall back to the underlying register class. 891 const RecordVal *R = Rec->getValue("ParserMatchClass"); 892 if (R == 0 || R->getValue() == 0) 893 throw "Record `" + Rec->getName() + 894 "' does not have a ParserMatchClass!\n"; 895 896 if (DefInit *DI= dynamic_cast<DefInit*>(R->getValue())) { 897 Record *MatchClass = DI->getDef(); 898 if (ClassInfo *CI = AsmOperandClasses[MatchClass]) 899 return CI; 900 } 901 902 // No custom match class. Just use the register class. 903 Record *ClassRec = Rec->getValueAsDef("RegClass"); 904 if (!ClassRec) 905 throw TGError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() + 906 "' has no associated register class!\n"); 907 if (ClassInfo *CI = RegisterClassClasses[ClassRec]) 908 return CI; 909 throw TGError(Rec->getLoc(), "register class has no class info!"); 910 } 911 912 913 if (Rec->isSubClassOf("RegisterClass")) { 914 if (ClassInfo *CI = RegisterClassClasses[Rec]) 915 return CI; 916 throw TGError(Rec->getLoc(), "register class has no class info!"); 917 } 918 919 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!"); 920 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass"); 921 if (ClassInfo *CI = AsmOperandClasses[MatchClass]) 922 return CI; 923 924 throw TGError(Rec->getLoc(), "operand has no match class!"); 925} 926 927void AsmMatcherInfo:: 928BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) { 929 const std::vector<CodeGenRegister*> &Registers = 930 Target.getRegBank().getRegisters(); 931 ArrayRef<CodeGenRegisterClass*> RegClassList = 932 Target.getRegBank().getRegClasses(); 933 934 // The register sets used for matching. 935 std::set< std::set<Record*> > RegisterSets; 936 937 // Gather the defined sets. 938 for (ArrayRef<CodeGenRegisterClass*>::const_iterator it = 939 RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) 940 RegisterSets.insert(std::set<Record*>( 941 (*it)->getOrder().begin(), (*it)->getOrder().end())); 942 943 // Add any required singleton sets. 944 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(), 945 ie = SingletonRegisters.end(); it != ie; ++it) { 946 Record *Rec = *it; 947 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1)); 948 } 949 950 // Introduce derived sets where necessary (when a register does not determine 951 // a unique register set class), and build the mapping of registers to the set 952 // they should classify to. 953 std::map<Record*, std::set<Record*> > RegisterMap; 954 for (std::vector<CodeGenRegister*>::const_iterator it = Registers.begin(), 955 ie = Registers.end(); it != ie; ++it) { 956 const CodeGenRegister &CGR = **it; 957 // Compute the intersection of all sets containing this register. 958 std::set<Record*> ContainingSet; 959 960 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(), 961 ie = RegisterSets.end(); it != ie; ++it) { 962 if (!it->count(CGR.TheDef)) 963 continue; 964 965 if (ContainingSet.empty()) { 966 ContainingSet = *it; 967 continue; 968 } 969 970 std::set<Record*> Tmp; 971 std::swap(Tmp, ContainingSet); 972 std::insert_iterator< std::set<Record*> > II(ContainingSet, 973 ContainingSet.begin()); 974 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(), II); 975 } 976 977 if (!ContainingSet.empty()) { 978 RegisterSets.insert(ContainingSet); 979 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet)); 980 } 981 } 982 983 // Construct the register classes. 984 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses; 985 unsigned Index = 0; 986 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(), 987 ie = RegisterSets.end(); it != ie; ++it, ++Index) { 988 ClassInfo *CI = new ClassInfo(); 989 CI->Kind = ClassInfo::RegisterClass0 + Index; 990 CI->ClassName = "Reg" + utostr(Index); 991 CI->Name = "MCK_Reg" + utostr(Index); 992 CI->ValueName = ""; 993 CI->PredicateMethod = ""; // unused 994 CI->RenderMethod = "addRegOperands"; 995 CI->Registers = *it; 996 Classes.push_back(CI); 997 RegisterSetClasses.insert(std::make_pair(*it, CI)); 998 } 999 1000 // Find the superclasses; we could compute only the subgroup lattice edges, 1001 // but there isn't really a point. 1002 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(), 1003 ie = RegisterSets.end(); it != ie; ++it) { 1004 ClassInfo *CI = RegisterSetClasses[*it]; 1005 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(), 1006 ie2 = RegisterSets.end(); it2 != ie2; ++it2) 1007 if (*it != *it2 && 1008 std::includes(it2->begin(), it2->end(), it->begin(), it->end())) 1009 CI->SuperClasses.push_back(RegisterSetClasses[*it2]); 1010 } 1011 1012 // Name the register classes which correspond to a user defined RegisterClass. 1013 for (ArrayRef<CodeGenRegisterClass*>::const_iterator 1014 it = RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) { 1015 const CodeGenRegisterClass &RC = **it; 1016 // Def will be NULL for non-user defined register classes. 1017 Record *Def = RC.getDef(); 1018 if (!Def) 1019 continue; 1020 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(RC.getOrder().begin(), 1021 RC.getOrder().end())]; 1022 if (CI->ValueName.empty()) { 1023 CI->ClassName = RC.getName(); 1024 CI->Name = "MCK_" + RC.getName(); 1025 CI->ValueName = RC.getName(); 1026 } else 1027 CI->ValueName = CI->ValueName + "," + RC.getName(); 1028 1029 RegisterClassClasses.insert(std::make_pair(Def, CI)); 1030 } 1031 1032 // Populate the map for individual registers. 1033 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(), 1034 ie = RegisterMap.end(); it != ie; ++it) 1035 RegisterClasses[it->first] = RegisterSetClasses[it->second]; 1036 1037 // Name the register classes which correspond to singleton registers. 1038 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(), 1039 ie = SingletonRegisters.end(); it != ie; ++it) { 1040 Record *Rec = *it; 1041 ClassInfo *CI = RegisterClasses[Rec]; 1042 assert(CI && "Missing singleton register class info!"); 1043 1044 if (CI->ValueName.empty()) { 1045 CI->ClassName = Rec->getName(); 1046 CI->Name = "MCK_" + Rec->getName(); 1047 CI->ValueName = Rec->getName(); 1048 } else 1049 CI->ValueName = CI->ValueName + "," + Rec->getName(); 1050 } 1051} 1052 1053void AsmMatcherInfo::BuildOperandClasses() { 1054 std::vector<Record*> AsmOperands = 1055 Records.getAllDerivedDefinitions("AsmOperandClass"); 1056 1057 // Pre-populate AsmOperandClasses map. 1058 for (std::vector<Record*>::iterator it = AsmOperands.begin(), 1059 ie = AsmOperands.end(); it != ie; ++it) 1060 AsmOperandClasses[*it] = new ClassInfo(); 1061 1062 unsigned Index = 0; 1063 for (std::vector<Record*>::iterator it = AsmOperands.begin(), 1064 ie = AsmOperands.end(); it != ie; ++it, ++Index) { 1065 ClassInfo *CI = AsmOperandClasses[*it]; 1066 CI->Kind = ClassInfo::UserClass0 + Index; 1067 1068 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses"); 1069 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) { 1070 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i)); 1071 if (!DI) { 1072 PrintError((*it)->getLoc(), "Invalid super class reference!"); 1073 continue; 1074 } 1075 1076 ClassInfo *SC = AsmOperandClasses[DI->getDef()]; 1077 if (!SC) 1078 PrintError((*it)->getLoc(), "Invalid super class reference!"); 1079 else 1080 CI->SuperClasses.push_back(SC); 1081 } 1082 CI->ClassName = (*it)->getValueAsString("Name"); 1083 CI->Name = "MCK_" + CI->ClassName; 1084 CI->ValueName = (*it)->getName(); 1085 1086 // Get or construct the predicate method name. 1087 Init *PMName = (*it)->getValueInit("PredicateMethod"); 1088 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) { 1089 CI->PredicateMethod = SI->getValue(); 1090 } else { 1091 assert(dynamic_cast<UnsetInit*>(PMName) && 1092 "Unexpected PredicateMethod field!"); 1093 CI->PredicateMethod = "is" + CI->ClassName; 1094 } 1095 1096 // Get or construct the render method name. 1097 Init *RMName = (*it)->getValueInit("RenderMethod"); 1098 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) { 1099 CI->RenderMethod = SI->getValue(); 1100 } else { 1101 assert(dynamic_cast<UnsetInit*>(RMName) && 1102 "Unexpected RenderMethod field!"); 1103 CI->RenderMethod = "add" + CI->ClassName + "Operands"; 1104 } 1105 1106 // Get the parse method name or leave it as empty. 1107 Init *PRMName = (*it)->getValueInit("ParserMethod"); 1108 if (StringInit *SI = dynamic_cast<StringInit*>(PRMName)) 1109 CI->ParserMethod = SI->getValue(); 1110 1111 AsmOperandClasses[*it] = CI; 1112 Classes.push_back(CI); 1113 } 1114} 1115 1116AsmMatcherInfo::AsmMatcherInfo(Record *asmParser, 1117 CodeGenTarget &target, 1118 RecordKeeper &records) 1119 : Records(records), AsmParser(asmParser), Target(target) { 1120} 1121 1122/// BuildOperandMatchInfo - Build the necessary information to handle user 1123/// defined operand parsing methods. 1124void AsmMatcherInfo::BuildOperandMatchInfo() { 1125 1126 /// Map containing a mask with all operands indicies that can be found for 1127 /// that class inside a instruction. 1128 std::map<ClassInfo*, unsigned> OpClassMask; 1129 1130 for (std::vector<MatchableInfo*>::const_iterator it = 1131 Matchables.begin(), ie = Matchables.end(); 1132 it != ie; ++it) { 1133 MatchableInfo &II = **it; 1134 OpClassMask.clear(); 1135 1136 // Keep track of all operands of this instructions which belong to the 1137 // same class. 1138 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) { 1139 MatchableInfo::AsmOperand &Op = II.AsmOperands[i]; 1140 if (Op.Class->ParserMethod.empty()) 1141 continue; 1142 unsigned &OperandMask = OpClassMask[Op.Class]; 1143 OperandMask |= (1 << i); 1144 } 1145 1146 // Generate operand match info for each mnemonic/operand class pair. 1147 for (std::map<ClassInfo*, unsigned>::iterator iit = OpClassMask.begin(), 1148 iie = OpClassMask.end(); iit != iie; ++iit) { 1149 unsigned OpMask = iit->second; 1150 ClassInfo *CI = iit->first; 1151 OperandMatchInfo.push_back(OperandMatchEntry::Create(&II, CI, OpMask)); 1152 } 1153 } 1154} 1155 1156void AsmMatcherInfo::BuildInfo() { 1157 // Build information about all of the AssemblerPredicates. 1158 std::vector<Record*> AllPredicates = 1159 Records.getAllDerivedDefinitions("Predicate"); 1160 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) { 1161 Record *Pred = AllPredicates[i]; 1162 // Ignore predicates that are not intended for the assembler. 1163 if (!Pred->getValueAsBit("AssemblerMatcherPredicate")) 1164 continue; 1165 1166 if (Pred->getName().empty()) 1167 throw TGError(Pred->getLoc(), "Predicate has no name!"); 1168 1169 unsigned FeatureNo = SubtargetFeatures.size(); 1170 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo); 1171 assert(FeatureNo < 32 && "Too many subtarget features!"); 1172 } 1173 1174 std::string CommentDelimiter = AsmParser->getValueAsString("CommentDelimiter"); 1175 std::string RegisterPrefix = AsmParser->getValueAsString("RegisterPrefix"); 1176 int AsmVariantNo = AsmParser->getValueAsInt("Variant"); 1177 1178 // Parse the instructions; we need to do this first so that we can gather the 1179 // singleton register classes. 1180 SmallPtrSet<Record*, 16> SingletonRegisters; 1181 for (CodeGenTarget::inst_iterator I = Target.inst_begin(), 1182 E = Target.inst_end(); I != E; ++I) { 1183 const CodeGenInstruction &CGI = **I; 1184 1185 // If the tblgen -match-prefix option is specified (for tblgen hackers), 1186 // filter the set of instructions we consider. 1187 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix)) 1188 continue; 1189 1190 // Ignore "codegen only" instructions. 1191 if (CGI.TheDef->getValueAsBit("isCodeGenOnly")) 1192 continue; 1193 1194 // Validate the operand list to ensure we can handle this instruction. 1195 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) { 1196 const CGIOperandList::OperandInfo &OI = CGI.Operands[i]; 1197 1198 // Validate tied operands. 1199 if (OI.getTiedRegister() != -1) { 1200 // If we have a tied operand that consists of multiple MCOperands, 1201 // reject it. We reject aliases and ignore instructions for now. 1202 if (OI.MINumOperands != 1) { 1203 // FIXME: Should reject these. The ARM backend hits this with $lane 1204 // in a bunch of instructions. It is unclear what the right answer is. 1205 DEBUG({ 1206 errs() << "warning: '" << CGI.TheDef->getName() << "': " 1207 << "ignoring instruction with multi-operand tied operand '" 1208 << OI.Name << "'\n"; 1209 }); 1210 continue; 1211 } 1212 } 1213 } 1214 1215 OwningPtr<MatchableInfo> II(new MatchableInfo(CGI)); 1216 1217 II->Initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix); 1218 1219 // Ignore instructions which shouldn't be matched and diagnose invalid 1220 // instruction definitions with an error. 1221 if (!II->Validate(CommentDelimiter, true)) 1222 continue; 1223 1224 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases. 1225 // 1226 // FIXME: This is a total hack. 1227 if (StringRef(II->TheDef->getName()).startswith("Int_") || 1228 StringRef(II->TheDef->getName()).endswith("_Int")) 1229 continue; 1230 1231 Matchables.push_back(II.take()); 1232 } 1233 1234 // Parse all of the InstAlias definitions and stick them in the list of 1235 // matchables. 1236 std::vector<Record*> AllInstAliases = 1237 Records.getAllDerivedDefinitions("InstAlias"); 1238 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) { 1239 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i], Target); 1240 1241 // If the tblgen -match-prefix option is specified (for tblgen hackers), 1242 // filter the set of instruction aliases we consider, based on the target 1243 // instruction. 1244 if (!StringRef(Alias->ResultInst->TheDef->getName()).startswith( 1245 MatchPrefix)) 1246 continue; 1247 1248 OwningPtr<MatchableInfo> II(new MatchableInfo(Alias)); 1249 1250 II->Initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix); 1251 1252 // Validate the alias definitions. 1253 II->Validate(CommentDelimiter, false); 1254 1255 Matchables.push_back(II.take()); 1256 } 1257 1258 // Build info for the register classes. 1259 BuildRegisterClasses(SingletonRegisters); 1260 1261 // Build info for the user defined assembly operand classes. 1262 BuildOperandClasses(); 1263 1264 // Build the information about matchables, now that we have fully formed 1265 // classes. 1266 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(), 1267 ie = Matchables.end(); it != ie; ++it) { 1268 MatchableInfo *II = *it; 1269 1270 // Parse the tokens after the mnemonic. 1271 // Note: BuildInstructionOperandReference may insert new AsmOperands, so 1272 // don't precompute the loop bound. 1273 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) { 1274 MatchableInfo::AsmOperand &Op = II->AsmOperands[i]; 1275 StringRef Token = Op.Token; 1276 1277 // Check for singleton registers. 1278 if (Record *RegRecord = II->AsmOperands[i].SingletonReg) { 1279 Op.Class = RegisterClasses[RegRecord]; 1280 assert(Op.Class && Op.Class->Registers.size() == 1 && 1281 "Unexpected class for singleton register"); 1282 continue; 1283 } 1284 1285 // Check for simple tokens. 1286 if (Token[0] != '$') { 1287 Op.Class = getTokenClass(Token); 1288 continue; 1289 } 1290 1291 if (Token.size() > 1 && isdigit(Token[1])) { 1292 Op.Class = getTokenClass(Token); 1293 continue; 1294 } 1295 1296 // Otherwise this is an operand reference. 1297 StringRef OperandName; 1298 if (Token[1] == '{') 1299 OperandName = Token.substr(2, Token.size() - 3); 1300 else 1301 OperandName = Token.substr(1); 1302 1303 if (II->DefRec.is<const CodeGenInstruction*>()) 1304 BuildInstructionOperandReference(II, OperandName, i); 1305 else 1306 BuildAliasOperandReference(II, OperandName, Op); 1307 } 1308 1309 if (II->DefRec.is<const CodeGenInstruction*>()) 1310 II->BuildInstructionResultOperands(); 1311 else 1312 II->BuildAliasResultOperands(); 1313 } 1314 1315 // Process token alias definitions and set up the associated superclass 1316 // information. 1317 std::vector<Record*> AllTokenAliases = 1318 Records.getAllDerivedDefinitions("TokenAlias"); 1319 for (unsigned i = 0, e = AllTokenAliases.size(); i != e; ++i) { 1320 Record *Rec = AllTokenAliases[i]; 1321 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken")); 1322 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken")); 1323 FromClass->SuperClasses.push_back(ToClass); 1324 } 1325 1326 // Reorder classes so that classes precede super classes. 1327 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>()); 1328} 1329 1330/// BuildInstructionOperandReference - The specified operand is a reference to a 1331/// named operand such as $src. Resolve the Class and OperandInfo pointers. 1332void AsmMatcherInfo:: 1333BuildInstructionOperandReference(MatchableInfo *II, 1334 StringRef OperandName, 1335 unsigned AsmOpIdx) { 1336 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>(); 1337 const CGIOperandList &Operands = CGI.Operands; 1338 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx]; 1339 1340 // Map this token to an operand. 1341 unsigned Idx; 1342 if (!Operands.hasOperandNamed(OperandName, Idx)) 1343 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" + 1344 OperandName.str() + "'"); 1345 1346 // If the instruction operand has multiple suboperands, but the parser 1347 // match class for the asm operand is still the default "ImmAsmOperand", 1348 // then handle each suboperand separately. 1349 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) { 1350 Record *Rec = Operands[Idx].Rec; 1351 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!"); 1352 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass"); 1353 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") { 1354 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands. 1355 StringRef Token = Op->Token; // save this in case Op gets moved 1356 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) { 1357 MatchableInfo::AsmOperand NewAsmOp(Token); 1358 NewAsmOp.SubOpIdx = SI; 1359 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp); 1360 } 1361 // Replace Op with first suboperand. 1362 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved 1363 Op->SubOpIdx = 0; 1364 } 1365 } 1366 1367 // Set up the operand class. 1368 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx); 1369 1370 // If the named operand is tied, canonicalize it to the untied operand. 1371 // For example, something like: 1372 // (outs GPR:$dst), (ins GPR:$src) 1373 // with an asmstring of 1374 // "inc $src" 1375 // we want to canonicalize to: 1376 // "inc $dst" 1377 // so that we know how to provide the $dst operand when filling in the result. 1378 int OITied = Operands[Idx].getTiedRegister(); 1379 if (OITied != -1) { 1380 // The tied operand index is an MIOperand index, find the operand that 1381 // contains it. 1382 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied); 1383 OperandName = Operands[Idx.first].Name; 1384 Op->SubOpIdx = Idx.second; 1385 } 1386 1387 Op->SrcOpName = OperandName; 1388} 1389 1390/// BuildAliasOperandReference - When parsing an operand reference out of the 1391/// matching string (e.g. "movsx $src, $dst"), determine what the class of the 1392/// operand reference is by looking it up in the result pattern definition. 1393void AsmMatcherInfo::BuildAliasOperandReference(MatchableInfo *II, 1394 StringRef OperandName, 1395 MatchableInfo::AsmOperand &Op) { 1396 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>(); 1397 1398 // Set up the operand class. 1399 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i) 1400 if (CGA.ResultOperands[i].isRecord() && 1401 CGA.ResultOperands[i].getName() == OperandName) { 1402 // It's safe to go with the first one we find, because CodeGenInstAlias 1403 // validates that all operands with the same name have the same record. 1404 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second; 1405 // Use the match class from the Alias definition, not the 1406 // destination instruction, as we may have an immediate that's 1407 // being munged by the match class. 1408 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(), 1409 Op.SubOpIdx); 1410 Op.SrcOpName = OperandName; 1411 return; 1412 } 1413 1414 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" + 1415 OperandName.str() + "'"); 1416} 1417 1418void MatchableInfo::BuildInstructionResultOperands() { 1419 const CodeGenInstruction *ResultInst = getResultInst(); 1420 1421 // Loop over all operands of the result instruction, determining how to 1422 // populate them. 1423 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) { 1424 const CGIOperandList::OperandInfo &OpInfo = ResultInst->Operands[i]; 1425 1426 // If this is a tied operand, just copy from the previously handled operand. 1427 int TiedOp = OpInfo.getTiedRegister(); 1428 if (TiedOp != -1) { 1429 ResOperands.push_back(ResOperand::getTiedOp(TiedOp)); 1430 continue; 1431 } 1432 1433 // Find out what operand from the asmparser this MCInst operand comes from. 1434 int SrcOperand = FindAsmOperandNamed(OpInfo.Name); 1435 if (OpInfo.Name.empty() || SrcOperand == -1) 1436 throw TGError(TheDef->getLoc(), "Instruction '" + 1437 TheDef->getName() + "' has operand '" + OpInfo.Name + 1438 "' that doesn't appear in asm string!"); 1439 1440 // Check if the one AsmOperand populates the entire operand. 1441 unsigned NumOperands = OpInfo.MINumOperands; 1442 if (AsmOperands[SrcOperand].SubOpIdx == -1) { 1443 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands)); 1444 continue; 1445 } 1446 1447 // Add a separate ResOperand for each suboperand. 1448 for (unsigned AI = 0; AI < NumOperands; ++AI) { 1449 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI && 1450 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name && 1451 "unexpected AsmOperands for suboperands"); 1452 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1)); 1453 } 1454 } 1455} 1456 1457void MatchableInfo::BuildAliasResultOperands() { 1458 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>(); 1459 const CodeGenInstruction *ResultInst = getResultInst(); 1460 1461 // Loop over all operands of the result instruction, determining how to 1462 // populate them. 1463 unsigned AliasOpNo = 0; 1464 unsigned LastOpNo = CGA.ResultInstOperandIndex.size(); 1465 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) { 1466 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i]; 1467 1468 // If this is a tied operand, just copy from the previously handled operand. 1469 int TiedOp = OpInfo->getTiedRegister(); 1470 if (TiedOp != -1) { 1471 ResOperands.push_back(ResOperand::getTiedOp(TiedOp)); 1472 continue; 1473 } 1474 1475 // Handle all the suboperands for this operand. 1476 const std::string &OpName = OpInfo->Name; 1477 for ( ; AliasOpNo < LastOpNo && 1478 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) { 1479 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second; 1480 1481 // Find out what operand from the asmparser that this MCInst operand 1482 // comes from. 1483 switch (CGA.ResultOperands[AliasOpNo].Kind) { 1484 default: assert(0 && "unexpected InstAlias operand kind"); 1485 case CodeGenInstAlias::ResultOperand::K_Record: { 1486 StringRef Name = CGA.ResultOperands[AliasOpNo].getName(); 1487 int SrcOperand = FindAsmOperand(Name, SubIdx); 1488 if (SrcOperand == -1) 1489 throw TGError(TheDef->getLoc(), "Instruction '" + 1490 TheDef->getName() + "' has operand '" + OpName + 1491 "' that doesn't appear in asm string!"); 1492 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1); 1493 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, 1494 NumOperands)); 1495 break; 1496 } 1497 case CodeGenInstAlias::ResultOperand::K_Imm: { 1498 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm(); 1499 ResOperands.push_back(ResOperand::getImmOp(ImmVal)); 1500 break; 1501 } 1502 case CodeGenInstAlias::ResultOperand::K_Reg: { 1503 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister(); 1504 ResOperands.push_back(ResOperand::getRegOp(Reg)); 1505 break; 1506 } 1507 } 1508 } 1509 } 1510} 1511 1512static void EmitConvertToMCInst(CodeGenTarget &Target, StringRef ClassName, 1513 std::vector<MatchableInfo*> &Infos, 1514 raw_ostream &OS) { 1515 // Write the convert function to a separate stream, so we can drop it after 1516 // the enum. 1517 std::string ConvertFnBody; 1518 raw_string_ostream CvtOS(ConvertFnBody); 1519 1520 // Function we have already generated. 1521 std::set<std::string> GeneratedFns; 1522 1523 // Start the unified conversion function. 1524 CvtOS << "bool " << Target.getName() << ClassName << "::\n"; 1525 CvtOS << "ConvertToMCInst(unsigned Kind, MCInst &Inst, " 1526 << "unsigned Opcode,\n" 1527 << " const SmallVectorImpl<MCParsedAsmOperand*" 1528 << "> &Operands) {\n"; 1529 CvtOS << " Inst.setOpcode(Opcode);\n"; 1530 CvtOS << " switch (Kind) {\n"; 1531 CvtOS << " default:\n"; 1532 1533 // Start the enum, which we will generate inline. 1534 1535 OS << "// Unified function for converting operands to MCInst instances.\n\n"; 1536 OS << "enum ConversionKind {\n"; 1537 1538 // TargetOperandClass - This is the target's operand class, like X86Operand. 1539 std::string TargetOperandClass = Target.getName() + "Operand"; 1540 1541 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(), 1542 ie = Infos.end(); it != ie; ++it) { 1543 MatchableInfo &II = **it; 1544 1545 // Check if we have a custom match function. 1546 std::string AsmMatchConverter = 1547 II.getResultInst()->TheDef->getValueAsString("AsmMatchConverter"); 1548 if (!AsmMatchConverter.empty()) { 1549 std::string Signature = "ConvertCustom_" + AsmMatchConverter; 1550 II.ConversionFnKind = Signature; 1551 1552 // Check if we have already generated this signature. 1553 if (!GeneratedFns.insert(Signature).second) 1554 continue; 1555 1556 // If not, emit it now. Add to the enum list. 1557 OS << " " << Signature << ",\n"; 1558 1559 CvtOS << " case " << Signature << ":\n"; 1560 CvtOS << " return " << AsmMatchConverter 1561 << "(Inst, Opcode, Operands);\n"; 1562 continue; 1563 } 1564 1565 // Build the conversion function signature. 1566 std::string Signature = "Convert"; 1567 std::string CaseBody; 1568 raw_string_ostream CaseOS(CaseBody); 1569 1570 // Compute the convert enum and the case body. 1571 for (unsigned i = 0, e = II.ResOperands.size(); i != e; ++i) { 1572 const MatchableInfo::ResOperand &OpInfo = II.ResOperands[i]; 1573 1574 // Generate code to populate each result operand. 1575 switch (OpInfo.Kind) { 1576 case MatchableInfo::ResOperand::RenderAsmOperand: { 1577 // This comes from something we parsed. 1578 MatchableInfo::AsmOperand &Op = II.AsmOperands[OpInfo.AsmOperandNum]; 1579 1580 // Registers are always converted the same, don't duplicate the 1581 // conversion function based on them. 1582 Signature += "__"; 1583 if (Op.Class->isRegisterClass()) 1584 Signature += "Reg"; 1585 else 1586 Signature += Op.Class->ClassName; 1587 Signature += utostr(OpInfo.MINumOperands); 1588 Signature += "_" + itostr(OpInfo.AsmOperandNum); 1589 1590 CaseOS << " ((" << TargetOperandClass << "*)Operands[" 1591 << (OpInfo.AsmOperandNum+1) << "])->" << Op.Class->RenderMethod 1592 << "(Inst, " << OpInfo.MINumOperands << ");\n"; 1593 break; 1594 } 1595 1596 case MatchableInfo::ResOperand::TiedOperand: { 1597 // If this operand is tied to a previous one, just copy the MCInst 1598 // operand from the earlier one.We can only tie single MCOperand values. 1599 //assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand"); 1600 unsigned TiedOp = OpInfo.TiedOperandNum; 1601 assert(i > TiedOp && "Tied operand precedes its target!"); 1602 CaseOS << " Inst.addOperand(Inst.getOperand(" << TiedOp << "));\n"; 1603 Signature += "__Tie" + utostr(TiedOp); 1604 break; 1605 } 1606 case MatchableInfo::ResOperand::ImmOperand: { 1607 int64_t Val = OpInfo.ImmVal; 1608 CaseOS << " Inst.addOperand(MCOperand::CreateImm(" << Val << "));\n"; 1609 Signature += "__imm" + itostr(Val); 1610 break; 1611 } 1612 case MatchableInfo::ResOperand::RegOperand: { 1613 if (OpInfo.Register == 0) { 1614 CaseOS << " Inst.addOperand(MCOperand::CreateReg(0));\n"; 1615 Signature += "__reg0"; 1616 } else { 1617 std::string N = getQualifiedName(OpInfo.Register); 1618 CaseOS << " Inst.addOperand(MCOperand::CreateReg(" << N << "));\n"; 1619 Signature += "__reg" + OpInfo.Register->getName(); 1620 } 1621 } 1622 } 1623 } 1624 1625 II.ConversionFnKind = Signature; 1626 1627 // Check if we have already generated this signature. 1628 if (!GeneratedFns.insert(Signature).second) 1629 continue; 1630 1631 // If not, emit it now. Add to the enum list. 1632 OS << " " << Signature << ",\n"; 1633 1634 CvtOS << " case " << Signature << ":\n"; 1635 CvtOS << CaseOS.str(); 1636 CvtOS << " return true;\n"; 1637 } 1638 1639 // Finish the convert function. 1640 1641 CvtOS << " }\n"; 1642 CvtOS << " return false;\n"; 1643 CvtOS << "}\n\n"; 1644 1645 // Finish the enum, and drop the convert function after it. 1646 1647 OS << " NumConversionVariants\n"; 1648 OS << "};\n\n"; 1649 1650 OS << CvtOS.str(); 1651} 1652 1653/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds. 1654static void EmitMatchClassEnumeration(CodeGenTarget &Target, 1655 std::vector<ClassInfo*> &Infos, 1656 raw_ostream &OS) { 1657 OS << "namespace {\n\n"; 1658 1659 OS << "/// MatchClassKind - The kinds of classes which participate in\n" 1660 << "/// instruction matching.\n"; 1661 OS << "enum MatchClassKind {\n"; 1662 OS << " InvalidMatchClass = 0,\n"; 1663 for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 1664 ie = Infos.end(); it != ie; ++it) { 1665 ClassInfo &CI = **it; 1666 OS << " " << CI.Name << ", // "; 1667 if (CI.Kind == ClassInfo::Token) { 1668 OS << "'" << CI.ValueName << "'\n"; 1669 } else if (CI.isRegisterClass()) { 1670 if (!CI.ValueName.empty()) 1671 OS << "register class '" << CI.ValueName << "'\n"; 1672 else 1673 OS << "derived register class\n"; 1674 } else { 1675 OS << "user defined class '" << CI.ValueName << "'\n"; 1676 } 1677 } 1678 OS << " NumMatchClassKinds\n"; 1679 OS << "};\n\n"; 1680 1681 OS << "}\n\n"; 1682} 1683 1684/// EmitValidateOperandClass - Emit the function to validate an operand class. 1685static void EmitValidateOperandClass(AsmMatcherInfo &Info, 1686 raw_ostream &OS) { 1687 OS << "static bool validateOperandClass(MCParsedAsmOperand *GOp, " 1688 << "MatchClassKind Kind) {\n"; 1689 OS << " " << Info.Target.getName() << "Operand &Operand = *(" 1690 << Info.Target.getName() << "Operand*)GOp;\n"; 1691 1692 // The InvalidMatchClass is not to match any operand. 1693 OS << " if (Kind == InvalidMatchClass)\n"; 1694 OS << " return false;\n\n"; 1695 1696 // Check for Token operands first. 1697 OS << " if (Operand.isToken())\n"; 1698 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind);" 1699 << "\n\n"; 1700 1701 // Check for register operands, including sub-classes. 1702 OS << " if (Operand.isReg()) {\n"; 1703 OS << " MatchClassKind OpKind;\n"; 1704 OS << " switch (Operand.getReg()) {\n"; 1705 OS << " default: OpKind = InvalidMatchClass; break;\n"; 1706 for (std::map<Record*, ClassInfo*>::iterator 1707 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end(); 1708 it != ie; ++it) 1709 OS << " case " << Info.Target.getName() << "::" 1710 << it->first->getName() << ": OpKind = " << it->second->Name 1711 << "; break;\n"; 1712 OS << " }\n"; 1713 OS << " return isSubclass(OpKind, Kind);\n"; 1714 OS << " }\n\n"; 1715 1716 // Check the user classes. We don't care what order since we're only 1717 // actually matching against one of them. 1718 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(), 1719 ie = Info.Classes.end(); it != ie; ++it) { 1720 ClassInfo &CI = **it; 1721 1722 if (!CI.isUserClass()) 1723 continue; 1724 1725 OS << " // '" << CI.ClassName << "' class\n"; 1726 OS << " if (Kind == " << CI.Name 1727 << " && Operand." << CI.PredicateMethod << "()) {\n"; 1728 OS << " return true;\n"; 1729 OS << " }\n\n"; 1730 } 1731 1732 OS << " return false;\n"; 1733 OS << "}\n\n"; 1734} 1735 1736/// EmitIsSubclass - Emit the subclass predicate function. 1737static void EmitIsSubclass(CodeGenTarget &Target, 1738 std::vector<ClassInfo*> &Infos, 1739 raw_ostream &OS) { 1740 OS << "/// isSubclass - Compute whether \\arg A is a subclass of \\arg B.\n"; 1741 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n"; 1742 OS << " if (A == B)\n"; 1743 OS << " return true;\n\n"; 1744 1745 OS << " switch (A) {\n"; 1746 OS << " default:\n"; 1747 OS << " return false;\n"; 1748 for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 1749 ie = Infos.end(); it != ie; ++it) { 1750 ClassInfo &A = **it; 1751 1752 std::vector<StringRef> SuperClasses; 1753 for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 1754 ie = Infos.end(); it != ie; ++it) { 1755 ClassInfo &B = **it; 1756 1757 if (&A != &B && A.isSubsetOf(B)) 1758 SuperClasses.push_back(B.Name); 1759 } 1760 1761 if (SuperClasses.empty()) 1762 continue; 1763 1764 OS << "\n case " << A.Name << ":\n"; 1765 1766 if (SuperClasses.size() == 1) { 1767 OS << " return B == " << SuperClasses.back() << ";\n"; 1768 continue; 1769 } 1770 1771 OS << " switch (B) {\n"; 1772 OS << " default: return false;\n"; 1773 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i) 1774 OS << " case " << SuperClasses[i] << ": return true;\n"; 1775 OS << " }\n"; 1776 } 1777 OS << " }\n"; 1778 OS << "}\n\n"; 1779} 1780 1781/// EmitMatchTokenString - Emit the function to match a token string to the 1782/// appropriate match class value. 1783static void EmitMatchTokenString(CodeGenTarget &Target, 1784 std::vector<ClassInfo*> &Infos, 1785 raw_ostream &OS) { 1786 // Construct the match list. 1787 std::vector<StringMatcher::StringPair> Matches; 1788 for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 1789 ie = Infos.end(); it != ie; ++it) { 1790 ClassInfo &CI = **it; 1791 1792 if (CI.Kind == ClassInfo::Token) 1793 Matches.push_back(StringMatcher::StringPair(CI.ValueName, 1794 "return " + CI.Name + ";")); 1795 } 1796 1797 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n"; 1798 1799 StringMatcher("Name", Matches, OS).Emit(); 1800 1801 OS << " return InvalidMatchClass;\n"; 1802 OS << "}\n\n"; 1803} 1804 1805/// EmitMatchRegisterName - Emit the function to match a string to the target 1806/// specific register enum. 1807static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser, 1808 raw_ostream &OS) { 1809 // Construct the match list. 1810 std::vector<StringMatcher::StringPair> Matches; 1811 const std::vector<CodeGenRegister*> &Regs = 1812 Target.getRegBank().getRegisters(); 1813 for (unsigned i = 0, e = Regs.size(); i != e; ++i) { 1814 const CodeGenRegister *Reg = Regs[i]; 1815 if (Reg->TheDef->getValueAsString("AsmName").empty()) 1816 continue; 1817 1818 Matches.push_back(StringMatcher::StringPair( 1819 Reg->TheDef->getValueAsString("AsmName"), 1820 "return " + utostr(Reg->EnumValue) + ";")); 1821 } 1822 1823 OS << "static unsigned MatchRegisterName(StringRef Name) {\n"; 1824 1825 StringMatcher("Name", Matches, OS).Emit(); 1826 1827 OS << " return 0;\n"; 1828 OS << "}\n\n"; 1829} 1830 1831/// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag 1832/// definitions. 1833static void EmitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info, 1834 raw_ostream &OS) { 1835 OS << "// Flags for subtarget features that participate in " 1836 << "instruction matching.\n"; 1837 OS << "enum SubtargetFeatureFlag {\n"; 1838 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator 1839 it = Info.SubtargetFeatures.begin(), 1840 ie = Info.SubtargetFeatures.end(); it != ie; ++it) { 1841 SubtargetFeatureInfo &SFI = *it->second; 1842 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n"; 1843 } 1844 OS << " Feature_None = 0\n"; 1845 OS << "};\n\n"; 1846} 1847 1848/// EmitComputeAvailableFeatures - Emit the function to compute the list of 1849/// available features given a subtarget. 1850static void EmitComputeAvailableFeatures(AsmMatcherInfo &Info, 1851 raw_ostream &OS) { 1852 std::string ClassName = 1853 Info.AsmParser->getValueAsString("AsmParserClassName"); 1854 1855 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n" 1856 << "ComputeAvailableFeatures(uint64_t FB) const {\n"; 1857 OS << " unsigned Features = 0;\n"; 1858 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator 1859 it = Info.SubtargetFeatures.begin(), 1860 ie = Info.SubtargetFeatures.end(); it != ie; ++it) { 1861 SubtargetFeatureInfo &SFI = *it->second; 1862 1863 OS << " if ("; 1864 std::string CondStorage = SFI.TheDef->getValueAsString("AssemblerCondString"); 1865 StringRef Conds = CondStorage; 1866 std::pair<StringRef,StringRef> Comma = Conds.split(','); 1867 bool First = true; 1868 do { 1869 if (!First) 1870 OS << " && "; 1871 1872 bool Neg = false; 1873 StringRef Cond = Comma.first; 1874 if (Cond[0] == '!') { 1875 Neg = true; 1876 Cond = Cond.substr(1); 1877 } 1878 1879 OS << "((FB & " << Info.Target.getName() << "::" << Cond << ")"; 1880 if (Neg) 1881 OS << " == 0"; 1882 else 1883 OS << " != 0"; 1884 OS << ")"; 1885 1886 if (Comma.second.empty()) 1887 break; 1888 1889 First = false; 1890 Comma = Comma.second.split(','); 1891 } while (true); 1892 1893 OS << ")\n"; 1894 OS << " Features |= " << SFI.getEnumName() << ";\n"; 1895 } 1896 OS << " return Features;\n"; 1897 OS << "}\n\n"; 1898} 1899 1900static std::string GetAliasRequiredFeatures(Record *R, 1901 const AsmMatcherInfo &Info) { 1902 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates"); 1903 std::string Result; 1904 unsigned NumFeatures = 0; 1905 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) { 1906 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]); 1907 1908 if (F == 0) 1909 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() + 1910 "' is not marked as an AssemblerPredicate!"); 1911 1912 if (NumFeatures) 1913 Result += '|'; 1914 1915 Result += F->getEnumName(); 1916 ++NumFeatures; 1917 } 1918 1919 if (NumFeatures > 1) 1920 Result = '(' + Result + ')'; 1921 return Result; 1922} 1923 1924/// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions, 1925/// emit a function for them and return true, otherwise return false. 1926static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) { 1927 // Ignore aliases when match-prefix is set. 1928 if (!MatchPrefix.empty()) 1929 return false; 1930 1931 std::vector<Record*> Aliases = 1932 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias"); 1933 if (Aliases.empty()) return false; 1934 1935 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, " 1936 "unsigned Features) {\n"; 1937 1938 // Keep track of all the aliases from a mnemonic. Use an std::map so that the 1939 // iteration order of the map is stable. 1940 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic; 1941 1942 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) { 1943 Record *R = Aliases[i]; 1944 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R); 1945 } 1946 1947 // Process each alias a "from" mnemonic at a time, building the code executed 1948 // by the string remapper. 1949 std::vector<StringMatcher::StringPair> Cases; 1950 for (std::map<std::string, std::vector<Record*> >::iterator 1951 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end(); 1952 I != E; ++I) { 1953 const std::vector<Record*> &ToVec = I->second; 1954 1955 // Loop through each alias and emit code that handles each case. If there 1956 // are two instructions without predicates, emit an error. If there is one, 1957 // emit it last. 1958 std::string MatchCode; 1959 int AliasWithNoPredicate = -1; 1960 1961 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) { 1962 Record *R = ToVec[i]; 1963 std::string FeatureMask = GetAliasRequiredFeatures(R, Info); 1964 1965 // If this unconditionally matches, remember it for later and diagnose 1966 // duplicates. 1967 if (FeatureMask.empty()) { 1968 if (AliasWithNoPredicate != -1) { 1969 // We can't have two aliases from the same mnemonic with no predicate. 1970 PrintError(ToVec[AliasWithNoPredicate]->getLoc(), 1971 "two MnemonicAliases with the same 'from' mnemonic!"); 1972 throw TGError(R->getLoc(), "this is the other MnemonicAlias."); 1973 } 1974 1975 AliasWithNoPredicate = i; 1976 continue; 1977 } 1978 if (R->getValueAsString("ToMnemonic") == I->first) 1979 throw TGError(R->getLoc(), "MnemonicAlias to the same string"); 1980 1981 if (!MatchCode.empty()) 1982 MatchCode += "else "; 1983 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n"; 1984 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n"; 1985 } 1986 1987 if (AliasWithNoPredicate != -1) { 1988 Record *R = ToVec[AliasWithNoPredicate]; 1989 if (!MatchCode.empty()) 1990 MatchCode += "else\n "; 1991 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n"; 1992 } 1993 1994 MatchCode += "return;"; 1995 1996 Cases.push_back(std::make_pair(I->first, MatchCode)); 1997 } 1998 1999 StringMatcher("Mnemonic", Cases, OS).Emit(); 2000 OS << "}\n\n"; 2001 2002 return true; 2003} 2004 2005static const char *getMinimalTypeForRange(uint64_t Range) { 2006 assert(Range < 0xFFFFFFFFULL && "Enum too large"); 2007 if (Range > 0xFFFF) 2008 return "uint32_t"; 2009 if (Range > 0xFF) 2010 return "uint16_t"; 2011 return "uint8_t"; 2012} 2013 2014static void EmitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target, 2015 const AsmMatcherInfo &Info, StringRef ClassName) { 2016 // Emit the static custom operand parsing table; 2017 OS << "namespace {\n"; 2018 OS << " struct OperandMatchEntry {\n"; 2019 OS << " const char *Mnemonic;\n"; 2020 OS << " unsigned OperandMask;\n"; 2021 OS << " MatchClassKind Class;\n"; 2022 OS << " unsigned RequiredFeatures;\n"; 2023 OS << " };\n\n"; 2024 2025 OS << " // Predicate for searching for an opcode.\n"; 2026 OS << " struct LessOpcodeOperand {\n"; 2027 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n"; 2028 OS << " return StringRef(LHS.Mnemonic) < RHS;\n"; 2029 OS << " }\n"; 2030 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n"; 2031 OS << " return LHS < StringRef(RHS.Mnemonic);\n"; 2032 OS << " }\n"; 2033 OS << " bool operator()(const OperandMatchEntry &LHS,"; 2034 OS << " const OperandMatchEntry &RHS) {\n"; 2035 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n"; 2036 OS << " }\n"; 2037 OS << " };\n"; 2038 2039 OS << "} // end anonymous namespace.\n\n"; 2040 2041 OS << "static const OperandMatchEntry OperandMatchTable[" 2042 << Info.OperandMatchInfo.size() << "] = {\n"; 2043 2044 OS << " /* Mnemonic, Operand List Mask, Operand Class, Features */\n"; 2045 for (std::vector<OperandMatchEntry>::const_iterator it = 2046 Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end(); 2047 it != ie; ++it) { 2048 const OperandMatchEntry &OMI = *it; 2049 const MatchableInfo &II = *OMI.MI; 2050 2051 OS << " { \"" << II.Mnemonic << "\"" 2052 << ", " << OMI.OperandMask; 2053 2054 OS << " /* "; 2055 bool printComma = false; 2056 for (int i = 0, e = 31; i !=e; ++i) 2057 if (OMI.OperandMask & (1 << i)) { 2058 if (printComma) 2059 OS << ", "; 2060 OS << i; 2061 printComma = true; 2062 } 2063 OS << " */"; 2064 2065 OS << ", " << OMI.CI->Name 2066 << ", "; 2067 2068 // Write the required features mask. 2069 if (!II.RequiredFeatures.empty()) { 2070 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) { 2071 if (i) OS << "|"; 2072 OS << II.RequiredFeatures[i]->getEnumName(); 2073 } 2074 } else 2075 OS << "0"; 2076 OS << " },\n"; 2077 } 2078 OS << "};\n\n"; 2079 2080 // Emit the operand class switch to call the correct custom parser for 2081 // the found operand class. 2082 OS << Target.getName() << ClassName << "::OperandMatchResultTy " 2083 << Target.getName() << ClassName << "::\n" 2084 << "tryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>" 2085 << " &Operands,\n unsigned MCK) {\n\n" 2086 << " switch(MCK) {\n"; 2087 2088 for (std::vector<ClassInfo*>::const_iterator it = Info.Classes.begin(), 2089 ie = Info.Classes.end(); it != ie; ++it) { 2090 ClassInfo *CI = *it; 2091 if (CI->ParserMethod.empty()) 2092 continue; 2093 OS << " case " << CI->Name << ":\n" 2094 << " return " << CI->ParserMethod << "(Operands);\n"; 2095 } 2096 2097 OS << " default:\n"; 2098 OS << " return MatchOperand_NoMatch;\n"; 2099 OS << " }\n"; 2100 OS << " return MatchOperand_NoMatch;\n"; 2101 OS << "}\n\n"; 2102 2103 // Emit the static custom operand parser. This code is very similar with 2104 // the other matcher. Also use MatchResultTy here just in case we go for 2105 // a better error handling. 2106 OS << Target.getName() << ClassName << "::OperandMatchResultTy " 2107 << Target.getName() << ClassName << "::\n" 2108 << "MatchOperandParserImpl(SmallVectorImpl<MCParsedAsmOperand*>" 2109 << " &Operands,\n StringRef Mnemonic) {\n"; 2110 2111 // Emit code to get the available features. 2112 OS << " // Get the current feature set.\n"; 2113 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n"; 2114 2115 OS << " // Get the next operand index.\n"; 2116 OS << " unsigned NextOpNum = Operands.size()-1;\n"; 2117 2118 // Emit code to search the table. 2119 OS << " // Search the table.\n"; 2120 OS << " std::pair<const OperandMatchEntry*, const OperandMatchEntry*>"; 2121 OS << " MnemonicRange =\n"; 2122 OS << " std::equal_range(OperandMatchTable, OperandMatchTable+" 2123 << Info.OperandMatchInfo.size() << ", Mnemonic,\n" 2124 << " LessOpcodeOperand());\n\n"; 2125 2126 OS << " if (MnemonicRange.first == MnemonicRange.second)\n"; 2127 OS << " return MatchOperand_NoMatch;\n\n"; 2128 2129 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n" 2130 << " *ie = MnemonicRange.second; it != ie; ++it) {\n"; 2131 2132 OS << " // equal_range guarantees that instruction mnemonic matches.\n"; 2133 OS << " assert(Mnemonic == it->Mnemonic);\n\n"; 2134 2135 // Emit check that the required features are available. 2136 OS << " // check if the available features match\n"; 2137 OS << " if ((AvailableFeatures & it->RequiredFeatures) " 2138 << "!= it->RequiredFeatures) {\n"; 2139 OS << " continue;\n"; 2140 OS << " }\n\n"; 2141 2142 // Emit check to ensure the operand number matches. 2143 OS << " // check if the operand in question has a custom parser.\n"; 2144 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n"; 2145 OS << " continue;\n\n"; 2146 2147 // Emit call to the custom parser method 2148 OS << " // call custom parse method to handle the operand\n"; 2149 OS << " OperandMatchResultTy Result = "; 2150 OS << "tryCustomParseOperand(Operands, it->Class);\n"; 2151 OS << " if (Result != MatchOperand_NoMatch)\n"; 2152 OS << " return Result;\n"; 2153 OS << " }\n\n"; 2154 2155 OS << " // Okay, we had no match.\n"; 2156 OS << " return MatchOperand_NoMatch;\n"; 2157 OS << "}\n\n"; 2158} 2159 2160void AsmMatcherEmitter::run(raw_ostream &OS) { 2161 CodeGenTarget Target(Records); 2162 Record *AsmParser = Target.getAsmParser(); 2163 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName"); 2164 2165 // Compute the information on the instructions to match. 2166 AsmMatcherInfo Info(AsmParser, Target, Records); 2167 Info.BuildInfo(); 2168 2169 // Sort the instruction table using the partial order on classes. We use 2170 // stable_sort to ensure that ambiguous instructions are still 2171 // deterministically ordered. 2172 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(), 2173 less_ptr<MatchableInfo>()); 2174 2175 DEBUG_WITH_TYPE("instruction_info", { 2176 for (std::vector<MatchableInfo*>::iterator 2177 it = Info.Matchables.begin(), ie = Info.Matchables.end(); 2178 it != ie; ++it) 2179 (*it)->dump(); 2180 }); 2181 2182 // Check for ambiguous matchables. 2183 DEBUG_WITH_TYPE("ambiguous_instrs", { 2184 unsigned NumAmbiguous = 0; 2185 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) { 2186 for (unsigned j = i + 1; j != e; ++j) { 2187 MatchableInfo &A = *Info.Matchables[i]; 2188 MatchableInfo &B = *Info.Matchables[j]; 2189 2190 if (A.CouldMatchAmbiguouslyWith(B)) { 2191 errs() << "warning: ambiguous matchables:\n"; 2192 A.dump(); 2193 errs() << "\nis incomparable with:\n"; 2194 B.dump(); 2195 errs() << "\n\n"; 2196 ++NumAmbiguous; 2197 } 2198 } 2199 } 2200 if (NumAmbiguous) 2201 errs() << "warning: " << NumAmbiguous 2202 << " ambiguous matchables!\n"; 2203 }); 2204 2205 // Compute the information on the custom operand parsing. 2206 Info.BuildOperandMatchInfo(); 2207 2208 // Write the output. 2209 2210 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS); 2211 2212 // Information for the class declaration. 2213 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n"; 2214 OS << "#undef GET_ASSEMBLER_HEADER\n"; 2215 OS << " // This should be included into the middle of the declaration of\n"; 2216 OS << " // your subclasses implementation of MCTargetAsmParser.\n"; 2217 OS << " unsigned ComputeAvailableFeatures(uint64_t FeatureBits) const;\n"; 2218 OS << " bool ConvertToMCInst(unsigned Kind, MCInst &Inst, " 2219 << "unsigned Opcode,\n" 2220 << " const SmallVectorImpl<MCParsedAsmOperand*> " 2221 << "&Operands);\n"; 2222 OS << " bool MnemonicIsValid(StringRef Mnemonic);\n"; 2223 OS << " unsigned MatchInstructionImpl(\n"; 2224 OS << " const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n"; 2225 OS << " MCInst &Inst, unsigned &ErrorInfo);\n"; 2226 2227 if (Info.OperandMatchInfo.size()) { 2228 OS << "\n enum OperandMatchResultTy {\n"; 2229 OS << " MatchOperand_Success, // operand matched successfully\n"; 2230 OS << " MatchOperand_NoMatch, // operand did not match\n"; 2231 OS << " MatchOperand_ParseFail // operand matched but had errors\n"; 2232 OS << " };\n"; 2233 OS << " OperandMatchResultTy MatchOperandParserImpl(\n"; 2234 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n"; 2235 OS << " StringRef Mnemonic);\n"; 2236 2237 OS << " OperandMatchResultTy tryCustomParseOperand(\n"; 2238 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n"; 2239 OS << " unsigned MCK);\n\n"; 2240 } 2241 2242 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n"; 2243 2244 OS << "\n#ifdef GET_REGISTER_MATCHER\n"; 2245 OS << "#undef GET_REGISTER_MATCHER\n\n"; 2246 2247 // Emit the subtarget feature enumeration. 2248 EmitSubtargetFeatureFlagEnumeration(Info, OS); 2249 2250 // Emit the function to match a register name to number. 2251 EmitMatchRegisterName(Target, AsmParser, OS); 2252 2253 OS << "#endif // GET_REGISTER_MATCHER\n\n"; 2254 2255 2256 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n"; 2257 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n"; 2258 2259 // Generate the function that remaps for mnemonic aliases. 2260 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info); 2261 2262 // Generate the unified function to convert operands into an MCInst. 2263 EmitConvertToMCInst(Target, ClassName, Info.Matchables, OS); 2264 2265 // Emit the enumeration for classes which participate in matching. 2266 EmitMatchClassEnumeration(Target, Info.Classes, OS); 2267 2268 // Emit the routine to match token strings to their match class. 2269 EmitMatchTokenString(Target, Info.Classes, OS); 2270 2271 // Emit the subclass predicate routine. 2272 EmitIsSubclass(Target, Info.Classes, OS); 2273 2274 // Emit the routine to validate an operand against a match class. 2275 EmitValidateOperandClass(Info, OS); 2276 2277 // Emit the available features compute function. 2278 EmitComputeAvailableFeatures(Info, OS); 2279 2280 2281 size_t MaxNumOperands = 0; 2282 for (std::vector<MatchableInfo*>::const_iterator it = 2283 Info.Matchables.begin(), ie = Info.Matchables.end(); 2284 it != ie; ++it) 2285 MaxNumOperands = std::max(MaxNumOperands, (*it)->AsmOperands.size()); 2286 2287 // Emit the static match table; unused classes get initalized to 0 which is 2288 // guaranteed to be InvalidMatchClass. 2289 // 2290 // FIXME: We can reduce the size of this table very easily. First, we change 2291 // it so that store the kinds in separate bit-fields for each index, which 2292 // only needs to be the max width used for classes at that index (we also need 2293 // to reject based on this during classification). If we then make sure to 2294 // order the match kinds appropriately (putting mnemonics last), then we 2295 // should only end up using a few bits for each class, especially the ones 2296 // following the mnemonic. 2297 OS << "namespace {\n"; 2298 OS << " struct MatchEntry {\n"; 2299 OS << " unsigned Opcode;\n"; 2300 OS << " const char *Mnemonic;\n"; 2301 OS << " " << getMinimalTypeForRange(Info.Matchables.size()) 2302 << " ConvertFn;\n"; 2303 OS << " " << getMinimalTypeForRange(Info.Classes.size()) 2304 << " Classes[" << MaxNumOperands << "];\n"; 2305 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size()) 2306 << " RequiredFeatures;\n"; 2307 OS << " };\n\n"; 2308 2309 OS << " // Predicate for searching for an opcode.\n"; 2310 OS << " struct LessOpcode {\n"; 2311 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n"; 2312 OS << " return StringRef(LHS.Mnemonic) < RHS;\n"; 2313 OS << " }\n"; 2314 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n"; 2315 OS << " return LHS < StringRef(RHS.Mnemonic);\n"; 2316 OS << " }\n"; 2317 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n"; 2318 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n"; 2319 OS << " }\n"; 2320 OS << " };\n"; 2321 2322 OS << "} // end anonymous namespace.\n\n"; 2323 2324 OS << "static const MatchEntry MatchTable[" 2325 << Info.Matchables.size() << "] = {\n"; 2326 2327 for (std::vector<MatchableInfo*>::const_iterator it = 2328 Info.Matchables.begin(), ie = Info.Matchables.end(); 2329 it != ie; ++it) { 2330 MatchableInfo &II = **it; 2331 2332 OS << " { " << Target.getName() << "::" 2333 << II.getResultInst()->TheDef->getName() << ", \"" << II.Mnemonic << "\"" 2334 << ", " << II.ConversionFnKind << ", { "; 2335 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) { 2336 MatchableInfo::AsmOperand &Op = II.AsmOperands[i]; 2337 2338 if (i) OS << ", "; 2339 OS << Op.Class->Name; 2340 } 2341 OS << " }, "; 2342 2343 // Write the required features mask. 2344 if (!II.RequiredFeatures.empty()) { 2345 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) { 2346 if (i) OS << "|"; 2347 OS << II.RequiredFeatures[i]->getEnumName(); 2348 } 2349 } else 2350 OS << "0"; 2351 2352 OS << "},\n"; 2353 } 2354 2355 OS << "};\n\n"; 2356 2357 // A method to determine if a mnemonic is in the list. 2358 OS << "bool " << Target.getName() << ClassName << "::\n" 2359 << "MnemonicIsValid(StringRef Mnemonic) {\n"; 2360 OS << " // Search the table.\n"; 2361 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n"; 2362 OS << " std::equal_range(MatchTable, MatchTable+" 2363 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n"; 2364 OS << " return MnemonicRange.first != MnemonicRange.second;\n"; 2365 OS << "}\n\n"; 2366 2367 // Finally, build the match function. 2368 OS << "unsigned " 2369 << Target.getName() << ClassName << "::\n" 2370 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>" 2371 << " &Operands,\n"; 2372 OS << " MCInst &Inst, unsigned &ErrorInfo) {\n"; 2373 2374 // Emit code to get the available features. 2375 OS << " // Get the current feature set.\n"; 2376 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n"; 2377 2378 OS << " // Get the instruction mnemonic, which is the first token.\n"; 2379 OS << " StringRef Mnemonic = ((" << Target.getName() 2380 << "Operand*)Operands[0])->getToken();\n\n"; 2381 2382 if (HasMnemonicAliases) { 2383 OS << " // Process all MnemonicAliases to remap the mnemonic.\n"; 2384 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n"; 2385 } 2386 2387 // Emit code to compute the class list for this operand vector. 2388 OS << " // Eliminate obvious mismatches.\n"; 2389 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n"; 2390 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n"; 2391 OS << " return Match_InvalidOperand;\n"; 2392 OS << " }\n\n"; 2393 2394 OS << " // Some state to try to produce better error messages.\n"; 2395 OS << " bool HadMatchOtherThanFeatures = false;\n"; 2396 OS << " bool HadMatchOtherThanPredicate = false;\n"; 2397 OS << " unsigned RetCode = Match_InvalidOperand;\n"; 2398 OS << " // Set ErrorInfo to the operand that mismatches if it is\n"; 2399 OS << " // wrong for all instances of the instruction.\n"; 2400 OS << " ErrorInfo = ~0U;\n"; 2401 2402 // Emit code to search the table. 2403 OS << " // Search the table.\n"; 2404 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n"; 2405 OS << " std::equal_range(MatchTable, MatchTable+" 2406 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n"; 2407 2408 OS << " // Return a more specific error code if no mnemonics match.\n"; 2409 OS << " if (MnemonicRange.first == MnemonicRange.second)\n"; 2410 OS << " return Match_MnemonicFail;\n\n"; 2411 2412 OS << " for (const MatchEntry *it = MnemonicRange.first, " 2413 << "*ie = MnemonicRange.second;\n"; 2414 OS << " it != ie; ++it) {\n"; 2415 2416 OS << " // equal_range guarantees that instruction mnemonic matches.\n"; 2417 OS << " assert(Mnemonic == it->Mnemonic);\n"; 2418 2419 // Emit check that the subclasses match. 2420 OS << " bool OperandsValid = true;\n"; 2421 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n"; 2422 OS << " if (i + 1 >= Operands.size()) {\n"; 2423 OS << " OperandsValid = (it->Classes[i] == " <<"InvalidMatchClass);\n"; 2424 OS << " break;\n"; 2425 OS << " }\n"; 2426 OS << " if (validateOperandClass(Operands[i+1], " 2427 "(MatchClassKind)it->Classes[i]))\n"; 2428 OS << " continue;\n"; 2429 OS << " // If this operand is broken for all of the instances of this\n"; 2430 OS << " // mnemonic, keep track of it so we can report loc info.\n"; 2431 OS << " if (it == MnemonicRange.first || ErrorInfo <= i+1)\n"; 2432 OS << " ErrorInfo = i+1;\n"; 2433 OS << " // Otherwise, just reject this instance of the mnemonic.\n"; 2434 OS << " OperandsValid = false;\n"; 2435 OS << " break;\n"; 2436 OS << " }\n\n"; 2437 2438 OS << " if (!OperandsValid) continue;\n"; 2439 2440 // Emit check that the required features are available. 2441 OS << " if ((AvailableFeatures & it->RequiredFeatures) " 2442 << "!= it->RequiredFeatures) {\n"; 2443 OS << " HadMatchOtherThanFeatures = true;\n"; 2444 OS << " continue;\n"; 2445 OS << " }\n"; 2446 OS << "\n"; 2447 OS << " // We have selected a definite instruction, convert the parsed\n" 2448 << " // operands into the appropriate MCInst.\n"; 2449 OS << " if (!ConvertToMCInst(it->ConvertFn, Inst,\n" 2450 << " it->Opcode, Operands))\n"; 2451 OS << " return Match_ConversionFail;\n"; 2452 OS << "\n"; 2453 2454 // Verify the instruction with the target-specific match predicate function. 2455 OS << " // We have a potential match. Check the target predicate to\n" 2456 << " // handle any context sensitive constraints.\n" 2457 << " unsigned MatchResult;\n" 2458 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !=" 2459 << " Match_Success) {\n" 2460 << " Inst.clear();\n" 2461 << " RetCode = MatchResult;\n" 2462 << " HadMatchOtherThanPredicate = true;\n" 2463 << " continue;\n" 2464 << " }\n\n"; 2465 2466 // Call the post-processing function, if used. 2467 std::string InsnCleanupFn = 2468 AsmParser->getValueAsString("AsmParserInstCleanup"); 2469 if (!InsnCleanupFn.empty()) 2470 OS << " " << InsnCleanupFn << "(Inst);\n"; 2471 2472 OS << " return Match_Success;\n"; 2473 OS << " }\n\n"; 2474 2475 OS << " // Okay, we had no match. Try to return a useful error code.\n"; 2476 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)"; 2477 OS << " return RetCode;\n"; 2478 OS << " return Match_MissingFeature;\n"; 2479 OS << "}\n\n"; 2480 2481 if (Info.OperandMatchInfo.size()) 2482 EmitCustomOperandParsing(OS, Target, Info, ClassName); 2483 2484 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n"; 2485} 2486