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 "StringMatcher.h"
80 #include "llvm/ADT/OwningPtr.h"
81 #include "llvm/ADT/SmallVector.h"
82 #include "llvm/ADT/STLExtras.h"
83 #include "llvm/ADT/StringExtras.h"
84 #include "llvm/Support/CommandLine.h"
85 #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"));
95 /// FlattenVariants - Flatten an .td file assembly string by selecting the
96 /// variant at index \arg N.
97 static std::string FlattenVariants(const std::string &AsmString,
99 StringRef Cur = AsmString;
100 std::string Res = "";
103 // Find the start of the next variant string.
104 size_t VariantsStart = 0;
105 for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
106 if (Cur[VariantsStart] == '{' &&
107 (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
108 Cur[VariantsStart-1] != '\\')))
111 // Add the prefix to the result.
112 Res += Cur.slice(0, VariantsStart);
113 if (VariantsStart == Cur.size())
116 ++VariantsStart; // Skip the '{'.
118 // Scan to the end of the variants string.
119 size_t VariantsEnd = VariantsStart;
120 unsigned NestedBraces = 1;
121 for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
122 if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
123 if (--NestedBraces == 0)
125 } else if (Cur[VariantsEnd] == '{')
129 // Select the Nth variant (or empty).
130 StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
131 for (unsigned i = 0; i != N; ++i)
132 Selection = Selection.split('|').second;
133 Res += Selection.split('|').first;
135 assert(VariantsEnd != Cur.size() &&
136 "Unterminated variants in assembly string!");
137 Cur = Cur.substr(VariantsEnd + 1);
143 /// TokenizeAsmString - Tokenize a simplified assembly string.
144 static void TokenizeAsmString(StringRef AsmString,
145 SmallVectorImpl<StringRef> &Tokens) {
148 for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {
149 switch (AsmString[i]) {
158 Tokens.push_back(AsmString.slice(Prev, i));
161 if (!isspace(AsmString[i]) && AsmString[i] != ',')
162 Tokens.push_back(AsmString.substr(i, 1));
168 Tokens.push_back(AsmString.slice(Prev, i));
172 assert(i != AsmString.size() && "Invalid quoted character");
173 Tokens.push_back(AsmString.substr(i, 1));
178 // If this isn't "${", treat like a normal token.
179 if (i + 1 == AsmString.size() || AsmString[i + 1] != '{') {
181 Tokens.push_back(AsmString.slice(Prev, i));
189 Tokens.push_back(AsmString.slice(Prev, i));
193 StringRef::iterator End =
194 std::find(AsmString.begin() + i, AsmString.end(), '}');
195 assert(End != AsmString.end() && "Missing brace in operand reference!");
196 size_t EndPos = End - AsmString.begin();
197 Tokens.push_back(AsmString.slice(i, EndPos+1));
205 Tokens.push_back(AsmString.slice(Prev, i));
215 if (InTok && Prev != AsmString.size())
216 Tokens.push_back(AsmString.substr(Prev));
219 static bool IsAssemblerInstruction(StringRef Name,
220 const CodeGenInstruction &CGI,
221 const SmallVectorImpl<StringRef> &Tokens) {
222 // Ignore "codegen only" instructions.
223 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
226 // Ignore pseudo ops.
228 // FIXME: This is a hack [for X86]; can we convert these instructions to set
229 // the "codegen only" bit instead?
230 if (const RecordVal *Form = CGI.TheDef->getValue("Form"))
231 if (Form->getValue()->getAsString() == "Pseudo")
234 // FIXME: This is a hack [for ARM]; can we convert these instructions to set
235 // the "codegen only" bit instead?
236 if (const RecordVal *Form = CGI.TheDef->getValue("F"))
237 if (Form->getValue()->getAsString() == "Pseudo")
241 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
243 // FIXME: This is a total hack.
244 if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
247 // Ignore instructions with no .s string.
249 // FIXME: What are these?
250 if (CGI.AsmString.empty()) {
251 PrintError(CGI.TheDef->getLoc(),
252 "instruction with empty asm string");
253 throw std::string("ERROR: Invalid instruction for asm matcher");
256 // FIXME: Hack; ignore any instructions with a newline in them.
257 if (std::find(CGI.AsmString.begin(),
258 CGI.AsmString.end(), '\n') != CGI.AsmString.end())
261 // Reject instructions with attributes, these aren't something we can handle,
262 // the target should be refactored to use operands instead of modifiers.
264 // Also, check for instructions which reference the operand multiple times;
265 // this implies a constraint we would not honor.
266 std::set<std::string> OperandNames;
267 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
268 if (Tokens[i][0] == '$' &&
269 Tokens[i].find(':') != StringRef::npos) {
270 PrintError(CGI.TheDef->getLoc(),
271 "instruction with operand modifier '" + Tokens[i].str() +
272 "' not supported by asm matcher. Mark isCodeGenOnly!");
273 throw std::string("ERROR: Invalid instruction");
276 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
278 errs() << "warning: '" << Name << "': "
279 << "ignoring instruction with tied operand '"
280 << Tokens[i].str() << "'\n";
291 struct SubtargetFeatureInfo;
293 /// ClassInfo - Helper class for storing the information about a particular
294 /// class of operands which can be matched.
297 /// Invalid kind, for use as a sentinel value.
300 /// The class for a particular token.
303 /// The (first) register class, subsequent register classes are
304 /// RegisterClass0+1, and so on.
307 /// The (first) user defined class, subsequent user defined classes are
308 /// UserClass0+1, and so on.
312 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
313 /// N) for the Nth user defined class.
316 /// SuperClasses - The super classes of this class. Note that for simplicities
317 /// sake user operands only record their immediate super class, while register
318 /// operands include all superclasses.
319 std::vector<ClassInfo*> SuperClasses;
321 /// Name - The full class name, suitable for use in an enum.
324 /// ClassName - The unadorned generic name for this class (e.g., Token).
325 std::string ClassName;
327 /// ValueName - The name of the value this class represents; for a token this
328 /// is the literal token string, for an operand it is the TableGen class (or
329 /// empty if this is a derived class).
330 std::string ValueName;
332 /// PredicateMethod - The name of the operand method to test whether the
333 /// operand matches this class; this is not valid for Token or register kinds.
334 std::string PredicateMethod;
336 /// RenderMethod - The name of the operand method to add this operand to an
337 /// MCInst; this is not valid for Token or register kinds.
338 std::string RenderMethod;
340 /// For register classes, the records for all the registers in this class.
341 std::set<Record*> Registers;
344 /// isRegisterClass() - Check if this is a register class.
345 bool isRegisterClass() const {
346 return Kind >= RegisterClass0 && Kind < UserClass0;
349 /// isUserClass() - Check if this is a user defined class.
350 bool isUserClass() const {
351 return Kind >= UserClass0;
354 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
355 /// are related if they are in the same class hierarchy.
356 bool isRelatedTo(const ClassInfo &RHS) const {
357 // Tokens are only related to tokens.
358 if (Kind == Token || RHS.Kind == Token)
359 return Kind == Token && RHS.Kind == Token;
361 // Registers classes are only related to registers classes, and only if
362 // their intersection is non-empty.
363 if (isRegisterClass() || RHS.isRegisterClass()) {
364 if (!isRegisterClass() || !RHS.isRegisterClass())
367 std::set<Record*> Tmp;
368 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
369 std::set_intersection(Registers.begin(), Registers.end(),
370 RHS.Registers.begin(), RHS.Registers.end(),
376 // Otherwise we have two users operands; they are related if they are in the
377 // same class hierarchy.
379 // FIXME: This is an oversimplification, they should only be related if they
380 // intersect, however we don't have that information.
381 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
382 const ClassInfo *Root = this;
383 while (!Root->SuperClasses.empty())
384 Root = Root->SuperClasses.front();
386 const ClassInfo *RHSRoot = &RHS;
387 while (!RHSRoot->SuperClasses.empty())
388 RHSRoot = RHSRoot->SuperClasses.front();
390 return Root == RHSRoot;
393 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
394 bool isSubsetOf(const ClassInfo &RHS) const {
395 // This is a subset of RHS if it is the same class...
399 // ... or if any of its super classes are a subset of RHS.
400 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
401 ie = SuperClasses.end(); it != ie; ++it)
402 if ((*it)->isSubsetOf(RHS))
408 /// operator< - Compare two classes.
409 bool operator<(const ClassInfo &RHS) const {
413 // Unrelated classes can be ordered by kind.
414 if (!isRelatedTo(RHS))
415 return Kind < RHS.Kind;
419 assert(0 && "Invalid kind!");
421 // Tokens are comparable by value.
423 // FIXME: Compare by enum value.
424 return ValueName < RHS.ValueName;
427 // This class preceeds the RHS if it is a proper subset of the RHS.
430 if (RHS.isSubsetOf(*this))
433 // Otherwise, order by name to ensure we have a total ordering.
434 return ValueName < RHS.ValueName;
439 /// InstructionInfo - Helper class for storing the necessary information for an
440 /// instruction which is capable of being matched.
441 struct InstructionInfo {
443 /// The unique class instance this operand should match.
446 /// The original operand this corresponds to, if any.
447 const CodeGenInstruction::OperandInfo *OperandInfo;
450 /// InstrName - The target name for this instruction.
451 std::string InstrName;
453 /// Instr - The instruction this matches.
454 const CodeGenInstruction *Instr;
456 /// AsmString - The assembly string for this instruction (with variants
458 std::string AsmString;
460 /// Tokens - The tokenized assembly pattern that this instruction matches.
461 SmallVector<StringRef, 4> Tokens;
463 /// Operands - The operands that this instruction matches.
464 SmallVector<Operand, 4> Operands;
466 /// Predicates - The required subtarget features to match this instruction.
467 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
469 /// ConversionFnKind - The enum value which is passed to the generated
470 /// ConvertToMCInst to convert parsed operands into an MCInst for this
472 std::string ConversionFnKind;
474 /// operator< - Compare two instructions.
475 bool operator<(const InstructionInfo &RHS) const {
476 // The primary comparator is the instruction mnemonic.
477 if (Tokens[0] != RHS.Tokens[0])
478 return Tokens[0] < RHS.Tokens[0];
480 if (Operands.size() != RHS.Operands.size())
481 return Operands.size() < RHS.Operands.size();
483 // Compare lexicographically by operand. The matcher validates that other
484 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
485 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
486 if (*Operands[i].Class < *RHS.Operands[i].Class)
488 if (*RHS.Operands[i].Class < *Operands[i].Class)
495 /// CouldMatchAmiguouslyWith - Check whether this instruction could
496 /// ambiguously match the same set of operands as \arg RHS (without being a
497 /// strictly superior match).
498 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
499 // The number of operands is unambiguous.
500 if (Operands.size() != RHS.Operands.size())
503 // Otherwise, make sure the ordering of the two instructions is unambiguous
504 // by checking that either (a) a token or operand kind discriminates them,
505 // or (b) the ordering among equivalent kinds is consistent.
507 // Tokens and operand kinds are unambiguous (assuming a correct target
509 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
510 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
511 Operands[i].Class->Kind == ClassInfo::Token)
512 if (*Operands[i].Class < *RHS.Operands[i].Class ||
513 *RHS.Operands[i].Class < *Operands[i].Class)
516 // Otherwise, this operand could commute if all operands are equivalent, or
517 // there is a pair of operands that compare less than and a pair that
518 // compare greater than.
519 bool HasLT = false, HasGT = false;
520 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
521 if (*Operands[i].Class < *RHS.Operands[i].Class)
523 if (*RHS.Operands[i].Class < *Operands[i].Class)
527 return !(HasLT ^ HasGT);
534 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
535 /// feature which participates in instruction matching.
536 struct SubtargetFeatureInfo {
537 /// \brief The predicate record for this feature.
540 /// \brief An unique index assigned to represent this feature.
543 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
545 /// \brief The name of the enumerated constant identifying this feature.
546 std::string getEnumName() const {
547 return "Feature_" + TheDef->getName();
551 class AsmMatcherInfo {
553 /// The tablegen AsmParser record.
556 /// The AsmParser "CommentDelimiter" value.
557 std::string CommentDelimiter;
559 /// The AsmParser "RegisterPrefix" value.
560 std::string RegisterPrefix;
562 /// The classes which are needed for matching.
563 std::vector<ClassInfo*> Classes;
565 /// The information on the instruction to match.
566 std::vector<InstructionInfo*> Instructions;
568 /// Map of Register records to their class information.
569 std::map<Record*, ClassInfo*> RegisterClasses;
571 /// Map of Predicate records to their subtarget information.
572 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
575 /// Map of token to class information which has already been constructed.
576 std::map<std::string, ClassInfo*> TokenClasses;
578 /// Map of RegisterClass records to their class information.
579 std::map<Record*, ClassInfo*> RegisterClassClasses;
581 /// Map of AsmOperandClass records to their class information.
582 std::map<Record*, ClassInfo*> AsmOperandClasses;
585 /// getTokenClass - Lookup or create the class for the given token.
586 ClassInfo *getTokenClass(StringRef Token);
588 /// getOperandClass - Lookup or create the class for the given operand.
589 ClassInfo *getOperandClass(StringRef Token,
590 const CodeGenInstruction::OperandInfo &OI);
592 /// BuildRegisterClasses - Build the ClassInfo* instances for register
594 void BuildRegisterClasses(CodeGenTarget &Target,
595 std::set<std::string> &SingletonRegisterNames);
597 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
599 void BuildOperandClasses(CodeGenTarget &Target);
602 AsmMatcherInfo(Record *_AsmParser);
604 /// BuildInfo - Construct the various tables used during matching.
605 void BuildInfo(CodeGenTarget &Target);
607 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
609 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
610 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
611 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
612 SubtargetFeatures.find(Def);
613 return I == SubtargetFeatures.end() ? 0 : I->second;
619 void InstructionInfo::dump() {
620 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
622 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
629 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
630 Operand &Op = Operands[i];
631 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
632 if (Op.Class->Kind == ClassInfo::Token) {
633 errs() << '\"' << Tokens[i] << "\"\n";
637 if (!Op.OperandInfo) {
638 errs() << "(singleton register)\n";
642 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
643 errs() << OI.Name << " " << OI.Rec->getName()
644 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
648 static std::string getEnumNameForToken(StringRef Str) {
651 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
653 case '*': Res += "_STAR_"; break;
654 case '%': Res += "_PCT_"; break;
655 case ':': Res += "_COLON_"; break;
660 Res += "_" + utostr((unsigned) *it) + "_";
667 /// getRegisterRecord - Get the register record for \arg name, or 0.
668 static Record *getRegisterRecord(CodeGenTarget &Target, StringRef Name) {
669 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
670 const CodeGenRegister &Reg = Target.getRegisters()[i];
671 if (Name == Reg.TheDef->getValueAsString("AsmName"))
678 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
679 ClassInfo *&Entry = TokenClasses[Token];
682 Entry = new ClassInfo();
683 Entry->Kind = ClassInfo::Token;
684 Entry->ClassName = "Token";
685 Entry->Name = "MCK_" + getEnumNameForToken(Token);
686 Entry->ValueName = Token;
687 Entry->PredicateMethod = "<invalid>";
688 Entry->RenderMethod = "<invalid>";
689 Classes.push_back(Entry);
696 AsmMatcherInfo::getOperandClass(StringRef Token,
697 const CodeGenInstruction::OperandInfo &OI) {
698 if (OI.Rec->isSubClassOf("RegisterClass")) {
699 ClassInfo *CI = RegisterClassClasses[OI.Rec];
702 PrintError(OI.Rec->getLoc(), "register class has no class info!");
703 throw std::string("ERROR: Missing register class!");
709 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
710 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
711 ClassInfo *CI = AsmOperandClasses[MatchClass];
714 PrintError(OI.Rec->getLoc(), "operand has no match class!");
715 throw std::string("ERROR: Missing match class!");
721 void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target,
722 std::set<std::string>
723 &SingletonRegisterNames) {
724 std::vector<CodeGenRegisterClass> RegisterClasses;
725 std::vector<CodeGenRegister> Registers;
727 RegisterClasses = Target.getRegisterClasses();
728 Registers = Target.getRegisters();
730 // The register sets used for matching.
731 std::set< std::set<Record*> > RegisterSets;
733 // Gather the defined sets.
734 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
735 ie = RegisterClasses.end(); it != ie; ++it)
736 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
737 it->Elements.end()));
739 // Add any required singleton sets.
740 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
741 ie = SingletonRegisterNames.end(); it != ie; ++it)
742 if (Record *Rec = getRegisterRecord(Target, *it))
743 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
745 // Introduce derived sets where necessary (when a register does not determine
746 // a unique register set class), and build the mapping of registers to the set
747 // they should classify to.
748 std::map<Record*, std::set<Record*> > RegisterMap;
749 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
750 ie = Registers.end(); it != ie; ++it) {
751 CodeGenRegister &CGR = *it;
752 // Compute the intersection of all sets containing this register.
753 std::set<Record*> ContainingSet;
755 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
756 ie = RegisterSets.end(); it != ie; ++it) {
757 if (!it->count(CGR.TheDef))
760 if (ContainingSet.empty()) {
763 std::set<Record*> Tmp;
764 std::swap(Tmp, ContainingSet);
765 std::insert_iterator< std::set<Record*> > II(ContainingSet,
766 ContainingSet.begin());
767 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
772 if (!ContainingSet.empty()) {
773 RegisterSets.insert(ContainingSet);
774 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
778 // Construct the register classes.
779 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
781 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
782 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
783 ClassInfo *CI = new ClassInfo();
784 CI->Kind = ClassInfo::RegisterClass0 + Index;
785 CI->ClassName = "Reg" + utostr(Index);
786 CI->Name = "MCK_Reg" + utostr(Index);
788 CI->PredicateMethod = ""; // unused
789 CI->RenderMethod = "addRegOperands";
791 Classes.push_back(CI);
792 RegisterSetClasses.insert(std::make_pair(*it, CI));
795 // Find the superclasses; we could compute only the subgroup lattice edges,
796 // but there isn't really a point.
797 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
798 ie = RegisterSets.end(); it != ie; ++it) {
799 ClassInfo *CI = RegisterSetClasses[*it];
800 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
801 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
803 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
804 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
807 // Name the register classes which correspond to a user defined RegisterClass.
808 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
809 ie = RegisterClasses.end(); it != ie; ++it) {
810 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
811 it->Elements.end())];
812 if (CI->ValueName.empty()) {
813 CI->ClassName = it->getName();
814 CI->Name = "MCK_" + it->getName();
815 CI->ValueName = it->getName();
817 CI->ValueName = CI->ValueName + "," + it->getName();
819 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
822 // Populate the map for individual registers.
823 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
824 ie = RegisterMap.end(); it != ie; ++it)
825 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
827 // Name the register classes which correspond to singleton registers.
828 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
829 ie = SingletonRegisterNames.end(); it != ie; ++it) {
830 if (Record *Rec = getRegisterRecord(Target, *it)) {
831 ClassInfo *CI = this->RegisterClasses[Rec];
832 assert(CI && "Missing singleton register class info!");
834 if (CI->ValueName.empty()) {
835 CI->ClassName = Rec->getName();
836 CI->Name = "MCK_" + Rec->getName();
837 CI->ValueName = Rec->getName();
839 CI->ValueName = CI->ValueName + "," + Rec->getName();
844 void AsmMatcherInfo::BuildOperandClasses(CodeGenTarget &Target) {
845 std::vector<Record*> AsmOperands;
846 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
848 // Pre-populate AsmOperandClasses map.
849 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
850 ie = AsmOperands.end(); it != ie; ++it)
851 AsmOperandClasses[*it] = new ClassInfo();
854 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
855 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
856 ClassInfo *CI = AsmOperandClasses[*it];
857 CI->Kind = ClassInfo::UserClass0 + Index;
859 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
860 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
861 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
863 PrintError((*it)->getLoc(), "Invalid super class reference!");
867 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
869 PrintError((*it)->getLoc(), "Invalid super class reference!");
871 CI->SuperClasses.push_back(SC);
873 CI->ClassName = (*it)->getValueAsString("Name");
874 CI->Name = "MCK_" + CI->ClassName;
875 CI->ValueName = (*it)->getName();
877 // Get or construct the predicate method name.
878 Init *PMName = (*it)->getValueInit("PredicateMethod");
879 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
880 CI->PredicateMethod = SI->getValue();
882 assert(dynamic_cast<UnsetInit*>(PMName) &&
883 "Unexpected PredicateMethod field!");
884 CI->PredicateMethod = "is" + CI->ClassName;
887 // Get or construct the render method name.
888 Init *RMName = (*it)->getValueInit("RenderMethod");
889 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
890 CI->RenderMethod = SI->getValue();
892 assert(dynamic_cast<UnsetInit*>(RMName) &&
893 "Unexpected RenderMethod field!");
894 CI->RenderMethod = "add" + CI->ClassName + "Operands";
897 AsmOperandClasses[*it] = CI;
898 Classes.push_back(CI);
902 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser)
903 : AsmParser(asmParser),
904 CommentDelimiter(AsmParser->getValueAsString("CommentDelimiter")),
905 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix"))
909 void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
910 // Build information about all of the AssemblerPredicates.
911 std::vector<Record*> AllPredicates =
912 Records.getAllDerivedDefinitions("Predicate");
913 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
914 Record *Pred = AllPredicates[i];
915 // Ignore predicates that are not intended for the assembler.
916 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
919 if (Pred->getName().empty()) {
920 PrintError(Pred->getLoc(), "Predicate has no name!");
921 throw std::string("ERROR: Predicate defs must be named");
924 unsigned FeatureNo = SubtargetFeatures.size();
925 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
926 assert(FeatureNo < 32 && "Too many subtarget features!");
929 // Parse the instructions; we need to do this first so that we can gather the
930 // singleton register classes.
931 std::set<std::string> SingletonRegisterNames;
932 const std::vector<const CodeGenInstruction*> &InstrList =
933 Target.getInstructionsByEnumValue();
934 for (unsigned i = 0, e = InstrList.size(); i != e; ++i) {
935 const CodeGenInstruction &CGI = *InstrList[i];
937 // If the tblgen -match-prefix option is specified (for tblgen hackers),
938 // filter the set of instructions we consider.
939 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
942 OwningPtr<InstructionInfo> II(new InstructionInfo());
944 II->InstrName = CGI.TheDef->getName();
946 II->AsmString = FlattenVariants(CGI.AsmString, 0);
948 // Remove comments from the asm string. We know that the asmstring only
950 if (!CommentDelimiter.empty()) {
951 size_t Idx = StringRef(II->AsmString).find(CommentDelimiter);
952 if (Idx != StringRef::npos)
953 II->AsmString = II->AsmString.substr(0, Idx);
956 TokenizeAsmString(II->AsmString, II->Tokens);
958 // Ignore instructions which shouldn't be matched.
959 if (!IsAssemblerInstruction(CGI.TheDef->getName(), CGI, II->Tokens))
962 // Collect singleton registers, if used.
963 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
964 if (!II->Tokens[i].startswith(RegisterPrefix))
967 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
968 Record *Rec = getRegisterRecord(Target, RegName);
971 // If there is no register prefix (i.e. "%" in "%eax"), then this may
972 // be some random non-register token, just ignore it.
973 if (RegisterPrefix.empty())
976 std::string Err = "unable to find register for '" + RegName.str() +
977 "' (which matches register prefix)";
978 throw TGError(CGI.TheDef->getLoc(), Err);
981 SingletonRegisterNames.insert(RegName);
984 // Compute the require features.
985 std::vector<Record*> Predicates =
986 CGI.TheDef->getValueAsListOfDefs("Predicates");
987 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
988 if (SubtargetFeatureInfo *Feature = getSubtargetFeature(Predicates[i]))
989 II->RequiredFeatures.push_back(Feature);
991 Instructions.push_back(II.take());
994 // Build info for the register classes.
995 BuildRegisterClasses(Target, SingletonRegisterNames);
997 // Build info for the user defined assembly operand classes.
998 BuildOperandClasses(Target);
1000 // Build the instruction information.
1001 for (std::vector<InstructionInfo*>::iterator it = Instructions.begin(),
1002 ie = Instructions.end(); it != ie; ++it) {
1003 InstructionInfo *II = *it;
1005 // The first token of the instruction is the mnemonic, which must be a
1007 assert(!II->Tokens.empty() && "Instruction has no tokens?");
1008 StringRef Mnemonic = II->Tokens[0];
1009 assert(Mnemonic[0] != '$' &&
1010 (RegisterPrefix.empty() || !Mnemonic.startswith(RegisterPrefix)));
1012 // Parse the tokens after the mnemonic.
1013 for (unsigned i = 1, e = II->Tokens.size(); i != e; ++i) {
1014 StringRef Token = II->Tokens[i];
1016 // Check for singleton registers.
1017 if (Token.startswith(RegisterPrefix)) {
1018 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
1019 if (Record *RegRecord = getRegisterRecord(Target, RegName)) {
1020 InstructionInfo::Operand Op;
1021 Op.Class = RegisterClasses[RegRecord];
1023 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1024 "Unexpected class for singleton register");
1025 II->Operands.push_back(Op);
1029 if (!RegisterPrefix.empty()) {
1030 std::string Err = "unable to find register for '" + RegName.str() +
1031 "' (which matches register prefix)";
1032 throw TGError(II->Instr->TheDef->getLoc(), Err);
1036 // Check for simple tokens.
1037 if (Token[0] != '$') {
1038 InstructionInfo::Operand Op;
1039 Op.Class = getTokenClass(Token);
1041 II->Operands.push_back(Op);
1045 // Otherwise this is an operand reference.
1046 StringRef OperandName;
1047 if (Token[1] == '{')
1048 OperandName = Token.substr(2, Token.size() - 3);
1050 OperandName = Token.substr(1);
1052 // Map this token to an operand. FIXME: Move elsewhere.
1055 Idx = II->Instr->getOperandNamed(OperandName);
1057 throw std::string("error: unable to find operand: '" +
1058 OperandName.str() + "'");
1061 // FIXME: This is annoying, the named operand may be tied (e.g.,
1062 // XCHG8rm). What we want is the untied operand, which we now have to
1063 // grovel for. Only worry about this for single entry operands, we have to
1064 // clean this up anyway.
1065 const CodeGenInstruction::OperandInfo *OI = &II->Instr->OperandList[Idx];
1066 if (OI->Constraints[0].isTied()) {
1067 unsigned TiedOp = OI->Constraints[0].getTiedOperand();
1069 // The tied operand index is an MIOperand index, find the operand that
1071 for (unsigned i = 0, e = II->Instr->OperandList.size(); i != e; ++i) {
1072 if (II->Instr->OperandList[i].MIOperandNo == TiedOp) {
1073 OI = &II->Instr->OperandList[i];
1078 assert(OI && "Unable to find tied operand target!");
1081 InstructionInfo::Operand Op;
1082 Op.Class = getOperandClass(Token, *OI);
1083 Op.OperandInfo = OI;
1084 II->Operands.push_back(Op);
1088 // Reorder classes so that classes preceed super classes.
1089 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
1092 static std::pair<unsigned, unsigned> *
1093 GetTiedOperandAtIndex(SmallVectorImpl<std::pair<unsigned, unsigned> > &List,
1095 for (unsigned i = 0, e = List.size(); i != e; ++i)
1096 if (Index == List[i].first)
1102 static void EmitConvertToMCInst(CodeGenTarget &Target,
1103 std::vector<InstructionInfo*> &Infos,
1105 // Write the convert function to a separate stream, so we can drop it after
1107 std::string ConvertFnBody;
1108 raw_string_ostream CvtOS(ConvertFnBody);
1110 // Function we have already generated.
1111 std::set<std::string> GeneratedFns;
1113 // Start the unified conversion function.
1115 CvtOS << "static void ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
1116 << "unsigned Opcode,\n"
1117 << " const SmallVectorImpl<MCParsedAsmOperand*"
1118 << "> &Operands) {\n";
1119 CvtOS << " Inst.setOpcode(Opcode);\n";
1120 CvtOS << " switch (Kind) {\n";
1121 CvtOS << " default:\n";
1123 // Start the enum, which we will generate inline.
1125 OS << "// Unified function for converting operants to MCInst instances.\n\n";
1126 OS << "enum ConversionKind {\n";
1128 // TargetOperandClass - This is the target's operand class, like X86Operand.
1129 std::string TargetOperandClass = Target.getName() + "Operand";
1131 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
1132 ie = Infos.end(); it != ie; ++it) {
1133 InstructionInfo &II = **it;
1135 // Order the (class) operands by the order to convert them into an MCInst.
1136 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
1137 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1138 InstructionInfo::Operand &Op = II.Operands[i];
1140 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
1143 // Find any tied operands.
1144 SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands;
1145 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1146 const CodeGenInstruction::OperandInfo &OpInfo = II.Instr->OperandList[i];
1147 for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) {
1148 const CodeGenInstruction::ConstraintInfo &CI = OpInfo.Constraints[j];
1150 TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo + j,
1151 CI.getTiedOperand()));
1155 std::sort(MIOperandList.begin(), MIOperandList.end());
1157 // Compute the total number of operands.
1158 unsigned NumMIOperands = 0;
1159 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1160 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
1161 NumMIOperands = std::max(NumMIOperands,
1162 OI.MIOperandNo + OI.MINumOperands);
1165 // Build the conversion function signature.
1166 std::string Signature = "Convert";
1167 unsigned CurIndex = 0;
1168 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1169 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1170 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
1171 "Duplicate match for instruction operand!");
1173 // Skip operands which weren't matched by anything, this occurs when the
1174 // .td file encodes "implicit" operands as explicit ones.
1176 // FIXME: This should be removed from the MCInst structure.
1177 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1178 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1181 Signature += "__Imp";
1183 Signature += "__Tie" + utostr(Tie->second);
1188 // Registers are always converted the same, don't duplicate the conversion
1189 // function based on them.
1191 // FIXME: We could generalize this based on the render method, if it
1193 if (Op.Class->isRegisterClass())
1196 Signature += Op.Class->ClassName;
1197 Signature += utostr(Op.OperandInfo->MINumOperands);
1198 Signature += "_" + utostr(MIOperandList[i].second);
1200 CurIndex += Op.OperandInfo->MINumOperands;
1203 // Add any trailing implicit operands.
1204 for (; CurIndex != NumMIOperands; ++CurIndex) {
1205 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1208 Signature += "__Imp";
1210 Signature += "__Tie" + utostr(Tie->second);
1213 II.ConversionFnKind = Signature;
1215 // Check if we have already generated this signature.
1216 if (!GeneratedFns.insert(Signature).second)
1219 // If not, emit it now.
1221 // Add to the enum list.
1222 OS << " " << Signature << ",\n";
1224 // And to the convert function.
1225 CvtOS << " case " << Signature << ":\n";
1227 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1228 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1230 // Add the implicit operands.
1231 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1232 // See if this is a tied operand.
1233 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1237 // If not, this is some implicit operand. Just assume it is a register
1239 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1241 // Copy the tied operand.
1242 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1243 CvtOS << " Inst.addOperand(Inst.getOperand("
1244 << Tie->second << "));\n";
1248 CvtOS << " ((" << TargetOperandClass << "*)Operands["
1249 << MIOperandList[i].second
1250 << "+1])->" << Op.Class->RenderMethod
1251 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
1252 CurIndex += Op.OperandInfo->MINumOperands;
1255 // And add trailing implicit operands.
1256 for (; CurIndex != NumMIOperands; ++CurIndex) {
1257 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1261 // If not, this is some implicit operand. Just assume it is a register
1263 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1265 // Copy the tied operand.
1266 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1267 CvtOS << " Inst.addOperand(Inst.getOperand("
1268 << Tie->second << "));\n";
1272 CvtOS << " return;\n";
1275 // Finish the convert function.
1280 // Finish the enum, and drop the convert function after it.
1282 OS << " NumConversionVariants\n";
1288 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1289 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1290 std::vector<ClassInfo*> &Infos,
1292 OS << "namespace {\n\n";
1294 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1295 << "/// instruction matching.\n";
1296 OS << "enum MatchClassKind {\n";
1297 OS << " InvalidMatchClass = 0,\n";
1298 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1299 ie = Infos.end(); it != ie; ++it) {
1300 ClassInfo &CI = **it;
1301 OS << " " << CI.Name << ", // ";
1302 if (CI.Kind == ClassInfo::Token) {
1303 OS << "'" << CI.ValueName << "'\n";
1304 } else if (CI.isRegisterClass()) {
1305 if (!CI.ValueName.empty())
1306 OS << "register class '" << CI.ValueName << "'\n";
1308 OS << "derived register class\n";
1310 OS << "user defined class '" << CI.ValueName << "'\n";
1313 OS << " NumMatchClassKinds\n";
1319 /// EmitClassifyOperand - Emit the function to classify an operand.
1320 static void EmitClassifyOperand(CodeGenTarget &Target,
1321 AsmMatcherInfo &Info,
1323 OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
1324 << " " << Target.getName() << "Operand &Operand = *("
1325 << Target.getName() << "Operand*)GOp;\n";
1328 OS << " if (Operand.isToken())\n";
1329 OS << " return MatchTokenString(Operand.getToken());\n\n";
1331 // Classify registers.
1333 // FIXME: Don't hardcode isReg, getReg.
1334 OS << " if (Operand.isReg()) {\n";
1335 OS << " switch (Operand.getReg()) {\n";
1336 OS << " default: return InvalidMatchClass;\n";
1337 for (std::map<Record*, ClassInfo*>::iterator
1338 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1340 OS << " case " << Target.getName() << "::"
1341 << it->first->getName() << ": return " << it->second->Name << ";\n";
1345 // Classify user defined operands.
1346 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1347 ie = Info.Classes.end(); it != ie; ++it) {
1348 ClassInfo &CI = **it;
1350 if (!CI.isUserClass())
1353 OS << " // '" << CI.ClassName << "' class";
1354 if (!CI.SuperClasses.empty()) {
1355 OS << ", subclass of ";
1356 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1358 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1359 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
1364 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
1366 // Validate subclass relationships.
1367 if (!CI.SuperClasses.empty()) {
1368 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1369 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1370 << "() && \"Invalid class relationship!\");\n";
1373 OS << " return " << CI.Name << ";\n";
1376 OS << " return InvalidMatchClass;\n";
1380 /// EmitIsSubclass - Emit the subclass predicate function.
1381 static void EmitIsSubclass(CodeGenTarget &Target,
1382 std::vector<ClassInfo*> &Infos,
1384 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1385 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1386 OS << " if (A == B)\n";
1387 OS << " return true;\n\n";
1389 OS << " switch (A) {\n";
1390 OS << " default:\n";
1391 OS << " return false;\n";
1392 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1393 ie = Infos.end(); it != ie; ++it) {
1394 ClassInfo &A = **it;
1396 if (A.Kind != ClassInfo::Token) {
1397 std::vector<StringRef> SuperClasses;
1398 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1399 ie = Infos.end(); it != ie; ++it) {
1400 ClassInfo &B = **it;
1402 if (&A != &B && A.isSubsetOf(B))
1403 SuperClasses.push_back(B.Name);
1406 if (SuperClasses.empty())
1409 OS << "\n case " << A.Name << ":\n";
1411 if (SuperClasses.size() == 1) {
1412 OS << " return B == " << SuperClasses.back() << ";\n";
1416 OS << " switch (B) {\n";
1417 OS << " default: return false;\n";
1418 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1419 OS << " case " << SuperClasses[i] << ": return true;\n";
1429 /// EmitMatchTokenString - Emit the function to match a token string to the
1430 /// appropriate match class value.
1431 static void EmitMatchTokenString(CodeGenTarget &Target,
1432 std::vector<ClassInfo*> &Infos,
1434 // Construct the match list.
1435 std::vector<StringMatcher::StringPair> Matches;
1436 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1437 ie = Infos.end(); it != ie; ++it) {
1438 ClassInfo &CI = **it;
1440 if (CI.Kind == ClassInfo::Token)
1441 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1442 "return " + CI.Name + ";"));
1445 OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
1447 StringMatcher("Name", Matches, OS).Emit();
1449 OS << " return InvalidMatchClass;\n";
1453 /// EmitMatchRegisterName - Emit the function to match a string to the target
1454 /// specific register enum.
1455 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1457 // Construct the match list.
1458 std::vector<StringMatcher::StringPair> Matches;
1459 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1460 const CodeGenRegister &Reg = Target.getRegisters()[i];
1461 if (Reg.TheDef->getValueAsString("AsmName").empty())
1464 Matches.push_back(StringMatcher::StringPair(
1465 Reg.TheDef->getValueAsString("AsmName"),
1466 "return " + utostr(i + 1) + ";"));
1469 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
1471 StringMatcher("Name", Matches, OS).Emit();
1473 OS << " return 0;\n";
1477 /// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1479 static void EmitSubtargetFeatureFlagEnumeration(CodeGenTarget &Target,
1480 AsmMatcherInfo &Info,
1482 OS << "// Flags for subtarget features that participate in "
1483 << "instruction matching.\n";
1484 OS << "enum SubtargetFeatureFlag {\n";
1485 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1486 it = Info.SubtargetFeatures.begin(),
1487 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1488 SubtargetFeatureInfo &SFI = *it->second;
1489 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
1491 OS << " Feature_None = 0\n";
1495 /// EmitComputeAvailableFeatures - Emit the function to compute the list of
1496 /// available features given a subtarget.
1497 static void EmitComputeAvailableFeatures(CodeGenTarget &Target,
1498 AsmMatcherInfo &Info,
1500 std::string ClassName =
1501 Info.AsmParser->getValueAsString("AsmParserClassName");
1503 OS << "unsigned " << Target.getName() << ClassName << "::\n"
1504 << "ComputeAvailableFeatures(const " << Target.getName()
1505 << "Subtarget *Subtarget) const {\n";
1506 OS << " unsigned Features = 0;\n";
1507 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1508 it = Info.SubtargetFeatures.begin(),
1509 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1510 SubtargetFeatureInfo &SFI = *it->second;
1511 OS << " if (" << SFI.TheDef->getValueAsString("CondString")
1513 OS << " Features |= " << SFI.getEnumName() << ";\n";
1515 OS << " return Features;\n";
1519 static std::string GetAliasRequiredFeatures(Record *R,
1520 const AsmMatcherInfo &Info) {
1521 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
1523 unsigned NumFeatures = 0;
1524 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
1525 if (SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i])) {
1529 Result += F->getEnumName();
1534 if (NumFeatures > 1)
1535 Result = '(' + Result + ')';
1539 /// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
1540 /// emit a function for them and return true, otherwise return false.
1541 static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
1542 std::vector<Record*> Aliases =
1543 Records.getAllDerivedDefinitions("MnemonicAlias");
1544 if (Aliases.empty()) return false;
1546 OS << "static void ApplyMnemonicAliases(StringRef &Mnemonic, "
1547 "unsigned Features) {\n";
1549 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
1550 // iteration order of the map is stable.
1551 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1553 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1554 Record *R = Aliases[i];
1555 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
1558 // Process each alias a "from" mnemonic at a time, building the code executed
1559 // by the string remapper.
1560 std::vector<StringMatcher::StringPair> Cases;
1561 for (std::map<std::string, std::vector<Record*> >::iterator
1562 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1564 const std::vector<Record*> &ToVec = I->second;
1566 // Loop through each alias and emit code that handles each case. If there
1567 // are two instructions without predicates, emit an error. If there is one,
1569 std::string MatchCode;
1570 int AliasWithNoPredicate = -1;
1572 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1573 Record *R = ToVec[i];
1574 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
1576 // If this unconditionally matches, remember it for later and diagnose
1578 if (FeatureMask.empty()) {
1579 if (AliasWithNoPredicate != -1) {
1580 // We can't have two aliases from the same mnemonic with no predicate.
1581 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1582 "two MnemonicAliases with the same 'from' mnemonic!");
1583 PrintError(R->getLoc(), "this is the other MnemonicAlias.");
1584 throw std::string("ERROR: Invalid MnemonicAlias definitions!");
1587 AliasWithNoPredicate = i;
1591 if (!MatchCode.empty())
1592 MatchCode += "else ";
1593 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1594 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
1597 if (AliasWithNoPredicate != -1) {
1598 Record *R = ToVec[AliasWithNoPredicate];
1599 if (!MatchCode.empty())
1600 MatchCode += "else\n ";
1601 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
1604 MatchCode += "return;";
1606 Cases.push_back(std::make_pair(I->first, MatchCode));
1610 StringMatcher("Mnemonic", Cases, OS).Emit();
1616 void AsmMatcherEmitter::run(raw_ostream &OS) {
1617 CodeGenTarget Target;
1618 Record *AsmParser = Target.getAsmParser();
1619 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1621 // Compute the information on the instructions to match.
1622 AsmMatcherInfo Info(AsmParser);
1623 Info.BuildInfo(Target);
1625 // Sort the instruction table using the partial order on classes. We use
1626 // stable_sort to ensure that ambiguous instructions are still
1627 // deterministically ordered.
1628 std::stable_sort(Info.Instructions.begin(), Info.Instructions.end(),
1629 less_ptr<InstructionInfo>());
1631 DEBUG_WITH_TYPE("instruction_info", {
1632 for (std::vector<InstructionInfo*>::iterator
1633 it = Info.Instructions.begin(), ie = Info.Instructions.end();
1638 // Check for ambiguous instructions.
1639 DEBUG_WITH_TYPE("ambiguous_instrs", {
1640 unsigned NumAmbiguous = 0;
1641 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1642 for (unsigned j = i + 1; j != e; ++j) {
1643 InstructionInfo &A = *Info.Instructions[i];
1644 InstructionInfo &B = *Info.Instructions[j];
1646 if (A.CouldMatchAmiguouslyWith(B)) {
1647 errs() << "warning: ambiguous instruction match:\n";
1649 errs() << "\nis incomparable with:\n";
1657 errs() << "warning: " << NumAmbiguous
1658 << " ambiguous instructions!\n";
1661 // Write the output.
1663 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1665 // Information for the class declaration.
1666 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
1667 OS << "#undef GET_ASSEMBLER_HEADER\n";
1668 OS << " // This should be included into the middle of the declaration of \n";
1669 OS << " // your subclasses implementation of TargetAsmParser.\n";
1670 OS << " unsigned ComputeAvailableFeatures(const " <<
1671 Target.getName() << "Subtarget *Subtarget) const;\n";
1672 OS << " enum MatchResultTy {\n";
1673 OS << " Match_Success, Match_MnemonicFail, Match_InvalidOperand,\n";
1674 OS << " Match_MissingFeature\n";
1676 OS << " MatchResultTy MatchInstructionImpl(const "
1677 << "SmallVectorImpl<MCParsedAsmOperand*>"
1678 << " &Operands, MCInst &Inst, unsigned &ErrorInfo);\n\n";
1679 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
1684 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
1685 OS << "#undef GET_REGISTER_MATCHER\n\n";
1687 // Emit the subtarget feature enumeration.
1688 EmitSubtargetFeatureFlagEnumeration(Target, Info, OS);
1690 // Emit the function to match a register name to number.
1691 EmitMatchRegisterName(Target, AsmParser, OS);
1693 OS << "#endif // GET_REGISTER_MATCHER\n\n";
1696 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
1697 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
1699 // Generate the function that remaps for mnemonic aliases.
1700 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
1702 // Generate the unified function to convert operands into an MCInst.
1703 EmitConvertToMCInst(Target, Info.Instructions, OS);
1705 // Emit the enumeration for classes which participate in matching.
1706 EmitMatchClassEnumeration(Target, Info.Classes, OS);
1708 // Emit the routine to match token strings to their match class.
1709 EmitMatchTokenString(Target, Info.Classes, OS);
1711 // Emit the routine to classify an operand.
1712 EmitClassifyOperand(Target, Info, OS);
1714 // Emit the subclass predicate routine.
1715 EmitIsSubclass(Target, Info.Classes, OS);
1717 // Emit the available features compute function.
1718 EmitComputeAvailableFeatures(Target, Info, OS);
1721 size_t MaxNumOperands = 0;
1722 for (std::vector<InstructionInfo*>::const_iterator it =
1723 Info.Instructions.begin(), ie = Info.Instructions.end();
1725 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1728 // Emit the static match table; unused classes get initalized to 0 which is
1729 // guaranteed to be InvalidMatchClass.
1731 // FIXME: We can reduce the size of this table very easily. First, we change
1732 // it so that store the kinds in separate bit-fields for each index, which
1733 // only needs to be the max width used for classes at that index (we also need
1734 // to reject based on this during classification). If we then make sure to
1735 // order the match kinds appropriately (putting mnemonics last), then we
1736 // should only end up using a few bits for each class, especially the ones
1737 // following the mnemonic.
1738 OS << "namespace {\n";
1739 OS << " struct MatchEntry {\n";
1740 OS << " unsigned Opcode;\n";
1741 OS << " const char *Mnemonic;\n";
1742 OS << " ConversionKind ConvertFn;\n";
1743 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1744 OS << " unsigned RequiredFeatures;\n";
1747 OS << "// Predicate for searching for an opcode.\n";
1748 OS << " struct LessOpcode {\n";
1749 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
1750 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
1752 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
1753 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
1755 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
1756 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
1760 OS << "} // end anonymous namespace.\n\n";
1762 OS << "static const MatchEntry MatchTable["
1763 << Info.Instructions.size() << "] = {\n";
1765 for (std::vector<InstructionInfo*>::const_iterator it =
1766 Info.Instructions.begin(), ie = Info.Instructions.end();
1768 InstructionInfo &II = **it;
1770 OS << " { " << Target.getName() << "::" << II.InstrName
1771 << ", \"" << II.Tokens[0] << "\""
1772 << ", " << II.ConversionFnKind << ", { ";
1773 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1774 InstructionInfo::Operand &Op = II.Operands[i];
1777 OS << Op.Class->Name;
1781 // Write the required features mask.
1782 if (!II.RequiredFeatures.empty()) {
1783 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
1785 OS << II.RequiredFeatures[i]->getEnumName();
1795 // Finally, build the match function.
1796 OS << Target.getName() << ClassName << "::MatchResultTy "
1797 << Target.getName() << ClassName << "::\n"
1798 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
1800 OS << " MCInst &Inst, unsigned &ErrorInfo) {\n";
1802 // Emit code to get the available features.
1803 OS << " // Get the current feature set.\n";
1804 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
1806 OS << " // Get the instruction mnemonic, which is the first token.\n";
1807 OS << " StringRef Mnemonic = ((" << Target.getName()
1808 << "Operand*)Operands[0])->getToken();\n\n";
1810 if (HasMnemonicAliases) {
1811 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
1812 OS << " ApplyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
1815 // Emit code to compute the class list for this operand vector.
1816 OS << " // Eliminate obvious mismatches.\n";
1817 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
1818 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
1819 OS << " return Match_InvalidOperand;\n";
1822 OS << " // Compute the class list for this operand vector.\n";
1823 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1824 OS << " for (unsigned i = 1, e = Operands.size(); i != e; ++i) {\n";
1825 OS << " Classes[i-1] = ClassifyOperand(Operands[i]);\n\n";
1827 OS << " // Check for invalid operands before matching.\n";
1828 OS << " if (Classes[i-1] == InvalidMatchClass) {\n";
1829 OS << " ErrorInfo = i;\n";
1830 OS << " return Match_InvalidOperand;\n";
1834 OS << " // Mark unused classes.\n";
1835 OS << " for (unsigned i = Operands.size()-1, e = " << MaxNumOperands << "; "
1836 << "i != e; ++i)\n";
1837 OS << " Classes[i] = InvalidMatchClass;\n\n";
1839 OS << " // Some state to try to produce better error messages.\n";
1840 OS << " bool HadMatchOtherThanFeatures = false;\n\n";
1841 OS << " // Set ErrorInfo to the operand that mismatches if it is \n";
1842 OS << " // wrong for all instances of the instruction.\n";
1843 OS << " ErrorInfo = ~0U;\n";
1845 // Emit code to search the table.
1846 OS << " // Search the table.\n";
1847 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
1848 OS << " std::equal_range(MatchTable, MatchTable+"
1849 << Info.Instructions.size() << ", Mnemonic, LessOpcode());\n\n";
1851 OS << " // Return a more specific error code if no mnemonics match.\n";
1852 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
1853 OS << " return Match_MnemonicFail;\n\n";
1855 OS << " for (const MatchEntry *it = MnemonicRange.first, "
1856 << "*ie = MnemonicRange.second;\n";
1857 OS << " it != ie; ++it) {\n";
1859 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
1860 OS << " assert(Mnemonic == it->Mnemonic);\n";
1862 // Emit check that the subclasses match.
1863 OS << " bool OperandsValid = true;\n";
1864 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
1865 OS << " if (IsSubclass(Classes[i], it->Classes[i]))\n";
1866 OS << " continue;\n";
1867 OS << " // If this operand is broken for all of the instances of this\n";
1868 OS << " // mnemonic, keep track of it so we can report loc info.\n";
1869 OS << " if (it == MnemonicRange.first || ErrorInfo == i+1)\n";
1870 OS << " ErrorInfo = i+1;\n";
1872 OS << " ErrorInfo = ~0U;";
1873 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
1874 OS << " OperandsValid = false;\n";
1878 OS << " if (!OperandsValid) continue;\n";
1880 // Emit check that the required features are available.
1881 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
1882 << "!= it->RequiredFeatures) {\n";
1883 OS << " HadMatchOtherThanFeatures = true;\n";
1884 OS << " continue;\n";
1888 OS << " ConvertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
1890 // Call the post-processing function, if used.
1891 std::string InsnCleanupFn =
1892 AsmParser->getValueAsString("AsmParserInstCleanup");
1893 if (!InsnCleanupFn.empty())
1894 OS << " " << InsnCleanupFn << "(Inst);\n";
1896 OS << " return Match_Success;\n";
1899 OS << " // Okay, we had no match. Try to return a useful error code.\n";
1900 OS << " if (HadMatchOtherThanFeatures) return Match_MissingFeature;\n";
1901 OS << " return Match_InvalidOperand;\n";
1904 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";