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 "AsmMatcherEmitter.h"
100 #include "CodeGenTarget.h"
103 #include "StringMatcher.h"
104 #include "llvm/ADT/OwningPtr.h"
105 #include "llvm/ADT/PointerUnion.h"
106 #include "llvm/ADT/SmallPtrSet.h"
107 #include "llvm/ADT/SmallVector.h"
108 #include "llvm/ADT/STLExtras.h"
109 #include "llvm/ADT/StringExtras.h"
110 #include "llvm/Support/CommandLine.h"
111 #include "llvm/Support/Debug.h"
114 using namespace llvm;
116 static cl::opt<std::string>
117 MatchPrefix("match-prefix", cl::init(""),
118 cl::desc("Only match instructions with the given prefix"));
121 class AsmMatcherInfo;
122 struct SubtargetFeatureInfo;
124 /// ClassInfo - Helper class for storing the information about a particular
125 /// class of operands which can be matched.
128 /// Invalid kind, for use as a sentinel value.
131 /// The class for a particular token.
134 /// The (first) register class, subsequent register classes are
135 /// RegisterClass0+1, and so on.
138 /// The (first) user defined class, subsequent user defined classes are
139 /// UserClass0+1, and so on.
143 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
144 /// N) for the Nth user defined class.
147 /// SuperClasses - The super classes of this class. Note that for simplicities
148 /// sake user operands only record their immediate super class, while register
149 /// operands include all superclasses.
150 std::vector<ClassInfo*> SuperClasses;
152 /// Name - The full class name, suitable for use in an enum.
155 /// ClassName - The unadorned generic name for this class (e.g., Token).
156 std::string ClassName;
158 /// ValueName - The name of the value this class represents; for a token this
159 /// is the literal token string, for an operand it is the TableGen class (or
160 /// empty if this is a derived class).
161 std::string ValueName;
163 /// PredicateMethod - The name of the operand method to test whether the
164 /// operand matches this class; this is not valid for Token or register kinds.
165 std::string PredicateMethod;
167 /// RenderMethod - The name of the operand method to add this operand to an
168 /// MCInst; this is not valid for Token or register kinds.
169 std::string RenderMethod;
171 /// ParserMethod - The name of the operand method to do a target specific
172 /// parsing on the operand.
173 std::string ParserMethod;
175 /// For register classes, the records for all the registers in this class.
176 std::set<Record*> Registers;
179 /// isRegisterClass() - Check if this is a register class.
180 bool isRegisterClass() const {
181 return Kind >= RegisterClass0 && Kind < UserClass0;
184 /// isUserClass() - Check if this is a user defined class.
185 bool isUserClass() const {
186 return Kind >= UserClass0;
189 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
190 /// are related if they are in the same class hierarchy.
191 bool isRelatedTo(const ClassInfo &RHS) const {
192 // Tokens are only related to tokens.
193 if (Kind == Token || RHS.Kind == Token)
194 return Kind == Token && RHS.Kind == Token;
196 // Registers classes are only related to registers classes, and only if
197 // their intersection is non-empty.
198 if (isRegisterClass() || RHS.isRegisterClass()) {
199 if (!isRegisterClass() || !RHS.isRegisterClass())
202 std::set<Record*> Tmp;
203 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
204 std::set_intersection(Registers.begin(), Registers.end(),
205 RHS.Registers.begin(), RHS.Registers.end(),
211 // Otherwise we have two users operands; they are related if they are in the
212 // same class hierarchy.
214 // FIXME: This is an oversimplification, they should only be related if they
215 // intersect, however we don't have that information.
216 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
217 const ClassInfo *Root = this;
218 while (!Root->SuperClasses.empty())
219 Root = Root->SuperClasses.front();
221 const ClassInfo *RHSRoot = &RHS;
222 while (!RHSRoot->SuperClasses.empty())
223 RHSRoot = RHSRoot->SuperClasses.front();
225 return Root == RHSRoot;
228 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
229 bool isSubsetOf(const ClassInfo &RHS) const {
230 // This is a subset of RHS if it is the same class...
234 // ... or if any of its super classes are a subset of RHS.
235 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
236 ie = SuperClasses.end(); it != ie; ++it)
237 if ((*it)->isSubsetOf(RHS))
243 /// operator< - Compare two classes.
244 bool operator<(const ClassInfo &RHS) const {
248 // Unrelated classes can be ordered by kind.
249 if (!isRelatedTo(RHS))
250 return Kind < RHS.Kind;
254 assert(0 && "Invalid kind!");
256 // Tokens are comparable by value.
258 // FIXME: Compare by enum value.
259 return ValueName < RHS.ValueName;
262 // This class precedes the RHS if it is a proper subset of the RHS.
265 if (RHS.isSubsetOf(*this))
268 // Otherwise, order by name to ensure we have a total ordering.
269 return ValueName < RHS.ValueName;
274 /// MatchableInfo - Helper class for storing the necessary information for an
275 /// instruction or alias which is capable of being matched.
276 struct MatchableInfo {
278 /// Token - This is the token that the operand came from.
281 /// The unique class instance this operand should match.
284 /// The operand name this is, if anything.
287 /// The suboperand index within SrcOpName, or -1 for the entire operand.
290 explicit AsmOperand(StringRef T) : Token(T), Class(0), SubOpIdx(-1) {}
293 /// ResOperand - This represents a single operand in the result instruction
294 /// generated by the match. In cases (like addressing modes) where a single
295 /// assembler operand expands to multiple MCOperands, this represents the
296 /// single assembler operand, not the MCOperand.
299 /// RenderAsmOperand - This represents an operand result that is
300 /// generated by calling the render method on the assembly operand. The
301 /// corresponding AsmOperand is specified by AsmOperandNum.
304 /// TiedOperand - This represents a result operand that is a duplicate of
305 /// a previous result operand.
308 /// ImmOperand - This represents an immediate value that is dumped into
312 /// RegOperand - This represents a fixed register that is dumped in.
317 /// This is the operand # in the AsmOperands list that this should be
319 unsigned AsmOperandNum;
321 /// TiedOperandNum - This is the (earlier) result operand that should be
323 unsigned TiedOperandNum;
325 /// ImmVal - This is the immediate value added to the instruction.
328 /// Register - This is the register record.
332 /// MINumOperands - The number of MCInst operands populated by this
334 unsigned MINumOperands;
336 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
338 X.Kind = RenderAsmOperand;
339 X.AsmOperandNum = AsmOpNum;
340 X.MINumOperands = NumOperands;
344 static ResOperand getTiedOp(unsigned TiedOperandNum) {
346 X.Kind = TiedOperand;
347 X.TiedOperandNum = TiedOperandNum;
352 static ResOperand getImmOp(int64_t Val) {
360 static ResOperand getRegOp(Record *Reg) {
369 /// TheDef - This is the definition of the instruction or InstAlias that this
370 /// matchable came from.
371 Record *const TheDef;
373 /// DefRec - This is the definition that it came from.
374 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
376 const CodeGenInstruction *getResultInst() const {
377 if (DefRec.is<const CodeGenInstruction*>())
378 return DefRec.get<const CodeGenInstruction*>();
379 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
382 /// ResOperands - This is the operand list that should be built for the result
384 std::vector<ResOperand> ResOperands;
386 /// AsmString - The assembly string for this instruction (with variants
387 /// removed), e.g. "movsx $src, $dst".
388 std::string AsmString;
390 /// Mnemonic - This is the first token of the matched instruction, its
394 /// AsmOperands - The textual operands that this instruction matches,
395 /// annotated with a class and where in the OperandList they were defined.
396 /// This directly corresponds to the tokenized AsmString after the mnemonic is
398 SmallVector<AsmOperand, 4> AsmOperands;
400 /// Predicates - The required subtarget features to match this instruction.
401 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
403 /// ConversionFnKind - The enum value which is passed to the generated
404 /// ConvertToMCInst to convert parsed operands into an MCInst for this
406 std::string ConversionFnKind;
408 MatchableInfo(const CodeGenInstruction &CGI)
409 : TheDef(CGI.TheDef), DefRec(&CGI), AsmString(CGI.AsmString) {
412 MatchableInfo(const CodeGenInstAlias *Alias)
413 : TheDef(Alias->TheDef), DefRec(Alias), AsmString(Alias->AsmString) {
416 void Initialize(const AsmMatcherInfo &Info,
417 SmallPtrSet<Record*, 16> &SingletonRegisters);
419 /// Validate - Return true if this matchable is a valid thing to match against
420 /// and perform a bunch of validity checking.
421 bool Validate(StringRef CommentDelimiter, bool Hack) const;
423 /// getSingletonRegisterForAsmOperand - If the specified token is a singleton
424 /// register, return the Record for it, otherwise return null.
425 Record *getSingletonRegisterForAsmOperand(unsigned i,
426 const AsmMatcherInfo &Info) const;
428 /// FindAsmOperand - Find the AsmOperand with the specified name and
429 /// suboperand index.
430 int FindAsmOperand(StringRef N, int SubOpIdx) const {
431 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
432 if (N == AsmOperands[i].SrcOpName &&
433 SubOpIdx == AsmOperands[i].SubOpIdx)
438 /// FindAsmOperandNamed - Find the first AsmOperand with the specified name.
439 /// This does not check the suboperand index.
440 int FindAsmOperandNamed(StringRef N) const {
441 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
442 if (N == AsmOperands[i].SrcOpName)
447 void BuildInstructionResultOperands();
448 void BuildAliasResultOperands();
450 /// operator< - Compare two matchables.
451 bool operator<(const MatchableInfo &RHS) const {
452 // The primary comparator is the instruction mnemonic.
453 if (Mnemonic != RHS.Mnemonic)
454 return Mnemonic < RHS.Mnemonic;
456 if (AsmOperands.size() != RHS.AsmOperands.size())
457 return AsmOperands.size() < RHS.AsmOperands.size();
459 // Compare lexicographically by operand. The matcher validates that other
460 // orderings wouldn't be ambiguous using \see CouldMatchAmbiguouslyWith().
461 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
462 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
464 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
471 /// CouldMatchAmbiguouslyWith - Check whether this matchable could
472 /// ambiguously match the same set of operands as \arg RHS (without being a
473 /// strictly superior match).
474 bool CouldMatchAmbiguouslyWith(const MatchableInfo &RHS) {
475 // The primary comparator is the instruction mnemonic.
476 if (Mnemonic != RHS.Mnemonic)
479 // The number of operands is unambiguous.
480 if (AsmOperands.size() != RHS.AsmOperands.size())
483 // Otherwise, make sure the ordering of the two instructions is unambiguous
484 // by checking that either (a) a token or operand kind discriminates them,
485 // or (b) the ordering among equivalent kinds is consistent.
487 // Tokens and operand kinds are unambiguous (assuming a correct target
489 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
490 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
491 AsmOperands[i].Class->Kind == ClassInfo::Token)
492 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
493 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
496 // Otherwise, this operand could commute if all operands are equivalent, or
497 // there is a pair of operands that compare less than and a pair that
498 // compare greater than.
499 bool HasLT = false, HasGT = false;
500 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
501 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
503 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
507 return !(HasLT ^ HasGT);
513 void TokenizeAsmString(const AsmMatcherInfo &Info);
516 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
517 /// feature which participates in instruction matching.
518 struct SubtargetFeatureInfo {
519 /// \brief The predicate record for this feature.
522 /// \brief An unique index assigned to represent this feature.
525 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
527 /// \brief The name of the enumerated constant identifying this feature.
528 std::string getEnumName() const {
529 return "Feature_" + TheDef->getName();
533 struct OperandMatchEntry {
534 unsigned OperandMask;
538 static OperandMatchEntry Create(MatchableInfo* mi, ClassInfo *ci,
541 X.OperandMask = opMask;
549 class AsmMatcherInfo {
552 RecordKeeper &Records;
554 /// The tablegen AsmParser record.
557 /// Target - The target information.
558 CodeGenTarget &Target;
560 /// The AsmParser "RegisterPrefix" value.
561 std::string RegisterPrefix;
563 /// The classes which are needed for matching.
564 std::vector<ClassInfo*> Classes;
566 /// The information on the matchables to match.
567 std::vector<MatchableInfo*> Matchables;
569 /// Info for custom matching operands by user defined methods.
570 std::vector<OperandMatchEntry> OperandMatchInfo;
572 /// Map of Register records to their class information.
573 std::map<Record*, ClassInfo*> RegisterClasses;
575 /// Map of Predicate records to their subtarget information.
576 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
579 /// Map of token to class information which has already been constructed.
580 std::map<std::string, ClassInfo*> TokenClasses;
582 /// Map of RegisterClass records to their class information.
583 std::map<Record*, ClassInfo*> RegisterClassClasses;
585 /// Map of AsmOperandClass records to their class information.
586 std::map<Record*, ClassInfo*> AsmOperandClasses;
589 /// getTokenClass - Lookup or create the class for the given token.
590 ClassInfo *getTokenClass(StringRef Token);
592 /// getOperandClass - Lookup or create the class for the given operand.
593 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
596 /// BuildRegisterClasses - Build the ClassInfo* instances for register
598 void BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
600 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
602 void BuildOperandClasses();
604 void BuildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
606 void BuildAliasOperandReference(MatchableInfo *II, StringRef OpName,
607 MatchableInfo::AsmOperand &Op);
610 AsmMatcherInfo(Record *AsmParser,
611 CodeGenTarget &Target,
612 RecordKeeper &Records);
614 /// BuildInfo - Construct the various tables used during matching.
617 /// BuildOperandMatchInfo - Build the necessary information to handle user
618 /// defined operand parsing methods.
619 void BuildOperandMatchInfo();
621 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
623 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
624 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
625 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
626 SubtargetFeatures.find(Def);
627 return I == SubtargetFeatures.end() ? 0 : I->second;
630 RecordKeeper &getRecords() const {
637 void MatchableInfo::dump() {
638 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
640 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
641 AsmOperand &Op = AsmOperands[i];
642 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
643 errs() << '\"' << Op.Token << "\"\n";
647 void MatchableInfo::Initialize(const AsmMatcherInfo &Info,
648 SmallPtrSet<Record*, 16> &SingletonRegisters) {
649 // TODO: Eventually support asmparser for Variant != 0.
650 AsmString = CodeGenInstruction::FlattenAsmStringVariants(AsmString, 0);
652 TokenizeAsmString(Info);
654 // Compute the require features.
655 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates");
656 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
657 if (SubtargetFeatureInfo *Feature =
658 Info.getSubtargetFeature(Predicates[i]))
659 RequiredFeatures.push_back(Feature);
661 // Collect singleton registers, if used.
662 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
663 if (Record *Reg = getSingletonRegisterForAsmOperand(i, Info))
664 SingletonRegisters.insert(Reg);
668 /// TokenizeAsmString - Tokenize a simplified assembly string.
669 void MatchableInfo::TokenizeAsmString(const AsmMatcherInfo &Info) {
670 StringRef String = AsmString;
673 for (unsigned i = 0, e = String.size(); i != e; ++i) {
683 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
686 if (!isspace(String[i]) && String[i] != ',')
687 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
693 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
697 assert(i != String.size() && "Invalid quoted character");
698 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
704 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
708 // If this isn't "${", treat like a normal token.
709 if (i + 1 == String.size() || String[i + 1] != '{') {
714 StringRef::iterator End = std::find(String.begin() + i, String.end(),'}');
715 assert(End != String.end() && "Missing brace in operand reference!");
716 size_t EndPos = End - String.begin();
717 AsmOperands.push_back(AsmOperand(String.slice(i, EndPos+1)));
725 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
734 if (InTok && Prev != String.size())
735 AsmOperands.push_back(AsmOperand(String.substr(Prev)));
737 // The first token of the instruction is the mnemonic, which must be a
738 // simple string, not a $foo variable or a singleton register.
739 assert(!AsmOperands.empty() && "Instruction has no tokens?");
740 Mnemonic = AsmOperands[0].Token;
741 if (Mnemonic[0] == '$' || getSingletonRegisterForAsmOperand(0, Info))
742 throw TGError(TheDef->getLoc(),
743 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
745 // Remove the first operand, it is tracked in the mnemonic field.
746 AsmOperands.erase(AsmOperands.begin());
749 bool MatchableInfo::Validate(StringRef CommentDelimiter, bool Hack) const {
750 // Reject matchables with no .s string.
751 if (AsmString.empty())
752 throw TGError(TheDef->getLoc(), "instruction with empty asm string");
754 // Reject any matchables with a newline in them, they should be marked
755 // isCodeGenOnly if they are pseudo instructions.
756 if (AsmString.find('\n') != std::string::npos)
757 throw TGError(TheDef->getLoc(),
758 "multiline instruction is not valid for the asmparser, "
759 "mark it isCodeGenOnly");
761 // Remove comments from the asm string. We know that the asmstring only
763 if (!CommentDelimiter.empty() &&
764 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
765 throw TGError(TheDef->getLoc(),
766 "asmstring for instruction has comment character in it, "
767 "mark it isCodeGenOnly");
769 // Reject matchables with operand modifiers, these aren't something we can
770 // handle, the target should be refactored to use operands instead of
773 // Also, check for instructions which reference the operand multiple times;
774 // this implies a constraint we would not honor.
775 std::set<std::string> OperandNames;
776 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
777 StringRef Tok = AsmOperands[i].Token;
778 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
779 throw TGError(TheDef->getLoc(),
780 "matchable with operand modifier '" + Tok.str() +
781 "' not supported by asm matcher. Mark isCodeGenOnly!");
783 // Verify that any operand is only mentioned once.
784 // We reject aliases and ignore instructions for now.
785 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
787 throw TGError(TheDef->getLoc(),
788 "ERROR: matchable with tied operand '" + Tok.str() +
789 "' can never be matched!");
790 // FIXME: Should reject these. The ARM backend hits this with $lane in a
791 // bunch of instructions. It is unclear what the right answer is.
793 errs() << "warning: '" << TheDef->getName() << "': "
794 << "ignoring instruction with tied operand '"
795 << Tok.str() << "'\n";
804 /// getSingletonRegisterForAsmOperand - If the specified token is a singleton
805 /// register, return the register name, otherwise return a null StringRef.
806 Record *MatchableInfo::
807 getSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info) const{
808 StringRef Tok = AsmOperands[i].Token;
809 if (!Tok.startswith(Info.RegisterPrefix))
812 StringRef RegName = Tok.substr(Info.RegisterPrefix.size());
813 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
816 // If there is no register prefix (i.e. "%" in "%eax"), then this may
817 // be some random non-register token, just ignore it.
818 if (Info.RegisterPrefix.empty())
821 // Otherwise, we have something invalid prefixed with the register prefix,
823 std::string Err = "unable to find register for '" + RegName.str() +
824 "' (which matches register prefix)";
825 throw TGError(TheDef->getLoc(), Err);
828 static std::string getEnumNameForToken(StringRef Str) {
831 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
833 case '*': Res += "_STAR_"; break;
834 case '%': Res += "_PCT_"; break;
835 case ':': Res += "_COLON_"; break;
836 case '!': Res += "_EXCLAIM_"; break;
837 case '.': Res += "_DOT_"; break;
842 Res += "_" + utostr((unsigned) *it) + "_";
849 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
850 ClassInfo *&Entry = TokenClasses[Token];
853 Entry = new ClassInfo();
854 Entry->Kind = ClassInfo::Token;
855 Entry->ClassName = "Token";
856 Entry->Name = "MCK_" + getEnumNameForToken(Token);
857 Entry->ValueName = Token;
858 Entry->PredicateMethod = "<invalid>";
859 Entry->RenderMethod = "<invalid>";
860 Entry->ParserMethod = "";
861 Classes.push_back(Entry);
868 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
870 Record *Rec = OI.Rec;
872 Rec = dynamic_cast<DefInit*>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
874 if (Rec->isSubClassOf("RegisterOperand")) {
875 // RegisterOperand may have an associated ParserMatchClass. If it does,
876 // use it, else just fall back to the underlying register class.
877 const RecordVal *R = Rec->getValue("ParserMatchClass");
878 if (R == 0 || R->getValue() == 0)
879 throw "Record `" + Rec->getName() +
880 "' does not have a ParserMatchClass!\n";
882 if (DefInit *DI= dynamic_cast<DefInit*>(R->getValue())) {
883 Record *MatchClass = DI->getDef();
884 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
888 // No custom match class. Just use the register class.
889 Record *ClassRec = Rec->getValueAsDef("RegClass");
891 throw TGError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
892 "' has no associated register class!\n");
893 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
895 throw TGError(Rec->getLoc(), "register class has no class info!");
899 if (Rec->isSubClassOf("RegisterClass")) {
900 if (ClassInfo *CI = RegisterClassClasses[Rec])
902 throw TGError(Rec->getLoc(), "register class has no class info!");
905 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
906 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
907 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
910 throw TGError(Rec->getLoc(), "operand has no match class!");
913 void AsmMatcherInfo::
914 BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
915 const std::vector<CodeGenRegister*> &Registers =
916 Target.getRegBank().getRegisters();
917 ArrayRef<CodeGenRegisterClass*> RegClassList =
918 Target.getRegBank().getRegClasses();
920 // The register sets used for matching.
921 std::set< std::set<Record*> > RegisterSets;
923 // Gather the defined sets.
924 for (ArrayRef<CodeGenRegisterClass*>::const_iterator it =
925 RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it)
926 RegisterSets.insert(std::set<Record*>(
927 (*it)->getOrder().begin(), (*it)->getOrder().end()));
929 // Add any required singleton sets.
930 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
931 ie = SingletonRegisters.end(); it != ie; ++it) {
933 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
936 // Introduce derived sets where necessary (when a register does not determine
937 // a unique register set class), and build the mapping of registers to the set
938 // they should classify to.
939 std::map<Record*, std::set<Record*> > RegisterMap;
940 for (std::vector<CodeGenRegister*>::const_iterator it = Registers.begin(),
941 ie = Registers.end(); it != ie; ++it) {
942 const CodeGenRegister &CGR = **it;
943 // Compute the intersection of all sets containing this register.
944 std::set<Record*> ContainingSet;
946 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
947 ie = RegisterSets.end(); it != ie; ++it) {
948 if (!it->count(CGR.TheDef))
951 if (ContainingSet.empty()) {
956 std::set<Record*> Tmp;
957 std::swap(Tmp, ContainingSet);
958 std::insert_iterator< std::set<Record*> > II(ContainingSet,
959 ContainingSet.begin());
960 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(), II);
963 if (!ContainingSet.empty()) {
964 RegisterSets.insert(ContainingSet);
965 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
969 // Construct the register classes.
970 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
972 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
973 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
974 ClassInfo *CI = new ClassInfo();
975 CI->Kind = ClassInfo::RegisterClass0 + Index;
976 CI->ClassName = "Reg" + utostr(Index);
977 CI->Name = "MCK_Reg" + utostr(Index);
979 CI->PredicateMethod = ""; // unused
980 CI->RenderMethod = "addRegOperands";
982 Classes.push_back(CI);
983 RegisterSetClasses.insert(std::make_pair(*it, CI));
986 // Find the superclasses; we could compute only the subgroup lattice edges,
987 // but there isn't really a point.
988 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
989 ie = RegisterSets.end(); it != ie; ++it) {
990 ClassInfo *CI = RegisterSetClasses[*it];
991 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
992 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
994 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
995 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
998 // Name the register classes which correspond to a user defined RegisterClass.
999 for (ArrayRef<CodeGenRegisterClass*>::const_iterator
1000 it = RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) {
1001 const CodeGenRegisterClass &RC = **it;
1002 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(RC.getOrder().begin(),
1003 RC.getOrder().end())];
1004 if (CI->ValueName.empty()) {
1005 CI->ClassName = RC.getName();
1006 CI->Name = "MCK_" + RC.getName();
1007 CI->ValueName = RC.getName();
1009 CI->ValueName = CI->ValueName + "," + RC.getName();
1011 RegisterClassClasses.insert(std::make_pair(RC.TheDef, CI));
1014 // Populate the map for individual registers.
1015 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
1016 ie = RegisterMap.end(); it != ie; ++it)
1017 RegisterClasses[it->first] = RegisterSetClasses[it->second];
1019 // Name the register classes which correspond to singleton registers.
1020 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1021 ie = SingletonRegisters.end(); it != ie; ++it) {
1023 ClassInfo *CI = RegisterClasses[Rec];
1024 assert(CI && "Missing singleton register class info!");
1026 if (CI->ValueName.empty()) {
1027 CI->ClassName = Rec->getName();
1028 CI->Name = "MCK_" + Rec->getName();
1029 CI->ValueName = Rec->getName();
1031 CI->ValueName = CI->ValueName + "," + Rec->getName();
1035 void AsmMatcherInfo::BuildOperandClasses() {
1036 std::vector<Record*> AsmOperands =
1037 Records.getAllDerivedDefinitions("AsmOperandClass");
1039 // Pre-populate AsmOperandClasses map.
1040 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1041 ie = AsmOperands.end(); it != ie; ++it)
1042 AsmOperandClasses[*it] = new ClassInfo();
1045 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1046 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
1047 ClassInfo *CI = AsmOperandClasses[*it];
1048 CI->Kind = ClassInfo::UserClass0 + Index;
1050 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
1051 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
1052 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
1054 PrintError((*it)->getLoc(), "Invalid super class reference!");
1058 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1060 PrintError((*it)->getLoc(), "Invalid super class reference!");
1062 CI->SuperClasses.push_back(SC);
1064 CI->ClassName = (*it)->getValueAsString("Name");
1065 CI->Name = "MCK_" + CI->ClassName;
1066 CI->ValueName = (*it)->getName();
1068 // Get or construct the predicate method name.
1069 Init *PMName = (*it)->getValueInit("PredicateMethod");
1070 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
1071 CI->PredicateMethod = SI->getValue();
1073 assert(dynamic_cast<UnsetInit*>(PMName) &&
1074 "Unexpected PredicateMethod field!");
1075 CI->PredicateMethod = "is" + CI->ClassName;
1078 // Get or construct the render method name.
1079 Init *RMName = (*it)->getValueInit("RenderMethod");
1080 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
1081 CI->RenderMethod = SI->getValue();
1083 assert(dynamic_cast<UnsetInit*>(RMName) &&
1084 "Unexpected RenderMethod field!");
1085 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1088 // Get the parse method name or leave it as empty.
1089 Init *PRMName = (*it)->getValueInit("ParserMethod");
1090 if (StringInit *SI = dynamic_cast<StringInit*>(PRMName))
1091 CI->ParserMethod = SI->getValue();
1093 AsmOperandClasses[*it] = CI;
1094 Classes.push_back(CI);
1098 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1099 CodeGenTarget &target,
1100 RecordKeeper &records)
1101 : Records(records), AsmParser(asmParser), Target(target),
1102 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix")) {
1105 /// BuildOperandMatchInfo - Build the necessary information to handle user
1106 /// defined operand parsing methods.
1107 void AsmMatcherInfo::BuildOperandMatchInfo() {
1109 /// Map containing a mask with all operands indicies that can be found for
1110 /// that class inside a instruction.
1111 std::map<ClassInfo*, unsigned> OpClassMask;
1113 for (std::vector<MatchableInfo*>::const_iterator it =
1114 Matchables.begin(), ie = Matchables.end();
1116 MatchableInfo &II = **it;
1117 OpClassMask.clear();
1119 // Keep track of all operands of this instructions which belong to the
1121 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
1122 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
1123 if (Op.Class->ParserMethod.empty())
1125 unsigned &OperandMask = OpClassMask[Op.Class];
1126 OperandMask |= (1 << i);
1129 // Generate operand match info for each mnemonic/operand class pair.
1130 for (std::map<ClassInfo*, unsigned>::iterator iit = OpClassMask.begin(),
1131 iie = OpClassMask.end(); iit != iie; ++iit) {
1132 unsigned OpMask = iit->second;
1133 ClassInfo *CI = iit->first;
1134 OperandMatchInfo.push_back(OperandMatchEntry::Create(&II, CI, OpMask));
1139 void AsmMatcherInfo::BuildInfo() {
1140 // Build information about all of the AssemblerPredicates.
1141 std::vector<Record*> AllPredicates =
1142 Records.getAllDerivedDefinitions("Predicate");
1143 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
1144 Record *Pred = AllPredicates[i];
1145 // Ignore predicates that are not intended for the assembler.
1146 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
1149 if (Pred->getName().empty())
1150 throw TGError(Pred->getLoc(), "Predicate has no name!");
1152 unsigned FeatureNo = SubtargetFeatures.size();
1153 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
1154 assert(FeatureNo < 32 && "Too many subtarget features!");
1157 std::string CommentDelimiter = AsmParser->getValueAsString("CommentDelimiter");
1159 // Parse the instructions; we need to do this first so that we can gather the
1160 // singleton register classes.
1161 SmallPtrSet<Record*, 16> SingletonRegisters;
1162 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
1163 E = Target.inst_end(); I != E; ++I) {
1164 const CodeGenInstruction &CGI = **I;
1166 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1167 // filter the set of instructions we consider.
1168 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
1171 // Ignore "codegen only" instructions.
1172 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
1175 // Validate the operand list to ensure we can handle this instruction.
1176 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1177 const CGIOperandList::OperandInfo &OI = CGI.Operands[i];
1179 // Validate tied operands.
1180 if (OI.getTiedRegister() != -1) {
1181 // If we have a tied operand that consists of multiple MCOperands,
1182 // reject it. We reject aliases and ignore instructions for now.
1183 if (OI.MINumOperands != 1) {
1184 // FIXME: Should reject these. The ARM backend hits this with $lane
1185 // in a bunch of instructions. It is unclear what the right answer is.
1187 errs() << "warning: '" << CGI.TheDef->getName() << "': "
1188 << "ignoring instruction with multi-operand tied operand '"
1189 << OI.Name << "'\n";
1196 OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
1198 II->Initialize(*this, SingletonRegisters);
1200 // Ignore instructions which shouldn't be matched and diagnose invalid
1201 // instruction definitions with an error.
1202 if (!II->Validate(CommentDelimiter, true))
1205 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
1207 // FIXME: This is a total hack.
1208 if (StringRef(II->TheDef->getName()).startswith("Int_") ||
1209 StringRef(II->TheDef->getName()).endswith("_Int"))
1212 Matchables.push_back(II.take());
1215 // Parse all of the InstAlias definitions and stick them in the list of
1217 std::vector<Record*> AllInstAliases =
1218 Records.getAllDerivedDefinitions("InstAlias");
1219 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
1220 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i], Target);
1222 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1223 // filter the set of instruction aliases we consider, based on the target
1225 if (!StringRef(Alias->ResultInst->TheDef->getName()).startswith(
1229 OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
1231 II->Initialize(*this, SingletonRegisters);
1233 // Validate the alias definitions.
1234 II->Validate(CommentDelimiter, false);
1236 Matchables.push_back(II.take());
1239 // Build info for the register classes.
1240 BuildRegisterClasses(SingletonRegisters);
1242 // Build info for the user defined assembly operand classes.
1243 BuildOperandClasses();
1245 // Build the information about matchables, now that we have fully formed
1247 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(),
1248 ie = Matchables.end(); it != ie; ++it) {
1249 MatchableInfo *II = *it;
1251 // Parse the tokens after the mnemonic.
1252 // Note: BuildInstructionOperandReference may insert new AsmOperands, so
1253 // don't precompute the loop bound.
1254 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1255 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
1256 StringRef Token = Op.Token;
1258 // Check for singleton registers.
1259 if (Record *RegRecord = II->getSingletonRegisterForAsmOperand(i, *this)) {
1260 Op.Class = RegisterClasses[RegRecord];
1261 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1262 "Unexpected class for singleton register");
1266 // Check for simple tokens.
1267 if (Token[0] != '$') {
1268 Op.Class = getTokenClass(Token);
1272 if (Token.size() > 1 && isdigit(Token[1])) {
1273 Op.Class = getTokenClass(Token);
1277 // Otherwise this is an operand reference.
1278 StringRef OperandName;
1279 if (Token[1] == '{')
1280 OperandName = Token.substr(2, Token.size() - 3);
1282 OperandName = Token.substr(1);
1284 if (II->DefRec.is<const CodeGenInstruction*>())
1285 BuildInstructionOperandReference(II, OperandName, i);
1287 BuildAliasOperandReference(II, OperandName, Op);
1290 if (II->DefRec.is<const CodeGenInstruction*>())
1291 II->BuildInstructionResultOperands();
1293 II->BuildAliasResultOperands();
1296 // Reorder classes so that classes precede super classes.
1297 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
1300 /// BuildInstructionOperandReference - The specified operand is a reference to a
1301 /// named operand such as $src. Resolve the Class and OperandInfo pointers.
1302 void AsmMatcherInfo::
1303 BuildInstructionOperandReference(MatchableInfo *II,
1304 StringRef OperandName,
1305 unsigned AsmOpIdx) {
1306 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1307 const CGIOperandList &Operands = CGI.Operands;
1308 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
1310 // Map this token to an operand.
1312 if (!Operands.hasOperandNamed(OperandName, Idx))
1313 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1314 OperandName.str() + "'");
1316 // If the instruction operand has multiple suboperands, but the parser
1317 // match class for the asm operand is still the default "ImmAsmOperand",
1318 // then handle each suboperand separately.
1319 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1320 Record *Rec = Operands[Idx].Rec;
1321 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1322 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1323 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1324 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1325 StringRef Token = Op->Token; // save this in case Op gets moved
1326 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1327 MatchableInfo::AsmOperand NewAsmOp(Token);
1328 NewAsmOp.SubOpIdx = SI;
1329 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1331 // Replace Op with first suboperand.
1332 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1337 // Set up the operand class.
1338 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
1340 // If the named operand is tied, canonicalize it to the untied operand.
1341 // For example, something like:
1342 // (outs GPR:$dst), (ins GPR:$src)
1343 // with an asmstring of
1345 // we want to canonicalize to:
1347 // so that we know how to provide the $dst operand when filling in the result.
1348 int OITied = Operands[Idx].getTiedRegister();
1350 // The tied operand index is an MIOperand index, find the operand that
1352 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1353 OperandName = Operands[Idx.first].Name;
1354 Op->SubOpIdx = Idx.second;
1357 Op->SrcOpName = OperandName;
1360 /// BuildAliasOperandReference - When parsing an operand reference out of the
1361 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1362 /// operand reference is by looking it up in the result pattern definition.
1363 void AsmMatcherInfo::BuildAliasOperandReference(MatchableInfo *II,
1364 StringRef OperandName,
1365 MatchableInfo::AsmOperand &Op) {
1366 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
1368 // Set up the operand class.
1369 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
1370 if (CGA.ResultOperands[i].isRecord() &&
1371 CGA.ResultOperands[i].getName() == OperandName) {
1372 // It's safe to go with the first one we find, because CodeGenInstAlias
1373 // validates that all operands with the same name have the same record.
1374 unsigned ResultIdx = CGA.ResultInstOperandIndex[i].first;
1375 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
1376 Op.Class = getOperandClass(CGA.ResultInst->Operands[ResultIdx],
1378 Op.SrcOpName = OperandName;
1382 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1383 OperandName.str() + "'");
1386 void MatchableInfo::BuildInstructionResultOperands() {
1387 const CodeGenInstruction *ResultInst = getResultInst();
1389 // Loop over all operands of the result instruction, determining how to
1391 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1392 const CGIOperandList::OperandInfo &OpInfo = ResultInst->Operands[i];
1394 // If this is a tied operand, just copy from the previously handled operand.
1395 int TiedOp = OpInfo.getTiedRegister();
1397 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1401 // Find out what operand from the asmparser this MCInst operand comes from.
1402 int SrcOperand = FindAsmOperandNamed(OpInfo.Name);
1403 if (OpInfo.Name.empty() || SrcOperand == -1)
1404 throw TGError(TheDef->getLoc(), "Instruction '" +
1405 TheDef->getName() + "' has operand '" + OpInfo.Name +
1406 "' that doesn't appear in asm string!");
1408 // Check if the one AsmOperand populates the entire operand.
1409 unsigned NumOperands = OpInfo.MINumOperands;
1410 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1411 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
1415 // Add a separate ResOperand for each suboperand.
1416 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1417 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1418 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1419 "unexpected AsmOperands for suboperands");
1420 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1425 void MatchableInfo::BuildAliasResultOperands() {
1426 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1427 const CodeGenInstruction *ResultInst = getResultInst();
1429 // Loop over all operands of the result instruction, determining how to
1431 unsigned AliasOpNo = 0;
1432 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
1433 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1434 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
1436 // If this is a tied operand, just copy from the previously handled operand.
1437 int TiedOp = OpInfo->getTiedRegister();
1439 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1443 // Handle all the suboperands for this operand.
1444 const std::string &OpName = OpInfo->Name;
1445 for ( ; AliasOpNo < LastOpNo &&
1446 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1447 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1449 // Find out what operand from the asmparser that this MCInst operand
1451 switch (CGA.ResultOperands[AliasOpNo].Kind) {
1452 default: assert(0 && "unexpected InstAlias operand kind");
1453 case CodeGenInstAlias::ResultOperand::K_Record: {
1454 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1455 int SrcOperand = FindAsmOperand(Name, SubIdx);
1456 if (SrcOperand == -1)
1457 throw TGError(TheDef->getLoc(), "Instruction '" +
1458 TheDef->getName() + "' has operand '" + OpName +
1459 "' that doesn't appear in asm string!");
1460 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1461 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1465 case CodeGenInstAlias::ResultOperand::K_Imm: {
1466 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1467 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1470 case CodeGenInstAlias::ResultOperand::K_Reg: {
1471 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1472 ResOperands.push_back(ResOperand::getRegOp(Reg));
1480 static void EmitConvertToMCInst(CodeGenTarget &Target, StringRef ClassName,
1481 std::vector<MatchableInfo*> &Infos,
1483 // Write the convert function to a separate stream, so we can drop it after
1485 std::string ConvertFnBody;
1486 raw_string_ostream CvtOS(ConvertFnBody);
1488 // Function we have already generated.
1489 std::set<std::string> GeneratedFns;
1491 // Start the unified conversion function.
1492 CvtOS << "bool " << Target.getName() << ClassName << "::\n";
1493 CvtOS << "ConvertToMCInst(unsigned Kind, MCInst &Inst, "
1494 << "unsigned Opcode,\n"
1495 << " const SmallVectorImpl<MCParsedAsmOperand*"
1496 << "> &Operands) {\n";
1497 CvtOS << " Inst.setOpcode(Opcode);\n";
1498 CvtOS << " switch (Kind) {\n";
1499 CvtOS << " default:\n";
1501 // Start the enum, which we will generate inline.
1503 OS << "// Unified function for converting operands to MCInst instances.\n\n";
1504 OS << "enum ConversionKind {\n";
1506 // TargetOperandClass - This is the target's operand class, like X86Operand.
1507 std::string TargetOperandClass = Target.getName() + "Operand";
1509 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(),
1510 ie = Infos.end(); it != ie; ++it) {
1511 MatchableInfo &II = **it;
1513 // Check if we have a custom match function.
1514 std::string AsmMatchConverter =
1515 II.getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
1516 if (!AsmMatchConverter.empty()) {
1517 std::string Signature = "ConvertCustom_" + AsmMatchConverter;
1518 II.ConversionFnKind = Signature;
1520 // Check if we have already generated this signature.
1521 if (!GeneratedFns.insert(Signature).second)
1524 // If not, emit it now. Add to the enum list.
1525 OS << " " << Signature << ",\n";
1527 CvtOS << " case " << Signature << ":\n";
1528 CvtOS << " return " << AsmMatchConverter
1529 << "(Inst, Opcode, Operands);\n";
1533 // Build the conversion function signature.
1534 std::string Signature = "Convert";
1535 std::string CaseBody;
1536 raw_string_ostream CaseOS(CaseBody);
1538 // Compute the convert enum and the case body.
1539 for (unsigned i = 0, e = II.ResOperands.size(); i != e; ++i) {
1540 const MatchableInfo::ResOperand &OpInfo = II.ResOperands[i];
1542 // Generate code to populate each result operand.
1543 switch (OpInfo.Kind) {
1544 case MatchableInfo::ResOperand::RenderAsmOperand: {
1545 // This comes from something we parsed.
1546 MatchableInfo::AsmOperand &Op = II.AsmOperands[OpInfo.AsmOperandNum];
1548 // Registers are always converted the same, don't duplicate the
1549 // conversion function based on them.
1551 if (Op.Class->isRegisterClass())
1554 Signature += Op.Class->ClassName;
1555 Signature += utostr(OpInfo.MINumOperands);
1556 Signature += "_" + itostr(OpInfo.AsmOperandNum);
1558 CaseOS << " ((" << TargetOperandClass << "*)Operands["
1559 << (OpInfo.AsmOperandNum+1) << "])->" << Op.Class->RenderMethod
1560 << "(Inst, " << OpInfo.MINumOperands << ");\n";
1564 case MatchableInfo::ResOperand::TiedOperand: {
1565 // If this operand is tied to a previous one, just copy the MCInst
1566 // operand from the earlier one.We can only tie single MCOperand values.
1567 //assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
1568 unsigned TiedOp = OpInfo.TiedOperandNum;
1569 assert(i > TiedOp && "Tied operand precedes its target!");
1570 CaseOS << " Inst.addOperand(Inst.getOperand(" << TiedOp << "));\n";
1571 Signature += "__Tie" + utostr(TiedOp);
1574 case MatchableInfo::ResOperand::ImmOperand: {
1575 int64_t Val = OpInfo.ImmVal;
1576 CaseOS << " Inst.addOperand(MCOperand::CreateImm(" << Val << "));\n";
1577 Signature += "__imm" + itostr(Val);
1580 case MatchableInfo::ResOperand::RegOperand: {
1581 if (OpInfo.Register == 0) {
1582 CaseOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1583 Signature += "__reg0";
1585 std::string N = getQualifiedName(OpInfo.Register);
1586 CaseOS << " Inst.addOperand(MCOperand::CreateReg(" << N << "));\n";
1587 Signature += "__reg" + OpInfo.Register->getName();
1593 II.ConversionFnKind = Signature;
1595 // Check if we have already generated this signature.
1596 if (!GeneratedFns.insert(Signature).second)
1599 // If not, emit it now. Add to the enum list.
1600 OS << " " << Signature << ",\n";
1602 CvtOS << " case " << Signature << ":\n";
1603 CvtOS << CaseOS.str();
1604 CvtOS << " return true;\n";
1607 // Finish the convert function.
1610 CvtOS << " return false;\n";
1613 // Finish the enum, and drop the convert function after it.
1615 OS << " NumConversionVariants\n";
1621 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1622 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1623 std::vector<ClassInfo*> &Infos,
1625 OS << "namespace {\n\n";
1627 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1628 << "/// instruction matching.\n";
1629 OS << "enum MatchClassKind {\n";
1630 OS << " InvalidMatchClass = 0,\n";
1631 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1632 ie = Infos.end(); it != ie; ++it) {
1633 ClassInfo &CI = **it;
1634 OS << " " << CI.Name << ", // ";
1635 if (CI.Kind == ClassInfo::Token) {
1636 OS << "'" << CI.ValueName << "'\n";
1637 } else if (CI.isRegisterClass()) {
1638 if (!CI.ValueName.empty())
1639 OS << "register class '" << CI.ValueName << "'\n";
1641 OS << "derived register class\n";
1643 OS << "user defined class '" << CI.ValueName << "'\n";
1646 OS << " NumMatchClassKinds\n";
1652 /// EmitValidateOperandClass - Emit the function to validate an operand class.
1653 static void EmitValidateOperandClass(AsmMatcherInfo &Info,
1655 OS << "static bool ValidateOperandClass(MCParsedAsmOperand *GOp, "
1656 << "MatchClassKind Kind) {\n";
1657 OS << " " << Info.Target.getName() << "Operand &Operand = *("
1658 << Info.Target.getName() << "Operand*)GOp;\n";
1660 // The InvalidMatchClass is not to match any operand.
1661 OS << " if (Kind == InvalidMatchClass)\n";
1662 OS << " return false;\n\n";
1664 // Check for Token operands first.
1665 OS << " if (Operand.isToken())\n";
1666 OS << " return MatchTokenString(Operand.getToken()) == Kind;\n\n";
1668 // Check for register operands, including sub-classes.
1669 OS << " if (Operand.isReg()) {\n";
1670 OS << " MatchClassKind OpKind;\n";
1671 OS << " switch (Operand.getReg()) {\n";
1672 OS << " default: OpKind = InvalidMatchClass; break;\n";
1673 for (std::map<Record*, ClassInfo*>::iterator
1674 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1676 OS << " case " << Info.Target.getName() << "::"
1677 << it->first->getName() << ": OpKind = " << it->second->Name
1680 OS << " return IsSubclass(OpKind, Kind);\n";
1683 // Check the user classes. We don't care what order since we're only
1684 // actually matching against one of them.
1685 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1686 ie = Info.Classes.end(); it != ie; ++it) {
1687 ClassInfo &CI = **it;
1689 if (!CI.isUserClass())
1692 OS << " // '" << CI.ClassName << "' class\n";
1693 OS << " if (Kind == " << CI.Name
1694 << " && Operand." << CI.PredicateMethod << "()) {\n";
1695 OS << " return true;\n";
1699 OS << " return false;\n";
1703 /// EmitIsSubclass - Emit the subclass predicate function.
1704 static void EmitIsSubclass(CodeGenTarget &Target,
1705 std::vector<ClassInfo*> &Infos,
1707 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1708 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1709 OS << " if (A == B)\n";
1710 OS << " return true;\n\n";
1712 OS << " switch (A) {\n";
1713 OS << " default:\n";
1714 OS << " return false;\n";
1715 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1716 ie = Infos.end(); it != ie; ++it) {
1717 ClassInfo &A = **it;
1719 if (A.Kind != ClassInfo::Token) {
1720 std::vector<StringRef> SuperClasses;
1721 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1722 ie = Infos.end(); it != ie; ++it) {
1723 ClassInfo &B = **it;
1725 if (&A != &B && A.isSubsetOf(B))
1726 SuperClasses.push_back(B.Name);
1729 if (SuperClasses.empty())
1732 OS << "\n case " << A.Name << ":\n";
1734 if (SuperClasses.size() == 1) {
1735 OS << " return B == " << SuperClasses.back() << ";\n";
1739 OS << " switch (B) {\n";
1740 OS << " default: return false;\n";
1741 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1742 OS << " case " << SuperClasses[i] << ": return true;\n";
1750 /// EmitMatchTokenString - Emit the function to match a token string to the
1751 /// appropriate match class value.
1752 static void EmitMatchTokenString(CodeGenTarget &Target,
1753 std::vector<ClassInfo*> &Infos,
1755 // Construct the match list.
1756 std::vector<StringMatcher::StringPair> Matches;
1757 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1758 ie = Infos.end(); it != ie; ++it) {
1759 ClassInfo &CI = **it;
1761 if (CI.Kind == ClassInfo::Token)
1762 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1763 "return " + CI.Name + ";"));
1766 OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
1768 StringMatcher("Name", Matches, OS).Emit();
1770 OS << " return InvalidMatchClass;\n";
1774 /// EmitMatchRegisterName - Emit the function to match a string to the target
1775 /// specific register enum.
1776 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1778 // Construct the match list.
1779 std::vector<StringMatcher::StringPair> Matches;
1780 const std::vector<CodeGenRegister*> &Regs =
1781 Target.getRegBank().getRegisters();
1782 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1783 const CodeGenRegister *Reg = Regs[i];
1784 if (Reg->TheDef->getValueAsString("AsmName").empty())
1787 Matches.push_back(StringMatcher::StringPair(
1788 Reg->TheDef->getValueAsString("AsmName"),
1789 "return " + utostr(Reg->EnumValue) + ";"));
1792 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
1794 StringMatcher("Name", Matches, OS).Emit();
1796 OS << " return 0;\n";
1800 /// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1802 static void EmitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
1804 OS << "// Flags for subtarget features that participate in "
1805 << "instruction matching.\n";
1806 OS << "enum SubtargetFeatureFlag {\n";
1807 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1808 it = Info.SubtargetFeatures.begin(),
1809 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1810 SubtargetFeatureInfo &SFI = *it->second;
1811 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
1813 OS << " Feature_None = 0\n";
1817 /// EmitComputeAvailableFeatures - Emit the function to compute the list of
1818 /// available features given a subtarget.
1819 static void EmitComputeAvailableFeatures(AsmMatcherInfo &Info,
1821 std::string ClassName =
1822 Info.AsmParser->getValueAsString("AsmParserClassName");
1824 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
1825 << "ComputeAvailableFeatures(uint64_t FB) const {\n";
1826 OS << " unsigned Features = 0;\n";
1827 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1828 it = Info.SubtargetFeatures.begin(),
1829 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1830 SubtargetFeatureInfo &SFI = *it->second;
1833 std::string CondStorage = SFI.TheDef->getValueAsString("AssemblerCondString");
1834 StringRef Conds = CondStorage;
1835 std::pair<StringRef,StringRef> Comma = Conds.split(',');
1842 StringRef Cond = Comma.first;
1843 if (Cond[0] == '!') {
1845 Cond = Cond.substr(1);
1848 OS << "((FB & " << Info.Target.getName() << "::" << Cond << ")";
1855 if (Comma.second.empty())
1859 Comma = Comma.second.split(',');
1863 OS << " Features |= " << SFI.getEnumName() << ";\n";
1865 OS << " return Features;\n";
1869 static std::string GetAliasRequiredFeatures(Record *R,
1870 const AsmMatcherInfo &Info) {
1871 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
1873 unsigned NumFeatures = 0;
1874 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
1875 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
1878 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
1879 "' is not marked as an AssemblerPredicate!");
1884 Result += F->getEnumName();
1888 if (NumFeatures > 1)
1889 Result = '(' + Result + ')';
1893 /// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
1894 /// emit a function for them and return true, otherwise return false.
1895 static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
1896 // Ignore aliases when match-prefix is set.
1897 if (!MatchPrefix.empty())
1900 std::vector<Record*> Aliases =
1901 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
1902 if (Aliases.empty()) return false;
1904 OS << "static void ApplyMnemonicAliases(StringRef &Mnemonic, "
1905 "unsigned Features) {\n";
1907 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
1908 // iteration order of the map is stable.
1909 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1911 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1912 Record *R = Aliases[i];
1913 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
1916 // Process each alias a "from" mnemonic at a time, building the code executed
1917 // by the string remapper.
1918 std::vector<StringMatcher::StringPair> Cases;
1919 for (std::map<std::string, std::vector<Record*> >::iterator
1920 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1922 const std::vector<Record*> &ToVec = I->second;
1924 // Loop through each alias and emit code that handles each case. If there
1925 // are two instructions without predicates, emit an error. If there is one,
1927 std::string MatchCode;
1928 int AliasWithNoPredicate = -1;
1930 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1931 Record *R = ToVec[i];
1932 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
1934 // If this unconditionally matches, remember it for later and diagnose
1936 if (FeatureMask.empty()) {
1937 if (AliasWithNoPredicate != -1) {
1938 // We can't have two aliases from the same mnemonic with no predicate.
1939 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1940 "two MnemonicAliases with the same 'from' mnemonic!");
1941 throw TGError(R->getLoc(), "this is the other MnemonicAlias.");
1944 AliasWithNoPredicate = i;
1947 if (R->getValueAsString("ToMnemonic") == I->first)
1948 throw TGError(R->getLoc(), "MnemonicAlias to the same string");
1950 if (!MatchCode.empty())
1951 MatchCode += "else ";
1952 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1953 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
1956 if (AliasWithNoPredicate != -1) {
1957 Record *R = ToVec[AliasWithNoPredicate];
1958 if (!MatchCode.empty())
1959 MatchCode += "else\n ";
1960 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
1963 MatchCode += "return;";
1965 Cases.push_back(std::make_pair(I->first, MatchCode));
1968 StringMatcher("Mnemonic", Cases, OS).Emit();
1974 static void EmitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
1975 const AsmMatcherInfo &Info, StringRef ClassName) {
1976 // Emit the static custom operand parsing table;
1977 OS << "namespace {\n";
1978 OS << " struct OperandMatchEntry {\n";
1979 OS << " const char *Mnemonic;\n";
1980 OS << " unsigned OperandMask;\n";
1981 OS << " MatchClassKind Class;\n";
1982 OS << " unsigned RequiredFeatures;\n";
1985 OS << " // Predicate for searching for an opcode.\n";
1986 OS << " struct LessOpcodeOperand {\n";
1987 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
1988 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
1990 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
1991 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
1993 OS << " bool operator()(const OperandMatchEntry &LHS,";
1994 OS << " const OperandMatchEntry &RHS) {\n";
1995 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
1999 OS << "} // end anonymous namespace.\n\n";
2001 OS << "static const OperandMatchEntry OperandMatchTable["
2002 << Info.OperandMatchInfo.size() << "] = {\n";
2004 OS << " /* Mnemonic, Operand List Mask, Operand Class, Features */\n";
2005 for (std::vector<OperandMatchEntry>::const_iterator it =
2006 Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end();
2008 const OperandMatchEntry &OMI = *it;
2009 const MatchableInfo &II = *OMI.MI;
2011 OS << " { \"" << II.Mnemonic << "\""
2012 << ", " << OMI.OperandMask;
2015 bool printComma = false;
2016 for (int i = 0, e = 31; i !=e; ++i)
2017 if (OMI.OperandMask & (1 << i)) {
2025 OS << ", " << OMI.CI->Name
2028 // Write the required features mask.
2029 if (!II.RequiredFeatures.empty()) {
2030 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2032 OS << II.RequiredFeatures[i]->getEnumName();
2040 // Emit the operand class switch to call the correct custom parser for
2041 // the found operand class.
2042 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2043 << Target.getName() << ClassName << "::\n"
2044 << "TryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>"
2045 << " &Operands,\n unsigned MCK) {\n\n"
2046 << " switch(MCK) {\n";
2048 for (std::vector<ClassInfo*>::const_iterator it = Info.Classes.begin(),
2049 ie = Info.Classes.end(); it != ie; ++it) {
2050 ClassInfo *CI = *it;
2051 if (CI->ParserMethod.empty())
2053 OS << " case " << CI->Name << ":\n"
2054 << " return " << CI->ParserMethod << "(Operands);\n";
2057 OS << " default:\n";
2058 OS << " return MatchOperand_NoMatch;\n";
2060 OS << " return MatchOperand_NoMatch;\n";
2063 // Emit the static custom operand parser. This code is very similar with
2064 // the other matcher. Also use MatchResultTy here just in case we go for
2065 // a better error handling.
2066 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2067 << Target.getName() << ClassName << "::\n"
2068 << "MatchOperandParserImpl(SmallVectorImpl<MCParsedAsmOperand*>"
2069 << " &Operands,\n StringRef Mnemonic) {\n";
2071 // Emit code to get the available features.
2072 OS << " // Get the current feature set.\n";
2073 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2075 OS << " // Get the next operand index.\n";
2076 OS << " unsigned NextOpNum = Operands.size()-1;\n";
2078 // Emit code to search the table.
2079 OS << " // Search the table.\n";
2080 OS << " std::pair<const OperandMatchEntry*, const OperandMatchEntry*>";
2081 OS << " MnemonicRange =\n";
2082 OS << " std::equal_range(OperandMatchTable, OperandMatchTable+"
2083 << Info.OperandMatchInfo.size() << ", Mnemonic,\n"
2084 << " LessOpcodeOperand());\n\n";
2086 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2087 OS << " return MatchOperand_NoMatch;\n\n";
2089 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2090 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2092 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2093 OS << " assert(Mnemonic == it->Mnemonic);\n\n";
2095 // Emit check that the required features are available.
2096 OS << " // check if the available features match\n";
2097 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2098 << "!= it->RequiredFeatures) {\n";
2099 OS << " continue;\n";
2102 // Emit check to ensure the operand number matches.
2103 OS << " // check if the operand in question has a custom parser.\n";
2104 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2105 OS << " continue;\n\n";
2107 // Emit call to the custom parser method
2108 OS << " // call custom parse method to handle the operand\n";
2109 OS << " OperandMatchResultTy Result = ";
2110 OS << "TryCustomParseOperand(Operands, it->Class);\n";
2111 OS << " if (Result != MatchOperand_NoMatch)\n";
2112 OS << " return Result;\n";
2115 OS << " // Okay, we had no match.\n";
2116 OS << " return MatchOperand_NoMatch;\n";
2120 void AsmMatcherEmitter::run(raw_ostream &OS) {
2121 CodeGenTarget Target(Records);
2122 Record *AsmParser = Target.getAsmParser();
2123 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2125 // Compute the information on the instructions to match.
2126 AsmMatcherInfo Info(AsmParser, Target, Records);
2129 // Sort the instruction table using the partial order on classes. We use
2130 // stable_sort to ensure that ambiguous instructions are still
2131 // deterministically ordered.
2132 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2133 less_ptr<MatchableInfo>());
2135 DEBUG_WITH_TYPE("instruction_info", {
2136 for (std::vector<MatchableInfo*>::iterator
2137 it = Info.Matchables.begin(), ie = Info.Matchables.end();
2142 // Check for ambiguous matchables.
2143 DEBUG_WITH_TYPE("ambiguous_instrs", {
2144 unsigned NumAmbiguous = 0;
2145 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) {
2146 for (unsigned j = i + 1; j != e; ++j) {
2147 MatchableInfo &A = *Info.Matchables[i];
2148 MatchableInfo &B = *Info.Matchables[j];
2150 if (A.CouldMatchAmbiguouslyWith(B)) {
2151 errs() << "warning: ambiguous matchables:\n";
2153 errs() << "\nis incomparable with:\n";
2161 errs() << "warning: " << NumAmbiguous
2162 << " ambiguous matchables!\n";
2165 // Compute the information on the custom operand parsing.
2166 Info.BuildOperandMatchInfo();
2168 // Write the output.
2170 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
2172 // Information for the class declaration.
2173 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2174 OS << "#undef GET_ASSEMBLER_HEADER\n";
2175 OS << " // This should be included into the middle of the declaration of\n";
2176 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
2177 OS << " unsigned ComputeAvailableFeatures(uint64_t FeatureBits) const;\n";
2178 OS << " bool ConvertToMCInst(unsigned Kind, MCInst &Inst, "
2179 << "unsigned Opcode,\n"
2180 << " const SmallVectorImpl<MCParsedAsmOperand*> "
2182 OS << " bool MnemonicIsValid(StringRef Mnemonic);\n";
2183 OS << " unsigned MatchInstructionImpl(\n";
2184 OS << " const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2185 OS << " MCInst &Inst, unsigned &ErrorInfo);\n";
2187 if (Info.OperandMatchInfo.size()) {
2188 OS << "\n enum OperandMatchResultTy {\n";
2189 OS << " MatchOperand_Success, // operand matched successfully\n";
2190 OS << " MatchOperand_NoMatch, // operand did not match\n";
2191 OS << " MatchOperand_ParseFail // operand matched but had errors\n";
2193 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
2194 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2195 OS << " StringRef Mnemonic);\n";
2197 OS << " OperandMatchResultTy TryCustomParseOperand(\n";
2198 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2199 OS << " unsigned MCK);\n\n";
2202 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2204 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2205 OS << "#undef GET_REGISTER_MATCHER\n\n";
2207 // Emit the subtarget feature enumeration.
2208 EmitSubtargetFeatureFlagEnumeration(Info, OS);
2210 // Emit the function to match a register name to number.
2211 EmitMatchRegisterName(Target, AsmParser, OS);
2213 OS << "#endif // GET_REGISTER_MATCHER\n\n";
2216 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2217 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
2219 // Generate the function that remaps for mnemonic aliases.
2220 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
2222 // Generate the unified function to convert operands into an MCInst.
2223 EmitConvertToMCInst(Target, ClassName, Info.Matchables, OS);
2225 // Emit the enumeration for classes which participate in matching.
2226 EmitMatchClassEnumeration(Target, Info.Classes, OS);
2228 // Emit the routine to match token strings to their match class.
2229 EmitMatchTokenString(Target, Info.Classes, OS);
2231 // Emit the subclass predicate routine.
2232 EmitIsSubclass(Target, Info.Classes, OS);
2234 // Emit the routine to validate an operand against a match class.
2235 EmitValidateOperandClass(Info, OS);
2237 // Emit the available features compute function.
2238 EmitComputeAvailableFeatures(Info, OS);
2241 size_t MaxNumOperands = 0;
2242 for (std::vector<MatchableInfo*>::const_iterator it =
2243 Info.Matchables.begin(), ie = Info.Matchables.end();
2245 MaxNumOperands = std::max(MaxNumOperands, (*it)->AsmOperands.size());
2247 // Emit the static match table; unused classes get initalized to 0 which is
2248 // guaranteed to be InvalidMatchClass.
2250 // FIXME: We can reduce the size of this table very easily. First, we change
2251 // it so that store the kinds in separate bit-fields for each index, which
2252 // only needs to be the max width used for classes at that index (we also need
2253 // to reject based on this during classification). If we then make sure to
2254 // order the match kinds appropriately (putting mnemonics last), then we
2255 // should only end up using a few bits for each class, especially the ones
2256 // following the mnemonic.
2257 OS << "namespace {\n";
2258 OS << " struct MatchEntry {\n";
2259 OS << " unsigned Opcode;\n";
2260 OS << " const char *Mnemonic;\n";
2261 OS << " ConversionKind ConvertFn;\n";
2262 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
2263 OS << " unsigned RequiredFeatures;\n";
2266 OS << " // Predicate for searching for an opcode.\n";
2267 OS << " struct LessOpcode {\n";
2268 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
2269 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
2271 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
2272 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
2274 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
2275 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
2279 OS << "} // end anonymous namespace.\n\n";
2281 OS << "static const MatchEntry MatchTable["
2282 << Info.Matchables.size() << "] = {\n";
2284 for (std::vector<MatchableInfo*>::const_iterator it =
2285 Info.Matchables.begin(), ie = Info.Matchables.end();
2287 MatchableInfo &II = **it;
2289 OS << " { " << Target.getName() << "::"
2290 << II.getResultInst()->TheDef->getName() << ", \"" << II.Mnemonic << "\""
2291 << ", " << II.ConversionFnKind << ", { ";
2292 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
2293 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
2296 OS << Op.Class->Name;
2300 // Write the required features mask.
2301 if (!II.RequiredFeatures.empty()) {
2302 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2304 OS << II.RequiredFeatures[i]->getEnumName();
2314 // A method to determine if a mnemonic is in the list.
2315 OS << "bool " << Target.getName() << ClassName << "::\n"
2316 << "MnemonicIsValid(StringRef Mnemonic) {\n";
2317 OS << " // Search the table.\n";
2318 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2319 OS << " std::equal_range(MatchTable, MatchTable+"
2320 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n";
2321 OS << " return MnemonicRange.first != MnemonicRange.second;\n";
2324 // Finally, build the match function.
2326 << Target.getName() << ClassName << "::\n"
2327 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
2329 OS << " MCInst &Inst, unsigned &ErrorInfo) {\n";
2331 // Emit code to get the available features.
2332 OS << " // Get the current feature set.\n";
2333 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2335 OS << " // Get the instruction mnemonic, which is the first token.\n";
2336 OS << " StringRef Mnemonic = ((" << Target.getName()
2337 << "Operand*)Operands[0])->getToken();\n\n";
2339 if (HasMnemonicAliases) {
2340 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
2341 OS << " ApplyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
2344 // Emit code to compute the class list for this operand vector.
2345 OS << " // Eliminate obvious mismatches.\n";
2346 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
2347 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
2348 OS << " return Match_InvalidOperand;\n";
2351 OS << " // Some state to try to produce better error messages.\n";
2352 OS << " bool HadMatchOtherThanFeatures = false;\n";
2353 OS << " bool HadMatchOtherThanPredicate = false;\n";
2354 OS << " unsigned RetCode = Match_InvalidOperand;\n";
2355 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
2356 OS << " // wrong for all instances of the instruction.\n";
2357 OS << " ErrorInfo = ~0U;\n";
2359 // Emit code to search the table.
2360 OS << " // Search the table.\n";
2361 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2362 OS << " std::equal_range(MatchTable, MatchTable+"
2363 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n";
2365 OS << " // Return a more specific error code if no mnemonics match.\n";
2366 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2367 OS << " return Match_MnemonicFail;\n\n";
2369 OS << " for (const MatchEntry *it = MnemonicRange.first, "
2370 << "*ie = MnemonicRange.second;\n";
2371 OS << " it != ie; ++it) {\n";
2373 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2374 OS << " assert(Mnemonic == it->Mnemonic);\n";
2376 // Emit check that the subclasses match.
2377 OS << " bool OperandsValid = true;\n";
2378 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
2379 OS << " if (i + 1 >= Operands.size()) {\n";
2380 OS << " OperandsValid = (it->Classes[i] == " <<"InvalidMatchClass);\n";
2383 OS << " if (ValidateOperandClass(Operands[i+1], it->Classes[i]))\n";
2384 OS << " continue;\n";
2385 OS << " // If this operand is broken for all of the instances of this\n";
2386 OS << " // mnemonic, keep track of it so we can report loc info.\n";
2387 OS << " if (it == MnemonicRange.first || ErrorInfo <= i+1)\n";
2388 OS << " ErrorInfo = i+1;\n";
2389 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
2390 OS << " OperandsValid = false;\n";
2394 OS << " if (!OperandsValid) continue;\n";
2396 // Emit check that the required features are available.
2397 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2398 << "!= it->RequiredFeatures) {\n";
2399 OS << " HadMatchOtherThanFeatures = true;\n";
2400 OS << " continue;\n";
2403 OS << " // We have selected a definite instruction, convert the parsed\n"
2404 << " // operands into the appropriate MCInst.\n";
2405 OS << " if (!ConvertToMCInst(it->ConvertFn, Inst,\n"
2406 << " it->Opcode, Operands))\n";
2407 OS << " return Match_ConversionFail;\n";
2410 // Verify the instruction with the target-specific match predicate function.
2411 OS << " // We have a potential match. Check the target predicate to\n"
2412 << " // handle any context sensitive constraints.\n"
2413 << " unsigned MatchResult;\n"
2414 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
2415 << " Match_Success) {\n"
2416 << " Inst.clear();\n"
2417 << " RetCode = MatchResult;\n"
2418 << " HadMatchOtherThanPredicate = true;\n"
2422 // Call the post-processing function, if used.
2423 std::string InsnCleanupFn =
2424 AsmParser->getValueAsString("AsmParserInstCleanup");
2425 if (!InsnCleanupFn.empty())
2426 OS << " " << InsnCleanupFn << "(Inst);\n";
2428 OS << " return Match_Success;\n";
2431 OS << " // Okay, we had no match. Try to return a useful error code.\n";
2432 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)";
2433 OS << " return RetCode;\n";
2434 OS << " return Match_MissingFeature;\n";
2437 if (Info.OperandMatchInfo.size())
2438 EmitCustomOperandParsing(OS, Target, Info, ClassName);
2440 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";