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 psuedo ops.
215 // FIXME: This is a hack.
216 if (const RecordVal *Form = CGI.TheDef->getValue("Form"))
217 if (Form->getValue()->getAsString() == "Pseudo")
220 // Ignore "PHI" node.
222 // FIXME: This is also a hack.
226 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
228 // FIXME: This is a total hack.
229 if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
232 // Ignore instructions with no .s string.
234 // FIXME: What are these?
235 if (CGI.AsmString.empty())
238 // FIXME: Hack; ignore any instructions with a newline in them.
239 if (std::find(CGI.AsmString.begin(),
240 CGI.AsmString.end(), '\n') != CGI.AsmString.end())
243 // Ignore instructions with attributes, these are always fake instructions for
244 // simplifying codegen.
246 // FIXME: Is this true?
248 // Also, we ignore instructions which reference the operand multiple times;
249 // this implies a constraint we would not currently honor. These are
250 // currently always fake instructions for simplifying codegen.
252 // FIXME: Encode this assumption in the .td, so we can error out here.
253 std::set<std::string> OperandNames;
254 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
255 if (Tokens[i][0] == '$' &&
256 std::find(Tokens[i].begin(),
257 Tokens[i].end(), ':') != Tokens[i].end()) {
259 errs() << "warning: '" << Name << "': "
260 << "ignoring instruction; operand with attribute '"
261 << Tokens[i] << "', \n";
266 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
268 errs() << "warning: '" << Name << "': "
269 << "ignoring instruction; tied operand '"
270 << Tokens[i] << "'\n";
281 /// ClassInfo - Helper class for storing the information about a particular
282 /// class of operands which can be matched.
285 /// Invalid kind, for use as a sentinel value.
288 /// The class for a particular token.
291 /// The (first) register class, subsequent register classes are
292 /// RegisterClass0+1, and so on.
295 /// The (first) user defined class, subsequent user defined classes are
296 /// UserClass0+1, and so on.
300 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
301 /// N) for the Nth user defined class.
304 /// SuperClasses - The super classes of this class. Note that for simplicities
305 /// sake user operands only record their immediate super class, while register
306 /// operands include all superclasses.
307 std::vector<ClassInfo*> SuperClasses;
309 /// Name - The full class name, suitable for use in an enum.
312 /// ClassName - The unadorned generic name for this class (e.g., Token).
313 std::string ClassName;
315 /// ValueName - The name of the value this class represents; for a token this
316 /// is the literal token string, for an operand it is the TableGen class (or
317 /// empty if this is a derived class).
318 std::string ValueName;
320 /// PredicateMethod - The name of the operand method to test whether the
321 /// operand matches this class; this is not valid for Token or register kinds.
322 std::string PredicateMethod;
324 /// RenderMethod - The name of the operand method to add this operand to an
325 /// MCInst; this is not valid for Token or register kinds.
326 std::string RenderMethod;
328 /// For register classes, the records for all the registers in this class.
329 std::set<Record*> Registers;
332 /// isRegisterClass() - Check if this is a register class.
333 bool isRegisterClass() const {
334 return Kind >= RegisterClass0 && Kind < UserClass0;
337 /// isUserClass() - Check if this is a user defined class.
338 bool isUserClass() const {
339 return Kind >= UserClass0;
342 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
343 /// are related if they are in the same class hierarchy.
344 bool isRelatedTo(const ClassInfo &RHS) const {
345 // Tokens are only related to tokens.
346 if (Kind == Token || RHS.Kind == Token)
347 return Kind == Token && RHS.Kind == Token;
349 // Registers classes are only related to registers classes, and only if
350 // their intersection is non-empty.
351 if (isRegisterClass() || RHS.isRegisterClass()) {
352 if (!isRegisterClass() || !RHS.isRegisterClass())
355 std::set<Record*> Tmp;
356 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
357 std::set_intersection(Registers.begin(), Registers.end(),
358 RHS.Registers.begin(), RHS.Registers.end(),
364 // Otherwise we have two users operands; they are related if they are in the
365 // same class hierarchy.
367 // FIXME: This is an oversimplification, they should only be related if they
368 // intersect, however we don't have that information.
369 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
370 const ClassInfo *Root = this;
371 while (!Root->SuperClasses.empty())
372 Root = Root->SuperClasses.front();
374 const ClassInfo *RHSRoot = &RHS;
375 while (!RHSRoot->SuperClasses.empty())
376 RHSRoot = RHSRoot->SuperClasses.front();
378 return Root == RHSRoot;
381 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
382 bool isSubsetOf(const ClassInfo &RHS) const {
383 // This is a subset of RHS if it is the same class...
387 // ... or if any of its super classes are a subset of RHS.
388 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
389 ie = SuperClasses.end(); it != ie; ++it)
390 if ((*it)->isSubsetOf(RHS))
396 /// operator< - Compare two classes.
397 bool operator<(const ClassInfo &RHS) const {
398 // Unrelated classes can be ordered by kind.
399 if (!isRelatedTo(RHS))
400 return Kind < RHS.Kind;
404 assert(0 && "Invalid kind!");
406 // Tokens are comparable by value.
408 // FIXME: Compare by enum value.
409 return ValueName < RHS.ValueName;
412 // This class preceeds the RHS if it is a proper subset of the RHS.
413 return this != &RHS && isSubsetOf(RHS);
418 /// InstructionInfo - Helper class for storing the necessary information for an
419 /// instruction which is capable of being matched.
420 struct InstructionInfo {
422 /// The unique class instance this operand should match.
425 /// The original operand this corresponds to, if any.
426 const CodeGenInstruction::OperandInfo *OperandInfo;
429 /// InstrName - The target name for this instruction.
430 std::string InstrName;
432 /// Instr - The instruction this matches.
433 const CodeGenInstruction *Instr;
435 /// AsmString - The assembly string for this instruction (with variants
437 std::string AsmString;
439 /// Tokens - The tokenized assembly pattern that this instruction matches.
440 SmallVector<StringRef, 4> Tokens;
442 /// Operands - The operands that this instruction matches.
443 SmallVector<Operand, 4> Operands;
445 /// ConversionFnKind - The enum value which is passed to the generated
446 /// ConvertToMCInst to convert parsed operands into an MCInst for this
448 std::string ConversionFnKind;
450 /// operator< - Compare two instructions.
451 bool operator<(const InstructionInfo &RHS) const {
452 if (Operands.size() != RHS.Operands.size())
453 return Operands.size() < RHS.Operands.size();
455 // Compare lexicographically by operand. The matcher validates that other
456 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
457 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
458 if (*Operands[i].Class < *RHS.Operands[i].Class)
460 if (*RHS.Operands[i].Class < *Operands[i].Class)
467 /// CouldMatchAmiguouslyWith - Check whether this instruction could
468 /// ambiguously match the same set of operands as \arg RHS (without being a
469 /// strictly superior match).
470 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
471 // The number of operands is unambiguous.
472 if (Operands.size() != RHS.Operands.size())
475 // Tokens and operand kinds are unambiguous (assuming a correct target
477 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
478 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
479 Operands[i].Class->Kind == ClassInfo::Token)
480 if (*Operands[i].Class < *RHS.Operands[i].Class ||
481 *RHS.Operands[i].Class < *Operands[i].Class)
484 // Otherwise, this operand could commute if all operands are equivalent, or
485 // there is a pair of operands that compare less than and a pair that
486 // compare greater than.
487 bool HasLT = false, HasGT = false;
488 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
489 if (*Operands[i].Class < *RHS.Operands[i].Class)
491 if (*RHS.Operands[i].Class < *Operands[i].Class)
495 return !(HasLT ^ HasGT);
502 class AsmMatcherInfo {
504 /// The classes which are needed for matching.
505 std::vector<ClassInfo*> Classes;
507 /// The information on the instruction to match.
508 std::vector<InstructionInfo*> Instructions;
510 /// Map of Register records to their class information.
511 std::map<Record*, ClassInfo*> RegisterClasses;
514 /// Map of token to class information which has already been constructed.
515 std::map<std::string, ClassInfo*> TokenClasses;
517 /// Map of RegisterClass records to their class information.
518 std::map<Record*, ClassInfo*> RegisterClassClasses;
520 /// Map of AsmOperandClass records to their class information.
521 std::map<Record*, ClassInfo*> AsmOperandClasses;
524 /// getTokenClass - Lookup or create the class for the given token.
525 ClassInfo *getTokenClass(const StringRef &Token);
527 /// getOperandClass - Lookup or create the class for the given operand.
528 ClassInfo *getOperandClass(const StringRef &Token,
529 const CodeGenInstruction::OperandInfo &OI);
531 /// BuildRegisterClasses - Build the ClassInfo* instances for register
533 void BuildRegisterClasses(CodeGenTarget &Target);
535 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
537 void BuildOperandClasses(CodeGenTarget &Target);
540 /// BuildInfo - Construct the various tables used during matching.
541 void BuildInfo(CodeGenTarget &Target);
546 void InstructionInfo::dump() {
547 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
549 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
556 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
557 Operand &Op = Operands[i];
558 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
559 if (Op.Class->Kind == ClassInfo::Token) {
560 errs() << '\"' << Tokens[i] << "\"\n";
564 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
565 errs() << OI.Name << " " << OI.Rec->getName()
566 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
570 static std::string getEnumNameForToken(const StringRef &Str) {
573 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
575 case '*': Res += "_STAR_"; break;
576 case '%': Res += "_PCT_"; break;
577 case ':': Res += "_COLON_"; break;
583 Res += "_" + utostr((unsigned) *it) + "_";
591 ClassInfo *AsmMatcherInfo::getTokenClass(const StringRef &Token) {
592 ClassInfo *&Entry = TokenClasses[Token];
595 Entry = new ClassInfo();
596 Entry->Kind = ClassInfo::Token;
597 Entry->ClassName = "Token";
598 Entry->Name = "MCK_" + getEnumNameForToken(Token);
599 Entry->ValueName = Token;
600 Entry->PredicateMethod = "<invalid>";
601 Entry->RenderMethod = "<invalid>";
602 Classes.push_back(Entry);
609 AsmMatcherInfo::getOperandClass(const StringRef &Token,
610 const CodeGenInstruction::OperandInfo &OI) {
611 if (OI.Rec->isSubClassOf("RegisterClass")) {
612 ClassInfo *CI = RegisterClassClasses[OI.Rec];
615 PrintError(OI.Rec->getLoc(), "register class has no class info!");
616 throw std::string("ERROR: Missing register class!");
622 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
623 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
624 ClassInfo *CI = AsmOperandClasses[MatchClass];
627 PrintError(OI.Rec->getLoc(), "operand has no match class!");
628 throw std::string("ERROR: Missing match class!");
634 void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target) {
635 std::vector<CodeGenRegisterClass> RegisterClasses;
636 std::vector<CodeGenRegister> Registers;
638 RegisterClasses = Target.getRegisterClasses();
639 Registers = Target.getRegisters();
641 // The register sets used for matching.
642 std::set< std::set<Record*> > RegisterSets;
644 // Gather the defined sets.
645 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
646 ie = RegisterClasses.end(); it != ie; ++it)
647 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
648 it->Elements.end()));
650 // Introduce derived sets where necessary (when a register does not determine
651 // a unique register set class), and build the mapping of registers to the set
652 // they should classify to.
653 std::map<Record*, std::set<Record*> > RegisterMap;
654 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
655 ie = Registers.end(); it != ie; ++it) {
656 CodeGenRegister &CGR = *it;
657 // Compute the intersection of all sets containing this register.
658 std::set<Record*> ContainingSet;
660 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
661 ie = RegisterSets.end(); it != ie; ++it) {
662 if (!it->count(CGR.TheDef))
665 if (ContainingSet.empty()) {
668 std::set<Record*> Tmp;
669 std::swap(Tmp, ContainingSet);
670 std::insert_iterator< std::set<Record*> > II(ContainingSet,
671 ContainingSet.begin());
672 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
677 if (!ContainingSet.empty()) {
678 RegisterSets.insert(ContainingSet);
679 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
683 // Construct the register classes.
684 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
686 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
687 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
688 ClassInfo *CI = new ClassInfo();
689 CI->Kind = ClassInfo::RegisterClass0 + Index;
690 CI->ClassName = "Reg" + utostr(Index);
691 CI->Name = "MCK_Reg" + utostr(Index);
693 CI->PredicateMethod = ""; // unused
694 CI->RenderMethod = "addRegOperands";
696 Classes.push_back(CI);
697 RegisterSetClasses.insert(std::make_pair(*it, CI));
700 // Find the superclasses; we could compute only the subgroup lattice edges,
701 // but there isn't really a point.
702 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
703 ie = RegisterSets.end(); it != ie; ++it) {
704 ClassInfo *CI = RegisterSetClasses[*it];
705 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
706 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
708 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
709 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
712 // Name the register classes which correspond to a user defined RegisterClass.
713 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
714 ie = RegisterClasses.end(); it != ie; ++it) {
715 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
716 it->Elements.end())];
717 if (CI->ValueName.empty()) {
718 CI->ClassName = it->getName();
719 CI->Name = "MCK_" + it->getName();
720 CI->ValueName = it->getName();
722 CI->ValueName = CI->ValueName + "," + it->getName();
724 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
727 // Populate the map for individual registers.
728 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
729 ie = RegisterMap.end(); it != ie; ++it)
730 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
733 void AsmMatcherInfo::BuildOperandClasses(CodeGenTarget &Target) {
734 std::vector<Record*> AsmOperands;
735 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
737 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
738 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
739 ClassInfo *CI = new ClassInfo();
740 CI->Kind = ClassInfo::UserClass0 + Index;
742 Init *Super = (*it)->getValueInit("SuperClass");
743 if (DefInit *DI = dynamic_cast<DefInit*>(Super)) {
744 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
746 PrintError((*it)->getLoc(), "Invalid super class reference!");
748 CI->SuperClasses.push_back(SC);
750 assert(dynamic_cast<UnsetInit*>(Super) && "Unexpected SuperClass field!");
752 CI->ClassName = (*it)->getValueAsString("Name");
753 CI->Name = "MCK_" + CI->ClassName;
754 CI->ValueName = (*it)->getName();
756 // Get or construct the predicate method name.
757 Init *PMName = (*it)->getValueInit("PredicateMethod");
758 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
759 CI->PredicateMethod = SI->getValue();
761 assert(dynamic_cast<UnsetInit*>(PMName) &&
762 "Unexpected PredicateMethod field!");
763 CI->PredicateMethod = "is" + CI->ClassName;
766 // Get or construct the render method name.
767 Init *RMName = (*it)->getValueInit("RenderMethod");
768 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
769 CI->RenderMethod = SI->getValue();
771 assert(dynamic_cast<UnsetInit*>(RMName) &&
772 "Unexpected RenderMethod field!");
773 CI->RenderMethod = "add" + CI->ClassName + "Operands";
776 AsmOperandClasses[*it] = CI;
777 Classes.push_back(CI);
781 void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
782 // Build info for the register classes.
783 BuildRegisterClasses(Target);
785 // Build info for the user defined assembly operand classes.
786 BuildOperandClasses(Target);
788 // Build the instruction information.
789 for (std::map<std::string, CodeGenInstruction>::const_iterator
790 it = Target.getInstructions().begin(),
791 ie = Target.getInstructions().end();
793 const CodeGenInstruction &CGI = it->second;
795 if (!StringRef(it->first).startswith(MatchPrefix))
798 OwningPtr<InstructionInfo> II(new InstructionInfo);
800 II->InstrName = it->first;
801 II->Instr = &it->second;
802 II->AsmString = FlattenVariants(CGI.AsmString, 0);
804 TokenizeAsmString(II->AsmString, II->Tokens);
806 // Ignore instructions which shouldn't be matched.
807 if (!IsAssemblerInstruction(it->first, CGI, II->Tokens))
810 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
811 StringRef Token = II->Tokens[i];
813 // Check for simple tokens.
814 if (Token[0] != '$') {
815 InstructionInfo::Operand Op;
816 Op.Class = getTokenClass(Token);
818 II->Operands.push_back(Op);
822 // Otherwise this is an operand reference.
823 StringRef OperandName;
825 OperandName = Token.substr(2, Token.size() - 3);
827 OperandName = Token.substr(1);
829 // Map this token to an operand. FIXME: Move elsewhere.
832 Idx = CGI.getOperandNamed(OperandName);
834 errs() << "error: unable to find operand: '" << OperandName << "'!\n";
838 const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx];
839 InstructionInfo::Operand Op;
840 Op.Class = getOperandClass(Token, OI);
841 Op.OperandInfo = &OI;
842 II->Operands.push_back(Op);
845 // If we broke out, ignore the instruction.
846 if (II->Operands.size() != II->Tokens.size())
849 Instructions.push_back(II.take());
852 // Reorder classes so that classes preceed super classes.
853 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
856 static void EmitConvertToMCInst(CodeGenTarget &Target,
857 std::vector<InstructionInfo*> &Infos,
859 // Write the convert function to a separate stream, so we can drop it after
861 std::string ConvertFnBody;
862 raw_string_ostream CvtOS(ConvertFnBody);
864 // Function we have already generated.
865 std::set<std::string> GeneratedFns;
867 // Start the unified conversion function.
869 CvtOS << "static bool ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
870 << "unsigned Opcode,\n"
871 << " SmallVectorImpl<"
872 << Target.getName() << "Operand> &Operands) {\n";
873 CvtOS << " Inst.setOpcode(Opcode);\n";
874 CvtOS << " switch (Kind) {\n";
875 CvtOS << " default:\n";
877 // Start the enum, which we will generate inline.
879 OS << "// Unified function for converting operants to MCInst instances.\n\n";
880 OS << "enum ConversionKind {\n";
882 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
883 ie = Infos.end(); it != ie; ++it) {
884 InstructionInfo &II = **it;
886 // Order the (class) operands by the order to convert them into an MCInst.
887 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
888 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
889 InstructionInfo::Operand &Op = II.Operands[i];
891 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
893 std::sort(MIOperandList.begin(), MIOperandList.end());
895 // Compute the total number of operands.
896 unsigned NumMIOperands = 0;
897 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
898 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
899 NumMIOperands = std::max(NumMIOperands,
900 OI.MIOperandNo + OI.MINumOperands);
903 // Build the conversion function signature.
904 std::string Signature = "Convert";
905 unsigned CurIndex = 0;
906 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
907 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
908 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
909 "Duplicate match for instruction operand!");
913 // Skip operands which weren't matched by anything, this occurs when the
914 // .td file encodes "implicit" operands as explicit ones.
916 // FIXME: This should be removed from the MCInst structure.
917 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
920 // Registers are always converted the same, don't duplicate the conversion
921 // function based on them.
923 // FIXME: We could generalize this based on the render method, if it
925 if (Op.Class->isRegisterClass())
928 Signature += Op.Class->ClassName;
929 Signature += utostr(Op.OperandInfo->MINumOperands);
930 Signature += "_" + utostr(MIOperandList[i].second);
932 CurIndex += Op.OperandInfo->MINumOperands;
935 // Add any trailing implicit operands.
936 for (; CurIndex != NumMIOperands; ++CurIndex)
939 II.ConversionFnKind = Signature;
941 // Check if we have already generated this signature.
942 if (!GeneratedFns.insert(Signature).second)
945 // If not, emit it now.
947 // Add to the enum list.
948 OS << " " << Signature << ",\n";
950 // And to the convert function.
951 CvtOS << " case " << Signature << ":\n";
953 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
954 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
956 // Add the implicit operands.
957 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
958 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
960 CvtOS << " Operands[" << MIOperandList[i].second
961 << "]." << Op.Class->RenderMethod
962 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
963 CurIndex += Op.OperandInfo->MINumOperands;
966 // And add trailing implicit operands.
967 for (; CurIndex != NumMIOperands; ++CurIndex)
968 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
969 CvtOS << " break;\n";
972 // Finish the convert function.
975 CvtOS << " return false;\n";
978 // Finish the enum, and drop the convert function after it.
980 OS << " NumConversionVariants\n";
986 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
987 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
988 std::vector<ClassInfo*> &Infos,
990 OS << "namespace {\n\n";
992 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
993 << "/// instruction matching.\n";
994 OS << "enum MatchClassKind {\n";
995 OS << " InvalidMatchClass = 0,\n";
996 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
997 ie = Infos.end(); it != ie; ++it) {
998 ClassInfo &CI = **it;
999 OS << " " << CI.Name << ", // ";
1000 if (CI.Kind == ClassInfo::Token) {
1001 OS << "'" << CI.ValueName << "'\n";
1002 } else if (CI.isRegisterClass()) {
1003 if (!CI.ValueName.empty())
1004 OS << "register class '" << CI.ValueName << "'\n";
1006 OS << "derived register class\n";
1008 OS << "user defined class '" << CI.ValueName << "'\n";
1011 OS << " NumMatchClassKinds\n";
1017 /// EmitClassifyOperand - Emit the function to classify an operand.
1018 static void EmitClassifyOperand(CodeGenTarget &Target,
1019 AsmMatcherInfo &Info,
1021 OS << "static MatchClassKind ClassifyOperand("
1022 << Target.getName() << "Operand &Operand) {\n";
1025 OS << " if (Operand.isToken())\n";
1026 OS << " return MatchTokenString(Operand.getToken());\n\n";
1028 // Classify registers.
1030 // FIXME: Don't hardcode isReg, getReg.
1031 OS << " if (Operand.isReg()) {\n";
1032 OS << " switch (Operand.getReg()) {\n";
1033 OS << " default: return InvalidMatchClass;\n";
1034 for (std::map<Record*, ClassInfo*>::iterator
1035 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1037 OS << " case " << Target.getName() << "::"
1038 << it->first->getName() << ": return " << it->second->Name << ";\n";
1042 // Classify user defined operands.
1043 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1044 ie = Info.Classes.end(); it != ie; ++it) {
1045 ClassInfo &CI = **it;
1047 if (!CI.isUserClass())
1050 OS << " // '" << CI.ClassName << "' class";
1051 if (!CI.SuperClasses.empty()) {
1052 OS << ", subclass of ";
1053 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1055 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1056 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
1061 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
1063 // Validate subclass relationships.
1064 if (!CI.SuperClasses.empty()) {
1065 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1066 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1067 << "() && \"Invalid class relationship!\");\n";
1070 OS << " return " << CI.Name << ";\n";
1073 OS << " return InvalidMatchClass;\n";
1077 /// EmitIsSubclass - Emit the subclass predicate function.
1078 static void EmitIsSubclass(CodeGenTarget &Target,
1079 std::vector<ClassInfo*> &Infos,
1081 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1082 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1083 OS << " if (A == B)\n";
1084 OS << " return true;\n\n";
1086 OS << " switch (A) {\n";
1087 OS << " default:\n";
1088 OS << " return false;\n";
1089 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1090 ie = Infos.end(); it != ie; ++it) {
1091 ClassInfo &A = **it;
1093 if (A.Kind != ClassInfo::Token) {
1094 std::vector<StringRef> SuperClasses;
1095 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1096 ie = Infos.end(); it != ie; ++it) {
1097 ClassInfo &B = **it;
1099 if (&A != &B && A.isSubsetOf(B))
1100 SuperClasses.push_back(B.Name);
1103 if (SuperClasses.empty())
1106 OS << "\n case " << A.Name << ":\n";
1108 if (SuperClasses.size() == 1) {
1109 OS << " return B == " << SuperClasses.back() << ";\n";
1113 OS << " switch (B) {\n";
1114 OS << " default: return false;\n";
1115 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1116 OS << " case " << SuperClasses[i] << ": return true;\n";
1124 typedef std::pair<std::string, std::string> StringPair;
1126 /// FindFirstNonCommonLetter - Find the first character in the keys of the
1127 /// string pairs that is not shared across the whole set of strings. All
1128 /// strings are assumed to have the same length.
1130 FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
1131 assert(!Matches.empty());
1132 for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
1133 // Check to see if letter i is the same across the set.
1134 char Letter = Matches[0]->first[i];
1136 for (unsigned str = 0, e = Matches.size(); str != e; ++str)
1137 if (Matches[str]->first[i] != Letter)
1141 return Matches[0]->first.size();
1144 /// EmitStringMatcherForChar - Given a set of strings that are known to be the
1145 /// same length and whose characters leading up to CharNo are the same, emit
1146 /// code to verify that CharNo and later are the same.
1148 /// \return - True if control can leave the emitted code fragment.
1149 static bool EmitStringMatcherForChar(const std::string &StrVariableName,
1150 const std::vector<const StringPair*> &Matches,
1151 unsigned CharNo, unsigned IndentCount,
1153 assert(!Matches.empty() && "Must have at least one string to match!");
1154 std::string Indent(IndentCount*2+4, ' ');
1156 // If we have verified that the entire string matches, we're done: output the
1158 if (CharNo == Matches[0]->first.size()) {
1159 assert(Matches.size() == 1 && "Had duplicate keys to match on");
1161 // FIXME: If Matches[0].first has embeded \n, this will be bad.
1162 OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
1167 // Bucket the matches by the character we are comparing.
1168 std::map<char, std::vector<const StringPair*> > MatchesByLetter;
1170 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1171 MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
1174 // If we have exactly one bucket to match, see how many characters are common
1175 // across the whole set and match all of them at once.
1176 if (MatchesByLetter.size() == 1) {
1177 unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
1178 unsigned NumChars = FirstNonCommonLetter-CharNo;
1180 // Emit code to break out if the prefix doesn't match.
1181 if (NumChars == 1) {
1182 // Do the comparison with if (Str[1] != 'f')
1183 // FIXME: Need to escape general characters.
1184 OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
1185 << Matches[0]->first[CharNo] << "')\n";
1186 OS << Indent << " break;\n";
1188 // Do the comparison with if (Str.substr(1,3) != "foo").
1189 // FIXME: Need to escape general strings.
1190 OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
1191 << NumChars << ") != \"";
1192 OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
1193 OS << Indent << " break;\n";
1196 return EmitStringMatcherForChar(StrVariableName, Matches,
1197 FirstNonCommonLetter, IndentCount, OS);
1200 // Otherwise, we have multiple possible things, emit a switch on the
1202 OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
1203 OS << Indent << "default: break;\n";
1205 for (std::map<char, std::vector<const StringPair*> >::iterator LI =
1206 MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
1207 // TODO: escape hard stuff (like \n) if we ever care about it.
1208 OS << Indent << "case '" << LI->first << "':\t // "
1209 << LI->second.size() << " strings to match.\n";
1210 if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
1212 OS << Indent << " break;\n";
1215 OS << Indent << "}\n";
1220 /// EmitStringMatcher - Given a list of strings and code to execute when they
1221 /// match, output a simple switch tree to classify the input string.
1223 /// If a match is found, the code in Vals[i].second is executed; control must
1224 /// not exit this code fragment. If nothing matches, execution falls through.
1226 /// \param StrVariableName - The name of the variable to test.
1227 static void EmitStringMatcher(const std::string &StrVariableName,
1228 const std::vector<StringPair> &Matches,
1230 // First level categorization: group strings by length.
1231 std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
1233 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1234 MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
1236 // Output a switch statement on length and categorize the elements within each
1238 OS << " switch (" << StrVariableName << ".size()) {\n";
1239 OS << " default: break;\n";
1241 for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
1242 MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
1243 OS << " case " << LI->first << ":\t // " << LI->second.size()
1244 << " strings to match.\n";
1245 if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
1253 /// EmitMatchTokenString - Emit the function to match a token string to the
1254 /// appropriate match class value.
1255 static void EmitMatchTokenString(CodeGenTarget &Target,
1256 std::vector<ClassInfo*> &Infos,
1258 // Construct the match list.
1259 std::vector<StringPair> Matches;
1260 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1261 ie = Infos.end(); it != ie; ++it) {
1262 ClassInfo &CI = **it;
1264 if (CI.Kind == ClassInfo::Token)
1265 Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
1268 OS << "static MatchClassKind MatchTokenString(const StringRef &Name) {\n";
1270 EmitStringMatcher("Name", Matches, OS);
1272 OS << " return InvalidMatchClass;\n";
1276 /// EmitMatchRegisterName - Emit the function to match a string to the target
1277 /// specific register enum.
1278 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1280 // Construct the match list.
1281 std::vector<StringPair> Matches;
1282 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1283 const CodeGenRegister &Reg = Target.getRegisters()[i];
1284 if (Reg.TheDef->getValueAsString("AsmName").empty())
1287 Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
1288 "return " + utostr(i + 1) + ";"));
1291 OS << "unsigned " << Target.getName()
1292 << AsmParser->getValueAsString("AsmParserClassName")
1293 << "::MatchRegisterName(const StringRef &Name) {\n";
1295 EmitStringMatcher("Name", Matches, OS);
1297 OS << " return 0;\n";
1301 void AsmMatcherEmitter::run(raw_ostream &OS) {
1302 CodeGenTarget Target;
1303 Record *AsmParser = Target.getAsmParser();
1304 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1306 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1308 // Emit the function to match a register name to number.
1309 EmitMatchRegisterName(Target, AsmParser, OS);
1311 // Compute the information on the instructions to match.
1312 AsmMatcherInfo Info;
1313 Info.BuildInfo(Target);
1315 // Sort the instruction table using the partial order on classes.
1316 std::sort(Info.Instructions.begin(), Info.Instructions.end(),
1317 less_ptr<InstructionInfo>());
1319 DEBUG_WITH_TYPE("instruction_info", {
1320 for (std::vector<InstructionInfo*>::iterator
1321 it = Info.Instructions.begin(), ie = Info.Instructions.end();
1326 // Check for ambiguous instructions.
1327 unsigned NumAmbiguous = 0;
1328 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1329 for (unsigned j = i + 1; j != e; ++j) {
1330 InstructionInfo &A = *Info.Instructions[i];
1331 InstructionInfo &B = *Info.Instructions[j];
1333 if (A.CouldMatchAmiguouslyWith(B)) {
1334 DEBUG_WITH_TYPE("ambiguous_instrs", {
1335 errs() << "warning: ambiguous instruction match:\n";
1337 errs() << "\nis incomparable with:\n";
1346 DEBUG_WITH_TYPE("ambiguous_instrs", {
1347 errs() << "warning: " << NumAmbiguous
1348 << " ambiguous instructions!\n";
1351 // Generate the unified function to convert operands into an MCInst.
1352 EmitConvertToMCInst(Target, Info.Instructions, OS);
1354 // Emit the enumeration for classes which participate in matching.
1355 EmitMatchClassEnumeration(Target, Info.Classes, OS);
1357 // Emit the routine to match token strings to their match class.
1358 EmitMatchTokenString(Target, Info.Classes, OS);
1360 // Emit the routine to classify an operand.
1361 EmitClassifyOperand(Target, Info, OS);
1363 // Emit the subclass predicate routine.
1364 EmitIsSubclass(Target, Info.Classes, OS);
1366 // Finally, build the match function.
1368 size_t MaxNumOperands = 0;
1369 for (std::vector<InstructionInfo*>::const_iterator it =
1370 Info.Instructions.begin(), ie = Info.Instructions.end();
1372 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1374 OS << "bool " << Target.getName() << ClassName
1375 << "::MatchInstruction("
1376 << "SmallVectorImpl<" << Target.getName() << "Operand> &Operands, "
1377 << "MCInst &Inst) {\n";
1379 // Emit the static match table; unused classes get initalized to 0 which is
1380 // guaranteed to be InvalidMatchClass.
1382 // FIXME: We can reduce the size of this table very easily. First, we change
1383 // it so that store the kinds in separate bit-fields for each index, which
1384 // only needs to be the max width used for classes at that index (we also need
1385 // to reject based on this during classification). If we then make sure to
1386 // order the match kinds appropriately (putting mnemonics last), then we
1387 // should only end up using a few bits for each class, especially the ones
1388 // following the mnemonic.
1389 OS << " static const struct MatchEntry {\n";
1390 OS << " unsigned Opcode;\n";
1391 OS << " ConversionKind ConvertFn;\n";
1392 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1393 OS << " } MatchTable[" << Info.Instructions.size() << "] = {\n";
1395 for (std::vector<InstructionInfo*>::const_iterator it =
1396 Info.Instructions.begin(), ie = Info.Instructions.end();
1398 InstructionInfo &II = **it;
1400 OS << " { " << Target.getName() << "::" << II.InstrName
1401 << ", " << II.ConversionFnKind << ", { ";
1402 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1403 InstructionInfo::Operand &Op = II.Operands[i];
1406 OS << Op.Class->Name;
1413 // Emit code to compute the class list for this operand vector.
1414 OS << " // Eliminate obvious mismatches.\n";
1415 OS << " if (Operands.size() > " << MaxNumOperands << ")\n";
1416 OS << " return true;\n\n";
1418 OS << " // Compute the class list for this operand vector.\n";
1419 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1420 OS << " for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1421 OS << " Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1423 OS << " // Check for invalid operands before matching.\n";
1424 OS << " if (Classes[i] == InvalidMatchClass)\n";
1425 OS << " return true;\n";
1428 OS << " // Mark unused classes.\n";
1429 OS << " for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1430 << "i != e; ++i)\n";
1431 OS << " Classes[i] = InvalidMatchClass;\n\n";
1433 // Emit code to search the table.
1434 OS << " // Search the table.\n";
1435 OS << " for (const MatchEntry *it = MatchTable, "
1436 << "*ie = MatchTable + " << Info.Instructions.size()
1437 << "; it != ie; ++it) {\n";
1438 for (unsigned i = 0; i != MaxNumOperands; ++i) {
1439 OS << " if (!IsSubclass(Classes["
1440 << i << "], it->Classes[" << i << "]))\n";
1441 OS << " continue;\n";
1444 OS << " return ConvertToMCInst(it->ConvertFn, Inst, "
1445 << "it->Opcode, Operands);\n";
1448 OS << " return true;\n";