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. It also emits a matcher for
12 // custom operand parsing.
14 // Converting assembly operands into MCInst structures
15 // ---------------------------------------------------
17 // The input to the target specific matcher is a list of literal tokens and
18 // operands. The target specific parser should generally eliminate any syntax
19 // which is not relevant for matching; for example, comma tokens should have
20 // already been consumed and eliminated by the parser. Most instructions will
21 // end up with a single literal token (the instruction name) and some number of
24 // Some example inputs, for X86:
25 // 'addl' (immediate ...) (register ...)
26 // 'add' (immediate ...) (memory ...)
29 // The assembly matcher is responsible for converting this input into a precise
30 // machine instruction (i.e., an instruction with a well defined encoding). This
31 // mapping has several properties which complicate matching:
33 // - It may be ambiguous; many architectures can legally encode particular
34 // variants of an instruction in different ways (for example, using a smaller
35 // encoding for small immediates). Such ambiguities should never be
36 // arbitrarily resolved by the assembler, the assembler is always responsible
37 // for choosing the "best" available instruction.
39 // - It may depend on the subtarget or the assembler context. Instructions
40 // which are invalid for the current mode, but otherwise unambiguous (e.g.,
41 // an SSE instruction in a file being assembled for i486) should be accepted
42 // and rejected by the assembler front end. However, if the proper encoding
43 // for an instruction is dependent on the assembler context then the matcher
44 // is responsible for selecting the correct machine instruction for the
47 // The core matching algorithm attempts to exploit the regularity in most
48 // instruction sets to quickly determine the set of possibly matching
49 // instructions, and the simplify the generated code. Additionally, this helps
50 // to ensure that the ambiguities are intentionally resolved by the user.
52 // The matching is divided into two distinct phases:
54 // 1. Classification: Each operand is mapped to the unique set which (a)
55 // contains it, and (b) is the largest such subset for which a single
56 // instruction could match all members.
58 // For register classes, we can generate these subgroups automatically. For
59 // arbitrary operands, we expect the user to define the classes and their
60 // relations to one another (for example, 8-bit signed immediates as a
61 // subset of 32-bit immediates).
63 // By partitioning the operands in this way, we guarantee that for any
64 // tuple of classes, any single instruction must match either all or none
65 // of the sets of operands which could classify to that tuple.
67 // In addition, the subset relation amongst classes induces a partial order
68 // on such tuples, which we use to resolve ambiguities.
70 // 2. The input can now be treated as a tuple of classes (static tokens are
71 // simple singleton sets). Each such tuple should generally map to a single
72 // instruction (we currently ignore cases where this isn't true, whee!!!),
73 // which we can emit a simple matcher for.
75 // Custom Operand Parsing
76 // ----------------------
78 // Some targets need a custom way to parse operands, some specific instructions
79 // can contain arguments that can represent processor flags and other kinds of
80 // identifiers that need to be mapped to specific values in the final encoded
81 // instructions. The target specific custom operand parsing works in the
84 // 1. A operand match table is built, each entry contains a mnemonic, an
85 // operand class, a mask for all operand positions for that same
86 // class/mnemonic and target features to be checked while trying to match.
88 // 2. The operand matcher will try every possible entry with the same
89 // mnemonic and will check if the target feature for this mnemonic also
90 // matches. After that, if the operand to be matched has its index
91 // present in the mask, a successful match occurs. Otherwise, fallback
92 // to the regular operand parsing.
94 // 3. For a match success, each operand class that has a 'ParserMethod'
95 // becomes part of a switch from where the custom method is called.
97 //===----------------------------------------------------------------------===//
99 #include "CodeGenTarget.h"
100 #include "llvm/ADT/PointerUnion.h"
101 #include "llvm/ADT/STLExtras.h"
102 #include "llvm/ADT/SmallPtrSet.h"
103 #include "llvm/ADT/SmallVector.h"
104 #include "llvm/ADT/StringExtras.h"
105 #include "llvm/Support/CommandLine.h"
106 #include "llvm/Support/Debug.h"
107 #include "llvm/Support/ErrorHandling.h"
108 #include "llvm/TableGen/Error.h"
109 #include "llvm/TableGen/Record.h"
110 #include "llvm/TableGen/StringMatcher.h"
111 #include "llvm/TableGen/StringToOffsetTable.h"
112 #include "llvm/TableGen/TableGenBackend.h"
118 using namespace llvm;
120 static cl::opt<std::string>
121 MatchPrefix("match-prefix", cl::init(""),
122 cl::desc("Only match instructions with the given prefix"));
125 class AsmMatcherInfo;
126 struct SubtargetFeatureInfo;
128 // Register sets are used as keys in some second-order sets TableGen creates
129 // when generating its data structures. This means that the order of two
130 // RegisterSets can be seen in the outputted AsmMatcher tables occasionally, and
131 // can even affect compiler output (at least seen in diagnostics produced when
132 // all matches fail). So we use a type that sorts them consistently.
133 typedef std::set<Record*, LessRecordByID> RegisterSet;
135 class AsmMatcherEmitter {
136 RecordKeeper &Records;
138 AsmMatcherEmitter(RecordKeeper &R) : Records(R) {}
140 void run(raw_ostream &o);
143 /// ClassInfo - Helper class for storing the information about a particular
144 /// class of operands which can be matched.
147 /// Invalid kind, for use as a sentinel value.
150 /// The class for a particular token.
153 /// The (first) register class, subsequent register classes are
154 /// RegisterClass0+1, and so on.
157 /// The (first) user defined class, subsequent user defined classes are
158 /// UserClass0+1, and so on.
162 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
163 /// N) for the Nth user defined class.
166 /// SuperClasses - The super classes of this class. Note that for simplicities
167 /// sake user operands only record their immediate super class, while register
168 /// operands include all superclasses.
169 std::vector<ClassInfo*> SuperClasses;
171 /// Name - The full class name, suitable for use in an enum.
174 /// ClassName - The unadorned generic name for this class (e.g., Token).
175 std::string ClassName;
177 /// ValueName - The name of the value this class represents; for a token this
178 /// is the literal token string, for an operand it is the TableGen class (or
179 /// empty if this is a derived class).
180 std::string ValueName;
182 /// PredicateMethod - The name of the operand method to test whether the
183 /// operand matches this class; this is not valid for Token or register kinds.
184 std::string PredicateMethod;
186 /// RenderMethod - The name of the operand method to add this operand to an
187 /// MCInst; this is not valid for Token or register kinds.
188 std::string RenderMethod;
190 /// ParserMethod - The name of the operand method to do a target specific
191 /// parsing on the operand.
192 std::string ParserMethod;
194 /// For register classes, the records for all the registers in this class.
195 RegisterSet Registers;
197 /// For custom match classes, he diagnostic kind for when the predicate fails.
198 std::string DiagnosticType;
200 /// isRegisterClass() - Check if this is a register class.
201 bool isRegisterClass() const {
202 return Kind >= RegisterClass0 && Kind < UserClass0;
205 /// isUserClass() - Check if this is a user defined class.
206 bool isUserClass() const {
207 return Kind >= UserClass0;
210 /// isRelatedTo - Check whether this class is "related" to \p RHS. Classes
211 /// are related if they are in the same class hierarchy.
212 bool isRelatedTo(const ClassInfo &RHS) const {
213 // Tokens are only related to tokens.
214 if (Kind == Token || RHS.Kind == Token)
215 return Kind == Token && RHS.Kind == Token;
217 // Registers classes are only related to registers classes, and only if
218 // their intersection is non-empty.
219 if (isRegisterClass() || RHS.isRegisterClass()) {
220 if (!isRegisterClass() || !RHS.isRegisterClass())
224 std::insert_iterator<RegisterSet> II(Tmp, Tmp.begin());
225 std::set_intersection(Registers.begin(), Registers.end(),
226 RHS.Registers.begin(), RHS.Registers.end(),
227 II, LessRecordByID());
232 // Otherwise we have two users operands; they are related if they are in the
233 // same class hierarchy.
235 // FIXME: This is an oversimplification, they should only be related if they
236 // intersect, however we don't have that information.
237 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
238 const ClassInfo *Root = this;
239 while (!Root->SuperClasses.empty())
240 Root = Root->SuperClasses.front();
242 const ClassInfo *RHSRoot = &RHS;
243 while (!RHSRoot->SuperClasses.empty())
244 RHSRoot = RHSRoot->SuperClasses.front();
246 return Root == RHSRoot;
249 /// isSubsetOf - Test whether this class is a subset of \p RHS.
250 bool isSubsetOf(const ClassInfo &RHS) const {
251 // This is a subset of RHS if it is the same class...
255 // ... or if any of its super classes are a subset of RHS.
256 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
257 ie = SuperClasses.end(); it != ie; ++it)
258 if ((*it)->isSubsetOf(RHS))
264 /// operator< - Compare two classes.
265 bool operator<(const ClassInfo &RHS) const {
269 // Unrelated classes can be ordered by kind.
270 if (!isRelatedTo(RHS))
271 return Kind < RHS.Kind;
275 llvm_unreachable("Invalid kind!");
278 // This class precedes the RHS if it is a proper subset of the RHS.
281 if (RHS.isSubsetOf(*this))
284 // Otherwise, order by name to ensure we have a total ordering.
285 return ValueName < RHS.ValueName;
290 /// MatchableInfo - Helper class for storing the necessary information for an
291 /// instruction or alias which is capable of being matched.
292 struct MatchableInfo {
294 /// Token - This is the token that the operand came from.
297 /// The unique class instance this operand should match.
300 /// The operand name this is, if anything.
303 /// The suboperand index within SrcOpName, or -1 for the entire operand.
306 /// Register record if this token is singleton register.
307 Record *SingletonReg;
309 explicit AsmOperand(StringRef T) : Token(T), Class(0), SubOpIdx(-1),
313 /// ResOperand - This represents a single operand in the result instruction
314 /// generated by the match. In cases (like addressing modes) where a single
315 /// assembler operand expands to multiple MCOperands, this represents the
316 /// single assembler operand, not the MCOperand.
319 /// RenderAsmOperand - This represents an operand result that is
320 /// generated by calling the render method on the assembly operand. The
321 /// corresponding AsmOperand is specified by AsmOperandNum.
324 /// TiedOperand - This represents a result operand that is a duplicate of
325 /// a previous result operand.
328 /// ImmOperand - This represents an immediate value that is dumped into
332 /// RegOperand - This represents a fixed register that is dumped in.
337 /// This is the operand # in the AsmOperands list that this should be
339 unsigned AsmOperandNum;
341 /// TiedOperandNum - This is the (earlier) result operand that should be
343 unsigned TiedOperandNum;
345 /// ImmVal - This is the immediate value added to the instruction.
348 /// Register - This is the register record.
352 /// MINumOperands - The number of MCInst operands populated by this
354 unsigned MINumOperands;
356 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
358 X.Kind = RenderAsmOperand;
359 X.AsmOperandNum = AsmOpNum;
360 X.MINumOperands = NumOperands;
364 static ResOperand getTiedOp(unsigned TiedOperandNum) {
366 X.Kind = TiedOperand;
367 X.TiedOperandNum = TiedOperandNum;
372 static ResOperand getImmOp(int64_t Val) {
380 static ResOperand getRegOp(Record *Reg) {
389 /// AsmVariantID - Target's assembly syntax variant no.
392 /// TheDef - This is the definition of the instruction or InstAlias that this
393 /// matchable came from.
394 Record *const TheDef;
396 /// DefRec - This is the definition that it came from.
397 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
399 const CodeGenInstruction *getResultInst() const {
400 if (DefRec.is<const CodeGenInstruction*>())
401 return DefRec.get<const CodeGenInstruction*>();
402 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
405 /// ResOperands - This is the operand list that should be built for the result
407 SmallVector<ResOperand, 8> ResOperands;
409 /// AsmString - The assembly string for this instruction (with variants
410 /// removed), e.g. "movsx $src, $dst".
411 std::string AsmString;
413 /// Mnemonic - This is the first token of the matched instruction, its
417 /// AsmOperands - The textual operands that this instruction matches,
418 /// annotated with a class and where in the OperandList they were defined.
419 /// This directly corresponds to the tokenized AsmString after the mnemonic is
421 SmallVector<AsmOperand, 8> AsmOperands;
423 /// Predicates - The required subtarget features to match this instruction.
424 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
426 /// ConversionFnKind - The enum value which is passed to the generated
427 /// convertToMCInst to convert parsed operands into an MCInst for this
429 std::string ConversionFnKind;
431 /// If this instruction is deprecated in some form.
434 MatchableInfo(const CodeGenInstruction &CGI)
435 : AsmVariantID(0), TheDef(CGI.TheDef), DefRec(&CGI),
436 AsmString(CGI.AsmString) {
439 MatchableInfo(const CodeGenInstAlias *Alias)
440 : AsmVariantID(0), TheDef(Alias->TheDef), DefRec(Alias),
441 AsmString(Alias->AsmString) {
444 // Two-operand aliases clone from the main matchable, but mark the second
445 // operand as a tied operand of the first for purposes of the assembler.
446 void formTwoOperandAlias(StringRef Constraint);
448 void initialize(const AsmMatcherInfo &Info,
449 SmallPtrSet<Record*, 16> &SingletonRegisters,
450 int AsmVariantNo, std::string &RegisterPrefix);
452 /// validate - Return true if this matchable is a valid thing to match against
453 /// and perform a bunch of validity checking.
454 bool validate(StringRef CommentDelimiter, bool Hack) const;
456 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
457 /// if present, from specified token.
459 extractSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info,
460 std::string &RegisterPrefix);
462 /// findAsmOperand - Find the AsmOperand with the specified name and
463 /// suboperand index.
464 int findAsmOperand(StringRef N, int SubOpIdx) const {
465 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
466 if (N == AsmOperands[i].SrcOpName &&
467 SubOpIdx == AsmOperands[i].SubOpIdx)
472 /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
473 /// This does not check the suboperand index.
474 int findAsmOperandNamed(StringRef N) const {
475 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
476 if (N == AsmOperands[i].SrcOpName)
481 void buildInstructionResultOperands();
482 void buildAliasResultOperands();
484 /// operator< - Compare two matchables.
485 bool operator<(const MatchableInfo &RHS) const {
486 // The primary comparator is the instruction mnemonic.
487 if (Mnemonic != RHS.Mnemonic)
488 return Mnemonic < RHS.Mnemonic;
490 if (AsmOperands.size() != RHS.AsmOperands.size())
491 return AsmOperands.size() < RHS.AsmOperands.size();
493 // Compare lexicographically by operand. The matcher validates that other
494 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
495 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
496 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
498 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
502 // Give matches that require more features higher precedence. This is useful
503 // because we cannot define AssemblerPredicates with the negation of
504 // processor features. For example, ARM v6 "nop" may be either a HINT or
505 // MOV. With v6, we want to match HINT. The assembler has no way to
506 // predicate MOV under "NoV6", but HINT will always match first because it
507 // requires V6 while MOV does not.
508 if (RequiredFeatures.size() != RHS.RequiredFeatures.size())
509 return RequiredFeatures.size() > RHS.RequiredFeatures.size();
514 /// couldMatchAmbiguouslyWith - Check whether this matchable could
515 /// ambiguously match the same set of operands as \p RHS (without being a
516 /// strictly superior match).
517 bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) {
518 // The primary comparator is the instruction mnemonic.
519 if (Mnemonic != RHS.Mnemonic)
522 // The number of operands is unambiguous.
523 if (AsmOperands.size() != RHS.AsmOperands.size())
526 // Otherwise, make sure the ordering of the two instructions is unambiguous
527 // by checking that either (a) a token or operand kind discriminates them,
528 // or (b) the ordering among equivalent kinds is consistent.
530 // Tokens and operand kinds are unambiguous (assuming a correct target
532 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
533 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
534 AsmOperands[i].Class->Kind == ClassInfo::Token)
535 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
536 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
539 // Otherwise, this operand could commute if all operands are equivalent, or
540 // there is a pair of operands that compare less than and a pair that
541 // compare greater than.
542 bool HasLT = false, HasGT = false;
543 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
544 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
546 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
550 return !(HasLT ^ HasGT);
556 void tokenizeAsmString(const AsmMatcherInfo &Info);
559 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
560 /// feature which participates in instruction matching.
561 struct SubtargetFeatureInfo {
562 /// \brief The predicate record for this feature.
565 /// \brief An unique index assigned to represent this feature.
568 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
570 /// \brief The name of the enumerated constant identifying this feature.
571 std::string getEnumName() const {
572 return "Feature_" + TheDef->getName();
576 struct OperandMatchEntry {
577 unsigned OperandMask;
581 static OperandMatchEntry create(MatchableInfo* mi, ClassInfo *ci,
584 X.OperandMask = opMask;
592 class AsmMatcherInfo {
595 RecordKeeper &Records;
597 /// The tablegen AsmParser record.
600 /// Target - The target information.
601 CodeGenTarget &Target;
603 /// The classes which are needed for matching.
604 std::vector<ClassInfo*> Classes;
606 /// The information on the matchables to match.
607 std::vector<MatchableInfo*> Matchables;
609 /// Info for custom matching operands by user defined methods.
610 std::vector<OperandMatchEntry> OperandMatchInfo;
612 /// Map of Register records to their class information.
613 typedef std::map<Record*, ClassInfo*, LessRecordByID> RegisterClassesTy;
614 RegisterClassesTy RegisterClasses;
616 /// Map of Predicate records to their subtarget information.
617 std::map<Record*, SubtargetFeatureInfo*, LessRecordByID> SubtargetFeatures;
619 /// Map of AsmOperandClass records to their class information.
620 std::map<Record*, ClassInfo*> AsmOperandClasses;
623 /// Map of token to class information which has already been constructed.
624 std::map<std::string, ClassInfo*> TokenClasses;
626 /// Map of RegisterClass records to their class information.
627 std::map<Record*, ClassInfo*> RegisterClassClasses;
630 /// getTokenClass - Lookup or create the class for the given token.
631 ClassInfo *getTokenClass(StringRef Token);
633 /// getOperandClass - Lookup or create the class for the given operand.
634 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
636 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
638 /// buildRegisterClasses - Build the ClassInfo* instances for register
640 void buildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
642 /// buildOperandClasses - Build the ClassInfo* instances for user defined
644 void buildOperandClasses();
646 void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
648 void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
649 MatchableInfo::AsmOperand &Op);
652 AsmMatcherInfo(Record *AsmParser,
653 CodeGenTarget &Target,
654 RecordKeeper &Records);
656 /// buildInfo - Construct the various tables used during matching.
659 /// buildOperandMatchInfo - Build the necessary information to handle user
660 /// defined operand parsing methods.
661 void buildOperandMatchInfo();
663 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
665 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
666 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
667 std::map<Record*, SubtargetFeatureInfo*, LessRecordByID>::const_iterator I =
668 SubtargetFeatures.find(Def);
669 return I == SubtargetFeatures.end() ? 0 : I->second;
672 RecordKeeper &getRecords() const {
677 } // End anonymous namespace
679 void MatchableInfo::dump() {
680 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
682 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
683 AsmOperand &Op = AsmOperands[i];
684 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
685 errs() << '\"' << Op.Token << "\"\n";
689 static std::pair<StringRef, StringRef>
690 parseTwoOperandConstraint(StringRef S, ArrayRef<SMLoc> Loc) {
691 // Split via the '='.
692 std::pair<StringRef, StringRef> Ops = S.split('=');
693 if (Ops.second == "")
694 PrintFatalError(Loc, "missing '=' in two-operand alias constraint");
695 // Trim whitespace and the leading '$' on the operand names.
696 size_t start = Ops.first.find_first_of('$');
697 if (start == std::string::npos)
698 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
699 Ops.first = Ops.first.slice(start + 1, std::string::npos);
700 size_t end = Ops.first.find_last_of(" \t");
701 Ops.first = Ops.first.slice(0, end);
702 // Now the second operand.
703 start = Ops.second.find_first_of('$');
704 if (start == std::string::npos)
705 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
706 Ops.second = Ops.second.slice(start + 1, std::string::npos);
707 end = Ops.second.find_last_of(" \t");
708 Ops.first = Ops.first.slice(0, end);
712 void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
713 // Figure out which operands are aliased and mark them as tied.
714 std::pair<StringRef, StringRef> Ops =
715 parseTwoOperandConstraint(Constraint, TheDef->getLoc());
717 // Find the AsmOperands that refer to the operands we're aliasing.
718 int SrcAsmOperand = findAsmOperandNamed(Ops.first);
719 int DstAsmOperand = findAsmOperandNamed(Ops.second);
720 if (SrcAsmOperand == -1)
721 PrintFatalError(TheDef->getLoc(),
722 "unknown source two-operand alias operand '" + Ops.first +
724 if (DstAsmOperand == -1)
725 PrintFatalError(TheDef->getLoc(),
726 "unknown destination two-operand alias operand '" +
729 // Find the ResOperand that refers to the operand we're aliasing away
730 // and update it to refer to the combined operand instead.
731 for (unsigned i = 0, e = ResOperands.size(); i != e; ++i) {
732 ResOperand &Op = ResOperands[i];
733 if (Op.Kind == ResOperand::RenderAsmOperand &&
734 Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
735 Op.AsmOperandNum = DstAsmOperand;
739 // Remove the AsmOperand for the alias operand.
740 AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
741 // Adjust the ResOperand references to any AsmOperands that followed
742 // the one we just deleted.
743 for (unsigned i = 0, e = ResOperands.size(); i != e; ++i) {
744 ResOperand &Op = ResOperands[i];
747 // Nothing to do for operands that don't reference AsmOperands.
749 case ResOperand::RenderAsmOperand:
750 if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
753 case ResOperand::TiedOperand:
754 if (Op.TiedOperandNum > (unsigned)SrcAsmOperand)
761 void MatchableInfo::initialize(const AsmMatcherInfo &Info,
762 SmallPtrSet<Record*, 16> &SingletonRegisters,
763 int AsmVariantNo, std::string &RegisterPrefix) {
764 AsmVariantID = AsmVariantNo;
766 CodeGenInstruction::FlattenAsmStringVariants(AsmString, AsmVariantNo);
768 tokenizeAsmString(Info);
770 // Compute the require features.
771 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates");
772 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
773 if (SubtargetFeatureInfo *Feature =
774 Info.getSubtargetFeature(Predicates[i]))
775 RequiredFeatures.push_back(Feature);
777 // Collect singleton registers, if used.
778 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
779 extractSingletonRegisterForAsmOperand(i, Info, RegisterPrefix);
780 if (Record *Reg = AsmOperands[i].SingletonReg)
781 SingletonRegisters.insert(Reg);
784 const RecordVal *DepMask = TheDef->getValue("DeprecatedFeatureMask");
786 DepMask = TheDef->getValue("ComplexDeprecationPredicate");
789 DepMask ? !DepMask->getValue()->getAsUnquotedString().empty() : false;
792 /// tokenizeAsmString - Tokenize a simplified assembly string.
793 void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info) {
794 StringRef String = AsmString;
797 for (unsigned i = 0, e = String.size(); i != e; ++i) {
807 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
810 if (!isspace(String[i]) && String[i] != ',')
811 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
817 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
821 assert(i != String.size() && "Invalid quoted character");
822 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
828 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
832 // If this isn't "${", treat like a normal token.
833 if (i + 1 == String.size() || String[i + 1] != '{') {
838 StringRef::iterator End = std::find(String.begin() + i, String.end(),'}');
839 assert(End != String.end() && "Missing brace in operand reference!");
840 size_t EndPos = End - String.begin();
841 AsmOperands.push_back(AsmOperand(String.slice(i, EndPos+1)));
848 if (!Info.AsmParser->getValueAsBit("MnemonicContainsDot")) {
850 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
860 if (InTok && Prev != String.size())
861 AsmOperands.push_back(AsmOperand(String.substr(Prev)));
863 // The first token of the instruction is the mnemonic, which must be a
864 // simple string, not a $foo variable or a singleton register.
865 if (AsmOperands.empty())
866 PrintFatalError(TheDef->getLoc(),
867 "Instruction '" + TheDef->getName() + "' has no tokens");
868 Mnemonic = AsmOperands[0].Token;
869 if (Mnemonic.empty())
870 PrintFatalError(TheDef->getLoc(),
871 "Missing instruction mnemonic");
872 // FIXME : Check and raise an error if it is a register.
873 if (Mnemonic[0] == '$')
874 PrintFatalError(TheDef->getLoc(),
875 "Invalid instruction mnemonic '" + Mnemonic + "'!");
877 // Remove the first operand, it is tracked in the mnemonic field.
878 AsmOperands.erase(AsmOperands.begin());
881 bool MatchableInfo::validate(StringRef CommentDelimiter, bool Hack) const {
882 // Reject matchables with no .s string.
883 if (AsmString.empty())
884 PrintFatalError(TheDef->getLoc(), "instruction with empty asm string");
886 // Reject any matchables with a newline in them, they should be marked
887 // isCodeGenOnly if they are pseudo instructions.
888 if (AsmString.find('\n') != std::string::npos)
889 PrintFatalError(TheDef->getLoc(),
890 "multiline instruction is not valid for the asmparser, "
891 "mark it isCodeGenOnly");
893 // Remove comments from the asm string. We know that the asmstring only
895 if (!CommentDelimiter.empty() &&
896 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
897 PrintFatalError(TheDef->getLoc(),
898 "asmstring for instruction has comment character in it, "
899 "mark it isCodeGenOnly");
901 // Reject matchables with operand modifiers, these aren't something we can
902 // handle, the target should be refactored to use operands instead of
905 // Also, check for instructions which reference the operand multiple times;
906 // this implies a constraint we would not honor.
907 std::set<std::string> OperandNames;
908 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
909 StringRef Tok = AsmOperands[i].Token;
910 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
911 PrintFatalError(TheDef->getLoc(),
912 "matchable with operand modifier '" + Tok +
913 "' not supported by asm matcher. Mark isCodeGenOnly!");
915 // Verify that any operand is only mentioned once.
916 // We reject aliases and ignore instructions for now.
917 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
919 PrintFatalError(TheDef->getLoc(),
920 "ERROR: matchable with tied operand '" + Tok +
921 "' can never be matched!");
922 // FIXME: Should reject these. The ARM backend hits this with $lane in a
923 // bunch of instructions. It is unclear what the right answer is.
925 errs() << "warning: '" << TheDef->getName() << "': "
926 << "ignoring instruction with tied operand '"
936 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
937 /// if present, from specified token.
939 extractSingletonRegisterForAsmOperand(unsigned OperandNo,
940 const AsmMatcherInfo &Info,
941 std::string &RegisterPrefix) {
942 StringRef Tok = AsmOperands[OperandNo].Token;
943 if (RegisterPrefix.empty()) {
944 std::string LoweredTok = Tok.lower();
945 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
946 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
950 if (!Tok.startswith(RegisterPrefix))
953 StringRef RegName = Tok.substr(RegisterPrefix.size());
954 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
955 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
957 // If there is no register prefix (i.e. "%" in "%eax"), then this may
958 // be some random non-register token, just ignore it.
962 static std::string getEnumNameForToken(StringRef Str) {
965 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
967 case '*': Res += "_STAR_"; break;
968 case '%': Res += "_PCT_"; break;
969 case ':': Res += "_COLON_"; break;
970 case '!': Res += "_EXCLAIM_"; break;
971 case '.': Res += "_DOT_"; break;
972 case '<': Res += "_LT_"; break;
973 case '>': Res += "_GT_"; break;
975 if ((*it >= 'A' && *it <= 'Z') ||
976 (*it >= 'a' && *it <= 'z') ||
977 (*it >= '0' && *it <= '9'))
980 Res += "_" + utostr((unsigned) *it) + "_";
987 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
988 ClassInfo *&Entry = TokenClasses[Token];
991 Entry = new ClassInfo();
992 Entry->Kind = ClassInfo::Token;
993 Entry->ClassName = "Token";
994 Entry->Name = "MCK_" + getEnumNameForToken(Token);
995 Entry->ValueName = Token;
996 Entry->PredicateMethod = "<invalid>";
997 Entry->RenderMethod = "<invalid>";
998 Entry->ParserMethod = "";
999 Entry->DiagnosticType = "";
1000 Classes.push_back(Entry);
1007 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
1009 Record *Rec = OI.Rec;
1011 Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
1012 return getOperandClass(Rec, SubOpIdx);
1016 AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
1017 if (Rec->isSubClassOf("RegisterOperand")) {
1018 // RegisterOperand may have an associated ParserMatchClass. If it does,
1019 // use it, else just fall back to the underlying register class.
1020 const RecordVal *R = Rec->getValue("ParserMatchClass");
1021 if (R == 0 || R->getValue() == 0)
1022 PrintFatalError("Record `" + Rec->getName() +
1023 "' does not have a ParserMatchClass!\n");
1025 if (DefInit *DI= dyn_cast<DefInit>(R->getValue())) {
1026 Record *MatchClass = DI->getDef();
1027 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1031 // No custom match class. Just use the register class.
1032 Record *ClassRec = Rec->getValueAsDef("RegClass");
1034 PrintFatalError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
1035 "' has no associated register class!\n");
1036 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
1038 PrintFatalError(Rec->getLoc(), "register class has no class info!");
1042 if (Rec->isSubClassOf("RegisterClass")) {
1043 if (ClassInfo *CI = RegisterClassClasses[Rec])
1045 PrintFatalError(Rec->getLoc(), "register class has no class info!");
1048 if (!Rec->isSubClassOf("Operand"))
1049 PrintFatalError(Rec->getLoc(), "Operand `" + Rec->getName() +
1050 "' does not derive from class Operand!\n");
1051 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1052 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1055 PrintFatalError(Rec->getLoc(), "operand has no match class!");
1058 struct LessRegisterSet {
1059 bool operator() (const RegisterSet &LHS, const RegisterSet & RHS) const {
1060 // std::set<T> defines its own compariso "operator<", but it
1061 // performs a lexicographical comparison by T's innate comparison
1062 // for some reason. We don't want non-deterministic pointer
1063 // comparisons so use this instead.
1064 return std::lexicographical_compare(LHS.begin(), LHS.end(),
1065 RHS.begin(), RHS.end(),
1070 void AsmMatcherInfo::
1071 buildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
1072 const std::vector<CodeGenRegister*> &Registers =
1073 Target.getRegBank().getRegisters();
1074 ArrayRef<CodeGenRegisterClass*> RegClassList =
1075 Target.getRegBank().getRegClasses();
1077 typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet;
1079 // The register sets used for matching.
1080 RegisterSetSet RegisterSets;
1082 // Gather the defined sets.
1083 for (ArrayRef<CodeGenRegisterClass*>::const_iterator it =
1084 RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it)
1085 RegisterSets.insert(RegisterSet(
1086 (*it)->getOrder().begin(), (*it)->getOrder().end()));
1088 // Add any required singleton sets.
1089 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1090 ie = SingletonRegisters.end(); it != ie; ++it) {
1092 RegisterSets.insert(RegisterSet(&Rec, &Rec + 1));
1095 // Introduce derived sets where necessary (when a register does not determine
1096 // a unique register set class), and build the mapping of registers to the set
1097 // they should classify to.
1098 std::map<Record*, RegisterSet> RegisterMap;
1099 for (std::vector<CodeGenRegister*>::const_iterator it = Registers.begin(),
1100 ie = Registers.end(); it != ie; ++it) {
1101 const CodeGenRegister &CGR = **it;
1102 // Compute the intersection of all sets containing this register.
1103 RegisterSet ContainingSet;
1105 for (RegisterSetSet::iterator it = RegisterSets.begin(),
1106 ie = RegisterSets.end(); it != ie; ++it) {
1107 if (!it->count(CGR.TheDef))
1110 if (ContainingSet.empty()) {
1111 ContainingSet = *it;
1116 std::swap(Tmp, ContainingSet);
1117 std::insert_iterator<RegisterSet> II(ContainingSet,
1118 ContainingSet.begin());
1119 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(), II,
1123 if (!ContainingSet.empty()) {
1124 RegisterSets.insert(ContainingSet);
1125 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
1129 // Construct the register classes.
1130 std::map<RegisterSet, ClassInfo*, LessRegisterSet> RegisterSetClasses;
1132 for (RegisterSetSet::iterator it = RegisterSets.begin(),
1133 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
1134 ClassInfo *CI = new ClassInfo();
1135 CI->Kind = ClassInfo::RegisterClass0 + Index;
1136 CI->ClassName = "Reg" + utostr(Index);
1137 CI->Name = "MCK_Reg" + utostr(Index);
1139 CI->PredicateMethod = ""; // unused
1140 CI->RenderMethod = "addRegOperands";
1141 CI->Registers = *it;
1142 // FIXME: diagnostic type.
1143 CI->DiagnosticType = "";
1144 Classes.push_back(CI);
1145 RegisterSetClasses.insert(std::make_pair(*it, CI));
1148 // Find the superclasses; we could compute only the subgroup lattice edges,
1149 // but there isn't really a point.
1150 for (RegisterSetSet::iterator it = RegisterSets.begin(),
1151 ie = RegisterSets.end(); it != ie; ++it) {
1152 ClassInfo *CI = RegisterSetClasses[*it];
1153 for (RegisterSetSet::iterator it2 = RegisterSets.begin(),
1154 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
1156 std::includes(it2->begin(), it2->end(), it->begin(), it->end(),
1158 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
1161 // Name the register classes which correspond to a user defined RegisterClass.
1162 for (ArrayRef<CodeGenRegisterClass*>::const_iterator
1163 it = RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) {
1164 const CodeGenRegisterClass &RC = **it;
1165 // Def will be NULL for non-user defined register classes.
1166 Record *Def = RC.getDef();
1169 ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(),
1170 RC.getOrder().end())];
1171 if (CI->ValueName.empty()) {
1172 CI->ClassName = RC.getName();
1173 CI->Name = "MCK_" + RC.getName();
1174 CI->ValueName = RC.getName();
1176 CI->ValueName = CI->ValueName + "," + RC.getName();
1178 RegisterClassClasses.insert(std::make_pair(Def, CI));
1181 // Populate the map for individual registers.
1182 for (std::map<Record*, RegisterSet>::iterator it = RegisterMap.begin(),
1183 ie = RegisterMap.end(); it != ie; ++it)
1184 RegisterClasses[it->first] = RegisterSetClasses[it->second];
1186 // Name the register classes which correspond to singleton registers.
1187 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1188 ie = SingletonRegisters.end(); it != ie; ++it) {
1190 ClassInfo *CI = RegisterClasses[Rec];
1191 assert(CI && "Missing singleton register class info!");
1193 if (CI->ValueName.empty()) {
1194 CI->ClassName = Rec->getName();
1195 CI->Name = "MCK_" + Rec->getName();
1196 CI->ValueName = Rec->getName();
1198 CI->ValueName = CI->ValueName + "," + Rec->getName();
1202 void AsmMatcherInfo::buildOperandClasses() {
1203 std::vector<Record*> AsmOperands =
1204 Records.getAllDerivedDefinitions("AsmOperandClass");
1206 // Pre-populate AsmOperandClasses map.
1207 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1208 ie = AsmOperands.end(); it != ie; ++it)
1209 AsmOperandClasses[*it] = new ClassInfo();
1212 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1213 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
1214 ClassInfo *CI = AsmOperandClasses[*it];
1215 CI->Kind = ClassInfo::UserClass0 + Index;
1217 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
1218 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
1219 DefInit *DI = dyn_cast<DefInit>(Supers->getElement(i));
1221 PrintError((*it)->getLoc(), "Invalid super class reference!");
1225 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1227 PrintError((*it)->getLoc(), "Invalid super class reference!");
1229 CI->SuperClasses.push_back(SC);
1231 CI->ClassName = (*it)->getValueAsString("Name");
1232 CI->Name = "MCK_" + CI->ClassName;
1233 CI->ValueName = (*it)->getName();
1235 // Get or construct the predicate method name.
1236 Init *PMName = (*it)->getValueInit("PredicateMethod");
1237 if (StringInit *SI = dyn_cast<StringInit>(PMName)) {
1238 CI->PredicateMethod = SI->getValue();
1240 assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!");
1241 CI->PredicateMethod = "is" + CI->ClassName;
1244 // Get or construct the render method name.
1245 Init *RMName = (*it)->getValueInit("RenderMethod");
1246 if (StringInit *SI = dyn_cast<StringInit>(RMName)) {
1247 CI->RenderMethod = SI->getValue();
1249 assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!");
1250 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1253 // Get the parse method name or leave it as empty.
1254 Init *PRMName = (*it)->getValueInit("ParserMethod");
1255 if (StringInit *SI = dyn_cast<StringInit>(PRMName))
1256 CI->ParserMethod = SI->getValue();
1258 // Get the diagnostic type or leave it as empty.
1259 // Get the parse method name or leave it as empty.
1260 Init *DiagnosticType = (*it)->getValueInit("DiagnosticType");
1261 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
1262 CI->DiagnosticType = SI->getValue();
1264 AsmOperandClasses[*it] = CI;
1265 Classes.push_back(CI);
1269 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1270 CodeGenTarget &target,
1271 RecordKeeper &records)
1272 : Records(records), AsmParser(asmParser), Target(target) {
1275 /// buildOperandMatchInfo - Build the necessary information to handle user
1276 /// defined operand parsing methods.
1277 void AsmMatcherInfo::buildOperandMatchInfo() {
1279 /// Map containing a mask with all operands indices that can be found for
1280 /// that class inside a instruction.
1281 typedef std::map<ClassInfo *, unsigned, less_ptr<ClassInfo>> OpClassMaskTy;
1282 OpClassMaskTy OpClassMask;
1284 for (std::vector<MatchableInfo*>::const_iterator it =
1285 Matchables.begin(), ie = Matchables.end();
1287 MatchableInfo &II = **it;
1288 OpClassMask.clear();
1290 // Keep track of all operands of this instructions which belong to the
1292 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
1293 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
1294 if (Op.Class->ParserMethod.empty())
1296 unsigned &OperandMask = OpClassMask[Op.Class];
1297 OperandMask |= (1 << i);
1300 // Generate operand match info for each mnemonic/operand class pair.
1301 for (OpClassMaskTy::iterator iit = OpClassMask.begin(),
1302 iie = OpClassMask.end(); iit != iie; ++iit) {
1303 unsigned OpMask = iit->second;
1304 ClassInfo *CI = iit->first;
1305 OperandMatchInfo.push_back(OperandMatchEntry::create(&II, CI, OpMask));
1310 void AsmMatcherInfo::buildInfo() {
1311 // Build information about all of the AssemblerPredicates.
1312 std::vector<Record*> AllPredicates =
1313 Records.getAllDerivedDefinitions("Predicate");
1314 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
1315 Record *Pred = AllPredicates[i];
1316 // Ignore predicates that are not intended for the assembler.
1317 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
1320 if (Pred->getName().empty())
1321 PrintFatalError(Pred->getLoc(), "Predicate has no name!");
1323 unsigned FeatureNo = SubtargetFeatures.size();
1324 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
1325 assert(FeatureNo < 32 && "Too many subtarget features!");
1328 // Parse the instructions; we need to do this first so that we can gather the
1329 // singleton register classes.
1330 SmallPtrSet<Record*, 16> SingletonRegisters;
1331 unsigned VariantCount = Target.getAsmParserVariantCount();
1332 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1333 Record *AsmVariant = Target.getAsmParserVariant(VC);
1334 std::string CommentDelimiter =
1335 AsmVariant->getValueAsString("CommentDelimiter");
1336 std::string RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
1337 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
1339 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
1340 E = Target.inst_end(); I != E; ++I) {
1341 const CodeGenInstruction &CGI = **I;
1343 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1344 // filter the set of instructions we consider.
1345 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
1348 // Ignore "codegen only" instructions.
1349 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
1352 std::unique_ptr<MatchableInfo> II(new MatchableInfo(CGI));
1354 II->initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
1356 // Ignore instructions which shouldn't be matched and diagnose invalid
1357 // instruction definitions with an error.
1358 if (!II->validate(CommentDelimiter, true))
1361 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
1363 // FIXME: This is a total hack.
1364 if (StringRef(II->TheDef->getName()).startswith("Int_") ||
1365 StringRef(II->TheDef->getName()).endswith("_Int"))
1368 Matchables.push_back(II.release());
1371 // Parse all of the InstAlias definitions and stick them in the list of
1373 std::vector<Record*> AllInstAliases =
1374 Records.getAllDerivedDefinitions("InstAlias");
1375 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
1376 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i], Target);
1378 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1379 // filter the set of instruction aliases we consider, based on the target
1381 if (!StringRef(Alias->ResultInst->TheDef->getName())
1382 .startswith( MatchPrefix))
1385 std::unique_ptr<MatchableInfo> II(new MatchableInfo(Alias));
1387 II->initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
1389 // Validate the alias definitions.
1390 II->validate(CommentDelimiter, false);
1392 Matchables.push_back(II.release());
1396 // Build info for the register classes.
1397 buildRegisterClasses(SingletonRegisters);
1399 // Build info for the user defined assembly operand classes.
1400 buildOperandClasses();
1402 // Build the information about matchables, now that we have fully formed
1404 std::vector<MatchableInfo*> NewMatchables;
1405 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(),
1406 ie = Matchables.end(); it != ie; ++it) {
1407 MatchableInfo *II = *it;
1409 // Parse the tokens after the mnemonic.
1410 // Note: buildInstructionOperandReference may insert new AsmOperands, so
1411 // don't precompute the loop bound.
1412 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1413 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
1414 StringRef Token = Op.Token;
1416 // Check for singleton registers.
1417 if (Record *RegRecord = II->AsmOperands[i].SingletonReg) {
1418 Op.Class = RegisterClasses[RegRecord];
1419 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1420 "Unexpected class for singleton register");
1424 // Check for simple tokens.
1425 if (Token[0] != '$') {
1426 Op.Class = getTokenClass(Token);
1430 if (Token.size() > 1 && isdigit(Token[1])) {
1431 Op.Class = getTokenClass(Token);
1435 // Otherwise this is an operand reference.
1436 StringRef OperandName;
1437 if (Token[1] == '{')
1438 OperandName = Token.substr(2, Token.size() - 3);
1440 OperandName = Token.substr(1);
1442 if (II->DefRec.is<const CodeGenInstruction*>())
1443 buildInstructionOperandReference(II, OperandName, i);
1445 buildAliasOperandReference(II, OperandName, Op);
1448 if (II->DefRec.is<const CodeGenInstruction*>()) {
1449 II->buildInstructionResultOperands();
1450 // If the instruction has a two-operand alias, build up the
1451 // matchable here. We'll add them in bulk at the end to avoid
1452 // confusing this loop.
1453 std::string Constraint =
1454 II->TheDef->getValueAsString("TwoOperandAliasConstraint");
1455 if (Constraint != "") {
1456 // Start by making a copy of the original matchable.
1457 std::unique_ptr<MatchableInfo> AliasII(new MatchableInfo(*II));
1459 // Adjust it to be a two-operand alias.
1460 AliasII->formTwoOperandAlias(Constraint);
1462 // Add the alias to the matchables list.
1463 NewMatchables.push_back(AliasII.release());
1466 II->buildAliasResultOperands();
1468 if (!NewMatchables.empty())
1469 Matchables.insert(Matchables.end(), NewMatchables.begin(),
1470 NewMatchables.end());
1472 // Process token alias definitions and set up the associated superclass
1474 std::vector<Record*> AllTokenAliases =
1475 Records.getAllDerivedDefinitions("TokenAlias");
1476 for (unsigned i = 0, e = AllTokenAliases.size(); i != e; ++i) {
1477 Record *Rec = AllTokenAliases[i];
1478 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1479 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
1480 if (FromClass == ToClass)
1481 PrintFatalError(Rec->getLoc(),
1482 "error: Destination value identical to source value.");
1483 FromClass->SuperClasses.push_back(ToClass);
1486 // Reorder classes so that classes precede super classes.
1487 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
1490 /// buildInstructionOperandReference - The specified operand is a reference to a
1491 /// named operand such as $src. Resolve the Class and OperandInfo pointers.
1492 void AsmMatcherInfo::
1493 buildInstructionOperandReference(MatchableInfo *II,
1494 StringRef OperandName,
1495 unsigned AsmOpIdx) {
1496 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1497 const CGIOperandList &Operands = CGI.Operands;
1498 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
1500 // Map this token to an operand.
1502 if (!Operands.hasOperandNamed(OperandName, Idx))
1503 PrintFatalError(II->TheDef->getLoc(),
1504 "error: unable to find operand: '" + OperandName + "'");
1506 // If the instruction operand has multiple suboperands, but the parser
1507 // match class for the asm operand is still the default "ImmAsmOperand",
1508 // then handle each suboperand separately.
1509 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1510 Record *Rec = Operands[Idx].Rec;
1511 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1512 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1513 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1514 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1515 StringRef Token = Op->Token; // save this in case Op gets moved
1516 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1517 MatchableInfo::AsmOperand NewAsmOp(Token);
1518 NewAsmOp.SubOpIdx = SI;
1519 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1521 // Replace Op with first suboperand.
1522 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1527 // Set up the operand class.
1528 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
1530 // If the named operand is tied, canonicalize it to the untied operand.
1531 // For example, something like:
1532 // (outs GPR:$dst), (ins GPR:$src)
1533 // with an asmstring of
1535 // we want to canonicalize to:
1537 // so that we know how to provide the $dst operand when filling in the result.
1539 if (Operands[Idx].MINumOperands == 1)
1540 OITied = Operands[Idx].getTiedRegister();
1542 // The tied operand index is an MIOperand index, find the operand that
1544 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1545 OperandName = Operands[Idx.first].Name;
1546 Op->SubOpIdx = Idx.second;
1549 Op->SrcOpName = OperandName;
1552 /// buildAliasOperandReference - When parsing an operand reference out of the
1553 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1554 /// operand reference is by looking it up in the result pattern definition.
1555 void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
1556 StringRef OperandName,
1557 MatchableInfo::AsmOperand &Op) {
1558 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
1560 // Set up the operand class.
1561 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
1562 if (CGA.ResultOperands[i].isRecord() &&
1563 CGA.ResultOperands[i].getName() == OperandName) {
1564 // It's safe to go with the first one we find, because CodeGenInstAlias
1565 // validates that all operands with the same name have the same record.
1566 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
1567 // Use the match class from the Alias definition, not the
1568 // destination instruction, as we may have an immediate that's
1569 // being munged by the match class.
1570 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
1572 Op.SrcOpName = OperandName;
1576 PrintFatalError(II->TheDef->getLoc(),
1577 "error: unable to find operand: '" + OperandName + "'");
1580 void MatchableInfo::buildInstructionResultOperands() {
1581 const CodeGenInstruction *ResultInst = getResultInst();
1583 // Loop over all operands of the result instruction, determining how to
1585 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1586 const CGIOperandList::OperandInfo &OpInfo = ResultInst->Operands[i];
1588 // If this is a tied operand, just copy from the previously handled operand.
1590 if (OpInfo.MINumOperands == 1)
1591 TiedOp = OpInfo.getTiedRegister();
1593 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1597 // Find out what operand from the asmparser this MCInst operand comes from.
1598 int SrcOperand = findAsmOperandNamed(OpInfo.Name);
1599 if (OpInfo.Name.empty() || SrcOperand == -1) {
1600 // This may happen for operands that are tied to a suboperand of a
1601 // complex operand. Simply use a dummy value here; nobody should
1602 // use this operand slot.
1603 // FIXME: The long term goal is for the MCOperand list to not contain
1604 // tied operands at all.
1605 ResOperands.push_back(ResOperand::getImmOp(0));
1609 // Check if the one AsmOperand populates the entire operand.
1610 unsigned NumOperands = OpInfo.MINumOperands;
1611 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1612 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
1616 // Add a separate ResOperand for each suboperand.
1617 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1618 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1619 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1620 "unexpected AsmOperands for suboperands");
1621 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1626 void MatchableInfo::buildAliasResultOperands() {
1627 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1628 const CodeGenInstruction *ResultInst = getResultInst();
1630 // Loop over all operands of the result instruction, determining how to
1632 unsigned AliasOpNo = 0;
1633 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
1634 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1635 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
1637 // If this is a tied operand, just copy from the previously handled operand.
1639 if (OpInfo->MINumOperands == 1)
1640 TiedOp = OpInfo->getTiedRegister();
1642 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1646 // Handle all the suboperands for this operand.
1647 const std::string &OpName = OpInfo->Name;
1648 for ( ; AliasOpNo < LastOpNo &&
1649 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1650 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1652 // Find out what operand from the asmparser that this MCInst operand
1654 switch (CGA.ResultOperands[AliasOpNo].Kind) {
1655 case CodeGenInstAlias::ResultOperand::K_Record: {
1656 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1657 int SrcOperand = findAsmOperand(Name, SubIdx);
1658 if (SrcOperand == -1)
1659 PrintFatalError(TheDef->getLoc(), "Instruction '" +
1660 TheDef->getName() + "' has operand '" + OpName +
1661 "' that doesn't appear in asm string!");
1662 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1663 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1667 case CodeGenInstAlias::ResultOperand::K_Imm: {
1668 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1669 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1672 case CodeGenInstAlias::ResultOperand::K_Reg: {
1673 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1674 ResOperands.push_back(ResOperand::getRegOp(Reg));
1682 static unsigned getConverterOperandID(const std::string &Name,
1683 SetVector<std::string> &Table,
1685 IsNew = Table.insert(Name);
1687 unsigned ID = IsNew ? Table.size() - 1 :
1688 std::find(Table.begin(), Table.end(), Name) - Table.begin();
1690 assert(ID < Table.size());
1696 static void emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName,
1697 std::vector<MatchableInfo*> &Infos,
1699 SetVector<std::string> OperandConversionKinds;
1700 SetVector<std::string> InstructionConversionKinds;
1701 std::vector<std::vector<uint8_t> > ConversionTable;
1702 size_t MaxRowLength = 2; // minimum is custom converter plus terminator.
1704 // TargetOperandClass - This is the target's operand class, like X86Operand.
1705 std::string TargetOperandClass = Target.getName() + "Operand";
1707 // Write the convert function to a separate stream, so we can drop it after
1708 // the enum. We'll build up the conversion handlers for the individual
1709 // operand types opportunistically as we encounter them.
1710 std::string ConvertFnBody;
1711 raw_string_ostream CvtOS(ConvertFnBody);
1712 // Start the unified conversion function.
1713 CvtOS << "void " << Target.getName() << ClassName << "::\n"
1714 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1715 << "unsigned Opcode,\n"
1716 << " const SmallVectorImpl<MCParsedAsmOperand*"
1717 << "> &Operands) {\n"
1718 << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
1719 << " const uint8_t *Converter = ConversionTable[Kind];\n"
1720 << " Inst.setOpcode(Opcode);\n"
1721 << " for (const uint8_t *p = Converter; *p; p+= 2) {\n"
1722 << " switch (*p) {\n"
1723 << " default: llvm_unreachable(\"invalid conversion entry!\");\n"
1724 << " case CVT_Reg:\n"
1725 << " static_cast<" << TargetOperandClass
1726 << "*>(Operands[*(p + 1)])->addRegOperands(Inst, 1);\n"
1728 << " case CVT_Tied:\n"
1729 << " Inst.addOperand(Inst.getOperand(*(p + 1)));\n"
1732 std::string OperandFnBody;
1733 raw_string_ostream OpOS(OperandFnBody);
1734 // Start the operand number lookup function.
1735 OpOS << "void " << Target.getName() << ClassName << "::\n"
1736 << "convertToMapAndConstraints(unsigned Kind,\n";
1738 OpOS << "const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {\n"
1739 << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
1740 << " unsigned NumMCOperands = 0;\n"
1741 << " const uint8_t *Converter = ConversionTable[Kind];\n"
1742 << " for (const uint8_t *p = Converter; *p; p+= 2) {\n"
1743 << " switch (*p) {\n"
1744 << " default: llvm_unreachable(\"invalid conversion entry!\");\n"
1745 << " case CVT_Reg:\n"
1746 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
1747 << " Operands[*(p + 1)]->setConstraint(\"r\");\n"
1748 << " ++NumMCOperands;\n"
1750 << " case CVT_Tied:\n"
1751 << " ++NumMCOperands;\n"
1754 // Pre-populate the operand conversion kinds with the standard always
1755 // available entries.
1756 OperandConversionKinds.insert("CVT_Done");
1757 OperandConversionKinds.insert("CVT_Reg");
1758 OperandConversionKinds.insert("CVT_Tied");
1759 enum { CVT_Done, CVT_Reg, CVT_Tied };
1761 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(),
1762 ie = Infos.end(); it != ie; ++it) {
1763 MatchableInfo &II = **it;
1765 // Check if we have a custom match function.
1766 std::string AsmMatchConverter =
1767 II.getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
1768 if (!AsmMatchConverter.empty()) {
1769 std::string Signature = "ConvertCustom_" + AsmMatchConverter;
1770 II.ConversionFnKind = Signature;
1772 // Check if we have already generated this signature.
1773 if (!InstructionConversionKinds.insert(Signature))
1776 // Remember this converter for the kind enum.
1777 unsigned KindID = OperandConversionKinds.size();
1778 OperandConversionKinds.insert("CVT_" +
1779 getEnumNameForToken(AsmMatchConverter));
1781 // Add the converter row for this instruction.
1782 ConversionTable.push_back(std::vector<uint8_t>());
1783 ConversionTable.back().push_back(KindID);
1784 ConversionTable.back().push_back(CVT_Done);
1786 // Add the handler to the conversion driver function.
1787 CvtOS << " case CVT_"
1788 << getEnumNameForToken(AsmMatchConverter) << ":\n"
1789 << " " << AsmMatchConverter << "(Inst, Operands);\n"
1792 // FIXME: Handle the operand number lookup for custom match functions.
1796 // Build the conversion function signature.
1797 std::string Signature = "Convert";
1799 std::vector<uint8_t> ConversionRow;
1801 // Compute the convert enum and the case body.
1802 MaxRowLength = std::max(MaxRowLength, II.ResOperands.size()*2 + 1 );
1804 for (unsigned i = 0, e = II.ResOperands.size(); i != e; ++i) {
1805 const MatchableInfo::ResOperand &OpInfo = II.ResOperands[i];
1807 // Generate code to populate each result operand.
1808 switch (OpInfo.Kind) {
1809 case MatchableInfo::ResOperand::RenderAsmOperand: {
1810 // This comes from something we parsed.
1811 MatchableInfo::AsmOperand &Op = II.AsmOperands[OpInfo.AsmOperandNum];
1813 // Registers are always converted the same, don't duplicate the
1814 // conversion function based on them.
1817 Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName;
1819 Signature += utostr(OpInfo.MINumOperands);
1820 Signature += "_" + itostr(OpInfo.AsmOperandNum);
1822 // Add the conversion kind, if necessary, and get the associated ID
1823 // the index of its entry in the vector).
1824 std::string Name = "CVT_" + (Op.Class->isRegisterClass() ? "Reg" :
1825 Op.Class->RenderMethod);
1826 Name = getEnumNameForToken(Name);
1828 bool IsNewConverter = false;
1829 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
1832 // Add the operand entry to the instruction kind conversion row.
1833 ConversionRow.push_back(ID);
1834 ConversionRow.push_back(OpInfo.AsmOperandNum + 1);
1836 if (!IsNewConverter)
1839 // This is a new operand kind. Add a handler for it to the
1840 // converter driver.
1841 CvtOS << " case " << Name << ":\n"
1842 << " static_cast<" << TargetOperandClass
1843 << "*>(Operands[*(p + 1)])->"
1844 << Op.Class->RenderMethod << "(Inst, " << OpInfo.MINumOperands
1848 // Add a handler for the operand number lookup.
1849 OpOS << " case " << Name << ":\n"
1850 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n";
1852 if (Op.Class->isRegisterClass())
1853 OpOS << " Operands[*(p + 1)]->setConstraint(\"r\");\n";
1855 OpOS << " Operands[*(p + 1)]->setConstraint(\"m\");\n";
1856 OpOS << " NumMCOperands += " << OpInfo.MINumOperands << ";\n"
1860 case MatchableInfo::ResOperand::TiedOperand: {
1861 // If this operand is tied to a previous one, just copy the MCInst
1862 // operand from the earlier one.We can only tie single MCOperand values.
1863 assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
1864 unsigned TiedOp = OpInfo.TiedOperandNum;
1865 assert(i > TiedOp && "Tied operand precedes its target!");
1866 Signature += "__Tie" + utostr(TiedOp);
1867 ConversionRow.push_back(CVT_Tied);
1868 ConversionRow.push_back(TiedOp);
1871 case MatchableInfo::ResOperand::ImmOperand: {
1872 int64_t Val = OpInfo.ImmVal;
1873 std::string Ty = "imm_" + itostr(Val);
1874 Signature += "__" + Ty;
1876 std::string Name = "CVT_" + Ty;
1877 bool IsNewConverter = false;
1878 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
1880 // Add the operand entry to the instruction kind conversion row.
1881 ConversionRow.push_back(ID);
1882 ConversionRow.push_back(0);
1884 if (!IsNewConverter)
1887 CvtOS << " case " << Name << ":\n"
1888 << " Inst.addOperand(MCOperand::CreateImm(" << Val << "));\n"
1891 OpOS << " case " << Name << ":\n"
1892 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
1893 << " Operands[*(p + 1)]->setConstraint(\"\");\n"
1894 << " ++NumMCOperands;\n"
1898 case MatchableInfo::ResOperand::RegOperand: {
1899 std::string Reg, Name;
1900 if (OpInfo.Register == 0) {
1904 Reg = getQualifiedName(OpInfo.Register);
1905 Name = "reg" + OpInfo.Register->getName();
1907 Signature += "__" + Name;
1908 Name = "CVT_" + Name;
1909 bool IsNewConverter = false;
1910 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
1912 // Add the operand entry to the instruction kind conversion row.
1913 ConversionRow.push_back(ID);
1914 ConversionRow.push_back(0);
1916 if (!IsNewConverter)
1918 CvtOS << " case " << Name << ":\n"
1919 << " Inst.addOperand(MCOperand::CreateReg(" << Reg << "));\n"
1922 OpOS << " case " << Name << ":\n"
1923 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
1924 << " Operands[*(p + 1)]->setConstraint(\"m\");\n"
1925 << " ++NumMCOperands;\n"
1931 // If there were no operands, add to the signature to that effect
1932 if (Signature == "Convert")
1933 Signature += "_NoOperands";
1935 II.ConversionFnKind = Signature;
1937 // Save the signature. If we already have it, don't add a new row
1939 if (!InstructionConversionKinds.insert(Signature))
1942 // Add the row to the table.
1943 ConversionTable.push_back(ConversionRow);
1946 // Finish up the converter driver function.
1947 CvtOS << " }\n }\n}\n\n";
1949 // Finish up the operand number lookup function.
1950 OpOS << " }\n }\n}\n\n";
1952 OS << "namespace {\n";
1954 // Output the operand conversion kind enum.
1955 OS << "enum OperatorConversionKind {\n";
1956 for (unsigned i = 0, e = OperandConversionKinds.size(); i != e; ++i)
1957 OS << " " << OperandConversionKinds[i] << ",\n";
1958 OS << " CVT_NUM_CONVERTERS\n";
1961 // Output the instruction conversion kind enum.
1962 OS << "enum InstructionConversionKind {\n";
1963 for (SetVector<std::string>::const_iterator
1964 i = InstructionConversionKinds.begin(),
1965 e = InstructionConversionKinds.end(); i != e; ++i)
1966 OS << " " << *i << ",\n";
1967 OS << " CVT_NUM_SIGNATURES\n";
1971 OS << "} // end anonymous namespace\n\n";
1973 // Output the conversion table.
1974 OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES]["
1975 << MaxRowLength << "] = {\n";
1977 for (unsigned Row = 0, ERow = ConversionTable.size(); Row != ERow; ++Row) {
1978 assert(ConversionTable[Row].size() % 2 == 0 && "bad conversion row!");
1979 OS << " // " << InstructionConversionKinds[Row] << "\n";
1981 for (unsigned i = 0, e = ConversionTable[Row].size(); i != e; i += 2)
1982 OS << OperandConversionKinds[ConversionTable[Row][i]] << ", "
1983 << (unsigned)(ConversionTable[Row][i + 1]) << ", ";
1984 OS << "CVT_Done },\n";
1989 // Spit out the conversion driver function.
1992 // Spit out the operand number lookup function.
1996 /// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
1997 static void emitMatchClassEnumeration(CodeGenTarget &Target,
1998 std::vector<ClassInfo*> &Infos,
2000 OS << "namespace {\n\n";
2002 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
2003 << "/// instruction matching.\n";
2004 OS << "enum MatchClassKind {\n";
2005 OS << " InvalidMatchClass = 0,\n";
2006 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
2007 ie = Infos.end(); it != ie; ++it) {
2008 ClassInfo &CI = **it;
2009 OS << " " << CI.Name << ", // ";
2010 if (CI.Kind == ClassInfo::Token) {
2011 OS << "'" << CI.ValueName << "'\n";
2012 } else if (CI.isRegisterClass()) {
2013 if (!CI.ValueName.empty())
2014 OS << "register class '" << CI.ValueName << "'\n";
2016 OS << "derived register class\n";
2018 OS << "user defined class '" << CI.ValueName << "'\n";
2021 OS << " NumMatchClassKinds\n";
2027 /// emitValidateOperandClass - Emit the function to validate an operand class.
2028 static void emitValidateOperandClass(AsmMatcherInfo &Info,
2030 OS << "static unsigned validateOperandClass(MCParsedAsmOperand *GOp, "
2031 << "MatchClassKind Kind) {\n";
2032 OS << " " << Info.Target.getName() << "Operand &Operand = *("
2033 << Info.Target.getName() << "Operand*)GOp;\n";
2035 // The InvalidMatchClass is not to match any operand.
2036 OS << " if (Kind == InvalidMatchClass)\n";
2037 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n\n";
2039 // Check for Token operands first.
2040 // FIXME: Use a more specific diagnostic type.
2041 OS << " if (Operand.isToken())\n";
2042 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
2043 << " MCTargetAsmParser::Match_Success :\n"
2044 << " MCTargetAsmParser::Match_InvalidOperand;\n\n";
2046 // Check the user classes. We don't care what order since we're only
2047 // actually matching against one of them.
2048 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
2049 ie = Info.Classes.end(); it != ie; ++it) {
2050 ClassInfo &CI = **it;
2052 if (!CI.isUserClass())
2055 OS << " // '" << CI.ClassName << "' class\n";
2056 OS << " if (Kind == " << CI.Name << ") {\n";
2057 OS << " if (Operand." << CI.PredicateMethod << "())\n";
2058 OS << " return MCTargetAsmParser::Match_Success;\n";
2059 if (!CI.DiagnosticType.empty())
2060 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
2061 << CI.DiagnosticType << ";\n";
2065 // Check for register operands, including sub-classes.
2066 OS << " if (Operand.isReg()) {\n";
2067 OS << " MatchClassKind OpKind;\n";
2068 OS << " switch (Operand.getReg()) {\n";
2069 OS << " default: OpKind = InvalidMatchClass; break;\n";
2070 for (AsmMatcherInfo::RegisterClassesTy::iterator
2071 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
2073 OS << " case " << Info.Target.getName() << "::"
2074 << it->first->getName() << ": OpKind = " << it->second->Name
2077 OS << " return isSubclass(OpKind, Kind) ? "
2078 << "MCTargetAsmParser::Match_Success :\n "
2079 << " MCTargetAsmParser::Match_InvalidOperand;\n }\n\n";
2081 // Generic fallthrough match failure case for operands that don't have
2082 // specialized diagnostic types.
2083 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2087 /// emitIsSubclass - Emit the subclass predicate function.
2088 static void emitIsSubclass(CodeGenTarget &Target,
2089 std::vector<ClassInfo*> &Infos,
2091 OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n";
2092 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
2093 OS << " if (A == B)\n";
2094 OS << " return true;\n\n";
2097 raw_string_ostream SS(OStr);
2099 SS << " switch (A) {\n";
2100 SS << " default:\n";
2101 SS << " return false;\n";
2102 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
2103 ie = Infos.end(); it != ie; ++it) {
2104 ClassInfo &A = **it;
2106 std::vector<StringRef> SuperClasses;
2107 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
2108 ie = Infos.end(); it != ie; ++it) {
2109 ClassInfo &B = **it;
2111 if (&A != &B && A.isSubsetOf(B))
2112 SuperClasses.push_back(B.Name);
2115 if (SuperClasses.empty())
2119 SS << "\n case " << A.Name << ":\n";
2121 if (SuperClasses.size() == 1) {
2122 SS << " return B == " << SuperClasses.back().str() << ";\n";
2126 if (!SuperClasses.empty()) {
2127 SS << " switch (B) {\n";
2128 SS << " default: return false;\n";
2129 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
2130 SS << " case " << SuperClasses[i].str() << ": return true;\n";
2133 // No case statement to emit
2134 SS << " return false;\n";
2139 // If there were case statements emitted into the string stream, write them
2140 // to the output stream, otherwise write the default.
2144 OS << " return false;\n";
2149 /// emitMatchTokenString - Emit the function to match a token string to the
2150 /// appropriate match class value.
2151 static void emitMatchTokenString(CodeGenTarget &Target,
2152 std::vector<ClassInfo*> &Infos,
2154 // Construct the match list.
2155 std::vector<StringMatcher::StringPair> Matches;
2156 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
2157 ie = Infos.end(); it != ie; ++it) {
2158 ClassInfo &CI = **it;
2160 if (CI.Kind == ClassInfo::Token)
2161 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
2162 "return " + CI.Name + ";"));
2165 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
2167 StringMatcher("Name", Matches, OS).Emit();
2169 OS << " return InvalidMatchClass;\n";
2173 /// emitMatchRegisterName - Emit the function to match a string to the target
2174 /// specific register enum.
2175 static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
2177 // Construct the match list.
2178 std::vector<StringMatcher::StringPair> Matches;
2179 const std::vector<CodeGenRegister*> &Regs =
2180 Target.getRegBank().getRegisters();
2181 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
2182 const CodeGenRegister *Reg = Regs[i];
2183 if (Reg->TheDef->getValueAsString("AsmName").empty())
2186 Matches.push_back(StringMatcher::StringPair(
2187 Reg->TheDef->getValueAsString("AsmName"),
2188 "return " + utostr(Reg->EnumValue) + ";"));
2191 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
2193 StringMatcher("Name", Matches, OS).Emit();
2195 OS << " return 0;\n";
2199 /// emitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
2201 static void emitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
2203 OS << "// Flags for subtarget features that participate in "
2204 << "instruction matching.\n";
2205 OS << "enum SubtargetFeatureFlag {\n";
2206 for (std::map<Record*, SubtargetFeatureInfo*, LessRecordByID>::const_iterator
2207 it = Info.SubtargetFeatures.begin(),
2208 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
2209 SubtargetFeatureInfo &SFI = *it->second;
2210 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
2212 OS << " Feature_None = 0\n";
2216 /// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
2217 static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) {
2218 // Get the set of diagnostic types from all of the operand classes.
2219 std::set<StringRef> Types;
2220 for (std::map<Record*, ClassInfo*>::const_iterator
2221 I = Info.AsmOperandClasses.begin(),
2222 E = Info.AsmOperandClasses.end(); I != E; ++I) {
2223 if (!I->second->DiagnosticType.empty())
2224 Types.insert(I->second->DiagnosticType);
2227 if (Types.empty()) return;
2229 // Now emit the enum entries.
2230 for (std::set<StringRef>::const_iterator I = Types.begin(), E = Types.end();
2232 OS << " Match_" << *I << ",\n";
2233 OS << " END_OPERAND_DIAGNOSTIC_TYPES\n";
2236 /// emitGetSubtargetFeatureName - Emit the helper function to get the
2237 /// user-level name for a subtarget feature.
2238 static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
2239 OS << "// User-level names for subtarget features that participate in\n"
2240 << "// instruction matching.\n"
2241 << "static const char *getSubtargetFeatureName(unsigned Val) {\n";
2242 if (!Info.SubtargetFeatures.empty()) {
2243 OS << " switch(Val) {\n";
2244 typedef std::map<Record*, SubtargetFeatureInfo*, LessRecordByID> RecFeatMap;
2245 for (RecFeatMap::const_iterator it = Info.SubtargetFeatures.begin(),
2246 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
2247 SubtargetFeatureInfo &SFI = *it->second;
2248 // FIXME: Totally just a placeholder name to get the algorithm working.
2249 OS << " case " << SFI.getEnumName() << ": return \""
2250 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
2252 OS << " default: return \"(unknown)\";\n";
2255 // Nothing to emit, so skip the switch
2256 OS << " return \"(unknown)\";\n";
2261 /// emitComputeAvailableFeatures - Emit the function to compute the list of
2262 /// available features given a subtarget.
2263 static void emitComputeAvailableFeatures(AsmMatcherInfo &Info,
2265 std::string ClassName =
2266 Info.AsmParser->getValueAsString("AsmParserClassName");
2268 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
2269 << "ComputeAvailableFeatures(uint64_t FB) const {\n";
2270 OS << " unsigned Features = 0;\n";
2271 for (std::map<Record*, SubtargetFeatureInfo*, LessRecordByID>::const_iterator
2272 it = Info.SubtargetFeatures.begin(),
2273 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
2274 SubtargetFeatureInfo &SFI = *it->second;
2277 std::string CondStorage =
2278 SFI.TheDef->getValueAsString("AssemblerCondString");
2279 StringRef Conds = CondStorage;
2280 std::pair<StringRef,StringRef> Comma = Conds.split(',');
2287 StringRef Cond = Comma.first;
2288 if (Cond[0] == '!') {
2290 Cond = Cond.substr(1);
2293 OS << "((FB & " << Info.Target.getName() << "::" << Cond << ")";
2300 if (Comma.second.empty())
2304 Comma = Comma.second.split(',');
2308 OS << " Features |= " << SFI.getEnumName() << ";\n";
2310 OS << " return Features;\n";
2314 static std::string GetAliasRequiredFeatures(Record *R,
2315 const AsmMatcherInfo &Info) {
2316 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
2318 unsigned NumFeatures = 0;
2319 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
2320 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
2323 PrintFatalError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
2324 "' is not marked as an AssemblerPredicate!");
2329 Result += F->getEnumName();
2333 if (NumFeatures > 1)
2334 Result = '(' + Result + ')';
2338 static void emitMnemonicAliasVariant(raw_ostream &OS,const AsmMatcherInfo &Info,
2339 std::vector<Record*> &Aliases,
2340 unsigned Indent = 0,
2341 StringRef AsmParserVariantName = StringRef()){
2342 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
2343 // iteration order of the map is stable.
2344 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
2346 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
2347 Record *R = Aliases[i];
2348 // FIXME: Allow AssemblerVariantName to be a comma separated list.
2349 std::string AsmVariantName = R->getValueAsString("AsmVariantName");
2350 if (AsmVariantName != AsmParserVariantName)
2352 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
2354 if (AliasesFromMnemonic.empty())
2357 // Process each alias a "from" mnemonic at a time, building the code executed
2358 // by the string remapper.
2359 std::vector<StringMatcher::StringPair> Cases;
2360 for (std::map<std::string, std::vector<Record*> >::iterator
2361 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
2363 const std::vector<Record*> &ToVec = I->second;
2365 // Loop through each alias and emit code that handles each case. If there
2366 // are two instructions without predicates, emit an error. If there is one,
2368 std::string MatchCode;
2369 int AliasWithNoPredicate = -1;
2371 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
2372 Record *R = ToVec[i];
2373 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
2375 // If this unconditionally matches, remember it for later and diagnose
2377 if (FeatureMask.empty()) {
2378 if (AliasWithNoPredicate != -1) {
2379 // We can't have two aliases from the same mnemonic with no predicate.
2380 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
2381 "two MnemonicAliases with the same 'from' mnemonic!");
2382 PrintFatalError(R->getLoc(), "this is the other MnemonicAlias.");
2385 AliasWithNoPredicate = i;
2388 if (R->getValueAsString("ToMnemonic") == I->first)
2389 PrintFatalError(R->getLoc(), "MnemonicAlias to the same string");
2391 if (!MatchCode.empty())
2392 MatchCode += "else ";
2393 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
2394 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
2397 if (AliasWithNoPredicate != -1) {
2398 Record *R = ToVec[AliasWithNoPredicate];
2399 if (!MatchCode.empty())
2400 MatchCode += "else\n ";
2401 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
2404 MatchCode += "return;";
2406 Cases.push_back(std::make_pair(I->first, MatchCode));
2408 StringMatcher("Mnemonic", Cases, OS).Emit(Indent);
2411 /// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
2412 /// emit a function for them and return true, otherwise return false.
2413 static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info,
2414 CodeGenTarget &Target) {
2415 // Ignore aliases when match-prefix is set.
2416 if (!MatchPrefix.empty())
2419 std::vector<Record*> Aliases =
2420 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
2421 if (Aliases.empty()) return false;
2423 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
2424 "unsigned Features, unsigned VariantID) {\n";
2425 OS << " switch (VariantID) {\n";
2426 unsigned VariantCount = Target.getAsmParserVariantCount();
2427 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2428 Record *AsmVariant = Target.getAsmParserVariant(VC);
2429 int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant");
2430 std::string AsmParserVariantName = AsmVariant->getValueAsString("Name");
2431 OS << " case " << AsmParserVariantNo << ":\n";
2432 emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2,
2433 AsmParserVariantName);
2438 // Emit aliases that apply to all variants.
2439 emitMnemonicAliasVariant(OS, Info, Aliases);
2446 static const char *getMinimalTypeForRange(uint64_t Range) {
2447 assert(Range < 0xFFFFFFFFULL && "Enum too large");
2455 static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
2456 const AsmMatcherInfo &Info, StringRef ClassName,
2457 StringToOffsetTable &StringTable,
2458 unsigned MaxMnemonicIndex) {
2459 unsigned MaxMask = 0;
2460 for (std::vector<OperandMatchEntry>::const_iterator it =
2461 Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end();
2463 MaxMask |= it->OperandMask;
2466 // Emit the static custom operand parsing table;
2467 OS << "namespace {\n";
2468 OS << " struct OperandMatchEntry {\n";
2469 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2470 << " RequiredFeatures;\n";
2471 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
2473 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2475 OS << " " << getMinimalTypeForRange(MaxMask)
2476 << " OperandMask;\n\n";
2477 OS << " StringRef getMnemonic() const {\n";
2478 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2479 OS << " MnemonicTable[Mnemonic]);\n";
2483 OS << " // Predicate for searching for an opcode.\n";
2484 OS << " struct LessOpcodeOperand {\n";
2485 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
2486 OS << " return LHS.getMnemonic() < RHS;\n";
2488 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
2489 OS << " return LHS < RHS.getMnemonic();\n";
2491 OS << " bool operator()(const OperandMatchEntry &LHS,";
2492 OS << " const OperandMatchEntry &RHS) {\n";
2493 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
2497 OS << "} // end anonymous namespace.\n\n";
2499 OS << "static const OperandMatchEntry OperandMatchTable["
2500 << Info.OperandMatchInfo.size() << "] = {\n";
2502 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
2503 for (std::vector<OperandMatchEntry>::const_iterator it =
2504 Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end();
2506 const OperandMatchEntry &OMI = *it;
2507 const MatchableInfo &II = *OMI.MI;
2511 // Write the required features mask.
2512 if (!II.RequiredFeatures.empty()) {
2513 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2515 OS << II.RequiredFeatures[i]->getEnumName();
2520 // Store a pascal-style length byte in the mnemonic.
2521 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2522 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2523 << " /* " << II.Mnemonic << " */, ";
2527 OS << ", " << OMI.OperandMask;
2529 bool printComma = false;
2530 for (int i = 0, e = 31; i !=e; ++i)
2531 if (OMI.OperandMask & (1 << i)) {
2543 // Emit the operand class switch to call the correct custom parser for
2544 // the found operand class.
2545 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2546 << Target.getName() << ClassName << "::\n"
2547 << "tryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>"
2548 << " &Operands,\n unsigned MCK) {\n\n"
2549 << " switch(MCK) {\n";
2551 for (std::vector<ClassInfo*>::const_iterator it = Info.Classes.begin(),
2552 ie = Info.Classes.end(); it != ie; ++it) {
2553 ClassInfo *CI = *it;
2554 if (CI->ParserMethod.empty())
2556 OS << " case " << CI->Name << ":\n"
2557 << " return " << CI->ParserMethod << "(Operands);\n";
2560 OS << " default:\n";
2561 OS << " return MatchOperand_NoMatch;\n";
2563 OS << " return MatchOperand_NoMatch;\n";
2566 // Emit the static custom operand parser. This code is very similar with
2567 // the other matcher. Also use MatchResultTy here just in case we go for
2568 // a better error handling.
2569 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2570 << Target.getName() << ClassName << "::\n"
2571 << "MatchOperandParserImpl(SmallVectorImpl<MCParsedAsmOperand*>"
2572 << " &Operands,\n StringRef Mnemonic) {\n";
2574 // Emit code to get the available features.
2575 OS << " // Get the current feature set.\n";
2576 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2578 OS << " // Get the next operand index.\n";
2579 OS << " unsigned NextOpNum = Operands.size()-1;\n";
2581 // Emit code to search the table.
2582 OS << " // Search the table.\n";
2583 OS << " std::pair<const OperandMatchEntry*, const OperandMatchEntry*>";
2584 OS << " MnemonicRange =\n";
2585 OS << " std::equal_range(OperandMatchTable, OperandMatchTable+"
2586 << Info.OperandMatchInfo.size() << ", Mnemonic,\n"
2587 << " LessOpcodeOperand());\n\n";
2589 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2590 OS << " return MatchOperand_NoMatch;\n\n";
2592 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2593 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2595 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2596 OS << " assert(Mnemonic == it->getMnemonic());\n\n";
2598 // Emit check that the required features are available.
2599 OS << " // check if the available features match\n";
2600 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2601 << "!= it->RequiredFeatures) {\n";
2602 OS << " continue;\n";
2605 // Emit check to ensure the operand number matches.
2606 OS << " // check if the operand in question has a custom parser.\n";
2607 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2608 OS << " continue;\n\n";
2610 // Emit call to the custom parser method
2611 OS << " // call custom parse method to handle the operand\n";
2612 OS << " OperandMatchResultTy Result = ";
2613 OS << "tryCustomParseOperand(Operands, it->Class);\n";
2614 OS << " if (Result != MatchOperand_NoMatch)\n";
2615 OS << " return Result;\n";
2618 OS << " // Okay, we had no match.\n";
2619 OS << " return MatchOperand_NoMatch;\n";
2623 void AsmMatcherEmitter::run(raw_ostream &OS) {
2624 CodeGenTarget Target(Records);
2625 Record *AsmParser = Target.getAsmParser();
2626 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2628 // Compute the information on the instructions to match.
2629 AsmMatcherInfo Info(AsmParser, Target, Records);
2632 // Sort the instruction table using the partial order on classes. We use
2633 // stable_sort to ensure that ambiguous instructions are still
2634 // deterministically ordered.
2635 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2636 less_ptr<MatchableInfo>());
2638 DEBUG_WITH_TYPE("instruction_info", {
2639 for (std::vector<MatchableInfo*>::iterator
2640 it = Info.Matchables.begin(), ie = Info.Matchables.end();
2645 // Check for ambiguous matchables.
2646 DEBUG_WITH_TYPE("ambiguous_instrs", {
2647 unsigned NumAmbiguous = 0;
2648 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) {
2649 for (unsigned j = i + 1; j != e; ++j) {
2650 MatchableInfo &A = *Info.Matchables[i];
2651 MatchableInfo &B = *Info.Matchables[j];
2653 if (A.couldMatchAmbiguouslyWith(B)) {
2654 errs() << "warning: ambiguous matchables:\n";
2656 errs() << "\nis incomparable with:\n";
2664 errs() << "warning: " << NumAmbiguous
2665 << " ambiguous matchables!\n";
2668 // Compute the information on the custom operand parsing.
2669 Info.buildOperandMatchInfo();
2671 // Write the output.
2673 // Information for the class declaration.
2674 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2675 OS << "#undef GET_ASSEMBLER_HEADER\n";
2676 OS << " // This should be included into the middle of the declaration of\n";
2677 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
2678 OS << " unsigned ComputeAvailableFeatures(uint64_t FeatureBits) const;\n";
2679 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
2680 << "unsigned Opcode,\n"
2681 << " const SmallVectorImpl<MCParsedAsmOperand*> "
2683 OS << " void convertToMapAndConstraints(unsigned Kind,\n ";
2684 OS << " const SmallVectorImpl<MCParsedAsmOperand*> &Operands) override;\n";
2685 OS << " bool mnemonicIsValid(StringRef Mnemonic, unsigned VariantID) override;\n";
2686 OS << " unsigned MatchInstructionImpl(\n";
2688 OS << "const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n"
2689 << " MCInst &Inst,\n"
2690 << " unsigned &ErrorInfo,"
2691 << " bool matchingInlineAsm,\n"
2692 << " unsigned VariantID = 0);\n";
2694 if (Info.OperandMatchInfo.size()) {
2695 OS << "\n enum OperandMatchResultTy {\n";
2696 OS << " MatchOperand_Success, // operand matched successfully\n";
2697 OS << " MatchOperand_NoMatch, // operand did not match\n";
2698 OS << " MatchOperand_ParseFail // operand matched but had errors\n";
2700 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
2701 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2702 OS << " StringRef Mnemonic);\n";
2704 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
2705 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2706 OS << " unsigned MCK);\n\n";
2709 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2711 // Emit the operand match diagnostic enum names.
2712 OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
2713 OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
2714 emitOperandDiagnosticTypes(Info, OS);
2715 OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
2718 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2719 OS << "#undef GET_REGISTER_MATCHER\n\n";
2721 // Emit the subtarget feature enumeration.
2722 emitSubtargetFeatureFlagEnumeration(Info, OS);
2724 // Emit the function to match a register name to number.
2725 // This should be omitted for Mips target
2726 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName"))
2727 emitMatchRegisterName(Target, AsmParser, OS);
2729 OS << "#endif // GET_REGISTER_MATCHER\n\n";
2731 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
2732 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
2734 // Generate the helper function to get the names for subtarget features.
2735 emitGetSubtargetFeatureName(Info, OS);
2737 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
2739 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2740 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
2742 // Generate the function that remaps for mnemonic aliases.
2743 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target);
2745 // Generate the convertToMCInst function to convert operands into an MCInst.
2746 // Also, generate the convertToMapAndConstraints function for MS-style inline
2747 // assembly. The latter doesn't actually generate a MCInst.
2748 emitConvertFuncs(Target, ClassName, Info.Matchables, OS);
2750 // Emit the enumeration for classes which participate in matching.
2751 emitMatchClassEnumeration(Target, Info.Classes, OS);
2753 // Emit the routine to match token strings to their match class.
2754 emitMatchTokenString(Target, Info.Classes, OS);
2756 // Emit the subclass predicate routine.
2757 emitIsSubclass(Target, Info.Classes, OS);
2759 // Emit the routine to validate an operand against a match class.
2760 emitValidateOperandClass(Info, OS);
2762 // Emit the available features compute function.
2763 emitComputeAvailableFeatures(Info, OS);
2766 StringToOffsetTable StringTable;
2768 size_t MaxNumOperands = 0;
2769 unsigned MaxMnemonicIndex = 0;
2770 bool HasDeprecation = false;
2771 for (std::vector<MatchableInfo*>::const_iterator it =
2772 Info.Matchables.begin(), ie = Info.Matchables.end();
2774 MatchableInfo &II = **it;
2775 MaxNumOperands = std::max(MaxNumOperands, II.AsmOperands.size());
2776 HasDeprecation |= II.HasDeprecation;
2778 // Store a pascal-style length byte in the mnemonic.
2779 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2780 MaxMnemonicIndex = std::max(MaxMnemonicIndex,
2781 StringTable.GetOrAddStringOffset(LenMnemonic, false));
2784 OS << "static const char *const MnemonicTable =\n";
2785 StringTable.EmitString(OS);
2788 // Emit the static match table; unused classes get initalized to 0 which is
2789 // guaranteed to be InvalidMatchClass.
2791 // FIXME: We can reduce the size of this table very easily. First, we change
2792 // it so that store the kinds in separate bit-fields for each index, which
2793 // only needs to be the max width used for classes at that index (we also need
2794 // to reject based on this during classification). If we then make sure to
2795 // order the match kinds appropriately (putting mnemonics last), then we
2796 // should only end up using a few bits for each class, especially the ones
2797 // following the mnemonic.
2798 OS << "namespace {\n";
2799 OS << " struct MatchEntry {\n";
2800 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
2802 OS << " uint16_t Opcode;\n";
2803 OS << " " << getMinimalTypeForRange(Info.Matchables.size())
2805 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2806 << " RequiredFeatures;\n";
2807 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2808 << " Classes[" << MaxNumOperands << "];\n";
2809 OS << " StringRef getMnemonic() const {\n";
2810 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2811 OS << " MnemonicTable[Mnemonic]);\n";
2815 OS << " // Predicate for searching for an opcode.\n";
2816 OS << " struct LessOpcode {\n";
2817 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
2818 OS << " return LHS.getMnemonic() < RHS;\n";
2820 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
2821 OS << " return LHS < RHS.getMnemonic();\n";
2823 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
2824 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
2828 OS << "} // end anonymous namespace.\n\n";
2830 unsigned VariantCount = Target.getAsmParserVariantCount();
2831 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2832 Record *AsmVariant = Target.getAsmParserVariant(VC);
2833 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
2835 OS << "static const MatchEntry MatchTable" << VC << "[] = {\n";
2837 for (std::vector<MatchableInfo*>::const_iterator it =
2838 Info.Matchables.begin(), ie = Info.Matchables.end();
2840 MatchableInfo &II = **it;
2841 if (II.AsmVariantID != AsmVariantNo)
2844 // Store a pascal-style length byte in the mnemonic.
2845 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2846 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2847 << " /* " << II.Mnemonic << " */, "
2848 << Target.getName() << "::"
2849 << II.getResultInst()->TheDef->getName() << ", "
2850 << II.ConversionFnKind << ", ";
2852 // Write the required features mask.
2853 if (!II.RequiredFeatures.empty()) {
2854 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2856 OS << II.RequiredFeatures[i]->getEnumName();
2862 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
2863 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
2866 OS << Op.Class->Name;
2874 // A method to determine if a mnemonic is in the list.
2875 OS << "bool " << Target.getName() << ClassName << "::\n"
2876 << "mnemonicIsValid(StringRef Mnemonic, unsigned VariantID) {\n";
2877 OS << " // Find the appropriate table for this asm variant.\n";
2878 OS << " const MatchEntry *Start, *End;\n";
2879 OS << " switch (VariantID) {\n";
2880 OS << " default: // unreachable\n";
2881 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2882 Record *AsmVariant = Target.getAsmParserVariant(VC);
2883 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
2884 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
2885 << "); End = std::end(MatchTable" << VC << "); break;\n";
2888 OS << " // Search the table.\n";
2889 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2890 OS << " std::equal_range(Start, End, Mnemonic, LessOpcode());\n";
2891 OS << " return MnemonicRange.first != MnemonicRange.second;\n";
2894 // Finally, build the match function.
2896 << Target.getName() << ClassName << "::\n"
2897 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
2899 OS << " MCInst &Inst,\n"
2900 << "unsigned &ErrorInfo, bool matchingInlineAsm, unsigned VariantID) {\n";
2902 OS << " // Eliminate obvious mismatches.\n";
2903 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
2904 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
2905 OS << " return Match_InvalidOperand;\n";
2908 // Emit code to get the available features.
2909 OS << " // Get the current feature set.\n";
2910 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2912 OS << " // Get the instruction mnemonic, which is the first token.\n";
2913 OS << " StringRef Mnemonic = ((" << Target.getName()
2914 << "Operand*)Operands[0])->getToken();\n\n";
2916 if (HasMnemonicAliases) {
2917 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
2918 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n";
2921 // Emit code to compute the class list for this operand vector.
2922 OS << " // Some state to try to produce better error messages.\n";
2923 OS << " bool HadMatchOtherThanFeatures = false;\n";
2924 OS << " bool HadMatchOtherThanPredicate = false;\n";
2925 OS << " unsigned RetCode = Match_InvalidOperand;\n";
2926 OS << " unsigned MissingFeatures = ~0U;\n";
2927 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
2928 OS << " // wrong for all instances of the instruction.\n";
2929 OS << " ErrorInfo = ~0U;\n";
2931 // Emit code to search the table.
2932 OS << " // Find the appropriate table for this asm variant.\n";
2933 OS << " const MatchEntry *Start, *End;\n";
2934 OS << " switch (VariantID) {\n";
2935 OS << " default: // unreachable\n";
2936 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2937 Record *AsmVariant = Target.getAsmParserVariant(VC);
2938 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
2939 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
2940 << "); End = std::end(MatchTable" << VC << "); break;\n";
2943 OS << " // Search the table.\n";
2944 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2945 OS << " std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
2947 OS << " // Return a more specific error code if no mnemonics match.\n";
2948 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2949 OS << " return Match_MnemonicFail;\n\n";
2951 OS << " for (const MatchEntry *it = MnemonicRange.first, "
2952 << "*ie = MnemonicRange.second;\n";
2953 OS << " it != ie; ++it) {\n";
2955 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2956 OS << " assert(Mnemonic == it->getMnemonic());\n";
2958 // Emit check that the subclasses match.
2959 OS << " bool OperandsValid = true;\n";
2960 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
2961 OS << " if (i + 1 >= Operands.size()) {\n";
2962 OS << " OperandsValid = (it->Classes[i] == " <<"InvalidMatchClass);\n";
2963 OS << " if (!OperandsValid) ErrorInfo = i + 1;\n";
2966 OS << " unsigned Diag = validateOperandClass(Operands[i+1],\n";
2968 OS << "(MatchClassKind)it->Classes[i]);\n";
2969 OS << " if (Diag == Match_Success)\n";
2970 OS << " continue;\n";
2971 OS << " // If the generic handler indicates an invalid operand\n";
2972 OS << " // failure, check for a special case.\n";
2973 OS << " if (Diag == Match_InvalidOperand) {\n";
2974 OS << " Diag = validateTargetOperandClass(Operands[i+1],\n";
2976 OS << "(MatchClassKind)it->Classes[i]);\n";
2977 OS << " if (Diag == Match_Success)\n";
2978 OS << " continue;\n";
2980 OS << " // If this operand is broken for all of the instances of this\n";
2981 OS << " // mnemonic, keep track of it so we can report loc info.\n";
2982 OS << " // If we already had a match that only failed due to a\n";
2983 OS << " // target predicate, that diagnostic is preferred.\n";
2984 OS << " if (!HadMatchOtherThanPredicate &&\n";
2985 OS << " (it == MnemonicRange.first || ErrorInfo <= i+1)) {\n";
2986 OS << " ErrorInfo = i+1;\n";
2987 OS << " // InvalidOperand is the default. Prefer specificity.\n";
2988 OS << " if (Diag != Match_InvalidOperand)\n";
2989 OS << " RetCode = Diag;\n";
2991 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
2992 OS << " OperandsValid = false;\n";
2996 OS << " if (!OperandsValid) continue;\n";
2998 // Emit check that the required features are available.
2999 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
3000 << "!= it->RequiredFeatures) {\n";
3001 OS << " HadMatchOtherThanFeatures = true;\n";
3002 OS << " unsigned NewMissingFeatures = it->RequiredFeatures & "
3003 "~AvailableFeatures;\n";
3004 OS << " if (CountPopulation_32(NewMissingFeatures) <=\n"
3005 " CountPopulation_32(MissingFeatures))\n";
3006 OS << " MissingFeatures = NewMissingFeatures;\n";
3007 OS << " continue;\n";
3010 OS << " if (matchingInlineAsm) {\n";
3011 OS << " Inst.setOpcode(it->Opcode);\n";
3012 OS << " convertToMapAndConstraints(it->ConvertFn, Operands);\n";
3013 OS << " return Match_Success;\n";
3015 OS << " // We have selected a definite instruction, convert the parsed\n"
3016 << " // operands into the appropriate MCInst.\n";
3017 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
3020 // Verify the instruction with the target-specific match predicate function.
3021 OS << " // We have a potential match. Check the target predicate to\n"
3022 << " // handle any context sensitive constraints.\n"
3023 << " unsigned MatchResult;\n"
3024 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
3025 << " Match_Success) {\n"
3026 << " Inst.clear();\n"
3027 << " RetCode = MatchResult;\n"
3028 << " HadMatchOtherThanPredicate = true;\n"
3032 // Call the post-processing function, if used.
3033 std::string InsnCleanupFn =
3034 AsmParser->getValueAsString("AsmParserInstCleanup");
3035 if (!InsnCleanupFn.empty())
3036 OS << " " << InsnCleanupFn << "(Inst);\n";
3038 if (HasDeprecation) {
3039 OS << " std::string Info;\n";
3040 OS << " if (MII.get(Inst.getOpcode()).getDeprecatedInfo(Inst, STI, Info)) {\n";
3041 OS << " SMLoc Loc = ((" << Target.getName() << "Operand*)Operands[0])->getStartLoc();\n";
3042 OS << " Parser.Warning(Loc, Info, None);\n";
3046 OS << " return Match_Success;\n";
3049 OS << " // Okay, we had no match. Try to return a useful error code.\n";
3050 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n";
3051 OS << " return RetCode;\n\n";
3052 OS << " // Missing feature matches return which features were missing\n";
3053 OS << " ErrorInfo = MissingFeatures;\n";
3054 OS << " return Match_MissingFeature;\n";
3057 if (Info.OperandMatchInfo.size())
3058 emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable,
3061 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
3066 void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
3067 emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
3068 AsmMatcherEmitter(RK).run(OS);
3071 } // End llvm namespace