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"
91 static cl::opt<std::string>
92 MatchPrefix("match-prefix", cl::init(""),
93 cl::desc("Only match instructions with the given prefix"));
96 /// FlattenVariants - Flatten an .td file assembly string by selecting the
97 /// variant at index \arg N.
98 static std::string FlattenVariants(const std::string &AsmString,
100 StringRef Cur = AsmString;
101 std::string Res = "";
104 // Find the start of the next variant string.
105 size_t VariantsStart = 0;
106 for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
107 if (Cur[VariantsStart] == '{' &&
108 (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
109 Cur[VariantsStart-1] != '\\')))
112 // Add the prefix to the result.
113 Res += Cur.slice(0, VariantsStart);
114 if (VariantsStart == Cur.size())
117 ++VariantsStart; // Skip the '{'.
119 // Scan to the end of the variants string.
120 size_t VariantsEnd = VariantsStart;
121 unsigned NestedBraces = 1;
122 for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
123 if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
124 if (--NestedBraces == 0)
126 } else if (Cur[VariantsEnd] == '{')
130 // Select the Nth variant (or empty).
131 StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
132 for (unsigned i = 0; i != N; ++i)
133 Selection = Selection.split('|').second;
134 Res += Selection.split('|').first;
136 assert(VariantsEnd != Cur.size() &&
137 "Unterminated variants in assembly string!");
138 Cur = Cur.substr(VariantsEnd + 1);
144 /// TokenizeAsmString - Tokenize a simplified assembly string.
145 static void TokenizeAsmString(const StringRef &AsmString,
146 SmallVectorImpl<StringRef> &Tokens) {
149 for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {
150 switch (AsmString[i]) {
159 Tokens.push_back(AsmString.slice(Prev, i));
162 if (!isspace(AsmString[i]) && AsmString[i] != ',')
163 Tokens.push_back(AsmString.substr(i, 1));
169 Tokens.push_back(AsmString.slice(Prev, i));
173 assert(i != AsmString.size() && "Invalid quoted character");
174 Tokens.push_back(AsmString.substr(i, 1));
179 // If this isn't "${", treat like a normal token.
180 if (i + 1 == AsmString.size() || AsmString[i + 1] != '{') {
182 Tokens.push_back(AsmString.slice(Prev, i));
190 Tokens.push_back(AsmString.slice(Prev, i));
194 StringRef::iterator End =
195 std::find(AsmString.begin() + i, AsmString.end(), '}');
196 assert(End != AsmString.end() && "Missing brace in operand reference!");
197 size_t EndPos = End - AsmString.begin();
198 Tokens.push_back(AsmString.slice(i, EndPos+1));
208 if (InTok && Prev != AsmString.size())
209 Tokens.push_back(AsmString.substr(Prev));
212 static bool IsAssemblerInstruction(const StringRef &Name,
213 const CodeGenInstruction &CGI,
214 const SmallVectorImpl<StringRef> &Tokens) {
215 // Ignore psuedo ops.
217 // FIXME: This is a hack.
218 if (const RecordVal *Form = CGI.TheDef->getValue("Form"))
219 if (Form->getValue()->getAsString() == "Pseudo")
222 // Ignore "PHI" node.
224 // FIXME: This is also a hack.
228 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
230 // FIXME: This is a total hack.
231 if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
234 // Ignore instructions with no .s string.
236 // FIXME: What are these?
237 if (CGI.AsmString.empty())
240 // FIXME: Hack; ignore any instructions with a newline in them.
241 if (std::find(CGI.AsmString.begin(),
242 CGI.AsmString.end(), '\n') != CGI.AsmString.end())
245 // Ignore instructions with attributes, these are always fake instructions for
246 // simplifying codegen.
248 // FIXME: Is this true?
250 // Also, we ignore instructions which reference the operand multiple times;
251 // this implies a constraint we would not currently honor. These are
252 // currently always fake instructions for simplifying codegen.
254 // FIXME: Encode this assumption in the .td, so we can error out here.
255 std::set<std::string> OperandNames;
256 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
257 if (Tokens[i][0] == '$' &&
258 std::find(Tokens[i].begin(),
259 Tokens[i].end(), ':') != Tokens[i].end()) {
261 errs() << "warning: '" << Name << "': "
262 << "ignoring instruction; operand with attribute '"
263 << Tokens[i] << "', \n";
268 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
270 errs() << "warning: '" << Name << "': "
271 << "ignoring instruction; tied operand '"
272 << Tokens[i] << "'\n";
283 /// ClassInfo - Helper class for storing the information about a particular
284 /// class of operands which can be matched.
287 Invalid = 0, ///< Invalid kind, for use as a sentinel value.
288 Token, ///< The class for a particular token.
289 Register, ///< A register class.
290 UserClass0 ///< The (first) user defined class, subsequent user defined
291 /// classes are UserClass0+1, and so on.
294 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
295 /// N) for the Nth user defined class.
298 /// SuperClassKind - The super class kind for user classes.
299 unsigned SuperClassKind;
301 /// SuperClass - The super class, or 0.
302 ClassInfo *SuperClass;
304 /// Name - The full class name, suitable for use in an enum.
307 /// ClassName - The unadorned generic name for this class (e.g., Token).
308 std::string ClassName;
310 /// ValueName - The name of the value this class represents; for a token this
311 /// is the literal token string, for an operand it is the TableGen class (or
312 /// empty if this is a derived class).
313 std::string ValueName;
315 /// PredicateMethod - The name of the operand method to test whether the
316 /// operand matches this class; this is not valid for Token kinds.
317 std::string PredicateMethod;
319 /// RenderMethod - The name of the operand method to add this operand to an
320 /// MCInst; this is not valid for Token kinds.
321 std::string RenderMethod;
323 /// isUserClass() - Check if this is a user defined class.
324 bool isUserClass() const {
325 return Kind >= UserClass0;
328 /// getRootClass - Return the root class of this one.
329 const ClassInfo *getRootClass() const {
330 const ClassInfo *CI = this;
331 while (CI->SuperClass)
336 /// operator< - Compare two classes.
337 bool operator<(const ClassInfo &RHS) const {
338 // Incompatible kinds are comparable for classes in disjoint hierarchies.
339 if (Kind != RHS.Kind && getRootClass() != RHS.getRootClass())
340 return Kind < RHS.Kind;
344 assert(0 && "Invalid kind!");
346 // Tokens are comparable by value.
348 // FIXME: Compare by enum value.
349 return ValueName < RHS.ValueName;
352 // This class preceeds the RHS if the RHS is a super class.
353 for (ClassInfo *Parent = SuperClass; Parent; Parent = Parent->SuperClass)
362 /// InstructionInfo - Helper class for storing the necessary information for an
363 /// instruction which is capable of being matched.
364 struct InstructionInfo {
366 /// The unique class instance this operand should match.
369 /// The original operand this corresponds to, if any.
370 const CodeGenInstruction::OperandInfo *OperandInfo;
373 /// InstrName - The target name for this instruction.
374 std::string InstrName;
376 /// Instr - The instruction this matches.
377 const CodeGenInstruction *Instr;
379 /// AsmString - The assembly string for this instruction (with variants
381 std::string AsmString;
383 /// Tokens - The tokenized assembly pattern that this instruction matches.
384 SmallVector<StringRef, 4> Tokens;
386 /// Operands - The operands that this instruction matches.
387 SmallVector<Operand, 4> Operands;
389 /// ConversionFnKind - The enum value which is passed to the generated
390 /// ConvertToMCInst to convert parsed operands into an MCInst for this
392 std::string ConversionFnKind;
394 /// operator< - Compare two instructions.
395 bool operator<(const InstructionInfo &RHS) const {
396 if (Operands.size() != RHS.Operands.size())
397 return Operands.size() < RHS.Operands.size();
399 // Compare lexicographically by operand. The matcher validates that other
400 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
401 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
402 if (*Operands[i].Class < *RHS.Operands[i].Class)
404 if (*RHS.Operands[i].Class < *Operands[i].Class)
411 /// CouldMatchAmiguouslyWith - Check whether this instruction could
412 /// ambiguously match the same set of operands as \arg RHS (without being a
413 /// strictly superior match).
414 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
415 // The number of operands is unambiguous.
416 if (Operands.size() != RHS.Operands.size())
419 // Tokens and operand kinds are unambiguous (assuming a correct target
421 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
422 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
423 Operands[i].Class->Kind == ClassInfo::Token)
424 if (*Operands[i].Class < *RHS.Operands[i].Class ||
425 *RHS.Operands[i].Class < *Operands[i].Class)
428 // Otherwise, this operand could commute if all operands are equivalent, or
429 // there is a pair of operands that compare less than and a pair that
430 // compare greater than.
431 bool HasLT = false, HasGT = false;
432 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
433 if (*Operands[i].Class < *RHS.Operands[i].Class)
435 if (*RHS.Operands[i].Class < *Operands[i].Class)
439 return !(HasLT ^ HasGT);
446 class AsmMatcherInfo {
448 /// The classes which are needed for matching.
449 std::vector<ClassInfo*> Classes;
451 /// The information on the instruction to match.
452 std::vector<InstructionInfo*> Instructions;
455 /// Map of token to class information which has already been constructed.
456 std::map<std::string, ClassInfo*> TokenClasses;
458 /// Map of operand name to class information which has already been
460 std::map<std::string, ClassInfo*> OperandClasses;
462 /// Map of user class names to kind value.
463 std::map<std::string, unsigned> UserClasses;
466 /// getTokenClass - Lookup or create the class for the given token.
467 ClassInfo *getTokenClass(const StringRef &Token);
469 /// getUserClassKind - Lookup or create the kind value for the given class
471 unsigned getUserClassKind(const StringRef &Name);
473 /// getOperandClass - Lookup or create the class for the given operand.
474 ClassInfo *getOperandClass(const StringRef &Token,
475 const CodeGenInstruction::OperandInfo &OI);
478 /// BuildInfo - Construct the various tables used during matching.
479 void BuildInfo(CodeGenTarget &Target);
484 void InstructionInfo::dump() {
485 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
487 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
494 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
495 Operand &Op = Operands[i];
496 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
497 if (Op.Class->Kind == ClassInfo::Token) {
498 errs() << '\"' << Tokens[i] << "\"\n";
502 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
503 errs() << OI.Name << " " << OI.Rec->getName()
504 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
508 static std::string getEnumNameForToken(const StringRef &Str) {
511 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
513 case '*': Res += "_STAR_"; break;
514 case '%': Res += "_PCT_"; break;
515 case ':': Res += "_COLON_"; break;
521 Res += "_" + utostr((unsigned) *it) + "_";
529 ClassInfo *AsmMatcherInfo::getTokenClass(const StringRef &Token) {
530 ClassInfo *&Entry = TokenClasses[Token];
533 Entry = new ClassInfo();
534 Entry->Kind = ClassInfo::Token;
535 Entry->ClassName = "Token";
536 Entry->Name = "MCK_" + getEnumNameForToken(Token);
537 Entry->ValueName = Token;
538 Entry->PredicateMethod = "<invalid>";
539 Entry->RenderMethod = "<invalid>";
540 Classes.push_back(Entry);
546 unsigned AsmMatcherInfo::getUserClassKind(const StringRef &Name) {
547 unsigned &Entry = UserClasses[Name];
550 Entry = ClassInfo::UserClass0 + UserClasses.size() - 1;
556 AsmMatcherInfo::getOperandClass(const StringRef &Token,
557 const CodeGenInstruction::OperandInfo &OI) {
558 unsigned SuperClass = ClassInfo::Invalid;
559 std::string ClassName;
560 if (OI.Rec->isSubClassOf("RegisterClass")) {
564 ClassName = OI.Rec->getValueAsString("ParserMatchClass");
565 assert(ClassName != "Reg" && "'Reg' class name is reserved!");
567 PrintError(OI.Rec->getLoc(), "operand has no match class!");
568 ClassName = "Invalid";
571 // Determine the super class.
573 std::string SuperClassName =
574 OI.Rec->getValueAsString("ParserMatchSuperClass");
575 SuperClass = getUserClassKind(SuperClassName);
579 ClassInfo *&Entry = OperandClasses[ClassName];
582 Entry = new ClassInfo();
583 if (ClassName == "Reg") {
584 Entry->Kind = ClassInfo::Register;
585 Entry->SuperClassKind = SuperClass;
587 Entry->Kind = getUserClassKind(ClassName);
588 Entry->SuperClassKind = SuperClass;
590 Entry->ClassName = ClassName;
591 Entry->Name = "MCK_" + ClassName;
592 Entry->ValueName = OI.Rec->getName();
593 Entry->PredicateMethod = "is" + ClassName;
594 Entry->RenderMethod = "add" + ClassName + "Operands";
595 Classes.push_back(Entry);
597 // Verify the super class matches.
598 assert(SuperClass == Entry->SuperClassKind &&
599 "Cannot redefine super class kind!");
605 void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
606 for (std::map<std::string, CodeGenInstruction>::const_iterator
607 it = Target.getInstructions().begin(),
608 ie = Target.getInstructions().end();
610 const CodeGenInstruction &CGI = it->second;
612 if (!StringRef(it->first).startswith(MatchPrefix))
615 OwningPtr<InstructionInfo> II(new InstructionInfo);
617 II->InstrName = it->first;
618 II->Instr = &it->second;
619 II->AsmString = FlattenVariants(CGI.AsmString, 0);
621 TokenizeAsmString(II->AsmString, II->Tokens);
623 // Ignore instructions which shouldn't be matched.
624 if (!IsAssemblerInstruction(it->first, CGI, II->Tokens))
627 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
628 StringRef Token = II->Tokens[i];
630 // Check for simple tokens.
631 if (Token[0] != '$') {
632 InstructionInfo::Operand Op;
633 Op.Class = getTokenClass(Token);
635 II->Operands.push_back(Op);
639 // Otherwise this is an operand reference.
640 StringRef OperandName;
642 OperandName = Token.substr(2, Token.size() - 3);
644 OperandName = Token.substr(1);
646 // Map this token to an operand. FIXME: Move elsewhere.
649 Idx = CGI.getOperandNamed(OperandName);
651 errs() << "error: unable to find operand: '" << OperandName << "'!\n";
655 const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx];
656 InstructionInfo::Operand Op;
657 Op.Class = getOperandClass(Token, OI);
658 Op.OperandInfo = &OI;
659 II->Operands.push_back(Op);
662 // If we broke out, ignore the instruction.
663 if (II->Operands.size() != II->Tokens.size())
666 Instructions.push_back(II.take());
669 // Bind user super classes.
670 std::map<unsigned, ClassInfo*> UserClasses;
671 for (unsigned i = 0, e = Classes.size(); i != e; ++i) {
672 ClassInfo &CI = *Classes[i];
673 if (CI.isUserClass())
674 UserClasses[CI.Kind] = &CI;
677 for (unsigned i = 0, e = Classes.size(); i != e; ++i) {
678 ClassInfo &CI = *Classes[i];
679 if (CI.isUserClass() && CI.SuperClassKind != ClassInfo::Invalid) {
680 CI.SuperClass = UserClasses[CI.SuperClassKind];
681 assert(CI.SuperClass && "Missing super class definition!");
687 // Reorder classes so that classes preceed super classes.
688 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
691 static void EmitConvertToMCInst(CodeGenTarget &Target,
692 std::vector<InstructionInfo*> &Infos,
694 // Write the convert function to a separate stream, so we can drop it after
696 std::string ConvertFnBody;
697 raw_string_ostream CvtOS(ConvertFnBody);
699 // Function we have already generated.
700 std::set<std::string> GeneratedFns;
702 // Start the unified conversion function.
704 CvtOS << "static bool ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
705 << "unsigned Opcode,\n"
706 << " SmallVectorImpl<"
707 << Target.getName() << "Operand> &Operands) {\n";
708 CvtOS << " Inst.setOpcode(Opcode);\n";
709 CvtOS << " switch (Kind) {\n";
710 CvtOS << " default:\n";
712 // Start the enum, which we will generate inline.
714 OS << "// Unified function for converting operants to MCInst instances.\n\n";
715 OS << "enum ConversionKind {\n";
717 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
718 ie = Infos.end(); it != ie; ++it) {
719 InstructionInfo &II = **it;
721 // Order the (class) operands by the order to convert them into an MCInst.
722 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
723 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
724 InstructionInfo::Operand &Op = II.Operands[i];
726 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
728 std::sort(MIOperandList.begin(), MIOperandList.end());
730 // Compute the total number of operands.
731 unsigned NumMIOperands = 0;
732 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
733 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
734 NumMIOperands = std::max(NumMIOperands,
735 OI.MIOperandNo + OI.MINumOperands);
738 // Build the conversion function signature.
739 std::string Signature = "Convert";
740 unsigned CurIndex = 0;
741 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
742 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
743 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
744 "Duplicate match for instruction operand!");
748 // Skip operands which weren't matched by anything, this occurs when the
749 // .td file encodes "implicit" operands as explicit ones.
751 // FIXME: This should be removed from the MCInst structure.
752 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
755 Signature += Op.Class->ClassName;
756 Signature += utostr(Op.OperandInfo->MINumOperands);
757 Signature += "_" + utostr(MIOperandList[i].second);
759 CurIndex += Op.OperandInfo->MINumOperands;
762 // Add any trailing implicit operands.
763 for (; CurIndex != NumMIOperands; ++CurIndex)
766 II.ConversionFnKind = Signature;
768 // Check if we have already generated this signature.
769 if (!GeneratedFns.insert(Signature).second)
772 // If not, emit it now.
774 // Add to the enum list.
775 OS << " " << Signature << ",\n";
777 // And to the convert function.
778 CvtOS << " case " << Signature << ":\n";
780 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
781 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
783 // Add the implicit operands.
784 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
785 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
787 CvtOS << " Operands[" << MIOperandList[i].second
788 << "]." << Op.Class->RenderMethod
789 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
790 CurIndex += Op.OperandInfo->MINumOperands;
793 // And add trailing implicit operands.
794 for (; CurIndex != NumMIOperands; ++CurIndex)
795 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
796 CvtOS << " break;\n";
799 // Finish the convert function.
802 CvtOS << " return false;\n";
805 // Finish the enum, and drop the convert function after it.
807 OS << " NumConversionVariants\n";
813 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
814 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
815 std::vector<ClassInfo*> &Infos,
817 OS << "namespace {\n\n";
819 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
820 << "/// instruction matching.\n";
821 OS << "enum MatchClassKind {\n";
822 OS << " InvalidMatchClass = 0,\n";
823 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
824 ie = Infos.end(); it != ie; ++it) {
825 ClassInfo &CI = **it;
826 OS << " " << CI.Name << ", // ";
827 if (CI.Kind == ClassInfo::Token) {
828 OS << "'" << CI.ValueName << "'\n";
829 } else if (CI.Kind == ClassInfo::Register) {
830 if (!CI.ValueName.empty())
831 OS << "register class '" << CI.ValueName << "'\n";
833 OS << "derived register class\n";
835 OS << "user defined class '" << CI.ValueName << "'\n";
838 OS << " NumMatchClassKinds\n";
844 /// EmitClassifyOperand - Emit the function to classify an operand.
845 static void EmitClassifyOperand(CodeGenTarget &Target,
846 std::vector<ClassInfo*> &Infos,
848 OS << "static MatchClassKind ClassifyOperand("
849 << Target.getName() << "Operand &Operand) {\n";
850 OS << " if (Operand.isToken())\n";
851 OS << " return MatchTokenString(Operand.getToken());\n\n";
852 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
853 ie = Infos.end(); it != ie; ++it) {
854 ClassInfo &CI = **it;
856 if (CI.Kind != ClassInfo::Token) {
857 OS << " // '" << CI.ClassName << "' class";
859 OS << ", subclass of '" << CI.SuperClass->ClassName << "'";
860 assert(CI < *CI.SuperClass && "Invalid class relation!");
864 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
866 // Validate subclass relationships.
868 OS << " assert(Operand." << CI.SuperClass->PredicateMethod
869 << "() && \"Invalid class relationship!\");\n";
871 OS << " return " << CI.Name << ";\n\n";
875 OS << " return InvalidMatchClass;\n";
879 /// EmitIsSubclass - Emit the subclass predicate function.
880 static void EmitIsSubclass(CodeGenTarget &Target,
881 std::vector<ClassInfo*> &Infos,
883 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
884 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
885 OS << " if (A == B)\n";
886 OS << " return true;\n\n";
888 OS << " switch (A) {\n";
890 OS << " return false;\n";
891 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
892 ie = Infos.end(); it != ie; ++it) {
895 if (A.Kind != ClassInfo::Token) {
896 std::vector<StringRef> SuperClasses;
897 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
898 ie = Infos.end(); it != ie; ++it) {
901 if (&A != &B && A.getRootClass() == B.getRootClass() && A < B)
902 SuperClasses.push_back(B.Name);
905 if (SuperClasses.empty())
908 OS << "\n case " << A.Name << ":\n";
910 if (SuperClasses.size() == 1) {
911 OS << " return B == " << SuperClasses.back() << ";\n\n";
915 OS << " switch (B) {\n";
916 OS << " default: return false;\n";
917 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
918 OS << " case " << SuperClasses[i] << ": return true;\n";
926 typedef std::pair<std::string, std::string> StringPair;
928 /// FindFirstNonCommonLetter - Find the first character in the keys of the
929 /// string pairs that is not shared across the whole set of strings. All
930 /// strings are assumed to have the same length.
932 FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
933 assert(!Matches.empty());
934 for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
935 // Check to see if letter i is the same across the set.
936 char Letter = Matches[0]->first[i];
938 for (unsigned str = 0, e = Matches.size(); str != e; ++str)
939 if (Matches[str]->first[i] != Letter)
943 return Matches[0]->first.size();
946 /// EmitStringMatcherForChar - Given a set of strings that are known to be the
947 /// same length and whose characters leading up to CharNo are the same, emit
948 /// code to verify that CharNo and later are the same.
950 /// \return - True if control can leave the emitted code fragment.
951 static bool EmitStringMatcherForChar(const std::string &StrVariableName,
952 const std::vector<const StringPair*> &Matches,
953 unsigned CharNo, unsigned IndentCount,
955 assert(!Matches.empty() && "Must have at least one string to match!");
956 std::string Indent(IndentCount*2+4, ' ');
958 // If we have verified that the entire string matches, we're done: output the
960 if (CharNo == Matches[0]->first.size()) {
961 assert(Matches.size() == 1 && "Had duplicate keys to match on");
963 // FIXME: If Matches[0].first has embeded \n, this will be bad.
964 OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
969 // Bucket the matches by the character we are comparing.
970 std::map<char, std::vector<const StringPair*> > MatchesByLetter;
972 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
973 MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
976 // If we have exactly one bucket to match, see how many characters are common
977 // across the whole set and match all of them at once.
978 if (MatchesByLetter.size() == 1) {
979 unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
980 unsigned NumChars = FirstNonCommonLetter-CharNo;
982 // Emit code to break out if the prefix doesn't match.
984 // Do the comparison with if (Str[1] != 'f')
985 // FIXME: Need to escape general characters.
986 OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
987 << Matches[0]->first[CharNo] << "')\n";
988 OS << Indent << " break;\n";
990 // Do the comparison with if (Str.substr(1,3) != "foo").
991 // FIXME: Need to escape general strings.
992 OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
993 << NumChars << ") != \"";
994 OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
995 OS << Indent << " break;\n";
998 return EmitStringMatcherForChar(StrVariableName, Matches,
999 FirstNonCommonLetter, IndentCount, OS);
1002 // Otherwise, we have multiple possible things, emit a switch on the
1004 OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
1005 OS << Indent << "default: break;\n";
1007 for (std::map<char, std::vector<const StringPair*> >::iterator LI =
1008 MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
1009 // TODO: escape hard stuff (like \n) if we ever care about it.
1010 OS << Indent << "case '" << LI->first << "':\t // "
1011 << LI->second.size() << " strings to match.\n";
1012 if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
1014 OS << Indent << " break;\n";
1017 OS << Indent << "}\n";
1022 /// EmitStringMatcher - Given a list of strings and code to execute when they
1023 /// match, output a simple switch tree to classify the input string.
1025 /// If a match is found, the code in Vals[i].second is executed; control must
1026 /// not exit this code fragment. If nothing matches, execution falls through.
1028 /// \param StrVariableName - The name of the variable to test.
1029 static void EmitStringMatcher(const std::string &StrVariableName,
1030 const std::vector<StringPair> &Matches,
1032 // First level categorization: group strings by length.
1033 std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
1035 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1036 MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
1038 // Output a switch statement on length and categorize the elements within each
1040 OS << " switch (" << StrVariableName << ".size()) {\n";
1041 OS << " default: break;\n";
1043 for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
1044 MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
1045 OS << " case " << LI->first << ":\t // " << LI->second.size()
1046 << " strings to match.\n";
1047 if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
1055 /// EmitMatchTokenString - Emit the function to match a token string to the
1056 /// appropriate match class value.
1057 static void EmitMatchTokenString(CodeGenTarget &Target,
1058 std::vector<ClassInfo*> &Infos,
1060 // Construct the match list.
1061 std::vector<StringPair> Matches;
1062 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1063 ie = Infos.end(); it != ie; ++it) {
1064 ClassInfo &CI = **it;
1066 if (CI.Kind == ClassInfo::Token)
1067 Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
1070 OS << "static MatchClassKind MatchTokenString(const StringRef &Name) {\n";
1072 EmitStringMatcher("Name", Matches, OS);
1074 OS << " return InvalidMatchClass;\n";
1078 /// EmitMatchRegisterName - Emit the function to match a string to the target
1079 /// specific register enum.
1080 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1082 // Construct the match list.
1083 std::vector<StringPair> Matches;
1084 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1085 const CodeGenRegister &Reg = Target.getRegisters()[i];
1086 if (Reg.TheDef->getValueAsString("AsmName").empty())
1089 Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
1090 "return " + utostr(i + 1) + ";"));
1093 OS << "unsigned " << Target.getName()
1094 << AsmParser->getValueAsString("AsmParserClassName")
1095 << "::MatchRegisterName(const StringRef &Name) {\n";
1097 EmitStringMatcher("Name", Matches, OS);
1099 OS << " return 0;\n";
1103 void AsmMatcherEmitter::run(raw_ostream &OS) {
1104 CodeGenTarget Target;
1105 Record *AsmParser = Target.getAsmParser();
1106 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1108 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1110 // Emit the function to match a register name to number.
1111 EmitMatchRegisterName(Target, AsmParser, OS);
1113 // Compute the information on the instructions to match.
1114 AsmMatcherInfo Info;
1115 Info.BuildInfo(Target);
1117 // Sort the instruction table using the partial order on classes.
1118 std::sort(Info.Instructions.begin(), Info.Instructions.end(),
1119 less_ptr<InstructionInfo>());
1121 DEBUG_WITH_TYPE("instruction_info", {
1122 for (std::vector<InstructionInfo*>::iterator
1123 it = Info.Instructions.begin(), ie = Info.Instructions.end();
1128 // Check for ambiguous instructions.
1129 unsigned NumAmbiguous = 0;
1130 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1131 for (unsigned j = i + 1; j != e; ++j) {
1132 InstructionInfo &A = *Info.Instructions[i];
1133 InstructionInfo &B = *Info.Instructions[j];
1135 if (A.CouldMatchAmiguouslyWith(B)) {
1136 DEBUG_WITH_TYPE("ambiguous_instrs", {
1137 errs() << "warning: ambiguous instruction match:\n";
1139 errs() << "\nis incomparable with:\n";
1148 DEBUG_WITH_TYPE("ambiguous_instrs", {
1149 errs() << "warning: " << NumAmbiguous
1150 << " ambiguous instructions!\n";
1153 // Generate the unified function to convert operands into an MCInst.
1154 EmitConvertToMCInst(Target, Info.Instructions, OS);
1156 // Emit the enumeration for classes which participate in matching.
1157 EmitMatchClassEnumeration(Target, Info.Classes, OS);
1159 // Emit the routine to match token strings to their match class.
1160 EmitMatchTokenString(Target, Info.Classes, OS);
1162 // Emit the routine to classify an operand.
1163 EmitClassifyOperand(Target, Info.Classes, OS);
1165 // Emit the subclass predicate routine.
1166 EmitIsSubclass(Target, Info.Classes, OS);
1168 // Finally, build the match function.
1170 size_t MaxNumOperands = 0;
1171 for (std::vector<InstructionInfo*>::const_iterator it =
1172 Info.Instructions.begin(), ie = Info.Instructions.end();
1174 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1176 OS << "bool " << Target.getName() << ClassName
1177 << "::MatchInstruction("
1178 << "SmallVectorImpl<" << Target.getName() << "Operand> &Operands, "
1179 << "MCInst &Inst) {\n";
1181 // Emit the static match table; unused classes get initalized to 0 which is
1182 // guaranteed to be InvalidMatchClass.
1184 // FIXME: We can reduce the size of this table very easily. First, we change
1185 // it so that store the kinds in separate bit-fields for each index, which
1186 // only needs to be the max width used for classes at that index (we also need
1187 // to reject based on this during classification). If we then make sure to
1188 // order the match kinds appropriately (putting mnemonics last), then we
1189 // should only end up using a few bits for each class, especially the ones
1190 // following the mnemonic.
1191 OS << " static const struct MatchEntry {\n";
1192 OS << " unsigned Opcode;\n";
1193 OS << " ConversionKind ConvertFn;\n";
1194 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1195 OS << " } MatchTable[" << Info.Instructions.size() << "] = {\n";
1197 for (std::vector<InstructionInfo*>::const_iterator it =
1198 Info.Instructions.begin(), ie = Info.Instructions.end();
1200 InstructionInfo &II = **it;
1202 OS << " { " << Target.getName() << "::" << II.InstrName
1203 << ", " << II.ConversionFnKind << ", { ";
1204 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1205 InstructionInfo::Operand &Op = II.Operands[i];
1208 OS << Op.Class->Name;
1215 // Emit code to compute the class list for this operand vector.
1216 OS << " // Eliminate obvious mismatches.\n";
1217 OS << " if (Operands.size() > " << MaxNumOperands << ")\n";
1218 OS << " return true;\n\n";
1220 OS << " // Compute the class list for this operand vector.\n";
1221 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1222 OS << " for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1223 OS << " Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1225 OS << " // Check for invalid operands before matching.\n";
1226 OS << " if (Classes[i] == InvalidMatchClass)\n";
1227 OS << " return true;\n";
1230 OS << " // Mark unused classes.\n";
1231 OS << " for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1232 << "i != e; ++i)\n";
1233 OS << " Classes[i] = InvalidMatchClass;\n\n";
1235 // Emit code to search the table.
1236 OS << " // Search the table.\n";
1237 OS << " for (const MatchEntry *it = MatchTable, "
1238 << "*ie = MatchTable + " << Info.Instructions.size()
1239 << "; it != ie; ++it) {\n";
1240 for (unsigned i = 0; i != MaxNumOperands; ++i) {
1241 OS << " if (!IsSubclass(Classes["
1242 << i << "], it->Classes[" << i << "]))\n";
1243 OS << " continue;\n";
1246 OS << " return ConvertToMCInst(it->ConvertFn, Inst, "
1247 << "it->Opcode, Operands);\n";
1250 OS << " return true;\n";