1 //===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend emits a target specifier matcher for converting parsed
11 // assembly operands in the MCInst structures.
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
20 // Some example inputs, for X86:
21 // 'addl' (immediate ...) (register ...)
22 // 'add' (immediate ...) (memory ...)
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:
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.
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
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.
48 // The matching is divided into two distinct phases:
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.
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).
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.
63 // In addition, the subset relation amongst classes induces a partial order
64 // on such tuples, which we use to resolve ambiguities.
66 // FIXME: What do we do if a crazy case shows up where this is the wrong
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.
74 //===----------------------------------------------------------------------===//
76 #include "AsmMatcherEmitter.h"
77 #include "CodeGenTarget.h"
79 #include "llvm/ADT/OwningPtr.h"
80 #include "llvm/ADT/SmallVector.h"
81 #include "llvm/ADT/STLExtras.h"
82 #include "llvm/ADT/StringExtras.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/Debug.h"
90 static cl::opt<std::string>
91 MatchPrefix("match-prefix", cl::init(""),
92 cl::desc("Only match instructions with the given prefix"));
94 /// FlattenVariants - Flatten an .td file assembly string by selecting the
95 /// variant at index \arg N.
96 static std::string FlattenVariants(const std::string &AsmString,
98 StringRef Cur = AsmString;
102 // Find the start of the next variant string.
103 size_t VariantsStart = 0;
104 for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
105 if (Cur[VariantsStart] == '{' &&
106 (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
107 Cur[VariantsStart-1] != '\\')))
110 // Add the prefix to the result.
111 Res += Cur.slice(0, VariantsStart);
112 if (VariantsStart == Cur.size())
115 ++VariantsStart; // Skip the '{'.
117 // Scan to the end of the variants string.
118 size_t VariantsEnd = VariantsStart;
119 unsigned NestedBraces = 1;
120 for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
121 if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
122 if (--NestedBraces == 0)
124 } else if (Cur[VariantsEnd] == '{')
128 // Select the Nth variant (or empty).
129 StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
130 for (unsigned i = 0; i != N; ++i)
131 Selection = Selection.split('|').second;
132 Res += Selection.split('|').first;
134 assert(VariantsEnd != Cur.size() &&
135 "Unterminated variants in assembly string!");
136 Cur = Cur.substr(VariantsEnd + 1);
142 /// TokenizeAsmString - Tokenize a simplified assembly string.
143 static void TokenizeAsmString(const StringRef &AsmString,
144 SmallVectorImpl<StringRef> &Tokens) {
147 for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {
148 switch (AsmString[i]) {
157 Tokens.push_back(AsmString.slice(Prev, i));
160 if (!isspace(AsmString[i]) && AsmString[i] != ',')
161 Tokens.push_back(AsmString.substr(i, 1));
167 Tokens.push_back(AsmString.slice(Prev, i));
171 assert(i != AsmString.size() && "Invalid quoted character");
172 Tokens.push_back(AsmString.substr(i, 1));
177 // If this isn't "${", treat like a normal token.
178 if (i + 1 == AsmString.size() || AsmString[i + 1] != '{') {
180 Tokens.push_back(AsmString.slice(Prev, i));
188 Tokens.push_back(AsmString.slice(Prev, i));
192 StringRef::iterator End =
193 std::find(AsmString.begin() + i, AsmString.end(), '}');
194 assert(End != AsmString.end() && "Missing brace in operand reference!");
195 size_t EndPos = End - AsmString.begin();
196 Tokens.push_back(AsmString.slice(i, EndPos+1));
206 if (InTok && Prev != AsmString.size())
207 Tokens.push_back(AsmString.substr(Prev));
210 static bool IsAssemblerInstruction(const StringRef &Name,
211 const CodeGenInstruction &CGI,
212 const SmallVectorImpl<StringRef> &Tokens) {
213 // Ignore "codegen only" instructions.
214 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
217 // Ignore pseudo ops.
219 // FIXME: This is a hack; can we convert these instructions to set the
220 // "codegen only" bit instead?
221 if (const RecordVal *Form = CGI.TheDef->getValue("Form"))
222 if (Form->getValue()->getAsString() == "Pseudo")
225 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
227 // FIXME: This is a total hack.
228 if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
231 // Ignore instructions with no .s string.
233 // FIXME: What are these?
234 if (CGI.AsmString.empty())
237 // FIXME: Hack; ignore any instructions with a newline in them.
238 if (std::find(CGI.AsmString.begin(),
239 CGI.AsmString.end(), '\n') != CGI.AsmString.end())
242 // Ignore instructions with attributes, these are always fake instructions for
243 // simplifying codegen.
245 // FIXME: Is this true?
247 // Also, check for instructions which reference the operand multiple times;
248 // this implies a constraint we would not honor.
249 std::set<std::string> OperandNames;
250 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
251 if (Tokens[i][0] == '$' &&
252 std::find(Tokens[i].begin(),
253 Tokens[i].end(), ':') != Tokens[i].end()) {
255 errs() << "warning: '" << Name << "': "
256 << "ignoring instruction; operand with attribute '"
257 << Tokens[i] << "'\n";
262 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
263 std::string Err = "'" + Name.str() + "': " +
264 "invalid assembler instruction; tied operand '" + Tokens[i].str() + "'";
265 throw TGError(CGI.TheDef->getLoc(), Err);
274 /// ClassInfo - Helper class for storing the information about a particular
275 /// class of operands which can be matched.
278 /// Invalid kind, for use as a sentinel value.
281 /// The class for a particular token.
284 /// The (first) register class, subsequent register classes are
285 /// RegisterClass0+1, and so on.
288 /// The (first) user defined class, subsequent user defined classes are
289 /// UserClass0+1, and so on.
293 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
294 /// N) for the Nth user defined class.
297 /// SuperClasses - The super classes of this class. Note that for simplicities
298 /// sake user operands only record their immediate super class, while register
299 /// operands include all superclasses.
300 std::vector<ClassInfo*> SuperClasses;
302 /// Name - The full class name, suitable for use in an enum.
305 /// ClassName - The unadorned generic name for this class (e.g., Token).
306 std::string ClassName;
308 /// ValueName - The name of the value this class represents; for a token this
309 /// is the literal token string, for an operand it is the TableGen class (or
310 /// empty if this is a derived class).
311 std::string ValueName;
313 /// PredicateMethod - The name of the operand method to test whether the
314 /// operand matches this class; this is not valid for Token or register kinds.
315 std::string PredicateMethod;
317 /// RenderMethod - The name of the operand method to add this operand to an
318 /// MCInst; this is not valid for Token or register kinds.
319 std::string RenderMethod;
321 /// For register classes, the records for all the registers in this class.
322 std::set<Record*> Registers;
325 /// isRegisterClass() - Check if this is a register class.
326 bool isRegisterClass() const {
327 return Kind >= RegisterClass0 && Kind < UserClass0;
330 /// isUserClass() - Check if this is a user defined class.
331 bool isUserClass() const {
332 return Kind >= UserClass0;
335 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
336 /// are related if they are in the same class hierarchy.
337 bool isRelatedTo(const ClassInfo &RHS) const {
338 // Tokens are only related to tokens.
339 if (Kind == Token || RHS.Kind == Token)
340 return Kind == Token && RHS.Kind == Token;
342 // Registers classes are only related to registers classes, and only if
343 // their intersection is non-empty.
344 if (isRegisterClass() || RHS.isRegisterClass()) {
345 if (!isRegisterClass() || !RHS.isRegisterClass())
348 std::set<Record*> Tmp;
349 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
350 std::set_intersection(Registers.begin(), Registers.end(),
351 RHS.Registers.begin(), RHS.Registers.end(),
357 // Otherwise we have two users operands; they are related if they are in the
358 // same class hierarchy.
360 // FIXME: This is an oversimplification, they should only be related if they
361 // intersect, however we don't have that information.
362 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
363 const ClassInfo *Root = this;
364 while (!Root->SuperClasses.empty())
365 Root = Root->SuperClasses.front();
367 const ClassInfo *RHSRoot = &RHS;
368 while (!RHSRoot->SuperClasses.empty())
369 RHSRoot = RHSRoot->SuperClasses.front();
371 return Root == RHSRoot;
374 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
375 bool isSubsetOf(const ClassInfo &RHS) const {
376 // This is a subset of RHS if it is the same class...
380 // ... or if any of its super classes are a subset of RHS.
381 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
382 ie = SuperClasses.end(); it != ie; ++it)
383 if ((*it)->isSubsetOf(RHS))
389 /// operator< - Compare two classes.
390 bool operator<(const ClassInfo &RHS) const {
391 // Unrelated classes can be ordered by kind.
392 if (!isRelatedTo(RHS))
393 return Kind < RHS.Kind;
397 assert(0 && "Invalid kind!");
399 // Tokens are comparable by value.
401 // FIXME: Compare by enum value.
402 return ValueName < RHS.ValueName;
405 // This class preceeds the RHS if it is a proper subset of the RHS.
406 return this != &RHS && isSubsetOf(RHS);
411 /// InstructionInfo - Helper class for storing the necessary information for an
412 /// instruction which is capable of being matched.
413 struct InstructionInfo {
415 /// The unique class instance this operand should match.
418 /// The original operand this corresponds to, if any.
419 const CodeGenInstruction::OperandInfo *OperandInfo;
422 /// InstrName - The target name for this instruction.
423 std::string InstrName;
425 /// Instr - The instruction this matches.
426 const CodeGenInstruction *Instr;
428 /// AsmString - The assembly string for this instruction (with variants
430 std::string AsmString;
432 /// Tokens - The tokenized assembly pattern that this instruction matches.
433 SmallVector<StringRef, 4> Tokens;
435 /// Operands - The operands that this instruction matches.
436 SmallVector<Operand, 4> Operands;
438 /// ConversionFnKind - The enum value which is passed to the generated
439 /// ConvertToMCInst to convert parsed operands into an MCInst for this
441 std::string ConversionFnKind;
443 /// operator< - Compare two instructions.
444 bool operator<(const InstructionInfo &RHS) const {
445 if (Operands.size() != RHS.Operands.size())
446 return Operands.size() < RHS.Operands.size();
448 // Compare lexicographically by operand. The matcher validates that other
449 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
450 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
451 if (*Operands[i].Class < *RHS.Operands[i].Class)
453 if (*RHS.Operands[i].Class < *Operands[i].Class)
460 /// CouldMatchAmiguouslyWith - Check whether this instruction could
461 /// ambiguously match the same set of operands as \arg RHS (without being a
462 /// strictly superior match).
463 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
464 // The number of operands is unambiguous.
465 if (Operands.size() != RHS.Operands.size())
468 // Tokens and operand kinds are unambiguous (assuming a correct target
470 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
471 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
472 Operands[i].Class->Kind == ClassInfo::Token)
473 if (*Operands[i].Class < *RHS.Operands[i].Class ||
474 *RHS.Operands[i].Class < *Operands[i].Class)
477 // Otherwise, this operand could commute if all operands are equivalent, or
478 // there is a pair of operands that compare less than and a pair that
479 // compare greater than.
480 bool HasLT = false, HasGT = false;
481 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
482 if (*Operands[i].Class < *RHS.Operands[i].Class)
484 if (*RHS.Operands[i].Class < *Operands[i].Class)
488 return !(HasLT ^ HasGT);
495 class AsmMatcherInfo {
497 /// The tablegen AsmParser record.
500 /// The AsmParser "CommentDelimiter" value.
501 std::string CommentDelimiter;
503 /// The AsmParser "RegisterPrefix" value.
504 std::string RegisterPrefix;
506 /// The classes which are needed for matching.
507 std::vector<ClassInfo*> Classes;
509 /// The information on the instruction to match.
510 std::vector<InstructionInfo*> Instructions;
512 /// Map of Register records to their class information.
513 std::map<Record*, ClassInfo*> RegisterClasses;
516 /// Map of token to class information which has already been constructed.
517 std::map<std::string, ClassInfo*> TokenClasses;
519 /// Map of RegisterClass records to their class information.
520 std::map<Record*, ClassInfo*> RegisterClassClasses;
522 /// Map of AsmOperandClass records to their class information.
523 std::map<Record*, ClassInfo*> AsmOperandClasses;
526 /// getTokenClass - Lookup or create the class for the given token.
527 ClassInfo *getTokenClass(const StringRef &Token);
529 /// getOperandClass - Lookup or create the class for the given operand.
530 ClassInfo *getOperandClass(const StringRef &Token,
531 const CodeGenInstruction::OperandInfo &OI);
533 /// BuildRegisterClasses - Build the ClassInfo* instances for register
535 void BuildRegisterClasses(CodeGenTarget &Target,
536 std::set<std::string> &SingletonRegisterNames);
538 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
540 void BuildOperandClasses(CodeGenTarget &Target);
543 AsmMatcherInfo(Record *_AsmParser);
545 /// BuildInfo - Construct the various tables used during matching.
546 void BuildInfo(CodeGenTarget &Target);
551 void InstructionInfo::dump() {
552 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
554 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
561 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
562 Operand &Op = Operands[i];
563 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
564 if (Op.Class->Kind == ClassInfo::Token) {
565 errs() << '\"' << Tokens[i] << "\"\n";
569 if (!Op.OperandInfo) {
570 errs() << "(singleton register)\n";
574 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
575 errs() << OI.Name << " " << OI.Rec->getName()
576 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
580 static std::string getEnumNameForToken(const StringRef &Str) {
583 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
585 case '*': Res += "_STAR_"; break;
586 case '%': Res += "_PCT_"; break;
587 case ':': Res += "_COLON_"; break;
593 Res += "_" + utostr((unsigned) *it) + "_";
601 /// getRegisterRecord - Get the register record for \arg name, or 0.
602 static Record *getRegisterRecord(CodeGenTarget &Target, const StringRef &Name) {
603 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
604 const CodeGenRegister &Reg = Target.getRegisters()[i];
605 if (Name == Reg.TheDef->getValueAsString("AsmName"))
612 ClassInfo *AsmMatcherInfo::getTokenClass(const StringRef &Token) {
613 ClassInfo *&Entry = TokenClasses[Token];
616 Entry = new ClassInfo();
617 Entry->Kind = ClassInfo::Token;
618 Entry->ClassName = "Token";
619 Entry->Name = "MCK_" + getEnumNameForToken(Token);
620 Entry->ValueName = Token;
621 Entry->PredicateMethod = "<invalid>";
622 Entry->RenderMethod = "<invalid>";
623 Classes.push_back(Entry);
630 AsmMatcherInfo::getOperandClass(const StringRef &Token,
631 const CodeGenInstruction::OperandInfo &OI) {
632 if (OI.Rec->isSubClassOf("RegisterClass")) {
633 ClassInfo *CI = RegisterClassClasses[OI.Rec];
636 PrintError(OI.Rec->getLoc(), "register class has no class info!");
637 throw std::string("ERROR: Missing register class!");
643 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
644 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
645 ClassInfo *CI = AsmOperandClasses[MatchClass];
648 PrintError(OI.Rec->getLoc(), "operand has no match class!");
649 throw std::string("ERROR: Missing match class!");
655 void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target,
656 std::set<std::string>
657 &SingletonRegisterNames) {
658 std::vector<CodeGenRegisterClass> RegisterClasses;
659 std::vector<CodeGenRegister> Registers;
661 RegisterClasses = Target.getRegisterClasses();
662 Registers = Target.getRegisters();
664 // The register sets used for matching.
665 std::set< std::set<Record*> > RegisterSets;
667 // Gather the defined sets.
668 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
669 ie = RegisterClasses.end(); it != ie; ++it)
670 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
671 it->Elements.end()));
673 // Add any required singleton sets.
674 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
675 ie = SingletonRegisterNames.end(); it != ie; ++it)
676 if (Record *Rec = getRegisterRecord(Target, *it))
677 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
679 // Introduce derived sets where necessary (when a register does not determine
680 // a unique register set class), and build the mapping of registers to the set
681 // they should classify to.
682 std::map<Record*, std::set<Record*> > RegisterMap;
683 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
684 ie = Registers.end(); it != ie; ++it) {
685 CodeGenRegister &CGR = *it;
686 // Compute the intersection of all sets containing this register.
687 std::set<Record*> ContainingSet;
689 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
690 ie = RegisterSets.end(); it != ie; ++it) {
691 if (!it->count(CGR.TheDef))
694 if (ContainingSet.empty()) {
697 std::set<Record*> Tmp;
698 std::swap(Tmp, ContainingSet);
699 std::insert_iterator< std::set<Record*> > II(ContainingSet,
700 ContainingSet.begin());
701 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
706 if (!ContainingSet.empty()) {
707 RegisterSets.insert(ContainingSet);
708 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
712 // Construct the register classes.
713 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
715 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
716 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
717 ClassInfo *CI = new ClassInfo();
718 CI->Kind = ClassInfo::RegisterClass0 + Index;
719 CI->ClassName = "Reg" + utostr(Index);
720 CI->Name = "MCK_Reg" + utostr(Index);
722 CI->PredicateMethod = ""; // unused
723 CI->RenderMethod = "addRegOperands";
725 Classes.push_back(CI);
726 RegisterSetClasses.insert(std::make_pair(*it, CI));
729 // Find the superclasses; we could compute only the subgroup lattice edges,
730 // but there isn't really a point.
731 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
732 ie = RegisterSets.end(); it != ie; ++it) {
733 ClassInfo *CI = RegisterSetClasses[*it];
734 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
735 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
737 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
738 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
741 // Name the register classes which correspond to a user defined RegisterClass.
742 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
743 ie = RegisterClasses.end(); it != ie; ++it) {
744 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
745 it->Elements.end())];
746 if (CI->ValueName.empty()) {
747 CI->ClassName = it->getName();
748 CI->Name = "MCK_" + it->getName();
749 CI->ValueName = it->getName();
751 CI->ValueName = CI->ValueName + "," + it->getName();
753 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
756 // Populate the map for individual registers.
757 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
758 ie = RegisterMap.end(); it != ie; ++it)
759 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
761 // Name the register classes which correspond to singleton registers.
762 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
763 ie = SingletonRegisterNames.end(); it != ie; ++it) {
764 if (Record *Rec = getRegisterRecord(Target, *it)) {
765 ClassInfo *CI = this->RegisterClasses[Rec];
766 assert(CI && "Missing singleton register class info!");
768 if (CI->ValueName.empty()) {
769 CI->ClassName = Rec->getName();
770 CI->Name = "MCK_" + Rec->getName();
771 CI->ValueName = Rec->getName();
773 CI->ValueName = CI->ValueName + "," + Rec->getName();
778 void AsmMatcherInfo::BuildOperandClasses(CodeGenTarget &Target) {
779 std::vector<Record*> AsmOperands;
780 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
782 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
783 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
784 ClassInfo *CI = new ClassInfo();
785 CI->Kind = ClassInfo::UserClass0 + Index;
787 Init *Super = (*it)->getValueInit("SuperClass");
788 if (DefInit *DI = dynamic_cast<DefInit*>(Super)) {
789 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
791 PrintError((*it)->getLoc(), "Invalid super class reference!");
793 CI->SuperClasses.push_back(SC);
795 assert(dynamic_cast<UnsetInit*>(Super) && "Unexpected SuperClass field!");
797 CI->ClassName = (*it)->getValueAsString("Name");
798 CI->Name = "MCK_" + CI->ClassName;
799 CI->ValueName = (*it)->getName();
801 // Get or construct the predicate method name.
802 Init *PMName = (*it)->getValueInit("PredicateMethod");
803 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
804 CI->PredicateMethod = SI->getValue();
806 assert(dynamic_cast<UnsetInit*>(PMName) &&
807 "Unexpected PredicateMethod field!");
808 CI->PredicateMethod = "is" + CI->ClassName;
811 // Get or construct the render method name.
812 Init *RMName = (*it)->getValueInit("RenderMethod");
813 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
814 CI->RenderMethod = SI->getValue();
816 assert(dynamic_cast<UnsetInit*>(RMName) &&
817 "Unexpected RenderMethod field!");
818 CI->RenderMethod = "add" + CI->ClassName + "Operands";
821 AsmOperandClasses[*it] = CI;
822 Classes.push_back(CI);
826 AsmMatcherInfo::AsmMatcherInfo(Record *_AsmParser)
827 : AsmParser(_AsmParser),
828 CommentDelimiter(AsmParser->getValueAsString("CommentDelimiter")),
829 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix"))
833 void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
834 // Parse the instructions; we need to do this first so that we can gather the
835 // singleton register classes.
836 std::set<std::string> SingletonRegisterNames;
837 for (std::map<std::string, CodeGenInstruction>::const_iterator
838 it = Target.getInstructions().begin(),
839 ie = Target.getInstructions().end();
841 const CodeGenInstruction &CGI = it->second;
843 if (!StringRef(it->first).startswith(MatchPrefix))
846 OwningPtr<InstructionInfo> II(new InstructionInfo);
848 II->InstrName = it->first;
849 II->Instr = &it->second;
850 II->AsmString = FlattenVariants(CGI.AsmString, 0);
852 // Remove comments from the asm string.
853 if (!CommentDelimiter.empty()) {
854 size_t Idx = StringRef(II->AsmString).find(CommentDelimiter);
855 if (Idx != StringRef::npos)
856 II->AsmString = II->AsmString.substr(0, Idx);
859 TokenizeAsmString(II->AsmString, II->Tokens);
861 // Ignore instructions which shouldn't be matched.
862 if (!IsAssemblerInstruction(it->first, CGI, II->Tokens))
865 // Collect singleton registers, if used.
866 if (!RegisterPrefix.empty()) {
867 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
868 if (II->Tokens[i].startswith(RegisterPrefix)) {
869 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
870 Record *Rec = getRegisterRecord(Target, RegName);
873 std::string Err = "unable to find register for '" + RegName.str() +
874 "' (which matches register prefix)";
875 throw TGError(CGI.TheDef->getLoc(), Err);
878 SingletonRegisterNames.insert(RegName);
883 Instructions.push_back(II.take());
886 // Build info for the register classes.
887 BuildRegisterClasses(Target, SingletonRegisterNames);
889 // Build info for the user defined assembly operand classes.
890 BuildOperandClasses(Target);
892 // Build the instruction information.
893 for (std::vector<InstructionInfo*>::iterator it = Instructions.begin(),
894 ie = Instructions.end(); it != ie; ++it) {
895 InstructionInfo *II = *it;
897 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
898 StringRef Token = II->Tokens[i];
900 // Check for singleton registers.
901 if (!RegisterPrefix.empty() && Token.startswith(RegisterPrefix)) {
902 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
903 InstructionInfo::Operand Op;
904 Op.Class = RegisterClasses[getRegisterRecord(Target, RegName)];
906 assert(Op.Class && Op.Class->Registers.size() == 1 &&
907 "Unexpected class for singleton register");
908 II->Operands.push_back(Op);
912 // Check for simple tokens.
913 if (Token[0] != '$') {
914 InstructionInfo::Operand Op;
915 Op.Class = getTokenClass(Token);
917 II->Operands.push_back(Op);
921 // Otherwise this is an operand reference.
922 StringRef OperandName;
924 OperandName = Token.substr(2, Token.size() - 3);
926 OperandName = Token.substr(1);
928 // Map this token to an operand. FIXME: Move elsewhere.
931 Idx = II->Instr->getOperandNamed(OperandName);
933 throw std::string("error: unable to find operand: '" +
934 OperandName.str() + "'");
937 const CodeGenInstruction::OperandInfo &OI = II->Instr->OperandList[Idx];
938 InstructionInfo::Operand Op;
939 Op.Class = getOperandClass(Token, OI);
940 Op.OperandInfo = &OI;
941 II->Operands.push_back(Op);
945 // Reorder classes so that classes preceed super classes.
946 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
949 static void EmitConvertToMCInst(CodeGenTarget &Target,
950 std::vector<InstructionInfo*> &Infos,
952 // Write the convert function to a separate stream, so we can drop it after
954 std::string ConvertFnBody;
955 raw_string_ostream CvtOS(ConvertFnBody);
957 // Function we have already generated.
958 std::set<std::string> GeneratedFns;
960 // Start the unified conversion function.
962 CvtOS << "static bool ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
963 << "unsigned Opcode,\n"
964 << " const SmallVectorImpl<MCParsedAsmOperand*"
965 << "> &Operands) {\n";
966 CvtOS << " Inst.setOpcode(Opcode);\n";
967 CvtOS << " switch (Kind) {\n";
968 CvtOS << " default:\n";
970 // Start the enum, which we will generate inline.
972 OS << "// Unified function for converting operants to MCInst instances.\n\n";
973 OS << "enum ConversionKind {\n";
975 // TargetOperandClass - This is the target's operand class, like X86Operand.
976 std::string TargetOperandClass = Target.getName() + "Operand";
978 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
979 ie = Infos.end(); it != ie; ++it) {
980 InstructionInfo &II = **it;
982 // Order the (class) operands by the order to convert them into an MCInst.
983 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
984 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
985 InstructionInfo::Operand &Op = II.Operands[i];
987 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
989 std::sort(MIOperandList.begin(), MIOperandList.end());
991 // Compute the total number of operands.
992 unsigned NumMIOperands = 0;
993 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
994 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
995 NumMIOperands = std::max(NumMIOperands,
996 OI.MIOperandNo + OI.MINumOperands);
999 // Build the conversion function signature.
1000 std::string Signature = "Convert";
1001 unsigned CurIndex = 0;
1002 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1003 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1004 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
1005 "Duplicate match for instruction operand!");
1009 // Skip operands which weren't matched by anything, this occurs when the
1010 // .td file encodes "implicit" operands as explicit ones.
1012 // FIXME: This should be removed from the MCInst structure.
1013 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
1016 // Registers are always converted the same, don't duplicate the conversion
1017 // function based on them.
1019 // FIXME: We could generalize this based on the render method, if it
1021 if (Op.Class->isRegisterClass())
1024 Signature += Op.Class->ClassName;
1025 Signature += utostr(Op.OperandInfo->MINumOperands);
1026 Signature += "_" + utostr(MIOperandList[i].second);
1028 CurIndex += Op.OperandInfo->MINumOperands;
1031 // Add any trailing implicit operands.
1032 for (; CurIndex != NumMIOperands; ++CurIndex)
1035 II.ConversionFnKind = Signature;
1037 // Check if we have already generated this signature.
1038 if (!GeneratedFns.insert(Signature).second)
1041 // If not, emit it now.
1043 // Add to the enum list.
1044 OS << " " << Signature << ",\n";
1046 // And to the convert function.
1047 CvtOS << " case " << Signature << ":\n";
1049 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1050 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1052 // Add the implicit operands.
1053 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
1054 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1056 CvtOS << " ((" << TargetOperandClass << "*)Operands["
1057 << MIOperandList[i].second
1058 << "])->" << Op.Class->RenderMethod
1059 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
1060 CurIndex += Op.OperandInfo->MINumOperands;
1063 // And add trailing implicit operands.
1064 for (; CurIndex != NumMIOperands; ++CurIndex)
1065 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1066 CvtOS << " break;\n";
1069 // Finish the convert function.
1072 CvtOS << " return false;\n";
1075 // Finish the enum, and drop the convert function after it.
1077 OS << " NumConversionVariants\n";
1083 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1084 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1085 std::vector<ClassInfo*> &Infos,
1087 OS << "namespace {\n\n";
1089 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1090 << "/// instruction matching.\n";
1091 OS << "enum MatchClassKind {\n";
1092 OS << " InvalidMatchClass = 0,\n";
1093 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1094 ie = Infos.end(); it != ie; ++it) {
1095 ClassInfo &CI = **it;
1096 OS << " " << CI.Name << ", // ";
1097 if (CI.Kind == ClassInfo::Token) {
1098 OS << "'" << CI.ValueName << "'\n";
1099 } else if (CI.isRegisterClass()) {
1100 if (!CI.ValueName.empty())
1101 OS << "register class '" << CI.ValueName << "'\n";
1103 OS << "derived register class\n";
1105 OS << "user defined class '" << CI.ValueName << "'\n";
1108 OS << " NumMatchClassKinds\n";
1114 /// EmitClassifyOperand - Emit the function to classify an operand.
1115 static void EmitClassifyOperand(CodeGenTarget &Target,
1116 AsmMatcherInfo &Info,
1118 OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
1119 << " " << Target.getName() << "Operand &Operand = *("
1120 << Target.getName() << "Operand*)GOp;\n";
1123 OS << " if (Operand.isToken())\n";
1124 OS << " return MatchTokenString(Operand.getToken());\n\n";
1126 // Classify registers.
1128 // FIXME: Don't hardcode isReg, getReg.
1129 OS << " if (Operand.isReg()) {\n";
1130 OS << " switch (Operand.getReg()) {\n";
1131 OS << " default: return InvalidMatchClass;\n";
1132 for (std::map<Record*, ClassInfo*>::iterator
1133 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1135 OS << " case " << Target.getName() << "::"
1136 << it->first->getName() << ": return " << it->second->Name << ";\n";
1140 // Classify user defined operands.
1141 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1142 ie = Info.Classes.end(); it != ie; ++it) {
1143 ClassInfo &CI = **it;
1145 if (!CI.isUserClass())
1148 OS << " // '" << CI.ClassName << "' class";
1149 if (!CI.SuperClasses.empty()) {
1150 OS << ", subclass of ";
1151 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1153 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1154 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
1159 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
1161 // Validate subclass relationships.
1162 if (!CI.SuperClasses.empty()) {
1163 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1164 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1165 << "() && \"Invalid class relationship!\");\n";
1168 OS << " return " << CI.Name << ";\n";
1171 OS << " return InvalidMatchClass;\n";
1175 /// EmitIsSubclass - Emit the subclass predicate function.
1176 static void EmitIsSubclass(CodeGenTarget &Target,
1177 std::vector<ClassInfo*> &Infos,
1179 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1180 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1181 OS << " if (A == B)\n";
1182 OS << " return true;\n\n";
1184 OS << " switch (A) {\n";
1185 OS << " default:\n";
1186 OS << " return false;\n";
1187 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1188 ie = Infos.end(); it != ie; ++it) {
1189 ClassInfo &A = **it;
1191 if (A.Kind != ClassInfo::Token) {
1192 std::vector<StringRef> SuperClasses;
1193 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1194 ie = Infos.end(); it != ie; ++it) {
1195 ClassInfo &B = **it;
1197 if (&A != &B && A.isSubsetOf(B))
1198 SuperClasses.push_back(B.Name);
1201 if (SuperClasses.empty())
1204 OS << "\n case " << A.Name << ":\n";
1206 if (SuperClasses.size() == 1) {
1207 OS << " return B == " << SuperClasses.back() << ";\n";
1211 OS << " switch (B) {\n";
1212 OS << " default: return false;\n";
1213 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1214 OS << " case " << SuperClasses[i] << ": return true;\n";
1222 typedef std::pair<std::string, std::string> StringPair;
1224 /// FindFirstNonCommonLetter - Find the first character in the keys of the
1225 /// string pairs that is not shared across the whole set of strings. All
1226 /// strings are assumed to have the same length.
1228 FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
1229 assert(!Matches.empty());
1230 for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
1231 // Check to see if letter i is the same across the set.
1232 char Letter = Matches[0]->first[i];
1234 for (unsigned str = 0, e = Matches.size(); str != e; ++str)
1235 if (Matches[str]->first[i] != Letter)
1239 return Matches[0]->first.size();
1242 /// EmitStringMatcherForChar - Given a set of strings that are known to be the
1243 /// same length and whose characters leading up to CharNo are the same, emit
1244 /// code to verify that CharNo and later are the same.
1246 /// \return - True if control can leave the emitted code fragment.
1247 static bool EmitStringMatcherForChar(const std::string &StrVariableName,
1248 const std::vector<const StringPair*> &Matches,
1249 unsigned CharNo, unsigned IndentCount,
1251 assert(!Matches.empty() && "Must have at least one string to match!");
1252 std::string Indent(IndentCount*2+4, ' ');
1254 // If we have verified that the entire string matches, we're done: output the
1256 if (CharNo == Matches[0]->first.size()) {
1257 assert(Matches.size() == 1 && "Had duplicate keys to match on");
1259 // FIXME: If Matches[0].first has embeded \n, this will be bad.
1260 OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
1265 // Bucket the matches by the character we are comparing.
1266 std::map<char, std::vector<const StringPair*> > MatchesByLetter;
1268 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1269 MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
1272 // If we have exactly one bucket to match, see how many characters are common
1273 // across the whole set and match all of them at once.
1274 if (MatchesByLetter.size() == 1) {
1275 unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
1276 unsigned NumChars = FirstNonCommonLetter-CharNo;
1278 // Emit code to break out if the prefix doesn't match.
1279 if (NumChars == 1) {
1280 // Do the comparison with if (Str[1] != 'f')
1281 // FIXME: Need to escape general characters.
1282 OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
1283 << Matches[0]->first[CharNo] << "')\n";
1284 OS << Indent << " break;\n";
1286 // Do the comparison with if (Str.substr(1,3) != "foo").
1287 // FIXME: Need to escape general strings.
1288 OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
1289 << NumChars << ") != \"";
1290 OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
1291 OS << Indent << " break;\n";
1294 return EmitStringMatcherForChar(StrVariableName, Matches,
1295 FirstNonCommonLetter, IndentCount, OS);
1298 // Otherwise, we have multiple possible things, emit a switch on the
1300 OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
1301 OS << Indent << "default: break;\n";
1303 for (std::map<char, std::vector<const StringPair*> >::iterator LI =
1304 MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
1305 // TODO: escape hard stuff (like \n) if we ever care about it.
1306 OS << Indent << "case '" << LI->first << "':\t // "
1307 << LI->second.size() << " strings to match.\n";
1308 if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
1310 OS << Indent << " break;\n";
1313 OS << Indent << "}\n";
1318 /// EmitStringMatcher - Given a list of strings and code to execute when they
1319 /// match, output a simple switch tree to classify the input string.
1321 /// If a match is found, the code in Vals[i].second is executed; control must
1322 /// not exit this code fragment. If nothing matches, execution falls through.
1324 /// \param StrVariableName - The name of the variable to test.
1325 static void EmitStringMatcher(const std::string &StrVariableName,
1326 const std::vector<StringPair> &Matches,
1328 // First level categorization: group strings by length.
1329 std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
1331 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1332 MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
1334 // Output a switch statement on length and categorize the elements within each
1336 OS << " switch (" << StrVariableName << ".size()) {\n";
1337 OS << " default: break;\n";
1339 for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
1340 MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
1341 OS << " case " << LI->first << ":\t // " << LI->second.size()
1342 << " strings to match.\n";
1343 if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
1351 /// EmitMatchTokenString - Emit the function to match a token string to the
1352 /// appropriate match class value.
1353 static void EmitMatchTokenString(CodeGenTarget &Target,
1354 std::vector<ClassInfo*> &Infos,
1356 // Construct the match list.
1357 std::vector<StringPair> Matches;
1358 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1359 ie = Infos.end(); it != ie; ++it) {
1360 ClassInfo &CI = **it;
1362 if (CI.Kind == ClassInfo::Token)
1363 Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
1366 OS << "static MatchClassKind MatchTokenString(const StringRef &Name) {\n";
1368 EmitStringMatcher("Name", Matches, OS);
1370 OS << " return InvalidMatchClass;\n";
1374 /// EmitMatchRegisterName - Emit the function to match a string to the target
1375 /// specific register enum.
1376 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1378 // Construct the match list.
1379 std::vector<StringPair> Matches;
1380 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1381 const CodeGenRegister &Reg = Target.getRegisters()[i];
1382 if (Reg.TheDef->getValueAsString("AsmName").empty())
1385 Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
1386 "return " + utostr(i + 1) + ";"));
1389 OS << "unsigned " << Target.getName()
1390 << AsmParser->getValueAsString("AsmParserClassName")
1391 << "::MatchRegisterName(const StringRef &Name) {\n";
1393 EmitStringMatcher("Name", Matches, OS);
1395 OS << " return 0;\n";
1399 void AsmMatcherEmitter::run(raw_ostream &OS) {
1400 CodeGenTarget Target;
1401 Record *AsmParser = Target.getAsmParser();
1402 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1404 // Compute the information on the instructions to match.
1405 AsmMatcherInfo Info(AsmParser);
1406 Info.BuildInfo(Target);
1408 // Sort the instruction table using the partial order on classes.
1409 std::sort(Info.Instructions.begin(), Info.Instructions.end(),
1410 less_ptr<InstructionInfo>());
1412 DEBUG_WITH_TYPE("instruction_info", {
1413 for (std::vector<InstructionInfo*>::iterator
1414 it = Info.Instructions.begin(), ie = Info.Instructions.end();
1419 // Check for ambiguous instructions.
1420 unsigned NumAmbiguous = 0;
1421 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1422 for (unsigned j = i + 1; j != e; ++j) {
1423 InstructionInfo &A = *Info.Instructions[i];
1424 InstructionInfo &B = *Info.Instructions[j];
1426 if (A.CouldMatchAmiguouslyWith(B)) {
1427 DEBUG_WITH_TYPE("ambiguous_instrs", {
1428 errs() << "warning: ambiguous instruction match:\n";
1430 errs() << "\nis incomparable with:\n";
1439 DEBUG_WITH_TYPE("ambiguous_instrs", {
1440 errs() << "warning: " << NumAmbiguous
1441 << " ambiguous instructions!\n";
1444 // Write the output.
1446 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1448 // Emit the function to match a register name to number.
1449 EmitMatchRegisterName(Target, AsmParser, OS);
1451 // Generate the unified function to convert operands into an MCInst.
1452 EmitConvertToMCInst(Target, Info.Instructions, OS);
1454 // Emit the enumeration for classes which participate in matching.
1455 EmitMatchClassEnumeration(Target, Info.Classes, OS);
1457 // Emit the routine to match token strings to their match class.
1458 EmitMatchTokenString(Target, Info.Classes, OS);
1460 // Emit the routine to classify an operand.
1461 EmitClassifyOperand(Target, Info, OS);
1463 // Emit the subclass predicate routine.
1464 EmitIsSubclass(Target, Info.Classes, OS);
1466 // Finally, build the match function.
1468 size_t MaxNumOperands = 0;
1469 for (std::vector<InstructionInfo*>::const_iterator it =
1470 Info.Instructions.begin(), ie = Info.Instructions.end();
1472 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1474 OS << "bool " << Target.getName() << ClassName
1475 << "::\nMatchInstruction(const SmallVectorImpl<MCParsedAsmOperand*> "
1476 "&Operands,\n MCInst &Inst) {\n";
1478 // Emit the static match table; unused classes get initalized to 0 which is
1479 // guaranteed to be InvalidMatchClass.
1481 // FIXME: We can reduce the size of this table very easily. First, we change
1482 // it so that store the kinds in separate bit-fields for each index, which
1483 // only needs to be the max width used for classes at that index (we also need
1484 // to reject based on this during classification). If we then make sure to
1485 // order the match kinds appropriately (putting mnemonics last), then we
1486 // should only end up using a few bits for each class, especially the ones
1487 // following the mnemonic.
1488 OS << " static const struct MatchEntry {\n";
1489 OS << " unsigned Opcode;\n";
1490 OS << " ConversionKind ConvertFn;\n";
1491 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1492 OS << " } MatchTable[" << Info.Instructions.size() << "] = {\n";
1494 for (std::vector<InstructionInfo*>::const_iterator it =
1495 Info.Instructions.begin(), ie = Info.Instructions.end();
1497 InstructionInfo &II = **it;
1499 OS << " { " << Target.getName() << "::" << II.InstrName
1500 << ", " << II.ConversionFnKind << ", { ";
1501 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1502 InstructionInfo::Operand &Op = II.Operands[i];
1505 OS << Op.Class->Name;
1512 // Emit code to compute the class list for this operand vector.
1513 OS << " // Eliminate obvious mismatches.\n";
1514 OS << " if (Operands.size() > " << MaxNumOperands << ")\n";
1515 OS << " return true;\n\n";
1517 OS << " // Compute the class list for this operand vector.\n";
1518 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1519 OS << " for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1520 OS << " Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1522 OS << " // Check for invalid operands before matching.\n";
1523 OS << " if (Classes[i] == InvalidMatchClass)\n";
1524 OS << " return true;\n";
1527 OS << " // Mark unused classes.\n";
1528 OS << " for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1529 << "i != e; ++i)\n";
1530 OS << " Classes[i] = InvalidMatchClass;\n\n";
1532 // Emit code to search the table.
1533 OS << " // Search the table.\n";
1534 OS << " for (const MatchEntry *it = MatchTable, "
1535 << "*ie = MatchTable + " << Info.Instructions.size()
1536 << "; it != ie; ++it) {\n";
1537 for (unsigned i = 0; i != MaxNumOperands; ++i) {
1538 OS << " if (!IsSubclass(Classes["
1539 << i << "], it->Classes[" << i << "]))\n";
1540 OS << " continue;\n";
1543 OS << " return ConvertToMCInst(it->ConvertFn, Inst, "
1544 << "it->Opcode, Operands);\n";
1547 OS << " return true;\n";