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 "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 // Reject instructions with no .s string.
233 if (CGI.AsmString.empty()) {
234 PrintError(CGI.TheDef->getLoc(),
235 "instruction with empty asm string");
236 throw std::string("ERROR: Invalid instruction for asm matcher");
239 // Reject any instructions with a newline in them, they should be marked
240 // isCodeGenOnly if they are pseudo instructions.
241 if (CGI.AsmString.find('\n') != std::string::npos) {
242 PrintError(CGI.TheDef->getLoc(),
243 "multiline instruction is not valid for the asmparser, "
244 "mark it isCodeGenOnly");
245 throw std::string("ERROR: Invalid instruction");
248 // Reject instructions with attributes, these aren't something we can handle,
249 // the target should be refactored to use operands instead of modifiers.
251 // Also, check for instructions which reference the operand multiple times;
252 // this implies a constraint we would not honor.
253 std::set<std::string> OperandNames;
254 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
255 if (Tokens[i][0] == '$' &&
256 Tokens[i].find(':') != StringRef::npos) {
257 PrintError(CGI.TheDef->getLoc(),
258 "instruction with operand modifier '" + Tokens[i].str() +
259 "' not supported by asm matcher. Mark isCodeGenOnly!");
260 throw std::string("ERROR: Invalid instruction");
263 // FIXME: Should reject these.
264 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
266 errs() << "warning: '" << Name << "': "
267 << "ignoring instruction with tied operand '"
268 << Tokens[i].str() << "'\n";
279 struct SubtargetFeatureInfo;
281 /// ClassInfo - Helper class for storing the information about a particular
282 /// class of operands which can be matched.
285 /// Invalid kind, for use as a sentinel value.
288 /// The class for a particular token.
291 /// The (first) register class, subsequent register classes are
292 /// RegisterClass0+1, and so on.
295 /// The (first) user defined class, subsequent user defined classes are
296 /// UserClass0+1, and so on.
300 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
301 /// N) for the Nth user defined class.
304 /// SuperClasses - The super classes of this class. Note that for simplicities
305 /// sake user operands only record their immediate super class, while register
306 /// operands include all superclasses.
307 std::vector<ClassInfo*> SuperClasses;
309 /// Name - The full class name, suitable for use in an enum.
312 /// ClassName - The unadorned generic name for this class (e.g., Token).
313 std::string ClassName;
315 /// ValueName - The name of the value this class represents; for a token this
316 /// is the literal token string, for an operand it is the TableGen class (or
317 /// empty if this is a derived class).
318 std::string ValueName;
320 /// PredicateMethod - The name of the operand method to test whether the
321 /// operand matches this class; this is not valid for Token or register kinds.
322 std::string PredicateMethod;
324 /// RenderMethod - The name of the operand method to add this operand to an
325 /// MCInst; this is not valid for Token or register kinds.
326 std::string RenderMethod;
328 /// For register classes, the records for all the registers in this class.
329 std::set<Record*> Registers;
332 /// isRegisterClass() - Check if this is a register class.
333 bool isRegisterClass() const {
334 return Kind >= RegisterClass0 && Kind < UserClass0;
337 /// isUserClass() - Check if this is a user defined class.
338 bool isUserClass() const {
339 return Kind >= UserClass0;
342 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
343 /// are related if they are in the same class hierarchy.
344 bool isRelatedTo(const ClassInfo &RHS) const {
345 // Tokens are only related to tokens.
346 if (Kind == Token || RHS.Kind == Token)
347 return Kind == Token && RHS.Kind == Token;
349 // Registers classes are only related to registers classes, and only if
350 // their intersection is non-empty.
351 if (isRegisterClass() || RHS.isRegisterClass()) {
352 if (!isRegisterClass() || !RHS.isRegisterClass())
355 std::set<Record*> Tmp;
356 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
357 std::set_intersection(Registers.begin(), Registers.end(),
358 RHS.Registers.begin(), RHS.Registers.end(),
364 // Otherwise we have two users operands; they are related if they are in the
365 // same class hierarchy.
367 // FIXME: This is an oversimplification, they should only be related if they
368 // intersect, however we don't have that information.
369 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
370 const ClassInfo *Root = this;
371 while (!Root->SuperClasses.empty())
372 Root = Root->SuperClasses.front();
374 const ClassInfo *RHSRoot = &RHS;
375 while (!RHSRoot->SuperClasses.empty())
376 RHSRoot = RHSRoot->SuperClasses.front();
378 return Root == RHSRoot;
381 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
382 bool isSubsetOf(const ClassInfo &RHS) const {
383 // This is a subset of RHS if it is the same class...
387 // ... or if any of its super classes are a subset of RHS.
388 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
389 ie = SuperClasses.end(); it != ie; ++it)
390 if ((*it)->isSubsetOf(RHS))
396 /// operator< - Compare two classes.
397 bool operator<(const ClassInfo &RHS) const {
401 // Unrelated classes can be ordered by kind.
402 if (!isRelatedTo(RHS))
403 return Kind < RHS.Kind;
407 assert(0 && "Invalid kind!");
409 // Tokens are comparable by value.
411 // FIXME: Compare by enum value.
412 return ValueName < RHS.ValueName;
415 // This class preceeds the RHS if it is a proper subset of the RHS.
418 if (RHS.isSubsetOf(*this))
421 // Otherwise, order by name to ensure we have a total ordering.
422 return ValueName < RHS.ValueName;
427 /// InstructionInfo - Helper class for storing the necessary information for an
428 /// instruction which is capable of being matched.
429 struct InstructionInfo {
431 /// The unique class instance this operand should match.
434 /// The original operand this corresponds to, if any.
435 const CodeGenInstruction::OperandInfo *OperandInfo;
438 /// InstrName - The target name for this instruction.
439 std::string InstrName;
441 /// Instr - The instruction this matches.
442 const CodeGenInstruction *Instr;
444 /// AsmString - The assembly string for this instruction (with variants
446 std::string AsmString;
448 /// Tokens - The tokenized assembly pattern that this instruction matches.
449 SmallVector<StringRef, 4> Tokens;
451 /// Operands - The operands that this instruction matches.
452 SmallVector<Operand, 4> Operands;
454 /// Predicates - The required subtarget features to match this instruction.
455 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
457 /// ConversionFnKind - The enum value which is passed to the generated
458 /// ConvertToMCInst to convert parsed operands into an MCInst for this
460 std::string ConversionFnKind;
462 /// operator< - Compare two instructions.
463 bool operator<(const InstructionInfo &RHS) const {
464 // The primary comparator is the instruction mnemonic.
465 if (Tokens[0] != RHS.Tokens[0])
466 return Tokens[0] < RHS.Tokens[0];
468 if (Operands.size() != RHS.Operands.size())
469 return Operands.size() < RHS.Operands.size();
471 // Compare lexicographically by operand. The matcher validates that other
472 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
473 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
474 if (*Operands[i].Class < *RHS.Operands[i].Class)
476 if (*RHS.Operands[i].Class < *Operands[i].Class)
483 /// CouldMatchAmiguouslyWith - Check whether this instruction could
484 /// ambiguously match the same set of operands as \arg RHS (without being a
485 /// strictly superior match).
486 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
487 // The number of operands is unambiguous.
488 if (Operands.size() != RHS.Operands.size())
491 // Otherwise, make sure the ordering of the two instructions is unambiguous
492 // by checking that either (a) a token or operand kind discriminates them,
493 // or (b) the ordering among equivalent kinds is consistent.
495 // Tokens and operand kinds are unambiguous (assuming a correct target
497 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
498 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
499 Operands[i].Class->Kind == ClassInfo::Token)
500 if (*Operands[i].Class < *RHS.Operands[i].Class ||
501 *RHS.Operands[i].Class < *Operands[i].Class)
504 // Otherwise, this operand could commute if all operands are equivalent, or
505 // there is a pair of operands that compare less than and a pair that
506 // compare greater than.
507 bool HasLT = false, HasGT = false;
508 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
509 if (*Operands[i].Class < *RHS.Operands[i].Class)
511 if (*RHS.Operands[i].Class < *Operands[i].Class)
515 return !(HasLT ^ HasGT);
522 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
523 /// feature which participates in instruction matching.
524 struct SubtargetFeatureInfo {
525 /// \brief The predicate record for this feature.
528 /// \brief An unique index assigned to represent this feature.
531 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
533 /// \brief The name of the enumerated constant identifying this feature.
534 std::string getEnumName() const {
535 return "Feature_" + TheDef->getName();
539 class AsmMatcherInfo {
541 /// The tablegen AsmParser record.
544 /// The AsmParser "CommentDelimiter" value.
545 std::string CommentDelimiter;
547 /// The AsmParser "RegisterPrefix" value.
548 std::string RegisterPrefix;
550 /// The classes which are needed for matching.
551 std::vector<ClassInfo*> Classes;
553 /// The information on the instruction to match.
554 std::vector<InstructionInfo*> Instructions;
556 /// Map of Register records to their class information.
557 std::map<Record*, ClassInfo*> RegisterClasses;
559 /// Map of Predicate records to their subtarget information.
560 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
563 /// Map of token to class information which has already been constructed.
564 std::map<std::string, ClassInfo*> TokenClasses;
566 /// Map of RegisterClass records to their class information.
567 std::map<Record*, ClassInfo*> RegisterClassClasses;
569 /// Map of AsmOperandClass records to their class information.
570 std::map<Record*, ClassInfo*> AsmOperandClasses;
573 /// getTokenClass - Lookup or create the class for the given token.
574 ClassInfo *getTokenClass(StringRef Token);
576 /// getOperandClass - Lookup or create the class for the given operand.
577 ClassInfo *getOperandClass(StringRef Token,
578 const CodeGenInstruction::OperandInfo &OI);
580 /// BuildRegisterClasses - Build the ClassInfo* instances for register
582 void BuildRegisterClasses(CodeGenTarget &Target,
583 std::set<std::string> &SingletonRegisterNames);
585 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
587 void BuildOperandClasses(CodeGenTarget &Target);
590 AsmMatcherInfo(Record *_AsmParser);
592 /// BuildInfo - Construct the various tables used during matching.
593 void BuildInfo(CodeGenTarget &Target);
595 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
597 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
598 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
599 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
600 SubtargetFeatures.find(Def);
601 return I == SubtargetFeatures.end() ? 0 : I->second;
607 void InstructionInfo::dump() {
608 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
610 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
617 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
618 Operand &Op = Operands[i];
619 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
620 if (Op.Class->Kind == ClassInfo::Token) {
621 errs() << '\"' << Tokens[i] << "\"\n";
625 if (!Op.OperandInfo) {
626 errs() << "(singleton register)\n";
630 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
631 errs() << OI.Name << " " << OI.Rec->getName()
632 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
636 static std::string getEnumNameForToken(StringRef Str) {
639 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
641 case '*': Res += "_STAR_"; break;
642 case '%': Res += "_PCT_"; break;
643 case ':': Res += "_COLON_"; break;
648 Res += "_" + utostr((unsigned) *it) + "_";
655 /// getRegisterRecord - Get the register record for \arg name, or 0.
656 static Record *getRegisterRecord(CodeGenTarget &Target, StringRef Name) {
657 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
658 const CodeGenRegister &Reg = Target.getRegisters()[i];
659 if (Name == Reg.TheDef->getValueAsString("AsmName"))
666 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
667 ClassInfo *&Entry = TokenClasses[Token];
670 Entry = new ClassInfo();
671 Entry->Kind = ClassInfo::Token;
672 Entry->ClassName = "Token";
673 Entry->Name = "MCK_" + getEnumNameForToken(Token);
674 Entry->ValueName = Token;
675 Entry->PredicateMethod = "<invalid>";
676 Entry->RenderMethod = "<invalid>";
677 Classes.push_back(Entry);
684 AsmMatcherInfo::getOperandClass(StringRef Token,
685 const CodeGenInstruction::OperandInfo &OI) {
686 if (OI.Rec->isSubClassOf("RegisterClass")) {
687 ClassInfo *CI = RegisterClassClasses[OI.Rec];
690 PrintError(OI.Rec->getLoc(), "register class has no class info!");
691 throw std::string("ERROR: Missing register class!");
697 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
698 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
699 ClassInfo *CI = AsmOperandClasses[MatchClass];
702 PrintError(OI.Rec->getLoc(), "operand has no match class!");
703 throw std::string("ERROR: Missing match class!");
709 void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target,
710 std::set<std::string>
711 &SingletonRegisterNames) {
712 std::vector<CodeGenRegisterClass> RegisterClasses;
713 std::vector<CodeGenRegister> Registers;
715 RegisterClasses = Target.getRegisterClasses();
716 Registers = Target.getRegisters();
718 // The register sets used for matching.
719 std::set< std::set<Record*> > RegisterSets;
721 // Gather the defined sets.
722 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
723 ie = RegisterClasses.end(); it != ie; ++it)
724 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
725 it->Elements.end()));
727 // Add any required singleton sets.
728 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
729 ie = SingletonRegisterNames.end(); it != ie; ++it)
730 if (Record *Rec = getRegisterRecord(Target, *it))
731 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
733 // Introduce derived sets where necessary (when a register does not determine
734 // a unique register set class), and build the mapping of registers to the set
735 // they should classify to.
736 std::map<Record*, std::set<Record*> > RegisterMap;
737 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
738 ie = Registers.end(); it != ie; ++it) {
739 CodeGenRegister &CGR = *it;
740 // Compute the intersection of all sets containing this register.
741 std::set<Record*> ContainingSet;
743 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
744 ie = RegisterSets.end(); it != ie; ++it) {
745 if (!it->count(CGR.TheDef))
748 if (ContainingSet.empty()) {
751 std::set<Record*> Tmp;
752 std::swap(Tmp, ContainingSet);
753 std::insert_iterator< std::set<Record*> > II(ContainingSet,
754 ContainingSet.begin());
755 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
760 if (!ContainingSet.empty()) {
761 RegisterSets.insert(ContainingSet);
762 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
766 // Construct the register classes.
767 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
769 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
770 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
771 ClassInfo *CI = new ClassInfo();
772 CI->Kind = ClassInfo::RegisterClass0 + Index;
773 CI->ClassName = "Reg" + utostr(Index);
774 CI->Name = "MCK_Reg" + utostr(Index);
776 CI->PredicateMethod = ""; // unused
777 CI->RenderMethod = "addRegOperands";
779 Classes.push_back(CI);
780 RegisterSetClasses.insert(std::make_pair(*it, CI));
783 // Find the superclasses; we could compute only the subgroup lattice edges,
784 // but there isn't really a point.
785 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
786 ie = RegisterSets.end(); it != ie; ++it) {
787 ClassInfo *CI = RegisterSetClasses[*it];
788 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
789 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
791 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
792 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
795 // Name the register classes which correspond to a user defined RegisterClass.
796 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
797 ie = RegisterClasses.end(); it != ie; ++it) {
798 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
799 it->Elements.end())];
800 if (CI->ValueName.empty()) {
801 CI->ClassName = it->getName();
802 CI->Name = "MCK_" + it->getName();
803 CI->ValueName = it->getName();
805 CI->ValueName = CI->ValueName + "," + it->getName();
807 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
810 // Populate the map for individual registers.
811 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
812 ie = RegisterMap.end(); it != ie; ++it)
813 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
815 // Name the register classes which correspond to singleton registers.
816 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
817 ie = SingletonRegisterNames.end(); it != ie; ++it) {
818 if (Record *Rec = getRegisterRecord(Target, *it)) {
819 ClassInfo *CI = this->RegisterClasses[Rec];
820 assert(CI && "Missing singleton register class info!");
822 if (CI->ValueName.empty()) {
823 CI->ClassName = Rec->getName();
824 CI->Name = "MCK_" + Rec->getName();
825 CI->ValueName = Rec->getName();
827 CI->ValueName = CI->ValueName + "," + Rec->getName();
832 void AsmMatcherInfo::BuildOperandClasses(CodeGenTarget &Target) {
833 std::vector<Record*> AsmOperands;
834 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
836 // Pre-populate AsmOperandClasses map.
837 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
838 ie = AsmOperands.end(); it != ie; ++it)
839 AsmOperandClasses[*it] = new ClassInfo();
842 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
843 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
844 ClassInfo *CI = AsmOperandClasses[*it];
845 CI->Kind = ClassInfo::UserClass0 + Index;
847 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
848 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
849 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
851 PrintError((*it)->getLoc(), "Invalid super class reference!");
855 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
857 PrintError((*it)->getLoc(), "Invalid super class reference!");
859 CI->SuperClasses.push_back(SC);
861 CI->ClassName = (*it)->getValueAsString("Name");
862 CI->Name = "MCK_" + CI->ClassName;
863 CI->ValueName = (*it)->getName();
865 // Get or construct the predicate method name.
866 Init *PMName = (*it)->getValueInit("PredicateMethod");
867 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
868 CI->PredicateMethod = SI->getValue();
870 assert(dynamic_cast<UnsetInit*>(PMName) &&
871 "Unexpected PredicateMethod field!");
872 CI->PredicateMethod = "is" + CI->ClassName;
875 // Get or construct the render method name.
876 Init *RMName = (*it)->getValueInit("RenderMethod");
877 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
878 CI->RenderMethod = SI->getValue();
880 assert(dynamic_cast<UnsetInit*>(RMName) &&
881 "Unexpected RenderMethod field!");
882 CI->RenderMethod = "add" + CI->ClassName + "Operands";
885 AsmOperandClasses[*it] = CI;
886 Classes.push_back(CI);
890 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser)
891 : AsmParser(asmParser),
892 CommentDelimiter(AsmParser->getValueAsString("CommentDelimiter")),
893 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix"))
897 void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
898 // Build information about all of the AssemblerPredicates.
899 std::vector<Record*> AllPredicates =
900 Records.getAllDerivedDefinitions("Predicate");
901 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
902 Record *Pred = AllPredicates[i];
903 // Ignore predicates that are not intended for the assembler.
904 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
907 if (Pred->getName().empty()) {
908 PrintError(Pred->getLoc(), "Predicate has no name!");
909 throw std::string("ERROR: Predicate defs must be named");
912 unsigned FeatureNo = SubtargetFeatures.size();
913 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
914 assert(FeatureNo < 32 && "Too many subtarget features!");
917 // Parse the instructions; we need to do this first so that we can gather the
918 // singleton register classes.
919 std::set<std::string> SingletonRegisterNames;
920 const std::vector<const CodeGenInstruction*> &InstrList =
921 Target.getInstructionsByEnumValue();
922 for (unsigned i = 0, e = InstrList.size(); i != e; ++i) {
923 const CodeGenInstruction &CGI = *InstrList[i];
925 // If the tblgen -match-prefix option is specified (for tblgen hackers),
926 // filter the set of instructions we consider.
927 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
930 OwningPtr<InstructionInfo> II(new InstructionInfo());
932 II->InstrName = CGI.TheDef->getName();
934 II->AsmString = FlattenVariants(CGI.AsmString, 0);
936 // Remove comments from the asm string. We know that the asmstring only
938 if (!CommentDelimiter.empty()) {
939 size_t Idx = StringRef(II->AsmString).find(CommentDelimiter);
940 if (Idx != StringRef::npos)
941 II->AsmString = II->AsmString.substr(0, Idx);
944 TokenizeAsmString(II->AsmString, II->Tokens);
946 // Ignore instructions which shouldn't be matched.
947 if (!IsAssemblerInstruction(CGI.TheDef->getName(), CGI, II->Tokens))
950 // Collect singleton registers, if used.
951 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
952 if (!II->Tokens[i].startswith(RegisterPrefix))
955 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
956 Record *Rec = getRegisterRecord(Target, RegName);
959 // If there is no register prefix (i.e. "%" in "%eax"), then this may
960 // be some random non-register token, just ignore it.
961 if (RegisterPrefix.empty())
964 std::string Err = "unable to find register for '" + RegName.str() +
965 "' (which matches register prefix)";
966 throw TGError(CGI.TheDef->getLoc(), Err);
969 SingletonRegisterNames.insert(RegName);
972 // Compute the require features.
973 std::vector<Record*> Predicates =
974 CGI.TheDef->getValueAsListOfDefs("Predicates");
975 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
976 if (SubtargetFeatureInfo *Feature = getSubtargetFeature(Predicates[i]))
977 II->RequiredFeatures.push_back(Feature);
979 Instructions.push_back(II.take());
982 // Build info for the register classes.
983 BuildRegisterClasses(Target, SingletonRegisterNames);
985 // Build info for the user defined assembly operand classes.
986 BuildOperandClasses(Target);
988 // Build the instruction information.
989 for (std::vector<InstructionInfo*>::iterator it = Instructions.begin(),
990 ie = Instructions.end(); it != ie; ++it) {
991 InstructionInfo *II = *it;
993 // The first token of the instruction is the mnemonic, which must be a
995 assert(!II->Tokens.empty() && "Instruction has no tokens?");
996 StringRef Mnemonic = II->Tokens[0];
997 assert(Mnemonic[0] != '$' &&
998 (RegisterPrefix.empty() || !Mnemonic.startswith(RegisterPrefix)));
1000 // Parse the tokens after the mnemonic.
1001 for (unsigned i = 1, e = II->Tokens.size(); i != e; ++i) {
1002 StringRef Token = II->Tokens[i];
1004 // Check for singleton registers.
1005 if (Token.startswith(RegisterPrefix)) {
1006 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
1007 if (Record *RegRecord = getRegisterRecord(Target, RegName)) {
1008 InstructionInfo::Operand Op;
1009 Op.Class = RegisterClasses[RegRecord];
1011 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1012 "Unexpected class for singleton register");
1013 II->Operands.push_back(Op);
1017 if (!RegisterPrefix.empty()) {
1018 std::string Err = "unable to find register for '" + RegName.str() +
1019 "' (which matches register prefix)";
1020 throw TGError(II->Instr->TheDef->getLoc(), Err);
1024 // Check for simple tokens.
1025 if (Token[0] != '$') {
1026 InstructionInfo::Operand Op;
1027 Op.Class = getTokenClass(Token);
1029 II->Operands.push_back(Op);
1033 // Otherwise this is an operand reference.
1034 StringRef OperandName;
1035 if (Token[1] == '{')
1036 OperandName = Token.substr(2, Token.size() - 3);
1038 OperandName = Token.substr(1);
1040 // Map this token to an operand. FIXME: Move elsewhere.
1043 Idx = II->Instr->getOperandNamed(OperandName);
1045 throw std::string("error: unable to find operand: '" +
1046 OperandName.str() + "'");
1049 // FIXME: This is annoying, the named operand may be tied (e.g.,
1050 // XCHG8rm). What we want is the untied operand, which we now have to
1051 // grovel for. Only worry about this for single entry operands, we have to
1052 // clean this up anyway.
1053 const CodeGenInstruction::OperandInfo *OI = &II->Instr->OperandList[Idx];
1054 if (OI->Constraints[0].isTied()) {
1055 unsigned TiedOp = OI->Constraints[0].getTiedOperand();
1057 // The tied operand index is an MIOperand index, find the operand that
1059 for (unsigned i = 0, e = II->Instr->OperandList.size(); i != e; ++i) {
1060 if (II->Instr->OperandList[i].MIOperandNo == TiedOp) {
1061 OI = &II->Instr->OperandList[i];
1066 assert(OI && "Unable to find tied operand target!");
1069 InstructionInfo::Operand Op;
1070 Op.Class = getOperandClass(Token, *OI);
1071 Op.OperandInfo = OI;
1072 II->Operands.push_back(Op);
1076 // Reorder classes so that classes preceed super classes.
1077 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
1080 static std::pair<unsigned, unsigned> *
1081 GetTiedOperandAtIndex(SmallVectorImpl<std::pair<unsigned, unsigned> > &List,
1083 for (unsigned i = 0, e = List.size(); i != e; ++i)
1084 if (Index == List[i].first)
1090 static void EmitConvertToMCInst(CodeGenTarget &Target,
1091 std::vector<InstructionInfo*> &Infos,
1093 // Write the convert function to a separate stream, so we can drop it after
1095 std::string ConvertFnBody;
1096 raw_string_ostream CvtOS(ConvertFnBody);
1098 // Function we have already generated.
1099 std::set<std::string> GeneratedFns;
1101 // Start the unified conversion function.
1103 CvtOS << "static void ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
1104 << "unsigned Opcode,\n"
1105 << " const SmallVectorImpl<MCParsedAsmOperand*"
1106 << "> &Operands) {\n";
1107 CvtOS << " Inst.setOpcode(Opcode);\n";
1108 CvtOS << " switch (Kind) {\n";
1109 CvtOS << " default:\n";
1111 // Start the enum, which we will generate inline.
1113 OS << "// Unified function for converting operants to MCInst instances.\n\n";
1114 OS << "enum ConversionKind {\n";
1116 // TargetOperandClass - This is the target's operand class, like X86Operand.
1117 std::string TargetOperandClass = Target.getName() + "Operand";
1119 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
1120 ie = Infos.end(); it != ie; ++it) {
1121 InstructionInfo &II = **it;
1123 // Order the (class) operands by the order to convert them into an MCInst.
1124 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
1125 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1126 InstructionInfo::Operand &Op = II.Operands[i];
1128 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
1131 // Find any tied operands.
1132 SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands;
1133 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1134 const CodeGenInstruction::OperandInfo &OpInfo = II.Instr->OperandList[i];
1135 for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) {
1136 const CodeGenInstruction::ConstraintInfo &CI = OpInfo.Constraints[j];
1138 TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo + j,
1139 CI.getTiedOperand()));
1143 std::sort(MIOperandList.begin(), MIOperandList.end());
1145 // Compute the total number of operands.
1146 unsigned NumMIOperands = 0;
1147 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1148 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
1149 NumMIOperands = std::max(NumMIOperands,
1150 OI.MIOperandNo + OI.MINumOperands);
1153 // Build the conversion function signature.
1154 std::string Signature = "Convert";
1155 unsigned CurIndex = 0;
1156 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1157 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1158 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
1159 "Duplicate match for instruction operand!");
1161 // Skip operands which weren't matched by anything, this occurs when the
1162 // .td file encodes "implicit" operands as explicit ones.
1164 // FIXME: This should be removed from the MCInst structure.
1165 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1166 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1169 Signature += "__Imp";
1171 Signature += "__Tie" + utostr(Tie->second);
1176 // Registers are always converted the same, don't duplicate the conversion
1177 // function based on them.
1179 // FIXME: We could generalize this based on the render method, if it
1181 if (Op.Class->isRegisterClass())
1184 Signature += Op.Class->ClassName;
1185 Signature += utostr(Op.OperandInfo->MINumOperands);
1186 Signature += "_" + utostr(MIOperandList[i].second);
1188 CurIndex += Op.OperandInfo->MINumOperands;
1191 // Add any trailing implicit operands.
1192 for (; CurIndex != NumMIOperands; ++CurIndex) {
1193 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1196 Signature += "__Imp";
1198 Signature += "__Tie" + utostr(Tie->second);
1201 II.ConversionFnKind = Signature;
1203 // Check if we have already generated this signature.
1204 if (!GeneratedFns.insert(Signature).second)
1207 // If not, emit it now.
1209 // Add to the enum list.
1210 OS << " " << Signature << ",\n";
1212 // And to the convert function.
1213 CvtOS << " case " << Signature << ":\n";
1215 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1216 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1218 // Add the implicit operands.
1219 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1220 // See if this is a tied operand.
1221 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1225 // If not, this is some implicit operand. Just assume it is a register
1227 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1229 // Copy the tied operand.
1230 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1231 CvtOS << " Inst.addOperand(Inst.getOperand("
1232 << Tie->second << "));\n";
1236 CvtOS << " ((" << TargetOperandClass << "*)Operands["
1237 << MIOperandList[i].second
1238 << "+1])->" << Op.Class->RenderMethod
1239 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
1240 CurIndex += Op.OperandInfo->MINumOperands;
1243 // And add trailing implicit operands.
1244 for (; CurIndex != NumMIOperands; ++CurIndex) {
1245 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1249 // If not, this is some implicit operand. Just assume it is a register
1251 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1253 // Copy the tied operand.
1254 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1255 CvtOS << " Inst.addOperand(Inst.getOperand("
1256 << Tie->second << "));\n";
1260 CvtOS << " return;\n";
1263 // Finish the convert function.
1268 // Finish the enum, and drop the convert function after it.
1270 OS << " NumConversionVariants\n";
1276 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1277 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1278 std::vector<ClassInfo*> &Infos,
1280 OS << "namespace {\n\n";
1282 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1283 << "/// instruction matching.\n";
1284 OS << "enum MatchClassKind {\n";
1285 OS << " InvalidMatchClass = 0,\n";
1286 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1287 ie = Infos.end(); it != ie; ++it) {
1288 ClassInfo &CI = **it;
1289 OS << " " << CI.Name << ", // ";
1290 if (CI.Kind == ClassInfo::Token) {
1291 OS << "'" << CI.ValueName << "'\n";
1292 } else if (CI.isRegisterClass()) {
1293 if (!CI.ValueName.empty())
1294 OS << "register class '" << CI.ValueName << "'\n";
1296 OS << "derived register class\n";
1298 OS << "user defined class '" << CI.ValueName << "'\n";
1301 OS << " NumMatchClassKinds\n";
1307 /// EmitClassifyOperand - Emit the function to classify an operand.
1308 static void EmitClassifyOperand(CodeGenTarget &Target,
1309 AsmMatcherInfo &Info,
1311 OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
1312 << " " << Target.getName() << "Operand &Operand = *("
1313 << Target.getName() << "Operand*)GOp;\n";
1316 OS << " if (Operand.isToken())\n";
1317 OS << " return MatchTokenString(Operand.getToken());\n\n";
1319 // Classify registers.
1321 // FIXME: Don't hardcode isReg, getReg.
1322 OS << " if (Operand.isReg()) {\n";
1323 OS << " switch (Operand.getReg()) {\n";
1324 OS << " default: return InvalidMatchClass;\n";
1325 for (std::map<Record*, ClassInfo*>::iterator
1326 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1328 OS << " case " << Target.getName() << "::"
1329 << it->first->getName() << ": return " << it->second->Name << ";\n";
1333 // Classify user defined operands.
1334 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1335 ie = Info.Classes.end(); it != ie; ++it) {
1336 ClassInfo &CI = **it;
1338 if (!CI.isUserClass())
1341 OS << " // '" << CI.ClassName << "' class";
1342 if (!CI.SuperClasses.empty()) {
1343 OS << ", subclass of ";
1344 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1346 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1347 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
1352 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
1354 // Validate subclass relationships.
1355 if (!CI.SuperClasses.empty()) {
1356 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1357 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1358 << "() && \"Invalid class relationship!\");\n";
1361 OS << " return " << CI.Name << ";\n";
1364 OS << " return InvalidMatchClass;\n";
1368 /// EmitIsSubclass - Emit the subclass predicate function.
1369 static void EmitIsSubclass(CodeGenTarget &Target,
1370 std::vector<ClassInfo*> &Infos,
1372 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1373 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1374 OS << " if (A == B)\n";
1375 OS << " return true;\n\n";
1377 OS << " switch (A) {\n";
1378 OS << " default:\n";
1379 OS << " return false;\n";
1380 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1381 ie = Infos.end(); it != ie; ++it) {
1382 ClassInfo &A = **it;
1384 if (A.Kind != ClassInfo::Token) {
1385 std::vector<StringRef> SuperClasses;
1386 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1387 ie = Infos.end(); it != ie; ++it) {
1388 ClassInfo &B = **it;
1390 if (&A != &B && A.isSubsetOf(B))
1391 SuperClasses.push_back(B.Name);
1394 if (SuperClasses.empty())
1397 OS << "\n case " << A.Name << ":\n";
1399 if (SuperClasses.size() == 1) {
1400 OS << " return B == " << SuperClasses.back() << ";\n";
1404 OS << " switch (B) {\n";
1405 OS << " default: return false;\n";
1406 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1407 OS << " case " << SuperClasses[i] << ": return true;\n";
1417 /// EmitMatchTokenString - Emit the function to match a token string to the
1418 /// appropriate match class value.
1419 static void EmitMatchTokenString(CodeGenTarget &Target,
1420 std::vector<ClassInfo*> &Infos,
1422 // Construct the match list.
1423 std::vector<StringMatcher::StringPair> Matches;
1424 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1425 ie = Infos.end(); it != ie; ++it) {
1426 ClassInfo &CI = **it;
1428 if (CI.Kind == ClassInfo::Token)
1429 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1430 "return " + CI.Name + ";"));
1433 OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
1435 StringMatcher("Name", Matches, OS).Emit();
1437 OS << " return InvalidMatchClass;\n";
1441 /// EmitMatchRegisterName - Emit the function to match a string to the target
1442 /// specific register enum.
1443 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1445 // Construct the match list.
1446 std::vector<StringMatcher::StringPair> Matches;
1447 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1448 const CodeGenRegister &Reg = Target.getRegisters()[i];
1449 if (Reg.TheDef->getValueAsString("AsmName").empty())
1452 Matches.push_back(StringMatcher::StringPair(
1453 Reg.TheDef->getValueAsString("AsmName"),
1454 "return " + utostr(i + 1) + ";"));
1457 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
1459 StringMatcher("Name", Matches, OS).Emit();
1461 OS << " return 0;\n";
1465 /// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1467 static void EmitSubtargetFeatureFlagEnumeration(CodeGenTarget &Target,
1468 AsmMatcherInfo &Info,
1470 OS << "// Flags for subtarget features that participate in "
1471 << "instruction matching.\n";
1472 OS << "enum SubtargetFeatureFlag {\n";
1473 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1474 it = Info.SubtargetFeatures.begin(),
1475 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1476 SubtargetFeatureInfo &SFI = *it->second;
1477 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
1479 OS << " Feature_None = 0\n";
1483 /// EmitComputeAvailableFeatures - Emit the function to compute the list of
1484 /// available features given a subtarget.
1485 static void EmitComputeAvailableFeatures(CodeGenTarget &Target,
1486 AsmMatcherInfo &Info,
1488 std::string ClassName =
1489 Info.AsmParser->getValueAsString("AsmParserClassName");
1491 OS << "unsigned " << Target.getName() << ClassName << "::\n"
1492 << "ComputeAvailableFeatures(const " << Target.getName()
1493 << "Subtarget *Subtarget) const {\n";
1494 OS << " unsigned Features = 0;\n";
1495 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1496 it = Info.SubtargetFeatures.begin(),
1497 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1498 SubtargetFeatureInfo &SFI = *it->second;
1499 OS << " if (" << SFI.TheDef->getValueAsString("CondString")
1501 OS << " Features |= " << SFI.getEnumName() << ";\n";
1503 OS << " return Features;\n";
1507 static std::string GetAliasRequiredFeatures(Record *R,
1508 const AsmMatcherInfo &Info) {
1509 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
1511 unsigned NumFeatures = 0;
1512 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
1513 if (SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i])) {
1517 Result += F->getEnumName();
1522 if (NumFeatures > 1)
1523 Result = '(' + Result + ')';
1527 /// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
1528 /// emit a function for them and return true, otherwise return false.
1529 static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
1530 std::vector<Record*> Aliases =
1531 Records.getAllDerivedDefinitions("MnemonicAlias");
1532 if (Aliases.empty()) return false;
1534 OS << "static void ApplyMnemonicAliases(StringRef &Mnemonic, "
1535 "unsigned Features) {\n";
1537 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
1538 // iteration order of the map is stable.
1539 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1541 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1542 Record *R = Aliases[i];
1543 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
1546 // Process each alias a "from" mnemonic at a time, building the code executed
1547 // by the string remapper.
1548 std::vector<StringMatcher::StringPair> Cases;
1549 for (std::map<std::string, std::vector<Record*> >::iterator
1550 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1552 const std::vector<Record*> &ToVec = I->second;
1554 // Loop through each alias and emit code that handles each case. If there
1555 // are two instructions without predicates, emit an error. If there is one,
1557 std::string MatchCode;
1558 int AliasWithNoPredicate = -1;
1560 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1561 Record *R = ToVec[i];
1562 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
1564 // If this unconditionally matches, remember it for later and diagnose
1566 if (FeatureMask.empty()) {
1567 if (AliasWithNoPredicate != -1) {
1568 // We can't have two aliases from the same mnemonic with no predicate.
1569 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1570 "two MnemonicAliases with the same 'from' mnemonic!");
1571 PrintError(R->getLoc(), "this is the other MnemonicAlias.");
1572 throw std::string("ERROR: Invalid MnemonicAlias definitions!");
1575 AliasWithNoPredicate = i;
1579 if (!MatchCode.empty())
1580 MatchCode += "else ";
1581 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1582 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
1585 if (AliasWithNoPredicate != -1) {
1586 Record *R = ToVec[AliasWithNoPredicate];
1587 if (!MatchCode.empty())
1588 MatchCode += "else\n ";
1589 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
1592 MatchCode += "return;";
1594 Cases.push_back(std::make_pair(I->first, MatchCode));
1598 StringMatcher("Mnemonic", Cases, OS).Emit();
1604 void AsmMatcherEmitter::run(raw_ostream &OS) {
1605 CodeGenTarget Target;
1606 Record *AsmParser = Target.getAsmParser();
1607 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1609 // Compute the information on the instructions to match.
1610 AsmMatcherInfo Info(AsmParser);
1611 Info.BuildInfo(Target);
1613 // Sort the instruction table using the partial order on classes. We use
1614 // stable_sort to ensure that ambiguous instructions are still
1615 // deterministically ordered.
1616 std::stable_sort(Info.Instructions.begin(), Info.Instructions.end(),
1617 less_ptr<InstructionInfo>());
1619 DEBUG_WITH_TYPE("instruction_info", {
1620 for (std::vector<InstructionInfo*>::iterator
1621 it = Info.Instructions.begin(), ie = Info.Instructions.end();
1626 // Check for ambiguous instructions.
1627 DEBUG_WITH_TYPE("ambiguous_instrs", {
1628 unsigned NumAmbiguous = 0;
1629 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1630 for (unsigned j = i + 1; j != e; ++j) {
1631 InstructionInfo &A = *Info.Instructions[i];
1632 InstructionInfo &B = *Info.Instructions[j];
1634 if (A.CouldMatchAmiguouslyWith(B)) {
1635 errs() << "warning: ambiguous instruction match:\n";
1637 errs() << "\nis incomparable with:\n";
1645 errs() << "warning: " << NumAmbiguous
1646 << " ambiguous instructions!\n";
1649 // Write the output.
1651 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1653 // Information for the class declaration.
1654 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
1655 OS << "#undef GET_ASSEMBLER_HEADER\n";
1656 OS << " // This should be included into the middle of the declaration of \n";
1657 OS << " // your subclasses implementation of TargetAsmParser.\n";
1658 OS << " unsigned ComputeAvailableFeatures(const " <<
1659 Target.getName() << "Subtarget *Subtarget) const;\n";
1660 OS << " enum MatchResultTy {\n";
1661 OS << " Match_Success, Match_MnemonicFail, Match_InvalidOperand,\n";
1662 OS << " Match_MissingFeature\n";
1664 OS << " MatchResultTy MatchInstructionImpl(const "
1665 << "SmallVectorImpl<MCParsedAsmOperand*>"
1666 << " &Operands, MCInst &Inst, unsigned &ErrorInfo);\n\n";
1667 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
1672 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
1673 OS << "#undef GET_REGISTER_MATCHER\n\n";
1675 // Emit the subtarget feature enumeration.
1676 EmitSubtargetFeatureFlagEnumeration(Target, Info, OS);
1678 // Emit the function to match a register name to number.
1679 EmitMatchRegisterName(Target, AsmParser, OS);
1681 OS << "#endif // GET_REGISTER_MATCHER\n\n";
1684 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
1685 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
1687 // Generate the function that remaps for mnemonic aliases.
1688 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
1690 // Generate the unified function to convert operands into an MCInst.
1691 EmitConvertToMCInst(Target, Info.Instructions, OS);
1693 // Emit the enumeration for classes which participate in matching.
1694 EmitMatchClassEnumeration(Target, Info.Classes, OS);
1696 // Emit the routine to match token strings to their match class.
1697 EmitMatchTokenString(Target, Info.Classes, OS);
1699 // Emit the routine to classify an operand.
1700 EmitClassifyOperand(Target, Info, OS);
1702 // Emit the subclass predicate routine.
1703 EmitIsSubclass(Target, Info.Classes, OS);
1705 // Emit the available features compute function.
1706 EmitComputeAvailableFeatures(Target, Info, OS);
1709 size_t MaxNumOperands = 0;
1710 for (std::vector<InstructionInfo*>::const_iterator it =
1711 Info.Instructions.begin(), ie = Info.Instructions.end();
1713 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1716 // Emit the static match table; unused classes get initalized to 0 which is
1717 // guaranteed to be InvalidMatchClass.
1719 // FIXME: We can reduce the size of this table very easily. First, we change
1720 // it so that store the kinds in separate bit-fields for each index, which
1721 // only needs to be the max width used for classes at that index (we also need
1722 // to reject based on this during classification). If we then make sure to
1723 // order the match kinds appropriately (putting mnemonics last), then we
1724 // should only end up using a few bits for each class, especially the ones
1725 // following the mnemonic.
1726 OS << "namespace {\n";
1727 OS << " struct MatchEntry {\n";
1728 OS << " unsigned Opcode;\n";
1729 OS << " const char *Mnemonic;\n";
1730 OS << " ConversionKind ConvertFn;\n";
1731 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1732 OS << " unsigned RequiredFeatures;\n";
1735 OS << "// Predicate for searching for an opcode.\n";
1736 OS << " struct LessOpcode {\n";
1737 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
1738 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
1740 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
1741 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
1743 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
1744 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
1748 OS << "} // end anonymous namespace.\n\n";
1750 OS << "static const MatchEntry MatchTable["
1751 << Info.Instructions.size() << "] = {\n";
1753 for (std::vector<InstructionInfo*>::const_iterator it =
1754 Info.Instructions.begin(), ie = Info.Instructions.end();
1756 InstructionInfo &II = **it;
1758 OS << " { " << Target.getName() << "::" << II.InstrName
1759 << ", \"" << II.Tokens[0] << "\""
1760 << ", " << II.ConversionFnKind << ", { ";
1761 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1762 InstructionInfo::Operand &Op = II.Operands[i];
1765 OS << Op.Class->Name;
1769 // Write the required features mask.
1770 if (!II.RequiredFeatures.empty()) {
1771 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
1773 OS << II.RequiredFeatures[i]->getEnumName();
1783 // Finally, build the match function.
1784 OS << Target.getName() << ClassName << "::MatchResultTy "
1785 << Target.getName() << ClassName << "::\n"
1786 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
1788 OS << " MCInst &Inst, unsigned &ErrorInfo) {\n";
1790 // Emit code to get the available features.
1791 OS << " // Get the current feature set.\n";
1792 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
1794 OS << " // Get the instruction mnemonic, which is the first token.\n";
1795 OS << " StringRef Mnemonic = ((" << Target.getName()
1796 << "Operand*)Operands[0])->getToken();\n\n";
1798 if (HasMnemonicAliases) {
1799 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
1800 OS << " ApplyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
1803 // Emit code to compute the class list for this operand vector.
1804 OS << " // Eliminate obvious mismatches.\n";
1805 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
1806 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
1807 OS << " return Match_InvalidOperand;\n";
1810 OS << " // Compute the class list for this operand vector.\n";
1811 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1812 OS << " for (unsigned i = 1, e = Operands.size(); i != e; ++i) {\n";
1813 OS << " Classes[i-1] = ClassifyOperand(Operands[i]);\n\n";
1815 OS << " // Check for invalid operands before matching.\n";
1816 OS << " if (Classes[i-1] == InvalidMatchClass) {\n";
1817 OS << " ErrorInfo = i;\n";
1818 OS << " return Match_InvalidOperand;\n";
1822 OS << " // Mark unused classes.\n";
1823 OS << " for (unsigned i = Operands.size()-1, e = " << MaxNumOperands << "; "
1824 << "i != e; ++i)\n";
1825 OS << " Classes[i] = InvalidMatchClass;\n\n";
1827 OS << " // Some state to try to produce better error messages.\n";
1828 OS << " bool HadMatchOtherThanFeatures = false;\n\n";
1829 OS << " // Set ErrorInfo to the operand that mismatches if it is \n";
1830 OS << " // wrong for all instances of the instruction.\n";
1831 OS << " ErrorInfo = ~0U;\n";
1833 // Emit code to search the table.
1834 OS << " // Search the table.\n";
1835 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
1836 OS << " std::equal_range(MatchTable, MatchTable+"
1837 << Info.Instructions.size() << ", Mnemonic, LessOpcode());\n\n";
1839 OS << " // Return a more specific error code if no mnemonics match.\n";
1840 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
1841 OS << " return Match_MnemonicFail;\n\n";
1843 OS << " for (const MatchEntry *it = MnemonicRange.first, "
1844 << "*ie = MnemonicRange.second;\n";
1845 OS << " it != ie; ++it) {\n";
1847 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
1848 OS << " assert(Mnemonic == it->Mnemonic);\n";
1850 // Emit check that the subclasses match.
1851 OS << " bool OperandsValid = true;\n";
1852 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
1853 OS << " if (IsSubclass(Classes[i], it->Classes[i]))\n";
1854 OS << " continue;\n";
1855 OS << " // If this operand is broken for all of the instances of this\n";
1856 OS << " // mnemonic, keep track of it so we can report loc info.\n";
1857 OS << " if (it == MnemonicRange.first || ErrorInfo == i+1)\n";
1858 OS << " ErrorInfo = i+1;\n";
1860 OS << " ErrorInfo = ~0U;";
1861 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
1862 OS << " OperandsValid = false;\n";
1866 OS << " if (!OperandsValid) continue;\n";
1868 // Emit check that the required features are available.
1869 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
1870 << "!= it->RequiredFeatures) {\n";
1871 OS << " HadMatchOtherThanFeatures = true;\n";
1872 OS << " continue;\n";
1876 OS << " ConvertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
1878 // Call the post-processing function, if used.
1879 std::string InsnCleanupFn =
1880 AsmParser->getValueAsString("AsmParserInstCleanup");
1881 if (!InsnCleanupFn.empty())
1882 OS << " " << InsnCleanupFn << "(Inst);\n";
1884 OS << " return Match_Success;\n";
1887 OS << " // Okay, we had no match. Try to return a useful error code.\n";
1888 OS << " if (HadMatchOtherThanFeatures) return Match_MissingFeature;\n";
1889 OS << " return Match_InvalidOperand;\n";
1892 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";