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"
101 #include "StringMatcher.h"
102 #include "llvm/ADT/OwningPtr.h"
103 #include "llvm/ADT/PointerUnion.h"
104 #include "llvm/ADT/SmallPtrSet.h"
105 #include "llvm/ADT/SmallVector.h"
106 #include "llvm/ADT/STLExtras.h"
107 #include "llvm/ADT/StringExtras.h"
108 #include "llvm/Support/CommandLine.h"
109 #include "llvm/Support/Debug.h"
110 #include "llvm/Support/ErrorHandling.h"
111 #include "llvm/TableGen/Error.h"
112 #include "llvm/TableGen/Record.h"
115 using namespace llvm;
117 static cl::opt<std::string>
118 MatchPrefix("match-prefix", cl::init(""),
119 cl::desc("Only match instructions with the given prefix"));
122 class AsmMatcherInfo;
123 struct SubtargetFeatureInfo;
125 /// ClassInfo - Helper class for storing the information about a particular
126 /// class of operands which can be matched.
129 /// Invalid kind, for use as a sentinel value.
132 /// The class for a particular token.
135 /// The (first) register class, subsequent register classes are
136 /// RegisterClass0+1, and so on.
139 /// The (first) user defined class, subsequent user defined classes are
140 /// UserClass0+1, and so on.
144 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
145 /// N) for the Nth user defined class.
148 /// SuperClasses - The super classes of this class. Note that for simplicities
149 /// sake user operands only record their immediate super class, while register
150 /// operands include all superclasses.
151 std::vector<ClassInfo*> SuperClasses;
153 /// Name - The full class name, suitable for use in an enum.
156 /// ClassName - The unadorned generic name for this class (e.g., Token).
157 std::string ClassName;
159 /// ValueName - The name of the value this class represents; for a token this
160 /// is the literal token string, for an operand it is the TableGen class (or
161 /// empty if this is a derived class).
162 std::string ValueName;
164 /// PredicateMethod - The name of the operand method to test whether the
165 /// operand matches this class; this is not valid for Token or register kinds.
166 std::string PredicateMethod;
168 /// RenderMethod - The name of the operand method to add this operand to an
169 /// MCInst; this is not valid for Token or register kinds.
170 std::string RenderMethod;
172 /// ParserMethod - The name of the operand method to do a target specific
173 /// parsing on the operand.
174 std::string ParserMethod;
176 /// For register classes, the records for all the registers in this class.
177 std::set<Record*> Registers;
180 /// isRegisterClass() - Check if this is a register class.
181 bool isRegisterClass() const {
182 return Kind >= RegisterClass0 && Kind < UserClass0;
185 /// isUserClass() - Check if this is a user defined class.
186 bool isUserClass() const {
187 return Kind >= UserClass0;
190 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
191 /// are related if they are in the same class hierarchy.
192 bool isRelatedTo(const ClassInfo &RHS) const {
193 // Tokens are only related to tokens.
194 if (Kind == Token || RHS.Kind == Token)
195 return Kind == Token && RHS.Kind == Token;
197 // Registers classes are only related to registers classes, and only if
198 // their intersection is non-empty.
199 if (isRegisterClass() || RHS.isRegisterClass()) {
200 if (!isRegisterClass() || !RHS.isRegisterClass())
203 std::set<Record*> Tmp;
204 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
205 std::set_intersection(Registers.begin(), Registers.end(),
206 RHS.Registers.begin(), RHS.Registers.end(),
212 // Otherwise we have two users operands; they are related if they are in the
213 // same class hierarchy.
215 // FIXME: This is an oversimplification, they should only be related if they
216 // intersect, however we don't have that information.
217 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
218 const ClassInfo *Root = this;
219 while (!Root->SuperClasses.empty())
220 Root = Root->SuperClasses.front();
222 const ClassInfo *RHSRoot = &RHS;
223 while (!RHSRoot->SuperClasses.empty())
224 RHSRoot = RHSRoot->SuperClasses.front();
226 return Root == RHSRoot;
229 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
230 bool isSubsetOf(const ClassInfo &RHS) const {
231 // This is a subset of RHS if it is the same class...
235 // ... or if any of its super classes are a subset of RHS.
236 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
237 ie = SuperClasses.end(); it != ie; ++it)
238 if ((*it)->isSubsetOf(RHS))
244 /// operator< - Compare two classes.
245 bool operator<(const ClassInfo &RHS) const {
249 // Unrelated classes can be ordered by kind.
250 if (!isRelatedTo(RHS))
251 return Kind < RHS.Kind;
255 llvm_unreachable("Invalid kind!");
258 // This class precedes the RHS if it is a proper subset of the RHS.
261 if (RHS.isSubsetOf(*this))
264 // Otherwise, order by name to ensure we have a total ordering.
265 return ValueName < RHS.ValueName;
270 /// MatchableInfo - Helper class for storing the necessary information for an
271 /// instruction or alias which is capable of being matched.
272 struct MatchableInfo {
274 /// Token - This is the token that the operand came from.
277 /// The unique class instance this operand should match.
280 /// The operand name this is, if anything.
283 /// The suboperand index within SrcOpName, or -1 for the entire operand.
286 /// Register record if this token is singleton register.
287 Record *SingletonReg;
289 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 /// AsmVariantID - Target's assembly syntax variant no.
372 /// TheDef - This is the definition of the instruction or InstAlias that this
373 /// matchable came from.
374 Record *const TheDef;
376 /// DefRec - This is the definition that it came from.
377 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
379 const CodeGenInstruction *getResultInst() const {
380 if (DefRec.is<const CodeGenInstruction*>())
381 return DefRec.get<const CodeGenInstruction*>();
382 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
385 /// ResOperands - This is the operand list that should be built for the result
387 std::vector<ResOperand> ResOperands;
389 /// AsmString - The assembly string for this instruction (with variants
390 /// removed), e.g. "movsx $src, $dst".
391 std::string AsmString;
393 /// Mnemonic - This is the first token of the matched instruction, its
397 /// AsmOperands - The textual operands that this instruction matches,
398 /// annotated with a class and where in the OperandList they were defined.
399 /// This directly corresponds to the tokenized AsmString after the mnemonic is
401 SmallVector<AsmOperand, 4> AsmOperands;
403 /// Predicates - The required subtarget features to match this instruction.
404 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
406 /// ConversionFnKind - The enum value which is passed to the generated
407 /// ConvertToMCInst to convert parsed operands into an MCInst for this
409 std::string ConversionFnKind;
411 MatchableInfo(const CodeGenInstruction &CGI)
412 : AsmVariantID(0), TheDef(CGI.TheDef), DefRec(&CGI),
413 AsmString(CGI.AsmString) {
416 MatchableInfo(const CodeGenInstAlias *Alias)
417 : AsmVariantID(0), TheDef(Alias->TheDef), DefRec(Alias),
418 AsmString(Alias->AsmString) {
421 void Initialize(const AsmMatcherInfo &Info,
422 SmallPtrSet<Record*, 16> &SingletonRegisters,
423 int AsmVariantNo, std::string &RegisterPrefix);
425 /// Validate - Return true if this matchable is a valid thing to match against
426 /// and perform a bunch of validity checking.
427 bool Validate(StringRef CommentDelimiter, bool Hack) const;
429 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
430 /// if present, from specified token.
432 extractSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info,
433 std::string &RegisterPrefix);
435 /// FindAsmOperand - Find the AsmOperand with the specified name and
436 /// suboperand index.
437 int FindAsmOperand(StringRef N, int SubOpIdx) const {
438 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
439 if (N == AsmOperands[i].SrcOpName &&
440 SubOpIdx == AsmOperands[i].SubOpIdx)
445 /// FindAsmOperandNamed - Find the first AsmOperand with the specified name.
446 /// This does not check the suboperand index.
447 int FindAsmOperandNamed(StringRef N) const {
448 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
449 if (N == AsmOperands[i].SrcOpName)
454 void BuildInstructionResultOperands();
455 void BuildAliasResultOperands();
457 /// operator< - Compare two matchables.
458 bool operator<(const MatchableInfo &RHS) const {
459 // The primary comparator is the instruction mnemonic.
460 if (Mnemonic != RHS.Mnemonic)
461 return Mnemonic < RHS.Mnemonic;
463 if (AsmOperands.size() != RHS.AsmOperands.size())
464 return AsmOperands.size() < RHS.AsmOperands.size();
466 // Compare lexicographically by operand. The matcher validates that other
467 // orderings wouldn't be ambiguous using \see CouldMatchAmbiguouslyWith().
468 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
469 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
471 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
478 /// CouldMatchAmbiguouslyWith - Check whether this matchable could
479 /// ambiguously match the same set of operands as \arg RHS (without being a
480 /// strictly superior match).
481 bool CouldMatchAmbiguouslyWith(const MatchableInfo &RHS) {
482 // The primary comparator is the instruction mnemonic.
483 if (Mnemonic != RHS.Mnemonic)
486 // The number of operands is unambiguous.
487 if (AsmOperands.size() != RHS.AsmOperands.size())
490 // Otherwise, make sure the ordering of the two instructions is unambiguous
491 // by checking that either (a) a token or operand kind discriminates them,
492 // or (b) the ordering among equivalent kinds is consistent.
494 // Tokens and operand kinds are unambiguous (assuming a correct target
496 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
497 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
498 AsmOperands[i].Class->Kind == ClassInfo::Token)
499 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
500 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
503 // Otherwise, this operand could commute if all operands are equivalent, or
504 // there is a pair of operands that compare less than and a pair that
505 // compare greater than.
506 bool HasLT = false, HasGT = false;
507 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
508 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
510 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
514 return !(HasLT ^ HasGT);
520 void TokenizeAsmString(const AsmMatcherInfo &Info);
523 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
524 /// feature which participates in instruction matching.
525 struct SubtargetFeatureInfo {
526 /// \brief The predicate record for this feature.
529 /// \brief An unique index assigned to represent this feature.
532 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
534 /// \brief The name of the enumerated constant identifying this feature.
535 std::string getEnumName() const {
536 return "Feature_" + TheDef->getName();
540 struct OperandMatchEntry {
541 unsigned OperandMask;
545 static OperandMatchEntry Create(MatchableInfo* mi, ClassInfo *ci,
548 X.OperandMask = opMask;
556 class AsmMatcherInfo {
559 RecordKeeper &Records;
561 /// The tablegen AsmParser record.
564 /// Target - The target information.
565 CodeGenTarget &Target;
567 /// The classes which are needed for matching.
568 std::vector<ClassInfo*> Classes;
570 /// The information on the matchables to match.
571 std::vector<MatchableInfo*> Matchables;
573 /// Info for custom matching operands by user defined methods.
574 std::vector<OperandMatchEntry> OperandMatchInfo;
576 /// Map of Register records to their class information.
577 std::map<Record*, ClassInfo*> RegisterClasses;
579 /// Map of Predicate records to their subtarget information.
580 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
583 /// Map of token to class information which has already been constructed.
584 std::map<std::string, ClassInfo*> TokenClasses;
586 /// Map of RegisterClass records to their class information.
587 std::map<Record*, ClassInfo*> RegisterClassClasses;
589 /// Map of AsmOperandClass records to their class information.
590 std::map<Record*, ClassInfo*> AsmOperandClasses;
593 /// getTokenClass - Lookup or create the class for the given token.
594 ClassInfo *getTokenClass(StringRef Token);
596 /// getOperandClass - Lookup or create the class for the given operand.
597 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
599 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
601 /// BuildRegisterClasses - Build the ClassInfo* instances for register
603 void BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
605 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
607 void BuildOperandClasses();
609 void BuildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
611 void BuildAliasOperandReference(MatchableInfo *II, StringRef OpName,
612 MatchableInfo::AsmOperand &Op);
615 AsmMatcherInfo(Record *AsmParser,
616 CodeGenTarget &Target,
617 RecordKeeper &Records);
619 /// BuildInfo - Construct the various tables used during matching.
622 /// BuildOperandMatchInfo - Build the necessary information to handle user
623 /// defined operand parsing methods.
624 void BuildOperandMatchInfo();
626 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
628 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
629 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
630 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
631 SubtargetFeatures.find(Def);
632 return I == SubtargetFeatures.end() ? 0 : I->second;
635 RecordKeeper &getRecords() const {
642 void MatchableInfo::dump() {
643 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
645 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
646 AsmOperand &Op = AsmOperands[i];
647 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
648 errs() << '\"' << Op.Token << "\"\n";
652 void MatchableInfo::Initialize(const AsmMatcherInfo &Info,
653 SmallPtrSet<Record*, 16> &SingletonRegisters,
654 int AsmVariantNo, std::string &RegisterPrefix) {
655 AsmVariantID = AsmVariantNo;
657 CodeGenInstruction::FlattenAsmStringVariants(AsmString, AsmVariantNo);
659 TokenizeAsmString(Info);
661 // Compute the require features.
662 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates");
663 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
664 if (SubtargetFeatureInfo *Feature =
665 Info.getSubtargetFeature(Predicates[i]))
666 RequiredFeatures.push_back(Feature);
668 // Collect singleton registers, if used.
669 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
670 extractSingletonRegisterForAsmOperand(i, Info, RegisterPrefix);
671 if (Record *Reg = AsmOperands[i].SingletonReg)
672 SingletonRegisters.insert(Reg);
676 /// TokenizeAsmString - Tokenize a simplified assembly string.
677 void MatchableInfo::TokenizeAsmString(const AsmMatcherInfo &Info) {
678 StringRef String = AsmString;
681 for (unsigned i = 0, e = String.size(); i != e; ++i) {
691 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
694 if (!isspace(String[i]) && String[i] != ',')
695 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
701 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
705 assert(i != String.size() && "Invalid quoted character");
706 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
712 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
716 // If this isn't "${", treat like a normal token.
717 if (i + 1 == String.size() || String[i + 1] != '{') {
722 StringRef::iterator End = std::find(String.begin() + i, String.end(),'}');
723 assert(End != String.end() && "Missing brace in operand reference!");
724 size_t EndPos = End - String.begin();
725 AsmOperands.push_back(AsmOperand(String.slice(i, EndPos+1)));
733 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
742 if (InTok && Prev != String.size())
743 AsmOperands.push_back(AsmOperand(String.substr(Prev)));
745 // The first token of the instruction is the mnemonic, which must be a
746 // simple string, not a $foo variable or a singleton register.
747 if (AsmOperands.empty())
748 throw TGError(TheDef->getLoc(),
749 "Instruction '" + TheDef->getName() + "' has no tokens");
750 Mnemonic = AsmOperands[0].Token;
751 // FIXME : Check and raise an error if it is a register.
752 if (Mnemonic[0] == '$')
753 throw TGError(TheDef->getLoc(),
754 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
756 // Remove the first operand, it is tracked in the mnemonic field.
757 AsmOperands.erase(AsmOperands.begin());
760 bool MatchableInfo::Validate(StringRef CommentDelimiter, bool Hack) const {
761 // Reject matchables with no .s string.
762 if (AsmString.empty())
763 throw TGError(TheDef->getLoc(), "instruction with empty asm string");
765 // Reject any matchables with a newline in them, they should be marked
766 // isCodeGenOnly if they are pseudo instructions.
767 if (AsmString.find('\n') != std::string::npos)
768 throw TGError(TheDef->getLoc(),
769 "multiline instruction is not valid for the asmparser, "
770 "mark it isCodeGenOnly");
772 // Remove comments from the asm string. We know that the asmstring only
774 if (!CommentDelimiter.empty() &&
775 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
776 throw TGError(TheDef->getLoc(),
777 "asmstring for instruction has comment character in it, "
778 "mark it isCodeGenOnly");
780 // Reject matchables with operand modifiers, these aren't something we can
781 // handle, the target should be refactored to use operands instead of
784 // Also, check for instructions which reference the operand multiple times;
785 // this implies a constraint we would not honor.
786 std::set<std::string> OperandNames;
787 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
788 StringRef Tok = AsmOperands[i].Token;
789 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
790 throw TGError(TheDef->getLoc(),
791 "matchable with operand modifier '" + Tok.str() +
792 "' not supported by asm matcher. Mark isCodeGenOnly!");
794 // Verify that any operand is only mentioned once.
795 // We reject aliases and ignore instructions for now.
796 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
798 throw TGError(TheDef->getLoc(),
799 "ERROR: matchable with tied operand '" + Tok.str() +
800 "' can never be matched!");
801 // FIXME: Should reject these. The ARM backend hits this with $lane in a
802 // bunch of instructions. It is unclear what the right answer is.
804 errs() << "warning: '" << TheDef->getName() << "': "
805 << "ignoring instruction with tied operand '"
806 << Tok.str() << "'\n";
815 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
816 /// if present, from specified token.
818 extractSingletonRegisterForAsmOperand(unsigned OperandNo,
819 const AsmMatcherInfo &Info,
820 std::string &RegisterPrefix) {
821 StringRef Tok = AsmOperands[OperandNo].Token;
822 if (RegisterPrefix.empty()) {
823 std::string LoweredTok = Tok.lower();
824 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
825 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
829 if (!Tok.startswith(RegisterPrefix))
832 StringRef RegName = Tok.substr(RegisterPrefix.size());
833 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
834 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
836 // If there is no register prefix (i.e. "%" in "%eax"), then this may
837 // be some random non-register token, just ignore it.
841 static std::string getEnumNameForToken(StringRef Str) {
844 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
846 case '*': Res += "_STAR_"; break;
847 case '%': Res += "_PCT_"; break;
848 case ':': Res += "_COLON_"; break;
849 case '!': Res += "_EXCLAIM_"; break;
850 case '.': Res += "_DOT_"; break;
855 Res += "_" + utostr((unsigned) *it) + "_";
862 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
863 ClassInfo *&Entry = TokenClasses[Token];
866 Entry = new ClassInfo();
867 Entry->Kind = ClassInfo::Token;
868 Entry->ClassName = "Token";
869 Entry->Name = "MCK_" + getEnumNameForToken(Token);
870 Entry->ValueName = Token;
871 Entry->PredicateMethod = "<invalid>";
872 Entry->RenderMethod = "<invalid>";
873 Entry->ParserMethod = "";
874 Classes.push_back(Entry);
881 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
883 Record *Rec = OI.Rec;
885 Rec = dynamic_cast<DefInit*>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
886 return getOperandClass(Rec, SubOpIdx);
890 AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
891 if (Rec->isSubClassOf("RegisterOperand")) {
892 // RegisterOperand may have an associated ParserMatchClass. If it does,
893 // use it, else just fall back to the underlying register class.
894 const RecordVal *R = Rec->getValue("ParserMatchClass");
895 if (R == 0 || R->getValue() == 0)
896 throw "Record `" + Rec->getName() +
897 "' does not have a ParserMatchClass!\n";
899 if (DefInit *DI= dynamic_cast<DefInit*>(R->getValue())) {
900 Record *MatchClass = DI->getDef();
901 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
905 // No custom match class. Just use the register class.
906 Record *ClassRec = Rec->getValueAsDef("RegClass");
908 throw TGError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
909 "' has no associated register class!\n");
910 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
912 throw TGError(Rec->getLoc(), "register class has no class info!");
916 if (Rec->isSubClassOf("RegisterClass")) {
917 if (ClassInfo *CI = RegisterClassClasses[Rec])
919 throw TGError(Rec->getLoc(), "register class has no class info!");
922 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
923 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
924 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
927 throw TGError(Rec->getLoc(), "operand has no match class!");
930 void AsmMatcherInfo::
931 BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
932 const std::vector<CodeGenRegister*> &Registers =
933 Target.getRegBank().getRegisters();
934 ArrayRef<CodeGenRegisterClass*> RegClassList =
935 Target.getRegBank().getRegClasses();
937 // The register sets used for matching.
938 std::set< std::set<Record*> > RegisterSets;
940 // Gather the defined sets.
941 for (ArrayRef<CodeGenRegisterClass*>::const_iterator it =
942 RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it)
943 RegisterSets.insert(std::set<Record*>(
944 (*it)->getOrder().begin(), (*it)->getOrder().end()));
946 // Add any required singleton sets.
947 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
948 ie = SingletonRegisters.end(); it != ie; ++it) {
950 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
953 // Introduce derived sets where necessary (when a register does not determine
954 // a unique register set class), and build the mapping of registers to the set
955 // they should classify to.
956 std::map<Record*, std::set<Record*> > RegisterMap;
957 for (std::vector<CodeGenRegister*>::const_iterator it = Registers.begin(),
958 ie = Registers.end(); it != ie; ++it) {
959 const CodeGenRegister &CGR = **it;
960 // Compute the intersection of all sets containing this register.
961 std::set<Record*> ContainingSet;
963 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
964 ie = RegisterSets.end(); it != ie; ++it) {
965 if (!it->count(CGR.TheDef))
968 if (ContainingSet.empty()) {
973 std::set<Record*> Tmp;
974 std::swap(Tmp, ContainingSet);
975 std::insert_iterator< std::set<Record*> > II(ContainingSet,
976 ContainingSet.begin());
977 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(), II);
980 if (!ContainingSet.empty()) {
981 RegisterSets.insert(ContainingSet);
982 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
986 // Construct the register classes.
987 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
989 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
990 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
991 ClassInfo *CI = new ClassInfo();
992 CI->Kind = ClassInfo::RegisterClass0 + Index;
993 CI->ClassName = "Reg" + utostr(Index);
994 CI->Name = "MCK_Reg" + utostr(Index);
996 CI->PredicateMethod = ""; // unused
997 CI->RenderMethod = "addRegOperands";
999 Classes.push_back(CI);
1000 RegisterSetClasses.insert(std::make_pair(*it, CI));
1003 // Find the superclasses; we could compute only the subgroup lattice edges,
1004 // but there isn't really a point.
1005 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
1006 ie = RegisterSets.end(); it != ie; ++it) {
1007 ClassInfo *CI = RegisterSetClasses[*it];
1008 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
1009 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
1011 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
1012 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
1015 // Name the register classes which correspond to a user defined RegisterClass.
1016 for (ArrayRef<CodeGenRegisterClass*>::const_iterator
1017 it = RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) {
1018 const CodeGenRegisterClass &RC = **it;
1019 // Def will be NULL for non-user defined register classes.
1020 Record *Def = RC.getDef();
1023 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(RC.getOrder().begin(),
1024 RC.getOrder().end())];
1025 if (CI->ValueName.empty()) {
1026 CI->ClassName = RC.getName();
1027 CI->Name = "MCK_" + RC.getName();
1028 CI->ValueName = RC.getName();
1030 CI->ValueName = CI->ValueName + "," + RC.getName();
1032 RegisterClassClasses.insert(std::make_pair(Def, CI));
1035 // Populate the map for individual registers.
1036 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
1037 ie = RegisterMap.end(); it != ie; ++it)
1038 RegisterClasses[it->first] = RegisterSetClasses[it->second];
1040 // Name the register classes which correspond to singleton registers.
1041 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1042 ie = SingletonRegisters.end(); it != ie; ++it) {
1044 ClassInfo *CI = RegisterClasses[Rec];
1045 assert(CI && "Missing singleton register class info!");
1047 if (CI->ValueName.empty()) {
1048 CI->ClassName = Rec->getName();
1049 CI->Name = "MCK_" + Rec->getName();
1050 CI->ValueName = Rec->getName();
1052 CI->ValueName = CI->ValueName + "," + Rec->getName();
1056 void AsmMatcherInfo::BuildOperandClasses() {
1057 std::vector<Record*> AsmOperands =
1058 Records.getAllDerivedDefinitions("AsmOperandClass");
1060 // Pre-populate AsmOperandClasses map.
1061 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1062 ie = AsmOperands.end(); it != ie; ++it)
1063 AsmOperandClasses[*it] = new ClassInfo();
1066 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1067 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
1068 ClassInfo *CI = AsmOperandClasses[*it];
1069 CI->Kind = ClassInfo::UserClass0 + Index;
1071 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
1072 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
1073 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
1075 PrintError((*it)->getLoc(), "Invalid super class reference!");
1079 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1081 PrintError((*it)->getLoc(), "Invalid super class reference!");
1083 CI->SuperClasses.push_back(SC);
1085 CI->ClassName = (*it)->getValueAsString("Name");
1086 CI->Name = "MCK_" + CI->ClassName;
1087 CI->ValueName = (*it)->getName();
1089 // Get or construct the predicate method name.
1090 Init *PMName = (*it)->getValueInit("PredicateMethod");
1091 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
1092 CI->PredicateMethod = SI->getValue();
1094 assert(dynamic_cast<UnsetInit*>(PMName) &&
1095 "Unexpected PredicateMethod field!");
1096 CI->PredicateMethod = "is" + CI->ClassName;
1099 // Get or construct the render method name.
1100 Init *RMName = (*it)->getValueInit("RenderMethod");
1101 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
1102 CI->RenderMethod = SI->getValue();
1104 assert(dynamic_cast<UnsetInit*>(RMName) &&
1105 "Unexpected RenderMethod field!");
1106 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1109 // Get the parse method name or leave it as empty.
1110 Init *PRMName = (*it)->getValueInit("ParserMethod");
1111 if (StringInit *SI = dynamic_cast<StringInit*>(PRMName))
1112 CI->ParserMethod = SI->getValue();
1114 AsmOperandClasses[*it] = CI;
1115 Classes.push_back(CI);
1119 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1120 CodeGenTarget &target,
1121 RecordKeeper &records)
1122 : Records(records), AsmParser(asmParser), Target(target) {
1125 /// BuildOperandMatchInfo - Build the necessary information to handle user
1126 /// defined operand parsing methods.
1127 void AsmMatcherInfo::BuildOperandMatchInfo() {
1129 /// Map containing a mask with all operands indicies that can be found for
1130 /// that class inside a instruction.
1131 std::map<ClassInfo*, unsigned> OpClassMask;
1133 for (std::vector<MatchableInfo*>::const_iterator it =
1134 Matchables.begin(), ie = Matchables.end();
1136 MatchableInfo &II = **it;
1137 OpClassMask.clear();
1139 // Keep track of all operands of this instructions which belong to the
1141 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
1142 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
1143 if (Op.Class->ParserMethod.empty())
1145 unsigned &OperandMask = OpClassMask[Op.Class];
1146 OperandMask |= (1 << i);
1149 // Generate operand match info for each mnemonic/operand class pair.
1150 for (std::map<ClassInfo*, unsigned>::iterator iit = OpClassMask.begin(),
1151 iie = OpClassMask.end(); iit != iie; ++iit) {
1152 unsigned OpMask = iit->second;
1153 ClassInfo *CI = iit->first;
1154 OperandMatchInfo.push_back(OperandMatchEntry::Create(&II, CI, OpMask));
1159 void AsmMatcherInfo::BuildInfo() {
1160 // Build information about all of the AssemblerPredicates.
1161 std::vector<Record*> AllPredicates =
1162 Records.getAllDerivedDefinitions("Predicate");
1163 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
1164 Record *Pred = AllPredicates[i];
1165 // Ignore predicates that are not intended for the assembler.
1166 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
1169 if (Pred->getName().empty())
1170 throw TGError(Pred->getLoc(), "Predicate has no name!");
1172 unsigned FeatureNo = SubtargetFeatures.size();
1173 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
1174 assert(FeatureNo < 32 && "Too many subtarget features!");
1177 // Parse the instructions; we need to do this first so that we can gather the
1178 // singleton register classes.
1179 SmallPtrSet<Record*, 16> SingletonRegisters;
1180 unsigned VariantCount = Target.getAsmParserVariantCount();
1181 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1182 Record *AsmVariant = Target.getAsmParserVariant(VC);
1183 std::string CommentDelimiter = AsmVariant->getValueAsString("CommentDelimiter");
1184 std::string RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
1185 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
1187 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
1188 E = Target.inst_end(); I != E; ++I) {
1189 const CodeGenInstruction &CGI = **I;
1191 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1192 // filter the set of instructions we consider.
1193 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
1196 // Ignore "codegen only" instructions.
1197 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
1200 // Validate the operand list to ensure we can handle this instruction.
1201 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1202 const CGIOperandList::OperandInfo &OI = CGI.Operands[i];
1204 // Validate tied operands.
1205 if (OI.getTiedRegister() != -1) {
1206 // If we have a tied operand that consists of multiple MCOperands,
1207 // reject it. We reject aliases and ignore instructions for now.
1208 if (OI.MINumOperands != 1) {
1209 // FIXME: Should reject these. The ARM backend hits this with $lane
1210 // in a bunch of instructions. It is unclear what the right answer is.
1212 errs() << "warning: '" << CGI.TheDef->getName() << "': "
1213 << "ignoring instruction with multi-operand tied operand '"
1214 << OI.Name << "'\n";
1221 OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
1223 II->Initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
1225 // Ignore instructions which shouldn't be matched and diagnose invalid
1226 // instruction definitions with an error.
1227 if (!II->Validate(CommentDelimiter, true))
1230 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
1232 // FIXME: This is a total hack.
1233 if (StringRef(II->TheDef->getName()).startswith("Int_") ||
1234 StringRef(II->TheDef->getName()).endswith("_Int"))
1237 Matchables.push_back(II.take());
1240 // Parse all of the InstAlias definitions and stick them in the list of
1242 std::vector<Record*> AllInstAliases =
1243 Records.getAllDerivedDefinitions("InstAlias");
1244 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
1245 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i], Target);
1247 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1248 // filter the set of instruction aliases we consider, based on the target
1250 if (!StringRef(Alias->ResultInst->TheDef->getName()).startswith(
1254 OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
1256 II->Initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
1258 // Validate the alias definitions.
1259 II->Validate(CommentDelimiter, false);
1261 Matchables.push_back(II.take());
1265 // Build info for the register classes.
1266 BuildRegisterClasses(SingletonRegisters);
1268 // Build info for the user defined assembly operand classes.
1269 BuildOperandClasses();
1271 // Build the information about matchables, now that we have fully formed
1273 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(),
1274 ie = Matchables.end(); it != ie; ++it) {
1275 MatchableInfo *II = *it;
1277 // Parse the tokens after the mnemonic.
1278 // Note: BuildInstructionOperandReference may insert new AsmOperands, so
1279 // don't precompute the loop bound.
1280 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1281 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
1282 StringRef Token = Op.Token;
1284 // Check for singleton registers.
1285 if (Record *RegRecord = II->AsmOperands[i].SingletonReg) {
1286 Op.Class = RegisterClasses[RegRecord];
1287 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1288 "Unexpected class for singleton register");
1292 // Check for simple tokens.
1293 if (Token[0] != '$') {
1294 Op.Class = getTokenClass(Token);
1298 if (Token.size() > 1 && isdigit(Token[1])) {
1299 Op.Class = getTokenClass(Token);
1303 // Otherwise this is an operand reference.
1304 StringRef OperandName;
1305 if (Token[1] == '{')
1306 OperandName = Token.substr(2, Token.size() - 3);
1308 OperandName = Token.substr(1);
1310 if (II->DefRec.is<const CodeGenInstruction*>())
1311 BuildInstructionOperandReference(II, OperandName, i);
1313 BuildAliasOperandReference(II, OperandName, Op);
1316 if (II->DefRec.is<const CodeGenInstruction*>())
1317 II->BuildInstructionResultOperands();
1319 II->BuildAliasResultOperands();
1322 // Process token alias definitions and set up the associated superclass
1324 std::vector<Record*> AllTokenAliases =
1325 Records.getAllDerivedDefinitions("TokenAlias");
1326 for (unsigned i = 0, e = AllTokenAliases.size(); i != e; ++i) {
1327 Record *Rec = AllTokenAliases[i];
1328 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1329 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
1330 FromClass->SuperClasses.push_back(ToClass);
1333 // Reorder classes so that classes precede super classes.
1334 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
1337 /// BuildInstructionOperandReference - The specified operand is a reference to a
1338 /// named operand such as $src. Resolve the Class and OperandInfo pointers.
1339 void AsmMatcherInfo::
1340 BuildInstructionOperandReference(MatchableInfo *II,
1341 StringRef OperandName,
1342 unsigned AsmOpIdx) {
1343 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1344 const CGIOperandList &Operands = CGI.Operands;
1345 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
1347 // Map this token to an operand.
1349 if (!Operands.hasOperandNamed(OperandName, Idx))
1350 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1351 OperandName.str() + "'");
1353 // If the instruction operand has multiple suboperands, but the parser
1354 // match class for the asm operand is still the default "ImmAsmOperand",
1355 // then handle each suboperand separately.
1356 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1357 Record *Rec = Operands[Idx].Rec;
1358 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1359 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1360 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1361 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1362 StringRef Token = Op->Token; // save this in case Op gets moved
1363 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1364 MatchableInfo::AsmOperand NewAsmOp(Token);
1365 NewAsmOp.SubOpIdx = SI;
1366 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1368 // Replace Op with first suboperand.
1369 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1374 // Set up the operand class.
1375 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
1377 // If the named operand is tied, canonicalize it to the untied operand.
1378 // For example, something like:
1379 // (outs GPR:$dst), (ins GPR:$src)
1380 // with an asmstring of
1382 // we want to canonicalize to:
1384 // so that we know how to provide the $dst operand when filling in the result.
1385 int OITied = Operands[Idx].getTiedRegister();
1387 // The tied operand index is an MIOperand index, find the operand that
1389 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1390 OperandName = Operands[Idx.first].Name;
1391 Op->SubOpIdx = Idx.second;
1394 Op->SrcOpName = OperandName;
1397 /// BuildAliasOperandReference - When parsing an operand reference out of the
1398 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1399 /// operand reference is by looking it up in the result pattern definition.
1400 void AsmMatcherInfo::BuildAliasOperandReference(MatchableInfo *II,
1401 StringRef OperandName,
1402 MatchableInfo::AsmOperand &Op) {
1403 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
1405 // Set up the operand class.
1406 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
1407 if (CGA.ResultOperands[i].isRecord() &&
1408 CGA.ResultOperands[i].getName() == OperandName) {
1409 // It's safe to go with the first one we find, because CodeGenInstAlias
1410 // validates that all operands with the same name have the same record.
1411 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
1412 // Use the match class from the Alias definition, not the
1413 // destination instruction, as we may have an immediate that's
1414 // being munged by the match class.
1415 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
1417 Op.SrcOpName = OperandName;
1421 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1422 OperandName.str() + "'");
1425 void MatchableInfo::BuildInstructionResultOperands() {
1426 const CodeGenInstruction *ResultInst = getResultInst();
1428 // Loop over all operands of the result instruction, determining how to
1430 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1431 const CGIOperandList::OperandInfo &OpInfo = ResultInst->Operands[i];
1433 // If this is a tied operand, just copy from the previously handled operand.
1434 int TiedOp = OpInfo.getTiedRegister();
1436 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1440 // Find out what operand from the asmparser this MCInst operand comes from.
1441 int SrcOperand = FindAsmOperandNamed(OpInfo.Name);
1442 if (OpInfo.Name.empty() || SrcOperand == -1)
1443 throw TGError(TheDef->getLoc(), "Instruction '" +
1444 TheDef->getName() + "' has operand '" + OpInfo.Name +
1445 "' that doesn't appear in asm string!");
1447 // Check if the one AsmOperand populates the entire operand.
1448 unsigned NumOperands = OpInfo.MINumOperands;
1449 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1450 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
1454 // Add a separate ResOperand for each suboperand.
1455 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1456 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1457 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1458 "unexpected AsmOperands for suboperands");
1459 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1464 void MatchableInfo::BuildAliasResultOperands() {
1465 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1466 const CodeGenInstruction *ResultInst = getResultInst();
1468 // Loop over all operands of the result instruction, determining how to
1470 unsigned AliasOpNo = 0;
1471 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
1472 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1473 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
1475 // If this is a tied operand, just copy from the previously handled operand.
1476 int TiedOp = OpInfo->getTiedRegister();
1478 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1482 // Handle all the suboperands for this operand.
1483 const std::string &OpName = OpInfo->Name;
1484 for ( ; AliasOpNo < LastOpNo &&
1485 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1486 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1488 // Find out what operand from the asmparser that this MCInst operand
1490 switch (CGA.ResultOperands[AliasOpNo].Kind) {
1491 case CodeGenInstAlias::ResultOperand::K_Record: {
1492 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1493 int SrcOperand = FindAsmOperand(Name, SubIdx);
1494 if (SrcOperand == -1)
1495 throw TGError(TheDef->getLoc(), "Instruction '" +
1496 TheDef->getName() + "' has operand '" + OpName +
1497 "' that doesn't appear in asm string!");
1498 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1499 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1503 case CodeGenInstAlias::ResultOperand::K_Imm: {
1504 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1505 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1508 case CodeGenInstAlias::ResultOperand::K_Reg: {
1509 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1510 ResOperands.push_back(ResOperand::getRegOp(Reg));
1518 static void EmitConvertToMCInst(CodeGenTarget &Target, StringRef ClassName,
1519 std::vector<MatchableInfo*> &Infos,
1521 // Write the convert function to a separate stream, so we can drop it after
1523 std::string ConvertFnBody;
1524 raw_string_ostream CvtOS(ConvertFnBody);
1526 // Function we have already generated.
1527 std::set<std::string> GeneratedFns;
1529 // Start the unified conversion function.
1530 CvtOS << "bool " << Target.getName() << ClassName << "::\n";
1531 CvtOS << "ConvertToMCInst(unsigned Kind, MCInst &Inst, "
1532 << "unsigned Opcode,\n"
1533 << " const SmallVectorImpl<MCParsedAsmOperand*"
1534 << "> &Operands) {\n";
1535 CvtOS << " Inst.setOpcode(Opcode);\n";
1536 CvtOS << " switch (Kind) {\n";
1537 CvtOS << " default:\n";
1539 // Start the enum, which we will generate inline.
1541 OS << "// Unified function for converting operands to MCInst instances.\n\n";
1542 OS << "enum ConversionKind {\n";
1544 // TargetOperandClass - This is the target's operand class, like X86Operand.
1545 std::string TargetOperandClass = Target.getName() + "Operand";
1547 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(),
1548 ie = Infos.end(); it != ie; ++it) {
1549 MatchableInfo &II = **it;
1551 // Check if we have a custom match function.
1552 std::string AsmMatchConverter =
1553 II.getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
1554 if (!AsmMatchConverter.empty()) {
1555 std::string Signature = "ConvertCustom_" + AsmMatchConverter;
1556 II.ConversionFnKind = Signature;
1558 // Check if we have already generated this signature.
1559 if (!GeneratedFns.insert(Signature).second)
1562 // If not, emit it now. Add to the enum list.
1563 OS << " " << Signature << ",\n";
1565 CvtOS << " case " << Signature << ":\n";
1566 CvtOS << " return " << AsmMatchConverter
1567 << "(Inst, Opcode, Operands);\n";
1571 // Build the conversion function signature.
1572 std::string Signature = "Convert";
1573 std::string CaseBody;
1574 raw_string_ostream CaseOS(CaseBody);
1576 // Compute the convert enum and the case body.
1577 for (unsigned i = 0, e = II.ResOperands.size(); i != e; ++i) {
1578 const MatchableInfo::ResOperand &OpInfo = II.ResOperands[i];
1580 // Generate code to populate each result operand.
1581 switch (OpInfo.Kind) {
1582 case MatchableInfo::ResOperand::RenderAsmOperand: {
1583 // This comes from something we parsed.
1584 MatchableInfo::AsmOperand &Op = II.AsmOperands[OpInfo.AsmOperandNum];
1586 // Registers are always converted the same, don't duplicate the
1587 // conversion function based on them.
1589 if (Op.Class->isRegisterClass())
1592 Signature += Op.Class->ClassName;
1593 Signature += utostr(OpInfo.MINumOperands);
1594 Signature += "_" + itostr(OpInfo.AsmOperandNum);
1596 CaseOS << " ((" << TargetOperandClass << "*)Operands["
1597 << (OpInfo.AsmOperandNum+1) << "])->" << Op.Class->RenderMethod
1598 << "(Inst, " << OpInfo.MINumOperands << ");\n";
1602 case MatchableInfo::ResOperand::TiedOperand: {
1603 // If this operand is tied to a previous one, just copy the MCInst
1604 // operand from the earlier one.We can only tie single MCOperand values.
1605 //assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
1606 unsigned TiedOp = OpInfo.TiedOperandNum;
1607 assert(i > TiedOp && "Tied operand precedes its target!");
1608 CaseOS << " Inst.addOperand(Inst.getOperand(" << TiedOp << "));\n";
1609 Signature += "__Tie" + utostr(TiedOp);
1612 case MatchableInfo::ResOperand::ImmOperand: {
1613 int64_t Val = OpInfo.ImmVal;
1614 CaseOS << " Inst.addOperand(MCOperand::CreateImm(" << Val << "));\n";
1615 Signature += "__imm" + itostr(Val);
1618 case MatchableInfo::ResOperand::RegOperand: {
1619 if (OpInfo.Register == 0) {
1620 CaseOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1621 Signature += "__reg0";
1623 std::string N = getQualifiedName(OpInfo.Register);
1624 CaseOS << " Inst.addOperand(MCOperand::CreateReg(" << N << "));\n";
1625 Signature += "__reg" + OpInfo.Register->getName();
1631 II.ConversionFnKind = Signature;
1633 // Check if we have already generated this signature.
1634 if (!GeneratedFns.insert(Signature).second)
1637 // If not, emit it now. Add to the enum list.
1638 OS << " " << Signature << ",\n";
1640 CvtOS << " case " << Signature << ":\n";
1641 CvtOS << CaseOS.str();
1642 CvtOS << " return true;\n";
1645 // Finish the convert function.
1648 CvtOS << " return false;\n";
1651 // Finish the enum, and drop the convert function after it.
1653 OS << " NumConversionVariants\n";
1659 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1660 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1661 std::vector<ClassInfo*> &Infos,
1663 OS << "namespace {\n\n";
1665 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1666 << "/// instruction matching.\n";
1667 OS << "enum MatchClassKind {\n";
1668 OS << " InvalidMatchClass = 0,\n";
1669 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1670 ie = Infos.end(); it != ie; ++it) {
1671 ClassInfo &CI = **it;
1672 OS << " " << CI.Name << ", // ";
1673 if (CI.Kind == ClassInfo::Token) {
1674 OS << "'" << CI.ValueName << "'\n";
1675 } else if (CI.isRegisterClass()) {
1676 if (!CI.ValueName.empty())
1677 OS << "register class '" << CI.ValueName << "'\n";
1679 OS << "derived register class\n";
1681 OS << "user defined class '" << CI.ValueName << "'\n";
1684 OS << " NumMatchClassKinds\n";
1690 /// EmitValidateOperandClass - Emit the function to validate an operand class.
1691 static void EmitValidateOperandClass(AsmMatcherInfo &Info,
1693 OS << "static bool validateOperandClass(MCParsedAsmOperand *GOp, "
1694 << "MatchClassKind Kind) {\n";
1695 OS << " " << Info.Target.getName() << "Operand &Operand = *("
1696 << Info.Target.getName() << "Operand*)GOp;\n";
1698 // The InvalidMatchClass is not to match any operand.
1699 OS << " if (Kind == InvalidMatchClass)\n";
1700 OS << " return false;\n\n";
1702 // Check for Token operands first.
1703 OS << " if (Operand.isToken())\n";
1704 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind);"
1707 // Check for register operands, including sub-classes.
1708 OS << " if (Operand.isReg()) {\n";
1709 OS << " MatchClassKind OpKind;\n";
1710 OS << " switch (Operand.getReg()) {\n";
1711 OS << " default: OpKind = InvalidMatchClass; break;\n";
1712 for (std::map<Record*, ClassInfo*>::iterator
1713 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1715 OS << " case " << Info.Target.getName() << "::"
1716 << it->first->getName() << ": OpKind = " << it->second->Name
1719 OS << " return isSubclass(OpKind, Kind);\n";
1722 // Check the user classes. We don't care what order since we're only
1723 // actually matching against one of them.
1724 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1725 ie = Info.Classes.end(); it != ie; ++it) {
1726 ClassInfo &CI = **it;
1728 if (!CI.isUserClass())
1731 OS << " // '" << CI.ClassName << "' class\n";
1732 OS << " if (Kind == " << CI.Name
1733 << " && Operand." << CI.PredicateMethod << "()) {\n";
1734 OS << " return true;\n";
1738 OS << " return false;\n";
1742 /// EmitIsSubclass - Emit the subclass predicate function.
1743 static void EmitIsSubclass(CodeGenTarget &Target,
1744 std::vector<ClassInfo*> &Infos,
1746 OS << "/// isSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1747 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
1748 OS << " if (A == B)\n";
1749 OS << " return true;\n\n";
1751 OS << " switch (A) {\n";
1752 OS << " default:\n";
1753 OS << " return false;\n";
1754 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1755 ie = Infos.end(); it != ie; ++it) {
1756 ClassInfo &A = **it;
1758 std::vector<StringRef> SuperClasses;
1759 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1760 ie = Infos.end(); it != ie; ++it) {
1761 ClassInfo &B = **it;
1763 if (&A != &B && A.isSubsetOf(B))
1764 SuperClasses.push_back(B.Name);
1767 if (SuperClasses.empty())
1770 OS << "\n case " << A.Name << ":\n";
1772 if (SuperClasses.size() == 1) {
1773 OS << " return B == " << SuperClasses.back() << ";\n";
1777 OS << " switch (B) {\n";
1778 OS << " default: return false;\n";
1779 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1780 OS << " case " << SuperClasses[i] << ": return true;\n";
1787 /// EmitMatchTokenString - Emit the function to match a token string to the
1788 /// appropriate match class value.
1789 static void EmitMatchTokenString(CodeGenTarget &Target,
1790 std::vector<ClassInfo*> &Infos,
1792 // Construct the match list.
1793 std::vector<StringMatcher::StringPair> Matches;
1794 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1795 ie = Infos.end(); it != ie; ++it) {
1796 ClassInfo &CI = **it;
1798 if (CI.Kind == ClassInfo::Token)
1799 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1800 "return " + CI.Name + ";"));
1803 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
1805 StringMatcher("Name", Matches, OS).Emit();
1807 OS << " return InvalidMatchClass;\n";
1811 /// EmitMatchRegisterName - Emit the function to match a string to the target
1812 /// specific register enum.
1813 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1815 // Construct the match list.
1816 std::vector<StringMatcher::StringPair> Matches;
1817 const std::vector<CodeGenRegister*> &Regs =
1818 Target.getRegBank().getRegisters();
1819 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1820 const CodeGenRegister *Reg = Regs[i];
1821 if (Reg->TheDef->getValueAsString("AsmName").empty())
1824 Matches.push_back(StringMatcher::StringPair(
1825 Reg->TheDef->getValueAsString("AsmName"),
1826 "return " + utostr(Reg->EnumValue) + ";"));
1829 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
1831 StringMatcher("Name", Matches, OS).Emit();
1833 OS << " return 0;\n";
1837 /// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1839 static void EmitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
1841 OS << "// Flags for subtarget features that participate in "
1842 << "instruction matching.\n";
1843 OS << "enum SubtargetFeatureFlag {\n";
1844 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1845 it = Info.SubtargetFeatures.begin(),
1846 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1847 SubtargetFeatureInfo &SFI = *it->second;
1848 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
1850 OS << " Feature_None = 0\n";
1854 /// EmitComputeAvailableFeatures - Emit the function to compute the list of
1855 /// available features given a subtarget.
1856 static void EmitComputeAvailableFeatures(AsmMatcherInfo &Info,
1858 std::string ClassName =
1859 Info.AsmParser->getValueAsString("AsmParserClassName");
1861 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
1862 << "ComputeAvailableFeatures(uint64_t FB) const {\n";
1863 OS << " unsigned Features = 0;\n";
1864 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1865 it = Info.SubtargetFeatures.begin(),
1866 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1867 SubtargetFeatureInfo &SFI = *it->second;
1870 std::string CondStorage = SFI.TheDef->getValueAsString("AssemblerCondString");
1871 StringRef Conds = CondStorage;
1872 std::pair<StringRef,StringRef> Comma = Conds.split(',');
1879 StringRef Cond = Comma.first;
1880 if (Cond[0] == '!') {
1882 Cond = Cond.substr(1);
1885 OS << "((FB & " << Info.Target.getName() << "::" << Cond << ")";
1892 if (Comma.second.empty())
1896 Comma = Comma.second.split(',');
1900 OS << " Features |= " << SFI.getEnumName() << ";\n";
1902 OS << " return Features;\n";
1906 static std::string GetAliasRequiredFeatures(Record *R,
1907 const AsmMatcherInfo &Info) {
1908 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
1910 unsigned NumFeatures = 0;
1911 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
1912 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
1915 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
1916 "' is not marked as an AssemblerPredicate!");
1921 Result += F->getEnumName();
1925 if (NumFeatures > 1)
1926 Result = '(' + Result + ')';
1930 /// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
1931 /// emit a function for them and return true, otherwise return false.
1932 static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
1933 // Ignore aliases when match-prefix is set.
1934 if (!MatchPrefix.empty())
1937 std::vector<Record*> Aliases =
1938 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
1939 if (Aliases.empty()) return false;
1941 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
1942 "unsigned Features) {\n";
1944 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
1945 // iteration order of the map is stable.
1946 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1948 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1949 Record *R = Aliases[i];
1950 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
1953 // Process each alias a "from" mnemonic at a time, building the code executed
1954 // by the string remapper.
1955 std::vector<StringMatcher::StringPair> Cases;
1956 for (std::map<std::string, std::vector<Record*> >::iterator
1957 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1959 const std::vector<Record*> &ToVec = I->second;
1961 // Loop through each alias and emit code that handles each case. If there
1962 // are two instructions without predicates, emit an error. If there is one,
1964 std::string MatchCode;
1965 int AliasWithNoPredicate = -1;
1967 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1968 Record *R = ToVec[i];
1969 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
1971 // If this unconditionally matches, remember it for later and diagnose
1973 if (FeatureMask.empty()) {
1974 if (AliasWithNoPredicate != -1) {
1975 // We can't have two aliases from the same mnemonic with no predicate.
1976 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1977 "two MnemonicAliases with the same 'from' mnemonic!");
1978 throw TGError(R->getLoc(), "this is the other MnemonicAlias.");
1981 AliasWithNoPredicate = i;
1984 if (R->getValueAsString("ToMnemonic") == I->first)
1985 throw TGError(R->getLoc(), "MnemonicAlias to the same string");
1987 if (!MatchCode.empty())
1988 MatchCode += "else ";
1989 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1990 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
1993 if (AliasWithNoPredicate != -1) {
1994 Record *R = ToVec[AliasWithNoPredicate];
1995 if (!MatchCode.empty())
1996 MatchCode += "else\n ";
1997 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
2000 MatchCode += "return;";
2002 Cases.push_back(std::make_pair(I->first, MatchCode));
2005 StringMatcher("Mnemonic", Cases, OS).Emit();
2011 static const char *getMinimalTypeForRange(uint64_t Range) {
2012 assert(Range < 0xFFFFFFFFULL && "Enum too large");
2020 static void EmitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
2021 const AsmMatcherInfo &Info, StringRef ClassName) {
2022 // Emit the static custom operand parsing table;
2023 OS << "namespace {\n";
2024 OS << " struct OperandMatchEntry {\n";
2025 OS << " const char *Mnemonic;\n";
2026 OS << " unsigned OperandMask;\n";
2027 OS << " MatchClassKind Class;\n";
2028 OS << " unsigned RequiredFeatures;\n";
2031 OS << " // Predicate for searching for an opcode.\n";
2032 OS << " struct LessOpcodeOperand {\n";
2033 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
2034 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
2036 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
2037 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
2039 OS << " bool operator()(const OperandMatchEntry &LHS,";
2040 OS << " const OperandMatchEntry &RHS) {\n";
2041 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
2045 OS << "} // end anonymous namespace.\n\n";
2047 OS << "static const OperandMatchEntry OperandMatchTable["
2048 << Info.OperandMatchInfo.size() << "] = {\n";
2050 OS << " /* Mnemonic, Operand List Mask, Operand Class, Features */\n";
2051 for (std::vector<OperandMatchEntry>::const_iterator it =
2052 Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end();
2054 const OperandMatchEntry &OMI = *it;
2055 const MatchableInfo &II = *OMI.MI;
2057 OS << " { \"" << II.Mnemonic << "\""
2058 << ", " << OMI.OperandMask;
2061 bool printComma = false;
2062 for (int i = 0, e = 31; i !=e; ++i)
2063 if (OMI.OperandMask & (1 << i)) {
2071 OS << ", " << OMI.CI->Name
2074 // Write the required features mask.
2075 if (!II.RequiredFeatures.empty()) {
2076 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2078 OS << II.RequiredFeatures[i]->getEnumName();
2086 // Emit the operand class switch to call the correct custom parser for
2087 // the found operand class.
2088 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2089 << Target.getName() << ClassName << "::\n"
2090 << "tryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>"
2091 << " &Operands,\n unsigned MCK) {\n\n"
2092 << " switch(MCK) {\n";
2094 for (std::vector<ClassInfo*>::const_iterator it = Info.Classes.begin(),
2095 ie = Info.Classes.end(); it != ie; ++it) {
2096 ClassInfo *CI = *it;
2097 if (CI->ParserMethod.empty())
2099 OS << " case " << CI->Name << ":\n"
2100 << " return " << CI->ParserMethod << "(Operands);\n";
2103 OS << " default:\n";
2104 OS << " return MatchOperand_NoMatch;\n";
2106 OS << " return MatchOperand_NoMatch;\n";
2109 // Emit the static custom operand parser. This code is very similar with
2110 // the other matcher. Also use MatchResultTy here just in case we go for
2111 // a better error handling.
2112 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2113 << Target.getName() << ClassName << "::\n"
2114 << "MatchOperandParserImpl(SmallVectorImpl<MCParsedAsmOperand*>"
2115 << " &Operands,\n StringRef Mnemonic) {\n";
2117 // Emit code to get the available features.
2118 OS << " // Get the current feature set.\n";
2119 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2121 OS << " // Get the next operand index.\n";
2122 OS << " unsigned NextOpNum = Operands.size()-1;\n";
2124 // Emit code to search the table.
2125 OS << " // Search the table.\n";
2126 OS << " std::pair<const OperandMatchEntry*, const OperandMatchEntry*>";
2127 OS << " MnemonicRange =\n";
2128 OS << " std::equal_range(OperandMatchTable, OperandMatchTable+"
2129 << Info.OperandMatchInfo.size() << ", Mnemonic,\n"
2130 << " LessOpcodeOperand());\n\n";
2132 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2133 OS << " return MatchOperand_NoMatch;\n\n";
2135 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2136 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2138 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2139 OS << " assert(Mnemonic == it->Mnemonic);\n\n";
2141 // Emit check that the required features are available.
2142 OS << " // check if the available features match\n";
2143 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2144 << "!= it->RequiredFeatures) {\n";
2145 OS << " continue;\n";
2148 // Emit check to ensure the operand number matches.
2149 OS << " // check if the operand in question has a custom parser.\n";
2150 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2151 OS << " continue;\n\n";
2153 // Emit call to the custom parser method
2154 OS << " // call custom parse method to handle the operand\n";
2155 OS << " OperandMatchResultTy Result = ";
2156 OS << "tryCustomParseOperand(Operands, it->Class);\n";
2157 OS << " if (Result != MatchOperand_NoMatch)\n";
2158 OS << " return Result;\n";
2161 OS << " // Okay, we had no match.\n";
2162 OS << " return MatchOperand_NoMatch;\n";
2166 void AsmMatcherEmitter::run(raw_ostream &OS) {
2167 CodeGenTarget Target(Records);
2168 Record *AsmParser = Target.getAsmParser();
2169 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2171 // Compute the information on the instructions to match.
2172 AsmMatcherInfo Info(AsmParser, Target, Records);
2175 // Sort the instruction table using the partial order on classes. We use
2176 // stable_sort to ensure that ambiguous instructions are still
2177 // deterministically ordered.
2178 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2179 less_ptr<MatchableInfo>());
2181 DEBUG_WITH_TYPE("instruction_info", {
2182 for (std::vector<MatchableInfo*>::iterator
2183 it = Info.Matchables.begin(), ie = Info.Matchables.end();
2188 // Check for ambiguous matchables.
2189 DEBUG_WITH_TYPE("ambiguous_instrs", {
2190 unsigned NumAmbiguous = 0;
2191 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) {
2192 for (unsigned j = i + 1; j != e; ++j) {
2193 MatchableInfo &A = *Info.Matchables[i];
2194 MatchableInfo &B = *Info.Matchables[j];
2196 if (A.CouldMatchAmbiguouslyWith(B)) {
2197 errs() << "warning: ambiguous matchables:\n";
2199 errs() << "\nis incomparable with:\n";
2207 errs() << "warning: " << NumAmbiguous
2208 << " ambiguous matchables!\n";
2211 // Compute the information on the custom operand parsing.
2212 Info.BuildOperandMatchInfo();
2214 // Write the output.
2216 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
2218 // Information for the class declaration.
2219 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2220 OS << "#undef GET_ASSEMBLER_HEADER\n";
2221 OS << " // This should be included into the middle of the declaration of\n";
2222 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
2223 OS << " unsigned ComputeAvailableFeatures(uint64_t FeatureBits) const;\n";
2224 OS << " bool ConvertToMCInst(unsigned Kind, MCInst &Inst, "
2225 << "unsigned Opcode,\n"
2226 << " const SmallVectorImpl<MCParsedAsmOperand*> "
2228 OS << " bool MnemonicIsValid(StringRef Mnemonic);\n";
2229 OS << " unsigned MatchInstructionImpl(\n";
2230 OS << " const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2231 OS << " MCInst &Inst, unsigned &ErrorInfo, unsigned VariantID = 0);\n";
2233 if (Info.OperandMatchInfo.size()) {
2234 OS << "\n enum OperandMatchResultTy {\n";
2235 OS << " MatchOperand_Success, // operand matched successfully\n";
2236 OS << " MatchOperand_NoMatch, // operand did not match\n";
2237 OS << " MatchOperand_ParseFail // operand matched but had errors\n";
2239 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
2240 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2241 OS << " StringRef Mnemonic);\n";
2243 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
2244 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2245 OS << " unsigned MCK);\n\n";
2248 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2250 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2251 OS << "#undef GET_REGISTER_MATCHER\n\n";
2253 // Emit the subtarget feature enumeration.
2254 EmitSubtargetFeatureFlagEnumeration(Info, OS);
2256 // Emit the function to match a register name to number.
2257 EmitMatchRegisterName(Target, AsmParser, OS);
2259 OS << "#endif // GET_REGISTER_MATCHER\n\n";
2262 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2263 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
2265 // Generate the function that remaps for mnemonic aliases.
2266 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
2268 // Generate the unified function to convert operands into an MCInst.
2269 EmitConvertToMCInst(Target, ClassName, Info.Matchables, OS);
2271 // Emit the enumeration for classes which participate in matching.
2272 EmitMatchClassEnumeration(Target, Info.Classes, OS);
2274 // Emit the routine to match token strings to their match class.
2275 EmitMatchTokenString(Target, Info.Classes, OS);
2277 // Emit the subclass predicate routine.
2278 EmitIsSubclass(Target, Info.Classes, OS);
2280 // Emit the routine to validate an operand against a match class.
2281 EmitValidateOperandClass(Info, OS);
2283 // Emit the available features compute function.
2284 EmitComputeAvailableFeatures(Info, OS);
2287 size_t MaxNumOperands = 0;
2288 for (std::vector<MatchableInfo*>::const_iterator it =
2289 Info.Matchables.begin(), ie = Info.Matchables.end();
2291 MaxNumOperands = std::max(MaxNumOperands, (*it)->AsmOperands.size());
2293 // Emit the static match table; unused classes get initalized to 0 which is
2294 // guaranteed to be InvalidMatchClass.
2296 // FIXME: We can reduce the size of this table very easily. First, we change
2297 // it so that store the kinds in separate bit-fields for each index, which
2298 // only needs to be the max width used for classes at that index (we also need
2299 // to reject based on this during classification). If we then make sure to
2300 // order the match kinds appropriately (putting mnemonics last), then we
2301 // should only end up using a few bits for each class, especially the ones
2302 // following the mnemonic.
2303 OS << "namespace {\n";
2304 OS << " struct MatchEntry {\n";
2305 OS << " unsigned Opcode;\n";
2306 OS << " const char *Mnemonic;\n";
2307 OS << " " << getMinimalTypeForRange(Info.Matchables.size())
2309 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2310 << " Classes[" << MaxNumOperands << "];\n";
2311 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2312 << " RequiredFeatures;\n";
2313 OS << " unsigned AsmVariantID;\n";
2316 OS << " // Predicate for searching for an opcode.\n";
2317 OS << " struct LessOpcode {\n";
2318 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
2319 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
2321 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
2322 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
2324 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
2325 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
2329 OS << "} // end anonymous namespace.\n\n";
2331 OS << "static const MatchEntry MatchTable["
2332 << Info.Matchables.size() << "] = {\n";
2334 for (std::vector<MatchableInfo*>::const_iterator it =
2335 Info.Matchables.begin(), ie = Info.Matchables.end();
2337 MatchableInfo &II = **it;
2339 OS << " { " << Target.getName() << "::"
2340 << II.getResultInst()->TheDef->getName() << ", \"" << II.Mnemonic << "\""
2341 << ", " << II.ConversionFnKind << ", { ";
2342 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
2343 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
2346 OS << Op.Class->Name;
2350 // Write the required features mask.
2351 if (!II.RequiredFeatures.empty()) {
2352 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2354 OS << II.RequiredFeatures[i]->getEnumName();
2358 OS << ", " << II.AsmVariantID;
2364 // A method to determine if a mnemonic is in the list.
2365 OS << "bool " << Target.getName() << ClassName << "::\n"
2366 << "MnemonicIsValid(StringRef Mnemonic) {\n";
2367 OS << " // Search the table.\n";
2368 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2369 OS << " std::equal_range(MatchTable, MatchTable+"
2370 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n";
2371 OS << " return MnemonicRange.first != MnemonicRange.second;\n";
2374 // Finally, build the match function.
2376 << Target.getName() << ClassName << "::\n"
2377 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
2379 OS << " MCInst &Inst, unsigned &ErrorInfo,\n";
2380 OS << " unsigned VariantID) {\n";
2382 // Emit code to get the available features.
2383 OS << " // Get the current feature set.\n";
2384 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2386 OS << " // Get the instruction mnemonic, which is the first token.\n";
2387 OS << " StringRef Mnemonic = ((" << Target.getName()
2388 << "Operand*)Operands[0])->getToken();\n\n";
2390 if (HasMnemonicAliases) {
2391 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
2392 OS << " // FIXME : Add an entry in AsmParserVariant to check this.\n";
2393 OS << " if (!VariantID)\n";
2394 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
2397 // Emit code to compute the class list for this operand vector.
2398 OS << " // Eliminate obvious mismatches.\n";
2399 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
2400 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
2401 OS << " return Match_InvalidOperand;\n";
2404 OS << " // Some state to try to produce better error messages.\n";
2405 OS << " bool HadMatchOtherThanFeatures = false;\n";
2406 OS << " bool HadMatchOtherThanPredicate = false;\n";
2407 OS << " unsigned RetCode = Match_InvalidOperand;\n";
2408 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
2409 OS << " // wrong for all instances of the instruction.\n";
2410 OS << " ErrorInfo = ~0U;\n";
2412 // Emit code to search the table.
2413 OS << " // Search the table.\n";
2414 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2415 OS << " std::equal_range(MatchTable, MatchTable+"
2416 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n";
2418 OS << " // Return a more specific error code if no mnemonics match.\n";
2419 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2420 OS << " return Match_MnemonicFail;\n\n";
2422 OS << " for (const MatchEntry *it = MnemonicRange.first, "
2423 << "*ie = MnemonicRange.second;\n";
2424 OS << " it != ie; ++it) {\n";
2426 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2427 OS << " assert(Mnemonic == it->Mnemonic);\n";
2429 // Emit check that the subclasses match.
2430 OS << " if (VariantID != it->AsmVariantID) continue;\n";
2431 OS << " bool OperandsValid = true;\n";
2432 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
2433 OS << " if (i + 1 >= Operands.size()) {\n";
2434 OS << " OperandsValid = (it->Classes[i] == " <<"InvalidMatchClass);\n";
2437 OS << " if (validateOperandClass(Operands[i+1], "
2438 "(MatchClassKind)it->Classes[i]))\n";
2439 OS << " continue;\n";
2440 OS << " // If this operand is broken for all of the instances of this\n";
2441 OS << " // mnemonic, keep track of it so we can report loc info.\n";
2442 OS << " if (it == MnemonicRange.first || ErrorInfo <= i+1)\n";
2443 OS << " ErrorInfo = i+1;\n";
2444 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
2445 OS << " OperandsValid = false;\n";
2449 OS << " if (!OperandsValid) continue;\n";
2451 // Emit check that the required features are available.
2452 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2453 << "!= it->RequiredFeatures) {\n";
2454 OS << " HadMatchOtherThanFeatures = true;\n";
2455 OS << " continue;\n";
2458 OS << " // We have selected a definite instruction, convert the parsed\n"
2459 << " // operands into the appropriate MCInst.\n";
2460 OS << " if (!ConvertToMCInst(it->ConvertFn, Inst,\n"
2461 << " it->Opcode, Operands))\n";
2462 OS << " return Match_ConversionFail;\n";
2465 // Verify the instruction with the target-specific match predicate function.
2466 OS << " // We have a potential match. Check the target predicate to\n"
2467 << " // handle any context sensitive constraints.\n"
2468 << " unsigned MatchResult;\n"
2469 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
2470 << " Match_Success) {\n"
2471 << " Inst.clear();\n"
2472 << " RetCode = MatchResult;\n"
2473 << " HadMatchOtherThanPredicate = true;\n"
2477 // Call the post-processing function, if used.
2478 std::string InsnCleanupFn =
2479 AsmParser->getValueAsString("AsmParserInstCleanup");
2480 if (!InsnCleanupFn.empty())
2481 OS << " " << InsnCleanupFn << "(Inst);\n";
2483 OS << " return Match_Success;\n";
2486 OS << " // Okay, we had no match. Try to return a useful error code.\n";
2487 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)";
2488 OS << " return RetCode;\n";
2489 OS << " return Match_MissingFeature;\n";
2492 if (Info.OperandMatchInfo.size())
2493 EmitCustomOperandParsing(OS, Target, Info, ClassName);
2495 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";