1 //===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This tablegen backend emits a target specifier matcher for converting parsed
10 // assembly operands in the MCInst structures. It also emits a matcher for
11 // custom operand parsing.
13 // Converting assembly operands into MCInst structures
14 // ---------------------------------------------------
16 // The input to the target specific matcher is a list of literal tokens and
17 // operands. The target specific parser should generally eliminate any syntax
18 // which is not relevant for matching; for example, comma tokens should have
19 // already been consumed and eliminated by the parser. Most instructions will
20 // end up with a single literal token (the instruction name) and some number of
23 // Some example inputs, for X86:
24 // 'addl' (immediate ...) (register ...)
25 // 'add' (immediate ...) (memory ...)
28 // The assembly matcher is responsible for converting this input into a precise
29 // machine instruction (i.e., an instruction with a well defined encoding). This
30 // mapping has several properties which complicate matching:
32 // - It may be ambiguous; many architectures can legally encode particular
33 // variants of an instruction in different ways (for example, using a smaller
34 // encoding for small immediates). Such ambiguities should never be
35 // arbitrarily resolved by the assembler, the assembler is always responsible
36 // for choosing the "best" available instruction.
38 // - It may depend on the subtarget or the assembler context. Instructions
39 // which are invalid for the current mode, but otherwise unambiguous (e.g.,
40 // an SSE instruction in a file being assembled for i486) should be accepted
41 // and rejected by the assembler front end. However, if the proper encoding
42 // for an instruction is dependent on the assembler context then the matcher
43 // is responsible for selecting the correct machine instruction for the
46 // The core matching algorithm attempts to exploit the regularity in most
47 // instruction sets to quickly determine the set of possibly matching
48 // instructions, and the simplify the generated code. Additionally, this helps
49 // to ensure that the ambiguities are intentionally resolved by the user.
51 // The matching is divided into two distinct phases:
53 // 1. Classification: Each operand is mapped to the unique set which (a)
54 // contains it, and (b) is the largest such subset for which a single
55 // instruction could match all members.
57 // For register classes, we can generate these subgroups automatically. For
58 // arbitrary operands, we expect the user to define the classes and their
59 // relations to one another (for example, 8-bit signed immediates as a
60 // subset of 32-bit immediates).
62 // By partitioning the operands in this way, we guarantee that for any
63 // tuple of classes, any single instruction must match either all or none
64 // of the sets of operands which could classify to that tuple.
66 // In addition, the subset relation amongst classes induces a partial order
67 // on such tuples, which we use to resolve ambiguities.
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 // Custom Operand Parsing
75 // ----------------------
77 // Some targets need a custom way to parse operands, some specific instructions
78 // can contain arguments that can represent processor flags and other kinds of
79 // identifiers that need to be mapped to specific values in the final encoded
80 // instructions. The target specific custom operand parsing works in the
83 // 1. A operand match table is built, each entry contains a mnemonic, an
84 // operand class, a mask for all operand positions for that same
85 // class/mnemonic and target features to be checked while trying to match.
87 // 2. The operand matcher will try every possible entry with the same
88 // mnemonic and will check if the target feature for this mnemonic also
89 // matches. After that, if the operand to be matched has its index
90 // present in the mask, a successful match occurs. Otherwise, fallback
91 // to the regular operand parsing.
93 // 3. For a match success, each operand class that has a 'ParserMethod'
94 // becomes part of a switch from where the custom method is called.
96 //===----------------------------------------------------------------------===//
98 #include "CodeGenTarget.h"
99 #include "SubtargetFeatureInfo.h"
101 #include "llvm/ADT/CachedHashString.h"
102 #include "llvm/ADT/PointerUnion.h"
103 #include "llvm/ADT/STLExtras.h"
104 #include "llvm/ADT/SmallPtrSet.h"
105 #include "llvm/ADT/SmallVector.h"
106 #include "llvm/ADT/StringExtras.h"
107 #include "llvm/Config/llvm-config.h"
108 #include "llvm/Support/CommandLine.h"
109 #include "llvm/Support/Debug.h"
110 #include "llvm/Support/ErrorHandling.h"
111 #include "llvm/TableGen/Error.h"
112 #include "llvm/TableGen/Record.h"
113 #include "llvm/TableGen/StringMatcher.h"
114 #include "llvm/TableGen/StringToOffsetTable.h"
115 #include "llvm/TableGen/TableGenBackend.h"
118 #include <forward_list>
122 using namespace llvm
;
124 #define DEBUG_TYPE "asm-matcher-emitter"
126 cl::OptionCategory
AsmMatcherEmitterCat("Options for -gen-asm-matcher");
128 static cl::opt
<std::string
>
129 MatchPrefix("match-prefix", cl::init(""),
130 cl::desc("Only match instructions with the given prefix"),
131 cl::cat(AsmMatcherEmitterCat
));
134 class AsmMatcherInfo
;
136 // Register sets are used as keys in some second-order sets TableGen creates
137 // when generating its data structures. This means that the order of two
138 // RegisterSets can be seen in the outputted AsmMatcher tables occasionally, and
139 // can even affect compiler output (at least seen in diagnostics produced when
140 // all matches fail). So we use a type that sorts them consistently.
141 typedef std::set
<Record
*, LessRecordByID
> RegisterSet
;
143 class AsmMatcherEmitter
{
144 RecordKeeper
&Records
;
146 AsmMatcherEmitter(RecordKeeper
&R
) : Records(R
) {}
148 void run(raw_ostream
&o
);
151 /// ClassInfo - Helper class for storing the information about a particular
152 /// class of operands which can be matched.
155 /// Invalid kind, for use as a sentinel value.
158 /// The class for a particular token.
161 /// The (first) register class, subsequent register classes are
162 /// RegisterClass0+1, and so on.
165 /// The (first) user defined class, subsequent user defined classes are
166 /// UserClass0+1, and so on.
170 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
171 /// N) for the Nth user defined class.
174 /// SuperClasses - The super classes of this class. Note that for simplicities
175 /// sake user operands only record their immediate super class, while register
176 /// operands include all superclasses.
177 std::vector
<ClassInfo
*> SuperClasses
;
179 /// Name - The full class name, suitable for use in an enum.
182 /// ClassName - The unadorned generic name for this class (e.g., Token).
183 std::string ClassName
;
185 /// ValueName - The name of the value this class represents; for a token this
186 /// is the literal token string, for an operand it is the TableGen class (or
187 /// empty if this is a derived class).
188 std::string ValueName
;
190 /// PredicateMethod - The name of the operand method to test whether the
191 /// operand matches this class; this is not valid for Token or register kinds.
192 std::string PredicateMethod
;
194 /// RenderMethod - The name of the operand method to add this operand to an
195 /// MCInst; this is not valid for Token or register kinds.
196 std::string RenderMethod
;
198 /// ParserMethod - The name of the operand method to do a target specific
199 /// parsing on the operand.
200 std::string ParserMethod
;
202 /// For register classes: the records for all the registers in this class.
203 RegisterSet Registers
;
205 /// For custom match classes: the diagnostic kind for when the predicate fails.
206 std::string DiagnosticType
;
208 /// For custom match classes: the diagnostic string for when the predicate fails.
209 std::string DiagnosticString
;
211 /// Is this operand optional and not always required.
214 /// DefaultMethod - The name of the method that returns the default operand
215 /// for optional operand
216 std::string DefaultMethod
;
219 /// isRegisterClass() - Check if this is a register class.
220 bool isRegisterClass() const {
221 return Kind
>= RegisterClass0
&& Kind
< UserClass0
;
224 /// isUserClass() - Check if this is a user defined class.
225 bool isUserClass() const {
226 return Kind
>= UserClass0
;
229 /// isRelatedTo - Check whether this class is "related" to \p RHS. Classes
230 /// are related if they are in the same class hierarchy.
231 bool isRelatedTo(const ClassInfo
&RHS
) const {
232 // Tokens are only related to tokens.
233 if (Kind
== Token
|| RHS
.Kind
== Token
)
234 return Kind
== Token
&& RHS
.Kind
== Token
;
236 // Registers classes are only related to registers classes, and only if
237 // their intersection is non-empty.
238 if (isRegisterClass() || RHS
.isRegisterClass()) {
239 if (!isRegisterClass() || !RHS
.isRegisterClass())
243 std::insert_iterator
<RegisterSet
> II(Tmp
, Tmp
.begin());
244 std::set_intersection(Registers
.begin(), Registers
.end(),
245 RHS
.Registers
.begin(), RHS
.Registers
.end(),
246 II
, LessRecordByID());
251 // Otherwise we have two users operands; they are related if they are in the
252 // same class hierarchy.
254 // FIXME: This is an oversimplification, they should only be related if they
255 // intersect, however we don't have that information.
256 assert(isUserClass() && RHS
.isUserClass() && "Unexpected class!");
257 const ClassInfo
*Root
= this;
258 while (!Root
->SuperClasses
.empty())
259 Root
= Root
->SuperClasses
.front();
261 const ClassInfo
*RHSRoot
= &RHS
;
262 while (!RHSRoot
->SuperClasses
.empty())
263 RHSRoot
= RHSRoot
->SuperClasses
.front();
265 return Root
== RHSRoot
;
268 /// isSubsetOf - Test whether this class is a subset of \p RHS.
269 bool isSubsetOf(const ClassInfo
&RHS
) const {
270 // This is a subset of RHS if it is the same class...
274 // ... or if any of its super classes are a subset of RHS.
275 SmallVector
<const ClassInfo
*, 16> Worklist(SuperClasses
.begin(),
277 SmallPtrSet
<const ClassInfo
*, 16> Visited
;
278 while (!Worklist
.empty()) {
279 auto *CI
= Worklist
.pop_back_val();
282 for (auto *Super
: CI
->SuperClasses
)
283 if (Visited
.insert(Super
).second
)
284 Worklist
.push_back(Super
);
290 int getTreeDepth() const {
292 const ClassInfo
*Root
= this;
293 while (!Root
->SuperClasses
.empty()) {
295 Root
= Root
->SuperClasses
.front();
300 const ClassInfo
*findRoot() const {
301 const ClassInfo
*Root
= this;
302 while (!Root
->SuperClasses
.empty())
303 Root
= Root
->SuperClasses
.front();
307 /// Compare two classes. This does not produce a total ordering, but does
308 /// guarantee that subclasses are sorted before their parents, and that the
309 /// ordering is transitive.
310 bool operator<(const ClassInfo
&RHS
) const {
314 // First, enforce the ordering between the three different types of class.
315 // Tokens sort before registers, which sort before user classes.
317 if (RHS
.Kind
!= Token
)
319 assert(RHS
.Kind
== Token
);
320 } else if (isRegisterClass()) {
321 if (RHS
.Kind
== Token
)
323 else if (RHS
.isUserClass())
325 assert(RHS
.isRegisterClass());
326 } else if (isUserClass()) {
327 if (!RHS
.isUserClass())
329 assert(RHS
.isUserClass());
331 llvm_unreachable("Unknown ClassInfoKind");
334 if (Kind
== Token
|| isUserClass()) {
335 // Related tokens and user classes get sorted by depth in the inheritence
336 // tree (so that subclasses are before their parents).
337 if (isRelatedTo(RHS
)) {
338 if (getTreeDepth() > RHS
.getTreeDepth())
340 if (getTreeDepth() < RHS
.getTreeDepth())
343 // Unrelated tokens and user classes are ordered by the name of their
344 // root nodes, so that there is a consistent ordering between
345 // unconnected trees.
346 return findRoot()->ValueName
< RHS
.findRoot()->ValueName
;
348 } else if (isRegisterClass()) {
349 // For register sets, sort by number of registers. This guarantees that
350 // a set will always sort before all of it's strict supersets.
351 if (Registers
.size() != RHS
.Registers
.size())
352 return Registers
.size() < RHS
.Registers
.size();
354 llvm_unreachable("Unknown ClassInfoKind");
357 // FIXME: We should be able to just return false here, as we only need a
358 // partial order (we use stable sorts, so this is deterministic) and the
359 // name of a class shouldn't be significant. However, some of the backends
360 // accidentally rely on this behaviour, so it will have to stay like this
361 // until they are fixed.
362 return ValueName
< RHS
.ValueName
;
366 class AsmVariantInfo
{
368 StringRef RegisterPrefix
;
369 StringRef TokenizingCharacters
;
370 StringRef SeparatorCharacters
;
371 StringRef BreakCharacters
;
376 /// MatchableInfo - Helper class for storing the necessary information for an
377 /// instruction or alias which is capable of being matched.
378 struct MatchableInfo
{
380 /// Token - This is the token that the operand came from.
383 /// The unique class instance this operand should match.
386 /// The operand name this is, if anything.
389 /// The operand name this is, before renaming for tied operands.
390 StringRef OrigSrcOpName
;
392 /// The suboperand index within SrcOpName, or -1 for the entire operand.
395 /// Whether the token is "isolated", i.e., it is preceded and followed
397 bool IsIsolatedToken
;
399 /// Register record if this token is singleton register.
400 Record
*SingletonReg
;
402 explicit AsmOperand(bool IsIsolatedToken
, StringRef T
)
403 : Token(T
), Class(nullptr), SubOpIdx(-1),
404 IsIsolatedToken(IsIsolatedToken
), SingletonReg(nullptr) {}
407 /// ResOperand - This represents a single operand in the result instruction
408 /// generated by the match. In cases (like addressing modes) where a single
409 /// assembler operand expands to multiple MCOperands, this represents the
410 /// single assembler operand, not the MCOperand.
413 /// RenderAsmOperand - This represents an operand result that is
414 /// generated by calling the render method on the assembly operand. The
415 /// corresponding AsmOperand is specified by AsmOperandNum.
418 /// TiedOperand - This represents a result operand that is a duplicate of
419 /// a previous result operand.
422 /// ImmOperand - This represents an immediate value that is dumped into
426 /// RegOperand - This represents a fixed register that is dumped in.
430 /// Tuple containing the index of the (earlier) result operand that should
431 /// be copied from, as well as the indices of the corresponding (parsed)
432 /// operands in the asm string.
433 struct TiedOperandsTuple
{
435 unsigned SrcOpnd1Idx
;
436 unsigned SrcOpnd2Idx
;
440 /// This is the operand # in the AsmOperands list that this should be
442 unsigned AsmOperandNum
;
444 /// Description of tied operands.
445 TiedOperandsTuple TiedOperands
;
447 /// ImmVal - This is the immediate value added to the instruction.
450 /// Register - This is the register record.
454 /// MINumOperands - The number of MCInst operands populated by this
456 unsigned MINumOperands
;
458 static ResOperand
getRenderedOp(unsigned AsmOpNum
, unsigned NumOperands
) {
460 X
.Kind
= RenderAsmOperand
;
461 X
.AsmOperandNum
= AsmOpNum
;
462 X
.MINumOperands
= NumOperands
;
466 static ResOperand
getTiedOp(unsigned TiedOperandNum
, unsigned SrcOperand1
,
467 unsigned SrcOperand2
) {
469 X
.Kind
= TiedOperand
;
470 X
.TiedOperands
= { TiedOperandNum
, SrcOperand1
, SrcOperand2
};
475 static ResOperand
getImmOp(int64_t Val
) {
483 static ResOperand
getRegOp(Record
*Reg
) {
492 /// AsmVariantID - Target's assembly syntax variant no.
495 /// AsmString - The assembly string for this instruction (with variants
496 /// removed), e.g. "movsx $src, $dst".
497 std::string AsmString
;
499 /// TheDef - This is the definition of the instruction or InstAlias that this
500 /// matchable came from.
501 Record
*const TheDef
;
503 /// DefRec - This is the definition that it came from.
504 PointerUnion
<const CodeGenInstruction
*, const CodeGenInstAlias
*> DefRec
;
506 const CodeGenInstruction
*getResultInst() const {
507 if (DefRec
.is
<const CodeGenInstruction
*>())
508 return DefRec
.get
<const CodeGenInstruction
*>();
509 return DefRec
.get
<const CodeGenInstAlias
*>()->ResultInst
;
512 /// ResOperands - This is the operand list that should be built for the result
514 SmallVector
<ResOperand
, 8> ResOperands
;
516 /// Mnemonic - This is the first token of the matched instruction, its
520 /// AsmOperands - The textual operands that this instruction matches,
521 /// annotated with a class and where in the OperandList they were defined.
522 /// This directly corresponds to the tokenized AsmString after the mnemonic is
524 SmallVector
<AsmOperand
, 8> AsmOperands
;
526 /// Predicates - The required subtarget features to match this instruction.
527 SmallVector
<const SubtargetFeatureInfo
*, 4> RequiredFeatures
;
529 /// ConversionFnKind - The enum value which is passed to the generated
530 /// convertToMCInst to convert parsed operands into an MCInst for this
532 std::string ConversionFnKind
;
534 /// If this instruction is deprecated in some form.
537 /// If this is an alias, this is use to determine whether or not to using
538 /// the conversion function defined by the instruction's AsmMatchConverter
539 /// or to use the function generated by the alias.
540 bool UseInstAsmMatchConverter
;
542 MatchableInfo(const CodeGenInstruction
&CGI
)
543 : AsmVariantID(0), AsmString(CGI
.AsmString
), TheDef(CGI
.TheDef
), DefRec(&CGI
),
544 UseInstAsmMatchConverter(true) {
547 MatchableInfo(std::unique_ptr
<const CodeGenInstAlias
> Alias
)
548 : AsmVariantID(0), AsmString(Alias
->AsmString
), TheDef(Alias
->TheDef
),
549 DefRec(Alias
.release()),
550 UseInstAsmMatchConverter(
551 TheDef
->getValueAsBit("UseInstAsmMatchConverter")) {
554 // Could remove this and the dtor if PointerUnion supported unique_ptr
555 // elements with a dynamic failure/assertion (like the one below) in the case
556 // where it was copied while being in an owning state.
557 MatchableInfo(const MatchableInfo
&RHS
)
558 : AsmVariantID(RHS
.AsmVariantID
), AsmString(RHS
.AsmString
),
559 TheDef(RHS
.TheDef
), DefRec(RHS
.DefRec
), ResOperands(RHS
.ResOperands
),
560 Mnemonic(RHS
.Mnemonic
), AsmOperands(RHS
.AsmOperands
),
561 RequiredFeatures(RHS
.RequiredFeatures
),
562 ConversionFnKind(RHS
.ConversionFnKind
),
563 HasDeprecation(RHS
.HasDeprecation
),
564 UseInstAsmMatchConverter(RHS
.UseInstAsmMatchConverter
) {
565 assert(!DefRec
.is
<const CodeGenInstAlias
*>());
569 delete DefRec
.dyn_cast
<const CodeGenInstAlias
*>();
572 // Two-operand aliases clone from the main matchable, but mark the second
573 // operand as a tied operand of the first for purposes of the assembler.
574 void formTwoOperandAlias(StringRef Constraint
);
576 void initialize(const AsmMatcherInfo
&Info
,
577 SmallPtrSetImpl
<Record
*> &SingletonRegisters
,
578 AsmVariantInfo
const &Variant
,
579 bool HasMnemonicFirst
);
581 /// validate - Return true if this matchable is a valid thing to match against
582 /// and perform a bunch of validity checking.
583 bool validate(StringRef CommentDelimiter
, bool IsAlias
) const;
585 /// findAsmOperand - Find the AsmOperand with the specified name and
586 /// suboperand index.
587 int findAsmOperand(StringRef N
, int SubOpIdx
) const {
588 auto I
= find_if(AsmOperands
, [&](const AsmOperand
&Op
) {
589 return Op
.SrcOpName
== N
&& Op
.SubOpIdx
== SubOpIdx
;
591 return (I
!= AsmOperands
.end()) ? I
- AsmOperands
.begin() : -1;
594 /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
595 /// This does not check the suboperand index.
596 int findAsmOperandNamed(StringRef N
, int LastIdx
= -1) const {
597 auto I
= std::find_if(AsmOperands
.begin() + LastIdx
+ 1, AsmOperands
.end(),
598 [&](const AsmOperand
&Op
) { return Op
.SrcOpName
== N
; });
599 return (I
!= AsmOperands
.end()) ? I
- AsmOperands
.begin() : -1;
602 int findAsmOperandOriginallyNamed(StringRef N
) const {
605 [&](const AsmOperand
&Op
) { return Op
.OrigSrcOpName
== N
; });
606 return (I
!= AsmOperands
.end()) ? I
- AsmOperands
.begin() : -1;
609 void buildInstructionResultOperands();
610 void buildAliasResultOperands(bool AliasConstraintsAreChecked
);
612 /// operator< - Compare two matchables.
613 bool operator<(const MatchableInfo
&RHS
) const {
614 // The primary comparator is the instruction mnemonic.
615 if (int Cmp
= Mnemonic
.compare(RHS
.Mnemonic
))
618 if (AsmOperands
.size() != RHS
.AsmOperands
.size())
619 return AsmOperands
.size() < RHS
.AsmOperands
.size();
621 // Compare lexicographically by operand. The matcher validates that other
622 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
623 for (unsigned i
= 0, e
= AsmOperands
.size(); i
!= e
; ++i
) {
624 if (*AsmOperands
[i
].Class
< *RHS
.AsmOperands
[i
].Class
)
626 if (*RHS
.AsmOperands
[i
].Class
< *AsmOperands
[i
].Class
)
630 // Give matches that require more features higher precedence. This is useful
631 // because we cannot define AssemblerPredicates with the negation of
632 // processor features. For example, ARM v6 "nop" may be either a HINT or
633 // MOV. With v6, we want to match HINT. The assembler has no way to
634 // predicate MOV under "NoV6", but HINT will always match first because it
635 // requires V6 while MOV does not.
636 if (RequiredFeatures
.size() != RHS
.RequiredFeatures
.size())
637 return RequiredFeatures
.size() > RHS
.RequiredFeatures
.size();
642 /// couldMatchAmbiguouslyWith - Check whether this matchable could
643 /// ambiguously match the same set of operands as \p RHS (without being a
644 /// strictly superior match).
645 bool couldMatchAmbiguouslyWith(const MatchableInfo
&RHS
) const {
646 // The primary comparator is the instruction mnemonic.
647 if (Mnemonic
!= RHS
.Mnemonic
)
650 // Different variants can't conflict.
651 if (AsmVariantID
!= RHS
.AsmVariantID
)
654 // The number of operands is unambiguous.
655 if (AsmOperands
.size() != RHS
.AsmOperands
.size())
658 // Otherwise, make sure the ordering of the two instructions is unambiguous
659 // by checking that either (a) a token or operand kind discriminates them,
660 // or (b) the ordering among equivalent kinds is consistent.
662 // Tokens and operand kinds are unambiguous (assuming a correct target
664 for (unsigned i
= 0, e
= AsmOperands
.size(); i
!= e
; ++i
)
665 if (AsmOperands
[i
].Class
->Kind
!= RHS
.AsmOperands
[i
].Class
->Kind
||
666 AsmOperands
[i
].Class
->Kind
== ClassInfo::Token
)
667 if (*AsmOperands
[i
].Class
< *RHS
.AsmOperands
[i
].Class
||
668 *RHS
.AsmOperands
[i
].Class
< *AsmOperands
[i
].Class
)
671 // Otherwise, this operand could commute if all operands are equivalent, or
672 // there is a pair of operands that compare less than and a pair that
673 // compare greater than.
674 bool HasLT
= false, HasGT
= false;
675 for (unsigned i
= 0, e
= AsmOperands
.size(); i
!= e
; ++i
) {
676 if (*AsmOperands
[i
].Class
< *RHS
.AsmOperands
[i
].Class
)
678 if (*RHS
.AsmOperands
[i
].Class
< *AsmOperands
[i
].Class
)
682 return HasLT
== HasGT
;
688 void tokenizeAsmString(AsmMatcherInfo
const &Info
,
689 AsmVariantInfo
const &Variant
);
690 void addAsmOperand(StringRef Token
, bool IsIsolatedToken
= false);
693 struct OperandMatchEntry
{
694 unsigned OperandMask
;
695 const MatchableInfo
* MI
;
698 static OperandMatchEntry
create(const MatchableInfo
*mi
, ClassInfo
*ci
,
701 X
.OperandMask
= opMask
;
708 class AsmMatcherInfo
{
711 RecordKeeper
&Records
;
713 /// The tablegen AsmParser record.
716 /// Target - The target information.
717 CodeGenTarget
&Target
;
719 /// The classes which are needed for matching.
720 std::forward_list
<ClassInfo
> Classes
;
722 /// The information on the matchables to match.
723 std::vector
<std::unique_ptr
<MatchableInfo
>> Matchables
;
725 /// Info for custom matching operands by user defined methods.
726 std::vector
<OperandMatchEntry
> OperandMatchInfo
;
728 /// Map of Register records to their class information.
729 typedef std::map
<Record
*, ClassInfo
*, LessRecordByID
> RegisterClassesTy
;
730 RegisterClassesTy RegisterClasses
;
732 /// Map of Predicate records to their subtarget information.
733 std::map
<Record
*, SubtargetFeatureInfo
, LessRecordByID
> SubtargetFeatures
;
735 /// Map of AsmOperandClass records to their class information.
736 std::map
<Record
*, ClassInfo
*> AsmOperandClasses
;
738 /// Map of RegisterClass records to their class information.
739 std::map
<Record
*, ClassInfo
*> RegisterClassClasses
;
742 /// Map of token to class information which has already been constructed.
743 std::map
<std::string
, ClassInfo
*> TokenClasses
;
746 /// getTokenClass - Lookup or create the class for the given token.
747 ClassInfo
*getTokenClass(StringRef Token
);
749 /// getOperandClass - Lookup or create the class for the given operand.
750 ClassInfo
*getOperandClass(const CGIOperandList::OperandInfo
&OI
,
752 ClassInfo
*getOperandClass(Record
*Rec
, int SubOpIdx
);
754 /// buildRegisterClasses - Build the ClassInfo* instances for register
756 void buildRegisterClasses(SmallPtrSetImpl
<Record
*> &SingletonRegisters
);
758 /// buildOperandClasses - Build the ClassInfo* instances for user defined
760 void buildOperandClasses();
762 void buildInstructionOperandReference(MatchableInfo
*II
, StringRef OpName
,
764 void buildAliasOperandReference(MatchableInfo
*II
, StringRef OpName
,
765 MatchableInfo::AsmOperand
&Op
);
768 AsmMatcherInfo(Record
*AsmParser
,
769 CodeGenTarget
&Target
,
770 RecordKeeper
&Records
);
772 /// Construct the various tables used during matching.
775 /// buildOperandMatchInfo - Build the necessary information to handle user
776 /// defined operand parsing methods.
777 void buildOperandMatchInfo();
779 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
781 const SubtargetFeatureInfo
*getSubtargetFeature(Record
*Def
) const {
782 assert(Def
->isSubClassOf("Predicate") && "Invalid predicate type!");
783 const auto &I
= SubtargetFeatures
.find(Def
);
784 return I
== SubtargetFeatures
.end() ? nullptr : &I
->second
;
787 RecordKeeper
&getRecords() const {
791 bool hasOptionalOperands() const {
792 return find_if(Classes
, [](const ClassInfo
&Class
) {
793 return Class
.IsOptional
;
798 } // end anonymous namespace
800 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
801 LLVM_DUMP_METHOD
void MatchableInfo::dump() const {
802 errs() << TheDef
->getName() << " -- " << "flattened:\"" << AsmString
<<"\"\n";
804 errs() << " variant: " << AsmVariantID
<< "\n";
806 for (unsigned i
= 0, e
= AsmOperands
.size(); i
!= e
; ++i
) {
807 const AsmOperand
&Op
= AsmOperands
[i
];
808 errs() << " op[" << i
<< "] = " << Op
.Class
->ClassName
<< " - ";
809 errs() << '\"' << Op
.Token
<< "\"\n";
814 static std::pair
<StringRef
, StringRef
>
815 parseTwoOperandConstraint(StringRef S
, ArrayRef
<SMLoc
> Loc
) {
816 // Split via the '='.
817 std::pair
<StringRef
, StringRef
> Ops
= S
.split('=');
818 if (Ops
.second
== "")
819 PrintFatalError(Loc
, "missing '=' in two-operand alias constraint");
820 // Trim whitespace and the leading '$' on the operand names.
821 size_t start
= Ops
.first
.find_first_of('$');
822 if (start
== std::string::npos
)
823 PrintFatalError(Loc
, "expected '$' prefix on asm operand name");
824 Ops
.first
= Ops
.first
.slice(start
+ 1, std::string::npos
);
825 size_t end
= Ops
.first
.find_last_of(" \t");
826 Ops
.first
= Ops
.first
.slice(0, end
);
827 // Now the second operand.
828 start
= Ops
.second
.find_first_of('$');
829 if (start
== std::string::npos
)
830 PrintFatalError(Loc
, "expected '$' prefix on asm operand name");
831 Ops
.second
= Ops
.second
.slice(start
+ 1, std::string::npos
);
832 end
= Ops
.second
.find_last_of(" \t");
833 Ops
.first
= Ops
.first
.slice(0, end
);
837 void MatchableInfo::formTwoOperandAlias(StringRef Constraint
) {
838 // Figure out which operands are aliased and mark them as tied.
839 std::pair
<StringRef
, StringRef
> Ops
=
840 parseTwoOperandConstraint(Constraint
, TheDef
->getLoc());
842 // Find the AsmOperands that refer to the operands we're aliasing.
843 int SrcAsmOperand
= findAsmOperandNamed(Ops
.first
);
844 int DstAsmOperand
= findAsmOperandNamed(Ops
.second
);
845 if (SrcAsmOperand
== -1)
846 PrintFatalError(TheDef
->getLoc(),
847 "unknown source two-operand alias operand '" + Ops
.first
+
849 if (DstAsmOperand
== -1)
850 PrintFatalError(TheDef
->getLoc(),
851 "unknown destination two-operand alias operand '" +
854 // Find the ResOperand that refers to the operand we're aliasing away
855 // and update it to refer to the combined operand instead.
856 for (ResOperand
&Op
: ResOperands
) {
857 if (Op
.Kind
== ResOperand::RenderAsmOperand
&&
858 Op
.AsmOperandNum
== (unsigned)SrcAsmOperand
) {
859 Op
.AsmOperandNum
= DstAsmOperand
;
863 // Remove the AsmOperand for the alias operand.
864 AsmOperands
.erase(AsmOperands
.begin() + SrcAsmOperand
);
865 // Adjust the ResOperand references to any AsmOperands that followed
866 // the one we just deleted.
867 for (ResOperand
&Op
: ResOperands
) {
870 // Nothing to do for operands that don't reference AsmOperands.
872 case ResOperand::RenderAsmOperand
:
873 if (Op
.AsmOperandNum
> (unsigned)SrcAsmOperand
)
880 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
881 /// if present, from specified token.
883 extractSingletonRegisterForAsmOperand(MatchableInfo::AsmOperand
&Op
,
884 const AsmMatcherInfo
&Info
,
885 StringRef RegisterPrefix
) {
886 StringRef Tok
= Op
.Token
;
888 // If this token is not an isolated token, i.e., it isn't separated from
889 // other tokens (e.g. with whitespace), don't interpret it as a register name.
890 if (!Op
.IsIsolatedToken
)
893 if (RegisterPrefix
.empty()) {
894 std::string LoweredTok
= Tok
.lower();
895 if (const CodeGenRegister
*Reg
= Info
.Target
.getRegisterByName(LoweredTok
))
896 Op
.SingletonReg
= Reg
->TheDef
;
900 if (!Tok
.startswith(RegisterPrefix
))
903 StringRef RegName
= Tok
.substr(RegisterPrefix
.size());
904 if (const CodeGenRegister
*Reg
= Info
.Target
.getRegisterByName(RegName
))
905 Op
.SingletonReg
= Reg
->TheDef
;
907 // If there is no register prefix (i.e. "%" in "%eax"), then this may
908 // be some random non-register token, just ignore it.
911 void MatchableInfo::initialize(const AsmMatcherInfo
&Info
,
912 SmallPtrSetImpl
<Record
*> &SingletonRegisters
,
913 AsmVariantInfo
const &Variant
,
914 bool HasMnemonicFirst
) {
915 AsmVariantID
= Variant
.AsmVariantNo
;
917 CodeGenInstruction::FlattenAsmStringVariants(AsmString
,
918 Variant
.AsmVariantNo
);
920 tokenizeAsmString(Info
, Variant
);
922 // The first token of the instruction is the mnemonic, which must be a
923 // simple string, not a $foo variable or a singleton register.
924 if (AsmOperands
.empty())
925 PrintFatalError(TheDef
->getLoc(),
926 "Instruction '" + TheDef
->getName() + "' has no tokens");
928 assert(!AsmOperands
[0].Token
.empty());
929 if (HasMnemonicFirst
) {
930 Mnemonic
= AsmOperands
[0].Token
;
931 if (Mnemonic
[0] == '$')
932 PrintFatalError(TheDef
->getLoc(),
933 "Invalid instruction mnemonic '" + Mnemonic
+ "'!");
935 // Remove the first operand, it is tracked in the mnemonic field.
936 AsmOperands
.erase(AsmOperands
.begin());
937 } else if (AsmOperands
[0].Token
[0] != '$')
938 Mnemonic
= AsmOperands
[0].Token
;
940 // Compute the require features.
941 for (Record
*Predicate
: TheDef
->getValueAsListOfDefs("Predicates"))
942 if (const SubtargetFeatureInfo
*Feature
=
943 Info
.getSubtargetFeature(Predicate
))
944 RequiredFeatures
.push_back(Feature
);
946 // Collect singleton registers, if used.
947 for (MatchableInfo::AsmOperand
&Op
: AsmOperands
) {
948 extractSingletonRegisterForAsmOperand(Op
, Info
, Variant
.RegisterPrefix
);
949 if (Record
*Reg
= Op
.SingletonReg
)
950 SingletonRegisters
.insert(Reg
);
953 const RecordVal
*DepMask
= TheDef
->getValue("DeprecatedFeatureMask");
955 DepMask
= TheDef
->getValue("ComplexDeprecationPredicate");
958 DepMask
? !DepMask
->getValue()->getAsUnquotedString().empty() : false;
961 /// Append an AsmOperand for the given substring of AsmString.
962 void MatchableInfo::addAsmOperand(StringRef Token
, bool IsIsolatedToken
) {
963 AsmOperands
.push_back(AsmOperand(IsIsolatedToken
, Token
));
966 /// tokenizeAsmString - Tokenize a simplified assembly string.
967 void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo
&Info
,
968 AsmVariantInfo
const &Variant
) {
969 StringRef String
= AsmString
;
972 bool IsIsolatedToken
= true;
973 for (size_t i
= 0, e
= String
.size(); i
!= e
; ++i
) {
974 char Char
= String
[i
];
975 if (Variant
.BreakCharacters
.find(Char
) != std::string::npos
) {
977 addAsmOperand(String
.slice(Prev
, i
), false);
979 IsIsolatedToken
= false;
984 if (Variant
.TokenizingCharacters
.find(Char
) != std::string::npos
) {
986 addAsmOperand(String
.slice(Prev
, i
), IsIsolatedToken
);
988 IsIsolatedToken
= false;
990 addAsmOperand(String
.slice(i
, i
+ 1), IsIsolatedToken
);
992 IsIsolatedToken
= true;
995 if (Variant
.SeparatorCharacters
.find(Char
) != std::string::npos
) {
997 addAsmOperand(String
.slice(Prev
, i
), IsIsolatedToken
);
1001 IsIsolatedToken
= true;
1008 addAsmOperand(String
.slice(Prev
, i
), false);
1010 IsIsolatedToken
= false;
1013 assert(i
!= String
.size() && "Invalid quoted character");
1014 addAsmOperand(String
.slice(i
, i
+ 1), IsIsolatedToken
);
1016 IsIsolatedToken
= false;
1021 addAsmOperand(String
.slice(Prev
, i
), false);
1023 IsIsolatedToken
= false;
1026 // If this isn't "${", start new identifier looking like "$xxx"
1027 if (i
+ 1 == String
.size() || String
[i
+ 1] != '{') {
1032 size_t EndPos
= String
.find('}', i
);
1033 assert(EndPos
!= StringRef::npos
&&
1034 "Missing brace in operand reference!");
1035 addAsmOperand(String
.slice(i
, EndPos
+1), IsIsolatedToken
);
1038 IsIsolatedToken
= false;
1047 if (InTok
&& Prev
!= String
.size())
1048 addAsmOperand(String
.substr(Prev
), IsIsolatedToken
);
1051 bool MatchableInfo::validate(StringRef CommentDelimiter
, bool IsAlias
) const {
1052 // Reject matchables with no .s string.
1053 if (AsmString
.empty())
1054 PrintFatalError(TheDef
->getLoc(), "instruction with empty asm string");
1056 // Reject any matchables with a newline in them, they should be marked
1057 // isCodeGenOnly if they are pseudo instructions.
1058 if (AsmString
.find('\n') != std::string::npos
)
1059 PrintFatalError(TheDef
->getLoc(),
1060 "multiline instruction is not valid for the asmparser, "
1061 "mark it isCodeGenOnly");
1063 // Remove comments from the asm string. We know that the asmstring only
1065 if (!CommentDelimiter
.empty() &&
1066 StringRef(AsmString
).find(CommentDelimiter
) != StringRef::npos
)
1067 PrintFatalError(TheDef
->getLoc(),
1068 "asmstring for instruction has comment character in it, "
1069 "mark it isCodeGenOnly");
1071 // Reject matchables with operand modifiers, these aren't something we can
1072 // handle, the target should be refactored to use operands instead of
1075 // Also, check for instructions which reference the operand multiple times,
1076 // if they don't define a custom AsmMatcher: this implies a constraint that
1077 // the built-in matching code would not honor.
1078 std::set
<std::string
> OperandNames
;
1079 for (const AsmOperand
&Op
: AsmOperands
) {
1080 StringRef Tok
= Op
.Token
;
1081 if (Tok
[0] == '$' && Tok
.find(':') != StringRef::npos
)
1082 PrintFatalError(TheDef
->getLoc(),
1083 "matchable with operand modifier '" + Tok
+
1084 "' not supported by asm matcher. Mark isCodeGenOnly!");
1085 // Verify that any operand is only mentioned once.
1086 // We reject aliases and ignore instructions for now.
1087 if (!IsAlias
&& TheDef
->getValueAsString("AsmMatchConverter").empty() &&
1088 Tok
[0] == '$' && !OperandNames
.insert(Tok
).second
) {
1090 errs() << "warning: '" << TheDef
->getName() << "': "
1091 << "ignoring instruction with tied operand '"
1101 static std::string
getEnumNameForToken(StringRef Str
) {
1104 for (StringRef::iterator it
= Str
.begin(), ie
= Str
.end(); it
!= ie
; ++it
) {
1106 case '*': Res
+= "_STAR_"; break;
1107 case '%': Res
+= "_PCT_"; break;
1108 case ':': Res
+= "_COLON_"; break;
1109 case '!': Res
+= "_EXCLAIM_"; break;
1110 case '.': Res
+= "_DOT_"; break;
1111 case '<': Res
+= "_LT_"; break;
1112 case '>': Res
+= "_GT_"; break;
1113 case '-': Res
+= "_MINUS_"; break;
1115 if ((*it
>= 'A' && *it
<= 'Z') ||
1116 (*it
>= 'a' && *it
<= 'z') ||
1117 (*it
>= '0' && *it
<= '9'))
1120 Res
+= "_" + utostr((unsigned) *it
) + "_";
1127 ClassInfo
*AsmMatcherInfo::getTokenClass(StringRef Token
) {
1128 ClassInfo
*&Entry
= TokenClasses
[Token
];
1131 Classes
.emplace_front();
1132 Entry
= &Classes
.front();
1133 Entry
->Kind
= ClassInfo::Token
;
1134 Entry
->ClassName
= "Token";
1135 Entry
->Name
= "MCK_" + getEnumNameForToken(Token
);
1136 Entry
->ValueName
= Token
;
1137 Entry
->PredicateMethod
= "<invalid>";
1138 Entry
->RenderMethod
= "<invalid>";
1139 Entry
->ParserMethod
= "";
1140 Entry
->DiagnosticType
= "";
1141 Entry
->IsOptional
= false;
1142 Entry
->DefaultMethod
= "<invalid>";
1149 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo
&OI
,
1151 Record
*Rec
= OI
.Rec
;
1153 Rec
= cast
<DefInit
>(OI
.MIOperandInfo
->getArg(SubOpIdx
))->getDef();
1154 return getOperandClass(Rec
, SubOpIdx
);
1158 AsmMatcherInfo::getOperandClass(Record
*Rec
, int SubOpIdx
) {
1159 if (Rec
->isSubClassOf("RegisterOperand")) {
1160 // RegisterOperand may have an associated ParserMatchClass. If it does,
1161 // use it, else just fall back to the underlying register class.
1162 const RecordVal
*R
= Rec
->getValue("ParserMatchClass");
1163 if (!R
|| !R
->getValue())
1164 PrintFatalError(Rec
->getLoc(),
1165 "Record `" + Rec
->getName() +
1166 "' does not have a ParserMatchClass!\n");
1168 if (DefInit
*DI
= dyn_cast
<DefInit
>(R
->getValue())) {
1169 Record
*MatchClass
= DI
->getDef();
1170 if (ClassInfo
*CI
= AsmOperandClasses
[MatchClass
])
1174 // No custom match class. Just use the register class.
1175 Record
*ClassRec
= Rec
->getValueAsDef("RegClass");
1177 PrintFatalError(Rec
->getLoc(), "RegisterOperand `" + Rec
->getName() +
1178 "' has no associated register class!\n");
1179 if (ClassInfo
*CI
= RegisterClassClasses
[ClassRec
])
1181 PrintFatalError(Rec
->getLoc(), "register class has no class info!");
1184 if (Rec
->isSubClassOf("RegisterClass")) {
1185 if (ClassInfo
*CI
= RegisterClassClasses
[Rec
])
1187 PrintFatalError(Rec
->getLoc(), "register class has no class info!");
1190 if (!Rec
->isSubClassOf("Operand"))
1191 PrintFatalError(Rec
->getLoc(), "Operand `" + Rec
->getName() +
1192 "' does not derive from class Operand!\n");
1193 Record
*MatchClass
= Rec
->getValueAsDef("ParserMatchClass");
1194 if (ClassInfo
*CI
= AsmOperandClasses
[MatchClass
])
1197 PrintFatalError(Rec
->getLoc(), "operand has no match class!");
1200 struct LessRegisterSet
{
1201 bool operator() (const RegisterSet
&LHS
, const RegisterSet
& RHS
) const {
1202 // std::set<T> defines its own compariso "operator<", but it
1203 // performs a lexicographical comparison by T's innate comparison
1204 // for some reason. We don't want non-deterministic pointer
1205 // comparisons so use this instead.
1206 return std::lexicographical_compare(LHS
.begin(), LHS
.end(),
1207 RHS
.begin(), RHS
.end(),
1212 void AsmMatcherInfo::
1213 buildRegisterClasses(SmallPtrSetImpl
<Record
*> &SingletonRegisters
) {
1214 const auto &Registers
= Target
.getRegBank().getRegisters();
1215 auto &RegClassList
= Target
.getRegBank().getRegClasses();
1217 typedef std::set
<RegisterSet
, LessRegisterSet
> RegisterSetSet
;
1219 // The register sets used for matching.
1220 RegisterSetSet RegisterSets
;
1222 // Gather the defined sets.
1223 for (const CodeGenRegisterClass
&RC
: RegClassList
)
1224 RegisterSets
.insert(
1225 RegisterSet(RC
.getOrder().begin(), RC
.getOrder().end()));
1227 // Add any required singleton sets.
1228 for (Record
*Rec
: SingletonRegisters
) {
1229 RegisterSets
.insert(RegisterSet(&Rec
, &Rec
+ 1));
1232 // Introduce derived sets where necessary (when a register does not determine
1233 // a unique register set class), and build the mapping of registers to the set
1234 // they should classify to.
1235 std::map
<Record
*, RegisterSet
> RegisterMap
;
1236 for (const CodeGenRegister
&CGR
: Registers
) {
1237 // Compute the intersection of all sets containing this register.
1238 RegisterSet ContainingSet
;
1240 for (const RegisterSet
&RS
: RegisterSets
) {
1241 if (!RS
.count(CGR
.TheDef
))
1244 if (ContainingSet
.empty()) {
1250 std::swap(Tmp
, ContainingSet
);
1251 std::insert_iterator
<RegisterSet
> II(ContainingSet
,
1252 ContainingSet
.begin());
1253 std::set_intersection(Tmp
.begin(), Tmp
.end(), RS
.begin(), RS
.end(), II
,
1257 if (!ContainingSet
.empty()) {
1258 RegisterSets
.insert(ContainingSet
);
1259 RegisterMap
.insert(std::make_pair(CGR
.TheDef
, ContainingSet
));
1263 // Construct the register classes.
1264 std::map
<RegisterSet
, ClassInfo
*, LessRegisterSet
> RegisterSetClasses
;
1266 for (const RegisterSet
&RS
: RegisterSets
) {
1267 Classes
.emplace_front();
1268 ClassInfo
*CI
= &Classes
.front();
1269 CI
->Kind
= ClassInfo::RegisterClass0
+ Index
;
1270 CI
->ClassName
= "Reg" + utostr(Index
);
1271 CI
->Name
= "MCK_Reg" + utostr(Index
);
1273 CI
->PredicateMethod
= ""; // unused
1274 CI
->RenderMethod
= "addRegOperands";
1276 // FIXME: diagnostic type.
1277 CI
->DiagnosticType
= "";
1278 CI
->IsOptional
= false;
1279 CI
->DefaultMethod
= ""; // unused
1280 RegisterSetClasses
.insert(std::make_pair(RS
, CI
));
1284 // Find the superclasses; we could compute only the subgroup lattice edges,
1285 // but there isn't really a point.
1286 for (const RegisterSet
&RS
: RegisterSets
) {
1287 ClassInfo
*CI
= RegisterSetClasses
[RS
];
1288 for (const RegisterSet
&RS2
: RegisterSets
)
1290 std::includes(RS2
.begin(), RS2
.end(), RS
.begin(), RS
.end(),
1292 CI
->SuperClasses
.push_back(RegisterSetClasses
[RS2
]);
1295 // Name the register classes which correspond to a user defined RegisterClass.
1296 for (const CodeGenRegisterClass
&RC
: RegClassList
) {
1297 // Def will be NULL for non-user defined register classes.
1298 Record
*Def
= RC
.getDef();
1301 ClassInfo
*CI
= RegisterSetClasses
[RegisterSet(RC
.getOrder().begin(),
1302 RC
.getOrder().end())];
1303 if (CI
->ValueName
.empty()) {
1304 CI
->ClassName
= RC
.getName();
1305 CI
->Name
= "MCK_" + RC
.getName();
1306 CI
->ValueName
= RC
.getName();
1308 CI
->ValueName
= CI
->ValueName
+ "," + RC
.getName();
1310 Init
*DiagnosticType
= Def
->getValueInit("DiagnosticType");
1311 if (StringInit
*SI
= dyn_cast
<StringInit
>(DiagnosticType
))
1312 CI
->DiagnosticType
= SI
->getValue();
1314 Init
*DiagnosticString
= Def
->getValueInit("DiagnosticString");
1315 if (StringInit
*SI
= dyn_cast
<StringInit
>(DiagnosticString
))
1316 CI
->DiagnosticString
= SI
->getValue();
1318 // If we have a diagnostic string but the diagnostic type is not specified
1319 // explicitly, create an anonymous diagnostic type.
1320 if (!CI
->DiagnosticString
.empty() && CI
->DiagnosticType
.empty())
1321 CI
->DiagnosticType
= RC
.getName();
1323 RegisterClassClasses
.insert(std::make_pair(Def
, CI
));
1326 // Populate the map for individual registers.
1327 for (std::map
<Record
*, RegisterSet
>::iterator it
= RegisterMap
.begin(),
1328 ie
= RegisterMap
.end(); it
!= ie
; ++it
)
1329 RegisterClasses
[it
->first
] = RegisterSetClasses
[it
->second
];
1331 // Name the register classes which correspond to singleton registers.
1332 for (Record
*Rec
: SingletonRegisters
) {
1333 ClassInfo
*CI
= RegisterClasses
[Rec
];
1334 assert(CI
&& "Missing singleton register class info!");
1336 if (CI
->ValueName
.empty()) {
1337 CI
->ClassName
= Rec
->getName();
1338 CI
->Name
= "MCK_" + Rec
->getName().str();
1339 CI
->ValueName
= Rec
->getName();
1341 CI
->ValueName
= CI
->ValueName
+ "," + Rec
->getName().str();
1345 void AsmMatcherInfo::buildOperandClasses() {
1346 std::vector
<Record
*> AsmOperands
=
1347 Records
.getAllDerivedDefinitions("AsmOperandClass");
1349 // Pre-populate AsmOperandClasses map.
1350 for (Record
*Rec
: AsmOperands
) {
1351 Classes
.emplace_front();
1352 AsmOperandClasses
[Rec
] = &Classes
.front();
1356 for (Record
*Rec
: AsmOperands
) {
1357 ClassInfo
*CI
= AsmOperandClasses
[Rec
];
1358 CI
->Kind
= ClassInfo::UserClass0
+ Index
;
1360 ListInit
*Supers
= Rec
->getValueAsListInit("SuperClasses");
1361 for (Init
*I
: Supers
->getValues()) {
1362 DefInit
*DI
= dyn_cast
<DefInit
>(I
);
1364 PrintError(Rec
->getLoc(), "Invalid super class reference!");
1368 ClassInfo
*SC
= AsmOperandClasses
[DI
->getDef()];
1370 PrintError(Rec
->getLoc(), "Invalid super class reference!");
1372 CI
->SuperClasses
.push_back(SC
);
1374 CI
->ClassName
= Rec
->getValueAsString("Name");
1375 CI
->Name
= "MCK_" + CI
->ClassName
;
1376 CI
->ValueName
= Rec
->getName();
1378 // Get or construct the predicate method name.
1379 Init
*PMName
= Rec
->getValueInit("PredicateMethod");
1380 if (StringInit
*SI
= dyn_cast
<StringInit
>(PMName
)) {
1381 CI
->PredicateMethod
= SI
->getValue();
1383 assert(isa
<UnsetInit
>(PMName
) && "Unexpected PredicateMethod field!");
1384 CI
->PredicateMethod
= "is" + CI
->ClassName
;
1387 // Get or construct the render method name.
1388 Init
*RMName
= Rec
->getValueInit("RenderMethod");
1389 if (StringInit
*SI
= dyn_cast
<StringInit
>(RMName
)) {
1390 CI
->RenderMethod
= SI
->getValue();
1392 assert(isa
<UnsetInit
>(RMName
) && "Unexpected RenderMethod field!");
1393 CI
->RenderMethod
= "add" + CI
->ClassName
+ "Operands";
1396 // Get the parse method name or leave it as empty.
1397 Init
*PRMName
= Rec
->getValueInit("ParserMethod");
1398 if (StringInit
*SI
= dyn_cast
<StringInit
>(PRMName
))
1399 CI
->ParserMethod
= SI
->getValue();
1401 // Get the diagnostic type and string or leave them as empty.
1402 Init
*DiagnosticType
= Rec
->getValueInit("DiagnosticType");
1403 if (StringInit
*SI
= dyn_cast
<StringInit
>(DiagnosticType
))
1404 CI
->DiagnosticType
= SI
->getValue();
1405 Init
*DiagnosticString
= Rec
->getValueInit("DiagnosticString");
1406 if (StringInit
*SI
= dyn_cast
<StringInit
>(DiagnosticString
))
1407 CI
->DiagnosticString
= SI
->getValue();
1408 // If we have a DiagnosticString, we need a DiagnosticType for use within
1410 if (!CI
->DiagnosticString
.empty() && CI
->DiagnosticType
.empty())
1411 CI
->DiagnosticType
= CI
->ClassName
;
1413 Init
*IsOptional
= Rec
->getValueInit("IsOptional");
1414 if (BitInit
*BI
= dyn_cast
<BitInit
>(IsOptional
))
1415 CI
->IsOptional
= BI
->getValue();
1417 // Get or construct the default method name.
1418 Init
*DMName
= Rec
->getValueInit("DefaultMethod");
1419 if (StringInit
*SI
= dyn_cast
<StringInit
>(DMName
)) {
1420 CI
->DefaultMethod
= SI
->getValue();
1422 assert(isa
<UnsetInit
>(DMName
) && "Unexpected DefaultMethod field!");
1423 CI
->DefaultMethod
= "default" + CI
->ClassName
+ "Operands";
1430 AsmMatcherInfo::AsmMatcherInfo(Record
*asmParser
,
1431 CodeGenTarget
&target
,
1432 RecordKeeper
&records
)
1433 : Records(records
), AsmParser(asmParser
), Target(target
) {
1436 /// buildOperandMatchInfo - Build the necessary information to handle user
1437 /// defined operand parsing methods.
1438 void AsmMatcherInfo::buildOperandMatchInfo() {
1440 /// Map containing a mask with all operands indices that can be found for
1441 /// that class inside a instruction.
1442 typedef std::map
<ClassInfo
*, unsigned, less_ptr
<ClassInfo
>> OpClassMaskTy
;
1443 OpClassMaskTy OpClassMask
;
1445 for (const auto &MI
: Matchables
) {
1446 OpClassMask
.clear();
1448 // Keep track of all operands of this instructions which belong to the
1450 for (unsigned i
= 0, e
= MI
->AsmOperands
.size(); i
!= e
; ++i
) {
1451 const MatchableInfo::AsmOperand
&Op
= MI
->AsmOperands
[i
];
1452 if (Op
.Class
->ParserMethod
.empty())
1454 unsigned &OperandMask
= OpClassMask
[Op
.Class
];
1455 OperandMask
|= (1 << i
);
1458 // Generate operand match info for each mnemonic/operand class pair.
1459 for (const auto &OCM
: OpClassMask
) {
1460 unsigned OpMask
= OCM
.second
;
1461 ClassInfo
*CI
= OCM
.first
;
1462 OperandMatchInfo
.push_back(OperandMatchEntry::create(MI
.get(), CI
,
1468 void AsmMatcherInfo::buildInfo() {
1469 // Build information about all of the AssemblerPredicates.
1470 const std::vector
<std::pair
<Record
*, SubtargetFeatureInfo
>>
1471 &SubtargetFeaturePairs
= SubtargetFeatureInfo::getAll(Records
);
1472 SubtargetFeatures
.insert(SubtargetFeaturePairs
.begin(),
1473 SubtargetFeaturePairs
.end());
1475 for (const auto &Pair
: SubtargetFeatures
)
1476 LLVM_DEBUG(Pair
.second
.dump());
1479 bool HasMnemonicFirst
= AsmParser
->getValueAsBit("HasMnemonicFirst");
1480 bool ReportMultipleNearMisses
=
1481 AsmParser
->getValueAsBit("ReportMultipleNearMisses");
1483 // Parse the instructions; we need to do this first so that we can gather the
1484 // singleton register classes.
1485 SmallPtrSet
<Record
*, 16> SingletonRegisters
;
1486 unsigned VariantCount
= Target
.getAsmParserVariantCount();
1487 for (unsigned VC
= 0; VC
!= VariantCount
; ++VC
) {
1488 Record
*AsmVariant
= Target
.getAsmParserVariant(VC
);
1489 StringRef CommentDelimiter
=
1490 AsmVariant
->getValueAsString("CommentDelimiter");
1491 AsmVariantInfo Variant
;
1492 Variant
.RegisterPrefix
= AsmVariant
->getValueAsString("RegisterPrefix");
1493 Variant
.TokenizingCharacters
=
1494 AsmVariant
->getValueAsString("TokenizingCharacters");
1495 Variant
.SeparatorCharacters
=
1496 AsmVariant
->getValueAsString("SeparatorCharacters");
1497 Variant
.BreakCharacters
=
1498 AsmVariant
->getValueAsString("BreakCharacters");
1499 Variant
.Name
= AsmVariant
->getValueAsString("Name");
1500 Variant
.AsmVariantNo
= AsmVariant
->getValueAsInt("Variant");
1502 for (const CodeGenInstruction
*CGI
: Target
.getInstructionsByEnumValue()) {
1504 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1505 // filter the set of instructions we consider.
1506 if (!StringRef(CGI
->TheDef
->getName()).startswith(MatchPrefix
))
1509 // Ignore "codegen only" instructions.
1510 if (CGI
->TheDef
->getValueAsBit("isCodeGenOnly"))
1513 // Ignore instructions for different instructions
1514 StringRef V
= CGI
->TheDef
->getValueAsString("AsmVariantName");
1515 if (!V
.empty() && V
!= Variant
.Name
)
1518 auto II
= llvm::make_unique
<MatchableInfo
>(*CGI
);
1520 II
->initialize(*this, SingletonRegisters
, Variant
, HasMnemonicFirst
);
1522 // Ignore instructions which shouldn't be matched and diagnose invalid
1523 // instruction definitions with an error.
1524 if (!II
->validate(CommentDelimiter
, false))
1527 Matchables
.push_back(std::move(II
));
1530 // Parse all of the InstAlias definitions and stick them in the list of
1532 std::vector
<Record
*> AllInstAliases
=
1533 Records
.getAllDerivedDefinitions("InstAlias");
1534 for (unsigned i
= 0, e
= AllInstAliases
.size(); i
!= e
; ++i
) {
1535 auto Alias
= llvm::make_unique
<CodeGenInstAlias
>(AllInstAliases
[i
],
1538 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1539 // filter the set of instruction aliases we consider, based on the target
1541 if (!StringRef(Alias
->ResultInst
->TheDef
->getName())
1542 .startswith( MatchPrefix
))
1545 StringRef V
= Alias
->TheDef
->getValueAsString("AsmVariantName");
1546 if (!V
.empty() && V
!= Variant
.Name
)
1549 auto II
= llvm::make_unique
<MatchableInfo
>(std::move(Alias
));
1551 II
->initialize(*this, SingletonRegisters
, Variant
, HasMnemonicFirst
);
1553 // Validate the alias definitions.
1554 II
->validate(CommentDelimiter
, true);
1556 Matchables
.push_back(std::move(II
));
1560 // Build info for the register classes.
1561 buildRegisterClasses(SingletonRegisters
);
1563 // Build info for the user defined assembly operand classes.
1564 buildOperandClasses();
1566 // Build the information about matchables, now that we have fully formed
1568 std::vector
<std::unique_ptr
<MatchableInfo
>> NewMatchables
;
1569 for (auto &II
: Matchables
) {
1570 // Parse the tokens after the mnemonic.
1571 // Note: buildInstructionOperandReference may insert new AsmOperands, so
1572 // don't precompute the loop bound.
1573 for (unsigned i
= 0; i
!= II
->AsmOperands
.size(); ++i
) {
1574 MatchableInfo::AsmOperand
&Op
= II
->AsmOperands
[i
];
1575 StringRef Token
= Op
.Token
;
1577 // Check for singleton registers.
1578 if (Record
*RegRecord
= Op
.SingletonReg
) {
1579 Op
.Class
= RegisterClasses
[RegRecord
];
1580 assert(Op
.Class
&& Op
.Class
->Registers
.size() == 1 &&
1581 "Unexpected class for singleton register");
1585 // Check for simple tokens.
1586 if (Token
[0] != '$') {
1587 Op
.Class
= getTokenClass(Token
);
1591 if (Token
.size() > 1 && isdigit(Token
[1])) {
1592 Op
.Class
= getTokenClass(Token
);
1596 // Otherwise this is an operand reference.
1597 StringRef OperandName
;
1598 if (Token
[1] == '{')
1599 OperandName
= Token
.substr(2, Token
.size() - 3);
1601 OperandName
= Token
.substr(1);
1603 if (II
->DefRec
.is
<const CodeGenInstruction
*>())
1604 buildInstructionOperandReference(II
.get(), OperandName
, i
);
1606 buildAliasOperandReference(II
.get(), OperandName
, Op
);
1609 if (II
->DefRec
.is
<const CodeGenInstruction
*>()) {
1610 II
->buildInstructionResultOperands();
1611 // If the instruction has a two-operand alias, build up the
1612 // matchable here. We'll add them in bulk at the end to avoid
1613 // confusing this loop.
1614 StringRef Constraint
=
1615 II
->TheDef
->getValueAsString("TwoOperandAliasConstraint");
1616 if (Constraint
!= "") {
1617 // Start by making a copy of the original matchable.
1618 auto AliasII
= llvm::make_unique
<MatchableInfo
>(*II
);
1620 // Adjust it to be a two-operand alias.
1621 AliasII
->formTwoOperandAlias(Constraint
);
1623 // Add the alias to the matchables list.
1624 NewMatchables
.push_back(std::move(AliasII
));
1627 // FIXME: The tied operands checking is not yet integrated with the
1628 // framework for reporting multiple near misses. To prevent invalid
1629 // formats from being matched with an alias if a tied-operands check
1630 // would otherwise have disallowed it, we just disallow such constructs
1631 // in TableGen completely.
1632 II
->buildAliasResultOperands(!ReportMultipleNearMisses
);
1634 if (!NewMatchables
.empty())
1635 Matchables
.insert(Matchables
.end(),
1636 std::make_move_iterator(NewMatchables
.begin()),
1637 std::make_move_iterator(NewMatchables
.end()));
1639 // Process token alias definitions and set up the associated superclass
1641 std::vector
<Record
*> AllTokenAliases
=
1642 Records
.getAllDerivedDefinitions("TokenAlias");
1643 for (Record
*Rec
: AllTokenAliases
) {
1644 ClassInfo
*FromClass
= getTokenClass(Rec
->getValueAsString("FromToken"));
1645 ClassInfo
*ToClass
= getTokenClass(Rec
->getValueAsString("ToToken"));
1646 if (FromClass
== ToClass
)
1647 PrintFatalError(Rec
->getLoc(),
1648 "error: Destination value identical to source value.");
1649 FromClass
->SuperClasses
.push_back(ToClass
);
1652 // Reorder classes so that classes precede super classes.
1655 #ifdef EXPENSIVE_CHECKS
1656 // Verify that the table is sorted and operator < works transitively.
1657 for (auto I
= Classes
.begin(), E
= Classes
.end(); I
!= E
; ++I
) {
1658 for (auto J
= I
; J
!= E
; ++J
) {
1660 assert(I
== J
|| !J
->isSubsetOf(*I
));
1666 /// buildInstructionOperandReference - The specified operand is a reference to a
1667 /// named operand such as $src. Resolve the Class and OperandInfo pointers.
1668 void AsmMatcherInfo::
1669 buildInstructionOperandReference(MatchableInfo
*II
,
1670 StringRef OperandName
,
1671 unsigned AsmOpIdx
) {
1672 const CodeGenInstruction
&CGI
= *II
->DefRec
.get
<const CodeGenInstruction
*>();
1673 const CGIOperandList
&Operands
= CGI
.Operands
;
1674 MatchableInfo::AsmOperand
*Op
= &II
->AsmOperands
[AsmOpIdx
];
1676 // Map this token to an operand.
1678 if (!Operands
.hasOperandNamed(OperandName
, Idx
))
1679 PrintFatalError(II
->TheDef
->getLoc(),
1680 "error: unable to find operand: '" + OperandName
+ "'");
1682 // If the instruction operand has multiple suboperands, but the parser
1683 // match class for the asm operand is still the default "ImmAsmOperand",
1684 // then handle each suboperand separately.
1685 if (Op
->SubOpIdx
== -1 && Operands
[Idx
].MINumOperands
> 1) {
1686 Record
*Rec
= Operands
[Idx
].Rec
;
1687 assert(Rec
->isSubClassOf("Operand") && "Unexpected operand!");
1688 Record
*MatchClass
= Rec
->getValueAsDef("ParserMatchClass");
1689 if (MatchClass
&& MatchClass
->getValueAsString("Name") == "Imm") {
1690 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1691 StringRef Token
= Op
->Token
; // save this in case Op gets moved
1692 for (unsigned SI
= 1, SE
= Operands
[Idx
].MINumOperands
; SI
!= SE
; ++SI
) {
1693 MatchableInfo::AsmOperand
NewAsmOp(/*IsIsolatedToken=*/true, Token
);
1694 NewAsmOp
.SubOpIdx
= SI
;
1695 II
->AsmOperands
.insert(II
->AsmOperands
.begin()+AsmOpIdx
+SI
, NewAsmOp
);
1697 // Replace Op with first suboperand.
1698 Op
= &II
->AsmOperands
[AsmOpIdx
]; // update the pointer in case it moved
1703 // Set up the operand class.
1704 Op
->Class
= getOperandClass(Operands
[Idx
], Op
->SubOpIdx
);
1705 Op
->OrigSrcOpName
= OperandName
;
1707 // If the named operand is tied, canonicalize it to the untied operand.
1708 // For example, something like:
1709 // (outs GPR:$dst), (ins GPR:$src)
1710 // with an asmstring of
1712 // we want to canonicalize to:
1714 // so that we know how to provide the $dst operand when filling in the result.
1716 if (Operands
[Idx
].MINumOperands
== 1)
1717 OITied
= Operands
[Idx
].getTiedRegister();
1719 // The tied operand index is an MIOperand index, find the operand that
1721 std::pair
<unsigned, unsigned> Idx
= Operands
.getSubOperandNumber(OITied
);
1722 OperandName
= Operands
[Idx
.first
].Name
;
1723 Op
->SubOpIdx
= Idx
.second
;
1726 Op
->SrcOpName
= OperandName
;
1729 /// buildAliasOperandReference - When parsing an operand reference out of the
1730 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1731 /// operand reference is by looking it up in the result pattern definition.
1732 void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo
*II
,
1733 StringRef OperandName
,
1734 MatchableInfo::AsmOperand
&Op
) {
1735 const CodeGenInstAlias
&CGA
= *II
->DefRec
.get
<const CodeGenInstAlias
*>();
1737 // Set up the operand class.
1738 for (unsigned i
= 0, e
= CGA
.ResultOperands
.size(); i
!= e
; ++i
)
1739 if (CGA
.ResultOperands
[i
].isRecord() &&
1740 CGA
.ResultOperands
[i
].getName() == OperandName
) {
1741 // It's safe to go with the first one we find, because CodeGenInstAlias
1742 // validates that all operands with the same name have the same record.
1743 Op
.SubOpIdx
= CGA
.ResultInstOperandIndex
[i
].second
;
1744 // Use the match class from the Alias definition, not the
1745 // destination instruction, as we may have an immediate that's
1746 // being munged by the match class.
1747 Op
.Class
= getOperandClass(CGA
.ResultOperands
[i
].getRecord(),
1749 Op
.SrcOpName
= OperandName
;
1750 Op
.OrigSrcOpName
= OperandName
;
1754 PrintFatalError(II
->TheDef
->getLoc(),
1755 "error: unable to find operand: '" + OperandName
+ "'");
1758 void MatchableInfo::buildInstructionResultOperands() {
1759 const CodeGenInstruction
*ResultInst
= getResultInst();
1761 // Loop over all operands of the result instruction, determining how to
1763 for (const CGIOperandList::OperandInfo
&OpInfo
: ResultInst
->Operands
) {
1764 // If this is a tied operand, just copy from the previously handled operand.
1766 if (OpInfo
.MINumOperands
== 1)
1767 TiedOp
= OpInfo
.getTiedRegister();
1769 int TiedSrcOperand
= findAsmOperandOriginallyNamed(OpInfo
.Name
);
1770 if (TiedSrcOperand
!= -1 &&
1771 ResOperands
[TiedOp
].Kind
== ResOperand::RenderAsmOperand
)
1772 ResOperands
.push_back(ResOperand::getTiedOp(
1773 TiedOp
, ResOperands
[TiedOp
].AsmOperandNum
, TiedSrcOperand
));
1775 ResOperands
.push_back(ResOperand::getTiedOp(TiedOp
, 0, 0));
1779 int SrcOperand
= findAsmOperandNamed(OpInfo
.Name
);
1780 if (OpInfo
.Name
.empty() || SrcOperand
== -1) {
1781 // This may happen for operands that are tied to a suboperand of a
1782 // complex operand. Simply use a dummy value here; nobody should
1783 // use this operand slot.
1784 // FIXME: The long term goal is for the MCOperand list to not contain
1785 // tied operands at all.
1786 ResOperands
.push_back(ResOperand::getImmOp(0));
1790 // Check if the one AsmOperand populates the entire operand.
1791 unsigned NumOperands
= OpInfo
.MINumOperands
;
1792 if (AsmOperands
[SrcOperand
].SubOpIdx
== -1) {
1793 ResOperands
.push_back(ResOperand::getRenderedOp(SrcOperand
, NumOperands
));
1797 // Add a separate ResOperand for each suboperand.
1798 for (unsigned AI
= 0; AI
< NumOperands
; ++AI
) {
1799 assert(AsmOperands
[SrcOperand
+AI
].SubOpIdx
== (int)AI
&&
1800 AsmOperands
[SrcOperand
+AI
].SrcOpName
== OpInfo
.Name
&&
1801 "unexpected AsmOperands for suboperands");
1802 ResOperands
.push_back(ResOperand::getRenderedOp(SrcOperand
+ AI
, 1));
1807 void MatchableInfo::buildAliasResultOperands(bool AliasConstraintsAreChecked
) {
1808 const CodeGenInstAlias
&CGA
= *DefRec
.get
<const CodeGenInstAlias
*>();
1809 const CodeGenInstruction
*ResultInst
= getResultInst();
1811 // Map of: $reg -> #lastref
1812 // where $reg is the name of the operand in the asm string
1813 // where #lastref is the last processed index where $reg was referenced in
1815 SmallDenseMap
<StringRef
, int> OperandRefs
;
1817 // Loop over all operands of the result instruction, determining how to
1819 unsigned AliasOpNo
= 0;
1820 unsigned LastOpNo
= CGA
.ResultInstOperandIndex
.size();
1821 for (unsigned i
= 0, e
= ResultInst
->Operands
.size(); i
!= e
; ++i
) {
1822 const CGIOperandList::OperandInfo
*OpInfo
= &ResultInst
->Operands
[i
];
1824 // If this is a tied operand, just copy from the previously handled operand.
1826 if (OpInfo
->MINumOperands
== 1)
1827 TiedOp
= OpInfo
->getTiedRegister();
1829 unsigned SrcOp1
= 0;
1830 unsigned SrcOp2
= 0;
1832 // If an operand has been specified twice in the asm string,
1833 // add the two source operand's indices to the TiedOp so that
1834 // at runtime the 'tied' constraint is checked.
1835 if (ResOperands
[TiedOp
].Kind
== ResOperand::RenderAsmOperand
) {
1836 SrcOp1
= ResOperands
[TiedOp
].AsmOperandNum
;
1838 // Find the next operand (similarly named operand) in the string.
1839 StringRef Name
= AsmOperands
[SrcOp1
].SrcOpName
;
1840 auto Insert
= OperandRefs
.try_emplace(Name
, SrcOp1
);
1841 SrcOp2
= findAsmOperandNamed(Name
, Insert
.first
->second
);
1843 // Not updating the record in OperandRefs will cause TableGen
1844 // to fail with an error at the end of this function.
1845 if (AliasConstraintsAreChecked
)
1846 Insert
.first
->second
= SrcOp2
;
1848 // In case it only has one reference in the asm string,
1849 // it doesn't need to be checked for tied constraints.
1850 SrcOp2
= (SrcOp2
== (unsigned)-1) ? SrcOp1
: SrcOp2
;
1853 // If the alias operand is of a different operand class, we only want
1854 // to benefit from the tied-operands check and just match the operand
1855 // as a normal, but not copy the original (TiedOp) to the result
1856 // instruction. We do this by passing -1 as the tied operand to copy.
1857 if (ResultInst
->Operands
[i
].Rec
->getName() !=
1858 ResultInst
->Operands
[TiedOp
].Rec
->getName()) {
1859 SrcOp1
= ResOperands
[TiedOp
].AsmOperandNum
;
1860 int SubIdx
= CGA
.ResultInstOperandIndex
[AliasOpNo
].second
;
1861 StringRef Name
= CGA
.ResultOperands
[AliasOpNo
].getName();
1862 SrcOp2
= findAsmOperand(Name
, SubIdx
);
1863 ResOperands
.push_back(
1864 ResOperand::getTiedOp((unsigned)-1, SrcOp1
, SrcOp2
));
1866 ResOperands
.push_back(ResOperand::getTiedOp(TiedOp
, SrcOp1
, SrcOp2
));
1871 // Handle all the suboperands for this operand.
1872 const std::string
&OpName
= OpInfo
->Name
;
1873 for ( ; AliasOpNo
< LastOpNo
&&
1874 CGA
.ResultInstOperandIndex
[AliasOpNo
].first
== i
; ++AliasOpNo
) {
1875 int SubIdx
= CGA
.ResultInstOperandIndex
[AliasOpNo
].second
;
1877 // Find out what operand from the asmparser that this MCInst operand
1879 switch (CGA
.ResultOperands
[AliasOpNo
].Kind
) {
1880 case CodeGenInstAlias::ResultOperand::K_Record
: {
1881 StringRef Name
= CGA
.ResultOperands
[AliasOpNo
].getName();
1882 int SrcOperand
= findAsmOperand(Name
, SubIdx
);
1883 if (SrcOperand
== -1)
1884 PrintFatalError(TheDef
->getLoc(), "Instruction '" +
1885 TheDef
->getName() + "' has operand '" + OpName
+
1886 "' that doesn't appear in asm string!");
1888 // Add it to the operand references. If it is added a second time, the
1889 // record won't be updated and it will fail later on.
1890 OperandRefs
.try_emplace(Name
, SrcOperand
);
1892 unsigned NumOperands
= (SubIdx
== -1 ? OpInfo
->MINumOperands
: 1);
1893 ResOperands
.push_back(ResOperand::getRenderedOp(SrcOperand
,
1897 case CodeGenInstAlias::ResultOperand::K_Imm
: {
1898 int64_t ImmVal
= CGA
.ResultOperands
[AliasOpNo
].getImm();
1899 ResOperands
.push_back(ResOperand::getImmOp(ImmVal
));
1902 case CodeGenInstAlias::ResultOperand::K_Reg
: {
1903 Record
*Reg
= CGA
.ResultOperands
[AliasOpNo
].getRegister();
1904 ResOperands
.push_back(ResOperand::getRegOp(Reg
));
1911 // Check that operands are not repeated more times than is supported.
1912 for (auto &T
: OperandRefs
) {
1913 if (T
.second
!= -1 && findAsmOperandNamed(T
.first
, T
.second
) != -1)
1914 PrintFatalError(TheDef
->getLoc(),
1915 "Operand '" + T
.first
+ "' can never be matched");
1920 getConverterOperandID(const std::string
&Name
,
1921 SmallSetVector
<CachedHashString
, 16> &Table
,
1923 IsNew
= Table
.insert(CachedHashString(Name
));
1925 unsigned ID
= IsNew
? Table
.size() - 1 : find(Table
, Name
) - Table
.begin();
1927 assert(ID
< Table
.size());
1933 emitConvertFuncs(CodeGenTarget
&Target
, StringRef ClassName
,
1934 std::vector
<std::unique_ptr
<MatchableInfo
>> &Infos
,
1935 bool HasMnemonicFirst
, bool HasOptionalOperands
,
1937 SmallSetVector
<CachedHashString
, 16> OperandConversionKinds
;
1938 SmallSetVector
<CachedHashString
, 16> InstructionConversionKinds
;
1939 std::vector
<std::vector
<uint8_t> > ConversionTable
;
1940 size_t MaxRowLength
= 2; // minimum is custom converter plus terminator.
1942 // TargetOperandClass - This is the target's operand class, like X86Operand.
1943 std::string TargetOperandClass
= Target
.getName().str() + "Operand";
1945 // Write the convert function to a separate stream, so we can drop it after
1946 // the enum. We'll build up the conversion handlers for the individual
1947 // operand types opportunistically as we encounter them.
1948 std::string ConvertFnBody
;
1949 raw_string_ostream
CvtOS(ConvertFnBody
);
1950 // Start the unified conversion function.
1951 if (HasOptionalOperands
) {
1952 CvtOS
<< "void " << Target
.getName() << ClassName
<< "::\n"
1953 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1954 << "unsigned Opcode,\n"
1955 << " const OperandVector &Operands,\n"
1956 << " const SmallBitVector &OptionalOperandsMask) {\n";
1958 CvtOS
<< "void " << Target
.getName() << ClassName
<< "::\n"
1959 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1960 << "unsigned Opcode,\n"
1961 << " const OperandVector &Operands) {\n";
1963 CvtOS
<< " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
1964 CvtOS
<< " const uint8_t *Converter = ConversionTable[Kind];\n";
1965 if (HasOptionalOperands
) {
1966 size_t MaxNumOperands
= 0;
1967 for (const auto &MI
: Infos
) {
1968 MaxNumOperands
= std::max(MaxNumOperands
, MI
->AsmOperands
.size());
1970 CvtOS
<< " unsigned DefaultsOffset[" << (MaxNumOperands
+ 1)
1972 CvtOS
<< " assert(OptionalOperandsMask.size() == " << (MaxNumOperands
)
1974 CvtOS
<< " for (unsigned i = 0, NumDefaults = 0; i < " << (MaxNumOperands
)
1976 CvtOS
<< " DefaultsOffset[i + 1] = NumDefaults;\n";
1977 CvtOS
<< " NumDefaults += (OptionalOperandsMask[i] ? 1 : 0);\n";
1980 CvtOS
<< " unsigned OpIdx;\n";
1981 CvtOS
<< " Inst.setOpcode(Opcode);\n";
1982 CvtOS
<< " for (const uint8_t *p = Converter; *p; p+= 2) {\n";
1983 if (HasOptionalOperands
) {
1984 CvtOS
<< " OpIdx = *(p + 1) - DefaultsOffset[*(p + 1)];\n";
1986 CvtOS
<< " OpIdx = *(p + 1);\n";
1988 CvtOS
<< " switch (*p) {\n";
1989 CvtOS
<< " default: llvm_unreachable(\"invalid conversion entry!\");\n";
1990 CvtOS
<< " case CVT_Reg:\n";
1991 CvtOS
<< " static_cast<" << TargetOperandClass
1992 << "&>(*Operands[OpIdx]).addRegOperands(Inst, 1);\n";
1993 CvtOS
<< " break;\n";
1994 CvtOS
<< " case CVT_Tied: {\n";
1995 CvtOS
<< " assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
1996 CvtOS
<< " std::begin(TiedAsmOperandTable)) &&\n";
1997 CvtOS
<< " \"Tied operand not found\");\n";
1998 CvtOS
<< " unsigned TiedResOpnd = TiedAsmOperandTable[OpIdx][0];\n";
1999 CvtOS
<< " if (TiedResOpnd != (uint8_t) -1)\n";
2000 CvtOS
<< " Inst.addOperand(Inst.getOperand(TiedResOpnd));\n";
2001 CvtOS
<< " break;\n";
2004 std::string OperandFnBody
;
2005 raw_string_ostream
OpOS(OperandFnBody
);
2006 // Start the operand number lookup function.
2007 OpOS
<< "void " << Target
.getName() << ClassName
<< "::\n"
2008 << "convertToMapAndConstraints(unsigned Kind,\n";
2010 OpOS
<< "const OperandVector &Operands) {\n"
2011 << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
2012 << " unsigned NumMCOperands = 0;\n"
2013 << " const uint8_t *Converter = ConversionTable[Kind];\n"
2014 << " for (const uint8_t *p = Converter; *p; p+= 2) {\n"
2015 << " switch (*p) {\n"
2016 << " default: llvm_unreachable(\"invalid conversion entry!\");\n"
2017 << " case CVT_Reg:\n"
2018 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2019 << " Operands[*(p + 1)]->setConstraint(\"r\");\n"
2020 << " ++NumMCOperands;\n"
2022 << " case CVT_Tied:\n"
2023 << " ++NumMCOperands;\n"
2026 // Pre-populate the operand conversion kinds with the standard always
2027 // available entries.
2028 OperandConversionKinds
.insert(CachedHashString("CVT_Done"));
2029 OperandConversionKinds
.insert(CachedHashString("CVT_Reg"));
2030 OperandConversionKinds
.insert(CachedHashString("CVT_Tied"));
2031 enum { CVT_Done
, CVT_Reg
, CVT_Tied
};
2033 // Map of e.g. <0, 2, 3> -> "Tie_0_2_3" enum label.
2034 std::map
<std::tuple
<uint8_t, uint8_t, uint8_t>, std::string
>
2035 TiedOperandsEnumMap
;
2037 for (auto &II
: Infos
) {
2038 // Check if we have a custom match function.
2039 StringRef AsmMatchConverter
=
2040 II
->getResultInst()->TheDef
->getValueAsString("AsmMatchConverter");
2041 if (!AsmMatchConverter
.empty() && II
->UseInstAsmMatchConverter
) {
2042 std::string Signature
= ("ConvertCustom_" + AsmMatchConverter
).str();
2043 II
->ConversionFnKind
= Signature
;
2045 // Check if we have already generated this signature.
2046 if (!InstructionConversionKinds
.insert(CachedHashString(Signature
)))
2049 // Remember this converter for the kind enum.
2050 unsigned KindID
= OperandConversionKinds
.size();
2051 OperandConversionKinds
.insert(
2052 CachedHashString("CVT_" + getEnumNameForToken(AsmMatchConverter
)));
2054 // Add the converter row for this instruction.
2055 ConversionTable
.emplace_back();
2056 ConversionTable
.back().push_back(KindID
);
2057 ConversionTable
.back().push_back(CVT_Done
);
2059 // Add the handler to the conversion driver function.
2060 CvtOS
<< " case CVT_"
2061 << getEnumNameForToken(AsmMatchConverter
) << ":\n"
2062 << " " << AsmMatchConverter
<< "(Inst, Operands);\n"
2065 // FIXME: Handle the operand number lookup for custom match functions.
2069 // Build the conversion function signature.
2070 std::string Signature
= "Convert";
2072 std::vector
<uint8_t> ConversionRow
;
2074 // Compute the convert enum and the case body.
2075 MaxRowLength
= std::max(MaxRowLength
, II
->ResOperands
.size()*2 + 1 );
2077 for (unsigned i
= 0, e
= II
->ResOperands
.size(); i
!= e
; ++i
) {
2078 const MatchableInfo::ResOperand
&OpInfo
= II
->ResOperands
[i
];
2080 // Generate code to populate each result operand.
2081 switch (OpInfo
.Kind
) {
2082 case MatchableInfo::ResOperand::RenderAsmOperand
: {
2083 // This comes from something we parsed.
2084 const MatchableInfo::AsmOperand
&Op
=
2085 II
->AsmOperands
[OpInfo
.AsmOperandNum
];
2087 // Registers are always converted the same, don't duplicate the
2088 // conversion function based on them.
2091 Class
= Op
.Class
->isRegisterClass() ? "Reg" : Op
.Class
->ClassName
;
2093 Signature
+= utostr(OpInfo
.MINumOperands
);
2094 Signature
+= "_" + itostr(OpInfo
.AsmOperandNum
);
2096 // Add the conversion kind, if necessary, and get the associated ID
2097 // the index of its entry in the vector).
2098 std::string Name
= "CVT_" + (Op
.Class
->isRegisterClass() ? "Reg" :
2099 Op
.Class
->RenderMethod
);
2100 if (Op
.Class
->IsOptional
) {
2101 // For optional operands we must also care about DefaultMethod
2102 assert(HasOptionalOperands
);
2103 Name
+= "_" + Op
.Class
->DefaultMethod
;
2105 Name
= getEnumNameForToken(Name
);
2107 bool IsNewConverter
= false;
2108 unsigned ID
= getConverterOperandID(Name
, OperandConversionKinds
,
2111 // Add the operand entry to the instruction kind conversion row.
2112 ConversionRow
.push_back(ID
);
2113 ConversionRow
.push_back(OpInfo
.AsmOperandNum
+ HasMnemonicFirst
);
2115 if (!IsNewConverter
)
2118 // This is a new operand kind. Add a handler for it to the
2119 // converter driver.
2120 CvtOS
<< " case " << Name
<< ":\n";
2121 if (Op
.Class
->IsOptional
) {
2122 // If optional operand is not present in actual instruction then we
2123 // should call its DefaultMethod before RenderMethod
2124 assert(HasOptionalOperands
);
2125 CvtOS
<< " if (OptionalOperandsMask[*(p + 1) - 1]) {\n"
2126 << " " << Op
.Class
->DefaultMethod
<< "()"
2127 << "->" << Op
.Class
->RenderMethod
<< "(Inst, "
2128 << OpInfo
.MINumOperands
<< ");\n"
2130 << " static_cast<" << TargetOperandClass
2131 << "&>(*Operands[OpIdx])." << Op
.Class
->RenderMethod
2132 << "(Inst, " << OpInfo
.MINumOperands
<< ");\n"
2135 CvtOS
<< " static_cast<" << TargetOperandClass
2136 << "&>(*Operands[OpIdx])." << Op
.Class
->RenderMethod
2137 << "(Inst, " << OpInfo
.MINumOperands
<< ");\n";
2139 CvtOS
<< " break;\n";
2141 // Add a handler for the operand number lookup.
2142 OpOS
<< " case " << Name
<< ":\n"
2143 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n";
2145 if (Op
.Class
->isRegisterClass())
2146 OpOS
<< " Operands[*(p + 1)]->setConstraint(\"r\");\n";
2148 OpOS
<< " Operands[*(p + 1)]->setConstraint(\"m\");\n";
2149 OpOS
<< " NumMCOperands += " << OpInfo
.MINumOperands
<< ";\n"
2153 case MatchableInfo::ResOperand::TiedOperand
: {
2154 // If this operand is tied to a previous one, just copy the MCInst
2155 // operand from the earlier one.We can only tie single MCOperand values.
2156 assert(OpInfo
.MINumOperands
== 1 && "Not a singular MCOperand");
2157 uint8_t TiedOp
= OpInfo
.TiedOperands
.ResOpnd
;
2159 OpInfo
.TiedOperands
.SrcOpnd1Idx
+ HasMnemonicFirst
;
2161 OpInfo
.TiedOperands
.SrcOpnd2Idx
+ HasMnemonicFirst
;
2162 assert((i
> TiedOp
|| TiedOp
== (uint8_t)-1) &&
2163 "Tied operand precedes its target!");
2164 auto TiedTupleName
= std::string("Tie") + utostr(TiedOp
) + '_' +
2165 utostr(SrcOp1
) + '_' + utostr(SrcOp2
);
2166 Signature
+= "__" + TiedTupleName
;
2167 ConversionRow
.push_back(CVT_Tied
);
2168 ConversionRow
.push_back(TiedOp
);
2169 ConversionRow
.push_back(SrcOp1
);
2170 ConversionRow
.push_back(SrcOp2
);
2172 // Also create an 'enum' for this combination of tied operands.
2173 auto Key
= std::make_tuple(TiedOp
, SrcOp1
, SrcOp2
);
2174 TiedOperandsEnumMap
.emplace(Key
, TiedTupleName
);
2177 case MatchableInfo::ResOperand::ImmOperand
: {
2178 int64_t Val
= OpInfo
.ImmVal
;
2179 std::string Ty
= "imm_" + itostr(Val
);
2180 Ty
= getEnumNameForToken(Ty
);
2181 Signature
+= "__" + Ty
;
2183 std::string Name
= "CVT_" + Ty
;
2184 bool IsNewConverter
= false;
2185 unsigned ID
= getConverterOperandID(Name
, OperandConversionKinds
,
2187 // Add the operand entry to the instruction kind conversion row.
2188 ConversionRow
.push_back(ID
);
2189 ConversionRow
.push_back(0);
2191 if (!IsNewConverter
)
2194 CvtOS
<< " case " << Name
<< ":\n"
2195 << " Inst.addOperand(MCOperand::createImm(" << Val
<< "));\n"
2198 OpOS
<< " case " << Name
<< ":\n"
2199 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2200 << " Operands[*(p + 1)]->setConstraint(\"\");\n"
2201 << " ++NumMCOperands;\n"
2205 case MatchableInfo::ResOperand::RegOperand
: {
2206 std::string Reg
, Name
;
2207 if (!OpInfo
.Register
) {
2211 Reg
= getQualifiedName(OpInfo
.Register
);
2212 Name
= "reg" + OpInfo
.Register
->getName().str();
2214 Signature
+= "__" + Name
;
2215 Name
= "CVT_" + Name
;
2216 bool IsNewConverter
= false;
2217 unsigned ID
= getConverterOperandID(Name
, OperandConversionKinds
,
2219 // Add the operand entry to the instruction kind conversion row.
2220 ConversionRow
.push_back(ID
);
2221 ConversionRow
.push_back(0);
2223 if (!IsNewConverter
)
2225 CvtOS
<< " case " << Name
<< ":\n"
2226 << " Inst.addOperand(MCOperand::createReg(" << Reg
<< "));\n"
2229 OpOS
<< " case " << Name
<< ":\n"
2230 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2231 << " Operands[*(p + 1)]->setConstraint(\"m\");\n"
2232 << " ++NumMCOperands;\n"
2238 // If there were no operands, add to the signature to that effect
2239 if (Signature
== "Convert")
2240 Signature
+= "_NoOperands";
2242 II
->ConversionFnKind
= Signature
;
2244 // Save the signature. If we already have it, don't add a new row
2246 if (!InstructionConversionKinds
.insert(CachedHashString(Signature
)))
2249 // Add the row to the table.
2250 ConversionTable
.push_back(std::move(ConversionRow
));
2253 // Finish up the converter driver function.
2254 CvtOS
<< " }\n }\n}\n\n";
2256 // Finish up the operand number lookup function.
2257 OpOS
<< " }\n }\n}\n\n";
2259 // Output a static table for tied operands.
2260 if (TiedOperandsEnumMap
.size()) {
2261 // The number of tied operand combinations will be small in practice,
2262 // but just add the assert to be sure.
2263 assert(TiedOperandsEnumMap
.size() <= 254 &&
2264 "Too many tied-operand combinations to reference with "
2265 "an 8bit offset from the conversion table, where index "
2266 "'255' is reserved as operand not to be copied.");
2269 for (auto &KV
: TiedOperandsEnumMap
) {
2270 OS
<< " " << KV
.second
<< ",\n";
2274 OS
<< "static const uint8_t TiedAsmOperandTable[][3] = {\n";
2275 for (auto &KV
: TiedOperandsEnumMap
) {
2276 OS
<< " /* " << KV
.second
<< " */ { "
2277 << utostr(std::get
<0>(KV
.first
)) << ", "
2278 << utostr(std::get
<1>(KV
.first
)) << ", "
2279 << utostr(std::get
<2>(KV
.first
)) << " },\n";
2283 OS
<< "static const uint8_t TiedAsmOperandTable[][3] = "
2284 "{ /* empty */ {0, 0, 0} };\n\n";
2286 OS
<< "namespace {\n";
2288 // Output the operand conversion kind enum.
2289 OS
<< "enum OperatorConversionKind {\n";
2290 for (const auto &Converter
: OperandConversionKinds
)
2291 OS
<< " " << Converter
<< ",\n";
2292 OS
<< " CVT_NUM_CONVERTERS\n";
2295 // Output the instruction conversion kind enum.
2296 OS
<< "enum InstructionConversionKind {\n";
2297 for (const auto &Signature
: InstructionConversionKinds
)
2298 OS
<< " " << Signature
<< ",\n";
2299 OS
<< " CVT_NUM_SIGNATURES\n";
2302 OS
<< "} // end anonymous namespace\n\n";
2304 // Output the conversion table.
2305 OS
<< "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES]["
2306 << MaxRowLength
<< "] = {\n";
2308 for (unsigned Row
= 0, ERow
= ConversionTable
.size(); Row
!= ERow
; ++Row
) {
2309 assert(ConversionTable
[Row
].size() % 2 == 0 && "bad conversion row!");
2310 OS
<< " // " << InstructionConversionKinds
[Row
] << "\n";
2312 for (unsigned i
= 0, e
= ConversionTable
[Row
].size(); i
!= e
; i
+= 2) {
2313 OS
<< OperandConversionKinds
[ConversionTable
[Row
][i
]] << ", ";
2314 if (OperandConversionKinds
[ConversionTable
[Row
][i
]] !=
2315 CachedHashString("CVT_Tied")) {
2316 OS
<< (unsigned)(ConversionTable
[Row
][i
+ 1]) << ", ";
2320 // For a tied operand, emit a reference to the TiedAsmOperandTable
2321 // that contains the operand to copy, and the parsed operands to
2322 // check for their tied constraints.
2323 auto Key
= std::make_tuple((uint8_t)ConversionTable
[Row
][i
+ 1],
2324 (uint8_t)ConversionTable
[Row
][i
+ 2],
2325 (uint8_t)ConversionTable
[Row
][i
+ 3]);
2326 auto TiedOpndEnum
= TiedOperandsEnumMap
.find(Key
);
2327 assert(TiedOpndEnum
!= TiedOperandsEnumMap
.end() &&
2328 "No record for tied operand pair");
2329 OS
<< TiedOpndEnum
->second
<< ", ";
2332 OS
<< "CVT_Done },\n";
2337 // Spit out the conversion driver function.
2340 // Spit out the operand number lookup function.
2343 return ConversionTable
.size();
2346 /// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
2347 static void emitMatchClassEnumeration(CodeGenTarget
&Target
,
2348 std::forward_list
<ClassInfo
> &Infos
,
2350 OS
<< "namespace {\n\n";
2352 OS
<< "/// MatchClassKind - The kinds of classes which participate in\n"
2353 << "/// instruction matching.\n";
2354 OS
<< "enum MatchClassKind {\n";
2355 OS
<< " InvalidMatchClass = 0,\n";
2356 OS
<< " OptionalMatchClass = 1,\n";
2357 ClassInfo::ClassInfoKind LastKind
= ClassInfo::Token
;
2358 StringRef LastName
= "OptionalMatchClass";
2359 for (const auto &CI
: Infos
) {
2360 if (LastKind
== ClassInfo::Token
&& CI
.Kind
!= ClassInfo::Token
) {
2361 OS
<< " MCK_LAST_TOKEN = " << LastName
<< ",\n";
2362 } else if (LastKind
< ClassInfo::UserClass0
&&
2363 CI
.Kind
>= ClassInfo::UserClass0
) {
2364 OS
<< " MCK_LAST_REGISTER = " << LastName
<< ",\n";
2366 LastKind
= (ClassInfo::ClassInfoKind
)CI
.Kind
;
2369 OS
<< " " << CI
.Name
<< ", // ";
2370 if (CI
.Kind
== ClassInfo::Token
) {
2371 OS
<< "'" << CI
.ValueName
<< "'\n";
2372 } else if (CI
.isRegisterClass()) {
2373 if (!CI
.ValueName
.empty())
2374 OS
<< "register class '" << CI
.ValueName
<< "'\n";
2376 OS
<< "derived register class\n";
2378 OS
<< "user defined class '" << CI
.ValueName
<< "'\n";
2381 OS
<< " NumMatchClassKinds\n";
2387 /// emitMatchClassDiagStrings - Emit a function to get the diagnostic text to be
2388 /// used when an assembly operand does not match the expected operand class.
2389 static void emitOperandMatchErrorDiagStrings(AsmMatcherInfo
&Info
, raw_ostream
&OS
) {
2390 // If the target does not use DiagnosticString for any operands, don't emit
2391 // an unused function.
2393 Info
.Classes
.begin(), Info
.Classes
.end(),
2394 [](const ClassInfo
&CI
) { return CI
.DiagnosticString
.empty(); }))
2397 OS
<< "static const char *getMatchKindDiag(" << Info
.Target
.getName()
2398 << "AsmParser::" << Info
.Target
.getName()
2399 << "MatchResultTy MatchResult) {\n";
2400 OS
<< " switch (MatchResult) {\n";
2402 for (const auto &CI
: Info
.Classes
) {
2403 if (!CI
.DiagnosticString
.empty()) {
2404 assert(!CI
.DiagnosticType
.empty() &&
2405 "DiagnosticString set without DiagnosticType");
2406 OS
<< " case " << Info
.Target
.getName()
2407 << "AsmParser::Match_" << CI
.DiagnosticType
<< ":\n";
2408 OS
<< " return \"" << CI
.DiagnosticString
<< "\";\n";
2412 OS
<< " default:\n";
2413 OS
<< " return nullptr;\n";
2419 static void emitRegisterMatchErrorFunc(AsmMatcherInfo
&Info
, raw_ostream
&OS
) {
2420 OS
<< "static unsigned getDiagKindFromRegisterClass(MatchClassKind "
2421 "RegisterClass) {\n";
2422 if (none_of(Info
.Classes
, [](const ClassInfo
&CI
) {
2423 return CI
.isRegisterClass() && !CI
.DiagnosticType
.empty();
2425 OS
<< " return MCTargetAsmParser::Match_InvalidOperand;\n";
2427 OS
<< " switch (RegisterClass) {\n";
2428 for (const auto &CI
: Info
.Classes
) {
2429 if (CI
.isRegisterClass() && !CI
.DiagnosticType
.empty()) {
2430 OS
<< " case " << CI
.Name
<< ":\n";
2431 OS
<< " return " << Info
.Target
.getName() << "AsmParser::Match_"
2432 << CI
.DiagnosticType
<< ";\n";
2436 OS
<< " default:\n";
2437 OS
<< " return MCTargetAsmParser::Match_InvalidOperand;\n";
2444 /// emitValidateOperandClass - Emit the function to validate an operand class.
2445 static void emitValidateOperandClass(AsmMatcherInfo
&Info
,
2447 OS
<< "static unsigned validateOperandClass(MCParsedAsmOperand &GOp, "
2448 << "MatchClassKind Kind) {\n";
2449 OS
<< " " << Info
.Target
.getName() << "Operand &Operand = ("
2450 << Info
.Target
.getName() << "Operand&)GOp;\n";
2452 // The InvalidMatchClass is not to match any operand.
2453 OS
<< " if (Kind == InvalidMatchClass)\n";
2454 OS
<< " return MCTargetAsmParser::Match_InvalidOperand;\n\n";
2456 // Check for Token operands first.
2457 // FIXME: Use a more specific diagnostic type.
2458 OS
<< " if (Operand.isToken() && Kind <= MCK_LAST_TOKEN)\n";
2459 OS
<< " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
2460 << " MCTargetAsmParser::Match_Success :\n"
2461 << " MCTargetAsmParser::Match_InvalidOperand;\n\n";
2463 // Check the user classes. We don't care what order since we're only
2464 // actually matching against one of them.
2465 OS
<< " switch (Kind) {\n"
2466 " default: break;\n";
2467 for (const auto &CI
: Info
.Classes
) {
2468 if (!CI
.isUserClass())
2471 OS
<< " // '" << CI
.ClassName
<< "' class\n";
2472 OS
<< " case " << CI
.Name
<< ": {\n";
2473 OS
<< " DiagnosticPredicate DP(Operand." << CI
.PredicateMethod
2475 OS
<< " if (DP.isMatch())\n";
2476 OS
<< " return MCTargetAsmParser::Match_Success;\n";
2477 if (!CI
.DiagnosticType
.empty()) {
2478 OS
<< " if (DP.isNearMatch())\n";
2479 OS
<< " return " << Info
.Target
.getName() << "AsmParser::Match_"
2480 << CI
.DiagnosticType
<< ";\n";
2487 OS
<< " } // end switch (Kind)\n\n";
2489 // Check for register operands, including sub-classes.
2490 OS
<< " if (Operand.isReg()) {\n";
2491 OS
<< " MatchClassKind OpKind;\n";
2492 OS
<< " switch (Operand.getReg()) {\n";
2493 OS
<< " default: OpKind = InvalidMatchClass; break;\n";
2494 for (const auto &RC
: Info
.RegisterClasses
)
2495 OS
<< " case " << RC
.first
->getValueAsString("Namespace") << "::"
2496 << RC
.first
->getName() << ": OpKind = " << RC
.second
->Name
2499 OS
<< " return isSubclass(OpKind, Kind) ? "
2500 << "(unsigned)MCTargetAsmParser::Match_Success :\n "
2501 << " getDiagKindFromRegisterClass(Kind);\n }\n\n";
2503 // Expected operand is a register, but actual is not.
2504 OS
<< " if (Kind > MCK_LAST_TOKEN && Kind <= MCK_LAST_REGISTER)\n";
2505 OS
<< " return getDiagKindFromRegisterClass(Kind);\n\n";
2507 // Generic fallthrough match failure case for operands that don't have
2508 // specialized diagnostic types.
2509 OS
<< " return MCTargetAsmParser::Match_InvalidOperand;\n";
2513 /// emitIsSubclass - Emit the subclass predicate function.
2514 static void emitIsSubclass(CodeGenTarget
&Target
,
2515 std::forward_list
<ClassInfo
> &Infos
,
2517 OS
<< "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n";
2518 OS
<< "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
2519 OS
<< " if (A == B)\n";
2520 OS
<< " return true;\n\n";
2522 bool EmittedSwitch
= false;
2523 for (const auto &A
: Infos
) {
2524 std::vector
<StringRef
> SuperClasses
;
2526 SuperClasses
.push_back("OptionalMatchClass");
2527 for (const auto &B
: Infos
) {
2528 if (&A
!= &B
&& A
.isSubsetOf(B
))
2529 SuperClasses
.push_back(B
.Name
);
2532 if (SuperClasses
.empty())
2535 // If this is the first SuperClass, emit the switch header.
2536 if (!EmittedSwitch
) {
2537 OS
<< " switch (A) {\n";
2538 OS
<< " default:\n";
2539 OS
<< " return false;\n";
2540 EmittedSwitch
= true;
2543 OS
<< "\n case " << A
.Name
<< ":\n";
2545 if (SuperClasses
.size() == 1) {
2546 OS
<< " return B == " << SuperClasses
.back() << ";\n";
2550 if (!SuperClasses
.empty()) {
2551 OS
<< " switch (B) {\n";
2552 OS
<< " default: return false;\n";
2553 for (StringRef SC
: SuperClasses
)
2554 OS
<< " case " << SC
<< ": return true;\n";
2557 // No case statement to emit
2558 OS
<< " return false;\n";
2562 // If there were case statements emitted into the string stream write the
2567 OS
<< " return false;\n";
2572 /// emitMatchTokenString - Emit the function to match a token string to the
2573 /// appropriate match class value.
2574 static void emitMatchTokenString(CodeGenTarget
&Target
,
2575 std::forward_list
<ClassInfo
> &Infos
,
2577 // Construct the match list.
2578 std::vector
<StringMatcher::StringPair
> Matches
;
2579 for (const auto &CI
: Infos
) {
2580 if (CI
.Kind
== ClassInfo::Token
)
2581 Matches
.emplace_back(CI
.ValueName
, "return " + CI
.Name
+ ";");
2584 OS
<< "static MatchClassKind matchTokenString(StringRef Name) {\n";
2586 StringMatcher("Name", Matches
, OS
).Emit();
2588 OS
<< " return InvalidMatchClass;\n";
2592 /// emitMatchRegisterName - Emit the function to match a string to the target
2593 /// specific register enum.
2594 static void emitMatchRegisterName(CodeGenTarget
&Target
, Record
*AsmParser
,
2596 // Construct the match list.
2597 std::vector
<StringMatcher::StringPair
> Matches
;
2598 const auto &Regs
= Target
.getRegBank().getRegisters();
2599 for (const CodeGenRegister
&Reg
: Regs
) {
2600 if (Reg
.TheDef
->getValueAsString("AsmName").empty())
2603 Matches
.emplace_back(Reg
.TheDef
->getValueAsString("AsmName"),
2604 "return " + utostr(Reg
.EnumValue
) + ";");
2607 OS
<< "static unsigned MatchRegisterName(StringRef Name) {\n";
2609 bool IgnoreDuplicates
=
2610 AsmParser
->getValueAsBit("AllowDuplicateRegisterNames");
2611 StringMatcher("Name", Matches
, OS
).Emit(0, IgnoreDuplicates
);
2613 OS
<< " return 0;\n";
2617 /// Emit the function to match a string to the target
2618 /// specific register enum.
2619 static void emitMatchRegisterAltName(CodeGenTarget
&Target
, Record
*AsmParser
,
2621 // Construct the match list.
2622 std::vector
<StringMatcher::StringPair
> Matches
;
2623 const auto &Regs
= Target
.getRegBank().getRegisters();
2624 for (const CodeGenRegister
&Reg
: Regs
) {
2626 auto AltNames
= Reg
.TheDef
->getValueAsListOfStrings("AltNames");
2628 for (auto AltName
: AltNames
) {
2629 AltName
= StringRef(AltName
).trim();
2631 // don't handle empty alternative names
2632 if (AltName
.empty())
2635 Matches
.emplace_back(AltName
,
2636 "return " + utostr(Reg
.EnumValue
) + ";");
2640 OS
<< "static unsigned MatchRegisterAltName(StringRef Name) {\n";
2642 bool IgnoreDuplicates
=
2643 AsmParser
->getValueAsBit("AllowDuplicateRegisterNames");
2644 StringMatcher("Name", Matches
, OS
).Emit(0, IgnoreDuplicates
);
2646 OS
<< " return 0;\n";
2650 /// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
2651 static void emitOperandDiagnosticTypes(AsmMatcherInfo
&Info
, raw_ostream
&OS
) {
2652 // Get the set of diagnostic types from all of the operand classes.
2653 std::set
<StringRef
> Types
;
2654 for (const auto &OpClassEntry
: Info
.AsmOperandClasses
) {
2655 if (!OpClassEntry
.second
->DiagnosticType
.empty())
2656 Types
.insert(OpClassEntry
.second
->DiagnosticType
);
2658 for (const auto &OpClassEntry
: Info
.RegisterClassClasses
) {
2659 if (!OpClassEntry
.second
->DiagnosticType
.empty())
2660 Types
.insert(OpClassEntry
.second
->DiagnosticType
);
2663 if (Types
.empty()) return;
2665 // Now emit the enum entries.
2666 for (StringRef Type
: Types
)
2667 OS
<< " Match_" << Type
<< ",\n";
2668 OS
<< " END_OPERAND_DIAGNOSTIC_TYPES\n";
2671 /// emitGetSubtargetFeatureName - Emit the helper function to get the
2672 /// user-level name for a subtarget feature.
2673 static void emitGetSubtargetFeatureName(AsmMatcherInfo
&Info
, raw_ostream
&OS
) {
2674 OS
<< "// User-level names for subtarget features that participate in\n"
2675 << "// instruction matching.\n"
2676 << "static const char *getSubtargetFeatureName(uint64_t Val) {\n";
2677 if (!Info
.SubtargetFeatures
.empty()) {
2678 OS
<< " switch(Val) {\n";
2679 for (const auto &SF
: Info
.SubtargetFeatures
) {
2680 const SubtargetFeatureInfo
&SFI
= SF
.second
;
2681 // FIXME: Totally just a placeholder name to get the algorithm working.
2682 OS
<< " case " << SFI
.getEnumBitName() << ": return \""
2683 << SFI
.TheDef
->getValueAsString("PredicateName") << "\";\n";
2685 OS
<< " default: return \"(unknown)\";\n";
2688 // Nothing to emit, so skip the switch
2689 OS
<< " return \"(unknown)\";\n";
2694 static std::string
GetAliasRequiredFeatures(Record
*R
,
2695 const AsmMatcherInfo
&Info
) {
2696 std::vector
<Record
*> ReqFeatures
= R
->getValueAsListOfDefs("Predicates");
2699 if (ReqFeatures
.empty())
2702 for (unsigned i
= 0, e
= ReqFeatures
.size(); i
!= e
; ++i
) {
2703 const SubtargetFeatureInfo
*F
= Info
.getSubtargetFeature(ReqFeatures
[i
]);
2706 PrintFatalError(R
->getLoc(), "Predicate '" + ReqFeatures
[i
]->getName() +
2707 "' is not marked as an AssemblerPredicate!");
2712 Result
+= "Features.test(" + F
->getEnumBitName() + ')';
2718 static void emitMnemonicAliasVariant(raw_ostream
&OS
,const AsmMatcherInfo
&Info
,
2719 std::vector
<Record
*> &Aliases
,
2720 unsigned Indent
= 0,
2721 StringRef AsmParserVariantName
= StringRef()){
2722 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
2723 // iteration order of the map is stable.
2724 std::map
<std::string
, std::vector
<Record
*> > AliasesFromMnemonic
;
2726 for (Record
*R
: Aliases
) {
2727 // FIXME: Allow AssemblerVariantName to be a comma separated list.
2728 StringRef AsmVariantName
= R
->getValueAsString("AsmVariantName");
2729 if (AsmVariantName
!= AsmParserVariantName
)
2731 AliasesFromMnemonic
[R
->getValueAsString("FromMnemonic")].push_back(R
);
2733 if (AliasesFromMnemonic
.empty())
2736 // Process each alias a "from" mnemonic at a time, building the code executed
2737 // by the string remapper.
2738 std::vector
<StringMatcher::StringPair
> Cases
;
2739 for (const auto &AliasEntry
: AliasesFromMnemonic
) {
2740 const std::vector
<Record
*> &ToVec
= AliasEntry
.second
;
2742 // Loop through each alias and emit code that handles each case. If there
2743 // are two instructions without predicates, emit an error. If there is one,
2745 std::string MatchCode
;
2746 int AliasWithNoPredicate
= -1;
2748 for (unsigned i
= 0, e
= ToVec
.size(); i
!= e
; ++i
) {
2749 Record
*R
= ToVec
[i
];
2750 std::string FeatureMask
= GetAliasRequiredFeatures(R
, Info
);
2752 // If this unconditionally matches, remember it for later and diagnose
2754 if (FeatureMask
.empty()) {
2755 if (AliasWithNoPredicate
!= -1) {
2756 // We can't have two aliases from the same mnemonic with no predicate.
2757 PrintError(ToVec
[AliasWithNoPredicate
]->getLoc(),
2758 "two MnemonicAliases with the same 'from' mnemonic!");
2759 PrintFatalError(R
->getLoc(), "this is the other MnemonicAlias.");
2762 AliasWithNoPredicate
= i
;
2765 if (R
->getValueAsString("ToMnemonic") == AliasEntry
.first
)
2766 PrintFatalError(R
->getLoc(), "MnemonicAlias to the same string");
2768 if (!MatchCode
.empty())
2769 MatchCode
+= "else ";
2770 MatchCode
+= "if (" + FeatureMask
+ ")\n";
2771 MatchCode
+= " Mnemonic = \"";
2772 MatchCode
+= R
->getValueAsString("ToMnemonic");
2773 MatchCode
+= "\";\n";
2776 if (AliasWithNoPredicate
!= -1) {
2777 Record
*R
= ToVec
[AliasWithNoPredicate
];
2778 if (!MatchCode
.empty())
2779 MatchCode
+= "else\n ";
2780 MatchCode
+= "Mnemonic = \"";
2781 MatchCode
+= R
->getValueAsString("ToMnemonic");
2782 MatchCode
+= "\";\n";
2785 MatchCode
+= "return;";
2787 Cases
.push_back(std::make_pair(AliasEntry
.first
, MatchCode
));
2789 StringMatcher("Mnemonic", Cases
, OS
).Emit(Indent
);
2792 /// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
2793 /// emit a function for them and return true, otherwise return false.
2794 static bool emitMnemonicAliases(raw_ostream
&OS
, const AsmMatcherInfo
&Info
,
2795 CodeGenTarget
&Target
) {
2796 // Ignore aliases when match-prefix is set.
2797 if (!MatchPrefix
.empty())
2800 std::vector
<Record
*> Aliases
=
2801 Info
.getRecords().getAllDerivedDefinitions("MnemonicAlias");
2802 if (Aliases
.empty()) return false;
2804 OS
<< "static void applyMnemonicAliases(StringRef &Mnemonic, "
2805 "const FeatureBitset &Features, unsigned VariantID) {\n";
2806 OS
<< " switch (VariantID) {\n";
2807 unsigned VariantCount
= Target
.getAsmParserVariantCount();
2808 for (unsigned VC
= 0; VC
!= VariantCount
; ++VC
) {
2809 Record
*AsmVariant
= Target
.getAsmParserVariant(VC
);
2810 int AsmParserVariantNo
= AsmVariant
->getValueAsInt("Variant");
2811 StringRef AsmParserVariantName
= AsmVariant
->getValueAsString("Name");
2812 OS
<< " case " << AsmParserVariantNo
<< ":\n";
2813 emitMnemonicAliasVariant(OS
, Info
, Aliases
, /*Indent=*/2,
2814 AsmParserVariantName
);
2819 // Emit aliases that apply to all variants.
2820 emitMnemonicAliasVariant(OS
, Info
, Aliases
);
2827 static void emitCustomOperandParsing(raw_ostream
&OS
, CodeGenTarget
&Target
,
2828 const AsmMatcherInfo
&Info
, StringRef ClassName
,
2829 StringToOffsetTable
&StringTable
,
2830 unsigned MaxMnemonicIndex
,
2831 unsigned MaxFeaturesIndex
,
2832 bool HasMnemonicFirst
) {
2833 unsigned MaxMask
= 0;
2834 for (const OperandMatchEntry
&OMI
: Info
.OperandMatchInfo
) {
2835 MaxMask
|= OMI
.OperandMask
;
2838 // Emit the static custom operand parsing table;
2839 OS
<< "namespace {\n";
2840 OS
<< " struct OperandMatchEntry {\n";
2841 OS
<< " " << getMinimalTypeForRange(MaxMnemonicIndex
)
2843 OS
<< " " << getMinimalTypeForRange(MaxMask
)
2844 << " OperandMask;\n";
2845 OS
<< " " << getMinimalTypeForRange(std::distance(
2846 Info
.Classes
.begin(), Info
.Classes
.end())) << " Class;\n";
2847 OS
<< " " << getMinimalTypeForRange(MaxFeaturesIndex
)
2848 << " RequiredFeaturesIdx;\n\n";
2849 OS
<< " StringRef getMnemonic() const {\n";
2850 OS
<< " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2851 OS
<< " MnemonicTable[Mnemonic]);\n";
2855 OS
<< " // Predicate for searching for an opcode.\n";
2856 OS
<< " struct LessOpcodeOperand {\n";
2857 OS
<< " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
2858 OS
<< " return LHS.getMnemonic() < RHS;\n";
2860 OS
<< " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
2861 OS
<< " return LHS < RHS.getMnemonic();\n";
2863 OS
<< " bool operator()(const OperandMatchEntry &LHS,";
2864 OS
<< " const OperandMatchEntry &RHS) {\n";
2865 OS
<< " return LHS.getMnemonic() < RHS.getMnemonic();\n";
2869 OS
<< "} // end anonymous namespace.\n\n";
2871 OS
<< "static const OperandMatchEntry OperandMatchTable["
2872 << Info
.OperandMatchInfo
.size() << "] = {\n";
2874 OS
<< " /* Operand List Mnemonic, Mask, Operand Class, Features */\n";
2875 for (const OperandMatchEntry
&OMI
: Info
.OperandMatchInfo
) {
2876 const MatchableInfo
&II
= *OMI
.MI
;
2880 // Store a pascal-style length byte in the mnemonic.
2881 std::string LenMnemonic
= char(II
.Mnemonic
.size()) + II
.Mnemonic
.str();
2882 OS
<< StringTable
.GetOrAddStringOffset(LenMnemonic
, false)
2883 << " /* " << II
.Mnemonic
<< " */, ";
2885 OS
<< OMI
.OperandMask
;
2887 bool printComma
= false;
2888 for (int i
= 0, e
= 31; i
!=e
; ++i
)
2889 if (OMI
.OperandMask
& (1 << i
)) {
2899 // Write the required features mask.
2901 if (II
.RequiredFeatures
.empty())
2904 for (unsigned i
= 0, e
= II
.RequiredFeatures
.size(); i
!= e
; ++i
)
2905 OS
<< '_' << II
.RequiredFeatures
[i
]->TheDef
->getName();
2911 // Emit the operand class switch to call the correct custom parser for
2912 // the found operand class.
2913 OS
<< "OperandMatchResultTy " << Target
.getName() << ClassName
<< "::\n"
2914 << "tryCustomParseOperand(OperandVector"
2915 << " &Operands,\n unsigned MCK) {\n\n"
2916 << " switch(MCK) {\n";
2918 for (const auto &CI
: Info
.Classes
) {
2919 if (CI
.ParserMethod
.empty())
2921 OS
<< " case " << CI
.Name
<< ":\n"
2922 << " return " << CI
.ParserMethod
<< "(Operands);\n";
2925 OS
<< " default:\n";
2926 OS
<< " return MatchOperand_NoMatch;\n";
2928 OS
<< " return MatchOperand_NoMatch;\n";
2931 // Emit the static custom operand parser. This code is very similar with
2932 // the other matcher. Also use MatchResultTy here just in case we go for
2933 // a better error handling.
2934 OS
<< "OperandMatchResultTy " << Target
.getName() << ClassName
<< "::\n"
2935 << "MatchOperandParserImpl(OperandVector"
2936 << " &Operands,\n StringRef Mnemonic,\n"
2937 << " bool ParseForAllFeatures) {\n";
2939 // Emit code to get the available features.
2940 OS
<< " // Get the current feature set.\n";
2941 OS
<< " const FeatureBitset &AvailableFeatures = getAvailableFeatures();\n\n";
2943 OS
<< " // Get the next operand index.\n";
2944 OS
<< " unsigned NextOpNum = Operands.size()"
2945 << (HasMnemonicFirst
? " - 1" : "") << ";\n";
2947 // Emit code to search the table.
2948 OS
<< " // Search the table.\n";
2949 if (HasMnemonicFirst
) {
2950 OS
<< " auto MnemonicRange =\n";
2951 OS
<< " std::equal_range(std::begin(OperandMatchTable), "
2952 "std::end(OperandMatchTable),\n";
2953 OS
<< " Mnemonic, LessOpcodeOperand());\n\n";
2955 OS
<< " auto MnemonicRange = std::make_pair(std::begin(OperandMatchTable),"
2956 " std::end(OperandMatchTable));\n";
2957 OS
<< " if (!Mnemonic.empty())\n";
2958 OS
<< " MnemonicRange =\n";
2959 OS
<< " std::equal_range(std::begin(OperandMatchTable), "
2960 "std::end(OperandMatchTable),\n";
2961 OS
<< " Mnemonic, LessOpcodeOperand());\n\n";
2964 OS
<< " if (MnemonicRange.first == MnemonicRange.second)\n";
2965 OS
<< " return MatchOperand_NoMatch;\n\n";
2967 OS
<< " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2968 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2970 OS
<< " // equal_range guarantees that instruction mnemonic matches.\n";
2971 OS
<< " assert(Mnemonic == it->getMnemonic());\n\n";
2973 // Emit check that the required features are available.
2974 OS
<< " // check if the available features match\n";
2975 OS
<< " const FeatureBitset &RequiredFeatures = "
2976 "FeatureBitsets[it->RequiredFeaturesIdx];\n";
2977 OS
<< " if (!ParseForAllFeatures && (AvailableFeatures & "
2978 "RequiredFeatures) != RequiredFeatures)\n";
2979 OS
<< " continue;\n\n";
2981 // Emit check to ensure the operand number matches.
2982 OS
<< " // check if the operand in question has a custom parser.\n";
2983 OS
<< " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2984 OS
<< " continue;\n\n";
2986 // Emit call to the custom parser method
2987 OS
<< " // call custom parse method to handle the operand\n";
2988 OS
<< " OperandMatchResultTy Result = ";
2989 OS
<< "tryCustomParseOperand(Operands, it->Class);\n";
2990 OS
<< " if (Result != MatchOperand_NoMatch)\n";
2991 OS
<< " return Result;\n";
2994 OS
<< " // Okay, we had no match.\n";
2995 OS
<< " return MatchOperand_NoMatch;\n";
2999 static void emitAsmTiedOperandConstraints(CodeGenTarget
&Target
,
3000 AsmMatcherInfo
&Info
,
3002 std::string AsmParserName
=
3003 Info
.AsmParser
->getValueAsString("AsmParserClassName");
3004 OS
<< "static bool ";
3005 OS
<< "checkAsmTiedOperandConstraints(const " << Target
.getName()
3006 << AsmParserName
<< "&AsmParser,\n";
3007 OS
<< " unsigned Kind,\n";
3008 OS
<< " const OperandVector &Operands,\n";
3009 OS
<< " uint64_t &ErrorInfo) {\n";
3010 OS
<< " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
3011 OS
<< " const uint8_t *Converter = ConversionTable[Kind];\n";
3012 OS
<< " for (const uint8_t *p = Converter; *p; p+= 2) {\n";
3013 OS
<< " switch (*p) {\n";
3014 OS
<< " case CVT_Tied: {\n";
3015 OS
<< " unsigned OpIdx = *(p+1);\n";
3016 OS
<< " assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
3017 OS
<< " std::begin(TiedAsmOperandTable)) &&\n";
3018 OS
<< " \"Tied operand not found\");\n";
3019 OS
<< " unsigned OpndNum1 = TiedAsmOperandTable[OpIdx][1];\n";
3020 OS
<< " unsigned OpndNum2 = TiedAsmOperandTable[OpIdx][2];\n";
3021 OS
<< " if (OpndNum1 != OpndNum2) {\n";
3022 OS
<< " auto &SrcOp1 = Operands[OpndNum1];\n";
3023 OS
<< " auto &SrcOp2 = Operands[OpndNum2];\n";
3024 OS
<< " if (SrcOp1->isReg() && SrcOp2->isReg()) {\n";
3025 OS
<< " if (!AsmParser.regsEqual(*SrcOp1, *SrcOp2)) {\n";
3026 OS
<< " ErrorInfo = OpndNum2;\n";
3027 OS
<< " return false;\n";
3033 OS
<< " default:\n";
3037 OS
<< " return true;\n";
3041 static void emitMnemonicSpellChecker(raw_ostream
&OS
, CodeGenTarget
&Target
,
3042 unsigned VariantCount
) {
3043 OS
<< "static std::string " << Target
.getName()
3044 << "MnemonicSpellCheck(StringRef S, const FeatureBitset &FBS,"
3045 << " unsigned VariantID) {\n";
3047 OS
<< " return \"\";";
3049 OS
<< " const unsigned MaxEditDist = 2;\n";
3050 OS
<< " std::vector<StringRef> Candidates;\n";
3051 OS
<< " StringRef Prev = \"\";\n\n";
3053 OS
<< " // Find the appropriate table for this asm variant.\n";
3054 OS
<< " const MatchEntry *Start, *End;\n";
3055 OS
<< " switch (VariantID) {\n";
3056 OS
<< " default: llvm_unreachable(\"invalid variant!\");\n";
3057 for (unsigned VC
= 0; VC
!= VariantCount
; ++VC
) {
3058 Record
*AsmVariant
= Target
.getAsmParserVariant(VC
);
3059 int AsmVariantNo
= AsmVariant
->getValueAsInt("Variant");
3060 OS
<< " case " << AsmVariantNo
<< ": Start = std::begin(MatchTable" << VC
3061 << "); End = std::end(MatchTable" << VC
<< "); break;\n";
3064 OS
<< " for (auto I = Start; I < End; I++) {\n";
3065 OS
<< " // Ignore unsupported instructions.\n";
3066 OS
<< " const FeatureBitset &RequiredFeatures = "
3067 "FeatureBitsets[I->RequiredFeaturesIdx];\n";
3068 OS
<< " if ((FBS & RequiredFeatures) != RequiredFeatures)\n";
3069 OS
<< " continue;\n";
3071 OS
<< " StringRef T = I->getMnemonic();\n";
3072 OS
<< " // Avoid recomputing the edit distance for the same string.\n";
3073 OS
<< " if (T.equals(Prev))\n";
3074 OS
<< " continue;\n";
3076 OS
<< " Prev = T;\n";
3077 OS
<< " unsigned Dist = S.edit_distance(T, false, MaxEditDist);\n";
3078 OS
<< " if (Dist <= MaxEditDist)\n";
3079 OS
<< " Candidates.push_back(T);\n";
3082 OS
<< " if (Candidates.empty())\n";
3083 OS
<< " return \"\";\n";
3085 OS
<< " std::string Res = \", did you mean: \";\n";
3086 OS
<< " unsigned i = 0;\n";
3087 OS
<< " for( ; i < Candidates.size() - 1; i++)\n";
3088 OS
<< " Res += Candidates[i].str() + \", \";\n";
3089 OS
<< " return Res + Candidates[i].str() + \"?\";\n";
3096 // Emit a function mapping match classes to strings, for debugging.
3097 static void emitMatchClassKindNames(std::forward_list
<ClassInfo
> &Infos
,
3099 OS
<< "#ifndef NDEBUG\n";
3100 OS
<< "const char *getMatchClassName(MatchClassKind Kind) {\n";
3101 OS
<< " switch (Kind) {\n";
3103 OS
<< " case InvalidMatchClass: return \"InvalidMatchClass\";\n";
3104 OS
<< " case OptionalMatchClass: return \"OptionalMatchClass\";\n";
3105 for (const auto &CI
: Infos
) {
3106 OS
<< " case " << CI
.Name
<< ": return \"" << CI
.Name
<< "\";\n";
3108 OS
<< " case NumMatchClassKinds: return \"NumMatchClassKinds\";\n";
3111 OS
<< " llvm_unreachable(\"unhandled MatchClassKind!\");\n";
3113 OS
<< "#endif // NDEBUG\n";
3117 getNameForFeatureBitset(const std::vector
<Record
*> &FeatureBitset
) {
3118 std::string Name
= "AMFBS";
3119 for (const auto &Feature
: FeatureBitset
)
3120 Name
+= ("_" + Feature
->getName()).str();
3124 void AsmMatcherEmitter::run(raw_ostream
&OS
) {
3125 CodeGenTarget
Target(Records
);
3126 Record
*AsmParser
= Target
.getAsmParser();
3127 StringRef ClassName
= AsmParser
->getValueAsString("AsmParserClassName");
3129 // Compute the information on the instructions to match.
3130 AsmMatcherInfo
Info(AsmParser
, Target
, Records
);
3133 // Sort the instruction table using the partial order on classes. We use
3134 // stable_sort to ensure that ambiguous instructions are still
3135 // deterministically ordered.
3138 [](const std::unique_ptr
<MatchableInfo
> &a
,
3139 const std::unique_ptr
<MatchableInfo
> &b
) { return *a
< *b
; });
3141 #ifdef EXPENSIVE_CHECKS
3142 // Verify that the table is sorted and operator < works transitively.
3143 for (auto I
= Info
.Matchables
.begin(), E
= Info
.Matchables
.end(); I
!= E
;
3145 for (auto J
= I
; J
!= E
; ++J
) {
3146 assert(!(**J
< **I
));
3151 DEBUG_WITH_TYPE("instruction_info", {
3152 for (const auto &MI
: Info
.Matchables
)
3156 // Check for ambiguous matchables.
3157 DEBUG_WITH_TYPE("ambiguous_instrs", {
3158 unsigned NumAmbiguous
= 0;
3159 for (auto I
= Info
.Matchables
.begin(), E
= Info
.Matchables
.end(); I
!= E
;
3161 for (auto J
= std::next(I
); J
!= E
; ++J
) {
3162 const MatchableInfo
&A
= **I
;
3163 const MatchableInfo
&B
= **J
;
3165 if (A
.couldMatchAmbiguouslyWith(B
)) {
3166 errs() << "warning: ambiguous matchables:\n";
3168 errs() << "\nis incomparable with:\n";
3176 errs() << "warning: " << NumAmbiguous
3177 << " ambiguous matchables!\n";
3180 // Compute the information on the custom operand parsing.
3181 Info
.buildOperandMatchInfo();
3183 bool HasMnemonicFirst
= AsmParser
->getValueAsBit("HasMnemonicFirst");
3184 bool HasOptionalOperands
= Info
.hasOptionalOperands();
3185 bool ReportMultipleNearMisses
=
3186 AsmParser
->getValueAsBit("ReportMultipleNearMisses");
3188 // Write the output.
3190 // Information for the class declaration.
3191 OS
<< "\n#ifdef GET_ASSEMBLER_HEADER\n";
3192 OS
<< "#undef GET_ASSEMBLER_HEADER\n";
3193 OS
<< " // This should be included into the middle of the declaration of\n";
3194 OS
<< " // your subclasses implementation of MCTargetAsmParser.\n";
3195 OS
<< " FeatureBitset ComputeAvailableFeatures(const FeatureBitset& FB) const;\n";
3196 if (HasOptionalOperands
) {
3197 OS
<< " void convertToMCInst(unsigned Kind, MCInst &Inst, "
3198 << "unsigned Opcode,\n"
3199 << " const OperandVector &Operands,\n"
3200 << " const SmallBitVector &OptionalOperandsMask);\n";
3202 OS
<< " void convertToMCInst(unsigned Kind, MCInst &Inst, "
3203 << "unsigned Opcode,\n"
3204 << " const OperandVector &Operands);\n";
3206 OS
<< " void convertToMapAndConstraints(unsigned Kind,\n ";
3207 OS
<< " const OperandVector &Operands) override;\n";
3208 OS
<< " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
3209 << " MCInst &Inst,\n";
3210 if (ReportMultipleNearMisses
)
3211 OS
<< " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
3213 OS
<< " uint64_t &ErrorInfo,\n"
3214 << " FeatureBitset &MissingFeatures,\n";
3215 OS
<< " bool matchingInlineAsm,\n"
3216 << " unsigned VariantID = 0);\n";
3217 if (!ReportMultipleNearMisses
)
3218 OS
<< " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
3219 << " MCInst &Inst,\n"
3220 << " uint64_t &ErrorInfo,\n"
3221 << " bool matchingInlineAsm,\n"
3222 << " unsigned VariantID = 0) {\n"
3223 << " FeatureBitset MissingFeatures;\n"
3224 << " return MatchInstructionImpl(Operands, Inst, ErrorInfo, MissingFeatures,\n"
3225 << " matchingInlineAsm, VariantID);\n"
3229 if (!Info
.OperandMatchInfo
.empty()) {
3230 OS
<< " OperandMatchResultTy MatchOperandParserImpl(\n";
3231 OS
<< " OperandVector &Operands,\n";
3232 OS
<< " StringRef Mnemonic,\n";
3233 OS
<< " bool ParseForAllFeatures = false);\n";
3235 OS
<< " OperandMatchResultTy tryCustomParseOperand(\n";
3236 OS
<< " OperandVector &Operands,\n";
3237 OS
<< " unsigned MCK);\n\n";
3240 OS
<< "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
3242 // Emit the operand match diagnostic enum names.
3243 OS
<< "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
3244 OS
<< "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3245 emitOperandDiagnosticTypes(Info
, OS
);
3246 OS
<< "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3248 OS
<< "\n#ifdef GET_REGISTER_MATCHER\n";
3249 OS
<< "#undef GET_REGISTER_MATCHER\n\n";
3251 // Emit the subtarget feature enumeration.
3252 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(
3253 Info
.SubtargetFeatures
, OS
);
3255 // Emit the function to match a register name to number.
3256 // This should be omitted for Mips target
3257 if (AsmParser
->getValueAsBit("ShouldEmitMatchRegisterName"))
3258 emitMatchRegisterName(Target
, AsmParser
, OS
);
3260 if (AsmParser
->getValueAsBit("ShouldEmitMatchRegisterAltName"))
3261 emitMatchRegisterAltName(Target
, AsmParser
, OS
);
3263 OS
<< "#endif // GET_REGISTER_MATCHER\n\n";
3265 OS
<< "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
3266 OS
<< "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
3268 // Generate the helper function to get the names for subtarget features.
3269 emitGetSubtargetFeatureName(Info
, OS
);
3271 OS
<< "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
3273 OS
<< "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
3274 OS
<< "#undef GET_MATCHER_IMPLEMENTATION\n\n";
3276 // Generate the function that remaps for mnemonic aliases.
3277 bool HasMnemonicAliases
= emitMnemonicAliases(OS
, Info
, Target
);
3279 // Generate the convertToMCInst function to convert operands into an MCInst.
3280 // Also, generate the convertToMapAndConstraints function for MS-style inline
3281 // assembly. The latter doesn't actually generate a MCInst.
3282 unsigned NumConverters
= emitConvertFuncs(Target
, ClassName
, Info
.Matchables
,
3284 HasOptionalOperands
, OS
);
3286 // Emit the enumeration for classes which participate in matching.
3287 emitMatchClassEnumeration(Target
, Info
.Classes
, OS
);
3289 // Emit a function to get the user-visible string to describe an operand
3290 // match failure in diagnostics.
3291 emitOperandMatchErrorDiagStrings(Info
, OS
);
3293 // Emit a function to map register classes to operand match failure codes.
3294 emitRegisterMatchErrorFunc(Info
, OS
);
3296 // Emit the routine to match token strings to their match class.
3297 emitMatchTokenString(Target
, Info
.Classes
, OS
);
3299 // Emit the subclass predicate routine.
3300 emitIsSubclass(Target
, Info
.Classes
, OS
);
3302 // Emit the routine to validate an operand against a match class.
3303 emitValidateOperandClass(Info
, OS
);
3305 emitMatchClassKindNames(Info
.Classes
, OS
);
3307 // Emit the available features compute function.
3308 SubtargetFeatureInfo::emitComputeAssemblerAvailableFeatures(
3309 Info
.Target
.getName(), ClassName
, "ComputeAvailableFeatures",
3310 Info
.SubtargetFeatures
, OS
);
3312 if (!ReportMultipleNearMisses
)
3313 emitAsmTiedOperandConstraints(Target
, Info
, OS
);
3315 StringToOffsetTable StringTable
;
3317 size_t MaxNumOperands
= 0;
3318 unsigned MaxMnemonicIndex
= 0;
3319 bool HasDeprecation
= false;
3320 for (const auto &MI
: Info
.Matchables
) {
3321 MaxNumOperands
= std::max(MaxNumOperands
, MI
->AsmOperands
.size());
3322 HasDeprecation
|= MI
->HasDeprecation
;
3324 // Store a pascal-style length byte in the mnemonic.
3325 std::string LenMnemonic
= char(MI
->Mnemonic
.size()) + MI
->Mnemonic
.str();
3326 MaxMnemonicIndex
= std::max(MaxMnemonicIndex
,
3327 StringTable
.GetOrAddStringOffset(LenMnemonic
, false));
3330 OS
<< "static const char *const MnemonicTable =\n";
3331 StringTable
.EmitString(OS
);
3334 std::vector
<std::vector
<Record
*>> FeatureBitsets
;
3335 for (const auto &MI
: Info
.Matchables
) {
3336 if (MI
->RequiredFeatures
.empty())
3338 FeatureBitsets
.emplace_back();
3339 for (unsigned I
= 0, E
= MI
->RequiredFeatures
.size(); I
!= E
; ++I
)
3340 FeatureBitsets
.back().push_back(MI
->RequiredFeatures
[I
]->TheDef
);
3343 llvm::sort(FeatureBitsets
, [&](const std::vector
<Record
*> &A
,
3344 const std::vector
<Record
*> &B
) {
3345 if (A
.size() < B
.size())
3347 if (A
.size() > B
.size())
3349 for (const auto &Pair
: zip(A
, B
)) {
3350 if (std::get
<0>(Pair
)->getName() < std::get
<1>(Pair
)->getName())
3352 if (std::get
<0>(Pair
)->getName() > std::get
<1>(Pair
)->getName())
3357 FeatureBitsets
.erase(
3358 std::unique(FeatureBitsets
.begin(), FeatureBitsets
.end()),
3359 FeatureBitsets
.end());
3360 OS
<< "// Feature bitsets.\n"
3361 << "enum : " << getMinimalTypeForRange(FeatureBitsets
.size()) << " {\n"
3362 << " AMFBS_None,\n";
3363 for (const auto &FeatureBitset
: FeatureBitsets
) {
3364 if (FeatureBitset
.empty())
3366 OS
<< " " << getNameForFeatureBitset(FeatureBitset
) << ",\n";
3369 << "const static FeatureBitset FeatureBitsets[] {\n"
3370 << " {}, // AMFBS_None\n";
3371 for (const auto &FeatureBitset
: FeatureBitsets
) {
3372 if (FeatureBitset
.empty())
3375 for (const auto &Feature
: FeatureBitset
) {
3376 const auto &I
= Info
.SubtargetFeatures
.find(Feature
);
3377 assert(I
!= Info
.SubtargetFeatures
.end() && "Didn't import predicate?");
3378 OS
<< I
->second
.getEnumBitName() << ", ";
3384 // Emit the static match table; unused classes get initialized to 0 which is
3385 // guaranteed to be InvalidMatchClass.
3387 // FIXME: We can reduce the size of this table very easily. First, we change
3388 // it so that store the kinds in separate bit-fields for each index, which
3389 // only needs to be the max width used for classes at that index (we also need
3390 // to reject based on this during classification). If we then make sure to
3391 // order the match kinds appropriately (putting mnemonics last), then we
3392 // should only end up using a few bits for each class, especially the ones
3393 // following the mnemonic.
3394 OS
<< "namespace {\n";
3395 OS
<< " struct MatchEntry {\n";
3396 OS
<< " " << getMinimalTypeForRange(MaxMnemonicIndex
)
3398 OS
<< " uint16_t Opcode;\n";
3399 OS
<< " " << getMinimalTypeForRange(NumConverters
)
3401 OS
<< " " << getMinimalTypeForRange(FeatureBitsets
.size())
3402 << " RequiredFeaturesIdx;\n";
3403 OS
<< " " << getMinimalTypeForRange(
3404 std::distance(Info
.Classes
.begin(), Info
.Classes
.end()))
3405 << " Classes[" << MaxNumOperands
<< "];\n";
3406 OS
<< " StringRef getMnemonic() const {\n";
3407 OS
<< " return StringRef(MnemonicTable + Mnemonic + 1,\n";
3408 OS
<< " MnemonicTable[Mnemonic]);\n";
3412 OS
<< " // Predicate for searching for an opcode.\n";
3413 OS
<< " struct LessOpcode {\n";
3414 OS
<< " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
3415 OS
<< " return LHS.getMnemonic() < RHS;\n";
3417 OS
<< " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
3418 OS
<< " return LHS < RHS.getMnemonic();\n";
3420 OS
<< " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
3421 OS
<< " return LHS.getMnemonic() < RHS.getMnemonic();\n";
3425 OS
<< "} // end anonymous namespace.\n\n";
3427 unsigned VariantCount
= Target
.getAsmParserVariantCount();
3428 for (unsigned VC
= 0; VC
!= VariantCount
; ++VC
) {
3429 Record
*AsmVariant
= Target
.getAsmParserVariant(VC
);
3430 int AsmVariantNo
= AsmVariant
->getValueAsInt("Variant");
3432 OS
<< "static const MatchEntry MatchTable" << VC
<< "[] = {\n";
3434 for (const auto &MI
: Info
.Matchables
) {
3435 if (MI
->AsmVariantID
!= AsmVariantNo
)
3438 // Store a pascal-style length byte in the mnemonic.
3439 std::string LenMnemonic
= char(MI
->Mnemonic
.size()) + MI
->Mnemonic
.str();
3440 OS
<< " { " << StringTable
.GetOrAddStringOffset(LenMnemonic
, false)
3441 << " /* " << MI
->Mnemonic
<< " */, "
3442 << Target
.getInstNamespace() << "::"
3443 << MI
->getResultInst()->TheDef
->getName() << ", "
3444 << MI
->ConversionFnKind
<< ", ";
3446 // Write the required features mask.
3448 if (MI
->RequiredFeatures
.empty())
3451 for (unsigned i
= 0, e
= MI
->RequiredFeatures
.size(); i
!= e
; ++i
)
3452 OS
<< '_' << MI
->RequiredFeatures
[i
]->TheDef
->getName();
3455 for (unsigned i
= 0, e
= MI
->AsmOperands
.size(); i
!= e
; ++i
) {
3456 const MatchableInfo::AsmOperand
&Op
= MI
->AsmOperands
[i
];
3459 OS
<< Op
.Class
->Name
;
3467 OS
<< "#include \"llvm/Support/Debug.h\"\n";
3468 OS
<< "#include \"llvm/Support/Format.h\"\n\n";
3470 // Finally, build the match function.
3471 OS
<< "unsigned " << Target
.getName() << ClassName
<< "::\n"
3472 << "MatchInstructionImpl(const OperandVector &Operands,\n";
3473 OS
<< " MCInst &Inst,\n";
3474 if (ReportMultipleNearMisses
)
3475 OS
<< " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
3477 OS
<< " uint64_t &ErrorInfo,\n"
3478 << " FeatureBitset &MissingFeatures,\n";
3479 OS
<< " bool matchingInlineAsm, unsigned VariantID) {\n";
3481 if (!ReportMultipleNearMisses
) {
3482 OS
<< " // Eliminate obvious mismatches.\n";
3483 OS
<< " if (Operands.size() > "
3484 << (MaxNumOperands
+ HasMnemonicFirst
) << ") {\n";
3485 OS
<< " ErrorInfo = "
3486 << (MaxNumOperands
+ HasMnemonicFirst
) << ";\n";
3487 OS
<< " return Match_InvalidOperand;\n";
3491 // Emit code to get the available features.
3492 OS
<< " // Get the current feature set.\n";
3493 OS
<< " const FeatureBitset &AvailableFeatures = getAvailableFeatures();\n\n";
3495 OS
<< " // Get the instruction mnemonic, which is the first token.\n";
3496 if (HasMnemonicFirst
) {
3497 OS
<< " StringRef Mnemonic = ((" << Target
.getName()
3498 << "Operand&)*Operands[0]).getToken();\n\n";
3500 OS
<< " StringRef Mnemonic;\n";
3501 OS
<< " if (Operands[0]->isToken())\n";
3502 OS
<< " Mnemonic = ((" << Target
.getName()
3503 << "Operand&)*Operands[0]).getToken();\n\n";
3506 if (HasMnemonicAliases
) {
3507 OS
<< " // Process all MnemonicAliases to remap the mnemonic.\n";
3508 OS
<< " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n";
3511 // Emit code to compute the class list for this operand vector.
3512 if (!ReportMultipleNearMisses
) {
3513 OS
<< " // Some state to try to produce better error messages.\n";
3514 OS
<< " bool HadMatchOtherThanFeatures = false;\n";
3515 OS
<< " bool HadMatchOtherThanPredicate = false;\n";
3516 OS
<< " unsigned RetCode = Match_InvalidOperand;\n";
3517 OS
<< " MissingFeatures.set();\n";
3518 OS
<< " // Set ErrorInfo to the operand that mismatches if it is\n";
3519 OS
<< " // wrong for all instances of the instruction.\n";
3520 OS
<< " ErrorInfo = ~0ULL;\n";
3523 if (HasOptionalOperands
) {
3524 OS
<< " SmallBitVector OptionalOperandsMask(" << MaxNumOperands
<< ");\n";
3527 // Emit code to search the table.
3528 OS
<< " // Find the appropriate table for this asm variant.\n";
3529 OS
<< " const MatchEntry *Start, *End;\n";
3530 OS
<< " switch (VariantID) {\n";
3531 OS
<< " default: llvm_unreachable(\"invalid variant!\");\n";
3532 for (unsigned VC
= 0; VC
!= VariantCount
; ++VC
) {
3533 Record
*AsmVariant
= Target
.getAsmParserVariant(VC
);
3534 int AsmVariantNo
= AsmVariant
->getValueAsInt("Variant");
3535 OS
<< " case " << AsmVariantNo
<< ": Start = std::begin(MatchTable" << VC
3536 << "); End = std::end(MatchTable" << VC
<< "); break;\n";
3540 OS
<< " // Search the table.\n";
3541 if (HasMnemonicFirst
) {
3542 OS
<< " auto MnemonicRange = "
3543 "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
3545 OS
<< " auto MnemonicRange = std::make_pair(Start, End);\n";
3546 OS
<< " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
3547 OS
<< " if (!Mnemonic.empty())\n";
3548 OS
<< " MnemonicRange = "
3549 "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
3552 OS
<< " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"AsmMatcher: found \" <<\n"
3553 << " std::distance(MnemonicRange.first, MnemonicRange.second) << \n"
3554 << " \" encodings with mnemonic '\" << Mnemonic << \"'\\n\");\n\n";
3556 OS
<< " // Return a more specific error code if no mnemonics match.\n";
3557 OS
<< " if (MnemonicRange.first == MnemonicRange.second)\n";
3558 OS
<< " return Match_MnemonicFail;\n\n";
3560 OS
<< " for (const MatchEntry *it = MnemonicRange.first, "
3561 << "*ie = MnemonicRange.second;\n";
3562 OS
<< " it != ie; ++it) {\n";
3563 OS
<< " const FeatureBitset &RequiredFeatures = "
3564 "FeatureBitsets[it->RequiredFeaturesIdx];\n";
3565 OS
<< " bool HasRequiredFeatures =\n";
3566 OS
<< " (AvailableFeatures & RequiredFeatures) == RequiredFeatures;\n";
3567 OS
<< " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Trying to match opcode \"\n";
3568 OS
<< " << MII.getName(it->Opcode) << \"\\n\");\n";
3570 if (ReportMultipleNearMisses
) {
3571 OS
<< " // Some state to record ways in which this instruction did not match.\n";
3572 OS
<< " NearMissInfo OperandNearMiss = NearMissInfo::getSuccess();\n";
3573 OS
<< " NearMissInfo FeaturesNearMiss = NearMissInfo::getSuccess();\n";
3574 OS
<< " NearMissInfo EarlyPredicateNearMiss = NearMissInfo::getSuccess();\n";
3575 OS
<< " NearMissInfo LatePredicateNearMiss = NearMissInfo::getSuccess();\n";
3576 OS
<< " bool MultipleInvalidOperands = false;\n";
3579 if (HasMnemonicFirst
) {
3580 OS
<< " // equal_range guarantees that instruction mnemonic matches.\n";
3581 OS
<< " assert(Mnemonic == it->getMnemonic());\n";
3584 // Emit check that the subclasses match.
3585 if (!ReportMultipleNearMisses
)
3586 OS
<< " bool OperandsValid = true;\n";
3587 if (HasOptionalOperands
) {
3588 OS
<< " OptionalOperandsMask.reset(0, " << MaxNumOperands
<< ");\n";
3590 OS
<< " for (unsigned FormalIdx = " << (HasMnemonicFirst
? "0" : "SIndex")
3591 << ", ActualIdx = " << (HasMnemonicFirst
? "1" : "SIndex")
3592 << "; FormalIdx != " << MaxNumOperands
<< "; ++FormalIdx) {\n";
3593 OS
<< " auto Formal = "
3594 << "static_cast<MatchClassKind>(it->Classes[FormalIdx]);\n";
3595 OS
<< " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3596 OS
<< " dbgs() << \" Matching formal operand class \" << getMatchClassName(Formal)\n";
3597 OS
<< " << \" against actual operand at index \" << ActualIdx);\n";
3598 OS
<< " if (ActualIdx < Operands.size())\n";
3599 OS
<< " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \" (\";\n";
3600 OS
<< " Operands[ActualIdx]->print(dbgs()); dbgs() << \"): \");\n";
3602 OS
<< " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \": \");\n";
3603 OS
<< " if (ActualIdx >= Operands.size()) {\n";
3604 OS
<< " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"actual operand index out of range \");\n";
3605 if (ReportMultipleNearMisses
) {
3606 OS
<< " bool ThisOperandValid = (Formal == " <<"InvalidMatchClass) || "
3607 "isSubclass(Formal, OptionalMatchClass);\n";
3608 OS
<< " if (!ThisOperandValid) {\n";
3609 OS
<< " if (!OperandNearMiss) {\n";
3610 OS
<< " // Record info about match failure for later use.\n";
3611 OS
<< " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"recording too-few-operands near miss\\n\");\n";
3612 OS
<< " OperandNearMiss =\n";
3613 OS
<< " NearMissInfo::getTooFewOperands(Formal, it->Opcode);\n";
3614 OS
<< " } else if (OperandNearMiss.getKind() != NearMissInfo::NearMissTooFewOperands) {\n";
3615 OS
<< " // If more than one operand is invalid, give up on this match entry.\n";
3616 OS
<< " DEBUG_WITH_TYPE(\n";
3617 OS
<< " \"asm-matcher\",\n";
3618 OS
<< " dbgs() << \"second invalid operand, giving up on this opcode\\n\");\n";
3619 OS
<< " MultipleInvalidOperands = true;\n";
3622 OS
<< " } else {\n";
3623 OS
<< " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"but formal operand not required\\n\");\n";
3626 OS
<< " continue;\n";
3628 OS
<< " OperandsValid = (Formal == InvalidMatchClass) || isSubclass(Formal, OptionalMatchClass);\n";
3629 OS
<< " if (!OperandsValid) ErrorInfo = ActualIdx;\n";
3630 if (HasOptionalOperands
) {
3631 OS
<< " OptionalOperandsMask.set(FormalIdx, " << MaxNumOperands
3637 OS
<< " MCParsedAsmOperand &Actual = *Operands[ActualIdx];\n";
3638 OS
<< " unsigned Diag = validateOperandClass(Actual, Formal);\n";
3639 OS
<< " if (Diag == Match_Success) {\n";
3640 OS
<< " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3641 OS
<< " dbgs() << \"match success using generic matcher\\n\");\n";
3642 OS
<< " ++ActualIdx;\n";
3643 OS
<< " continue;\n";
3645 OS
<< " // If the generic handler indicates an invalid operand\n";
3646 OS
<< " // failure, check for a special case.\n";
3647 OS
<< " if (Diag != Match_Success) {\n";
3648 OS
<< " unsigned TargetDiag = validateTargetOperandClass(Actual, Formal);\n";
3649 OS
<< " if (TargetDiag == Match_Success) {\n";
3650 OS
<< " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3651 OS
<< " dbgs() << \"match success using target matcher\\n\");\n";
3652 OS
<< " ++ActualIdx;\n";
3653 OS
<< " continue;\n";
3655 OS
<< " // If the target matcher returned a specific error code use\n";
3656 OS
<< " // that, else use the one from the generic matcher.\n";
3657 OS
<< " if (TargetDiag != Match_InvalidOperand && "
3658 "HasRequiredFeatures)\n";
3659 OS
<< " Diag = TargetDiag;\n";
3661 OS
<< " // If current formal operand wasn't matched and it is optional\n"
3662 << " // then try to match next formal operand\n";
3663 OS
<< " if (Diag == Match_InvalidOperand "
3664 << "&& isSubclass(Formal, OptionalMatchClass)) {\n";
3665 if (HasOptionalOperands
) {
3666 OS
<< " OptionalOperandsMask.set(FormalIdx);\n";
3668 OS
<< " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"ignoring optional operand\\n\");\n";
3669 OS
<< " continue;\n";
3672 if (ReportMultipleNearMisses
) {
3673 OS
<< " if (!OperandNearMiss) {\n";
3674 OS
<< " // If this is the first invalid operand we have seen, record some\n";
3675 OS
<< " // information about it.\n";
3676 OS
<< " DEBUG_WITH_TYPE(\n";
3677 OS
<< " \"asm-matcher\",\n";
3679 OS
<< " << \"operand match failed, recording near-miss with diag code \"\n";
3680 OS
<< " << Diag << \"\\n\");\n";
3681 OS
<< " OperandNearMiss =\n";
3682 OS
<< " NearMissInfo::getMissedOperand(Diag, Formal, it->Opcode, ActualIdx);\n";
3683 OS
<< " ++ActualIdx;\n";
3684 OS
<< " } else {\n";
3685 OS
<< " // If more than one operand is invalid, give up on this match entry.\n";
3686 OS
<< " DEBUG_WITH_TYPE(\n";
3687 OS
<< " \"asm-matcher\",\n";
3688 OS
<< " dbgs() << \"second operand mismatch, skipping this opcode\\n\");\n";
3689 OS
<< " MultipleInvalidOperands = true;\n";
3694 OS
<< " // If this operand is broken for all of the instances of this\n";
3695 OS
<< " // mnemonic, keep track of it so we can report loc info.\n";
3696 OS
<< " // If we already had a match that only failed due to a\n";
3697 OS
<< " // target predicate, that diagnostic is preferred.\n";
3698 OS
<< " if (!HadMatchOtherThanPredicate &&\n";
3699 OS
<< " (it == MnemonicRange.first || ErrorInfo <= ActualIdx)) {\n";
3700 OS
<< " if (HasRequiredFeatures && (ErrorInfo != ActualIdx || Diag "
3701 "!= Match_InvalidOperand))\n";
3702 OS
<< " RetCode = Diag;\n";
3703 OS
<< " ErrorInfo = ActualIdx;\n";
3705 OS
<< " // Otherwise, just reject this instance of the mnemonic.\n";
3706 OS
<< " OperandsValid = false;\n";
3711 if (ReportMultipleNearMisses
)
3712 OS
<< " if (MultipleInvalidOperands) {\n";
3714 OS
<< " if (!OperandsValid) {\n";
3715 OS
<< " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3716 OS
<< " \"operand mismatches, ignoring \"\n";
3717 OS
<< " \"this opcode\\n\");\n";
3718 OS
<< " continue;\n";
3721 // Emit check that the required features are available.
3722 OS
<< " if (!HasRequiredFeatures) {\n";
3723 if (!ReportMultipleNearMisses
)
3724 OS
<< " HadMatchOtherThanFeatures = true;\n";
3725 OS
<< " FeatureBitset NewMissingFeatures = RequiredFeatures & "
3726 "~AvailableFeatures;\n";
3727 OS
<< " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Missing target features:\";\n";
3728 OS
<< " for (unsigned I = 0, E = NewMissingFeatures.size(); I != E; ++I)\n";
3729 OS
<< " if (NewMissingFeatures[I])\n";
3730 OS
<< " dbgs() << ' ' << I;\n";
3731 OS
<< " dbgs() << \"\\n\");\n";
3732 if (ReportMultipleNearMisses
) {
3733 OS
<< " FeaturesNearMiss = NearMissInfo::getMissedFeature(NewMissingFeatures);\n";
3735 OS
<< " if (NewMissingFeatures.count() <=\n"
3736 " MissingFeatures.count())\n";
3737 OS
<< " MissingFeatures = NewMissingFeatures;\n";
3738 OS
<< " continue;\n";
3742 OS
<< " Inst.clear();\n\n";
3743 OS
<< " Inst.setOpcode(it->Opcode);\n";
3744 // Verify the instruction with the target-specific match predicate function.
3745 OS
<< " // We have a potential match but have not rendered the operands.\n"
3746 << " // Check the target predicate to handle any context sensitive\n"
3747 " // constraints.\n"
3748 << " // For example, Ties that are referenced multiple times must be\n"
3749 " // checked here to ensure the input is the same for each match\n"
3750 " // constraints. If we leave it any later the ties will have been\n"
3751 " // canonicalized\n"
3752 << " unsigned MatchResult;\n"
3753 << " if ((MatchResult = checkEarlyTargetMatchPredicate(Inst, "
3754 "Operands)) != Match_Success) {\n"
3755 << " Inst.clear();\n";
3756 OS
<< " DEBUG_WITH_TYPE(\n";
3757 OS
<< " \"asm-matcher\",\n";
3758 OS
<< " dbgs() << \"Early target match predicate failed with diag code \"\n";
3759 OS
<< " << MatchResult << \"\\n\");\n";
3760 if (ReportMultipleNearMisses
) {
3761 OS
<< " EarlyPredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
3763 OS
<< " RetCode = MatchResult;\n"
3764 << " HadMatchOtherThanPredicate = true;\n"
3769 if (ReportMultipleNearMisses
) {
3770 OS
<< " // If we did not successfully match the operands, then we can't convert to\n";
3771 OS
<< " // an MCInst, so bail out on this instruction variant now.\n";
3772 OS
<< " if (OperandNearMiss) {\n";
3773 OS
<< " // If the operand mismatch was the only problem, reprrt it as a near-miss.\n";
3774 OS
<< " if (NearMisses && !FeaturesNearMiss && !EarlyPredicateNearMiss) {\n";
3775 OS
<< " DEBUG_WITH_TYPE(\n";
3776 OS
<< " \"asm-matcher\",\n";
3778 OS
<< " << \"Opcode result: one mismatched operand, adding near-miss\\n\");\n";
3779 OS
<< " NearMisses->push_back(OperandNearMiss);\n";
3780 OS
<< " } else {\n";
3781 OS
<< " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3782 OS
<< " \"types of mismatch, so not \"\n";
3783 OS
<< " \"reporting near-miss\\n\");\n";
3785 OS
<< " continue;\n";
3789 OS
<< " if (matchingInlineAsm) {\n";
3790 OS
<< " convertToMapAndConstraints(it->ConvertFn, Operands);\n";
3791 if (!ReportMultipleNearMisses
) {
3792 OS
<< " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
3793 "Operands, ErrorInfo))\n";
3794 OS
<< " return Match_InvalidTiedOperand;\n";
3797 OS
<< " return Match_Success;\n";
3799 OS
<< " // We have selected a definite instruction, convert the parsed\n"
3800 << " // operands into the appropriate MCInst.\n";
3801 if (HasOptionalOperands
) {
3802 OS
<< " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands,\n"
3803 << " OptionalOperandsMask);\n";
3805 OS
<< " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
3809 // Verify the instruction with the target-specific match predicate function.
3810 OS
<< " // We have a potential match. Check the target predicate to\n"
3811 << " // handle any context sensitive constraints.\n"
3812 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
3813 << " Match_Success) {\n"
3814 << " DEBUG_WITH_TYPE(\"asm-matcher\",\n"
3815 << " dbgs() << \"Target match predicate failed with diag code \"\n"
3816 << " << MatchResult << \"\\n\");\n"
3817 << " Inst.clear();\n";
3818 if (ReportMultipleNearMisses
) {
3819 OS
<< " LatePredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
3821 OS
<< " RetCode = MatchResult;\n"
3822 << " HadMatchOtherThanPredicate = true;\n"
3827 if (ReportMultipleNearMisses
) {
3828 OS
<< " int NumNearMisses = ((int)(bool)OperandNearMiss +\n";
3829 OS
<< " (int)(bool)FeaturesNearMiss +\n";
3830 OS
<< " (int)(bool)EarlyPredicateNearMiss +\n";
3831 OS
<< " (int)(bool)LatePredicateNearMiss);\n";
3832 OS
<< " if (NumNearMisses == 1) {\n";
3833 OS
<< " // We had exactly one type of near-miss, so add that to the list.\n";
3834 OS
<< " assert(!OperandNearMiss && \"OperandNearMiss was handled earlier\");\n";
3835 OS
<< " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: found one type of \"\n";
3836 OS
<< " \"mismatch, so reporting a \"\n";
3837 OS
<< " \"near-miss\\n\");\n";
3838 OS
<< " if (NearMisses && FeaturesNearMiss)\n";
3839 OS
<< " NearMisses->push_back(FeaturesNearMiss);\n";
3840 OS
<< " else if (NearMisses && EarlyPredicateNearMiss)\n";
3841 OS
<< " NearMisses->push_back(EarlyPredicateNearMiss);\n";
3842 OS
<< " else if (NearMisses && LatePredicateNearMiss)\n";
3843 OS
<< " NearMisses->push_back(LatePredicateNearMiss);\n";
3845 OS
<< " continue;\n";
3846 OS
<< " } else if (NumNearMisses > 1) {\n";
3847 OS
<< " // This instruction missed in more than one way, so ignore it.\n";
3848 OS
<< " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3849 OS
<< " \"types of mismatch, so not \"\n";
3850 OS
<< " \"reporting near-miss\\n\");\n";
3851 OS
<< " continue;\n";
3855 // Call the post-processing function, if used.
3856 StringRef InsnCleanupFn
= AsmParser
->getValueAsString("AsmParserInstCleanup");
3857 if (!InsnCleanupFn
.empty())
3858 OS
<< " " << InsnCleanupFn
<< "(Inst);\n";
3860 if (HasDeprecation
) {
3861 OS
<< " std::string Info;\n";
3862 OS
<< " if (!getParser().getTargetParser().\n";
3863 OS
<< " getTargetOptions().MCNoDeprecatedWarn &&\n";
3864 OS
<< " MII.get(Inst.getOpcode()).getDeprecatedInfo(Inst, getSTI(), Info)) {\n";
3865 OS
<< " SMLoc Loc = ((" << Target
.getName()
3866 << "Operand&)*Operands[0]).getStartLoc();\n";
3867 OS
<< " getParser().Warning(Loc, Info, None);\n";
3871 if (!ReportMultipleNearMisses
) {
3872 OS
<< " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
3873 "Operands, ErrorInfo))\n";
3874 OS
<< " return Match_InvalidTiedOperand;\n";
3878 OS
<< " DEBUG_WITH_TYPE(\n";
3879 OS
<< " \"asm-matcher\",\n";
3880 OS
<< " dbgs() << \"Opcode result: complete match, selecting this opcode\\n\");\n";
3881 OS
<< " return Match_Success;\n";
3884 if (ReportMultipleNearMisses
) {
3885 OS
<< " // No instruction variants matched exactly.\n";
3886 OS
<< " return Match_NearMisses;\n";
3888 OS
<< " // Okay, we had no match. Try to return a useful error code.\n";
3889 OS
<< " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n";
3890 OS
<< " return RetCode;\n\n";
3891 OS
<< " ErrorInfo = 0;\n";
3892 OS
<< " return Match_MissingFeature;\n";
3896 if (!Info
.OperandMatchInfo
.empty())
3897 emitCustomOperandParsing(OS
, Target
, Info
, ClassName
, StringTable
,
3898 MaxMnemonicIndex
, FeatureBitsets
.size(),
3901 OS
<< "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
3903 OS
<< "\n#ifdef GET_MNEMONIC_SPELL_CHECKER\n";
3904 OS
<< "#undef GET_MNEMONIC_SPELL_CHECKER\n\n";
3906 emitMnemonicSpellChecker(OS
, Target
, VariantCount
);
3908 OS
<< "#endif // GET_MNEMONIC_SPELL_CHECKER\n\n";
3913 void EmitAsmMatcher(RecordKeeper
&RK
, raw_ostream
&OS
) {
3914 emitSourceFileHeader("Assembly Matcher Source Fragment", OS
);
3915 AsmMatcherEmitter(RK
).run(OS
);
3918 } // end namespace llvm