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 = 0, ///< Invalid kind, for use as a sentinel value.
286 Token, ///< The class for a particular token.
287 Register, ///< A register class.
288 UserClass0 ///< The (first) user defined class, subsequent user defined
289 /// classes are UserClass0+1, and so on.
292 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
293 /// N) for the Nth user defined class.
296 /// SuperClass - The super class, or 0.
297 ClassInfo *SuperClass;
299 /// Name - The full class name, suitable for use in an enum.
302 /// ClassName - The unadorned generic name for this class (e.g., Token).
303 std::string ClassName;
305 /// ValueName - The name of the value this class represents; for a token this
306 /// is the literal token string, for an operand it is the TableGen class (or
307 /// empty if this is a derived class).
308 std::string ValueName;
310 /// PredicateMethod - The name of the operand method to test whether the
311 /// operand matches this class; this is not valid for Token kinds.
312 std::string PredicateMethod;
314 /// RenderMethod - The name of the operand method to add this operand to an
315 /// MCInst; this is not valid for Token kinds.
316 std::string RenderMethod;
318 /// isUserClass() - Check if this is a user defined class.
319 bool isUserClass() const {
320 return Kind >= UserClass0;
323 /// getRootClass - Return the root class of this one.
324 const ClassInfo *getRootClass() const {
325 const ClassInfo *CI = this;
326 while (CI->SuperClass)
331 /// operator< - Compare two classes.
332 bool operator<(const ClassInfo &RHS) const {
333 // Incompatible kinds are comparable for classes in disjoint hierarchies.
334 if (Kind != RHS.Kind && getRootClass() != RHS.getRootClass())
335 return Kind < RHS.Kind;
339 assert(0 && "Invalid kind!");
341 // Tokens are comparable by value.
343 // FIXME: Compare by enum value.
344 return ValueName < RHS.ValueName;
347 // This class preceeds the RHS if the RHS is a super class.
348 for (ClassInfo *Parent = SuperClass; Parent; Parent = Parent->SuperClass)
357 /// InstructionInfo - Helper class for storing the necessary information for an
358 /// instruction which is capable of being matched.
359 struct InstructionInfo {
361 /// The unique class instance this operand should match.
364 /// The original operand this corresponds to, if any.
365 const CodeGenInstruction::OperandInfo *OperandInfo;
368 /// InstrName - The target name for this instruction.
369 std::string InstrName;
371 /// Instr - The instruction this matches.
372 const CodeGenInstruction *Instr;
374 /// AsmString - The assembly string for this instruction (with variants
376 std::string AsmString;
378 /// Tokens - The tokenized assembly pattern that this instruction matches.
379 SmallVector<StringRef, 4> Tokens;
381 /// Operands - The operands that this instruction matches.
382 SmallVector<Operand, 4> Operands;
384 /// ConversionFnKind - The enum value which is passed to the generated
385 /// ConvertToMCInst to convert parsed operands into an MCInst for this
387 std::string ConversionFnKind;
389 /// operator< - Compare two instructions.
390 bool operator<(const InstructionInfo &RHS) const {
391 if (Operands.size() != RHS.Operands.size())
392 return Operands.size() < RHS.Operands.size();
394 // Compare lexicographically by operand. The matcher validates that other
395 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
396 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
397 if (*Operands[i].Class < *RHS.Operands[i].Class)
399 if (*RHS.Operands[i].Class < *Operands[i].Class)
406 /// CouldMatchAmiguouslyWith - Check whether this instruction could
407 /// ambiguously match the same set of operands as \arg RHS (without being a
408 /// strictly superior match).
409 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
410 // The number of operands is unambiguous.
411 if (Operands.size() != RHS.Operands.size())
414 // Tokens and operand kinds are unambiguous (assuming a correct target
416 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
417 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
418 Operands[i].Class->Kind == ClassInfo::Token)
419 if (*Operands[i].Class < *RHS.Operands[i].Class ||
420 *RHS.Operands[i].Class < *Operands[i].Class)
423 // Otherwise, this operand could commute if all operands are equivalent, or
424 // there is a pair of operands that compare less than and a pair that
425 // compare greater than.
426 bool HasLT = false, HasGT = false;
427 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
428 if (*Operands[i].Class < *RHS.Operands[i].Class)
430 if (*RHS.Operands[i].Class < *Operands[i].Class)
434 return !(HasLT ^ HasGT);
441 class AsmMatcherInfo {
443 /// The classes which are needed for matching.
444 std::vector<ClassInfo*> Classes;
446 /// The information on the instruction to match.
447 std::vector<InstructionInfo*> Instructions;
450 /// Map of token to class information which has already been constructed.
451 std::map<std::string, ClassInfo*> TokenClasses;
453 /// The ClassInfo instance for registers.
454 ClassInfo *TheRegisterClass;
456 /// Map of AsmOperandClass records to their class information.
457 std::map<Record*, ClassInfo*> AsmOperandClasses;
460 /// getTokenClass - Lookup or create the class for the given token.
461 ClassInfo *getTokenClass(const StringRef &Token);
463 /// getOperandClass - Lookup or create the class for the given operand.
464 ClassInfo *getOperandClass(const StringRef &Token,
465 const CodeGenInstruction::OperandInfo &OI);
468 /// BuildInfo - Construct the various tables used during matching.
469 void BuildInfo(CodeGenTarget &Target);
474 void InstructionInfo::dump() {
475 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
477 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
484 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
485 Operand &Op = Operands[i];
486 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
487 if (Op.Class->Kind == ClassInfo::Token) {
488 errs() << '\"' << Tokens[i] << "\"\n";
492 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
493 errs() << OI.Name << " " << OI.Rec->getName()
494 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
498 static std::string getEnumNameForToken(const StringRef &Str) {
501 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
503 case '*': Res += "_STAR_"; break;
504 case '%': Res += "_PCT_"; break;
505 case ':': Res += "_COLON_"; break;
511 Res += "_" + utostr((unsigned) *it) + "_";
519 ClassInfo *AsmMatcherInfo::getTokenClass(const StringRef &Token) {
520 ClassInfo *&Entry = TokenClasses[Token];
523 Entry = new ClassInfo();
524 Entry->Kind = ClassInfo::Token;
525 Entry->SuperClass = 0;
526 Entry->ClassName = "Token";
527 Entry->Name = "MCK_" + getEnumNameForToken(Token);
528 Entry->ValueName = Token;
529 Entry->PredicateMethod = "<invalid>";
530 Entry->RenderMethod = "<invalid>";
531 Classes.push_back(Entry);
538 AsmMatcherInfo::getOperandClass(const StringRef &Token,
539 const CodeGenInstruction::OperandInfo &OI) {
540 if (OI.Rec->isSubClassOf("RegisterClass"))
541 return TheRegisterClass;
543 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
544 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
545 ClassInfo *CI = AsmOperandClasses[MatchClass];
548 PrintError(OI.Rec->getLoc(), "operand has no match class!");
549 throw std::string("ERROR: Missing match class!");
555 void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
556 // Build the assembly match class information.
558 // Construct the "Reg" class.
560 // FIXME: This needs to dice up the RegisterClass instances.
561 ClassInfo *RegClass = TheRegisterClass = new ClassInfo();
562 RegClass->Kind = ClassInfo::Register;
563 RegClass->SuperClass = 0;
564 RegClass->ClassName = "Reg";
565 RegClass->Name = "MCK_Reg";
566 RegClass->ValueName = "<register class>";
567 RegClass->PredicateMethod = "isReg";
568 RegClass->RenderMethod = "addRegOperands";
569 Classes.push_back(RegClass);
571 // Build info for the user defined assembly operand classes.
572 std::vector<Record*> AsmOperands;
573 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
575 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
576 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
577 ClassInfo *CI = new ClassInfo();
578 CI->Kind = ClassInfo::UserClass0 + Index;
580 Init *Super = (*it)->getValueInit("SuperClass");
581 if (DefInit *DI = dynamic_cast<DefInit*>(Super)) {
582 CI->SuperClass = AsmOperandClasses[DI->getDef()];
584 PrintError((*it)->getLoc(), "Invalid super class reference!");
586 assert(dynamic_cast<UnsetInit*>(Super) && "Unexpected SuperClass field!");
589 CI->ClassName = (*it)->getValueAsString("Name");
590 CI->Name = "MCK_" + CI->ClassName;
591 CI->ValueName = (*it)->getName();
592 CI->PredicateMethod = "is" + CI->ClassName;
593 CI->RenderMethod = "add" + CI->ClassName + "Operands";
594 AsmOperandClasses[*it] = CI;
595 Classes.push_back(CI);
598 // Build the instruction information.
599 for (std::map<std::string, CodeGenInstruction>::const_iterator
600 it = Target.getInstructions().begin(),
601 ie = Target.getInstructions().end();
603 const CodeGenInstruction &CGI = it->second;
605 if (!StringRef(it->first).startswith(MatchPrefix))
608 OwningPtr<InstructionInfo> II(new InstructionInfo);
610 II->InstrName = it->first;
611 II->Instr = &it->second;
612 II->AsmString = FlattenVariants(CGI.AsmString, 0);
614 TokenizeAsmString(II->AsmString, II->Tokens);
616 // Ignore instructions which shouldn't be matched.
617 if (!IsAssemblerInstruction(it->first, CGI, II->Tokens))
620 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
621 StringRef Token = II->Tokens[i];
623 // Check for simple tokens.
624 if (Token[0] != '$') {
625 InstructionInfo::Operand Op;
626 Op.Class = getTokenClass(Token);
628 II->Operands.push_back(Op);
632 // Otherwise this is an operand reference.
633 StringRef OperandName;
635 OperandName = Token.substr(2, Token.size() - 3);
637 OperandName = Token.substr(1);
639 // Map this token to an operand. FIXME: Move elsewhere.
642 Idx = CGI.getOperandNamed(OperandName);
644 errs() << "error: unable to find operand: '" << OperandName << "'!\n";
648 const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx];
649 InstructionInfo::Operand Op;
650 Op.Class = getOperandClass(Token, OI);
651 Op.OperandInfo = &OI;
652 II->Operands.push_back(Op);
655 // If we broke out, ignore the instruction.
656 if (II->Operands.size() != II->Tokens.size())
659 Instructions.push_back(II.take());
662 // Reorder classes so that classes preceed super classes.
663 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
666 static void EmitConvertToMCInst(CodeGenTarget &Target,
667 std::vector<InstructionInfo*> &Infos,
669 // Write the convert function to a separate stream, so we can drop it after
671 std::string ConvertFnBody;
672 raw_string_ostream CvtOS(ConvertFnBody);
674 // Function we have already generated.
675 std::set<std::string> GeneratedFns;
677 // Start the unified conversion function.
679 CvtOS << "static bool ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
680 << "unsigned Opcode,\n"
681 << " SmallVectorImpl<"
682 << Target.getName() << "Operand> &Operands) {\n";
683 CvtOS << " Inst.setOpcode(Opcode);\n";
684 CvtOS << " switch (Kind) {\n";
685 CvtOS << " default:\n";
687 // Start the enum, which we will generate inline.
689 OS << "// Unified function for converting operants to MCInst instances.\n\n";
690 OS << "enum ConversionKind {\n";
692 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
693 ie = Infos.end(); it != ie; ++it) {
694 InstructionInfo &II = **it;
696 // Order the (class) operands by the order to convert them into an MCInst.
697 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
698 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
699 InstructionInfo::Operand &Op = II.Operands[i];
701 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
703 std::sort(MIOperandList.begin(), MIOperandList.end());
705 // Compute the total number of operands.
706 unsigned NumMIOperands = 0;
707 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
708 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
709 NumMIOperands = std::max(NumMIOperands,
710 OI.MIOperandNo + OI.MINumOperands);
713 // Build the conversion function signature.
714 std::string Signature = "Convert";
715 unsigned CurIndex = 0;
716 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
717 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
718 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
719 "Duplicate match for instruction operand!");
723 // Skip operands which weren't matched by anything, this occurs when the
724 // .td file encodes "implicit" operands as explicit ones.
726 // FIXME: This should be removed from the MCInst structure.
727 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
730 Signature += Op.Class->ClassName;
731 Signature += utostr(Op.OperandInfo->MINumOperands);
732 Signature += "_" + utostr(MIOperandList[i].second);
734 CurIndex += Op.OperandInfo->MINumOperands;
737 // Add any trailing implicit operands.
738 for (; CurIndex != NumMIOperands; ++CurIndex)
741 II.ConversionFnKind = Signature;
743 // Check if we have already generated this signature.
744 if (!GeneratedFns.insert(Signature).second)
747 // If not, emit it now.
749 // Add to the enum list.
750 OS << " " << Signature << ",\n";
752 // And to the convert function.
753 CvtOS << " case " << Signature << ":\n";
755 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
756 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
758 // Add the implicit operands.
759 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
760 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
762 CvtOS << " Operands[" << MIOperandList[i].second
763 << "]." << Op.Class->RenderMethod
764 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
765 CurIndex += Op.OperandInfo->MINumOperands;
768 // And add trailing implicit operands.
769 for (; CurIndex != NumMIOperands; ++CurIndex)
770 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
771 CvtOS << " break;\n";
774 // Finish the convert function.
777 CvtOS << " return false;\n";
780 // Finish the enum, and drop the convert function after it.
782 OS << " NumConversionVariants\n";
788 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
789 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
790 std::vector<ClassInfo*> &Infos,
792 OS << "namespace {\n\n";
794 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
795 << "/// instruction matching.\n";
796 OS << "enum MatchClassKind {\n";
797 OS << " InvalidMatchClass = 0,\n";
798 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
799 ie = Infos.end(); it != ie; ++it) {
800 ClassInfo &CI = **it;
801 OS << " " << CI.Name << ", // ";
802 if (CI.Kind == ClassInfo::Token) {
803 OS << "'" << CI.ValueName << "'\n";
804 } else if (CI.Kind == ClassInfo::Register) {
805 if (!CI.ValueName.empty())
806 OS << "register class '" << CI.ValueName << "'\n";
808 OS << "derived register class\n";
810 OS << "user defined class '" << CI.ValueName << "'\n";
813 OS << " NumMatchClassKinds\n";
819 /// EmitClassifyOperand - Emit the function to classify an operand.
820 static void EmitClassifyOperand(CodeGenTarget &Target,
821 std::vector<ClassInfo*> &Infos,
823 OS << "static MatchClassKind ClassifyOperand("
824 << Target.getName() << "Operand &Operand) {\n";
825 OS << " if (Operand.isToken())\n";
826 OS << " return MatchTokenString(Operand.getToken());\n\n";
827 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
828 ie = Infos.end(); it != ie; ++it) {
829 ClassInfo &CI = **it;
831 if (CI.Kind != ClassInfo::Token) {
832 OS << " // '" << CI.ClassName << "' class";
834 OS << ", subclass of '" << CI.SuperClass->ClassName << "'";
835 assert(CI < *CI.SuperClass && "Invalid class relation!");
839 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
841 // Validate subclass relationships.
843 OS << " assert(Operand." << CI.SuperClass->PredicateMethod
844 << "() && \"Invalid class relationship!\");\n";
846 OS << " return " << CI.Name << ";\n";
850 OS << " return InvalidMatchClass;\n";
854 /// EmitIsSubclass - Emit the subclass predicate function.
855 static void EmitIsSubclass(CodeGenTarget &Target,
856 std::vector<ClassInfo*> &Infos,
858 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
859 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
860 OS << " if (A == B)\n";
861 OS << " return true;\n\n";
863 OS << " switch (A) {\n";
865 OS << " return false;\n";
866 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
867 ie = Infos.end(); it != ie; ++it) {
870 if (A.Kind != ClassInfo::Token) {
871 std::vector<StringRef> SuperClasses;
872 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
873 ie = Infos.end(); it != ie; ++it) {
876 if (&A != &B && A.getRootClass() == B.getRootClass() && A < B)
877 SuperClasses.push_back(B.Name);
880 if (SuperClasses.empty())
883 OS << "\n case " << A.Name << ":\n";
885 if (SuperClasses.size() == 1) {
886 OS << " return B == " << SuperClasses.back() << ";\n\n";
890 OS << " switch (B) {\n";
891 OS << " default: return false;\n";
892 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
893 OS << " case " << SuperClasses[i] << ": return true;\n";
901 typedef std::pair<std::string, std::string> StringPair;
903 /// FindFirstNonCommonLetter - Find the first character in the keys of the
904 /// string pairs that is not shared across the whole set of strings. All
905 /// strings are assumed to have the same length.
907 FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
908 assert(!Matches.empty());
909 for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
910 // Check to see if letter i is the same across the set.
911 char Letter = Matches[0]->first[i];
913 for (unsigned str = 0, e = Matches.size(); str != e; ++str)
914 if (Matches[str]->first[i] != Letter)
918 return Matches[0]->first.size();
921 /// EmitStringMatcherForChar - Given a set of strings that are known to be the
922 /// same length and whose characters leading up to CharNo are the same, emit
923 /// code to verify that CharNo and later are the same.
925 /// \return - True if control can leave the emitted code fragment.
926 static bool EmitStringMatcherForChar(const std::string &StrVariableName,
927 const std::vector<const StringPair*> &Matches,
928 unsigned CharNo, unsigned IndentCount,
930 assert(!Matches.empty() && "Must have at least one string to match!");
931 std::string Indent(IndentCount*2+4, ' ');
933 // If we have verified that the entire string matches, we're done: output the
935 if (CharNo == Matches[0]->first.size()) {
936 assert(Matches.size() == 1 && "Had duplicate keys to match on");
938 // FIXME: If Matches[0].first has embeded \n, this will be bad.
939 OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
944 // Bucket the matches by the character we are comparing.
945 std::map<char, std::vector<const StringPair*> > MatchesByLetter;
947 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
948 MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
951 // If we have exactly one bucket to match, see how many characters are common
952 // across the whole set and match all of them at once.
953 if (MatchesByLetter.size() == 1) {
954 unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
955 unsigned NumChars = FirstNonCommonLetter-CharNo;
957 // Emit code to break out if the prefix doesn't match.
959 // Do the comparison with if (Str[1] != 'f')
960 // FIXME: Need to escape general characters.
961 OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
962 << Matches[0]->first[CharNo] << "')\n";
963 OS << Indent << " break;\n";
965 // Do the comparison with if (Str.substr(1,3) != "foo").
966 // FIXME: Need to escape general strings.
967 OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
968 << NumChars << ") != \"";
969 OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
970 OS << Indent << " break;\n";
973 return EmitStringMatcherForChar(StrVariableName, Matches,
974 FirstNonCommonLetter, IndentCount, OS);
977 // Otherwise, we have multiple possible things, emit a switch on the
979 OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
980 OS << Indent << "default: break;\n";
982 for (std::map<char, std::vector<const StringPair*> >::iterator LI =
983 MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
984 // TODO: escape hard stuff (like \n) if we ever care about it.
985 OS << Indent << "case '" << LI->first << "':\t // "
986 << LI->second.size() << " strings to match.\n";
987 if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
989 OS << Indent << " break;\n";
992 OS << Indent << "}\n";
997 /// EmitStringMatcher - Given a list of strings and code to execute when they
998 /// match, output a simple switch tree to classify the input string.
1000 /// If a match is found, the code in Vals[i].second is executed; control must
1001 /// not exit this code fragment. If nothing matches, execution falls through.
1003 /// \param StrVariableName - The name of the variable to test.
1004 static void EmitStringMatcher(const std::string &StrVariableName,
1005 const std::vector<StringPair> &Matches,
1007 // First level categorization: group strings by length.
1008 std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
1010 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1011 MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
1013 // Output a switch statement on length and categorize the elements within each
1015 OS << " switch (" << StrVariableName << ".size()) {\n";
1016 OS << " default: break;\n";
1018 for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
1019 MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
1020 OS << " case " << LI->first << ":\t // " << LI->second.size()
1021 << " strings to match.\n";
1022 if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
1030 /// EmitMatchTokenString - Emit the function to match a token string to the
1031 /// appropriate match class value.
1032 static void EmitMatchTokenString(CodeGenTarget &Target,
1033 std::vector<ClassInfo*> &Infos,
1035 // Construct the match list.
1036 std::vector<StringPair> Matches;
1037 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1038 ie = Infos.end(); it != ie; ++it) {
1039 ClassInfo &CI = **it;
1041 if (CI.Kind == ClassInfo::Token)
1042 Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
1045 OS << "static MatchClassKind MatchTokenString(const StringRef &Name) {\n";
1047 EmitStringMatcher("Name", Matches, OS);
1049 OS << " return InvalidMatchClass;\n";
1053 /// EmitMatchRegisterName - Emit the function to match a string to the target
1054 /// specific register enum.
1055 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1057 // Construct the match list.
1058 std::vector<StringPair> Matches;
1059 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1060 const CodeGenRegister &Reg = Target.getRegisters()[i];
1061 if (Reg.TheDef->getValueAsString("AsmName").empty())
1064 Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
1065 "return " + utostr(i + 1) + ";"));
1068 OS << "unsigned " << Target.getName()
1069 << AsmParser->getValueAsString("AsmParserClassName")
1070 << "::MatchRegisterName(const StringRef &Name) {\n";
1072 EmitStringMatcher("Name", Matches, OS);
1074 OS << " return 0;\n";
1078 void AsmMatcherEmitter::run(raw_ostream &OS) {
1079 CodeGenTarget Target;
1080 Record *AsmParser = Target.getAsmParser();
1081 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1083 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1085 // Emit the function to match a register name to number.
1086 EmitMatchRegisterName(Target, AsmParser, OS);
1088 // Compute the information on the instructions to match.
1089 AsmMatcherInfo Info;
1090 Info.BuildInfo(Target);
1092 // Sort the instruction table using the partial order on classes.
1093 std::sort(Info.Instructions.begin(), Info.Instructions.end(),
1094 less_ptr<InstructionInfo>());
1096 DEBUG_WITH_TYPE("instruction_info", {
1097 for (std::vector<InstructionInfo*>::iterator
1098 it = Info.Instructions.begin(), ie = Info.Instructions.end();
1103 // Check for ambiguous instructions.
1104 unsigned NumAmbiguous = 0;
1105 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1106 for (unsigned j = i + 1; j != e; ++j) {
1107 InstructionInfo &A = *Info.Instructions[i];
1108 InstructionInfo &B = *Info.Instructions[j];
1110 if (A.CouldMatchAmiguouslyWith(B)) {
1111 DEBUG_WITH_TYPE("ambiguous_instrs", {
1112 errs() << "warning: ambiguous instruction match:\n";
1114 errs() << "\nis incomparable with:\n";
1123 DEBUG_WITH_TYPE("ambiguous_instrs", {
1124 errs() << "warning: " << NumAmbiguous
1125 << " ambiguous instructions!\n";
1128 // Generate the unified function to convert operands into an MCInst.
1129 EmitConvertToMCInst(Target, Info.Instructions, OS);
1131 // Emit the enumeration for classes which participate in matching.
1132 EmitMatchClassEnumeration(Target, Info.Classes, OS);
1134 // Emit the routine to match token strings to their match class.
1135 EmitMatchTokenString(Target, Info.Classes, OS);
1137 // Emit the routine to classify an operand.
1138 EmitClassifyOperand(Target, Info.Classes, OS);
1140 // Emit the subclass predicate routine.
1141 EmitIsSubclass(Target, Info.Classes, OS);
1143 // Finally, build the match function.
1145 size_t MaxNumOperands = 0;
1146 for (std::vector<InstructionInfo*>::const_iterator it =
1147 Info.Instructions.begin(), ie = Info.Instructions.end();
1149 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1151 OS << "bool " << Target.getName() << ClassName
1152 << "::MatchInstruction("
1153 << "SmallVectorImpl<" << Target.getName() << "Operand> &Operands, "
1154 << "MCInst &Inst) {\n";
1156 // Emit the static match table; unused classes get initalized to 0 which is
1157 // guaranteed to be InvalidMatchClass.
1159 // FIXME: We can reduce the size of this table very easily. First, we change
1160 // it so that store the kinds in separate bit-fields for each index, which
1161 // only needs to be the max width used for classes at that index (we also need
1162 // to reject based on this during classification). If we then make sure to
1163 // order the match kinds appropriately (putting mnemonics last), then we
1164 // should only end up using a few bits for each class, especially the ones
1165 // following the mnemonic.
1166 OS << " static const struct MatchEntry {\n";
1167 OS << " unsigned Opcode;\n";
1168 OS << " ConversionKind ConvertFn;\n";
1169 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1170 OS << " } MatchTable[" << Info.Instructions.size() << "] = {\n";
1172 for (std::vector<InstructionInfo*>::const_iterator it =
1173 Info.Instructions.begin(), ie = Info.Instructions.end();
1175 InstructionInfo &II = **it;
1177 OS << " { " << Target.getName() << "::" << II.InstrName
1178 << ", " << II.ConversionFnKind << ", { ";
1179 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1180 InstructionInfo::Operand &Op = II.Operands[i];
1183 OS << Op.Class->Name;
1190 // Emit code to compute the class list for this operand vector.
1191 OS << " // Eliminate obvious mismatches.\n";
1192 OS << " if (Operands.size() > " << MaxNumOperands << ")\n";
1193 OS << " return true;\n\n";
1195 OS << " // Compute the class list for this operand vector.\n";
1196 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1197 OS << " for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1198 OS << " Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1200 OS << " // Check for invalid operands before matching.\n";
1201 OS << " if (Classes[i] == InvalidMatchClass)\n";
1202 OS << " return true;\n";
1205 OS << " // Mark unused classes.\n";
1206 OS << " for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1207 << "i != e; ++i)\n";
1208 OS << " Classes[i] = InvalidMatchClass;\n\n";
1210 // Emit code to search the table.
1211 OS << " // Search the table.\n";
1212 OS << " for (const MatchEntry *it = MatchTable, "
1213 << "*ie = MatchTable + " << Info.Instructions.size()
1214 << "; it != ie; ++it) {\n";
1215 for (unsigned i = 0; i != MaxNumOperands; ++i) {
1216 OS << " if (!IsSubclass(Classes["
1217 << i << "], it->Classes[" << i << "]))\n";
1218 OS << " continue;\n";
1221 OS << " return ConvertToMCInst(it->ConvertFn, Inst, "
1222 << "it->Opcode, Operands);\n";
1225 OS << " return true;\n";