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 valeus 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 "StringToOffsetTable.h"
101 #include "llvm/ADT/OwningPtr.h"
102 #include "llvm/ADT/PointerUnion.h"
103 #include "llvm/ADT/SmallPtrSet.h"
104 #include "llvm/ADT/SmallVector.h"
105 #include "llvm/ADT/STLExtras.h"
106 #include "llvm/ADT/StringExtras.h"
107 #include "llvm/Support/CommandLine.h"
108 #include "llvm/Support/Debug.h"
109 #include "llvm/Support/ErrorHandling.h"
110 #include "llvm/TableGen/Error.h"
111 #include "llvm/TableGen/Record.h"
112 #include "llvm/TableGen/StringMatcher.h"
113 #include "llvm/TableGen/TableGenBackend.h"
117 using namespace llvm;
119 static cl::opt<std::string>
120 MatchPrefix("match-prefix", cl::init(""),
121 cl::desc("Only match instructions with the given prefix"));
124 class AsmMatcherInfo;
125 struct SubtargetFeatureInfo;
127 class AsmMatcherEmitter {
128 RecordKeeper &Records;
130 AsmMatcherEmitter(RecordKeeper &R) : Records(R) {}
132 void run(raw_ostream &o);
135 /// ClassInfo - Helper class for storing the information about a particular
136 /// class of operands which can be matched.
139 /// Invalid kind, for use as a sentinel value.
142 /// The class for a particular token.
145 /// The (first) register class, subsequent register classes are
146 /// RegisterClass0+1, and so on.
149 /// The (first) user defined class, subsequent user defined classes are
150 /// UserClass0+1, and so on.
154 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
155 /// N) for the Nth user defined class.
158 /// SuperClasses - The super classes of this class. Note that for simplicities
159 /// sake user operands only record their immediate super class, while register
160 /// operands include all superclasses.
161 std::vector<ClassInfo*> SuperClasses;
163 /// Name - The full class name, suitable for use in an enum.
166 /// ClassName - The unadorned generic name for this class (e.g., Token).
167 std::string ClassName;
169 /// ValueName - The name of the value this class represents; for a token this
170 /// is the literal token string, for an operand it is the TableGen class (or
171 /// empty if this is a derived class).
172 std::string ValueName;
174 /// PredicateMethod - The name of the operand method to test whether the
175 /// operand matches this class; this is not valid for Token or register kinds.
176 std::string PredicateMethod;
178 /// RenderMethod - The name of the operand method to add this operand to an
179 /// MCInst; this is not valid for Token or register kinds.
180 std::string RenderMethod;
182 /// ParserMethod - The name of the operand method to do a target specific
183 /// parsing on the operand.
184 std::string ParserMethod;
186 /// For register classes, the records for all the registers in this class.
187 std::set<Record*> Registers;
189 /// For custom match classes, he diagnostic kind for when the predicate fails.
190 std::string DiagnosticType;
192 /// isRegisterClass() - Check if this is a register class.
193 bool isRegisterClass() const {
194 return Kind >= RegisterClass0 && Kind < UserClass0;
197 /// isUserClass() - Check if this is a user defined class.
198 bool isUserClass() const {
199 return Kind >= UserClass0;
202 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
203 /// are related if they are in the same class hierarchy.
204 bool isRelatedTo(const ClassInfo &RHS) const {
205 // Tokens are only related to tokens.
206 if (Kind == Token || RHS.Kind == Token)
207 return Kind == Token && RHS.Kind == Token;
209 // Registers classes are only related to registers classes, and only if
210 // their intersection is non-empty.
211 if (isRegisterClass() || RHS.isRegisterClass()) {
212 if (!isRegisterClass() || !RHS.isRegisterClass())
215 std::set<Record*> Tmp;
216 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
217 std::set_intersection(Registers.begin(), Registers.end(),
218 RHS.Registers.begin(), RHS.Registers.end(),
224 // Otherwise we have two users operands; they are related if they are in the
225 // same class hierarchy.
227 // FIXME: This is an oversimplification, they should only be related if they
228 // intersect, however we don't have that information.
229 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
230 const ClassInfo *Root = this;
231 while (!Root->SuperClasses.empty())
232 Root = Root->SuperClasses.front();
234 const ClassInfo *RHSRoot = &RHS;
235 while (!RHSRoot->SuperClasses.empty())
236 RHSRoot = RHSRoot->SuperClasses.front();
238 return Root == RHSRoot;
241 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
242 bool isSubsetOf(const ClassInfo &RHS) const {
243 // This is a subset of RHS if it is the same class...
247 // ... or if any of its super classes are a subset of RHS.
248 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
249 ie = SuperClasses.end(); it != ie; ++it)
250 if ((*it)->isSubsetOf(RHS))
256 /// operator< - Compare two classes.
257 bool operator<(const ClassInfo &RHS) const {
261 // Unrelated classes can be ordered by kind.
262 if (!isRelatedTo(RHS))
263 return Kind < RHS.Kind;
267 llvm_unreachable("Invalid kind!");
270 // This class precedes the RHS if it is a proper subset of the RHS.
273 if (RHS.isSubsetOf(*this))
276 // Otherwise, order by name to ensure we have a total ordering.
277 return ValueName < RHS.ValueName;
282 /// MatchableInfo - Helper class for storing the necessary information for an
283 /// instruction or alias which is capable of being matched.
284 struct MatchableInfo {
286 /// Token - This is the token that the operand came from.
289 /// The unique class instance this operand should match.
292 /// The operand name this is, if anything.
295 /// The suboperand index within SrcOpName, or -1 for the entire operand.
298 /// Register record if this token is singleton register.
299 Record *SingletonReg;
301 explicit AsmOperand(StringRef T) : Token(T), Class(0), SubOpIdx(-1),
305 /// ResOperand - This represents a single operand in the result instruction
306 /// generated by the match. In cases (like addressing modes) where a single
307 /// assembler operand expands to multiple MCOperands, this represents the
308 /// single assembler operand, not the MCOperand.
311 /// RenderAsmOperand - This represents an operand result that is
312 /// generated by calling the render method on the assembly operand. The
313 /// corresponding AsmOperand is specified by AsmOperandNum.
316 /// TiedOperand - This represents a result operand that is a duplicate of
317 /// a previous result operand.
320 /// ImmOperand - This represents an immediate value that is dumped into
324 /// RegOperand - This represents a fixed register that is dumped in.
329 /// This is the operand # in the AsmOperands list that this should be
331 unsigned AsmOperandNum;
333 /// TiedOperandNum - This is the (earlier) result operand that should be
335 unsigned TiedOperandNum;
337 /// ImmVal - This is the immediate value added to the instruction.
340 /// Register - This is the register record.
344 /// MINumOperands - The number of MCInst operands populated by this
346 unsigned MINumOperands;
348 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
350 X.Kind = RenderAsmOperand;
351 X.AsmOperandNum = AsmOpNum;
352 X.MINumOperands = NumOperands;
356 static ResOperand getTiedOp(unsigned TiedOperandNum) {
358 X.Kind = TiedOperand;
359 X.TiedOperandNum = TiedOperandNum;
364 static ResOperand getImmOp(int64_t Val) {
372 static ResOperand getRegOp(Record *Reg) {
381 /// AsmVariantID - Target's assembly syntax variant no.
384 /// TheDef - This is the definition of the instruction or InstAlias that this
385 /// matchable came from.
386 Record *const TheDef;
388 /// DefRec - This is the definition that it came from.
389 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
391 const CodeGenInstruction *getResultInst() const {
392 if (DefRec.is<const CodeGenInstruction*>())
393 return DefRec.get<const CodeGenInstruction*>();
394 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
397 /// ResOperands - This is the operand list that should be built for the result
399 SmallVector<ResOperand, 8> ResOperands;
401 /// AsmString - The assembly string for this instruction (with variants
402 /// removed), e.g. "movsx $src, $dst".
403 std::string AsmString;
405 /// Mnemonic - This is the first token of the matched instruction, its
409 /// AsmOperands - The textual operands that this instruction matches,
410 /// annotated with a class and where in the OperandList they were defined.
411 /// This directly corresponds to the tokenized AsmString after the mnemonic is
413 SmallVector<AsmOperand, 8> AsmOperands;
415 /// Predicates - The required subtarget features to match this instruction.
416 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
418 /// ConversionFnKind - The enum value which is passed to the generated
419 /// ConvertToMCInst to convert parsed operands into an MCInst for this
421 std::string ConversionFnKind;
423 MatchableInfo(const CodeGenInstruction &CGI)
424 : AsmVariantID(0), TheDef(CGI.TheDef), DefRec(&CGI),
425 AsmString(CGI.AsmString) {
428 MatchableInfo(const CodeGenInstAlias *Alias)
429 : AsmVariantID(0), TheDef(Alias->TheDef), DefRec(Alias),
430 AsmString(Alias->AsmString) {
433 // Two-operand aliases clone from the main matchable, but mark the second
434 // operand as a tied operand of the first for purposes of the assembler.
435 void formTwoOperandAlias(StringRef Constraint);
437 void initialize(const AsmMatcherInfo &Info,
438 SmallPtrSet<Record*, 16> &SingletonRegisters,
439 int AsmVariantNo, std::string &RegisterPrefix);
441 /// validate - Return true if this matchable is a valid thing to match against
442 /// and perform a bunch of validity checking.
443 bool validate(StringRef CommentDelimiter, bool Hack) const;
445 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
446 /// if present, from specified token.
448 extractSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info,
449 std::string &RegisterPrefix);
451 /// findAsmOperand - Find the AsmOperand with the specified name and
452 /// suboperand index.
453 int findAsmOperand(StringRef N, int SubOpIdx) const {
454 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
455 if (N == AsmOperands[i].SrcOpName &&
456 SubOpIdx == AsmOperands[i].SubOpIdx)
461 /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
462 /// This does not check the suboperand index.
463 int findAsmOperandNamed(StringRef N) const {
464 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
465 if (N == AsmOperands[i].SrcOpName)
470 void buildInstructionResultOperands();
471 void buildAliasResultOperands();
473 /// operator< - Compare two matchables.
474 bool operator<(const MatchableInfo &RHS) const {
475 // The primary comparator is the instruction mnemonic.
476 if (Mnemonic != RHS.Mnemonic)
477 return Mnemonic < RHS.Mnemonic;
479 if (AsmOperands.size() != RHS.AsmOperands.size())
480 return AsmOperands.size() < RHS.AsmOperands.size();
482 // Compare lexicographically by operand. The matcher validates that other
483 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
484 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
485 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
487 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
494 /// couldMatchAmbiguouslyWith - Check whether this matchable could
495 /// ambiguously match the same set of operands as \arg RHS (without being a
496 /// strictly superior match).
497 bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) {
498 // The primary comparator is the instruction mnemonic.
499 if (Mnemonic != RHS.Mnemonic)
502 // The number of operands is unambiguous.
503 if (AsmOperands.size() != RHS.AsmOperands.size())
506 // Otherwise, make sure the ordering of the two instructions is unambiguous
507 // by checking that either (a) a token or operand kind discriminates them,
508 // or (b) the ordering among equivalent kinds is consistent.
510 // Tokens and operand kinds are unambiguous (assuming a correct target
512 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
513 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
514 AsmOperands[i].Class->Kind == ClassInfo::Token)
515 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
516 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
519 // Otherwise, this operand could commute if all operands are equivalent, or
520 // there is a pair of operands that compare less than and a pair that
521 // compare greater than.
522 bool HasLT = false, HasGT = false;
523 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
524 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
526 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
530 return !(HasLT ^ HasGT);
536 void tokenizeAsmString(const AsmMatcherInfo &Info);
539 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
540 /// feature which participates in instruction matching.
541 struct SubtargetFeatureInfo {
542 /// \brief The predicate record for this feature.
545 /// \brief An unique index assigned to represent this feature.
548 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
550 /// \brief The name of the enumerated constant identifying this feature.
551 std::string getEnumName() const {
552 return "Feature_" + TheDef->getName();
556 struct OperandMatchEntry {
557 unsigned OperandMask;
561 static OperandMatchEntry create(MatchableInfo* mi, ClassInfo *ci,
564 X.OperandMask = opMask;
572 class AsmMatcherInfo {
575 RecordKeeper &Records;
577 /// The tablegen AsmParser record.
580 /// Target - The target information.
581 CodeGenTarget &Target;
583 /// The classes which are needed for matching.
584 std::vector<ClassInfo*> Classes;
586 /// The information on the matchables to match.
587 std::vector<MatchableInfo*> Matchables;
589 /// Info for custom matching operands by user defined methods.
590 std::vector<OperandMatchEntry> OperandMatchInfo;
592 /// Map of Register records to their class information.
593 std::map<Record*, ClassInfo*> RegisterClasses;
595 /// Map of Predicate records to their subtarget information.
596 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
598 /// Map of AsmOperandClass records to their class information.
599 std::map<Record*, ClassInfo*> AsmOperandClasses;
602 /// Map of token to class information which has already been constructed.
603 std::map<std::string, ClassInfo*> TokenClasses;
605 /// Map of RegisterClass records to their class information.
606 std::map<Record*, ClassInfo*> RegisterClassClasses;
609 /// getTokenClass - Lookup or create the class for the given token.
610 ClassInfo *getTokenClass(StringRef Token);
612 /// getOperandClass - Lookup or create the class for the given operand.
613 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
615 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
617 /// buildRegisterClasses - Build the ClassInfo* instances for register
619 void buildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
621 /// buildOperandClasses - Build the ClassInfo* instances for user defined
623 void buildOperandClasses();
625 void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
627 void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
628 MatchableInfo::AsmOperand &Op);
631 AsmMatcherInfo(Record *AsmParser,
632 CodeGenTarget &Target,
633 RecordKeeper &Records);
635 /// buildInfo - Construct the various tables used during matching.
638 /// buildOperandMatchInfo - Build the necessary information to handle user
639 /// defined operand parsing methods.
640 void buildOperandMatchInfo();
642 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
644 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
645 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
646 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
647 SubtargetFeatures.find(Def);
648 return I == SubtargetFeatures.end() ? 0 : I->second;
651 RecordKeeper &getRecords() const {
656 } // End anonymous namespace
658 void MatchableInfo::dump() {
659 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
661 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
662 AsmOperand &Op = AsmOperands[i];
663 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
664 errs() << '\"' << Op.Token << "\"\n";
668 static std::pair<StringRef, StringRef>
669 parseTwoOperandConstraint(StringRef S, SMLoc Loc) {
670 // Split via the '='.
671 std::pair<StringRef, StringRef> Ops = S.split('=');
672 if (Ops.second == "")
673 throw TGError(Loc, "missing '=' in two-operand alias constraint");
674 // Trim whitespace and the leading '$' on the operand names.
675 size_t start = Ops.first.find_first_of('$');
676 if (start == std::string::npos)
677 throw TGError(Loc, "expected '$' prefix on asm operand name");
678 Ops.first = Ops.first.slice(start + 1, std::string::npos);
679 size_t end = Ops.first.find_last_of(" \t");
680 Ops.first = Ops.first.slice(0, end);
681 // Now the second operand.
682 start = Ops.second.find_first_of('$');
683 if (start == std::string::npos)
684 throw TGError(Loc, "expected '$' prefix on asm operand name");
685 Ops.second = Ops.second.slice(start + 1, std::string::npos);
686 end = Ops.second.find_last_of(" \t");
687 Ops.first = Ops.first.slice(0, end);
691 void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
692 // Figure out which operands are aliased and mark them as tied.
693 std::pair<StringRef, StringRef> Ops =
694 parseTwoOperandConstraint(Constraint, TheDef->getLoc());
696 // Find the AsmOperands that refer to the operands we're aliasing.
697 int SrcAsmOperand = findAsmOperandNamed(Ops.first);
698 int DstAsmOperand = findAsmOperandNamed(Ops.second);
699 if (SrcAsmOperand == -1)
700 throw TGError(TheDef->getLoc(),
701 "unknown source two-operand alias operand '" +
702 Ops.first.str() + "'.");
703 if (DstAsmOperand == -1)
704 throw TGError(TheDef->getLoc(),
705 "unknown destination two-operand alias operand '" +
706 Ops.second.str() + "'.");
708 // Find the ResOperand that refers to the operand we're aliasing away
709 // and update it to refer to the combined operand instead.
710 for (unsigned i = 0, e = ResOperands.size(); i != e; ++i) {
711 ResOperand &Op = ResOperands[i];
712 if (Op.Kind == ResOperand::RenderAsmOperand &&
713 Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
714 Op.AsmOperandNum = DstAsmOperand;
718 // Remove the AsmOperand for the alias operand.
719 AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
720 // Adjust the ResOperand references to any AsmOperands that followed
721 // the one we just deleted.
722 for (unsigned i = 0, e = ResOperands.size(); i != e; ++i) {
723 ResOperand &Op = ResOperands[i];
726 // Nothing to do for operands that don't reference AsmOperands.
728 case ResOperand::RenderAsmOperand:
729 if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
732 case ResOperand::TiedOperand:
733 if (Op.TiedOperandNum > (unsigned)SrcAsmOperand)
740 void MatchableInfo::initialize(const AsmMatcherInfo &Info,
741 SmallPtrSet<Record*, 16> &SingletonRegisters,
742 int AsmVariantNo, std::string &RegisterPrefix) {
743 AsmVariantID = AsmVariantNo;
745 CodeGenInstruction::FlattenAsmStringVariants(AsmString, AsmVariantNo);
747 tokenizeAsmString(Info);
749 // Compute the require features.
750 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates");
751 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
752 if (SubtargetFeatureInfo *Feature =
753 Info.getSubtargetFeature(Predicates[i]))
754 RequiredFeatures.push_back(Feature);
756 // Collect singleton registers, if used.
757 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
758 extractSingletonRegisterForAsmOperand(i, Info, RegisterPrefix);
759 if (Record *Reg = AsmOperands[i].SingletonReg)
760 SingletonRegisters.insert(Reg);
764 /// tokenizeAsmString - Tokenize a simplified assembly string.
765 void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info) {
766 StringRef String = AsmString;
769 for (unsigned i = 0, e = String.size(); i != e; ++i) {
779 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
782 if (!isspace(String[i]) && String[i] != ',')
783 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
789 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
793 assert(i != String.size() && "Invalid quoted character");
794 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
800 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
804 // If this isn't "${", treat like a normal token.
805 if (i + 1 == String.size() || String[i + 1] != '{') {
810 StringRef::iterator End = std::find(String.begin() + i, String.end(),'}');
811 assert(End != String.end() && "Missing brace in operand reference!");
812 size_t EndPos = End - String.begin();
813 AsmOperands.push_back(AsmOperand(String.slice(i, EndPos+1)));
821 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
830 if (InTok && Prev != String.size())
831 AsmOperands.push_back(AsmOperand(String.substr(Prev)));
833 // The first token of the instruction is the mnemonic, which must be a
834 // simple string, not a $foo variable or a singleton register.
835 if (AsmOperands.empty())
836 throw TGError(TheDef->getLoc(),
837 "Instruction '" + TheDef->getName() + "' has no tokens");
838 Mnemonic = AsmOperands[0].Token;
839 if (Mnemonic.empty())
840 throw TGError(TheDef->getLoc(),
841 "Missing instruction mnemonic");
842 // FIXME : Check and raise an error if it is a register.
843 if (Mnemonic[0] == '$')
844 throw TGError(TheDef->getLoc(),
845 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
847 // Remove the first operand, it is tracked in the mnemonic field.
848 AsmOperands.erase(AsmOperands.begin());
851 bool MatchableInfo::validate(StringRef CommentDelimiter, bool Hack) const {
852 // Reject matchables with no .s string.
853 if (AsmString.empty())
854 throw TGError(TheDef->getLoc(), "instruction with empty asm string");
856 // Reject any matchables with a newline in them, they should be marked
857 // isCodeGenOnly if they are pseudo instructions.
858 if (AsmString.find('\n') != std::string::npos)
859 throw TGError(TheDef->getLoc(),
860 "multiline instruction is not valid for the asmparser, "
861 "mark it isCodeGenOnly");
863 // Remove comments from the asm string. We know that the asmstring only
865 if (!CommentDelimiter.empty() &&
866 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
867 throw TGError(TheDef->getLoc(),
868 "asmstring for instruction has comment character in it, "
869 "mark it isCodeGenOnly");
871 // Reject matchables with operand modifiers, these aren't something we can
872 // handle, the target should be refactored to use operands instead of
875 // Also, check for instructions which reference the operand multiple times;
876 // this implies a constraint we would not honor.
877 std::set<std::string> OperandNames;
878 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
879 StringRef Tok = AsmOperands[i].Token;
880 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
881 throw TGError(TheDef->getLoc(),
882 "matchable with operand modifier '" + Tok.str() +
883 "' not supported by asm matcher. Mark isCodeGenOnly!");
885 // Verify that any operand is only mentioned once.
886 // We reject aliases and ignore instructions for now.
887 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
889 throw TGError(TheDef->getLoc(),
890 "ERROR: matchable with tied operand '" + Tok.str() +
891 "' can never be matched!");
892 // FIXME: Should reject these. The ARM backend hits this with $lane in a
893 // bunch of instructions. It is unclear what the right answer is.
895 errs() << "warning: '" << TheDef->getName() << "': "
896 << "ignoring instruction with tied operand '"
897 << Tok.str() << "'\n";
906 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
907 /// if present, from specified token.
909 extractSingletonRegisterForAsmOperand(unsigned OperandNo,
910 const AsmMatcherInfo &Info,
911 std::string &RegisterPrefix) {
912 StringRef Tok = AsmOperands[OperandNo].Token;
913 if (RegisterPrefix.empty()) {
914 std::string LoweredTok = Tok.lower();
915 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
916 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
920 if (!Tok.startswith(RegisterPrefix))
923 StringRef RegName = Tok.substr(RegisterPrefix.size());
924 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
925 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
927 // If there is no register prefix (i.e. "%" in "%eax"), then this may
928 // be some random non-register token, just ignore it.
932 static std::string getEnumNameForToken(StringRef Str) {
935 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
937 case '*': Res += "_STAR_"; break;
938 case '%': Res += "_PCT_"; break;
939 case ':': Res += "_COLON_"; break;
940 case '!': Res += "_EXCLAIM_"; break;
941 case '.': Res += "_DOT_"; break;
946 Res += "_" + utostr((unsigned) *it) + "_";
953 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
954 ClassInfo *&Entry = TokenClasses[Token];
957 Entry = new ClassInfo();
958 Entry->Kind = ClassInfo::Token;
959 Entry->ClassName = "Token";
960 Entry->Name = "MCK_" + getEnumNameForToken(Token);
961 Entry->ValueName = Token;
962 Entry->PredicateMethod = "<invalid>";
963 Entry->RenderMethod = "<invalid>";
964 Entry->ParserMethod = "";
965 Entry->DiagnosticType = "";
966 Classes.push_back(Entry);
973 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
975 Record *Rec = OI.Rec;
977 Rec = dynamic_cast<DefInit*>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
978 return getOperandClass(Rec, SubOpIdx);
982 AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
983 if (Rec->isSubClassOf("RegisterOperand")) {
984 // RegisterOperand may have an associated ParserMatchClass. If it does,
985 // use it, else just fall back to the underlying register class.
986 const RecordVal *R = Rec->getValue("ParserMatchClass");
987 if (R == 0 || R->getValue() == 0)
988 throw "Record `" + Rec->getName() +
989 "' does not have a ParserMatchClass!\n";
991 if (DefInit *DI= dynamic_cast<DefInit*>(R->getValue())) {
992 Record *MatchClass = DI->getDef();
993 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
997 // No custom match class. Just use the register class.
998 Record *ClassRec = Rec->getValueAsDef("RegClass");
1000 throw TGError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
1001 "' has no associated register class!\n");
1002 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
1004 throw TGError(Rec->getLoc(), "register class has no class info!");
1008 if (Rec->isSubClassOf("RegisterClass")) {
1009 if (ClassInfo *CI = RegisterClassClasses[Rec])
1011 throw TGError(Rec->getLoc(), "register class has no class info!");
1014 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1015 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1016 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1019 throw TGError(Rec->getLoc(), "operand has no match class!");
1022 void AsmMatcherInfo::
1023 buildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
1024 const std::vector<CodeGenRegister*> &Registers =
1025 Target.getRegBank().getRegisters();
1026 ArrayRef<CodeGenRegisterClass*> RegClassList =
1027 Target.getRegBank().getRegClasses();
1029 // The register sets used for matching.
1030 std::set< std::set<Record*> > RegisterSets;
1032 // Gather the defined sets.
1033 for (ArrayRef<CodeGenRegisterClass*>::const_iterator it =
1034 RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it)
1035 RegisterSets.insert(std::set<Record*>(
1036 (*it)->getOrder().begin(), (*it)->getOrder().end()));
1038 // Add any required singleton sets.
1039 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1040 ie = SingletonRegisters.end(); it != ie; ++it) {
1042 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
1045 // Introduce derived sets where necessary (when a register does not determine
1046 // a unique register set class), and build the mapping of registers to the set
1047 // they should classify to.
1048 std::map<Record*, std::set<Record*> > RegisterMap;
1049 for (std::vector<CodeGenRegister*>::const_iterator it = Registers.begin(),
1050 ie = Registers.end(); it != ie; ++it) {
1051 const CodeGenRegister &CGR = **it;
1052 // Compute the intersection of all sets containing this register.
1053 std::set<Record*> ContainingSet;
1055 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
1056 ie = RegisterSets.end(); it != ie; ++it) {
1057 if (!it->count(CGR.TheDef))
1060 if (ContainingSet.empty()) {
1061 ContainingSet = *it;
1065 std::set<Record*> Tmp;
1066 std::swap(Tmp, ContainingSet);
1067 std::insert_iterator< std::set<Record*> > II(ContainingSet,
1068 ContainingSet.begin());
1069 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(), II);
1072 if (!ContainingSet.empty()) {
1073 RegisterSets.insert(ContainingSet);
1074 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
1078 // Construct the register classes.
1079 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
1081 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
1082 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
1083 ClassInfo *CI = new ClassInfo();
1084 CI->Kind = ClassInfo::RegisterClass0 + Index;
1085 CI->ClassName = "Reg" + utostr(Index);
1086 CI->Name = "MCK_Reg" + utostr(Index);
1088 CI->PredicateMethod = ""; // unused
1089 CI->RenderMethod = "addRegOperands";
1090 CI->Registers = *it;
1091 // FIXME: diagnostic type.
1092 CI->DiagnosticType = "";
1093 Classes.push_back(CI);
1094 RegisterSetClasses.insert(std::make_pair(*it, CI));
1097 // Find the superclasses; we could compute only the subgroup lattice edges,
1098 // but there isn't really a point.
1099 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
1100 ie = RegisterSets.end(); it != ie; ++it) {
1101 ClassInfo *CI = RegisterSetClasses[*it];
1102 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
1103 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
1105 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
1106 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
1109 // Name the register classes which correspond to a user defined RegisterClass.
1110 for (ArrayRef<CodeGenRegisterClass*>::const_iterator
1111 it = RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) {
1112 const CodeGenRegisterClass &RC = **it;
1113 // Def will be NULL for non-user defined register classes.
1114 Record *Def = RC.getDef();
1117 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(RC.getOrder().begin(),
1118 RC.getOrder().end())];
1119 if (CI->ValueName.empty()) {
1120 CI->ClassName = RC.getName();
1121 CI->Name = "MCK_" + RC.getName();
1122 CI->ValueName = RC.getName();
1124 CI->ValueName = CI->ValueName + "," + RC.getName();
1126 RegisterClassClasses.insert(std::make_pair(Def, CI));
1129 // Populate the map for individual registers.
1130 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
1131 ie = RegisterMap.end(); it != ie; ++it)
1132 RegisterClasses[it->first] = RegisterSetClasses[it->second];
1134 // Name the register classes which correspond to singleton registers.
1135 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1136 ie = SingletonRegisters.end(); it != ie; ++it) {
1138 ClassInfo *CI = RegisterClasses[Rec];
1139 assert(CI && "Missing singleton register class info!");
1141 if (CI->ValueName.empty()) {
1142 CI->ClassName = Rec->getName();
1143 CI->Name = "MCK_" + Rec->getName();
1144 CI->ValueName = Rec->getName();
1146 CI->ValueName = CI->ValueName + "," + Rec->getName();
1150 void AsmMatcherInfo::buildOperandClasses() {
1151 std::vector<Record*> AsmOperands =
1152 Records.getAllDerivedDefinitions("AsmOperandClass");
1154 // Pre-populate AsmOperandClasses map.
1155 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1156 ie = AsmOperands.end(); it != ie; ++it)
1157 AsmOperandClasses[*it] = new ClassInfo();
1160 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1161 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
1162 ClassInfo *CI = AsmOperandClasses[*it];
1163 CI->Kind = ClassInfo::UserClass0 + Index;
1165 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
1166 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
1167 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
1169 PrintError((*it)->getLoc(), "Invalid super class reference!");
1173 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1175 PrintError((*it)->getLoc(), "Invalid super class reference!");
1177 CI->SuperClasses.push_back(SC);
1179 CI->ClassName = (*it)->getValueAsString("Name");
1180 CI->Name = "MCK_" + CI->ClassName;
1181 CI->ValueName = (*it)->getName();
1183 // Get or construct the predicate method name.
1184 Init *PMName = (*it)->getValueInit("PredicateMethod");
1185 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
1186 CI->PredicateMethod = SI->getValue();
1188 assert(dynamic_cast<UnsetInit*>(PMName) &&
1189 "Unexpected PredicateMethod field!");
1190 CI->PredicateMethod = "is" + CI->ClassName;
1193 // Get or construct the render method name.
1194 Init *RMName = (*it)->getValueInit("RenderMethod");
1195 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
1196 CI->RenderMethod = SI->getValue();
1198 assert(dynamic_cast<UnsetInit*>(RMName) &&
1199 "Unexpected RenderMethod field!");
1200 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1203 // Get the parse method name or leave it as empty.
1204 Init *PRMName = (*it)->getValueInit("ParserMethod");
1205 if (StringInit *SI = dynamic_cast<StringInit*>(PRMName))
1206 CI->ParserMethod = SI->getValue();
1208 // Get the diagnostic type or leave it as empty.
1209 // Get the parse method name or leave it as empty.
1210 Init *DiagnosticType = (*it)->getValueInit("DiagnosticType");
1211 if (StringInit *SI = dynamic_cast<StringInit*>(DiagnosticType))
1212 CI->DiagnosticType = SI->getValue();
1214 AsmOperandClasses[*it] = CI;
1215 Classes.push_back(CI);
1219 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1220 CodeGenTarget &target,
1221 RecordKeeper &records)
1222 : Records(records), AsmParser(asmParser), Target(target) {
1225 /// buildOperandMatchInfo - Build the necessary information to handle user
1226 /// defined operand parsing methods.
1227 void AsmMatcherInfo::buildOperandMatchInfo() {
1229 /// Map containing a mask with all operands indices that can be found for
1230 /// that class inside a instruction.
1231 std::map<ClassInfo*, unsigned> OpClassMask;
1233 for (std::vector<MatchableInfo*>::const_iterator it =
1234 Matchables.begin(), ie = Matchables.end();
1236 MatchableInfo &II = **it;
1237 OpClassMask.clear();
1239 // Keep track of all operands of this instructions which belong to the
1241 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
1242 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
1243 if (Op.Class->ParserMethod.empty())
1245 unsigned &OperandMask = OpClassMask[Op.Class];
1246 OperandMask |= (1 << i);
1249 // Generate operand match info for each mnemonic/operand class pair.
1250 for (std::map<ClassInfo*, unsigned>::iterator iit = OpClassMask.begin(),
1251 iie = OpClassMask.end(); iit != iie; ++iit) {
1252 unsigned OpMask = iit->second;
1253 ClassInfo *CI = iit->first;
1254 OperandMatchInfo.push_back(OperandMatchEntry::create(&II, CI, OpMask));
1259 void AsmMatcherInfo::buildInfo() {
1260 // Build information about all of the AssemblerPredicates.
1261 std::vector<Record*> AllPredicates =
1262 Records.getAllDerivedDefinitions("Predicate");
1263 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
1264 Record *Pred = AllPredicates[i];
1265 // Ignore predicates that are not intended for the assembler.
1266 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
1269 if (Pred->getName().empty())
1270 throw TGError(Pred->getLoc(), "Predicate has no name!");
1272 unsigned FeatureNo = SubtargetFeatures.size();
1273 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
1274 assert(FeatureNo < 32 && "Too many subtarget features!");
1277 // Parse the instructions; we need to do this first so that we can gather the
1278 // singleton register classes.
1279 SmallPtrSet<Record*, 16> SingletonRegisters;
1280 unsigned VariantCount = Target.getAsmParserVariantCount();
1281 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1282 Record *AsmVariant = Target.getAsmParserVariant(VC);
1283 std::string CommentDelimiter =
1284 AsmVariant->getValueAsString("CommentDelimiter");
1285 std::string RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
1286 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
1288 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
1289 E = Target.inst_end(); I != E; ++I) {
1290 const CodeGenInstruction &CGI = **I;
1292 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1293 // filter the set of instructions we consider.
1294 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
1297 // Ignore "codegen only" instructions.
1298 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
1301 // Validate the operand list to ensure we can handle this instruction.
1302 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1303 const CGIOperandList::OperandInfo &OI = CGI.Operands[i];
1305 // Validate tied operands.
1306 if (OI.getTiedRegister() != -1) {
1307 // If we have a tied operand that consists of multiple MCOperands,
1308 // reject it. We reject aliases and ignore instructions for now.
1309 if (OI.MINumOperands != 1) {
1310 // FIXME: Should reject these. The ARM backend hits this with $lane
1311 // in a bunch of instructions. The right answer is unclear.
1313 errs() << "warning: '" << CGI.TheDef->getName() << "': "
1314 << "ignoring instruction with multi-operand tied operand '"
1315 << OI.Name << "'\n";
1322 OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
1324 II->initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
1326 // Ignore instructions which shouldn't be matched and diagnose invalid
1327 // instruction definitions with an error.
1328 if (!II->validate(CommentDelimiter, true))
1331 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
1333 // FIXME: This is a total hack.
1334 if (StringRef(II->TheDef->getName()).startswith("Int_") ||
1335 StringRef(II->TheDef->getName()).endswith("_Int"))
1338 Matchables.push_back(II.take());
1341 // Parse all of the InstAlias definitions and stick them in the list of
1343 std::vector<Record*> AllInstAliases =
1344 Records.getAllDerivedDefinitions("InstAlias");
1345 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
1346 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i], Target);
1348 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1349 // filter the set of instruction aliases we consider, based on the target
1351 if (!StringRef(Alias->ResultInst->TheDef->getName())
1352 .startswith( MatchPrefix))
1355 OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
1357 II->initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
1359 // Validate the alias definitions.
1360 II->validate(CommentDelimiter, false);
1362 Matchables.push_back(II.take());
1366 // Build info for the register classes.
1367 buildRegisterClasses(SingletonRegisters);
1369 // Build info for the user defined assembly operand classes.
1370 buildOperandClasses();
1372 // Build the information about matchables, now that we have fully formed
1374 std::vector<MatchableInfo*> NewMatchables;
1375 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(),
1376 ie = Matchables.end(); it != ie; ++it) {
1377 MatchableInfo *II = *it;
1379 // Parse the tokens after the mnemonic.
1380 // Note: buildInstructionOperandReference may insert new AsmOperands, so
1381 // don't precompute the loop bound.
1382 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1383 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
1384 StringRef Token = Op.Token;
1386 // Check for singleton registers.
1387 if (Record *RegRecord = II->AsmOperands[i].SingletonReg) {
1388 Op.Class = RegisterClasses[RegRecord];
1389 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1390 "Unexpected class for singleton register");
1394 // Check for simple tokens.
1395 if (Token[0] != '$') {
1396 Op.Class = getTokenClass(Token);
1400 if (Token.size() > 1 && isdigit(Token[1])) {
1401 Op.Class = getTokenClass(Token);
1405 // Otherwise this is an operand reference.
1406 StringRef OperandName;
1407 if (Token[1] == '{')
1408 OperandName = Token.substr(2, Token.size() - 3);
1410 OperandName = Token.substr(1);
1412 if (II->DefRec.is<const CodeGenInstruction*>())
1413 buildInstructionOperandReference(II, OperandName, i);
1415 buildAliasOperandReference(II, OperandName, Op);
1418 if (II->DefRec.is<const CodeGenInstruction*>()) {
1419 II->buildInstructionResultOperands();
1420 // If the instruction has a two-operand alias, build up the
1421 // matchable here. We'll add them in bulk at the end to avoid
1422 // confusing this loop.
1423 std::string Constraint =
1424 II->TheDef->getValueAsString("TwoOperandAliasConstraint");
1425 if (Constraint != "") {
1426 // Start by making a copy of the original matchable.
1427 OwningPtr<MatchableInfo> AliasII(new MatchableInfo(*II));
1429 // Adjust it to be a two-operand alias.
1430 AliasII->formTwoOperandAlias(Constraint);
1432 // Add the alias to the matchables list.
1433 NewMatchables.push_back(AliasII.take());
1436 II->buildAliasResultOperands();
1438 if (!NewMatchables.empty())
1439 Matchables.insert(Matchables.end(), NewMatchables.begin(),
1440 NewMatchables.end());
1442 // Process token alias definitions and set up the associated superclass
1444 std::vector<Record*> AllTokenAliases =
1445 Records.getAllDerivedDefinitions("TokenAlias");
1446 for (unsigned i = 0, e = AllTokenAliases.size(); i != e; ++i) {
1447 Record *Rec = AllTokenAliases[i];
1448 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1449 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
1450 if (FromClass == ToClass)
1451 throw TGError(Rec->getLoc(),
1452 "error: Destination value identical to source value.");
1453 FromClass->SuperClasses.push_back(ToClass);
1456 // Reorder classes so that classes precede super classes.
1457 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
1460 /// buildInstructionOperandReference - The specified operand is a reference to a
1461 /// named operand such as $src. Resolve the Class and OperandInfo pointers.
1462 void AsmMatcherInfo::
1463 buildInstructionOperandReference(MatchableInfo *II,
1464 StringRef OperandName,
1465 unsigned AsmOpIdx) {
1466 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1467 const CGIOperandList &Operands = CGI.Operands;
1468 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
1470 // Map this token to an operand.
1472 if (!Operands.hasOperandNamed(OperandName, Idx))
1473 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1474 OperandName.str() + "'");
1476 // If the instruction operand has multiple suboperands, but the parser
1477 // match class for the asm operand is still the default "ImmAsmOperand",
1478 // then handle each suboperand separately.
1479 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1480 Record *Rec = Operands[Idx].Rec;
1481 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1482 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1483 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1484 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1485 StringRef Token = Op->Token; // save this in case Op gets moved
1486 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1487 MatchableInfo::AsmOperand NewAsmOp(Token);
1488 NewAsmOp.SubOpIdx = SI;
1489 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1491 // Replace Op with first suboperand.
1492 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1497 // Set up the operand class.
1498 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
1500 // If the named operand is tied, canonicalize it to the untied operand.
1501 // For example, something like:
1502 // (outs GPR:$dst), (ins GPR:$src)
1503 // with an asmstring of
1505 // we want to canonicalize to:
1507 // so that we know how to provide the $dst operand when filling in the result.
1508 int OITied = Operands[Idx].getTiedRegister();
1510 // The tied operand index is an MIOperand index, find the operand that
1512 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1513 OperandName = Operands[Idx.first].Name;
1514 Op->SubOpIdx = Idx.second;
1517 Op->SrcOpName = OperandName;
1520 /// buildAliasOperandReference - When parsing an operand reference out of the
1521 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1522 /// operand reference is by looking it up in the result pattern definition.
1523 void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
1524 StringRef OperandName,
1525 MatchableInfo::AsmOperand &Op) {
1526 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
1528 // Set up the operand class.
1529 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
1530 if (CGA.ResultOperands[i].isRecord() &&
1531 CGA.ResultOperands[i].getName() == OperandName) {
1532 // It's safe to go with the first one we find, because CodeGenInstAlias
1533 // validates that all operands with the same name have the same record.
1534 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
1535 // Use the match class from the Alias definition, not the
1536 // destination instruction, as we may have an immediate that's
1537 // being munged by the match class.
1538 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
1540 Op.SrcOpName = OperandName;
1544 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1545 OperandName.str() + "'");
1548 void MatchableInfo::buildInstructionResultOperands() {
1549 const CodeGenInstruction *ResultInst = getResultInst();
1551 // Loop over all operands of the result instruction, determining how to
1553 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1554 const CGIOperandList::OperandInfo &OpInfo = ResultInst->Operands[i];
1556 // If this is a tied operand, just copy from the previously handled operand.
1557 int TiedOp = OpInfo.getTiedRegister();
1559 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1563 // Find out what operand from the asmparser this MCInst operand comes from.
1564 int SrcOperand = findAsmOperandNamed(OpInfo.Name);
1565 if (OpInfo.Name.empty() || SrcOperand == -1)
1566 throw TGError(TheDef->getLoc(), "Instruction '" +
1567 TheDef->getName() + "' has operand '" + OpInfo.Name +
1568 "' that doesn't appear in asm string!");
1570 // Check if the one AsmOperand populates the entire operand.
1571 unsigned NumOperands = OpInfo.MINumOperands;
1572 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1573 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
1577 // Add a separate ResOperand for each suboperand.
1578 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1579 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1580 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1581 "unexpected AsmOperands for suboperands");
1582 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1587 void MatchableInfo::buildAliasResultOperands() {
1588 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1589 const CodeGenInstruction *ResultInst = getResultInst();
1591 // Loop over all operands of the result instruction, determining how to
1593 unsigned AliasOpNo = 0;
1594 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
1595 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1596 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
1598 // If this is a tied operand, just copy from the previously handled operand.
1599 int TiedOp = OpInfo->getTiedRegister();
1601 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1605 // Handle all the suboperands for this operand.
1606 const std::string &OpName = OpInfo->Name;
1607 for ( ; AliasOpNo < LastOpNo &&
1608 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1609 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1611 // Find out what operand from the asmparser that this MCInst operand
1613 switch (CGA.ResultOperands[AliasOpNo].Kind) {
1614 case CodeGenInstAlias::ResultOperand::K_Record: {
1615 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1616 int SrcOperand = findAsmOperand(Name, SubIdx);
1617 if (SrcOperand == -1)
1618 throw TGError(TheDef->getLoc(), "Instruction '" +
1619 TheDef->getName() + "' has operand '" + OpName +
1620 "' that doesn't appear in asm string!");
1621 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1622 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1626 case CodeGenInstAlias::ResultOperand::K_Imm: {
1627 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1628 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1631 case CodeGenInstAlias::ResultOperand::K_Reg: {
1632 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1633 ResOperands.push_back(ResOperand::getRegOp(Reg));
1641 static void emitConvertToMCInst(CodeGenTarget &Target, StringRef ClassName,
1642 std::vector<MatchableInfo*> &Infos,
1644 // Write the convert function to a separate stream, so we can drop it after
1646 std::string ConvertFnBody;
1647 raw_string_ostream CvtOS(ConvertFnBody);
1649 // Function we have already generated.
1650 std::set<std::string> GeneratedFns;
1652 // Start the unified conversion function.
1653 CvtOS << "bool " << Target.getName() << ClassName << "::\n";
1654 CvtOS << "ConvertToMCInst(unsigned Kind, MCInst &Inst, "
1655 << "unsigned Opcode,\n"
1656 << " const SmallVectorImpl<MCParsedAsmOperand*"
1657 << "> &Operands) {\n";
1658 CvtOS << " Inst.setOpcode(Opcode);\n";
1659 CvtOS << " switch (Kind) {\n";
1660 CvtOS << " default:\n";
1662 // Start the enum, which we will generate inline.
1664 OS << "// Unified function for converting operands to MCInst instances.\n\n";
1665 OS << "enum ConversionKind {\n";
1667 // TargetOperandClass - This is the target's operand class, like X86Operand.
1668 std::string TargetOperandClass = Target.getName() + "Operand";
1670 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(),
1671 ie = Infos.end(); it != ie; ++it) {
1672 MatchableInfo &II = **it;
1674 // Check if we have a custom match function.
1675 std::string AsmMatchConverter =
1676 II.getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
1677 if (!AsmMatchConverter.empty()) {
1678 std::string Signature = "ConvertCustom_" + AsmMatchConverter;
1679 II.ConversionFnKind = Signature;
1681 // Check if we have already generated this signature.
1682 if (!GeneratedFns.insert(Signature).second)
1685 // If not, emit it now. Add to the enum list.
1686 OS << " " << Signature << ",\n";
1688 CvtOS << " case " << Signature << ":\n";
1689 CvtOS << " return " << AsmMatchConverter
1690 << "(Inst, Opcode, Operands);\n";
1694 // Build the conversion function signature.
1695 std::string Signature = "Convert";
1696 std::string CaseBody;
1697 raw_string_ostream CaseOS(CaseBody);
1699 // Compute the convert enum and the case body.
1700 for (unsigned i = 0, e = II.ResOperands.size(); i != e; ++i) {
1701 const MatchableInfo::ResOperand &OpInfo = II.ResOperands[i];
1703 // Generate code to populate each result operand.
1704 switch (OpInfo.Kind) {
1705 case MatchableInfo::ResOperand::RenderAsmOperand: {
1706 // This comes from something we parsed.
1707 MatchableInfo::AsmOperand &Op = II.AsmOperands[OpInfo.AsmOperandNum];
1709 // Registers are always converted the same, don't duplicate the
1710 // conversion function based on them.
1712 if (Op.Class->isRegisterClass())
1715 Signature += Op.Class->ClassName;
1716 Signature += utostr(OpInfo.MINumOperands);
1717 Signature += "_" + itostr(OpInfo.AsmOperandNum);
1719 CaseOS << " ((" << TargetOperandClass << "*)Operands["
1720 << (OpInfo.AsmOperandNum+1) << "])->" << Op.Class->RenderMethod
1721 << "(Inst, " << OpInfo.MINumOperands << ");\n";
1725 case MatchableInfo::ResOperand::TiedOperand: {
1726 // If this operand is tied to a previous one, just copy the MCInst
1727 // operand from the earlier one.We can only tie single MCOperand values.
1728 //assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
1729 unsigned TiedOp = OpInfo.TiedOperandNum;
1730 assert(i > TiedOp && "Tied operand precedes its target!");
1731 CaseOS << " Inst.addOperand(Inst.getOperand(" << TiedOp << "));\n";
1732 Signature += "__Tie" + utostr(TiedOp);
1735 case MatchableInfo::ResOperand::ImmOperand: {
1736 int64_t Val = OpInfo.ImmVal;
1737 CaseOS << " Inst.addOperand(MCOperand::CreateImm(" << Val << "));\n";
1738 Signature += "__imm" + itostr(Val);
1741 case MatchableInfo::ResOperand::RegOperand: {
1742 if (OpInfo.Register == 0) {
1743 CaseOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1744 Signature += "__reg0";
1746 std::string N = getQualifiedName(OpInfo.Register);
1747 CaseOS << " Inst.addOperand(MCOperand::CreateReg(" << N << "));\n";
1748 Signature += "__reg" + OpInfo.Register->getName();
1754 II.ConversionFnKind = Signature;
1756 // Check if we have already generated this signature.
1757 if (!GeneratedFns.insert(Signature).second)
1760 // If not, emit it now. Add to the enum list.
1761 OS << " " << Signature << ",\n";
1763 CvtOS << " case " << Signature << ":\n";
1764 CvtOS << CaseOS.str();
1765 CvtOS << " return true;\n";
1768 // Finish the convert function.
1771 CvtOS << " return false;\n";
1774 // Finish the enum, and drop the convert function after it.
1776 OS << " NumConversionVariants\n";
1782 /// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
1783 static void emitMatchClassEnumeration(CodeGenTarget &Target,
1784 std::vector<ClassInfo*> &Infos,
1786 OS << "namespace {\n\n";
1788 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1789 << "/// instruction matching.\n";
1790 OS << "enum MatchClassKind {\n";
1791 OS << " InvalidMatchClass = 0,\n";
1792 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1793 ie = Infos.end(); it != ie; ++it) {
1794 ClassInfo &CI = **it;
1795 OS << " " << CI.Name << ", // ";
1796 if (CI.Kind == ClassInfo::Token) {
1797 OS << "'" << CI.ValueName << "'\n";
1798 } else if (CI.isRegisterClass()) {
1799 if (!CI.ValueName.empty())
1800 OS << "register class '" << CI.ValueName << "'\n";
1802 OS << "derived register class\n";
1804 OS << "user defined class '" << CI.ValueName << "'\n";
1807 OS << " NumMatchClassKinds\n";
1813 /// emitValidateOperandClass - Emit the function to validate an operand class.
1814 static void emitValidateOperandClass(AsmMatcherInfo &Info,
1816 OS << "static unsigned validateOperandClass(MCParsedAsmOperand *GOp, "
1817 << "MatchClassKind Kind) {\n";
1818 OS << " " << Info.Target.getName() << "Operand &Operand = *("
1819 << Info.Target.getName() << "Operand*)GOp;\n";
1821 // The InvalidMatchClass is not to match any operand.
1822 OS << " if (Kind == InvalidMatchClass)\n";
1823 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n\n";
1825 // Check for Token operands first.
1826 // FIXME: Use a more specific diagnostic type.
1827 OS << " if (Operand.isToken())\n";
1828 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
1829 << " MCTargetAsmParser::Match_Success :\n"
1830 << " MCTargetAsmParser::Match_InvalidOperand;\n\n";
1832 // Check the user classes. We don't care what order since we're only
1833 // actually matching against one of them.
1834 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1835 ie = Info.Classes.end(); it != ie; ++it) {
1836 ClassInfo &CI = **it;
1838 if (!CI.isUserClass())
1841 OS << " // '" << CI.ClassName << "' class\n";
1842 OS << " if (Kind == " << CI.Name << ") {\n";
1843 OS << " if (Operand." << CI.PredicateMethod << "())\n";
1844 OS << " return MCTargetAsmParser::Match_Success;\n";
1845 if (!CI.DiagnosticType.empty())
1846 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
1847 << CI.DiagnosticType << ";\n";
1851 // Check for register operands, including sub-classes.
1852 OS << " if (Operand.isReg()) {\n";
1853 OS << " MatchClassKind OpKind;\n";
1854 OS << " switch (Operand.getReg()) {\n";
1855 OS << " default: OpKind = InvalidMatchClass; break;\n";
1856 for (std::map<Record*, ClassInfo*>::iterator
1857 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1859 OS << " case " << Info.Target.getName() << "::"
1860 << it->first->getName() << ": OpKind = " << it->second->Name
1863 OS << " return isSubclass(OpKind, Kind) ? "
1864 << "MCTargetAsmParser::Match_Success :\n "
1865 << " MCTargetAsmParser::Match_InvalidOperand;\n }\n\n";
1867 // Generic fallthrough match failure case for operands that don't have
1868 // specialized diagnostic types.
1869 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
1873 /// emitIsSubclass - Emit the subclass predicate function.
1874 static void emitIsSubclass(CodeGenTarget &Target,
1875 std::vector<ClassInfo*> &Infos,
1877 OS << "/// isSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1878 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
1879 OS << " if (A == B)\n";
1880 OS << " return true;\n\n";
1882 OS << " switch (A) {\n";
1883 OS << " default:\n";
1884 OS << " return false;\n";
1885 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1886 ie = Infos.end(); it != ie; ++it) {
1887 ClassInfo &A = **it;
1889 std::vector<StringRef> SuperClasses;
1890 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1891 ie = Infos.end(); it != ie; ++it) {
1892 ClassInfo &B = **it;
1894 if (&A != &B && A.isSubsetOf(B))
1895 SuperClasses.push_back(B.Name);
1898 if (SuperClasses.empty())
1901 OS << "\n case " << A.Name << ":\n";
1903 if (SuperClasses.size() == 1) {
1904 OS << " return B == " << SuperClasses.back() << ";\n";
1908 OS << " switch (B) {\n";
1909 OS << " default: return false;\n";
1910 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1911 OS << " case " << SuperClasses[i] << ": return true;\n";
1918 /// emitMatchTokenString - Emit the function to match a token string to the
1919 /// appropriate match class value.
1920 static void emitMatchTokenString(CodeGenTarget &Target,
1921 std::vector<ClassInfo*> &Infos,
1923 // Construct the match list.
1924 std::vector<StringMatcher::StringPair> Matches;
1925 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1926 ie = Infos.end(); it != ie; ++it) {
1927 ClassInfo &CI = **it;
1929 if (CI.Kind == ClassInfo::Token)
1930 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1931 "return " + CI.Name + ";"));
1934 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
1936 StringMatcher("Name", Matches, OS).Emit();
1938 OS << " return InvalidMatchClass;\n";
1942 /// emitMatchRegisterName - Emit the function to match a string to the target
1943 /// specific register enum.
1944 static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1946 // Construct the match list.
1947 std::vector<StringMatcher::StringPair> Matches;
1948 const std::vector<CodeGenRegister*> &Regs =
1949 Target.getRegBank().getRegisters();
1950 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1951 const CodeGenRegister *Reg = Regs[i];
1952 if (Reg->TheDef->getValueAsString("AsmName").empty())
1955 Matches.push_back(StringMatcher::StringPair(
1956 Reg->TheDef->getValueAsString("AsmName"),
1957 "return " + utostr(Reg->EnumValue) + ";"));
1960 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
1962 StringMatcher("Name", Matches, OS).Emit();
1964 OS << " return 0;\n";
1968 /// emitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1970 static void emitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
1972 OS << "// Flags for subtarget features that participate in "
1973 << "instruction matching.\n";
1974 OS << "enum SubtargetFeatureFlag {\n";
1975 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1976 it = Info.SubtargetFeatures.begin(),
1977 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1978 SubtargetFeatureInfo &SFI = *it->second;
1979 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
1981 OS << " Feature_None = 0\n";
1985 /// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
1986 static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) {
1987 // Get the set of diagnostic types from all of the operand classes.
1988 std::set<StringRef> Types;
1989 for (std::map<Record*, ClassInfo*>::const_iterator
1990 I = Info.AsmOperandClasses.begin(),
1991 E = Info.AsmOperandClasses.end(); I != E; ++I) {
1992 if (!I->second->DiagnosticType.empty())
1993 Types.insert(I->second->DiagnosticType);
1996 if (Types.empty()) return;
1998 // Now emit the enum entries.
1999 for (std::set<StringRef>::const_iterator I = Types.begin(), E = Types.end();
2001 OS << " Match_" << *I << ",\n";
2002 OS << " END_OPERAND_DIAGNOSTIC_TYPES\n";
2005 /// emitGetSubtargetFeatureName - Emit the helper function to get the
2006 /// user-level name for a subtarget feature.
2007 static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
2008 OS << "// User-level names for subtarget features that participate in\n"
2009 << "// instruction matching.\n"
2010 << "static const char *getSubtargetFeatureName(unsigned Val) {\n"
2011 << " switch(Val) {\n";
2012 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
2013 it = Info.SubtargetFeatures.begin(),
2014 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
2015 SubtargetFeatureInfo &SFI = *it->second;
2016 // FIXME: Totally just a placeholder name to get the algorithm working.
2017 OS << " case " << SFI.getEnumName() << ": return \""
2018 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
2020 OS << " default: return \"(unknown)\";\n";
2024 /// emitComputeAvailableFeatures - Emit the function to compute the list of
2025 /// available features given a subtarget.
2026 static void emitComputeAvailableFeatures(AsmMatcherInfo &Info,
2028 std::string ClassName =
2029 Info.AsmParser->getValueAsString("AsmParserClassName");
2031 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
2032 << "ComputeAvailableFeatures(uint64_t FB) const {\n";
2033 OS << " unsigned Features = 0;\n";
2034 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
2035 it = Info.SubtargetFeatures.begin(),
2036 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
2037 SubtargetFeatureInfo &SFI = *it->second;
2040 std::string CondStorage =
2041 SFI.TheDef->getValueAsString("AssemblerCondString");
2042 StringRef Conds = CondStorage;
2043 std::pair<StringRef,StringRef> Comma = Conds.split(',');
2050 StringRef Cond = Comma.first;
2051 if (Cond[0] == '!') {
2053 Cond = Cond.substr(1);
2056 OS << "((FB & " << Info.Target.getName() << "::" << Cond << ")";
2063 if (Comma.second.empty())
2067 Comma = Comma.second.split(',');
2071 OS << " Features |= " << SFI.getEnumName() << ";\n";
2073 OS << " return Features;\n";
2077 static std::string GetAliasRequiredFeatures(Record *R,
2078 const AsmMatcherInfo &Info) {
2079 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
2081 unsigned NumFeatures = 0;
2082 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
2083 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
2086 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
2087 "' is not marked as an AssemblerPredicate!");
2092 Result += F->getEnumName();
2096 if (NumFeatures > 1)
2097 Result = '(' + Result + ')';
2101 /// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
2102 /// emit a function for them and return true, otherwise return false.
2103 static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
2104 // Ignore aliases when match-prefix is set.
2105 if (!MatchPrefix.empty())
2108 std::vector<Record*> Aliases =
2109 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
2110 if (Aliases.empty()) return false;
2112 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
2113 "unsigned Features) {\n";
2115 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
2116 // iteration order of the map is stable.
2117 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
2119 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
2120 Record *R = Aliases[i];
2121 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
2124 // Process each alias a "from" mnemonic at a time, building the code executed
2125 // by the string remapper.
2126 std::vector<StringMatcher::StringPair> Cases;
2127 for (std::map<std::string, std::vector<Record*> >::iterator
2128 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
2130 const std::vector<Record*> &ToVec = I->second;
2132 // Loop through each alias and emit code that handles each case. If there
2133 // are two instructions without predicates, emit an error. If there is one,
2135 std::string MatchCode;
2136 int AliasWithNoPredicate = -1;
2138 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
2139 Record *R = ToVec[i];
2140 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
2142 // If this unconditionally matches, remember it for later and diagnose
2144 if (FeatureMask.empty()) {
2145 if (AliasWithNoPredicate != -1) {
2146 // We can't have two aliases from the same mnemonic with no predicate.
2147 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
2148 "two MnemonicAliases with the same 'from' mnemonic!");
2149 throw TGError(R->getLoc(), "this is the other MnemonicAlias.");
2152 AliasWithNoPredicate = i;
2155 if (R->getValueAsString("ToMnemonic") == I->first)
2156 throw TGError(R->getLoc(), "MnemonicAlias to the same string");
2158 if (!MatchCode.empty())
2159 MatchCode += "else ";
2160 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
2161 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
2164 if (AliasWithNoPredicate != -1) {
2165 Record *R = ToVec[AliasWithNoPredicate];
2166 if (!MatchCode.empty())
2167 MatchCode += "else\n ";
2168 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
2171 MatchCode += "return;";
2173 Cases.push_back(std::make_pair(I->first, MatchCode));
2176 StringMatcher("Mnemonic", Cases, OS).Emit();
2182 static const char *getMinimalTypeForRange(uint64_t Range) {
2183 assert(Range < 0xFFFFFFFFULL && "Enum too large");
2191 static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
2192 const AsmMatcherInfo &Info, StringRef ClassName) {
2193 // Emit the static custom operand parsing table;
2194 OS << "namespace {\n";
2195 OS << " struct OperandMatchEntry {\n";
2196 OS << " static const char *const MnemonicTable;\n";
2197 OS << " uint32_t OperandMask;\n";
2198 OS << " uint32_t Mnemonic;\n";
2199 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2200 << " RequiredFeatures;\n";
2201 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2203 OS << " StringRef getMnemonic() const {\n";
2204 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2205 OS << " MnemonicTable[Mnemonic]);\n";
2209 OS << " // Predicate for searching for an opcode.\n";
2210 OS << " struct LessOpcodeOperand {\n";
2211 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
2212 OS << " return LHS.getMnemonic() < RHS;\n";
2214 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
2215 OS << " return LHS < RHS.getMnemonic();\n";
2217 OS << " bool operator()(const OperandMatchEntry &LHS,";
2218 OS << " const OperandMatchEntry &RHS) {\n";
2219 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
2223 OS << "} // end anonymous namespace.\n\n";
2225 StringToOffsetTable StringTable;
2227 OS << "static const OperandMatchEntry OperandMatchTable["
2228 << Info.OperandMatchInfo.size() << "] = {\n";
2230 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
2231 for (std::vector<OperandMatchEntry>::const_iterator it =
2232 Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end();
2234 const OperandMatchEntry &OMI = *it;
2235 const MatchableInfo &II = *OMI.MI;
2237 OS << " { " << OMI.OperandMask;
2240 bool printComma = false;
2241 for (int i = 0, e = 31; i !=e; ++i)
2242 if (OMI.OperandMask & (1 << i)) {
2250 // Store a pascal-style length byte in the mnemonic.
2251 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2252 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2253 << " /* " << II.Mnemonic << " */, ";
2255 // Write the required features mask.
2256 if (!II.RequiredFeatures.empty()) {
2257 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2259 OS << II.RequiredFeatures[i]->getEnumName();
2264 OS << ", " << OMI.CI->Name;
2270 OS << "const char *const OperandMatchEntry::MnemonicTable =\n";
2271 StringTable.EmitString(OS);
2274 // Emit the operand class switch to call the correct custom parser for
2275 // the found operand class.
2276 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2277 << Target.getName() << ClassName << "::\n"
2278 << "tryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>"
2279 << " &Operands,\n unsigned MCK) {\n\n"
2280 << " switch(MCK) {\n";
2282 for (std::vector<ClassInfo*>::const_iterator it = Info.Classes.begin(),
2283 ie = Info.Classes.end(); it != ie; ++it) {
2284 ClassInfo *CI = *it;
2285 if (CI->ParserMethod.empty())
2287 OS << " case " << CI->Name << ":\n"
2288 << " return " << CI->ParserMethod << "(Operands);\n";
2291 OS << " default:\n";
2292 OS << " return MatchOperand_NoMatch;\n";
2294 OS << " return MatchOperand_NoMatch;\n";
2297 // Emit the static custom operand parser. This code is very similar with
2298 // the other matcher. Also use MatchResultTy here just in case we go for
2299 // a better error handling.
2300 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2301 << Target.getName() << ClassName << "::\n"
2302 << "MatchOperandParserImpl(SmallVectorImpl<MCParsedAsmOperand*>"
2303 << " &Operands,\n StringRef Mnemonic) {\n";
2305 // Emit code to get the available features.
2306 OS << " // Get the current feature set.\n";
2307 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2309 OS << " // Get the next operand index.\n";
2310 OS << " unsigned NextOpNum = Operands.size()-1;\n";
2312 // Emit code to search the table.
2313 OS << " // Search the table.\n";
2314 OS << " std::pair<const OperandMatchEntry*, const OperandMatchEntry*>";
2315 OS << " MnemonicRange =\n";
2316 OS << " std::equal_range(OperandMatchTable, OperandMatchTable+"
2317 << Info.OperandMatchInfo.size() << ", Mnemonic,\n"
2318 << " LessOpcodeOperand());\n\n";
2320 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2321 OS << " return MatchOperand_NoMatch;\n\n";
2323 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2324 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2326 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2327 OS << " assert(Mnemonic == it->getMnemonic());\n\n";
2329 // Emit check that the required features are available.
2330 OS << " // check if the available features match\n";
2331 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2332 << "!= it->RequiredFeatures) {\n";
2333 OS << " continue;\n";
2336 // Emit check to ensure the operand number matches.
2337 OS << " // check if the operand in question has a custom parser.\n";
2338 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2339 OS << " continue;\n\n";
2341 // Emit call to the custom parser method
2342 OS << " // call custom parse method to handle the operand\n";
2343 OS << " OperandMatchResultTy Result = ";
2344 OS << "tryCustomParseOperand(Operands, it->Class);\n";
2345 OS << " if (Result != MatchOperand_NoMatch)\n";
2346 OS << " return Result;\n";
2349 OS << " // Okay, we had no match.\n";
2350 OS << " return MatchOperand_NoMatch;\n";
2354 void AsmMatcherEmitter::run(raw_ostream &OS) {
2355 CodeGenTarget Target(Records);
2356 Record *AsmParser = Target.getAsmParser();
2357 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2359 // Compute the information on the instructions to match.
2360 AsmMatcherInfo Info(AsmParser, Target, Records);
2363 // Sort the instruction table using the partial order on classes. We use
2364 // stable_sort to ensure that ambiguous instructions are still
2365 // deterministically ordered.
2366 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2367 less_ptr<MatchableInfo>());
2369 DEBUG_WITH_TYPE("instruction_info", {
2370 for (std::vector<MatchableInfo*>::iterator
2371 it = Info.Matchables.begin(), ie = Info.Matchables.end();
2376 // Check for ambiguous matchables.
2377 DEBUG_WITH_TYPE("ambiguous_instrs", {
2378 unsigned NumAmbiguous = 0;
2379 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) {
2380 for (unsigned j = i + 1; j != e; ++j) {
2381 MatchableInfo &A = *Info.Matchables[i];
2382 MatchableInfo &B = *Info.Matchables[j];
2384 if (A.couldMatchAmbiguouslyWith(B)) {
2385 errs() << "warning: ambiguous matchables:\n";
2387 errs() << "\nis incomparable with:\n";
2395 errs() << "warning: " << NumAmbiguous
2396 << " ambiguous matchables!\n";
2399 // Compute the information on the custom operand parsing.
2400 Info.buildOperandMatchInfo();
2402 // Write the output.
2404 // Information for the class declaration.
2405 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2406 OS << "#undef GET_ASSEMBLER_HEADER\n";
2407 OS << " // This should be included into the middle of the declaration of\n";
2408 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
2409 OS << " unsigned ComputeAvailableFeatures(uint64_t FeatureBits) const;\n";
2410 OS << " bool ConvertToMCInst(unsigned Kind, MCInst &Inst, "
2411 << "unsigned Opcode,\n"
2412 << " const SmallVectorImpl<MCParsedAsmOperand*> "
2414 OS << " bool MnemonicIsValid(StringRef Mnemonic);\n";
2415 OS << " unsigned MatchInstructionImpl(\n";
2416 OS << " const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2417 OS << " MCInst &Inst, unsigned &ErrorInfo, unsigned VariantID = 0);\n";
2419 if (Info.OperandMatchInfo.size()) {
2420 OS << "\n enum OperandMatchResultTy {\n";
2421 OS << " MatchOperand_Success, // operand matched successfully\n";
2422 OS << " MatchOperand_NoMatch, // operand did not match\n";
2423 OS << " MatchOperand_ParseFail // operand matched but had errors\n";
2425 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
2426 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2427 OS << " StringRef Mnemonic);\n";
2429 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
2430 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2431 OS << " unsigned MCK);\n\n";
2434 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2436 // Emit the operand match diagnostic enum names.
2437 OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
2438 OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
2439 emitOperandDiagnosticTypes(Info, OS);
2440 OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
2443 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2444 OS << "#undef GET_REGISTER_MATCHER\n\n";
2446 // Emit the subtarget feature enumeration.
2447 emitSubtargetFeatureFlagEnumeration(Info, OS);
2449 // Emit the function to match a register name to number.
2450 // This should be omitted for Mips target
2451 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName"))
2452 emitMatchRegisterName(Target, AsmParser, OS);
2454 OS << "#endif // GET_REGISTER_MATCHER\n\n";
2456 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
2457 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
2459 // Generate the helper function to get the names for subtarget features.
2460 emitGetSubtargetFeatureName(Info, OS);
2462 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
2464 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2465 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
2467 // Generate the function that remaps for mnemonic aliases.
2468 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info);
2470 // Generate the unified function to convert operands into an MCInst.
2471 emitConvertToMCInst(Target, ClassName, Info.Matchables, OS);
2473 // Emit the enumeration for classes which participate in matching.
2474 emitMatchClassEnumeration(Target, Info.Classes, OS);
2476 // Emit the routine to match token strings to their match class.
2477 emitMatchTokenString(Target, Info.Classes, OS);
2479 // Emit the subclass predicate routine.
2480 emitIsSubclass(Target, Info.Classes, OS);
2482 // Emit the routine to validate an operand against a match class.
2483 emitValidateOperandClass(Info, OS);
2485 // Emit the available features compute function.
2486 emitComputeAvailableFeatures(Info, OS);
2489 size_t MaxNumOperands = 0;
2490 for (std::vector<MatchableInfo*>::const_iterator it =
2491 Info.Matchables.begin(), ie = Info.Matchables.end();
2493 MaxNumOperands = std::max(MaxNumOperands, (*it)->AsmOperands.size());
2495 // Emit the static match table; unused classes get initalized to 0 which is
2496 // guaranteed to be InvalidMatchClass.
2498 // FIXME: We can reduce the size of this table very easily. First, we change
2499 // it so that store the kinds in separate bit-fields for each index, which
2500 // only needs to be the max width used for classes at that index (we also need
2501 // to reject based on this during classification). If we then make sure to
2502 // order the match kinds appropriately (putting mnemonics last), then we
2503 // should only end up using a few bits for each class, especially the ones
2504 // following the mnemonic.
2505 OS << "namespace {\n";
2506 OS << " struct MatchEntry {\n";
2507 OS << " static const char *const MnemonicTable;\n";
2508 OS << " uint32_t Mnemonic;\n";
2509 OS << " uint16_t Opcode;\n";
2510 OS << " " << getMinimalTypeForRange(Info.Matchables.size())
2512 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2513 << " RequiredFeatures;\n";
2514 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2515 << " Classes[" << MaxNumOperands << "];\n";
2516 OS << " uint8_t AsmVariantID;\n\n";
2517 OS << " StringRef getMnemonic() const {\n";
2518 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2519 OS << " MnemonicTable[Mnemonic]);\n";
2523 OS << " // Predicate for searching for an opcode.\n";
2524 OS << " struct LessOpcode {\n";
2525 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
2526 OS << " return LHS.getMnemonic() < RHS;\n";
2528 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
2529 OS << " return LHS < RHS.getMnemonic();\n";
2531 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
2532 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
2536 OS << "} // end anonymous namespace.\n\n";
2538 StringToOffsetTable StringTable;
2540 OS << "static const MatchEntry MatchTable["
2541 << Info.Matchables.size() << "] = {\n";
2543 for (std::vector<MatchableInfo*>::const_iterator it =
2544 Info.Matchables.begin(), ie = Info.Matchables.end();
2546 MatchableInfo &II = **it;
2548 // Store a pascal-style length byte in the mnemonic.
2549 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2550 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2551 << " /* " << II.Mnemonic << " */, "
2552 << Target.getName() << "::"
2553 << II.getResultInst()->TheDef->getName() << ", "
2554 << II.ConversionFnKind << ", ";
2556 // Write the required features mask.
2557 if (!II.RequiredFeatures.empty()) {
2558 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2560 OS << II.RequiredFeatures[i]->getEnumName();
2566 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
2567 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
2570 OS << Op.Class->Name;
2572 OS << " }, " << II.AsmVariantID;
2578 OS << "const char *const MatchEntry::MnemonicTable =\n";
2579 StringTable.EmitString(OS);
2582 // A method to determine if a mnemonic is in the list.
2583 OS << "bool " << Target.getName() << ClassName << "::\n"
2584 << "MnemonicIsValid(StringRef Mnemonic) {\n";
2585 OS << " // Search the table.\n";
2586 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2587 OS << " std::equal_range(MatchTable, MatchTable+"
2588 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n";
2589 OS << " return MnemonicRange.first != MnemonicRange.second;\n";
2592 // Finally, build the match function.
2594 << Target.getName() << ClassName << "::\n"
2595 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
2597 OS << " MCInst &Inst, unsigned &ErrorInfo, ";
2598 OS << "unsigned VariantID) {\n";
2600 // Emit code to get the available features.
2601 OS << " // Get the current feature set.\n";
2602 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2604 OS << " // Get the instruction mnemonic, which is the first token.\n";
2605 OS << " StringRef Mnemonic = ((" << Target.getName()
2606 << "Operand*)Operands[0])->getToken();\n\n";
2608 if (HasMnemonicAliases) {
2609 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
2610 OS << " // FIXME : Add an entry in AsmParserVariant to check this.\n";
2611 OS << " if (!VariantID)\n";
2612 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
2615 // Emit code to compute the class list for this operand vector.
2616 OS << " // Eliminate obvious mismatches.\n";
2617 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
2618 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
2619 OS << " return Match_InvalidOperand;\n";
2622 OS << " // Some state to try to produce better error messages.\n";
2623 OS << " bool HadMatchOtherThanFeatures = false;\n";
2624 OS << " bool HadMatchOtherThanPredicate = false;\n";
2625 OS << " unsigned RetCode = Match_InvalidOperand;\n";
2626 OS << " unsigned MissingFeatures = ~0U;\n";
2627 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
2628 OS << " // wrong for all instances of the instruction.\n";
2629 OS << " ErrorInfo = ~0U;\n";
2631 // Emit code to search the table.
2632 OS << " // Search the table.\n";
2633 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2634 OS << " std::equal_range(MatchTable, MatchTable+"
2635 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n";
2637 OS << " // Return a more specific error code if no mnemonics match.\n";
2638 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2639 OS << " return Match_MnemonicFail;\n\n";
2641 OS << " for (const MatchEntry *it = MnemonicRange.first, "
2642 << "*ie = MnemonicRange.second;\n";
2643 OS << " it != ie; ++it) {\n";
2645 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2646 OS << " assert(Mnemonic == it->getMnemonic());\n";
2648 // Emit check that the subclasses match.
2649 OS << " if (VariantID != it->AsmVariantID) continue;\n";
2650 OS << " bool OperandsValid = true;\n";
2651 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
2652 OS << " if (i + 1 >= Operands.size()) {\n";
2653 OS << " OperandsValid = (it->Classes[i] == " <<"InvalidMatchClass);\n";
2654 OS << " if (!OperandsValid) ErrorInfo = i + 1;\n";
2657 OS << " unsigned Diag = validateOperandClass(Operands[i+1],\n";
2659 OS << "(MatchClassKind)it->Classes[i]);\n";
2660 OS << " if (Diag == Match_Success)\n";
2661 OS << " continue;\n";
2662 OS << " // If this operand is broken for all of the instances of this\n";
2663 OS << " // mnemonic, keep track of it so we can report loc info.\n";
2664 OS << " // If we already had a match that only failed due to a\n";
2665 OS << " // target predicate, that diagnostic is preferred.\n";
2666 OS << " if (!HadMatchOtherThanPredicate &&\n";
2667 OS << " (it == MnemonicRange.first || ErrorInfo <= i+1)) {\n";
2668 OS << " ErrorInfo = i+1;\n";
2669 OS << " // InvalidOperand is the default. Prefer specificity.\n";
2670 OS << " if (Diag != Match_InvalidOperand)\n";
2671 OS << " RetCode = Diag;\n";
2673 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
2674 OS << " OperandsValid = false;\n";
2678 OS << " if (!OperandsValid) continue;\n";
2680 // Emit check that the required features are available.
2681 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2682 << "!= it->RequiredFeatures) {\n";
2683 OS << " HadMatchOtherThanFeatures = true;\n";
2684 OS << " unsigned NewMissingFeatures = it->RequiredFeatures & "
2685 "~AvailableFeatures;\n";
2686 OS << " if (CountPopulation_32(NewMissingFeatures) <= "
2687 "CountPopulation_32(MissingFeatures))\n";
2688 OS << " MissingFeatures = NewMissingFeatures;\n";
2689 OS << " continue;\n";
2692 OS << " // We have selected a definite instruction, convert the parsed\n"
2693 << " // operands into the appropriate MCInst.\n";
2694 OS << " if (!ConvertToMCInst(it->ConvertFn, Inst,\n"
2695 << " it->Opcode, Operands))\n";
2696 OS << " return Match_ConversionFail;\n";
2699 // Verify the instruction with the target-specific match predicate function.
2700 OS << " // We have a potential match. Check the target predicate to\n"
2701 << " // handle any context sensitive constraints.\n"
2702 << " unsigned MatchResult;\n"
2703 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
2704 << " Match_Success) {\n"
2705 << " Inst.clear();\n"
2706 << " RetCode = MatchResult;\n"
2707 << " HadMatchOtherThanPredicate = true;\n"
2711 // Call the post-processing function, if used.
2712 std::string InsnCleanupFn =
2713 AsmParser->getValueAsString("AsmParserInstCleanup");
2714 if (!InsnCleanupFn.empty())
2715 OS << " " << InsnCleanupFn << "(Inst);\n";
2717 OS << " return Match_Success;\n";
2720 OS << " // Okay, we had no match. Try to return a useful error code.\n";
2721 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)";
2722 OS << " return RetCode;\n";
2723 OS << " // Missing feature matches return which features were missing\n";
2724 OS << " ErrorInfo = MissingFeatures;\n";
2725 OS << " return Match_MissingFeature;\n";
2728 if (Info.OperandMatchInfo.size())
2729 emitCustomOperandParsing(OS, Target, Info, ClassName);
2731 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
2736 void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
2737 emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
2738 AsmMatcherEmitter(RK).run(OS);
2741 } // End llvm namespace