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/TableGen/Error.h"
111 #include "llvm/TableGen/Record.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!");
257 // This class precedes the RHS if it is a proper subset of the RHS.
260 if (RHS.isSubsetOf(*this))
263 // Otherwise, order by name to ensure we have a total ordering.
264 return ValueName < RHS.ValueName;
269 /// MatchableInfo - Helper class for storing the necessary information for an
270 /// instruction or alias which is capable of being matched.
271 struct MatchableInfo {
273 /// Token - This is the token that the operand came from.
276 /// The unique class instance this operand should match.
279 /// The operand name this is, if anything.
282 /// The suboperand index within SrcOpName, or -1 for the entire operand.
285 explicit AsmOperand(StringRef T) : Token(T), Class(0), SubOpIdx(-1) {}
288 /// ResOperand - This represents a single operand in the result instruction
289 /// generated by the match. In cases (like addressing modes) where a single
290 /// assembler operand expands to multiple MCOperands, this represents the
291 /// single assembler operand, not the MCOperand.
294 /// RenderAsmOperand - This represents an operand result that is
295 /// generated by calling the render method on the assembly operand. The
296 /// corresponding AsmOperand is specified by AsmOperandNum.
299 /// TiedOperand - This represents a result operand that is a duplicate of
300 /// a previous result operand.
303 /// ImmOperand - This represents an immediate value that is dumped into
307 /// RegOperand - This represents a fixed register that is dumped in.
312 /// This is the operand # in the AsmOperands list that this should be
314 unsigned AsmOperandNum;
316 /// TiedOperandNum - This is the (earlier) result operand that should be
318 unsigned TiedOperandNum;
320 /// ImmVal - This is the immediate value added to the instruction.
323 /// Register - This is the register record.
327 /// MINumOperands - The number of MCInst operands populated by this
329 unsigned MINumOperands;
331 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
333 X.Kind = RenderAsmOperand;
334 X.AsmOperandNum = AsmOpNum;
335 X.MINumOperands = NumOperands;
339 static ResOperand getTiedOp(unsigned TiedOperandNum) {
341 X.Kind = TiedOperand;
342 X.TiedOperandNum = TiedOperandNum;
347 static ResOperand getImmOp(int64_t Val) {
355 static ResOperand getRegOp(Record *Reg) {
364 /// TheDef - This is the definition of the instruction or InstAlias that this
365 /// matchable came from.
366 Record *const TheDef;
368 /// DefRec - This is the definition that it came from.
369 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
371 const CodeGenInstruction *getResultInst() const {
372 if (DefRec.is<const CodeGenInstruction*>())
373 return DefRec.get<const CodeGenInstruction*>();
374 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
377 /// ResOperands - This is the operand list that should be built for the result
379 std::vector<ResOperand> ResOperands;
381 /// AsmString - The assembly string for this instruction (with variants
382 /// removed), e.g. "movsx $src, $dst".
383 std::string AsmString;
385 /// Mnemonic - This is the first token of the matched instruction, its
389 /// AsmOperands - The textual operands that this instruction matches,
390 /// annotated with a class and where in the OperandList they were defined.
391 /// This directly corresponds to the tokenized AsmString after the mnemonic is
393 SmallVector<AsmOperand, 4> AsmOperands;
395 /// Predicates - The required subtarget features to match this instruction.
396 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
398 /// ConversionFnKind - The enum value which is passed to the generated
399 /// ConvertToMCInst to convert parsed operands into an MCInst for this
401 std::string ConversionFnKind;
403 MatchableInfo(const CodeGenInstruction &CGI)
404 : TheDef(CGI.TheDef), DefRec(&CGI), AsmString(CGI.AsmString) {
407 MatchableInfo(const CodeGenInstAlias *Alias)
408 : TheDef(Alias->TheDef), DefRec(Alias), AsmString(Alias->AsmString) {
411 void Initialize(const AsmMatcherInfo &Info,
412 SmallPtrSet<Record*, 16> &SingletonRegisters);
414 /// Validate - Return true if this matchable is a valid thing to match against
415 /// and perform a bunch of validity checking.
416 bool Validate(StringRef CommentDelimiter, bool Hack) const;
418 /// getSingletonRegisterForAsmOperand - If the specified token is a singleton
419 /// register, return the Record for it, otherwise return null.
420 Record *getSingletonRegisterForAsmOperand(unsigned i,
421 const AsmMatcherInfo &Info) const;
423 /// FindAsmOperand - Find the AsmOperand with the specified name and
424 /// suboperand index.
425 int FindAsmOperand(StringRef N, int SubOpIdx) const {
426 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
427 if (N == AsmOperands[i].SrcOpName &&
428 SubOpIdx == AsmOperands[i].SubOpIdx)
433 /// FindAsmOperandNamed - Find the first AsmOperand with the specified name.
434 /// This does not check the suboperand index.
435 int FindAsmOperandNamed(StringRef N) const {
436 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
437 if (N == AsmOperands[i].SrcOpName)
442 void BuildInstructionResultOperands();
443 void BuildAliasResultOperands();
445 /// operator< - Compare two matchables.
446 bool operator<(const MatchableInfo &RHS) const {
447 // The primary comparator is the instruction mnemonic.
448 if (Mnemonic != RHS.Mnemonic)
449 return Mnemonic < RHS.Mnemonic;
451 if (AsmOperands.size() != RHS.AsmOperands.size())
452 return AsmOperands.size() < RHS.AsmOperands.size();
454 // Compare lexicographically by operand. The matcher validates that other
455 // orderings wouldn't be ambiguous using \see CouldMatchAmbiguouslyWith().
456 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
457 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
459 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
466 /// CouldMatchAmbiguouslyWith - Check whether this matchable could
467 /// ambiguously match the same set of operands as \arg RHS (without being a
468 /// strictly superior match).
469 bool CouldMatchAmbiguouslyWith(const MatchableInfo &RHS) {
470 // The primary comparator is the instruction mnemonic.
471 if (Mnemonic != RHS.Mnemonic)
474 // The number of operands is unambiguous.
475 if (AsmOperands.size() != RHS.AsmOperands.size())
478 // Otherwise, make sure the ordering of the two instructions is unambiguous
479 // by checking that either (a) a token or operand kind discriminates them,
480 // or (b) the ordering among equivalent kinds is consistent.
482 // Tokens and operand kinds are unambiguous (assuming a correct target
484 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
485 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
486 AsmOperands[i].Class->Kind == ClassInfo::Token)
487 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
488 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
491 // Otherwise, this operand could commute if all operands are equivalent, or
492 // there is a pair of operands that compare less than and a pair that
493 // compare greater than.
494 bool HasLT = false, HasGT = false;
495 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
496 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
498 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
502 return !(HasLT ^ HasGT);
508 void TokenizeAsmString(const AsmMatcherInfo &Info);
511 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
512 /// feature which participates in instruction matching.
513 struct SubtargetFeatureInfo {
514 /// \brief The predicate record for this feature.
517 /// \brief An unique index assigned to represent this feature.
520 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
522 /// \brief The name of the enumerated constant identifying this feature.
523 std::string getEnumName() const {
524 return "Feature_" + TheDef->getName();
528 struct OperandMatchEntry {
529 unsigned OperandMask;
533 static OperandMatchEntry Create(MatchableInfo* mi, ClassInfo *ci,
536 X.OperandMask = opMask;
544 class AsmMatcherInfo {
547 RecordKeeper &Records;
549 /// The tablegen AsmParser record.
552 /// Target - The target information.
553 CodeGenTarget &Target;
555 /// The AsmParser "RegisterPrefix" value.
556 std::string RegisterPrefix;
558 /// The classes which are needed for matching.
559 std::vector<ClassInfo*> Classes;
561 /// The information on the matchables to match.
562 std::vector<MatchableInfo*> Matchables;
564 /// Info for custom matching operands by user defined methods.
565 std::vector<OperandMatchEntry> OperandMatchInfo;
567 /// Map of Register records to their class information.
568 std::map<Record*, ClassInfo*> RegisterClasses;
570 /// Map of Predicate records to their subtarget information.
571 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
574 /// Map of token to class information which has already been constructed.
575 std::map<std::string, ClassInfo*> TokenClasses;
577 /// Map of RegisterClass records to their class information.
578 std::map<Record*, ClassInfo*> RegisterClassClasses;
580 /// Map of AsmOperandClass records to their class information.
581 std::map<Record*, ClassInfo*> AsmOperandClasses;
584 /// getTokenClass - Lookup or create the class for the given token.
585 ClassInfo *getTokenClass(StringRef Token);
587 /// getOperandClass - Lookup or create the class for the given operand.
588 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
590 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
592 /// BuildRegisterClasses - Build the ClassInfo* instances for register
594 void BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
596 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
598 void BuildOperandClasses();
600 void BuildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
602 void BuildAliasOperandReference(MatchableInfo *II, StringRef OpName,
603 MatchableInfo::AsmOperand &Op);
606 AsmMatcherInfo(Record *AsmParser,
607 CodeGenTarget &Target,
608 RecordKeeper &Records);
610 /// BuildInfo - Construct the various tables used during matching.
613 /// BuildOperandMatchInfo - Build the necessary information to handle user
614 /// defined operand parsing methods.
615 void BuildOperandMatchInfo();
617 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
619 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
620 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
621 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
622 SubtargetFeatures.find(Def);
623 return I == SubtargetFeatures.end() ? 0 : I->second;
626 RecordKeeper &getRecords() const {
633 void MatchableInfo::dump() {
634 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
636 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
637 AsmOperand &Op = AsmOperands[i];
638 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
639 errs() << '\"' << Op.Token << "\"\n";
643 void MatchableInfo::Initialize(const AsmMatcherInfo &Info,
644 SmallPtrSet<Record*, 16> &SingletonRegisters) {
645 // TODO: Eventually support asmparser for Variant != 0.
646 AsmString = CodeGenInstruction::FlattenAsmStringVariants(AsmString, 0);
648 TokenizeAsmString(Info);
650 // Compute the require features.
651 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates");
652 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
653 if (SubtargetFeatureInfo *Feature =
654 Info.getSubtargetFeature(Predicates[i]))
655 RequiredFeatures.push_back(Feature);
657 // Collect singleton registers, if used.
658 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
659 if (Record *Reg = getSingletonRegisterForAsmOperand(i, Info))
660 SingletonRegisters.insert(Reg);
664 /// TokenizeAsmString - Tokenize a simplified assembly string.
665 void MatchableInfo::TokenizeAsmString(const AsmMatcherInfo &Info) {
666 StringRef String = AsmString;
669 for (unsigned i = 0, e = String.size(); i != e; ++i) {
679 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
682 if (!isspace(String[i]) && String[i] != ',')
683 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
689 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
693 assert(i != String.size() && "Invalid quoted character");
694 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
700 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
704 // If this isn't "${", treat like a normal token.
705 if (i + 1 == String.size() || String[i + 1] != '{') {
710 StringRef::iterator End = std::find(String.begin() + i, String.end(),'}');
711 assert(End != String.end() && "Missing brace in operand reference!");
712 size_t EndPos = End - String.begin();
713 AsmOperands.push_back(AsmOperand(String.slice(i, EndPos+1)));
721 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
730 if (InTok && Prev != String.size())
731 AsmOperands.push_back(AsmOperand(String.substr(Prev)));
733 // The first token of the instruction is the mnemonic, which must be a
734 // simple string, not a $foo variable or a singleton register.
735 if (AsmOperands.empty())
736 throw TGError(TheDef->getLoc(),
737 "Instruction '" + TheDef->getName() + "' has no tokens");
738 Mnemonic = AsmOperands[0].Token;
739 if (Mnemonic[0] == '$' || getSingletonRegisterForAsmOperand(0, Info))
740 throw TGError(TheDef->getLoc(),
741 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
743 // Remove the first operand, it is tracked in the mnemonic field.
744 AsmOperands.erase(AsmOperands.begin());
747 bool MatchableInfo::Validate(StringRef CommentDelimiter, bool Hack) const {
748 // Reject matchables with no .s string.
749 if (AsmString.empty())
750 throw TGError(TheDef->getLoc(), "instruction with empty asm string");
752 // Reject any matchables with a newline in them, they should be marked
753 // isCodeGenOnly if they are pseudo instructions.
754 if (AsmString.find('\n') != std::string::npos)
755 throw TGError(TheDef->getLoc(),
756 "multiline instruction is not valid for the asmparser, "
757 "mark it isCodeGenOnly");
759 // Remove comments from the asm string. We know that the asmstring only
761 if (!CommentDelimiter.empty() &&
762 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
763 throw TGError(TheDef->getLoc(),
764 "asmstring for instruction has comment character in it, "
765 "mark it isCodeGenOnly");
767 // Reject matchables with operand modifiers, these aren't something we can
768 // handle, the target should be refactored to use operands instead of
771 // Also, check for instructions which reference the operand multiple times;
772 // this implies a constraint we would not honor.
773 std::set<std::string> OperandNames;
774 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
775 StringRef Tok = AsmOperands[i].Token;
776 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
777 throw TGError(TheDef->getLoc(),
778 "matchable with operand modifier '" + Tok.str() +
779 "' not supported by asm matcher. Mark isCodeGenOnly!");
781 // Verify that any operand is only mentioned once.
782 // We reject aliases and ignore instructions for now.
783 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
785 throw TGError(TheDef->getLoc(),
786 "ERROR: matchable with tied operand '" + Tok.str() +
787 "' can never be matched!");
788 // FIXME: Should reject these. The ARM backend hits this with $lane in a
789 // bunch of instructions. It is unclear what the right answer is.
791 errs() << "warning: '" << TheDef->getName() << "': "
792 << "ignoring instruction with tied operand '"
793 << Tok.str() << "'\n";
802 /// getSingletonRegisterForAsmOperand - If the specified token is a singleton
803 /// register, return the register name, otherwise return a null StringRef.
804 Record *MatchableInfo::
805 getSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info) const{
806 StringRef Tok = AsmOperands[i].Token;
807 if (!Tok.startswith(Info.RegisterPrefix))
810 StringRef RegName = Tok.substr(Info.RegisterPrefix.size());
811 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
814 // If there is no register prefix (i.e. "%" in "%eax"), then this may
815 // be some random non-register token, just ignore it.
816 if (Info.RegisterPrefix.empty())
819 // Otherwise, we have something invalid prefixed with the register prefix,
821 std::string Err = "unable to find register for '" + RegName.str() +
822 "' (which matches register prefix)";
823 throw TGError(TheDef->getLoc(), Err);
826 static std::string getEnumNameForToken(StringRef Str) {
829 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
831 case '*': Res += "_STAR_"; break;
832 case '%': Res += "_PCT_"; break;
833 case ':': Res += "_COLON_"; break;
834 case '!': Res += "_EXCLAIM_"; break;
835 case '.': Res += "_DOT_"; break;
840 Res += "_" + utostr((unsigned) *it) + "_";
847 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
848 ClassInfo *&Entry = TokenClasses[Token];
851 Entry = new ClassInfo();
852 Entry->Kind = ClassInfo::Token;
853 Entry->ClassName = "Token";
854 Entry->Name = "MCK_" + getEnumNameForToken(Token);
855 Entry->ValueName = Token;
856 Entry->PredicateMethod = "<invalid>";
857 Entry->RenderMethod = "<invalid>";
858 Entry->ParserMethod = "";
859 Classes.push_back(Entry);
866 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
868 Record *Rec = OI.Rec;
870 Rec = dynamic_cast<DefInit*>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
871 return getOperandClass(Rec, SubOpIdx);
875 AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
876 if (Rec->isSubClassOf("RegisterOperand")) {
877 // RegisterOperand may have an associated ParserMatchClass. If it does,
878 // use it, else just fall back to the underlying register class.
879 const RecordVal *R = Rec->getValue("ParserMatchClass");
880 if (R == 0 || R->getValue() == 0)
881 throw "Record `" + Rec->getName() +
882 "' does not have a ParserMatchClass!\n";
884 if (DefInit *DI= dynamic_cast<DefInit*>(R->getValue())) {
885 Record *MatchClass = DI->getDef();
886 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
890 // No custom match class. Just use the register class.
891 Record *ClassRec = Rec->getValueAsDef("RegClass");
893 throw TGError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
894 "' has no associated register class!\n");
895 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
897 throw TGError(Rec->getLoc(), "register class has no class info!");
901 if (Rec->isSubClassOf("RegisterClass")) {
902 if (ClassInfo *CI = RegisterClassClasses[Rec])
904 throw TGError(Rec->getLoc(), "register class has no class info!");
907 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
908 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
909 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
912 throw TGError(Rec->getLoc(), "operand has no match class!");
915 void AsmMatcherInfo::
916 BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
917 const std::vector<CodeGenRegister*> &Registers =
918 Target.getRegBank().getRegisters();
919 ArrayRef<CodeGenRegisterClass*> RegClassList =
920 Target.getRegBank().getRegClasses();
922 // The register sets used for matching.
923 std::set< std::set<Record*> > RegisterSets;
925 // Gather the defined sets.
926 for (ArrayRef<CodeGenRegisterClass*>::const_iterator it =
927 RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it)
928 RegisterSets.insert(std::set<Record*>(
929 (*it)->getOrder().begin(), (*it)->getOrder().end()));
931 // Add any required singleton sets.
932 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
933 ie = SingletonRegisters.end(); it != ie; ++it) {
935 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
938 // Introduce derived sets where necessary (when a register does not determine
939 // a unique register set class), and build the mapping of registers to the set
940 // they should classify to.
941 std::map<Record*, std::set<Record*> > RegisterMap;
942 for (std::vector<CodeGenRegister*>::const_iterator it = Registers.begin(),
943 ie = Registers.end(); it != ie; ++it) {
944 const CodeGenRegister &CGR = **it;
945 // Compute the intersection of all sets containing this register.
946 std::set<Record*> ContainingSet;
948 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
949 ie = RegisterSets.end(); it != ie; ++it) {
950 if (!it->count(CGR.TheDef))
953 if (ContainingSet.empty()) {
958 std::set<Record*> Tmp;
959 std::swap(Tmp, ContainingSet);
960 std::insert_iterator< std::set<Record*> > II(ContainingSet,
961 ContainingSet.begin());
962 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(), II);
965 if (!ContainingSet.empty()) {
966 RegisterSets.insert(ContainingSet);
967 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
971 // Construct the register classes.
972 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
974 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
975 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
976 ClassInfo *CI = new ClassInfo();
977 CI->Kind = ClassInfo::RegisterClass0 + Index;
978 CI->ClassName = "Reg" + utostr(Index);
979 CI->Name = "MCK_Reg" + utostr(Index);
981 CI->PredicateMethod = ""; // unused
982 CI->RenderMethod = "addRegOperands";
984 Classes.push_back(CI);
985 RegisterSetClasses.insert(std::make_pair(*it, CI));
988 // Find the superclasses; we could compute only the subgroup lattice edges,
989 // but there isn't really a point.
990 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
991 ie = RegisterSets.end(); it != ie; ++it) {
992 ClassInfo *CI = RegisterSetClasses[*it];
993 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
994 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
996 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
997 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
1000 // Name the register classes which correspond to a user defined RegisterClass.
1001 for (ArrayRef<CodeGenRegisterClass*>::const_iterator
1002 it = RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) {
1003 const CodeGenRegisterClass &RC = **it;
1004 // Def will be NULL for non-user defined register classes.
1005 Record *Def = RC.getDef();
1008 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(RC.getOrder().begin(),
1009 RC.getOrder().end())];
1010 if (CI->ValueName.empty()) {
1011 CI->ClassName = RC.getName();
1012 CI->Name = "MCK_" + RC.getName();
1013 CI->ValueName = RC.getName();
1015 CI->ValueName = CI->ValueName + "," + RC.getName();
1017 RegisterClassClasses.insert(std::make_pair(Def, CI));
1020 // Populate the map for individual registers.
1021 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
1022 ie = RegisterMap.end(); it != ie; ++it)
1023 RegisterClasses[it->first] = RegisterSetClasses[it->second];
1025 // Name the register classes which correspond to singleton registers.
1026 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1027 ie = SingletonRegisters.end(); it != ie; ++it) {
1029 ClassInfo *CI = RegisterClasses[Rec];
1030 assert(CI && "Missing singleton register class info!");
1032 if (CI->ValueName.empty()) {
1033 CI->ClassName = Rec->getName();
1034 CI->Name = "MCK_" + Rec->getName();
1035 CI->ValueName = Rec->getName();
1037 CI->ValueName = CI->ValueName + "," + Rec->getName();
1041 void AsmMatcherInfo::BuildOperandClasses() {
1042 std::vector<Record*> AsmOperands =
1043 Records.getAllDerivedDefinitions("AsmOperandClass");
1045 // Pre-populate AsmOperandClasses map.
1046 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1047 ie = AsmOperands.end(); it != ie; ++it)
1048 AsmOperandClasses[*it] = new ClassInfo();
1051 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1052 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
1053 ClassInfo *CI = AsmOperandClasses[*it];
1054 CI->Kind = ClassInfo::UserClass0 + Index;
1056 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
1057 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
1058 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
1060 PrintError((*it)->getLoc(), "Invalid super class reference!");
1064 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1066 PrintError((*it)->getLoc(), "Invalid super class reference!");
1068 CI->SuperClasses.push_back(SC);
1070 CI->ClassName = (*it)->getValueAsString("Name");
1071 CI->Name = "MCK_" + CI->ClassName;
1072 CI->ValueName = (*it)->getName();
1074 // Get or construct the predicate method name.
1075 Init *PMName = (*it)->getValueInit("PredicateMethod");
1076 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
1077 CI->PredicateMethod = SI->getValue();
1079 assert(dynamic_cast<UnsetInit*>(PMName) &&
1080 "Unexpected PredicateMethod field!");
1081 CI->PredicateMethod = "is" + CI->ClassName;
1084 // Get or construct the render method name.
1085 Init *RMName = (*it)->getValueInit("RenderMethod");
1086 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
1087 CI->RenderMethod = SI->getValue();
1089 assert(dynamic_cast<UnsetInit*>(RMName) &&
1090 "Unexpected RenderMethod field!");
1091 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1094 // Get the parse method name or leave it as empty.
1095 Init *PRMName = (*it)->getValueInit("ParserMethod");
1096 if (StringInit *SI = dynamic_cast<StringInit*>(PRMName))
1097 CI->ParserMethod = SI->getValue();
1099 AsmOperandClasses[*it] = CI;
1100 Classes.push_back(CI);
1104 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1105 CodeGenTarget &target,
1106 RecordKeeper &records)
1107 : Records(records), AsmParser(asmParser), Target(target),
1108 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix")) {
1111 /// BuildOperandMatchInfo - Build the necessary information to handle user
1112 /// defined operand parsing methods.
1113 void AsmMatcherInfo::BuildOperandMatchInfo() {
1115 /// Map containing a mask with all operands indicies that can be found for
1116 /// that class inside a instruction.
1117 std::map<ClassInfo*, unsigned> OpClassMask;
1119 for (std::vector<MatchableInfo*>::const_iterator it =
1120 Matchables.begin(), ie = Matchables.end();
1122 MatchableInfo &II = **it;
1123 OpClassMask.clear();
1125 // Keep track of all operands of this instructions which belong to the
1127 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
1128 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
1129 if (Op.Class->ParserMethod.empty())
1131 unsigned &OperandMask = OpClassMask[Op.Class];
1132 OperandMask |= (1 << i);
1135 // Generate operand match info for each mnemonic/operand class pair.
1136 for (std::map<ClassInfo*, unsigned>::iterator iit = OpClassMask.begin(),
1137 iie = OpClassMask.end(); iit != iie; ++iit) {
1138 unsigned OpMask = iit->second;
1139 ClassInfo *CI = iit->first;
1140 OperandMatchInfo.push_back(OperandMatchEntry::Create(&II, CI, OpMask));
1145 void AsmMatcherInfo::BuildInfo() {
1146 // Build information about all of the AssemblerPredicates.
1147 std::vector<Record*> AllPredicates =
1148 Records.getAllDerivedDefinitions("Predicate");
1149 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
1150 Record *Pred = AllPredicates[i];
1151 // Ignore predicates that are not intended for the assembler.
1152 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
1155 if (Pred->getName().empty())
1156 throw TGError(Pred->getLoc(), "Predicate has no name!");
1158 unsigned FeatureNo = SubtargetFeatures.size();
1159 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
1160 assert(FeatureNo < 32 && "Too many subtarget features!");
1163 std::string CommentDelimiter = AsmParser->getValueAsString("CommentDelimiter");
1165 // Parse the instructions; we need to do this first so that we can gather the
1166 // singleton register classes.
1167 SmallPtrSet<Record*, 16> SingletonRegisters;
1168 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
1169 E = Target.inst_end(); I != E; ++I) {
1170 const CodeGenInstruction &CGI = **I;
1172 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1173 // filter the set of instructions we consider.
1174 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
1177 // Ignore "codegen only" instructions.
1178 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
1181 // Validate the operand list to ensure we can handle this instruction.
1182 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1183 const CGIOperandList::OperandInfo &OI = CGI.Operands[i];
1185 // Validate tied operands.
1186 if (OI.getTiedRegister() != -1) {
1187 // If we have a tied operand that consists of multiple MCOperands,
1188 // reject it. We reject aliases and ignore instructions for now.
1189 if (OI.MINumOperands != 1) {
1190 // FIXME: Should reject these. The ARM backend hits this with $lane
1191 // in a bunch of instructions. It is unclear what the right answer is.
1193 errs() << "warning: '" << CGI.TheDef->getName() << "': "
1194 << "ignoring instruction with multi-operand tied operand '"
1195 << OI.Name << "'\n";
1202 OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
1204 II->Initialize(*this, SingletonRegisters);
1206 // Ignore instructions which shouldn't be matched and diagnose invalid
1207 // instruction definitions with an error.
1208 if (!II->Validate(CommentDelimiter, true))
1211 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
1213 // FIXME: This is a total hack.
1214 if (StringRef(II->TheDef->getName()).startswith("Int_") ||
1215 StringRef(II->TheDef->getName()).endswith("_Int"))
1218 Matchables.push_back(II.take());
1221 // Parse all of the InstAlias definitions and stick them in the list of
1223 std::vector<Record*> AllInstAliases =
1224 Records.getAllDerivedDefinitions("InstAlias");
1225 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
1226 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i], Target);
1228 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1229 // filter the set of instruction aliases we consider, based on the target
1231 if (!StringRef(Alias->ResultInst->TheDef->getName()).startswith(
1235 OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
1237 II->Initialize(*this, SingletonRegisters);
1239 // Validate the alias definitions.
1240 II->Validate(CommentDelimiter, false);
1242 Matchables.push_back(II.take());
1245 // Build info for the register classes.
1246 BuildRegisterClasses(SingletonRegisters);
1248 // Build info for the user defined assembly operand classes.
1249 BuildOperandClasses();
1251 // Build the information about matchables, now that we have fully formed
1253 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(),
1254 ie = Matchables.end(); it != ie; ++it) {
1255 MatchableInfo *II = *it;
1257 // Parse the tokens after the mnemonic.
1258 // Note: BuildInstructionOperandReference may insert new AsmOperands, so
1259 // don't precompute the loop bound.
1260 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1261 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
1262 StringRef Token = Op.Token;
1264 // Check for singleton registers.
1265 if (Record *RegRecord = II->getSingletonRegisterForAsmOperand(i, *this)) {
1266 Op.Class = RegisterClasses[RegRecord];
1267 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1268 "Unexpected class for singleton register");
1272 // Check for simple tokens.
1273 if (Token[0] != '$') {
1274 Op.Class = getTokenClass(Token);
1278 if (Token.size() > 1 && isdigit(Token[1])) {
1279 Op.Class = getTokenClass(Token);
1283 // Otherwise this is an operand reference.
1284 StringRef OperandName;
1285 if (Token[1] == '{')
1286 OperandName = Token.substr(2, Token.size() - 3);
1288 OperandName = Token.substr(1);
1290 if (II->DefRec.is<const CodeGenInstruction*>())
1291 BuildInstructionOperandReference(II, OperandName, i);
1293 BuildAliasOperandReference(II, OperandName, Op);
1296 if (II->DefRec.is<const CodeGenInstruction*>())
1297 II->BuildInstructionResultOperands();
1299 II->BuildAliasResultOperands();
1302 // Process token alias definitions and set up the associated superclass
1304 std::vector<Record*> AllTokenAliases =
1305 Records.getAllDerivedDefinitions("TokenAlias");
1306 for (unsigned i = 0, e = AllTokenAliases.size(); i != e; ++i) {
1307 Record *Rec = AllTokenAliases[i];
1308 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1309 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
1310 FromClass->SuperClasses.push_back(ToClass);
1313 // Reorder classes so that classes precede super classes.
1314 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
1317 /// BuildInstructionOperandReference - The specified operand is a reference to a
1318 /// named operand such as $src. Resolve the Class and OperandInfo pointers.
1319 void AsmMatcherInfo::
1320 BuildInstructionOperandReference(MatchableInfo *II,
1321 StringRef OperandName,
1322 unsigned AsmOpIdx) {
1323 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1324 const CGIOperandList &Operands = CGI.Operands;
1325 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
1327 // Map this token to an operand.
1329 if (!Operands.hasOperandNamed(OperandName, Idx))
1330 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1331 OperandName.str() + "'");
1333 // If the instruction operand has multiple suboperands, but the parser
1334 // match class for the asm operand is still the default "ImmAsmOperand",
1335 // then handle each suboperand separately.
1336 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1337 Record *Rec = Operands[Idx].Rec;
1338 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1339 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1340 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1341 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1342 StringRef Token = Op->Token; // save this in case Op gets moved
1343 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1344 MatchableInfo::AsmOperand NewAsmOp(Token);
1345 NewAsmOp.SubOpIdx = SI;
1346 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1348 // Replace Op with first suboperand.
1349 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1354 // Set up the operand class.
1355 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
1357 // If the named operand is tied, canonicalize it to the untied operand.
1358 // For example, something like:
1359 // (outs GPR:$dst), (ins GPR:$src)
1360 // with an asmstring of
1362 // we want to canonicalize to:
1364 // so that we know how to provide the $dst operand when filling in the result.
1365 int OITied = Operands[Idx].getTiedRegister();
1367 // The tied operand index is an MIOperand index, find the operand that
1369 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1370 OperandName = Operands[Idx.first].Name;
1371 Op->SubOpIdx = Idx.second;
1374 Op->SrcOpName = OperandName;
1377 /// BuildAliasOperandReference - When parsing an operand reference out of the
1378 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1379 /// operand reference is by looking it up in the result pattern definition.
1380 void AsmMatcherInfo::BuildAliasOperandReference(MatchableInfo *II,
1381 StringRef OperandName,
1382 MatchableInfo::AsmOperand &Op) {
1383 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
1385 // Set up the operand class.
1386 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
1387 if (CGA.ResultOperands[i].isRecord() &&
1388 CGA.ResultOperands[i].getName() == OperandName) {
1389 // It's safe to go with the first one we find, because CodeGenInstAlias
1390 // validates that all operands with the same name have the same record.
1391 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
1392 // Use the match class from the Alias definition, not the
1393 // destination instruction, as we may have an immediate that's
1394 // being munged by the match class.
1395 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
1397 Op.SrcOpName = OperandName;
1401 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1402 OperandName.str() + "'");
1405 void MatchableInfo::BuildInstructionResultOperands() {
1406 const CodeGenInstruction *ResultInst = getResultInst();
1408 // Loop over all operands of the result instruction, determining how to
1410 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1411 const CGIOperandList::OperandInfo &OpInfo = ResultInst->Operands[i];
1413 // If this is a tied operand, just copy from the previously handled operand.
1414 int TiedOp = OpInfo.getTiedRegister();
1416 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1420 // Find out what operand from the asmparser this MCInst operand comes from.
1421 int SrcOperand = FindAsmOperandNamed(OpInfo.Name);
1422 if (OpInfo.Name.empty() || SrcOperand == -1)
1423 throw TGError(TheDef->getLoc(), "Instruction '" +
1424 TheDef->getName() + "' has operand '" + OpInfo.Name +
1425 "' that doesn't appear in asm string!");
1427 // Check if the one AsmOperand populates the entire operand.
1428 unsigned NumOperands = OpInfo.MINumOperands;
1429 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1430 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
1434 // Add a separate ResOperand for each suboperand.
1435 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1436 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1437 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1438 "unexpected AsmOperands for suboperands");
1439 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1444 void MatchableInfo::BuildAliasResultOperands() {
1445 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1446 const CodeGenInstruction *ResultInst = getResultInst();
1448 // Loop over all operands of the result instruction, determining how to
1450 unsigned AliasOpNo = 0;
1451 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
1452 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1453 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
1455 // If this is a tied operand, just copy from the previously handled operand.
1456 int TiedOp = OpInfo->getTiedRegister();
1458 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1462 // Handle all the suboperands for this operand.
1463 const std::string &OpName = OpInfo->Name;
1464 for ( ; AliasOpNo < LastOpNo &&
1465 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1466 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1468 // Find out what operand from the asmparser that this MCInst operand
1470 switch (CGA.ResultOperands[AliasOpNo].Kind) {
1471 default: assert(0 && "unexpected InstAlias operand kind");
1472 case CodeGenInstAlias::ResultOperand::K_Record: {
1473 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1474 int SrcOperand = FindAsmOperand(Name, SubIdx);
1475 if (SrcOperand == -1)
1476 throw TGError(TheDef->getLoc(), "Instruction '" +
1477 TheDef->getName() + "' has operand '" + OpName +
1478 "' that doesn't appear in asm string!");
1479 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1480 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1484 case CodeGenInstAlias::ResultOperand::K_Imm: {
1485 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1486 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1489 case CodeGenInstAlias::ResultOperand::K_Reg: {
1490 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1491 ResOperands.push_back(ResOperand::getRegOp(Reg));
1499 static void EmitConvertToMCInst(CodeGenTarget &Target, StringRef ClassName,
1500 std::vector<MatchableInfo*> &Infos,
1502 // Write the convert function to a separate stream, so we can drop it after
1504 std::string ConvertFnBody;
1505 raw_string_ostream CvtOS(ConvertFnBody);
1507 // Function we have already generated.
1508 std::set<std::string> GeneratedFns;
1510 // Start the unified conversion function.
1511 CvtOS << "bool " << Target.getName() << ClassName << "::\n";
1512 CvtOS << "ConvertToMCInst(unsigned Kind, MCInst &Inst, "
1513 << "unsigned Opcode,\n"
1514 << " const SmallVectorImpl<MCParsedAsmOperand*"
1515 << "> &Operands) {\n";
1516 CvtOS << " Inst.setOpcode(Opcode);\n";
1517 CvtOS << " switch (Kind) {\n";
1518 CvtOS << " default:\n";
1520 // Start the enum, which we will generate inline.
1522 OS << "// Unified function for converting operands to MCInst instances.\n\n";
1523 OS << "enum ConversionKind {\n";
1525 // TargetOperandClass - This is the target's operand class, like X86Operand.
1526 std::string TargetOperandClass = Target.getName() + "Operand";
1528 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(),
1529 ie = Infos.end(); it != ie; ++it) {
1530 MatchableInfo &II = **it;
1532 // Check if we have a custom match function.
1533 std::string AsmMatchConverter =
1534 II.getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
1535 if (!AsmMatchConverter.empty()) {
1536 std::string Signature = "ConvertCustom_" + AsmMatchConverter;
1537 II.ConversionFnKind = Signature;
1539 // Check if we have already generated this signature.
1540 if (!GeneratedFns.insert(Signature).second)
1543 // If not, emit it now. Add to the enum list.
1544 OS << " " << Signature << ",\n";
1546 CvtOS << " case " << Signature << ":\n";
1547 CvtOS << " return " << AsmMatchConverter
1548 << "(Inst, Opcode, Operands);\n";
1552 // Build the conversion function signature.
1553 std::string Signature = "Convert";
1554 std::string CaseBody;
1555 raw_string_ostream CaseOS(CaseBody);
1557 // Compute the convert enum and the case body.
1558 for (unsigned i = 0, e = II.ResOperands.size(); i != e; ++i) {
1559 const MatchableInfo::ResOperand &OpInfo = II.ResOperands[i];
1561 // Generate code to populate each result operand.
1562 switch (OpInfo.Kind) {
1563 case MatchableInfo::ResOperand::RenderAsmOperand: {
1564 // This comes from something we parsed.
1565 MatchableInfo::AsmOperand &Op = II.AsmOperands[OpInfo.AsmOperandNum];
1567 // Registers are always converted the same, don't duplicate the
1568 // conversion function based on them.
1570 if (Op.Class->isRegisterClass())
1573 Signature += Op.Class->ClassName;
1574 Signature += utostr(OpInfo.MINumOperands);
1575 Signature += "_" + itostr(OpInfo.AsmOperandNum);
1577 CaseOS << " ((" << TargetOperandClass << "*)Operands["
1578 << (OpInfo.AsmOperandNum+1) << "])->" << Op.Class->RenderMethod
1579 << "(Inst, " << OpInfo.MINumOperands << ");\n";
1583 case MatchableInfo::ResOperand::TiedOperand: {
1584 // If this operand is tied to a previous one, just copy the MCInst
1585 // operand from the earlier one.We can only tie single MCOperand values.
1586 //assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
1587 unsigned TiedOp = OpInfo.TiedOperandNum;
1588 assert(i > TiedOp && "Tied operand precedes its target!");
1589 CaseOS << " Inst.addOperand(Inst.getOperand(" << TiedOp << "));\n";
1590 Signature += "__Tie" + utostr(TiedOp);
1593 case MatchableInfo::ResOperand::ImmOperand: {
1594 int64_t Val = OpInfo.ImmVal;
1595 CaseOS << " Inst.addOperand(MCOperand::CreateImm(" << Val << "));\n";
1596 Signature += "__imm" + itostr(Val);
1599 case MatchableInfo::ResOperand::RegOperand: {
1600 if (OpInfo.Register == 0) {
1601 CaseOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1602 Signature += "__reg0";
1604 std::string N = getQualifiedName(OpInfo.Register);
1605 CaseOS << " Inst.addOperand(MCOperand::CreateReg(" << N << "));\n";
1606 Signature += "__reg" + OpInfo.Register->getName();
1612 II.ConversionFnKind = Signature;
1614 // Check if we have already generated this signature.
1615 if (!GeneratedFns.insert(Signature).second)
1618 // If not, emit it now. Add to the enum list.
1619 OS << " " << Signature << ",\n";
1621 CvtOS << " case " << Signature << ":\n";
1622 CvtOS << CaseOS.str();
1623 CvtOS << " return true;\n";
1626 // Finish the convert function.
1629 CvtOS << " return false;\n";
1632 // Finish the enum, and drop the convert function after it.
1634 OS << " NumConversionVariants\n";
1640 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1641 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1642 std::vector<ClassInfo*> &Infos,
1644 OS << "namespace {\n\n";
1646 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1647 << "/// instruction matching.\n";
1648 OS << "enum MatchClassKind {\n";
1649 OS << " InvalidMatchClass = 0,\n";
1650 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1651 ie = Infos.end(); it != ie; ++it) {
1652 ClassInfo &CI = **it;
1653 OS << " " << CI.Name << ", // ";
1654 if (CI.Kind == ClassInfo::Token) {
1655 OS << "'" << CI.ValueName << "'\n";
1656 } else if (CI.isRegisterClass()) {
1657 if (!CI.ValueName.empty())
1658 OS << "register class '" << CI.ValueName << "'\n";
1660 OS << "derived register class\n";
1662 OS << "user defined class '" << CI.ValueName << "'\n";
1665 OS << " NumMatchClassKinds\n";
1671 /// EmitValidateOperandClass - Emit the function to validate an operand class.
1672 static void EmitValidateOperandClass(AsmMatcherInfo &Info,
1674 OS << "static bool validateOperandClass(MCParsedAsmOperand *GOp, "
1675 << "MatchClassKind Kind) {\n";
1676 OS << " " << Info.Target.getName() << "Operand &Operand = *("
1677 << Info.Target.getName() << "Operand*)GOp;\n";
1679 // The InvalidMatchClass is not to match any operand.
1680 OS << " if (Kind == InvalidMatchClass)\n";
1681 OS << " return false;\n\n";
1683 // Check for Token operands first.
1684 OS << " if (Operand.isToken())\n";
1685 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind);"
1688 // Check for register operands, including sub-classes.
1689 OS << " if (Operand.isReg()) {\n";
1690 OS << " MatchClassKind OpKind;\n";
1691 OS << " switch (Operand.getReg()) {\n";
1692 OS << " default: OpKind = InvalidMatchClass; break;\n";
1693 for (std::map<Record*, ClassInfo*>::iterator
1694 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1696 OS << " case " << Info.Target.getName() << "::"
1697 << it->first->getName() << ": OpKind = " << it->second->Name
1700 OS << " return isSubclass(OpKind, Kind);\n";
1703 // Check the user classes. We don't care what order since we're only
1704 // actually matching against one of them.
1705 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1706 ie = Info.Classes.end(); it != ie; ++it) {
1707 ClassInfo &CI = **it;
1709 if (!CI.isUserClass())
1712 OS << " // '" << CI.ClassName << "' class\n";
1713 OS << " if (Kind == " << CI.Name
1714 << " && Operand." << CI.PredicateMethod << "()) {\n";
1715 OS << " return true;\n";
1719 OS << " return false;\n";
1723 /// EmitIsSubclass - Emit the subclass predicate function.
1724 static void EmitIsSubclass(CodeGenTarget &Target,
1725 std::vector<ClassInfo*> &Infos,
1727 OS << "/// isSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1728 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
1729 OS << " if (A == B)\n";
1730 OS << " return true;\n\n";
1732 OS << " switch (A) {\n";
1733 OS << " default:\n";
1734 OS << " return false;\n";
1735 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1736 ie = Infos.end(); it != ie; ++it) {
1737 ClassInfo &A = **it;
1739 std::vector<StringRef> SuperClasses;
1740 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1741 ie = Infos.end(); it != ie; ++it) {
1742 ClassInfo &B = **it;
1744 if (&A != &B && A.isSubsetOf(B))
1745 SuperClasses.push_back(B.Name);
1748 if (SuperClasses.empty())
1751 OS << "\n case " << A.Name << ":\n";
1753 if (SuperClasses.size() == 1) {
1754 OS << " return B == " << SuperClasses.back() << ";\n";
1758 OS << " switch (B) {\n";
1759 OS << " default: return false;\n";
1760 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1761 OS << " case " << SuperClasses[i] << ": return true;\n";
1768 /// EmitMatchTokenString - Emit the function to match a token string to the
1769 /// appropriate match class value.
1770 static void EmitMatchTokenString(CodeGenTarget &Target,
1771 std::vector<ClassInfo*> &Infos,
1773 // Construct the match list.
1774 std::vector<StringMatcher::StringPair> Matches;
1775 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1776 ie = Infos.end(); it != ie; ++it) {
1777 ClassInfo &CI = **it;
1779 if (CI.Kind == ClassInfo::Token)
1780 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1781 "return " + CI.Name + ";"));
1784 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
1786 StringMatcher("Name", Matches, OS).Emit();
1788 OS << " return InvalidMatchClass;\n";
1792 /// EmitMatchRegisterName - Emit the function to match a string to the target
1793 /// specific register enum.
1794 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1796 // Construct the match list.
1797 std::vector<StringMatcher::StringPair> Matches;
1798 const std::vector<CodeGenRegister*> &Regs =
1799 Target.getRegBank().getRegisters();
1800 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1801 const CodeGenRegister *Reg = Regs[i];
1802 if (Reg->TheDef->getValueAsString("AsmName").empty())
1805 Matches.push_back(StringMatcher::StringPair(
1806 Reg->TheDef->getValueAsString("AsmName"),
1807 "return " + utostr(Reg->EnumValue) + ";"));
1810 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
1812 StringMatcher("Name", Matches, OS).Emit();
1814 OS << " return 0;\n";
1818 /// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1820 static void EmitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
1822 OS << "// Flags for subtarget features that participate in "
1823 << "instruction matching.\n";
1824 OS << "enum SubtargetFeatureFlag {\n";
1825 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1826 it = Info.SubtargetFeatures.begin(),
1827 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1828 SubtargetFeatureInfo &SFI = *it->second;
1829 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
1831 OS << " Feature_None = 0\n";
1835 /// EmitComputeAvailableFeatures - Emit the function to compute the list of
1836 /// available features given a subtarget.
1837 static void EmitComputeAvailableFeatures(AsmMatcherInfo &Info,
1839 std::string ClassName =
1840 Info.AsmParser->getValueAsString("AsmParserClassName");
1842 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
1843 << "ComputeAvailableFeatures(uint64_t FB) const {\n";
1844 OS << " unsigned Features = 0;\n";
1845 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1846 it = Info.SubtargetFeatures.begin(),
1847 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1848 SubtargetFeatureInfo &SFI = *it->second;
1851 std::string CondStorage = SFI.TheDef->getValueAsString("AssemblerCondString");
1852 StringRef Conds = CondStorage;
1853 std::pair<StringRef,StringRef> Comma = Conds.split(',');
1860 StringRef Cond = Comma.first;
1861 if (Cond[0] == '!') {
1863 Cond = Cond.substr(1);
1866 OS << "((FB & " << Info.Target.getName() << "::" << Cond << ")";
1873 if (Comma.second.empty())
1877 Comma = Comma.second.split(',');
1881 OS << " Features |= " << SFI.getEnumName() << ";\n";
1883 OS << " return Features;\n";
1887 static std::string GetAliasRequiredFeatures(Record *R,
1888 const AsmMatcherInfo &Info) {
1889 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
1891 unsigned NumFeatures = 0;
1892 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
1893 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
1896 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
1897 "' is not marked as an AssemblerPredicate!");
1902 Result += F->getEnumName();
1906 if (NumFeatures > 1)
1907 Result = '(' + Result + ')';
1911 /// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
1912 /// emit a function for them and return true, otherwise return false.
1913 static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
1914 // Ignore aliases when match-prefix is set.
1915 if (!MatchPrefix.empty())
1918 std::vector<Record*> Aliases =
1919 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
1920 if (Aliases.empty()) return false;
1922 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
1923 "unsigned Features) {\n";
1925 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
1926 // iteration order of the map is stable.
1927 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1929 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1930 Record *R = Aliases[i];
1931 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
1934 // Process each alias a "from" mnemonic at a time, building the code executed
1935 // by the string remapper.
1936 std::vector<StringMatcher::StringPair> Cases;
1937 for (std::map<std::string, std::vector<Record*> >::iterator
1938 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1940 const std::vector<Record*> &ToVec = I->second;
1942 // Loop through each alias and emit code that handles each case. If there
1943 // are two instructions without predicates, emit an error. If there is one,
1945 std::string MatchCode;
1946 int AliasWithNoPredicate = -1;
1948 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1949 Record *R = ToVec[i];
1950 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
1952 // If this unconditionally matches, remember it for later and diagnose
1954 if (FeatureMask.empty()) {
1955 if (AliasWithNoPredicate != -1) {
1956 // We can't have two aliases from the same mnemonic with no predicate.
1957 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1958 "two MnemonicAliases with the same 'from' mnemonic!");
1959 throw TGError(R->getLoc(), "this is the other MnemonicAlias.");
1962 AliasWithNoPredicate = i;
1965 if (R->getValueAsString("ToMnemonic") == I->first)
1966 throw TGError(R->getLoc(), "MnemonicAlias to the same string");
1968 if (!MatchCode.empty())
1969 MatchCode += "else ";
1970 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1971 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
1974 if (AliasWithNoPredicate != -1) {
1975 Record *R = ToVec[AliasWithNoPredicate];
1976 if (!MatchCode.empty())
1977 MatchCode += "else\n ";
1978 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
1981 MatchCode += "return;";
1983 Cases.push_back(std::make_pair(I->first, MatchCode));
1986 StringMatcher("Mnemonic", Cases, OS).Emit();
1992 static const char *getMinimalTypeForRange(uint64_t Range) {
1993 assert(Range < 0xFFFFFFFFULL && "Enum too large");
2001 static void EmitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
2002 const AsmMatcherInfo &Info, StringRef ClassName) {
2003 // Emit the static custom operand parsing table;
2004 OS << "namespace {\n";
2005 OS << " struct OperandMatchEntry {\n";
2006 OS << " const char *Mnemonic;\n";
2007 OS << " unsigned OperandMask;\n";
2008 OS << " MatchClassKind Class;\n";
2009 OS << " unsigned RequiredFeatures;\n";
2012 OS << " // Predicate for searching for an opcode.\n";
2013 OS << " struct LessOpcodeOperand {\n";
2014 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
2015 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
2017 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
2018 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
2020 OS << " bool operator()(const OperandMatchEntry &LHS,";
2021 OS << " const OperandMatchEntry &RHS) {\n";
2022 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
2026 OS << "} // end anonymous namespace.\n\n";
2028 OS << "static const OperandMatchEntry OperandMatchTable["
2029 << Info.OperandMatchInfo.size() << "] = {\n";
2031 OS << " /* Mnemonic, Operand List Mask, Operand Class, Features */\n";
2032 for (std::vector<OperandMatchEntry>::const_iterator it =
2033 Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end();
2035 const OperandMatchEntry &OMI = *it;
2036 const MatchableInfo &II = *OMI.MI;
2038 OS << " { \"" << II.Mnemonic << "\""
2039 << ", " << OMI.OperandMask;
2042 bool printComma = false;
2043 for (int i = 0, e = 31; i !=e; ++i)
2044 if (OMI.OperandMask & (1 << i)) {
2052 OS << ", " << OMI.CI->Name
2055 // Write the required features mask.
2056 if (!II.RequiredFeatures.empty()) {
2057 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2059 OS << II.RequiredFeatures[i]->getEnumName();
2067 // Emit the operand class switch to call the correct custom parser for
2068 // the found operand class.
2069 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2070 << Target.getName() << ClassName << "::\n"
2071 << "tryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>"
2072 << " &Operands,\n unsigned MCK) {\n\n"
2073 << " switch(MCK) {\n";
2075 for (std::vector<ClassInfo*>::const_iterator it = Info.Classes.begin(),
2076 ie = Info.Classes.end(); it != ie; ++it) {
2077 ClassInfo *CI = *it;
2078 if (CI->ParserMethod.empty())
2080 OS << " case " << CI->Name << ":\n"
2081 << " return " << CI->ParserMethod << "(Operands);\n";
2084 OS << " default:\n";
2085 OS << " return MatchOperand_NoMatch;\n";
2087 OS << " return MatchOperand_NoMatch;\n";
2090 // Emit the static custom operand parser. This code is very similar with
2091 // the other matcher. Also use MatchResultTy here just in case we go for
2092 // a better error handling.
2093 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2094 << Target.getName() << ClassName << "::\n"
2095 << "MatchOperandParserImpl(SmallVectorImpl<MCParsedAsmOperand*>"
2096 << " &Operands,\n StringRef Mnemonic) {\n";
2098 // Emit code to get the available features.
2099 OS << " // Get the current feature set.\n";
2100 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2102 OS << " // Get the next operand index.\n";
2103 OS << " unsigned NextOpNum = Operands.size()-1;\n";
2105 // Emit code to search the table.
2106 OS << " // Search the table.\n";
2107 OS << " std::pair<const OperandMatchEntry*, const OperandMatchEntry*>";
2108 OS << " MnemonicRange =\n";
2109 OS << " std::equal_range(OperandMatchTable, OperandMatchTable+"
2110 << Info.OperandMatchInfo.size() << ", Mnemonic,\n"
2111 << " LessOpcodeOperand());\n\n";
2113 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2114 OS << " return MatchOperand_NoMatch;\n\n";
2116 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2117 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2119 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2120 OS << " assert(Mnemonic == it->Mnemonic);\n\n";
2122 // Emit check that the required features are available.
2123 OS << " // check if the available features match\n";
2124 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2125 << "!= it->RequiredFeatures) {\n";
2126 OS << " continue;\n";
2129 // Emit check to ensure the operand number matches.
2130 OS << " // check if the operand in question has a custom parser.\n";
2131 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2132 OS << " continue;\n\n";
2134 // Emit call to the custom parser method
2135 OS << " // call custom parse method to handle the operand\n";
2136 OS << " OperandMatchResultTy Result = ";
2137 OS << "tryCustomParseOperand(Operands, it->Class);\n";
2138 OS << " if (Result != MatchOperand_NoMatch)\n";
2139 OS << " return Result;\n";
2142 OS << " // Okay, we had no match.\n";
2143 OS << " return MatchOperand_NoMatch;\n";
2147 void AsmMatcherEmitter::run(raw_ostream &OS) {
2148 CodeGenTarget Target(Records);
2149 Record *AsmParser = Target.getAsmParser();
2150 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2152 // Compute the information on the instructions to match.
2153 AsmMatcherInfo Info(AsmParser, Target, Records);
2156 // Sort the instruction table using the partial order on classes. We use
2157 // stable_sort to ensure that ambiguous instructions are still
2158 // deterministically ordered.
2159 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2160 less_ptr<MatchableInfo>());
2162 DEBUG_WITH_TYPE("instruction_info", {
2163 for (std::vector<MatchableInfo*>::iterator
2164 it = Info.Matchables.begin(), ie = Info.Matchables.end();
2169 // Check for ambiguous matchables.
2170 DEBUG_WITH_TYPE("ambiguous_instrs", {
2171 unsigned NumAmbiguous = 0;
2172 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) {
2173 for (unsigned j = i + 1; j != e; ++j) {
2174 MatchableInfo &A = *Info.Matchables[i];
2175 MatchableInfo &B = *Info.Matchables[j];
2177 if (A.CouldMatchAmbiguouslyWith(B)) {
2178 errs() << "warning: ambiguous matchables:\n";
2180 errs() << "\nis incomparable with:\n";
2188 errs() << "warning: " << NumAmbiguous
2189 << " ambiguous matchables!\n";
2192 // Compute the information on the custom operand parsing.
2193 Info.BuildOperandMatchInfo();
2195 // Write the output.
2197 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
2199 // Information for the class declaration.
2200 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2201 OS << "#undef GET_ASSEMBLER_HEADER\n";
2202 OS << " // This should be included into the middle of the declaration of\n";
2203 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
2204 OS << " unsigned ComputeAvailableFeatures(uint64_t FeatureBits) const;\n";
2205 OS << " bool ConvertToMCInst(unsigned Kind, MCInst &Inst, "
2206 << "unsigned Opcode,\n"
2207 << " const SmallVectorImpl<MCParsedAsmOperand*> "
2209 OS << " bool MnemonicIsValid(StringRef Mnemonic);\n";
2210 OS << " unsigned MatchInstructionImpl(\n";
2211 OS << " const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2212 OS << " MCInst &Inst, unsigned &ErrorInfo);\n";
2214 if (Info.OperandMatchInfo.size()) {
2215 OS << "\n enum OperandMatchResultTy {\n";
2216 OS << " MatchOperand_Success, // operand matched successfully\n";
2217 OS << " MatchOperand_NoMatch, // operand did not match\n";
2218 OS << " MatchOperand_ParseFail // operand matched but had errors\n";
2220 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
2221 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2222 OS << " StringRef Mnemonic);\n";
2224 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
2225 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2226 OS << " unsigned MCK);\n\n";
2229 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2231 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2232 OS << "#undef GET_REGISTER_MATCHER\n\n";
2234 // Emit the subtarget feature enumeration.
2235 EmitSubtargetFeatureFlagEnumeration(Info, OS);
2237 // Emit the function to match a register name to number.
2238 EmitMatchRegisterName(Target, AsmParser, OS);
2240 OS << "#endif // GET_REGISTER_MATCHER\n\n";
2243 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2244 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
2246 // Generate the function that remaps for mnemonic aliases.
2247 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
2249 // Generate the unified function to convert operands into an MCInst.
2250 EmitConvertToMCInst(Target, ClassName, Info.Matchables, OS);
2252 // Emit the enumeration for classes which participate in matching.
2253 EmitMatchClassEnumeration(Target, Info.Classes, OS);
2255 // Emit the routine to match token strings to their match class.
2256 EmitMatchTokenString(Target, Info.Classes, OS);
2258 // Emit the subclass predicate routine.
2259 EmitIsSubclass(Target, Info.Classes, OS);
2261 // Emit the routine to validate an operand against a match class.
2262 EmitValidateOperandClass(Info, OS);
2264 // Emit the available features compute function.
2265 EmitComputeAvailableFeatures(Info, OS);
2268 size_t MaxNumOperands = 0;
2269 for (std::vector<MatchableInfo*>::const_iterator it =
2270 Info.Matchables.begin(), ie = Info.Matchables.end();
2272 MaxNumOperands = std::max(MaxNumOperands, (*it)->AsmOperands.size());
2274 // Emit the static match table; unused classes get initalized to 0 which is
2275 // guaranteed to be InvalidMatchClass.
2277 // FIXME: We can reduce the size of this table very easily. First, we change
2278 // it so that store the kinds in separate bit-fields for each index, which
2279 // only needs to be the max width used for classes at that index (we also need
2280 // to reject based on this during classification). If we then make sure to
2281 // order the match kinds appropriately (putting mnemonics last), then we
2282 // should only end up using a few bits for each class, especially the ones
2283 // following the mnemonic.
2284 OS << "namespace {\n";
2285 OS << " struct MatchEntry {\n";
2286 OS << " unsigned Opcode;\n";
2287 OS << " const char *Mnemonic;\n";
2288 OS << " " << getMinimalTypeForRange(Info.Matchables.size())
2290 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2291 << " Classes[" << MaxNumOperands << "];\n";
2292 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2293 << " RequiredFeatures;\n";
2296 OS << " // Predicate for searching for an opcode.\n";
2297 OS << " struct LessOpcode {\n";
2298 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
2299 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
2301 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
2302 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
2304 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
2305 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
2309 OS << "} // end anonymous namespace.\n\n";
2311 OS << "static const MatchEntry MatchTable["
2312 << Info.Matchables.size() << "] = {\n";
2314 for (std::vector<MatchableInfo*>::const_iterator it =
2315 Info.Matchables.begin(), ie = Info.Matchables.end();
2317 MatchableInfo &II = **it;
2319 OS << " { " << Target.getName() << "::"
2320 << II.getResultInst()->TheDef->getName() << ", \"" << II.Mnemonic << "\""
2321 << ", " << II.ConversionFnKind << ", { ";
2322 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
2323 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
2326 OS << Op.Class->Name;
2330 // Write the required features mask.
2331 if (!II.RequiredFeatures.empty()) {
2332 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2334 OS << II.RequiredFeatures[i]->getEnumName();
2344 // A method to determine if a mnemonic is in the list.
2345 OS << "bool " << Target.getName() << ClassName << "::\n"
2346 << "MnemonicIsValid(StringRef Mnemonic) {\n";
2347 OS << " // Search the table.\n";
2348 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2349 OS << " std::equal_range(MatchTable, MatchTable+"
2350 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n";
2351 OS << " return MnemonicRange.first != MnemonicRange.second;\n";
2354 // Finally, build the match function.
2356 << Target.getName() << ClassName << "::\n"
2357 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
2359 OS << " MCInst &Inst, unsigned &ErrorInfo) {\n";
2361 // Emit code to get the available features.
2362 OS << " // Get the current feature set.\n";
2363 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2365 OS << " // Get the instruction mnemonic, which is the first token.\n";
2366 OS << " StringRef Mnemonic = ((" << Target.getName()
2367 << "Operand*)Operands[0])->getToken();\n\n";
2369 if (HasMnemonicAliases) {
2370 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
2371 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
2374 // Emit code to compute the class list for this operand vector.
2375 OS << " // Eliminate obvious mismatches.\n";
2376 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
2377 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
2378 OS << " return Match_InvalidOperand;\n";
2381 OS << " // Some state to try to produce better error messages.\n";
2382 OS << " bool HadMatchOtherThanFeatures = false;\n";
2383 OS << " bool HadMatchOtherThanPredicate = false;\n";
2384 OS << " unsigned RetCode = Match_InvalidOperand;\n";
2385 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
2386 OS << " // wrong for all instances of the instruction.\n";
2387 OS << " ErrorInfo = ~0U;\n";
2389 // Emit code to search the table.
2390 OS << " // Search the table.\n";
2391 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2392 OS << " std::equal_range(MatchTable, MatchTable+"
2393 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n";
2395 OS << " // Return a more specific error code if no mnemonics match.\n";
2396 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2397 OS << " return Match_MnemonicFail;\n\n";
2399 OS << " for (const MatchEntry *it = MnemonicRange.first, "
2400 << "*ie = MnemonicRange.second;\n";
2401 OS << " it != ie; ++it) {\n";
2403 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2404 OS << " assert(Mnemonic == it->Mnemonic);\n";
2406 // Emit check that the subclasses match.
2407 OS << " bool OperandsValid = true;\n";
2408 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
2409 OS << " if (i + 1 >= Operands.size()) {\n";
2410 OS << " OperandsValid = (it->Classes[i] == " <<"InvalidMatchClass);\n";
2413 OS << " if (validateOperandClass(Operands[i+1], "
2414 "(MatchClassKind)it->Classes[i]))\n";
2415 OS << " continue;\n";
2416 OS << " // If this operand is broken for all of the instances of this\n";
2417 OS << " // mnemonic, keep track of it so we can report loc info.\n";
2418 OS << " if (it == MnemonicRange.first || ErrorInfo <= i+1)\n";
2419 OS << " ErrorInfo = i+1;\n";
2420 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
2421 OS << " OperandsValid = false;\n";
2425 OS << " if (!OperandsValid) continue;\n";
2427 // Emit check that the required features are available.
2428 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2429 << "!= it->RequiredFeatures) {\n";
2430 OS << " HadMatchOtherThanFeatures = true;\n";
2431 OS << " continue;\n";
2434 OS << " // We have selected a definite instruction, convert the parsed\n"
2435 << " // operands into the appropriate MCInst.\n";
2436 OS << " if (!ConvertToMCInst(it->ConvertFn, Inst,\n"
2437 << " it->Opcode, Operands))\n";
2438 OS << " return Match_ConversionFail;\n";
2441 // Verify the instruction with the target-specific match predicate function.
2442 OS << " // We have a potential match. Check the target predicate to\n"
2443 << " // handle any context sensitive constraints.\n"
2444 << " unsigned MatchResult;\n"
2445 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
2446 << " Match_Success) {\n"
2447 << " Inst.clear();\n"
2448 << " RetCode = MatchResult;\n"
2449 << " HadMatchOtherThanPredicate = true;\n"
2453 // Call the post-processing function, if used.
2454 std::string InsnCleanupFn =
2455 AsmParser->getValueAsString("AsmParserInstCleanup");
2456 if (!InsnCleanupFn.empty())
2457 OS << " " << InsnCleanupFn << "(Inst);\n";
2459 OS << " return Match_Success;\n";
2462 OS << " // Okay, we had no match. Try to return a useful error code.\n";
2463 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)";
2464 OS << " return RetCode;\n";
2465 OS << " return Match_MissingFeature;\n";
2468 if (Info.OperandMatchInfo.size())
2469 EmitCustomOperandParsing(OS, Target, Info, ClassName);
2471 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";