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.
13 // The input to the target specific matcher is a list of literal tokens and
14 // operands. The target specific parser should generally eliminate any syntax
15 // which is not relevant for matching; for example, comma tokens should have
16 // already been consumed and eliminated by the parser. Most instructions will
17 // end up with a single literal token (the instruction name) and some number of
20 // Some example inputs, for X86:
21 // 'addl' (immediate ...) (register ...)
22 // 'add' (immediate ...) (memory ...)
25 // The assembly matcher is responsible for converting this input into a precise
26 // machine instruction (i.e., an instruction with a well defined encoding). This
27 // mapping has several properties which complicate matching:
29 // - It may be ambiguous; many architectures can legally encode particular
30 // variants of an instruction in different ways (for example, using a smaller
31 // encoding for small immediates). Such ambiguities should never be
32 // arbitrarily resolved by the assembler, the assembler is always responsible
33 // for choosing the "best" available instruction.
35 // - It may depend on the subtarget or the assembler context. Instructions
36 // which are invalid for the current mode, but otherwise unambiguous (e.g.,
37 // an SSE instruction in a file being assembled for i486) should be accepted
38 // and rejected by the assembler front end. However, if the proper encoding
39 // for an instruction is dependent on the assembler context then the matcher
40 // is responsible for selecting the correct machine instruction for the
43 // The core matching algorithm attempts to exploit the regularity in most
44 // instruction sets to quickly determine the set of possibly matching
45 // instructions, and the simplify the generated code. Additionally, this helps
46 // to ensure that the ambiguities are intentionally resolved by the user.
48 // The matching is divided into two distinct phases:
50 // 1. Classification: Each operand is mapped to the unique set which (a)
51 // contains it, and (b) is the largest such subset for which a single
52 // instruction could match all members.
54 // For register classes, we can generate these subgroups automatically. For
55 // arbitrary operands, we expect the user to define the classes and their
56 // relations to one another (for example, 8-bit signed immediates as a
57 // subset of 32-bit immediates).
59 // By partitioning the operands in this way, we guarantee that for any
60 // tuple of classes, any single instruction must match either all or none
61 // of the sets of operands which could classify to that tuple.
63 // In addition, the subset relation amongst classes induces a partial order
64 // on such tuples, which we use to resolve ambiguities.
66 // FIXME: What do we do if a crazy case shows up where this is the wrong
69 // 2. The input can now be treated as a tuple of classes (static tokens are
70 // simple singleton sets). Each such tuple should generally map to a single
71 // instruction (we currently ignore cases where this isn't true, whee!!!),
72 // which we can emit a simple matcher for.
74 //===----------------------------------------------------------------------===//
76 #include "AsmMatcherEmitter.h"
77 #include "CodeGenTarget.h"
79 #include "StringMatcher.h"
80 #include "llvm/ADT/OwningPtr.h"
81 #include "llvm/ADT/SmallPtrSet.h"
82 #include "llvm/ADT/SmallVector.h"
83 #include "llvm/ADT/STLExtras.h"
84 #include "llvm/ADT/StringExtras.h"
85 #include "llvm/Support/CommandLine.h"
86 #include "llvm/Support/Debug.h"
92 static cl::opt<std::string>
93 MatchPrefix("match-prefix", cl::init(""),
94 cl::desc("Only match instructions with the given prefix"));
96 /// TokenizeAsmString - Tokenize a simplified assembly string.
97 static void TokenizeAsmString(StringRef AsmString,
98 SmallVectorImpl<StringRef> &Tokens) {
101 for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {
102 switch (AsmString[i]) {
111 Tokens.push_back(AsmString.slice(Prev, i));
114 if (!isspace(AsmString[i]) && AsmString[i] != ',')
115 Tokens.push_back(AsmString.substr(i, 1));
121 Tokens.push_back(AsmString.slice(Prev, i));
125 assert(i != AsmString.size() && "Invalid quoted character");
126 Tokens.push_back(AsmString.substr(i, 1));
131 // If this isn't "${", treat like a normal token.
132 if (i + 1 == AsmString.size() || AsmString[i + 1] != '{') {
134 Tokens.push_back(AsmString.slice(Prev, i));
142 Tokens.push_back(AsmString.slice(Prev, i));
146 StringRef::iterator End =
147 std::find(AsmString.begin() + i, AsmString.end(), '}');
148 assert(End != AsmString.end() && "Missing brace in operand reference!");
149 size_t EndPos = End - AsmString.begin();
150 Tokens.push_back(AsmString.slice(i, EndPos+1));
158 Tokens.push_back(AsmString.slice(Prev, i));
168 if (InTok && Prev != AsmString.size())
169 Tokens.push_back(AsmString.substr(Prev));
174 class AsmMatcherInfo;
175 struct SubtargetFeatureInfo;
177 /// ClassInfo - Helper class for storing the information about a particular
178 /// class of operands which can be matched.
181 /// Invalid kind, for use as a sentinel value.
184 /// The class for a particular token.
187 /// The (first) register class, subsequent register classes are
188 /// RegisterClass0+1, and so on.
191 /// The (first) user defined class, subsequent user defined classes are
192 /// UserClass0+1, and so on.
196 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
197 /// N) for the Nth user defined class.
200 /// SuperClasses - The super classes of this class. Note that for simplicities
201 /// sake user operands only record their immediate super class, while register
202 /// operands include all superclasses.
203 std::vector<ClassInfo*> SuperClasses;
205 /// Name - The full class name, suitable for use in an enum.
208 /// ClassName - The unadorned generic name for this class (e.g., Token).
209 std::string ClassName;
211 /// ValueName - The name of the value this class represents; for a token this
212 /// is the literal token string, for an operand it is the TableGen class (or
213 /// empty if this is a derived class).
214 std::string ValueName;
216 /// PredicateMethod - The name of the operand method to test whether the
217 /// operand matches this class; this is not valid for Token or register kinds.
218 std::string PredicateMethod;
220 /// RenderMethod - The name of the operand method to add this operand to an
221 /// MCInst; this is not valid for Token or register kinds.
222 std::string RenderMethod;
224 /// For register classes, the records for all the registers in this class.
225 std::set<Record*> Registers;
228 /// isRegisterClass() - Check if this is a register class.
229 bool isRegisterClass() const {
230 return Kind >= RegisterClass0 && Kind < UserClass0;
233 /// isUserClass() - Check if this is a user defined class.
234 bool isUserClass() const {
235 return Kind >= UserClass0;
238 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
239 /// are related if they are in the same class hierarchy.
240 bool isRelatedTo(const ClassInfo &RHS) const {
241 // Tokens are only related to tokens.
242 if (Kind == Token || RHS.Kind == Token)
243 return Kind == Token && RHS.Kind == Token;
245 // Registers classes are only related to registers classes, and only if
246 // their intersection is non-empty.
247 if (isRegisterClass() || RHS.isRegisterClass()) {
248 if (!isRegisterClass() || !RHS.isRegisterClass())
251 std::set<Record*> Tmp;
252 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
253 std::set_intersection(Registers.begin(), Registers.end(),
254 RHS.Registers.begin(), RHS.Registers.end(),
260 // Otherwise we have two users operands; they are related if they are in the
261 // same class hierarchy.
263 // FIXME: This is an oversimplification, they should only be related if they
264 // intersect, however we don't have that information.
265 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
266 const ClassInfo *Root = this;
267 while (!Root->SuperClasses.empty())
268 Root = Root->SuperClasses.front();
270 const ClassInfo *RHSRoot = &RHS;
271 while (!RHSRoot->SuperClasses.empty())
272 RHSRoot = RHSRoot->SuperClasses.front();
274 return Root == RHSRoot;
277 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
278 bool isSubsetOf(const ClassInfo &RHS) const {
279 // This is a subset of RHS if it is the same class...
283 // ... or if any of its super classes are a subset of RHS.
284 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
285 ie = SuperClasses.end(); it != ie; ++it)
286 if ((*it)->isSubsetOf(RHS))
292 /// operator< - Compare two classes.
293 bool operator<(const ClassInfo &RHS) const {
297 // Unrelated classes can be ordered by kind.
298 if (!isRelatedTo(RHS))
299 return Kind < RHS.Kind;
303 assert(0 && "Invalid kind!");
305 // Tokens are comparable by value.
307 // FIXME: Compare by enum value.
308 return ValueName < RHS.ValueName;
311 // This class preceeds the RHS if it is a proper subset of the RHS.
314 if (RHS.isSubsetOf(*this))
317 // Otherwise, order by name to ensure we have a total ordering.
318 return ValueName < RHS.ValueName;
323 /// MatchableInfo - Helper class for storing the necessary information for an
324 /// instruction or alias which is capable of being matched.
325 struct MatchableInfo {
327 /// The unique class instance this operand should match.
330 /// The original operand this corresponds to, if any.
331 const CGIOperandList::OperandInfo *OperandInfo;
333 Operand(ClassInfo *C, const CGIOperandList::OperandInfo *OpInfo)
334 : Class(C), OperandInfo(OpInfo) {}
337 /// InstrName - The target name for this instruction.
338 std::string InstrName;
340 Record *const TheDef;
341 const CGIOperandList &OperandList;
343 /// AsmString - The assembly string for this instruction (with variants
345 std::string AsmString;
347 /// Tokens - The tokenized assembly pattern that this instruction matches.
348 SmallVector<StringRef, 4> Tokens;
350 /// Operands - The operands that this instruction matches.
351 SmallVector<Operand, 4> Operands;
353 /// Predicates - The required subtarget features to match this instruction.
354 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
356 /// ConversionFnKind - The enum value which is passed to the generated
357 /// ConvertToMCInst to convert parsed operands into an MCInst for this
359 std::string ConversionFnKind;
361 MatchableInfo(const CodeGenInstruction &CGI)
362 : TheDef(CGI.TheDef), OperandList(CGI.Operands), AsmString(CGI.AsmString) {
363 InstrName = TheDef->getName();
366 MatchableInfo(const CodeGenInstAlias *Alias)
367 : TheDef(Alias->TheDef), OperandList(Alias->Operands),
368 AsmString(Alias->AsmString) {
371 DefInit *DI = dynamic_cast<DefInit*>(Alias->Result->getOperator());
374 InstrName = DI->getDef()->getName();
377 void Initialize(const AsmMatcherInfo &Info,
378 SmallPtrSet<Record*, 16> &SingletonRegisters);
380 /// Validate - Return true if this matchable is a valid thing to match against
381 /// and perform a bunch of validity checking.
382 bool Validate(StringRef CommentDelimiter, bool Hack) const;
384 /// getSingletonRegisterForToken - If the specified token is a singleton
385 /// register, return the Record for it, otherwise return null.
386 Record *getSingletonRegisterForToken(unsigned i,
387 const AsmMatcherInfo &Info) const;
389 /// operator< - Compare two matchables.
390 bool operator<(const MatchableInfo &RHS) const {
391 // The primary comparator is the instruction mnemonic.
392 if (Tokens[0] != RHS.Tokens[0])
393 return Tokens[0] < RHS.Tokens[0];
395 if (Operands.size() != RHS.Operands.size())
396 return Operands.size() < RHS.Operands.size();
398 // Compare lexicographically by operand. The matcher validates that other
399 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
400 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
401 if (*Operands[i].Class < *RHS.Operands[i].Class)
403 if (*RHS.Operands[i].Class < *Operands[i].Class)
410 /// CouldMatchAmiguouslyWith - Check whether this matchable could
411 /// ambiguously match the same set of operands as \arg RHS (without being a
412 /// strictly superior match).
413 bool CouldMatchAmiguouslyWith(const MatchableInfo &RHS) {
414 // The primary comparator is the instruction mnemonic.
415 if (Tokens[0] != RHS.Tokens[0])
418 // The number of operands is unambiguous.
419 if (Operands.size() != RHS.Operands.size())
422 // Otherwise, make sure the ordering of the two instructions is unambiguous
423 // by checking that either (a) a token or operand kind discriminates them,
424 // or (b) the ordering among equivalent kinds is consistent.
426 // Tokens and operand kinds are unambiguous (assuming a correct target
428 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
429 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
430 Operands[i].Class->Kind == ClassInfo::Token)
431 if (*Operands[i].Class < *RHS.Operands[i].Class ||
432 *RHS.Operands[i].Class < *Operands[i].Class)
435 // Otherwise, this operand could commute if all operands are equivalent, or
436 // there is a pair of operands that compare less than and a pair that
437 // compare greater than.
438 bool HasLT = false, HasGT = false;
439 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
440 if (*Operands[i].Class < *RHS.Operands[i].Class)
442 if (*RHS.Operands[i].Class < *Operands[i].Class)
446 return !(HasLT ^ HasGT);
452 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
453 /// feature which participates in instruction matching.
454 struct SubtargetFeatureInfo {
455 /// \brief The predicate record for this feature.
458 /// \brief An unique index assigned to represent this feature.
461 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
463 /// \brief The name of the enumerated constant identifying this feature.
464 std::string getEnumName() const {
465 return "Feature_" + TheDef->getName();
469 class AsmMatcherInfo {
471 /// The tablegen AsmParser record.
474 /// Target - The target information.
475 CodeGenTarget &Target;
477 /// The AsmParser "RegisterPrefix" value.
478 std::string RegisterPrefix;
480 /// The classes which are needed for matching.
481 std::vector<ClassInfo*> Classes;
483 /// The information on the matchables to match.
484 std::vector<MatchableInfo*> Matchables;
486 /// Map of Register records to their class information.
487 std::map<Record*, ClassInfo*> RegisterClasses;
489 /// Map of Predicate records to their subtarget information.
490 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
493 /// Map of token to class information which has already been constructed.
494 std::map<std::string, ClassInfo*> TokenClasses;
496 /// Map of RegisterClass records to their class information.
497 std::map<Record*, ClassInfo*> RegisterClassClasses;
499 /// Map of AsmOperandClass records to their class information.
500 std::map<Record*, ClassInfo*> AsmOperandClasses;
503 /// getTokenClass - Lookup or create the class for the given token.
504 ClassInfo *getTokenClass(StringRef Token);
506 /// getOperandClass - Lookup or create the class for the given operand.
507 ClassInfo *getOperandClass(StringRef Token,
508 const CGIOperandList::OperandInfo &OI);
510 /// BuildRegisterClasses - Build the ClassInfo* instances for register
512 void BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
514 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
516 void BuildOperandClasses();
519 AsmMatcherInfo(Record *AsmParser, CodeGenTarget &Target);
521 /// BuildInfo - Construct the various tables used during matching.
524 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
526 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
527 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
528 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
529 SubtargetFeatures.find(Def);
530 return I == SubtargetFeatures.end() ? 0 : I->second;
536 void MatchableInfo::dump() {
537 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
539 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
546 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
547 Operand &Op = Operands[i];
548 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
549 if (Op.Class->Kind == ClassInfo::Token) {
550 errs() << '\"' << Tokens[i] << "\"\n";
554 if (!Op.OperandInfo) {
555 errs() << "(singleton register)\n";
559 const CGIOperandList::OperandInfo &OI = *Op.OperandInfo;
560 errs() << OI.Name << " " << OI.Rec->getName()
561 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
565 void MatchableInfo::Initialize(const AsmMatcherInfo &Info,
566 SmallPtrSet<Record*, 16> &SingletonRegisters) {
567 // TODO: Eventually support asmparser for Variant != 0.
568 AsmString = CodeGenInstruction::FlattenAsmStringVariants(AsmString, 0);
570 TokenizeAsmString(AsmString, Tokens);
572 // Compute the require features.
573 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates");
574 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
575 if (SubtargetFeatureInfo *Feature =
576 Info.getSubtargetFeature(Predicates[i]))
577 RequiredFeatures.push_back(Feature);
579 // Collect singleton registers, if used.
580 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
581 if (Record *Reg = getSingletonRegisterForToken(i, Info))
582 SingletonRegisters.insert(Reg);
587 /// getRegisterRecord - Get the register record for \arg name, or 0.
588 static Record *getRegisterRecord(CodeGenTarget &Target, StringRef Name) {
589 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
590 const CodeGenRegister &Reg = Target.getRegisters()[i];
591 if (Name == Reg.TheDef->getValueAsString("AsmName"))
598 bool MatchableInfo::Validate(StringRef CommentDelimiter, bool Hack) const {
599 // Reject matchables with no .s string.
600 if (AsmString.empty())
601 throw TGError(TheDef->getLoc(), "instruction with empty asm string");
603 // Reject any matchables with a newline in them, they should be marked
604 // isCodeGenOnly if they are pseudo instructions.
605 if (AsmString.find('\n') != std::string::npos)
606 throw TGError(TheDef->getLoc(),
607 "multiline instruction is not valid for the asmparser, "
608 "mark it isCodeGenOnly");
610 // Remove comments from the asm string. We know that the asmstring only
612 if (!CommentDelimiter.empty() &&
613 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
614 throw TGError(TheDef->getLoc(),
615 "asmstring for instruction has comment character in it, "
616 "mark it isCodeGenOnly");
618 // Reject matchables with operand modifiers, these aren't something we can
619 /// handle, the target should be refactored to use operands instead of
622 // Also, check for instructions which reference the operand multiple times;
623 // this implies a constraint we would not honor.
624 std::set<std::string> OperandNames;
625 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
626 if (Tokens[i][0] == '$' && Tokens[i].find(':') != StringRef::npos)
627 throw TGError(TheDef->getLoc(),
628 "matchable with operand modifier '" + Tokens[i].str() +
629 "' not supported by asm matcher. Mark isCodeGenOnly!");
631 // Verify that any operand is only mentioned once.
632 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
634 throw TGError(TheDef->getLoc(),
635 "ERROR: matchable with tied operand '" + Tokens[i].str() +
636 "' can never be matched!");
637 // FIXME: Should reject these. The ARM backend hits this with $lane in a
638 // bunch of instructions. It is unclear what the right answer is.
640 errs() << "warning: '" << InstrName << "': "
641 << "ignoring instruction with tied operand '"
642 << Tokens[i].str() << "'\n";
652 /// getSingletonRegisterForToken - If the specified token is a singleton
653 /// register, return the register name, otherwise return a null StringRef.
654 Record *MatchableInfo::
655 getSingletonRegisterForToken(unsigned i, const AsmMatcherInfo &Info) const {
656 StringRef Tok = Tokens[i];
657 if (!Tok.startswith(Info.RegisterPrefix))
660 StringRef RegName = Tok.substr(Info.RegisterPrefix.size());
661 if (Record *Rec = getRegisterRecord(Info.Target, RegName))
664 // If there is no register prefix (i.e. "%" in "%eax"), then this may
665 // be some random non-register token, just ignore it.
666 if (Info.RegisterPrefix.empty())
669 std::string Err = "unable to find register for '" + RegName.str() +
670 "' (which matches register prefix)";
671 throw TGError(TheDef->getLoc(), Err);
675 static std::string getEnumNameForToken(StringRef Str) {
678 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
680 case '*': Res += "_STAR_"; break;
681 case '%': Res += "_PCT_"; break;
682 case ':': Res += "_COLON_"; break;
687 Res += "_" + utostr((unsigned) *it) + "_";
694 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
695 ClassInfo *&Entry = TokenClasses[Token];
698 Entry = new ClassInfo();
699 Entry->Kind = ClassInfo::Token;
700 Entry->ClassName = "Token";
701 Entry->Name = "MCK_" + getEnumNameForToken(Token);
702 Entry->ValueName = Token;
703 Entry->PredicateMethod = "<invalid>";
704 Entry->RenderMethod = "<invalid>";
705 Classes.push_back(Entry);
712 AsmMatcherInfo::getOperandClass(StringRef Token,
713 const CGIOperandList::OperandInfo &OI) {
714 if (OI.Rec->isSubClassOf("RegisterClass")) {
715 ClassInfo *CI = RegisterClassClasses[OI.Rec];
718 throw TGError(OI.Rec->getLoc(), "register class has no class info!");
723 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
724 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
725 ClassInfo *CI = AsmOperandClasses[MatchClass];
728 throw TGError(OI.Rec->getLoc(), "operand has no match class!");
733 void AsmMatcherInfo::
734 BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
735 std::vector<CodeGenRegisterClass> RegisterClasses;
736 std::vector<CodeGenRegister> Registers;
738 RegisterClasses = Target.getRegisterClasses();
739 Registers = Target.getRegisters();
741 // The register sets used for matching.
742 std::set< std::set<Record*> > RegisterSets;
744 // Gather the defined sets.
745 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
746 ie = RegisterClasses.end(); it != ie; ++it)
747 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
748 it->Elements.end()));
750 // Add any required singleton sets.
751 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
752 ie = SingletonRegisters.end(); it != ie; ++it) {
754 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
757 // Introduce derived sets where necessary (when a register does not determine
758 // a unique register set class), and build the mapping of registers to the set
759 // they should classify to.
760 std::map<Record*, std::set<Record*> > RegisterMap;
761 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
762 ie = Registers.end(); it != ie; ++it) {
763 CodeGenRegister &CGR = *it;
764 // Compute the intersection of all sets containing this register.
765 std::set<Record*> ContainingSet;
767 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
768 ie = RegisterSets.end(); it != ie; ++it) {
769 if (!it->count(CGR.TheDef))
772 if (ContainingSet.empty()) {
775 std::set<Record*> Tmp;
776 std::swap(Tmp, ContainingSet);
777 std::insert_iterator< std::set<Record*> > II(ContainingSet,
778 ContainingSet.begin());
779 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
784 if (!ContainingSet.empty()) {
785 RegisterSets.insert(ContainingSet);
786 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
790 // Construct the register classes.
791 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
793 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
794 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
795 ClassInfo *CI = new ClassInfo();
796 CI->Kind = ClassInfo::RegisterClass0 + Index;
797 CI->ClassName = "Reg" + utostr(Index);
798 CI->Name = "MCK_Reg" + utostr(Index);
800 CI->PredicateMethod = ""; // unused
801 CI->RenderMethod = "addRegOperands";
803 Classes.push_back(CI);
804 RegisterSetClasses.insert(std::make_pair(*it, CI));
807 // Find the superclasses; we could compute only the subgroup lattice edges,
808 // but there isn't really a point.
809 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
810 ie = RegisterSets.end(); it != ie; ++it) {
811 ClassInfo *CI = RegisterSetClasses[*it];
812 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
813 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
815 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
816 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
819 // Name the register classes which correspond to a user defined RegisterClass.
820 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
821 ie = RegisterClasses.end(); it != ie; ++it) {
822 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
823 it->Elements.end())];
824 if (CI->ValueName.empty()) {
825 CI->ClassName = it->getName();
826 CI->Name = "MCK_" + it->getName();
827 CI->ValueName = it->getName();
829 CI->ValueName = CI->ValueName + "," + it->getName();
831 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
834 // Populate the map for individual registers.
835 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
836 ie = RegisterMap.end(); it != ie; ++it)
837 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
839 // Name the register classes which correspond to singleton registers.
840 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
841 ie = SingletonRegisters.end(); it != ie; ++it) {
843 ClassInfo *CI = this->RegisterClasses[Rec];
844 assert(CI && "Missing singleton register class info!");
846 if (CI->ValueName.empty()) {
847 CI->ClassName = Rec->getName();
848 CI->Name = "MCK_" + Rec->getName();
849 CI->ValueName = Rec->getName();
851 CI->ValueName = CI->ValueName + "," + Rec->getName();
855 void AsmMatcherInfo::BuildOperandClasses() {
856 std::vector<Record*> AsmOperands =
857 Records.getAllDerivedDefinitions("AsmOperandClass");
859 // Pre-populate AsmOperandClasses map.
860 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
861 ie = AsmOperands.end(); it != ie; ++it)
862 AsmOperandClasses[*it] = new ClassInfo();
865 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
866 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
867 ClassInfo *CI = AsmOperandClasses[*it];
868 CI->Kind = ClassInfo::UserClass0 + Index;
870 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
871 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
872 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
874 PrintError((*it)->getLoc(), "Invalid super class reference!");
878 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
880 PrintError((*it)->getLoc(), "Invalid super class reference!");
882 CI->SuperClasses.push_back(SC);
884 CI->ClassName = (*it)->getValueAsString("Name");
885 CI->Name = "MCK_" + CI->ClassName;
886 CI->ValueName = (*it)->getName();
888 // Get or construct the predicate method name.
889 Init *PMName = (*it)->getValueInit("PredicateMethod");
890 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
891 CI->PredicateMethod = SI->getValue();
893 assert(dynamic_cast<UnsetInit*>(PMName) &&
894 "Unexpected PredicateMethod field!");
895 CI->PredicateMethod = "is" + CI->ClassName;
898 // Get or construct the render method name.
899 Init *RMName = (*it)->getValueInit("RenderMethod");
900 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
901 CI->RenderMethod = SI->getValue();
903 assert(dynamic_cast<UnsetInit*>(RMName) &&
904 "Unexpected RenderMethod field!");
905 CI->RenderMethod = "add" + CI->ClassName + "Operands";
908 AsmOperandClasses[*it] = CI;
909 Classes.push_back(CI);
913 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser, CodeGenTarget &target)
914 : AsmParser(asmParser), Target(target),
915 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix")) {
919 void AsmMatcherInfo::BuildInfo() {
920 // Build information about all of the AssemblerPredicates.
921 std::vector<Record*> AllPredicates =
922 Records.getAllDerivedDefinitions("Predicate");
923 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
924 Record *Pred = AllPredicates[i];
925 // Ignore predicates that are not intended for the assembler.
926 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
929 if (Pred->getName().empty())
930 throw TGError(Pred->getLoc(), "Predicate has no name!");
932 unsigned FeatureNo = SubtargetFeatures.size();
933 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
934 assert(FeatureNo < 32 && "Too many subtarget features!");
937 StringRef CommentDelimiter = AsmParser->getValueAsString("CommentDelimiter");
939 // Parse the instructions; we need to do this first so that we can gather the
940 // singleton register classes.
941 SmallPtrSet<Record*, 16> SingletonRegisters;
942 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
943 E = Target.inst_end(); I != E; ++I) {
944 const CodeGenInstruction &CGI = **I;
946 // If the tblgen -match-prefix option is specified (for tblgen hackers),
947 // filter the set of instructions we consider.
948 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
951 // Ignore "codegen only" instructions.
952 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
955 OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
957 II->Initialize(*this, SingletonRegisters);
959 // Ignore instructions which shouldn't be matched and diagnose invalid
960 // instruction definitions with an error.
961 if (!II->Validate(CommentDelimiter, true))
964 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
966 // FIXME: This is a total hack.
967 if (StringRef(II->InstrName).startswith("Int_") ||
968 StringRef(II->InstrName).endswith("_Int"))
971 Matchables.push_back(II.take());
974 // Parse all of the InstAlias definitions and stick them in the list of
976 std::vector<Record*> AllInstAliases =
977 Records.getAllDerivedDefinitions("InstAlias");
978 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
979 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i]);
981 OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
983 II->Initialize(*this, SingletonRegisters);
985 // Validate the alias definitions.
986 II->Validate(CommentDelimiter, false);
988 Matchables.push_back(II.take());
991 // Build info for the register classes.
992 BuildRegisterClasses(SingletonRegisters);
994 // Build info for the user defined assembly operand classes.
995 BuildOperandClasses();
997 // Build the information about matchables.
998 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(),
999 ie = Matchables.end(); it != ie; ++it) {
1000 MatchableInfo *II = *it;
1002 // The first token of the instruction is the mnemonic, which must be a
1003 // simple string, not a $foo variable or a singleton register.
1004 assert(!II->Tokens.empty() && "Instruction has no tokens?");
1005 StringRef Mnemonic = II->Tokens[0];
1006 if (Mnemonic[0] == '$' || II->getSingletonRegisterForToken(0, *this))
1007 throw TGError(II->TheDef->getLoc(),
1008 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
1010 // Parse the tokens after the mnemonic.
1011 for (unsigned i = 1, e = II->Tokens.size(); i != e; ++i) {
1012 StringRef Token = II->Tokens[i];
1014 // Check for singleton registers.
1015 if (Record *RegRecord = II->getSingletonRegisterForToken(i, *this)) {
1016 MatchableInfo::Operand Op(RegisterClasses[RegRecord], 0);
1017 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1018 "Unexpected class for singleton register");
1019 II->Operands.push_back(Op);
1023 // Check for simple tokens.
1024 if (Token[0] != '$') {
1025 II->Operands.push_back(MatchableInfo::Operand(getTokenClass(Token), 0));
1029 // Otherwise this is an operand reference.
1030 StringRef OperandName;
1031 if (Token[1] == '{')
1032 OperandName = Token.substr(2, Token.size() - 3);
1034 OperandName = Token.substr(1);
1036 // Map this token to an operand. FIXME: Move elsewhere.
1038 if (!II->OperandList.hasOperandNamed(OperandName, Idx))
1039 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1040 OperandName.str() + "'");
1042 // FIXME: This is annoying, the named operand may be tied (e.g.,
1043 // XCHG8rm). What we want is the untied operand, which we now have to
1044 // grovel for. Only worry about this for single entry operands, we have to
1045 // clean this up anyway.
1046 const CGIOperandList::OperandInfo *OI = &II->OperandList[Idx];
1047 if (OI->Constraints[0].isTied()) {
1048 unsigned TiedOp = OI->Constraints[0].getTiedOperand();
1050 // The tied operand index is an MIOperand index, find the operand that
1052 for (unsigned i = 0, e = II->OperandList.size(); i != e; ++i) {
1053 if (II->OperandList[i].MIOperandNo == TiedOp) {
1054 OI = &II->OperandList[i];
1059 assert(OI && "Unable to find tied operand target!");
1062 II->Operands.push_back(MatchableInfo::Operand(getOperandClass(Token,
1067 // Reorder classes so that classes preceed super classes.
1068 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
1071 static std::pair<unsigned, unsigned> *
1072 GetTiedOperandAtIndex(SmallVectorImpl<std::pair<unsigned, unsigned> > &List,
1074 for (unsigned i = 0, e = List.size(); i != e; ++i)
1075 if (Index == List[i].first)
1081 static void EmitConvertToMCInst(CodeGenTarget &Target,
1082 std::vector<MatchableInfo*> &Infos,
1084 // Write the convert function to a separate stream, so we can drop it after
1086 std::string ConvertFnBody;
1087 raw_string_ostream CvtOS(ConvertFnBody);
1089 // Function we have already generated.
1090 std::set<std::string> GeneratedFns;
1092 // Start the unified conversion function.
1094 CvtOS << "static void ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
1095 << "unsigned Opcode,\n"
1096 << " const SmallVectorImpl<MCParsedAsmOperand*"
1097 << "> &Operands) {\n";
1098 CvtOS << " Inst.setOpcode(Opcode);\n";
1099 CvtOS << " switch (Kind) {\n";
1100 CvtOS << " default:\n";
1102 // Start the enum, which we will generate inline.
1104 OS << "// Unified function for converting operants to MCInst instances.\n\n";
1105 OS << "enum ConversionKind {\n";
1107 // TargetOperandClass - This is the target's operand class, like X86Operand.
1108 std::string TargetOperandClass = Target.getName() + "Operand";
1110 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(),
1111 ie = Infos.end(); it != ie; ++it) {
1112 MatchableInfo &II = **it;
1114 // Order the (class) operands by the order to convert them into an MCInst.
1115 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
1116 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1117 MatchableInfo::Operand &Op = II.Operands[i];
1119 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
1122 // Find any tied operands.
1123 SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands;
1124 for (unsigned i = 0, e = II.OperandList.size(); i != e; ++i) {
1125 const CGIOperandList::OperandInfo &OpInfo = II.OperandList[i];
1126 for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) {
1127 const CGIOperandList::ConstraintInfo &CI = OpInfo.Constraints[j];
1129 TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo + j,
1130 CI.getTiedOperand()));
1134 array_pod_sort(MIOperandList.begin(), MIOperandList.end());
1136 // Compute the total number of operands.
1137 unsigned NumMIOperands = 0;
1138 for (unsigned i = 0, e = II.OperandList.size(); i != e; ++i) {
1139 const CGIOperandList::OperandInfo &OI = II.OperandList[i];
1140 NumMIOperands = std::max(NumMIOperands,
1141 OI.MIOperandNo + OI.MINumOperands);
1144 // Build the conversion function signature.
1145 std::string Signature = "Convert";
1146 unsigned CurIndex = 0;
1147 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1148 MatchableInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1149 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
1150 "Duplicate match for instruction operand!");
1152 // Skip operands which weren't matched by anything, this occurs when the
1153 // .td file encodes "implicit" operands as explicit ones.
1155 // FIXME: This should be removed from the MCInst structure.
1156 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1157 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1160 Signature += "__Imp";
1162 Signature += "__Tie" + utostr(Tie->second);
1167 // Registers are always converted the same, don't duplicate the conversion
1168 // function based on them.
1170 // FIXME: We could generalize this based on the render method, if it
1172 if (Op.Class->isRegisterClass())
1175 Signature += Op.Class->ClassName;
1176 Signature += utostr(Op.OperandInfo->MINumOperands);
1177 Signature += "_" + utostr(MIOperandList[i].second);
1179 CurIndex += Op.OperandInfo->MINumOperands;
1182 // Add any trailing implicit operands.
1183 for (; CurIndex != NumMIOperands; ++CurIndex) {
1184 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1187 Signature += "__Imp";
1189 Signature += "__Tie" + utostr(Tie->second);
1192 II.ConversionFnKind = Signature;
1194 // Check if we have already generated this signature.
1195 if (!GeneratedFns.insert(Signature).second)
1198 // If not, emit it now.
1200 // Add to the enum list.
1201 OS << " " << Signature << ",\n";
1203 // And to the convert function.
1204 CvtOS << " case " << Signature << ":\n";
1206 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1207 MatchableInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1209 // Add the implicit operands.
1210 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1211 // See if this is a tied operand.
1212 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1216 // If not, this is some implicit operand. Just assume it is a register
1218 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1220 // Copy the tied operand.
1221 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1222 CvtOS << " Inst.addOperand(Inst.getOperand("
1223 << Tie->second << "));\n";
1227 CvtOS << " ((" << TargetOperandClass << "*)Operands["
1228 << MIOperandList[i].second
1229 << "+1])->" << Op.Class->RenderMethod
1230 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
1231 CurIndex += Op.OperandInfo->MINumOperands;
1234 // And add trailing implicit operands.
1235 for (; CurIndex != NumMIOperands; ++CurIndex) {
1236 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1240 // If not, this is some implicit operand. Just assume it is a register
1242 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1244 // Copy the tied operand.
1245 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1246 CvtOS << " Inst.addOperand(Inst.getOperand("
1247 << Tie->second << "));\n";
1251 CvtOS << " return;\n";
1254 // Finish the convert function.
1259 // Finish the enum, and drop the convert function after it.
1261 OS << " NumConversionVariants\n";
1267 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1268 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1269 std::vector<ClassInfo*> &Infos,
1271 OS << "namespace {\n\n";
1273 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1274 << "/// instruction matching.\n";
1275 OS << "enum MatchClassKind {\n";
1276 OS << " InvalidMatchClass = 0,\n";
1277 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1278 ie = Infos.end(); it != ie; ++it) {
1279 ClassInfo &CI = **it;
1280 OS << " " << CI.Name << ", // ";
1281 if (CI.Kind == ClassInfo::Token) {
1282 OS << "'" << CI.ValueName << "'\n";
1283 } else if (CI.isRegisterClass()) {
1284 if (!CI.ValueName.empty())
1285 OS << "register class '" << CI.ValueName << "'\n";
1287 OS << "derived register class\n";
1289 OS << "user defined class '" << CI.ValueName << "'\n";
1292 OS << " NumMatchClassKinds\n";
1298 /// EmitClassifyOperand - Emit the function to classify an operand.
1299 static void EmitClassifyOperand(AsmMatcherInfo &Info,
1301 OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
1302 << " " << Info.Target.getName() << "Operand &Operand = *("
1303 << Info.Target.getName() << "Operand*)GOp;\n";
1306 OS << " if (Operand.isToken())\n";
1307 OS << " return MatchTokenString(Operand.getToken());\n\n";
1309 // Classify registers.
1311 // FIXME: Don't hardcode isReg, getReg.
1312 OS << " if (Operand.isReg()) {\n";
1313 OS << " switch (Operand.getReg()) {\n";
1314 OS << " default: return InvalidMatchClass;\n";
1315 for (std::map<Record*, ClassInfo*>::iterator
1316 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1318 OS << " case " << Info.Target.getName() << "::"
1319 << it->first->getName() << ": return " << it->second->Name << ";\n";
1323 // Classify user defined operands.
1324 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1325 ie = Info.Classes.end(); it != ie; ++it) {
1326 ClassInfo &CI = **it;
1328 if (!CI.isUserClass())
1331 OS << " // '" << CI.ClassName << "' class";
1332 if (!CI.SuperClasses.empty()) {
1333 OS << ", subclass of ";
1334 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1336 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1337 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
1342 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
1344 // Validate subclass relationships.
1345 if (!CI.SuperClasses.empty()) {
1346 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1347 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1348 << "() && \"Invalid class relationship!\");\n";
1351 OS << " return " << CI.Name << ";\n";
1354 OS << " return InvalidMatchClass;\n";
1358 /// EmitIsSubclass - Emit the subclass predicate function.
1359 static void EmitIsSubclass(CodeGenTarget &Target,
1360 std::vector<ClassInfo*> &Infos,
1362 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1363 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1364 OS << " if (A == B)\n";
1365 OS << " return true;\n\n";
1367 OS << " switch (A) {\n";
1368 OS << " default:\n";
1369 OS << " return false;\n";
1370 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1371 ie = Infos.end(); it != ie; ++it) {
1372 ClassInfo &A = **it;
1374 if (A.Kind != ClassInfo::Token) {
1375 std::vector<StringRef> SuperClasses;
1376 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1377 ie = Infos.end(); it != ie; ++it) {
1378 ClassInfo &B = **it;
1380 if (&A != &B && A.isSubsetOf(B))
1381 SuperClasses.push_back(B.Name);
1384 if (SuperClasses.empty())
1387 OS << "\n case " << A.Name << ":\n";
1389 if (SuperClasses.size() == 1) {
1390 OS << " return B == " << SuperClasses.back() << ";\n";
1394 OS << " switch (B) {\n";
1395 OS << " default: return false;\n";
1396 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1397 OS << " case " << SuperClasses[i] << ": return true;\n";
1407 /// EmitMatchTokenString - Emit the function to match a token string to the
1408 /// appropriate match class value.
1409 static void EmitMatchTokenString(CodeGenTarget &Target,
1410 std::vector<ClassInfo*> &Infos,
1412 // Construct the match list.
1413 std::vector<StringMatcher::StringPair> Matches;
1414 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1415 ie = Infos.end(); it != ie; ++it) {
1416 ClassInfo &CI = **it;
1418 if (CI.Kind == ClassInfo::Token)
1419 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1420 "return " + CI.Name + ";"));
1423 OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
1425 StringMatcher("Name", Matches, OS).Emit();
1427 OS << " return InvalidMatchClass;\n";
1431 /// EmitMatchRegisterName - Emit the function to match a string to the target
1432 /// specific register enum.
1433 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1435 // Construct the match list.
1436 std::vector<StringMatcher::StringPair> Matches;
1437 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1438 const CodeGenRegister &Reg = Target.getRegisters()[i];
1439 if (Reg.TheDef->getValueAsString("AsmName").empty())
1442 Matches.push_back(StringMatcher::StringPair(
1443 Reg.TheDef->getValueAsString("AsmName"),
1444 "return " + utostr(i + 1) + ";"));
1447 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
1449 StringMatcher("Name", Matches, OS).Emit();
1451 OS << " return 0;\n";
1455 /// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1457 static void EmitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
1459 OS << "// Flags for subtarget features that participate in "
1460 << "instruction matching.\n";
1461 OS << "enum SubtargetFeatureFlag {\n";
1462 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1463 it = Info.SubtargetFeatures.begin(),
1464 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1465 SubtargetFeatureInfo &SFI = *it->second;
1466 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
1468 OS << " Feature_None = 0\n";
1472 /// EmitComputeAvailableFeatures - Emit the function to compute the list of
1473 /// available features given a subtarget.
1474 static void EmitComputeAvailableFeatures(AsmMatcherInfo &Info,
1476 std::string ClassName =
1477 Info.AsmParser->getValueAsString("AsmParserClassName");
1479 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
1480 << "ComputeAvailableFeatures(const " << Info.Target.getName()
1481 << "Subtarget *Subtarget) const {\n";
1482 OS << " unsigned Features = 0;\n";
1483 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1484 it = Info.SubtargetFeatures.begin(),
1485 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1486 SubtargetFeatureInfo &SFI = *it->second;
1487 OS << " if (" << SFI.TheDef->getValueAsString("CondString")
1489 OS << " Features |= " << SFI.getEnumName() << ";\n";
1491 OS << " return Features;\n";
1495 static std::string GetAliasRequiredFeatures(Record *R,
1496 const AsmMatcherInfo &Info) {
1497 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
1499 unsigned NumFeatures = 0;
1500 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
1501 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
1504 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
1505 "' is not marked as an AssemblerPredicate!");
1510 Result += F->getEnumName();
1514 if (NumFeatures > 1)
1515 Result = '(' + Result + ')';
1519 /// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
1520 /// emit a function for them and return true, otherwise return false.
1521 static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
1522 std::vector<Record*> Aliases =
1523 Records.getAllDerivedDefinitions("MnemonicAlias");
1524 if (Aliases.empty()) return false;
1526 OS << "static void ApplyMnemonicAliases(StringRef &Mnemonic, "
1527 "unsigned Features) {\n";
1529 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
1530 // iteration order of the map is stable.
1531 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1533 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1534 Record *R = Aliases[i];
1535 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
1538 // Process each alias a "from" mnemonic at a time, building the code executed
1539 // by the string remapper.
1540 std::vector<StringMatcher::StringPair> Cases;
1541 for (std::map<std::string, std::vector<Record*> >::iterator
1542 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1544 const std::vector<Record*> &ToVec = I->second;
1546 // Loop through each alias and emit code that handles each case. If there
1547 // are two instructions without predicates, emit an error. If there is one,
1549 std::string MatchCode;
1550 int AliasWithNoPredicate = -1;
1552 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1553 Record *R = ToVec[i];
1554 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
1556 // If this unconditionally matches, remember it for later and diagnose
1558 if (FeatureMask.empty()) {
1559 if (AliasWithNoPredicate != -1) {
1560 // We can't have two aliases from the same mnemonic with no predicate.
1561 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1562 "two MnemonicAliases with the same 'from' mnemonic!");
1563 throw TGError(R->getLoc(), "this is the other MnemonicAlias.");
1566 AliasWithNoPredicate = i;
1570 if (!MatchCode.empty())
1571 MatchCode += "else ";
1572 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1573 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
1576 if (AliasWithNoPredicate != -1) {
1577 Record *R = ToVec[AliasWithNoPredicate];
1578 if (!MatchCode.empty())
1579 MatchCode += "else\n ";
1580 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
1583 MatchCode += "return;";
1585 Cases.push_back(std::make_pair(I->first, MatchCode));
1589 StringMatcher("Mnemonic", Cases, OS).Emit();
1595 void AsmMatcherEmitter::run(raw_ostream &OS) {
1596 CodeGenTarget Target;
1597 Record *AsmParser = Target.getAsmParser();
1598 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1600 // Compute the information on the instructions to match.
1601 AsmMatcherInfo Info(AsmParser, Target);
1604 // Sort the instruction table using the partial order on classes. We use
1605 // stable_sort to ensure that ambiguous instructions are still
1606 // deterministically ordered.
1607 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
1608 less_ptr<MatchableInfo>());
1610 DEBUG_WITH_TYPE("instruction_info", {
1611 for (std::vector<MatchableInfo*>::iterator
1612 it = Info.Matchables.begin(), ie = Info.Matchables.end();
1617 // Check for ambiguous matchables.
1618 DEBUG_WITH_TYPE("ambiguous_instrs", {
1619 unsigned NumAmbiguous = 0;
1620 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) {
1621 for (unsigned j = i + 1; j != e; ++j) {
1622 MatchableInfo &A = *Info.Matchables[i];
1623 MatchableInfo &B = *Info.Matchables[j];
1625 if (A.CouldMatchAmiguouslyWith(B)) {
1626 errs() << "warning: ambiguous matchables:\n";
1628 errs() << "\nis incomparable with:\n";
1636 errs() << "warning: " << NumAmbiguous
1637 << " ambiguous matchables!\n";
1640 // Write the output.
1642 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1644 // Information for the class declaration.
1645 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
1646 OS << "#undef GET_ASSEMBLER_HEADER\n";
1647 OS << " // This should be included into the middle of the declaration of \n";
1648 OS << " // your subclasses implementation of TargetAsmParser.\n";
1649 OS << " unsigned ComputeAvailableFeatures(const " <<
1650 Target.getName() << "Subtarget *Subtarget) const;\n";
1651 OS << " enum MatchResultTy {\n";
1652 OS << " Match_Success, Match_MnemonicFail, Match_InvalidOperand,\n";
1653 OS << " Match_MissingFeature\n";
1655 OS << " MatchResultTy MatchInstructionImpl(const "
1656 << "SmallVectorImpl<MCParsedAsmOperand*>"
1657 << " &Operands, MCInst &Inst, unsigned &ErrorInfo);\n\n";
1658 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
1663 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
1664 OS << "#undef GET_REGISTER_MATCHER\n\n";
1666 // Emit the subtarget feature enumeration.
1667 EmitSubtargetFeatureFlagEnumeration(Info, OS);
1669 // Emit the function to match a register name to number.
1670 EmitMatchRegisterName(Target, AsmParser, OS);
1672 OS << "#endif // GET_REGISTER_MATCHER\n\n";
1675 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
1676 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
1678 // Generate the function that remaps for mnemonic aliases.
1679 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
1681 // Generate the unified function to convert operands into an MCInst.
1682 EmitConvertToMCInst(Target, Info.Matchables, OS);
1684 // Emit the enumeration for classes which participate in matching.
1685 EmitMatchClassEnumeration(Target, Info.Classes, OS);
1687 // Emit the routine to match token strings to their match class.
1688 EmitMatchTokenString(Target, Info.Classes, OS);
1690 // Emit the routine to classify an operand.
1691 EmitClassifyOperand(Info, OS);
1693 // Emit the subclass predicate routine.
1694 EmitIsSubclass(Target, Info.Classes, OS);
1696 // Emit the available features compute function.
1697 EmitComputeAvailableFeatures(Info, OS);
1700 size_t MaxNumOperands = 0;
1701 for (std::vector<MatchableInfo*>::const_iterator it =
1702 Info.Matchables.begin(), ie = Info.Matchables.end();
1704 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1707 // Emit the static match table; unused classes get initalized to 0 which is
1708 // guaranteed to be InvalidMatchClass.
1710 // FIXME: We can reduce the size of this table very easily. First, we change
1711 // it so that store the kinds in separate bit-fields for each index, which
1712 // only needs to be the max width used for classes at that index (we also need
1713 // to reject based on this during classification). If we then make sure to
1714 // order the match kinds appropriately (putting mnemonics last), then we
1715 // should only end up using a few bits for each class, especially the ones
1716 // following the mnemonic.
1717 OS << "namespace {\n";
1718 OS << " struct MatchEntry {\n";
1719 OS << " unsigned Opcode;\n";
1720 OS << " const char *Mnemonic;\n";
1721 OS << " ConversionKind ConvertFn;\n";
1722 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1723 OS << " unsigned RequiredFeatures;\n";
1726 OS << "// Predicate for searching for an opcode.\n";
1727 OS << " struct LessOpcode {\n";
1728 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
1729 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
1731 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
1732 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
1734 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
1735 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
1739 OS << "} // end anonymous namespace.\n\n";
1741 OS << "static const MatchEntry MatchTable["
1742 << Info.Matchables.size() << "] = {\n";
1744 for (std::vector<MatchableInfo*>::const_iterator it =
1745 Info.Matchables.begin(), ie = Info.Matchables.end();
1747 MatchableInfo &II = **it;
1749 OS << " { " << Target.getName() << "::" << II.InstrName
1750 << ", \"" << II.Tokens[0] << "\""
1751 << ", " << II.ConversionFnKind << ", { ";
1752 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1753 MatchableInfo::Operand &Op = II.Operands[i];
1756 OS << Op.Class->Name;
1760 // Write the required features mask.
1761 if (!II.RequiredFeatures.empty()) {
1762 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
1764 OS << II.RequiredFeatures[i]->getEnumName();
1774 // Finally, build the match function.
1775 OS << Target.getName() << ClassName << "::MatchResultTy "
1776 << Target.getName() << ClassName << "::\n"
1777 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
1779 OS << " MCInst &Inst, unsigned &ErrorInfo) {\n";
1781 // Emit code to get the available features.
1782 OS << " // Get the current feature set.\n";
1783 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
1785 OS << " // Get the instruction mnemonic, which is the first token.\n";
1786 OS << " StringRef Mnemonic = ((" << Target.getName()
1787 << "Operand*)Operands[0])->getToken();\n\n";
1789 if (HasMnemonicAliases) {
1790 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
1791 OS << " ApplyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
1794 // Emit code to compute the class list for this operand vector.
1795 OS << " // Eliminate obvious mismatches.\n";
1796 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
1797 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
1798 OS << " return Match_InvalidOperand;\n";
1801 OS << " // Compute the class list for this operand vector.\n";
1802 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1803 OS << " for (unsigned i = 1, e = Operands.size(); i != e; ++i) {\n";
1804 OS << " Classes[i-1] = ClassifyOperand(Operands[i]);\n\n";
1806 OS << " // Check for invalid operands before matching.\n";
1807 OS << " if (Classes[i-1] == InvalidMatchClass) {\n";
1808 OS << " ErrorInfo = i;\n";
1809 OS << " return Match_InvalidOperand;\n";
1813 OS << " // Mark unused classes.\n";
1814 OS << " for (unsigned i = Operands.size()-1, e = " << MaxNumOperands << "; "
1815 << "i != e; ++i)\n";
1816 OS << " Classes[i] = InvalidMatchClass;\n\n";
1818 OS << " // Some state to try to produce better error messages.\n";
1819 OS << " bool HadMatchOtherThanFeatures = false;\n\n";
1820 OS << " // Set ErrorInfo to the operand that mismatches if it is \n";
1821 OS << " // wrong for all instances of the instruction.\n";
1822 OS << " ErrorInfo = ~0U;\n";
1824 // Emit code to search the table.
1825 OS << " // Search the table.\n";
1826 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
1827 OS << " std::equal_range(MatchTable, MatchTable+"
1828 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n";
1830 OS << " // Return a more specific error code if no mnemonics match.\n";
1831 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
1832 OS << " return Match_MnemonicFail;\n\n";
1834 OS << " for (const MatchEntry *it = MnemonicRange.first, "
1835 << "*ie = MnemonicRange.second;\n";
1836 OS << " it != ie; ++it) {\n";
1838 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
1839 OS << " assert(Mnemonic == it->Mnemonic);\n";
1841 // Emit check that the subclasses match.
1842 OS << " bool OperandsValid = true;\n";
1843 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
1844 OS << " if (IsSubclass(Classes[i], it->Classes[i]))\n";
1845 OS << " continue;\n";
1846 OS << " // If this operand is broken for all of the instances of this\n";
1847 OS << " // mnemonic, keep track of it so we can report loc info.\n";
1848 OS << " if (it == MnemonicRange.first || ErrorInfo == i+1)\n";
1849 OS << " ErrorInfo = i+1;\n";
1851 OS << " ErrorInfo = ~0U;";
1852 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
1853 OS << " OperandsValid = false;\n";
1857 OS << " if (!OperandsValid) continue;\n";
1859 // Emit check that the required features are available.
1860 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
1861 << "!= it->RequiredFeatures) {\n";
1862 OS << " HadMatchOtherThanFeatures = true;\n";
1863 OS << " continue;\n";
1867 OS << " ConvertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
1869 // Call the post-processing function, if used.
1870 std::string InsnCleanupFn =
1871 AsmParser->getValueAsString("AsmParserInstCleanup");
1872 if (!InsnCleanupFn.empty())
1873 OS << " " << InsnCleanupFn << "(Inst);\n";
1875 OS << " return Match_Success;\n";
1878 OS << " // Okay, we had no match. Try to return a useful error code.\n";
1879 OS << " if (HadMatchOtherThanFeatures) return Match_MissingFeature;\n";
1880 OS << " return Match_InvalidOperand;\n";
1883 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";