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;
190 /// isRegisterClass() - Check if this is a register class.
191 bool isRegisterClass() const {
192 return Kind >= RegisterClass0 && Kind < UserClass0;
195 /// isUserClass() - Check if this is a user defined class.
196 bool isUserClass() const {
197 return Kind >= UserClass0;
200 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
201 /// are related if they are in the same class hierarchy.
202 bool isRelatedTo(const ClassInfo &RHS) const {
203 // Tokens are only related to tokens.
204 if (Kind == Token || RHS.Kind == Token)
205 return Kind == Token && RHS.Kind == Token;
207 // Registers classes are only related to registers classes, and only if
208 // their intersection is non-empty.
209 if (isRegisterClass() || RHS.isRegisterClass()) {
210 if (!isRegisterClass() || !RHS.isRegisterClass())
213 std::set<Record*> Tmp;
214 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
215 std::set_intersection(Registers.begin(), Registers.end(),
216 RHS.Registers.begin(), RHS.Registers.end(),
222 // Otherwise we have two users operands; they are related if they are in the
223 // same class hierarchy.
225 // FIXME: This is an oversimplification, they should only be related if they
226 // intersect, however we don't have that information.
227 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
228 const ClassInfo *Root = this;
229 while (!Root->SuperClasses.empty())
230 Root = Root->SuperClasses.front();
232 const ClassInfo *RHSRoot = &RHS;
233 while (!RHSRoot->SuperClasses.empty())
234 RHSRoot = RHSRoot->SuperClasses.front();
236 return Root == RHSRoot;
239 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
240 bool isSubsetOf(const ClassInfo &RHS) const {
241 // This is a subset of RHS if it is the same class...
245 // ... or if any of its super classes are a subset of RHS.
246 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
247 ie = SuperClasses.end(); it != ie; ++it)
248 if ((*it)->isSubsetOf(RHS))
254 /// operator< - Compare two classes.
255 bool operator<(const ClassInfo &RHS) const {
259 // Unrelated classes can be ordered by kind.
260 if (!isRelatedTo(RHS))
261 return Kind < RHS.Kind;
265 llvm_unreachable("Invalid kind!");
268 // This class precedes the RHS if it is a proper subset of the RHS.
271 if (RHS.isSubsetOf(*this))
274 // Otherwise, order by name to ensure we have a total ordering.
275 return ValueName < RHS.ValueName;
280 /// MatchableInfo - Helper class for storing the necessary information for an
281 /// instruction or alias which is capable of being matched.
282 struct MatchableInfo {
284 /// Token - This is the token that the operand came from.
287 /// The unique class instance this operand should match.
290 /// The operand name this is, if anything.
293 /// The suboperand index within SrcOpName, or -1 for the entire operand.
296 /// Register record if this token is singleton register.
297 Record *SingletonReg;
299 explicit AsmOperand(StringRef T) : Token(T), Class(0), SubOpIdx(-1),
303 /// ResOperand - This represents a single operand in the result instruction
304 /// generated by the match. In cases (like addressing modes) where a single
305 /// assembler operand expands to multiple MCOperands, this represents the
306 /// single assembler operand, not the MCOperand.
309 /// RenderAsmOperand - This represents an operand result that is
310 /// generated by calling the render method on the assembly operand. The
311 /// corresponding AsmOperand is specified by AsmOperandNum.
314 /// TiedOperand - This represents a result operand that is a duplicate of
315 /// a previous result operand.
318 /// ImmOperand - This represents an immediate value that is dumped into
322 /// RegOperand - This represents a fixed register that is dumped in.
327 /// This is the operand # in the AsmOperands list that this should be
329 unsigned AsmOperandNum;
331 /// TiedOperandNum - This is the (earlier) result operand that should be
333 unsigned TiedOperandNum;
335 /// ImmVal - This is the immediate value added to the instruction.
338 /// Register - This is the register record.
342 /// MINumOperands - The number of MCInst operands populated by this
344 unsigned MINumOperands;
346 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
348 X.Kind = RenderAsmOperand;
349 X.AsmOperandNum = AsmOpNum;
350 X.MINumOperands = NumOperands;
354 static ResOperand getTiedOp(unsigned TiedOperandNum) {
356 X.Kind = TiedOperand;
357 X.TiedOperandNum = TiedOperandNum;
362 static ResOperand getImmOp(int64_t Val) {
370 static ResOperand getRegOp(Record *Reg) {
379 /// AsmVariantID - Target's assembly syntax variant no.
382 /// TheDef - This is the definition of the instruction or InstAlias that this
383 /// matchable came from.
384 Record *const TheDef;
386 /// DefRec - This is the definition that it came from.
387 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
389 const CodeGenInstruction *getResultInst() const {
390 if (DefRec.is<const CodeGenInstruction*>())
391 return DefRec.get<const CodeGenInstruction*>();
392 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
395 /// ResOperands - This is the operand list that should be built for the result
397 SmallVector<ResOperand, 8> ResOperands;
399 /// AsmString - The assembly string for this instruction (with variants
400 /// removed), e.g. "movsx $src, $dst".
401 std::string AsmString;
403 /// Mnemonic - This is the first token of the matched instruction, its
407 /// AsmOperands - The textual operands that this instruction matches,
408 /// annotated with a class and where in the OperandList they were defined.
409 /// This directly corresponds to the tokenized AsmString after the mnemonic is
411 SmallVector<AsmOperand, 8> AsmOperands;
413 /// Predicates - The required subtarget features to match this instruction.
414 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
416 /// ConversionFnKind - The enum value which is passed to the generated
417 /// ConvertToMCInst to convert parsed operands into an MCInst for this
419 std::string ConversionFnKind;
421 MatchableInfo(const CodeGenInstruction &CGI)
422 : AsmVariantID(0), TheDef(CGI.TheDef), DefRec(&CGI),
423 AsmString(CGI.AsmString) {
426 MatchableInfo(const CodeGenInstAlias *Alias)
427 : AsmVariantID(0), TheDef(Alias->TheDef), DefRec(Alias),
428 AsmString(Alias->AsmString) {
431 // Two-operand aliases clone from the main matchable, but mark the second
432 // operand as a tied operand of the first for purposes of the assembler.
433 void formTwoOperandAlias(StringRef Constraint);
435 void initialize(const AsmMatcherInfo &Info,
436 SmallPtrSet<Record*, 16> &SingletonRegisters,
437 int AsmVariantNo, std::string &RegisterPrefix);
439 /// validate - Return true if this matchable is a valid thing to match against
440 /// and perform a bunch of validity checking.
441 bool validate(StringRef CommentDelimiter, bool Hack) const;
443 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
444 /// if present, from specified token.
446 extractSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info,
447 std::string &RegisterPrefix);
449 /// findAsmOperand - Find the AsmOperand with the specified name and
450 /// suboperand index.
451 int findAsmOperand(StringRef N, int SubOpIdx) const {
452 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
453 if (N == AsmOperands[i].SrcOpName &&
454 SubOpIdx == AsmOperands[i].SubOpIdx)
459 /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
460 /// This does not check the suboperand index.
461 int findAsmOperandNamed(StringRef N) const {
462 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
463 if (N == AsmOperands[i].SrcOpName)
468 void buildInstructionResultOperands();
469 void buildAliasResultOperands();
471 /// operator< - Compare two matchables.
472 bool operator<(const MatchableInfo &RHS) const {
473 // The primary comparator is the instruction mnemonic.
474 if (Mnemonic != RHS.Mnemonic)
475 return Mnemonic < RHS.Mnemonic;
477 if (AsmOperands.size() != RHS.AsmOperands.size())
478 return AsmOperands.size() < RHS.AsmOperands.size();
480 // Compare lexicographically by operand. The matcher validates that other
481 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
482 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
483 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
485 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
492 /// couldMatchAmbiguouslyWith - Check whether this matchable could
493 /// ambiguously match the same set of operands as \arg RHS (without being a
494 /// strictly superior match).
495 bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) {
496 // The primary comparator is the instruction mnemonic.
497 if (Mnemonic != RHS.Mnemonic)
500 // The number of operands is unambiguous.
501 if (AsmOperands.size() != RHS.AsmOperands.size())
504 // Otherwise, make sure the ordering of the two instructions is unambiguous
505 // by checking that either (a) a token or operand kind discriminates them,
506 // or (b) the ordering among equivalent kinds is consistent.
508 // Tokens and operand kinds are unambiguous (assuming a correct target
510 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
511 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
512 AsmOperands[i].Class->Kind == ClassInfo::Token)
513 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
514 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
517 // Otherwise, this operand could commute if all operands are equivalent, or
518 // there is a pair of operands that compare less than and a pair that
519 // compare greater than.
520 bool HasLT = false, HasGT = false;
521 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
522 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
524 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
528 return !(HasLT ^ HasGT);
534 void tokenizeAsmString(const AsmMatcherInfo &Info);
537 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
538 /// feature which participates in instruction matching.
539 struct SubtargetFeatureInfo {
540 /// \brief The predicate record for this feature.
543 /// \brief An unique index assigned to represent this feature.
546 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
548 /// \brief The name of the enumerated constant identifying this feature.
549 std::string getEnumName() const {
550 return "Feature_" + TheDef->getName();
554 struct OperandMatchEntry {
555 unsigned OperandMask;
559 static OperandMatchEntry create(MatchableInfo* mi, ClassInfo *ci,
562 X.OperandMask = opMask;
570 class AsmMatcherInfo {
573 RecordKeeper &Records;
575 /// The tablegen AsmParser record.
578 /// Target - The target information.
579 CodeGenTarget &Target;
581 /// The classes which are needed for matching.
582 std::vector<ClassInfo*> Classes;
584 /// The information on the matchables to match.
585 std::vector<MatchableInfo*> Matchables;
587 /// Info for custom matching operands by user defined methods.
588 std::vector<OperandMatchEntry> OperandMatchInfo;
590 /// Map of Register records to their class information.
591 std::map<Record*, ClassInfo*> RegisterClasses;
593 /// Map of Predicate records to their subtarget information.
594 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
597 /// Map of token to class information which has already been constructed.
598 std::map<std::string, ClassInfo*> TokenClasses;
600 /// Map of RegisterClass records to their class information.
601 std::map<Record*, ClassInfo*> RegisterClassClasses;
603 /// Map of AsmOperandClass records to their class information.
604 std::map<Record*, ClassInfo*> AsmOperandClasses;
607 /// getTokenClass - Lookup or create the class for the given token.
608 ClassInfo *getTokenClass(StringRef Token);
610 /// getOperandClass - Lookup or create the class for the given operand.
611 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
613 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
615 /// buildRegisterClasses - Build the ClassInfo* instances for register
617 void buildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
619 /// buildOperandClasses - Build the ClassInfo* instances for user defined
621 void buildOperandClasses();
623 void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
625 void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
626 MatchableInfo::AsmOperand &Op);
629 AsmMatcherInfo(Record *AsmParser,
630 CodeGenTarget &Target,
631 RecordKeeper &Records);
633 /// buildInfo - Construct the various tables used during matching.
636 /// buildOperandMatchInfo - Build the necessary information to handle user
637 /// defined operand parsing methods.
638 void buildOperandMatchInfo();
640 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
642 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
643 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
644 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
645 SubtargetFeatures.find(Def);
646 return I == SubtargetFeatures.end() ? 0 : I->second;
649 RecordKeeper &getRecords() const {
654 } // End anonymous namespace
656 void MatchableInfo::dump() {
657 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
659 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
660 AsmOperand &Op = AsmOperands[i];
661 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
662 errs() << '\"' << Op.Token << "\"\n";
666 static std::pair<StringRef, StringRef>
667 parseTwoOperandConstraint(StringRef S, SMLoc Loc) {
668 // Split via the '='.
669 std::pair<StringRef, StringRef> Ops = S.split('=');
670 if (Ops.second == "")
671 throw TGError(Loc, "missing '=' in two-operand alias constraint");
672 // Trim whitespace and the leading '$' on the operand names.
673 size_t start = Ops.first.find_first_of('$');
674 if (start == std::string::npos)
675 throw TGError(Loc, "expected '$' prefix on asm operand name");
676 Ops.first = Ops.first.slice(start + 1, std::string::npos);
677 size_t end = Ops.first.find_last_of(" \t");
678 Ops.first = Ops.first.slice(0, end);
679 // Now the second operand.
680 start = Ops.second.find_first_of('$');
681 if (start == std::string::npos)
682 throw TGError(Loc, "expected '$' prefix on asm operand name");
683 Ops.second = Ops.second.slice(start + 1, std::string::npos);
684 end = Ops.second.find_last_of(" \t");
685 Ops.first = Ops.first.slice(0, end);
689 void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
690 // Figure out which operands are aliased and mark them as tied.
691 std::pair<StringRef, StringRef> Ops =
692 parseTwoOperandConstraint(Constraint, TheDef->getLoc());
694 // Find the AsmOperands that refer to the operands we're aliasing.
695 int SrcAsmOperand = findAsmOperandNamed(Ops.first);
696 int DstAsmOperand = findAsmOperandNamed(Ops.second);
697 if (SrcAsmOperand == -1)
698 throw TGError(TheDef->getLoc(),
699 "unknown source two-operand alias operand '" +
700 Ops.first.str() + "'.");
701 if (DstAsmOperand == -1)
702 throw TGError(TheDef->getLoc(),
703 "unknown destination two-operand alias operand '" +
704 Ops.second.str() + "'.");
706 // Find the ResOperand that refers to the operand we're aliasing away
707 // and update it to refer to the combined operand instead.
708 for (unsigned i = 0, e = ResOperands.size(); i != e; ++i) {
709 ResOperand &Op = ResOperands[i];
710 if (Op.Kind == ResOperand::RenderAsmOperand &&
711 Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
712 Op.AsmOperandNum = DstAsmOperand;
716 // Remove the AsmOperand for the alias operand.
717 AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
718 // Adjust the ResOperand references to any AsmOperands that followed
719 // the one we just deleted.
720 for (unsigned i = 0, e = ResOperands.size(); i != e; ++i) {
721 ResOperand &Op = ResOperands[i];
724 // Nothing to do for operands that don't reference AsmOperands.
726 case ResOperand::RenderAsmOperand:
727 if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
730 case ResOperand::TiedOperand:
731 if (Op.TiedOperandNum > (unsigned)SrcAsmOperand)
738 void MatchableInfo::initialize(const AsmMatcherInfo &Info,
739 SmallPtrSet<Record*, 16> &SingletonRegisters,
740 int AsmVariantNo, std::string &RegisterPrefix) {
741 AsmVariantID = AsmVariantNo;
743 CodeGenInstruction::FlattenAsmStringVariants(AsmString, AsmVariantNo);
745 tokenizeAsmString(Info);
747 // Compute the require features.
748 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates");
749 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
750 if (SubtargetFeatureInfo *Feature =
751 Info.getSubtargetFeature(Predicates[i]))
752 RequiredFeatures.push_back(Feature);
754 // Collect singleton registers, if used.
755 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
756 extractSingletonRegisterForAsmOperand(i, Info, RegisterPrefix);
757 if (Record *Reg = AsmOperands[i].SingletonReg)
758 SingletonRegisters.insert(Reg);
762 /// tokenizeAsmString - Tokenize a simplified assembly string.
763 void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info) {
764 StringRef String = AsmString;
767 for (unsigned i = 0, e = String.size(); i != e; ++i) {
777 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
780 if (!isspace(String[i]) && String[i] != ',')
781 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
787 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
791 assert(i != String.size() && "Invalid quoted character");
792 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
798 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
802 // If this isn't "${", treat like a normal token.
803 if (i + 1 == String.size() || String[i + 1] != '{') {
808 StringRef::iterator End = std::find(String.begin() + i, String.end(),'}');
809 assert(End != String.end() && "Missing brace in operand reference!");
810 size_t EndPos = End - String.begin();
811 AsmOperands.push_back(AsmOperand(String.slice(i, EndPos+1)));
819 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
828 if (InTok && Prev != String.size())
829 AsmOperands.push_back(AsmOperand(String.substr(Prev)));
831 // The first token of the instruction is the mnemonic, which must be a
832 // simple string, not a $foo variable or a singleton register.
833 if (AsmOperands.empty())
834 throw TGError(TheDef->getLoc(),
835 "Instruction '" + TheDef->getName() + "' has no tokens");
836 Mnemonic = AsmOperands[0].Token;
837 if (Mnemonic.empty())
838 throw TGError(TheDef->getLoc(),
839 "Missing instruction mnemonic");
840 // FIXME : Check and raise an error if it is a register.
841 if (Mnemonic[0] == '$')
842 throw TGError(TheDef->getLoc(),
843 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
845 // Remove the first operand, it is tracked in the mnemonic field.
846 AsmOperands.erase(AsmOperands.begin());
849 bool MatchableInfo::validate(StringRef CommentDelimiter, bool Hack) const {
850 // Reject matchables with no .s string.
851 if (AsmString.empty())
852 throw TGError(TheDef->getLoc(), "instruction with empty asm string");
854 // Reject any matchables with a newline in them, they should be marked
855 // isCodeGenOnly if they are pseudo instructions.
856 if (AsmString.find('\n') != std::string::npos)
857 throw TGError(TheDef->getLoc(),
858 "multiline instruction is not valid for the asmparser, "
859 "mark it isCodeGenOnly");
861 // Remove comments from the asm string. We know that the asmstring only
863 if (!CommentDelimiter.empty() &&
864 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
865 throw TGError(TheDef->getLoc(),
866 "asmstring for instruction has comment character in it, "
867 "mark it isCodeGenOnly");
869 // Reject matchables with operand modifiers, these aren't something we can
870 // handle, the target should be refactored to use operands instead of
873 // Also, check for instructions which reference the operand multiple times;
874 // this implies a constraint we would not honor.
875 std::set<std::string> OperandNames;
876 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
877 StringRef Tok = AsmOperands[i].Token;
878 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
879 throw TGError(TheDef->getLoc(),
880 "matchable with operand modifier '" + Tok.str() +
881 "' not supported by asm matcher. Mark isCodeGenOnly!");
883 // Verify that any operand is only mentioned once.
884 // We reject aliases and ignore instructions for now.
885 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
887 throw TGError(TheDef->getLoc(),
888 "ERROR: matchable with tied operand '" + Tok.str() +
889 "' can never be matched!");
890 // FIXME: Should reject these. The ARM backend hits this with $lane in a
891 // bunch of instructions. It is unclear what the right answer is.
893 errs() << "warning: '" << TheDef->getName() << "': "
894 << "ignoring instruction with tied operand '"
895 << Tok.str() << "'\n";
904 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
905 /// if present, from specified token.
907 extractSingletonRegisterForAsmOperand(unsigned OperandNo,
908 const AsmMatcherInfo &Info,
909 std::string &RegisterPrefix) {
910 StringRef Tok = AsmOperands[OperandNo].Token;
911 if (RegisterPrefix.empty()) {
912 std::string LoweredTok = Tok.lower();
913 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
914 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
918 if (!Tok.startswith(RegisterPrefix))
921 StringRef RegName = Tok.substr(RegisterPrefix.size());
922 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
923 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
925 // If there is no register prefix (i.e. "%" in "%eax"), then this may
926 // be some random non-register token, just ignore it.
930 static std::string getEnumNameForToken(StringRef Str) {
933 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
935 case '*': Res += "_STAR_"; break;
936 case '%': Res += "_PCT_"; break;
937 case ':': Res += "_COLON_"; break;
938 case '!': Res += "_EXCLAIM_"; break;
939 case '.': Res += "_DOT_"; break;
944 Res += "_" + utostr((unsigned) *it) + "_";
951 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
952 ClassInfo *&Entry = TokenClasses[Token];
955 Entry = new ClassInfo();
956 Entry->Kind = ClassInfo::Token;
957 Entry->ClassName = "Token";
958 Entry->Name = "MCK_" + getEnumNameForToken(Token);
959 Entry->ValueName = Token;
960 Entry->PredicateMethod = "<invalid>";
961 Entry->RenderMethod = "<invalid>";
962 Entry->ParserMethod = "";
963 Classes.push_back(Entry);
970 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
972 Record *Rec = OI.Rec;
974 Rec = dynamic_cast<DefInit*>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
975 return getOperandClass(Rec, SubOpIdx);
979 AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
980 if (Rec->isSubClassOf("RegisterOperand")) {
981 // RegisterOperand may have an associated ParserMatchClass. If it does,
982 // use it, else just fall back to the underlying register class.
983 const RecordVal *R = Rec->getValue("ParserMatchClass");
984 if (R == 0 || R->getValue() == 0)
985 throw "Record `" + Rec->getName() +
986 "' does not have a ParserMatchClass!\n";
988 if (DefInit *DI= dynamic_cast<DefInit*>(R->getValue())) {
989 Record *MatchClass = DI->getDef();
990 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
994 // No custom match class. Just use the register class.
995 Record *ClassRec = Rec->getValueAsDef("RegClass");
997 throw TGError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
998 "' has no associated register class!\n");
999 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
1001 throw TGError(Rec->getLoc(), "register class has no class info!");
1005 if (Rec->isSubClassOf("RegisterClass")) {
1006 if (ClassInfo *CI = RegisterClassClasses[Rec])
1008 throw TGError(Rec->getLoc(), "register class has no class info!");
1011 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1012 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1013 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1016 throw TGError(Rec->getLoc(), "operand has no match class!");
1019 void AsmMatcherInfo::
1020 buildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
1021 const std::vector<CodeGenRegister*> &Registers =
1022 Target.getRegBank().getRegisters();
1023 ArrayRef<CodeGenRegisterClass*> RegClassList =
1024 Target.getRegBank().getRegClasses();
1026 // The register sets used for matching.
1027 std::set< std::set<Record*> > RegisterSets;
1029 // Gather the defined sets.
1030 for (ArrayRef<CodeGenRegisterClass*>::const_iterator it =
1031 RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it)
1032 RegisterSets.insert(std::set<Record*>(
1033 (*it)->getOrder().begin(), (*it)->getOrder().end()));
1035 // Add any required singleton sets.
1036 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1037 ie = SingletonRegisters.end(); it != ie; ++it) {
1039 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
1042 // Introduce derived sets where necessary (when a register does not determine
1043 // a unique register set class), and build the mapping of registers to the set
1044 // they should classify to.
1045 std::map<Record*, std::set<Record*> > RegisterMap;
1046 for (std::vector<CodeGenRegister*>::const_iterator it = Registers.begin(),
1047 ie = Registers.end(); it != ie; ++it) {
1048 const CodeGenRegister &CGR = **it;
1049 // Compute the intersection of all sets containing this register.
1050 std::set<Record*> ContainingSet;
1052 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
1053 ie = RegisterSets.end(); it != ie; ++it) {
1054 if (!it->count(CGR.TheDef))
1057 if (ContainingSet.empty()) {
1058 ContainingSet = *it;
1062 std::set<Record*> Tmp;
1063 std::swap(Tmp, ContainingSet);
1064 std::insert_iterator< std::set<Record*> > II(ContainingSet,
1065 ContainingSet.begin());
1066 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(), II);
1069 if (!ContainingSet.empty()) {
1070 RegisterSets.insert(ContainingSet);
1071 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
1075 // Construct the register classes.
1076 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
1078 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
1079 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
1080 ClassInfo *CI = new ClassInfo();
1081 CI->Kind = ClassInfo::RegisterClass0 + Index;
1082 CI->ClassName = "Reg" + utostr(Index);
1083 CI->Name = "MCK_Reg" + utostr(Index);
1085 CI->PredicateMethod = ""; // unused
1086 CI->RenderMethod = "addRegOperands";
1087 CI->Registers = *it;
1088 Classes.push_back(CI);
1089 RegisterSetClasses.insert(std::make_pair(*it, CI));
1092 // Find the superclasses; we could compute only the subgroup lattice edges,
1093 // but there isn't really a point.
1094 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
1095 ie = RegisterSets.end(); it != ie; ++it) {
1096 ClassInfo *CI = RegisterSetClasses[*it];
1097 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
1098 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
1100 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
1101 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
1104 // Name the register classes which correspond to a user defined RegisterClass.
1105 for (ArrayRef<CodeGenRegisterClass*>::const_iterator
1106 it = RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) {
1107 const CodeGenRegisterClass &RC = **it;
1108 // Def will be NULL for non-user defined register classes.
1109 Record *Def = RC.getDef();
1112 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(RC.getOrder().begin(),
1113 RC.getOrder().end())];
1114 if (CI->ValueName.empty()) {
1115 CI->ClassName = RC.getName();
1116 CI->Name = "MCK_" + RC.getName();
1117 CI->ValueName = RC.getName();
1119 CI->ValueName = CI->ValueName + "," + RC.getName();
1121 RegisterClassClasses.insert(std::make_pair(Def, CI));
1124 // Populate the map for individual registers.
1125 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
1126 ie = RegisterMap.end(); it != ie; ++it)
1127 RegisterClasses[it->first] = RegisterSetClasses[it->second];
1129 // Name the register classes which correspond to singleton registers.
1130 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1131 ie = SingletonRegisters.end(); it != ie; ++it) {
1133 ClassInfo *CI = RegisterClasses[Rec];
1134 assert(CI && "Missing singleton register class info!");
1136 if (CI->ValueName.empty()) {
1137 CI->ClassName = Rec->getName();
1138 CI->Name = "MCK_" + Rec->getName();
1139 CI->ValueName = Rec->getName();
1141 CI->ValueName = CI->ValueName + "," + Rec->getName();
1145 void AsmMatcherInfo::buildOperandClasses() {
1146 std::vector<Record*> AsmOperands =
1147 Records.getAllDerivedDefinitions("AsmOperandClass");
1149 // Pre-populate AsmOperandClasses map.
1150 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1151 ie = AsmOperands.end(); it != ie; ++it)
1152 AsmOperandClasses[*it] = new ClassInfo();
1155 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1156 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
1157 ClassInfo *CI = AsmOperandClasses[*it];
1158 CI->Kind = ClassInfo::UserClass0 + Index;
1160 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
1161 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
1162 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
1164 PrintError((*it)->getLoc(), "Invalid super class reference!");
1168 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1170 PrintError((*it)->getLoc(), "Invalid super class reference!");
1172 CI->SuperClasses.push_back(SC);
1174 CI->ClassName = (*it)->getValueAsString("Name");
1175 CI->Name = "MCK_" + CI->ClassName;
1176 CI->ValueName = (*it)->getName();
1178 // Get or construct the predicate method name.
1179 Init *PMName = (*it)->getValueInit("PredicateMethod");
1180 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
1181 CI->PredicateMethod = SI->getValue();
1183 assert(dynamic_cast<UnsetInit*>(PMName) &&
1184 "Unexpected PredicateMethod field!");
1185 CI->PredicateMethod = "is" + CI->ClassName;
1188 // Get or construct the render method name.
1189 Init *RMName = (*it)->getValueInit("RenderMethod");
1190 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
1191 CI->RenderMethod = SI->getValue();
1193 assert(dynamic_cast<UnsetInit*>(RMName) &&
1194 "Unexpected RenderMethod field!");
1195 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1198 // Get the parse method name or leave it as empty.
1199 Init *PRMName = (*it)->getValueInit("ParserMethod");
1200 if (StringInit *SI = dynamic_cast<StringInit*>(PRMName))
1201 CI->ParserMethod = SI->getValue();
1203 AsmOperandClasses[*it] = CI;
1204 Classes.push_back(CI);
1208 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1209 CodeGenTarget &target,
1210 RecordKeeper &records)
1211 : Records(records), AsmParser(asmParser), Target(target) {
1214 /// buildOperandMatchInfo - Build the necessary information to handle user
1215 /// defined operand parsing methods.
1216 void AsmMatcherInfo::buildOperandMatchInfo() {
1218 /// Map containing a mask with all operands indices that can be found for
1219 /// that class inside a instruction.
1220 std::map<ClassInfo*, unsigned> OpClassMask;
1222 for (std::vector<MatchableInfo*>::const_iterator it =
1223 Matchables.begin(), ie = Matchables.end();
1225 MatchableInfo &II = **it;
1226 OpClassMask.clear();
1228 // Keep track of all operands of this instructions which belong to the
1230 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
1231 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
1232 if (Op.Class->ParserMethod.empty())
1234 unsigned &OperandMask = OpClassMask[Op.Class];
1235 OperandMask |= (1 << i);
1238 // Generate operand match info for each mnemonic/operand class pair.
1239 for (std::map<ClassInfo*, unsigned>::iterator iit = OpClassMask.begin(),
1240 iie = OpClassMask.end(); iit != iie; ++iit) {
1241 unsigned OpMask = iit->second;
1242 ClassInfo *CI = iit->first;
1243 OperandMatchInfo.push_back(OperandMatchEntry::create(&II, CI, OpMask));
1248 void AsmMatcherInfo::buildInfo() {
1249 // Build information about all of the AssemblerPredicates.
1250 std::vector<Record*> AllPredicates =
1251 Records.getAllDerivedDefinitions("Predicate");
1252 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
1253 Record *Pred = AllPredicates[i];
1254 // Ignore predicates that are not intended for the assembler.
1255 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
1258 if (Pred->getName().empty())
1259 throw TGError(Pred->getLoc(), "Predicate has no name!");
1261 unsigned FeatureNo = SubtargetFeatures.size();
1262 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
1263 assert(FeatureNo < 32 && "Too many subtarget features!");
1266 // Parse the instructions; we need to do this first so that we can gather the
1267 // singleton register classes.
1268 SmallPtrSet<Record*, 16> SingletonRegisters;
1269 unsigned VariantCount = Target.getAsmParserVariantCount();
1270 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1271 Record *AsmVariant = Target.getAsmParserVariant(VC);
1272 std::string CommentDelimiter =
1273 AsmVariant->getValueAsString("CommentDelimiter");
1274 std::string RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
1275 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
1277 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
1278 E = Target.inst_end(); I != E; ++I) {
1279 const CodeGenInstruction &CGI = **I;
1281 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1282 // filter the set of instructions we consider.
1283 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
1286 // Ignore "codegen only" instructions.
1287 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
1290 // Validate the operand list to ensure we can handle this instruction.
1291 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1292 const CGIOperandList::OperandInfo &OI = CGI.Operands[i];
1294 // Validate tied operands.
1295 if (OI.getTiedRegister() != -1) {
1296 // If we have a tied operand that consists of multiple MCOperands,
1297 // reject it. We reject aliases and ignore instructions for now.
1298 if (OI.MINumOperands != 1) {
1299 // FIXME: Should reject these. The ARM backend hits this with $lane
1300 // in a bunch of instructions. The right answer is unclear.
1302 errs() << "warning: '" << CGI.TheDef->getName() << "': "
1303 << "ignoring instruction with multi-operand tied operand '"
1304 << OI.Name << "'\n";
1311 OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
1313 II->initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
1315 // Ignore instructions which shouldn't be matched and diagnose invalid
1316 // instruction definitions with an error.
1317 if (!II->validate(CommentDelimiter, true))
1320 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
1322 // FIXME: This is a total hack.
1323 if (StringRef(II->TheDef->getName()).startswith("Int_") ||
1324 StringRef(II->TheDef->getName()).endswith("_Int"))
1327 Matchables.push_back(II.take());
1330 // Parse all of the InstAlias definitions and stick them in the list of
1332 std::vector<Record*> AllInstAliases =
1333 Records.getAllDerivedDefinitions("InstAlias");
1334 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
1335 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i], Target);
1337 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1338 // filter the set of instruction aliases we consider, based on the target
1340 if (!StringRef(Alias->ResultInst->TheDef->getName())
1341 .startswith( MatchPrefix))
1344 OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
1346 II->initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
1348 // Validate the alias definitions.
1349 II->validate(CommentDelimiter, false);
1351 Matchables.push_back(II.take());
1355 // Build info for the register classes.
1356 buildRegisterClasses(SingletonRegisters);
1358 // Build info for the user defined assembly operand classes.
1359 buildOperandClasses();
1361 // Build the information about matchables, now that we have fully formed
1363 std::vector<MatchableInfo*> NewMatchables;
1364 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(),
1365 ie = Matchables.end(); it != ie; ++it) {
1366 MatchableInfo *II = *it;
1368 // Parse the tokens after the mnemonic.
1369 // Note: buildInstructionOperandReference may insert new AsmOperands, so
1370 // don't precompute the loop bound.
1371 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1372 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
1373 StringRef Token = Op.Token;
1375 // Check for singleton registers.
1376 if (Record *RegRecord = II->AsmOperands[i].SingletonReg) {
1377 Op.Class = RegisterClasses[RegRecord];
1378 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1379 "Unexpected class for singleton register");
1383 // Check for simple tokens.
1384 if (Token[0] != '$') {
1385 Op.Class = getTokenClass(Token);
1389 if (Token.size() > 1 && isdigit(Token[1])) {
1390 Op.Class = getTokenClass(Token);
1394 // Otherwise this is an operand reference.
1395 StringRef OperandName;
1396 if (Token[1] == '{')
1397 OperandName = Token.substr(2, Token.size() - 3);
1399 OperandName = Token.substr(1);
1401 if (II->DefRec.is<const CodeGenInstruction*>())
1402 buildInstructionOperandReference(II, OperandName, i);
1404 buildAliasOperandReference(II, OperandName, Op);
1407 if (II->DefRec.is<const CodeGenInstruction*>()) {
1408 II->buildInstructionResultOperands();
1409 // If the instruction has a two-operand alias, build up the
1410 // matchable here. We'll add them in bulk at the end to avoid
1411 // confusing this loop.
1412 std::string Constraint =
1413 II->TheDef->getValueAsString("TwoOperandAliasConstraint");
1414 if (Constraint != "") {
1415 // Start by making a copy of the original matchable.
1416 OwningPtr<MatchableInfo> AliasII(new MatchableInfo(*II));
1418 // Adjust it to be a two-operand alias.
1419 AliasII->formTwoOperandAlias(Constraint);
1421 // Add the alias to the matchables list.
1422 NewMatchables.push_back(AliasII.take());
1425 II->buildAliasResultOperands();
1427 if (!NewMatchables.empty())
1428 Matchables.insert(Matchables.end(), NewMatchables.begin(),
1429 NewMatchables.end());
1431 // Process token alias definitions and set up the associated superclass
1433 std::vector<Record*> AllTokenAliases =
1434 Records.getAllDerivedDefinitions("TokenAlias");
1435 for (unsigned i = 0, e = AllTokenAliases.size(); i != e; ++i) {
1436 Record *Rec = AllTokenAliases[i];
1437 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1438 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
1439 if (FromClass == ToClass)
1440 throw TGError(Rec->getLoc(),
1441 "error: Destination value identical to source value.");
1442 FromClass->SuperClasses.push_back(ToClass);
1445 // Reorder classes so that classes precede super classes.
1446 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
1449 /// buildInstructionOperandReference - The specified operand is a reference to a
1450 /// named operand such as $src. Resolve the Class and OperandInfo pointers.
1451 void AsmMatcherInfo::
1452 buildInstructionOperandReference(MatchableInfo *II,
1453 StringRef OperandName,
1454 unsigned AsmOpIdx) {
1455 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1456 const CGIOperandList &Operands = CGI.Operands;
1457 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
1459 // Map this token to an operand.
1461 if (!Operands.hasOperandNamed(OperandName, Idx))
1462 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1463 OperandName.str() + "'");
1465 // If the instruction operand has multiple suboperands, but the parser
1466 // match class for the asm operand is still the default "ImmAsmOperand",
1467 // then handle each suboperand separately.
1468 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1469 Record *Rec = Operands[Idx].Rec;
1470 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1471 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1472 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1473 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1474 StringRef Token = Op->Token; // save this in case Op gets moved
1475 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1476 MatchableInfo::AsmOperand NewAsmOp(Token);
1477 NewAsmOp.SubOpIdx = SI;
1478 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1480 // Replace Op with first suboperand.
1481 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1486 // Set up the operand class.
1487 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
1489 // If the named operand is tied, canonicalize it to the untied operand.
1490 // For example, something like:
1491 // (outs GPR:$dst), (ins GPR:$src)
1492 // with an asmstring of
1494 // we want to canonicalize to:
1496 // so that we know how to provide the $dst operand when filling in the result.
1497 int OITied = Operands[Idx].getTiedRegister();
1499 // The tied operand index is an MIOperand index, find the operand that
1501 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1502 OperandName = Operands[Idx.first].Name;
1503 Op->SubOpIdx = Idx.second;
1506 Op->SrcOpName = OperandName;
1509 /// buildAliasOperandReference - When parsing an operand reference out of the
1510 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1511 /// operand reference is by looking it up in the result pattern definition.
1512 void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
1513 StringRef OperandName,
1514 MatchableInfo::AsmOperand &Op) {
1515 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
1517 // Set up the operand class.
1518 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
1519 if (CGA.ResultOperands[i].isRecord() &&
1520 CGA.ResultOperands[i].getName() == OperandName) {
1521 // It's safe to go with the first one we find, because CodeGenInstAlias
1522 // validates that all operands with the same name have the same record.
1523 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
1524 // Use the match class from the Alias definition, not the
1525 // destination instruction, as we may have an immediate that's
1526 // being munged by the match class.
1527 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
1529 Op.SrcOpName = OperandName;
1533 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1534 OperandName.str() + "'");
1537 void MatchableInfo::buildInstructionResultOperands() {
1538 const CodeGenInstruction *ResultInst = getResultInst();
1540 // Loop over all operands of the result instruction, determining how to
1542 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1543 const CGIOperandList::OperandInfo &OpInfo = ResultInst->Operands[i];
1545 // If this is a tied operand, just copy from the previously handled operand.
1546 int TiedOp = OpInfo.getTiedRegister();
1548 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1552 // Find out what operand from the asmparser this MCInst operand comes from.
1553 int SrcOperand = findAsmOperandNamed(OpInfo.Name);
1554 if (OpInfo.Name.empty() || SrcOperand == -1)
1555 throw TGError(TheDef->getLoc(), "Instruction '" +
1556 TheDef->getName() + "' has operand '" + OpInfo.Name +
1557 "' that doesn't appear in asm string!");
1559 // Check if the one AsmOperand populates the entire operand.
1560 unsigned NumOperands = OpInfo.MINumOperands;
1561 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1562 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
1566 // Add a separate ResOperand for each suboperand.
1567 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1568 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1569 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1570 "unexpected AsmOperands for suboperands");
1571 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1576 void MatchableInfo::buildAliasResultOperands() {
1577 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1578 const CodeGenInstruction *ResultInst = getResultInst();
1580 // Loop over all operands of the result instruction, determining how to
1582 unsigned AliasOpNo = 0;
1583 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
1584 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1585 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
1587 // If this is a tied operand, just copy from the previously handled operand.
1588 int TiedOp = OpInfo->getTiedRegister();
1590 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1594 // Handle all the suboperands for this operand.
1595 const std::string &OpName = OpInfo->Name;
1596 for ( ; AliasOpNo < LastOpNo &&
1597 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1598 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1600 // Find out what operand from the asmparser that this MCInst operand
1602 switch (CGA.ResultOperands[AliasOpNo].Kind) {
1603 case CodeGenInstAlias::ResultOperand::K_Record: {
1604 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1605 int SrcOperand = findAsmOperand(Name, SubIdx);
1606 if (SrcOperand == -1)
1607 throw TGError(TheDef->getLoc(), "Instruction '" +
1608 TheDef->getName() + "' has operand '" + OpName +
1609 "' that doesn't appear in asm string!");
1610 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1611 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1615 case CodeGenInstAlias::ResultOperand::K_Imm: {
1616 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1617 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1620 case CodeGenInstAlias::ResultOperand::K_Reg: {
1621 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1622 ResOperands.push_back(ResOperand::getRegOp(Reg));
1630 static void emitConvertToMCInst(CodeGenTarget &Target, StringRef ClassName,
1631 std::vector<MatchableInfo*> &Infos,
1633 // Write the convert function to a separate stream, so we can drop it after
1635 std::string ConvertFnBody;
1636 raw_string_ostream CvtOS(ConvertFnBody);
1638 // Function we have already generated.
1639 std::set<std::string> GeneratedFns;
1641 // Start the unified conversion function.
1642 CvtOS << "bool " << Target.getName() << ClassName << "::\n";
1643 CvtOS << "ConvertToMCInst(unsigned Kind, MCInst &Inst, "
1644 << "unsigned Opcode,\n"
1645 << " const SmallVectorImpl<MCParsedAsmOperand*"
1646 << "> &Operands) {\n";
1647 CvtOS << " Inst.setOpcode(Opcode);\n";
1648 CvtOS << " switch (Kind) {\n";
1649 CvtOS << " default:\n";
1651 // Start the enum, which we will generate inline.
1653 OS << "// Unified function for converting operands to MCInst instances.\n\n";
1654 OS << "enum ConversionKind {\n";
1656 // TargetOperandClass - This is the target's operand class, like X86Operand.
1657 std::string TargetOperandClass = Target.getName() + "Operand";
1659 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(),
1660 ie = Infos.end(); it != ie; ++it) {
1661 MatchableInfo &II = **it;
1663 // Check if we have a custom match function.
1664 std::string AsmMatchConverter =
1665 II.getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
1666 if (!AsmMatchConverter.empty()) {
1667 std::string Signature = "ConvertCustom_" + AsmMatchConverter;
1668 II.ConversionFnKind = Signature;
1670 // Check if we have already generated this signature.
1671 if (!GeneratedFns.insert(Signature).second)
1674 // If not, emit it now. Add to the enum list.
1675 OS << " " << Signature << ",\n";
1677 CvtOS << " case " << Signature << ":\n";
1678 CvtOS << " return " << AsmMatchConverter
1679 << "(Inst, Opcode, Operands);\n";
1683 // Build the conversion function signature.
1684 std::string Signature = "Convert";
1685 std::string CaseBody;
1686 raw_string_ostream CaseOS(CaseBody);
1688 // Compute the convert enum and the case body.
1689 for (unsigned i = 0, e = II.ResOperands.size(); i != e; ++i) {
1690 const MatchableInfo::ResOperand &OpInfo = II.ResOperands[i];
1692 // Generate code to populate each result operand.
1693 switch (OpInfo.Kind) {
1694 case MatchableInfo::ResOperand::RenderAsmOperand: {
1695 // This comes from something we parsed.
1696 MatchableInfo::AsmOperand &Op = II.AsmOperands[OpInfo.AsmOperandNum];
1698 // Registers are always converted the same, don't duplicate the
1699 // conversion function based on them.
1701 if (Op.Class->isRegisterClass())
1704 Signature += Op.Class->ClassName;
1705 Signature += utostr(OpInfo.MINumOperands);
1706 Signature += "_" + itostr(OpInfo.AsmOperandNum);
1708 CaseOS << " ((" << TargetOperandClass << "*)Operands["
1709 << (OpInfo.AsmOperandNum+1) << "])->" << Op.Class->RenderMethod
1710 << "(Inst, " << OpInfo.MINumOperands << ");\n";
1714 case MatchableInfo::ResOperand::TiedOperand: {
1715 // If this operand is tied to a previous one, just copy the MCInst
1716 // operand from the earlier one.We can only tie single MCOperand values.
1717 //assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
1718 unsigned TiedOp = OpInfo.TiedOperandNum;
1719 assert(i > TiedOp && "Tied operand precedes its target!");
1720 CaseOS << " Inst.addOperand(Inst.getOperand(" << TiedOp << "));\n";
1721 Signature += "__Tie" + utostr(TiedOp);
1724 case MatchableInfo::ResOperand::ImmOperand: {
1725 int64_t Val = OpInfo.ImmVal;
1726 CaseOS << " Inst.addOperand(MCOperand::CreateImm(" << Val << "));\n";
1727 Signature += "__imm" + itostr(Val);
1730 case MatchableInfo::ResOperand::RegOperand: {
1731 if (OpInfo.Register == 0) {
1732 CaseOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1733 Signature += "__reg0";
1735 std::string N = getQualifiedName(OpInfo.Register);
1736 CaseOS << " Inst.addOperand(MCOperand::CreateReg(" << N << "));\n";
1737 Signature += "__reg" + OpInfo.Register->getName();
1743 II.ConversionFnKind = Signature;
1745 // Check if we have already generated this signature.
1746 if (!GeneratedFns.insert(Signature).second)
1749 // If not, emit it now. Add to the enum list.
1750 OS << " " << Signature << ",\n";
1752 CvtOS << " case " << Signature << ":\n";
1753 CvtOS << CaseOS.str();
1754 CvtOS << " return true;\n";
1757 // Finish the convert function.
1760 CvtOS << " return false;\n";
1763 // Finish the enum, and drop the convert function after it.
1765 OS << " NumConversionVariants\n";
1771 /// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
1772 static void emitMatchClassEnumeration(CodeGenTarget &Target,
1773 std::vector<ClassInfo*> &Infos,
1775 OS << "namespace {\n\n";
1777 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1778 << "/// instruction matching.\n";
1779 OS << "enum MatchClassKind {\n";
1780 OS << " InvalidMatchClass = 0,\n";
1781 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1782 ie = Infos.end(); it != ie; ++it) {
1783 ClassInfo &CI = **it;
1784 OS << " " << CI.Name << ", // ";
1785 if (CI.Kind == ClassInfo::Token) {
1786 OS << "'" << CI.ValueName << "'\n";
1787 } else if (CI.isRegisterClass()) {
1788 if (!CI.ValueName.empty())
1789 OS << "register class '" << CI.ValueName << "'\n";
1791 OS << "derived register class\n";
1793 OS << "user defined class '" << CI.ValueName << "'\n";
1796 OS << " NumMatchClassKinds\n";
1802 /// emitValidateOperandClass - Emit the function to validate an operand class.
1803 static void emitValidateOperandClass(AsmMatcherInfo &Info,
1805 OS << "static bool validateOperandClass(MCParsedAsmOperand *GOp, "
1806 << "MatchClassKind Kind) {\n";
1807 OS << " " << Info.Target.getName() << "Operand &Operand = *("
1808 << Info.Target.getName() << "Operand*)GOp;\n";
1810 // The InvalidMatchClass is not to match any operand.
1811 OS << " if (Kind == InvalidMatchClass)\n";
1812 OS << " return false;\n\n";
1814 // Check for Token operands first.
1815 OS << " if (Operand.isToken())\n";
1816 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind);"
1819 // Check for register operands, including sub-classes.
1820 OS << " if (Operand.isReg()) {\n";
1821 OS << " MatchClassKind OpKind;\n";
1822 OS << " switch (Operand.getReg()) {\n";
1823 OS << " default: OpKind = InvalidMatchClass; break;\n";
1824 for (std::map<Record*, ClassInfo*>::iterator
1825 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1827 OS << " case " << Info.Target.getName() << "::"
1828 << it->first->getName() << ": OpKind = " << it->second->Name
1831 OS << " return isSubclass(OpKind, Kind);\n";
1834 // Check the user classes. We don't care what order since we're only
1835 // actually matching against one of them.
1836 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1837 ie = Info.Classes.end(); it != ie; ++it) {
1838 ClassInfo &CI = **it;
1840 if (!CI.isUserClass())
1843 OS << " // '" << CI.ClassName << "' class\n";
1844 OS << " if (Kind == " << CI.Name
1845 << " && Operand." << CI.PredicateMethod << "()) {\n";
1846 OS << " return true;\n";
1850 OS << " return false;\n";
1854 /// emitIsSubclass - Emit the subclass predicate function.
1855 static void emitIsSubclass(CodeGenTarget &Target,
1856 std::vector<ClassInfo*> &Infos,
1858 OS << "/// isSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1859 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
1860 OS << " if (A == B)\n";
1861 OS << " return true;\n\n";
1863 OS << " switch (A) {\n";
1864 OS << " default:\n";
1865 OS << " return false;\n";
1866 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1867 ie = Infos.end(); it != ie; ++it) {
1868 ClassInfo &A = **it;
1870 std::vector<StringRef> SuperClasses;
1871 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1872 ie = Infos.end(); it != ie; ++it) {
1873 ClassInfo &B = **it;
1875 if (&A != &B && A.isSubsetOf(B))
1876 SuperClasses.push_back(B.Name);
1879 if (SuperClasses.empty())
1882 OS << "\n case " << A.Name << ":\n";
1884 if (SuperClasses.size() == 1) {
1885 OS << " return B == " << SuperClasses.back() << ";\n";
1889 OS << " switch (B) {\n";
1890 OS << " default: return false;\n";
1891 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1892 OS << " case " << SuperClasses[i] << ": return true;\n";
1899 /// emitMatchTokenString - Emit the function to match a token string to the
1900 /// appropriate match class value.
1901 static void emitMatchTokenString(CodeGenTarget &Target,
1902 std::vector<ClassInfo*> &Infos,
1904 // Construct the match list.
1905 std::vector<StringMatcher::StringPair> Matches;
1906 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1907 ie = Infos.end(); it != ie; ++it) {
1908 ClassInfo &CI = **it;
1910 if (CI.Kind == ClassInfo::Token)
1911 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1912 "return " + CI.Name + ";"));
1915 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
1917 StringMatcher("Name", Matches, OS).Emit();
1919 OS << " return InvalidMatchClass;\n";
1923 /// emitMatchRegisterName - Emit the function to match a string to the target
1924 /// specific register enum.
1925 static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1927 // Construct the match list.
1928 std::vector<StringMatcher::StringPair> Matches;
1929 const std::vector<CodeGenRegister*> &Regs =
1930 Target.getRegBank().getRegisters();
1931 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1932 const CodeGenRegister *Reg = Regs[i];
1933 if (Reg->TheDef->getValueAsString("AsmName").empty())
1936 Matches.push_back(StringMatcher::StringPair(
1937 Reg->TheDef->getValueAsString("AsmName"),
1938 "return " + utostr(Reg->EnumValue) + ";"));
1941 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
1943 StringMatcher("Name", Matches, OS).Emit();
1945 OS << " return 0;\n";
1949 /// emitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1951 static void emitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
1953 OS << "// Flags for subtarget features that participate in "
1954 << "instruction matching.\n";
1955 OS << "enum SubtargetFeatureFlag {\n";
1956 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1957 it = Info.SubtargetFeatures.begin(),
1958 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1959 SubtargetFeatureInfo &SFI = *it->second;
1960 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
1962 OS << " Feature_None = 0\n";
1966 /// emitGetSubtargetFeatureName - Emit the helper function to get the
1967 /// user-level name for a subtarget feature.
1968 static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
1969 OS << "// User-level names for subtarget features that participate in\n"
1970 << "// instruction matching.\n"
1971 << "static const char *getSubtargetFeatureName(unsigned Val) {\n"
1972 << " switch(Val) {\n";
1973 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1974 it = Info.SubtargetFeatures.begin(),
1975 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1976 SubtargetFeatureInfo &SFI = *it->second;
1977 // FIXME: Totally just a placeholder name to get the algorithm working.
1978 OS << " case " << SFI.getEnumName() << ": return \""
1979 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
1981 OS << " default: return \"(unknown)\";\n";
1985 /// emitComputeAvailableFeatures - Emit the function to compute the list of
1986 /// available features given a subtarget.
1987 static void emitComputeAvailableFeatures(AsmMatcherInfo &Info,
1989 std::string ClassName =
1990 Info.AsmParser->getValueAsString("AsmParserClassName");
1992 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
1993 << "ComputeAvailableFeatures(uint64_t FB) const {\n";
1994 OS << " unsigned Features = 0;\n";
1995 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1996 it = Info.SubtargetFeatures.begin(),
1997 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1998 SubtargetFeatureInfo &SFI = *it->second;
2001 std::string CondStorage =
2002 SFI.TheDef->getValueAsString("AssemblerCondString");
2003 StringRef Conds = CondStorage;
2004 std::pair<StringRef,StringRef> Comma = Conds.split(',');
2011 StringRef Cond = Comma.first;
2012 if (Cond[0] == '!') {
2014 Cond = Cond.substr(1);
2017 OS << "((FB & " << Info.Target.getName() << "::" << Cond << ")";
2024 if (Comma.second.empty())
2028 Comma = Comma.second.split(',');
2032 OS << " Features |= " << SFI.getEnumName() << ";\n";
2034 OS << " return Features;\n";
2038 static std::string GetAliasRequiredFeatures(Record *R,
2039 const AsmMatcherInfo &Info) {
2040 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
2042 unsigned NumFeatures = 0;
2043 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
2044 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
2047 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
2048 "' is not marked as an AssemblerPredicate!");
2053 Result += F->getEnumName();
2057 if (NumFeatures > 1)
2058 Result = '(' + Result + ')';
2062 /// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
2063 /// emit a function for them and return true, otherwise return false.
2064 static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
2065 // Ignore aliases when match-prefix is set.
2066 if (!MatchPrefix.empty())
2069 std::vector<Record*> Aliases =
2070 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
2071 if (Aliases.empty()) return false;
2073 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
2074 "unsigned Features) {\n";
2076 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
2077 // iteration order of the map is stable.
2078 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
2080 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
2081 Record *R = Aliases[i];
2082 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
2085 // Process each alias a "from" mnemonic at a time, building the code executed
2086 // by the string remapper.
2087 std::vector<StringMatcher::StringPair> Cases;
2088 for (std::map<std::string, std::vector<Record*> >::iterator
2089 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
2091 const std::vector<Record*> &ToVec = I->second;
2093 // Loop through each alias and emit code that handles each case. If there
2094 // are two instructions without predicates, emit an error. If there is one,
2096 std::string MatchCode;
2097 int AliasWithNoPredicate = -1;
2099 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
2100 Record *R = ToVec[i];
2101 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
2103 // If this unconditionally matches, remember it for later and diagnose
2105 if (FeatureMask.empty()) {
2106 if (AliasWithNoPredicate != -1) {
2107 // We can't have two aliases from the same mnemonic with no predicate.
2108 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
2109 "two MnemonicAliases with the same 'from' mnemonic!");
2110 throw TGError(R->getLoc(), "this is the other MnemonicAlias.");
2113 AliasWithNoPredicate = i;
2116 if (R->getValueAsString("ToMnemonic") == I->first)
2117 throw TGError(R->getLoc(), "MnemonicAlias to the same string");
2119 if (!MatchCode.empty())
2120 MatchCode += "else ";
2121 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
2122 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
2125 if (AliasWithNoPredicate != -1) {
2126 Record *R = ToVec[AliasWithNoPredicate];
2127 if (!MatchCode.empty())
2128 MatchCode += "else\n ";
2129 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
2132 MatchCode += "return;";
2134 Cases.push_back(std::make_pair(I->first, MatchCode));
2137 StringMatcher("Mnemonic", Cases, OS).Emit();
2143 static const char *getMinimalTypeForRange(uint64_t Range) {
2144 assert(Range < 0xFFFFFFFFULL && "Enum too large");
2152 static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
2153 const AsmMatcherInfo &Info, StringRef ClassName) {
2154 // Emit the static custom operand parsing table;
2155 OS << "namespace {\n";
2156 OS << " struct OperandMatchEntry {\n";
2157 OS << " static const char *const MnemonicTable;\n";
2158 OS << " uint32_t OperandMask;\n";
2159 OS << " uint32_t Mnemonic;\n";
2160 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2161 << " RequiredFeatures;\n";
2162 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2164 OS << " StringRef getMnemonic() const {\n";
2165 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2166 OS << " MnemonicTable[Mnemonic]);\n";
2170 OS << " // Predicate for searching for an opcode.\n";
2171 OS << " struct LessOpcodeOperand {\n";
2172 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
2173 OS << " return LHS.getMnemonic() < RHS;\n";
2175 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
2176 OS << " return LHS < RHS.getMnemonic();\n";
2178 OS << " bool operator()(const OperandMatchEntry &LHS,";
2179 OS << " const OperandMatchEntry &RHS) {\n";
2180 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
2184 OS << "} // end anonymous namespace.\n\n";
2186 StringToOffsetTable StringTable;
2188 OS << "static const OperandMatchEntry OperandMatchTable["
2189 << Info.OperandMatchInfo.size() << "] = {\n";
2191 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
2192 for (std::vector<OperandMatchEntry>::const_iterator it =
2193 Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end();
2195 const OperandMatchEntry &OMI = *it;
2196 const MatchableInfo &II = *OMI.MI;
2198 OS << " { " << OMI.OperandMask;
2201 bool printComma = false;
2202 for (int i = 0, e = 31; i !=e; ++i)
2203 if (OMI.OperandMask & (1 << i)) {
2211 // Store a pascal-style length byte in the mnemonic.
2212 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2213 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2214 << " /* " << II.Mnemonic << " */, ";
2216 // Write the required features mask.
2217 if (!II.RequiredFeatures.empty()) {
2218 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2220 OS << II.RequiredFeatures[i]->getEnumName();
2225 OS << ", " << OMI.CI->Name;
2231 OS << "const char *const OperandMatchEntry::MnemonicTable =\n";
2232 StringTable.EmitString(OS);
2235 // Emit the operand class switch to call the correct custom parser for
2236 // the found operand class.
2237 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2238 << Target.getName() << ClassName << "::\n"
2239 << "tryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>"
2240 << " &Operands,\n unsigned MCK) {\n\n"
2241 << " switch(MCK) {\n";
2243 for (std::vector<ClassInfo*>::const_iterator it = Info.Classes.begin(),
2244 ie = Info.Classes.end(); it != ie; ++it) {
2245 ClassInfo *CI = *it;
2246 if (CI->ParserMethod.empty())
2248 OS << " case " << CI->Name << ":\n"
2249 << " return " << CI->ParserMethod << "(Operands);\n";
2252 OS << " default:\n";
2253 OS << " return MatchOperand_NoMatch;\n";
2255 OS << " return MatchOperand_NoMatch;\n";
2258 // Emit the static custom operand parser. This code is very similar with
2259 // the other matcher. Also use MatchResultTy here just in case we go for
2260 // a better error handling.
2261 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2262 << Target.getName() << ClassName << "::\n"
2263 << "MatchOperandParserImpl(SmallVectorImpl<MCParsedAsmOperand*>"
2264 << " &Operands,\n StringRef Mnemonic) {\n";
2266 // Emit code to get the available features.
2267 OS << " // Get the current feature set.\n";
2268 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2270 OS << " // Get the next operand index.\n";
2271 OS << " unsigned NextOpNum = Operands.size()-1;\n";
2273 // Emit code to search the table.
2274 OS << " // Search the table.\n";
2275 OS << " std::pair<const OperandMatchEntry*, const OperandMatchEntry*>";
2276 OS << " MnemonicRange =\n";
2277 OS << " std::equal_range(OperandMatchTable, OperandMatchTable+"
2278 << Info.OperandMatchInfo.size() << ", Mnemonic,\n"
2279 << " LessOpcodeOperand());\n\n";
2281 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2282 OS << " return MatchOperand_NoMatch;\n\n";
2284 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2285 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2287 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2288 OS << " assert(Mnemonic == it->getMnemonic());\n\n";
2290 // Emit check that the required features are available.
2291 OS << " // check if the available features match\n";
2292 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2293 << "!= it->RequiredFeatures) {\n";
2294 OS << " continue;\n";
2297 // Emit check to ensure the operand number matches.
2298 OS << " // check if the operand in question has a custom parser.\n";
2299 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2300 OS << " continue;\n\n";
2302 // Emit call to the custom parser method
2303 OS << " // call custom parse method to handle the operand\n";
2304 OS << " OperandMatchResultTy Result = ";
2305 OS << "tryCustomParseOperand(Operands, it->Class);\n";
2306 OS << " if (Result != MatchOperand_NoMatch)\n";
2307 OS << " return Result;\n";
2310 OS << " // Okay, we had no match.\n";
2311 OS << " return MatchOperand_NoMatch;\n";
2315 void AsmMatcherEmitter::run(raw_ostream &OS) {
2316 CodeGenTarget Target(Records);
2317 Record *AsmParser = Target.getAsmParser();
2318 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2320 // Compute the information on the instructions to match.
2321 AsmMatcherInfo Info(AsmParser, Target, Records);
2324 // Sort the instruction table using the partial order on classes. We use
2325 // stable_sort to ensure that ambiguous instructions are still
2326 // deterministically ordered.
2327 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2328 less_ptr<MatchableInfo>());
2330 DEBUG_WITH_TYPE("instruction_info", {
2331 for (std::vector<MatchableInfo*>::iterator
2332 it = Info.Matchables.begin(), ie = Info.Matchables.end();
2337 // Check for ambiguous matchables.
2338 DEBUG_WITH_TYPE("ambiguous_instrs", {
2339 unsigned NumAmbiguous = 0;
2340 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) {
2341 for (unsigned j = i + 1; j != e; ++j) {
2342 MatchableInfo &A = *Info.Matchables[i];
2343 MatchableInfo &B = *Info.Matchables[j];
2345 if (A.couldMatchAmbiguouslyWith(B)) {
2346 errs() << "warning: ambiguous matchables:\n";
2348 errs() << "\nis incomparable with:\n";
2356 errs() << "warning: " << NumAmbiguous
2357 << " ambiguous matchables!\n";
2360 // Compute the information on the custom operand parsing.
2361 Info.buildOperandMatchInfo();
2363 // Write the output.
2365 // Information for the class declaration.
2366 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2367 OS << "#undef GET_ASSEMBLER_HEADER\n";
2368 OS << " // This should be included into the middle of the declaration of\n";
2369 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
2370 OS << " unsigned ComputeAvailableFeatures(uint64_t FeatureBits) const;\n";
2371 OS << " bool ConvertToMCInst(unsigned Kind, MCInst &Inst, "
2372 << "unsigned Opcode,\n"
2373 << " const SmallVectorImpl<MCParsedAsmOperand*> "
2375 OS << " bool MnemonicIsValid(StringRef Mnemonic);\n";
2376 OS << " unsigned MatchInstructionImpl(\n";
2377 OS << " const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2378 OS << " MCInst &Inst, unsigned &ErrorInfo, unsigned VariantID = 0);\n";
2380 if (Info.OperandMatchInfo.size()) {
2381 OS << "\n enum OperandMatchResultTy {\n";
2382 OS << " MatchOperand_Success, // operand matched successfully\n";
2383 OS << " MatchOperand_NoMatch, // operand did not match\n";
2384 OS << " MatchOperand_ParseFail // operand matched but had errors\n";
2386 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
2387 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2388 OS << " StringRef Mnemonic);\n";
2390 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
2391 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2392 OS << " unsigned MCK);\n\n";
2395 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2397 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2398 OS << "#undef GET_REGISTER_MATCHER\n\n";
2400 // Emit the subtarget feature enumeration.
2401 emitSubtargetFeatureFlagEnumeration(Info, OS);
2403 // Emit the function to match a register name to number.
2404 emitMatchRegisterName(Target, AsmParser, OS);
2406 OS << "#endif // GET_REGISTER_MATCHER\n\n";
2408 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
2409 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
2411 // Generate the helper function to get the names for subtarget features.
2412 emitGetSubtargetFeatureName(Info, OS);
2414 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
2416 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2417 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
2419 // Generate the function that remaps for mnemonic aliases.
2420 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info);
2422 // Generate the unified function to convert operands into an MCInst.
2423 emitConvertToMCInst(Target, ClassName, Info.Matchables, OS);
2425 // Emit the enumeration for classes which participate in matching.
2426 emitMatchClassEnumeration(Target, Info.Classes, OS);
2428 // Emit the routine to match token strings to their match class.
2429 emitMatchTokenString(Target, Info.Classes, OS);
2431 // Emit the subclass predicate routine.
2432 emitIsSubclass(Target, Info.Classes, OS);
2434 // Emit the routine to validate an operand against a match class.
2435 emitValidateOperandClass(Info, OS);
2437 // Emit the available features compute function.
2438 emitComputeAvailableFeatures(Info, OS);
2441 size_t MaxNumOperands = 0;
2442 for (std::vector<MatchableInfo*>::const_iterator it =
2443 Info.Matchables.begin(), ie = Info.Matchables.end();
2445 MaxNumOperands = std::max(MaxNumOperands, (*it)->AsmOperands.size());
2447 // Emit the static match table; unused classes get initalized to 0 which is
2448 // guaranteed to be InvalidMatchClass.
2450 // FIXME: We can reduce the size of this table very easily. First, we change
2451 // it so that store the kinds in separate bit-fields for each index, which
2452 // only needs to be the max width used for classes at that index (we also need
2453 // to reject based on this during classification). If we then make sure to
2454 // order the match kinds appropriately (putting mnemonics last), then we
2455 // should only end up using a few bits for each class, especially the ones
2456 // following the mnemonic.
2457 OS << "namespace {\n";
2458 OS << " struct MatchEntry {\n";
2459 OS << " static const char *const MnemonicTable;\n";
2460 OS << " uint32_t Mnemonic;\n";
2461 OS << " uint16_t Opcode;\n";
2462 OS << " " << getMinimalTypeForRange(Info.Matchables.size())
2464 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2465 << " RequiredFeatures;\n";
2466 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2467 << " Classes[" << MaxNumOperands << "];\n";
2468 OS << " uint8_t AsmVariantID;\n\n";
2469 OS << " StringRef getMnemonic() const {\n";
2470 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2471 OS << " MnemonicTable[Mnemonic]);\n";
2475 OS << " // Predicate for searching for an opcode.\n";
2476 OS << " struct LessOpcode {\n";
2477 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
2478 OS << " return LHS.getMnemonic() < RHS;\n";
2480 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
2481 OS << " return LHS < RHS.getMnemonic();\n";
2483 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
2484 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
2488 OS << "} // end anonymous namespace.\n\n";
2490 StringToOffsetTable StringTable;
2492 OS << "static const MatchEntry MatchTable["
2493 << Info.Matchables.size() << "] = {\n";
2495 for (std::vector<MatchableInfo*>::const_iterator it =
2496 Info.Matchables.begin(), ie = Info.Matchables.end();
2498 MatchableInfo &II = **it;
2500 // Store a pascal-style length byte in the mnemonic.
2501 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2502 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2503 << " /* " << II.Mnemonic << " */, "
2504 << Target.getName() << "::"
2505 << II.getResultInst()->TheDef->getName() << ", "
2506 << II.ConversionFnKind << ", ";
2508 // Write the required features mask.
2509 if (!II.RequiredFeatures.empty()) {
2510 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2512 OS << II.RequiredFeatures[i]->getEnumName();
2518 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
2519 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
2522 OS << Op.Class->Name;
2524 OS << " }, " << II.AsmVariantID;
2530 OS << "const char *const MatchEntry::MnemonicTable =\n";
2531 StringTable.EmitString(OS);
2534 // A method to determine if a mnemonic is in the list.
2535 OS << "bool " << Target.getName() << ClassName << "::\n"
2536 << "MnemonicIsValid(StringRef Mnemonic) {\n";
2537 OS << " // Search the table.\n";
2538 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2539 OS << " std::equal_range(MatchTable, MatchTable+"
2540 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n";
2541 OS << " return MnemonicRange.first != MnemonicRange.second;\n";
2544 // Finally, build the match function.
2546 << Target.getName() << ClassName << "::\n"
2547 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
2549 OS << " MCInst &Inst, unsigned &ErrorInfo, ";
2550 OS << "unsigned VariantID) {\n";
2552 // Emit code to get the available features.
2553 OS << " // Get the current feature set.\n";
2554 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2556 OS << " // Get the instruction mnemonic, which is the first token.\n";
2557 OS << " StringRef Mnemonic = ((" << Target.getName()
2558 << "Operand*)Operands[0])->getToken();\n\n";
2560 if (HasMnemonicAliases) {
2561 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
2562 OS << " // FIXME : Add an entry in AsmParserVariant to check this.\n";
2563 OS << " if (!VariantID)\n";
2564 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
2567 // Emit code to compute the class list for this operand vector.
2568 OS << " // Eliminate obvious mismatches.\n";
2569 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
2570 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
2571 OS << " return Match_InvalidOperand;\n";
2574 OS << " // Some state to try to produce better error messages.\n";
2575 OS << " bool HadMatchOtherThanFeatures = false;\n";
2576 OS << " bool HadMatchOtherThanPredicate = false;\n";
2577 OS << " unsigned RetCode = Match_InvalidOperand;\n";
2578 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
2579 OS << " // wrong for all instances of the instruction.\n";
2580 OS << " ErrorInfo = ~0U;\n";
2582 // Emit code to search the table.
2583 OS << " // Search the table.\n";
2584 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2585 OS << " std::equal_range(MatchTable, MatchTable+"
2586 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n";
2588 OS << " // Return a more specific error code if no mnemonics match.\n";
2589 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2590 OS << " return Match_MnemonicFail;\n\n";
2592 OS << " for (const MatchEntry *it = MnemonicRange.first, "
2593 << "*ie = MnemonicRange.second;\n";
2594 OS << " it != ie; ++it) {\n";
2596 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2597 OS << " assert(Mnemonic == it->getMnemonic());\n";
2599 // Emit check that the subclasses match.
2600 OS << " if (VariantID != it->AsmVariantID) continue;\n";
2601 OS << " bool OperandsValid = true;\n";
2602 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
2603 OS << " if (i + 1 >= Operands.size()) {\n";
2604 OS << " OperandsValid = (it->Classes[i] == " <<"InvalidMatchClass);\n";
2607 OS << " if (validateOperandClass(Operands[i+1], "
2608 "(MatchClassKind)it->Classes[i]))\n";
2609 OS << " continue;\n";
2610 OS << " // If this operand is broken for all of the instances of this\n";
2611 OS << " // mnemonic, keep track of it so we can report loc info.\n";
2612 OS << " if (it == MnemonicRange.first || ErrorInfo <= i+1)\n";
2613 OS << " ErrorInfo = i+1;\n";
2614 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
2615 OS << " OperandsValid = false;\n";
2619 OS << " if (!OperandsValid) continue;\n";
2621 // Emit check that the required features are available.
2622 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2623 << "!= it->RequiredFeatures) {\n";
2624 OS << " HadMatchOtherThanFeatures = true;\n";
2625 OS << " ErrorInfo = it->RequiredFeatures & ~AvailableFeatures;\n";
2626 OS << " continue;\n";
2629 OS << " // We have selected a definite instruction, convert the parsed\n"
2630 << " // operands into the appropriate MCInst.\n";
2631 OS << " if (!ConvertToMCInst(it->ConvertFn, Inst,\n"
2632 << " it->Opcode, Operands))\n";
2633 OS << " return Match_ConversionFail;\n";
2636 // Verify the instruction with the target-specific match predicate function.
2637 OS << " // We have a potential match. Check the target predicate to\n"
2638 << " // handle any context sensitive constraints.\n"
2639 << " unsigned MatchResult;\n"
2640 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
2641 << " Match_Success) {\n"
2642 << " Inst.clear();\n"
2643 << " RetCode = MatchResult;\n"
2644 << " HadMatchOtherThanPredicate = true;\n"
2648 // Call the post-processing function, if used.
2649 std::string InsnCleanupFn =
2650 AsmParser->getValueAsString("AsmParserInstCleanup");
2651 if (!InsnCleanupFn.empty())
2652 OS << " " << InsnCleanupFn << "(Inst);\n";
2654 OS << " return Match_Success;\n";
2657 OS << " // Okay, we had no match. Try to return a useful error code.\n";
2658 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)";
2659 OS << " return RetCode;\n";
2660 OS << " assert(ErrorInfo && \"missing feature(s) but what?!\");";
2661 OS << " return Match_MissingFeature;\n";
2664 if (Info.OperandMatchInfo.size())
2665 emitCustomOperandParsing(OS, Target, Info, ClassName);
2667 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
2672 void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
2673 emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
2674 AsmMatcherEmitter(RK).run(OS);
2677 } // End llvm namespace