1 //===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend emits a target specifier matcher for converting parsed
11 // assembly operands in the MCInst structures. It also emits a matcher for
12 // custom operand parsing.
13 //
14 // Converting assembly operands into MCInst structures
15 // ---------------------------------------------------
16 //
17 // The input to the target specific matcher is a list of literal tokens and
18 // operands. The target specific parser should generally eliminate any syntax
19 // which is not relevant for matching; for example, comma tokens should have
20 // already been consumed and eliminated by the parser. Most instructions will
21 // end up with a single literal token (the instruction name) and some number of
22 // operands.
23 //
24 // Some example inputs, for X86:
25 //   'addl' (immediate ...) (register ...)
26 //   'add' (immediate ...) (memory ...)
27 //   'call' '*' %epc
28 //
29 // The assembly matcher is responsible for converting this input into a precise
30 // machine instruction (i.e., an instruction with a well defined encoding). This
31 // mapping has several properties which complicate matching:
32 //
33 //  - It may be ambiguous; many architectures can legally encode particular
34 //    variants of an instruction in different ways (for example, using a smaller
35 //    encoding for small immediates). Such ambiguities should never be
36 //    arbitrarily resolved by the assembler, the assembler is always responsible
37 //    for choosing the "best" available instruction.
38 //
39 //  - It may depend on the subtarget or the assembler context. Instructions
40 //    which are invalid for the current mode, but otherwise unambiguous (e.g.,
41 //    an SSE instruction in a file being assembled for i486) should be accepted
42 //    and rejected by the assembler front end. However, if the proper encoding
43 //    for an instruction is dependent on the assembler context then the matcher
44 //    is responsible for selecting the correct machine instruction for the
45 //    current mode.
46 //
47 // The core matching algorithm attempts to exploit the regularity in most
48 // instruction sets to quickly determine the set of possibly matching
49 // instructions, and the simplify the generated code. Additionally, this helps
50 // to ensure that the ambiguities are intentionally resolved by the user.
51 //
52 // The matching is divided into two distinct phases:
53 //
54 //   1. Classification: Each operand is mapped to the unique set which (a)
55 //      contains it, and (b) is the largest such subset for which a single
56 //      instruction could match all members.
57 //
58 //      For register classes, we can generate these subgroups automatically. For
59 //      arbitrary operands, we expect the user to define the classes and their
60 //      relations to one another (for example, 8-bit signed immediates as a
61 //      subset of 32-bit immediates).
62 //
63 //      By partitioning the operands in this way, we guarantee that for any
64 //      tuple of classes, any single instruction must match either all or none
65 //      of the sets of operands which could classify to that tuple.
66 //
67 //      In addition, the subset relation amongst classes induces a partial order
68 //      on such tuples, which we use to resolve ambiguities.
69 //
70 //   2. The input can now be treated as a tuple of classes (static tokens are
71 //      simple singleton sets). Each such tuple should generally map to a single
72 //      instruction (we currently ignore cases where this isn't true, whee!!!),
73 //      which we can emit a simple matcher for.
74 //
75 // Custom Operand Parsing
76 // ----------------------
77 //
78 //  Some targets need a custom way to parse operands, some specific instructions
79 //  can contain arguments that can represent processor flags and other kinds of
80 //  identifiers that need to be mapped to specific values in the final encoded
81 //  instructions. The target specific custom operand parsing works in the
82 //  following way:
83 //
84 //   1. A operand match table is built, each entry contains a mnemonic, an
85 //      operand class, a mask for all operand positions for that same
86 //      class/mnemonic and target features to be checked while trying to match.
87 //
88 //   2. The operand matcher will try every possible entry with the same
89 //      mnemonic and will check if the target feature for this mnemonic also
90 //      matches. After that, if the operand to be matched has its index
91 //      present in the mask, a successful match occurs. Otherwise, fallback
92 //      to the regular operand parsing.
93 //
94 //   3. For a match success, each operand class that has a 'ParserMethod'
95 //      becomes part of a switch from where the custom method is called.
96 //
97 //===----------------------------------------------------------------------===//
98 
99 #include "CodeGenTarget.h"
100 #include "llvm/ADT/PointerUnion.h"
101 #include "llvm/ADT/STLExtras.h"
102 #include "llvm/ADT/SmallPtrSet.h"
103 #include "llvm/ADT/SmallVector.h"
104 #include "llvm/ADT/StringExtras.h"
105 #include "llvm/Support/CommandLine.h"
106 #include "llvm/Support/Debug.h"
107 #include "llvm/Support/ErrorHandling.h"
108 #include "llvm/TableGen/Error.h"
109 #include "llvm/TableGen/Record.h"
110 #include "llvm/TableGen/StringMatcher.h"
111 #include "llvm/TableGen/StringToOffsetTable.h"
112 #include "llvm/TableGen/TableGenBackend.h"
113 #include <cassert>
114 #include <cctype>
115 #include <forward_list>
116 #include <map>
117 #include <set>
118 
119 using namespace llvm;
120 
121 #define DEBUG_TYPE "asm-matcher-emitter"
122 
123 static cl::opt<std::string>
124 MatchPrefix("match-prefix", cl::init(""),
125             cl::desc("Only match instructions with the given prefix"));
126 
127 namespace {
128 class AsmMatcherInfo;
129 struct SubtargetFeatureInfo;
130 
131 // Register sets are used as keys in some second-order sets TableGen creates
132 // when generating its data structures. This means that the order of two
133 // RegisterSets can be seen in the outputted AsmMatcher tables occasionally, and
134 // can even affect compiler output (at least seen in diagnostics produced when
135 // all matches fail). So we use a type that sorts them consistently.
136 typedef std::set<Record*, LessRecordByID> RegisterSet;
137 
138 class AsmMatcherEmitter {
139   RecordKeeper &Records;
140 public:
141   AsmMatcherEmitter(RecordKeeper &R) : Records(R) {}
142 
143   void run(raw_ostream &o);
144 };
145 
146 /// ClassInfo - Helper class for storing the information about a particular
147 /// class of operands which can be matched.
148 struct ClassInfo {
149   enum ClassInfoKind {
150     /// Invalid kind, for use as a sentinel value.
151     Invalid = 0,
152 
153     /// The class for a particular token.
154     Token,
155 
156     /// The (first) register class, subsequent register classes are
157     /// RegisterClass0+1, and so on.
158     RegisterClass0,
159 
160     /// The (first) user defined class, subsequent user defined classes are
161     /// UserClass0+1, and so on.
162     UserClass0 = 1<<16
163   };
164 
165   /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
166   /// N) for the Nth user defined class.
167   unsigned Kind;
168 
169   /// SuperClasses - The super classes of this class. Note that for simplicities
170   /// sake user operands only record their immediate super class, while register
171   /// operands include all superclasses.
172   std::vector<ClassInfo*> SuperClasses;
173 
174   /// Name - The full class name, suitable for use in an enum.
175   std::string Name;
176 
177   /// ClassName - The unadorned generic name for this class (e.g., Token).
178   std::string ClassName;
179 
180   /// ValueName - The name of the value this class represents; for a token this
181   /// is the literal token string, for an operand it is the TableGen class (or
182   /// empty if this is a derived class).
183   std::string ValueName;
184 
185   /// PredicateMethod - The name of the operand method to test whether the
186   /// operand matches this class; this is not valid for Token or register kinds.
187   std::string PredicateMethod;
188 
189   /// RenderMethod - The name of the operand method to add this operand to an
190   /// MCInst; this is not valid for Token or register kinds.
191   std::string RenderMethod;
192 
193   /// ParserMethod - The name of the operand method to do a target specific
194   /// parsing on the operand.
195   std::string ParserMethod;
196 
197   /// For register classes: the records for all the registers in this class.
198   RegisterSet Registers;
199 
200   /// For custom match classes: the diagnostic kind for when the predicate fails.
201   std::string DiagnosticType;
202 
203   /// Is this operand optional and not always required.
204   bool IsOptional;
205 
206   /// DefaultMethod - The name of the method that returns the default operand
207   /// for optional operand
208   std::string DefaultMethod;
209 
210 public:
211   /// isRegisterClass() - Check if this is a register class.
212   bool isRegisterClass() const {
213     return Kind >= RegisterClass0 && Kind < UserClass0;
214   }
215 
216   /// isUserClass() - Check if this is a user defined class.
217   bool isUserClass() const {
218     return Kind >= UserClass0;
219   }
220 
221   /// isRelatedTo - Check whether this class is "related" to \p RHS. Classes
222   /// are related if they are in the same class hierarchy.
223   bool isRelatedTo(const ClassInfo &RHS) const {
224     // Tokens are only related to tokens.
225     if (Kind == Token || RHS.Kind == Token)
226       return Kind == Token && RHS.Kind == Token;
227 
228     // Registers classes are only related to registers classes, and only if
229     // their intersection is non-empty.
230     if (isRegisterClass() || RHS.isRegisterClass()) {
231       if (!isRegisterClass() || !RHS.isRegisterClass())
232         return false;
233 
234       RegisterSet Tmp;
235       std::insert_iterator<RegisterSet> II(Tmp, Tmp.begin());
236       std::set_intersection(Registers.begin(), Registers.end(),
237                             RHS.Registers.begin(), RHS.Registers.end(),
238                             II, LessRecordByID());
239 
240       return !Tmp.empty();
241     }
242 
243     // Otherwise we have two users operands; they are related if they are in the
244     // same class hierarchy.
245     //
246     // FIXME: This is an oversimplification, they should only be related if they
247     // intersect, however we don't have that information.
248     assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
249     const ClassInfo *Root = this;
250     while (!Root->SuperClasses.empty())
251       Root = Root->SuperClasses.front();
252 
253     const ClassInfo *RHSRoot = &RHS;
254     while (!RHSRoot->SuperClasses.empty())
255       RHSRoot = RHSRoot->SuperClasses.front();
256 
257     return Root == RHSRoot;
258   }
259 
260   /// isSubsetOf - Test whether this class is a subset of \p RHS.
261   bool isSubsetOf(const ClassInfo &RHS) const {
262     // This is a subset of RHS if it is the same class...
263     if (this == &RHS)
264       return true;
265 
266     // ... or if any of its super classes are a subset of RHS.
267     for (const ClassInfo *CI : SuperClasses)
268       if (CI->isSubsetOf(RHS))
269         return true;
270 
271     return false;
272   }
273 
274   int getTreeDepth() const {
275     int Depth = 0;
276     const ClassInfo *Root = this;
277     while (!Root->SuperClasses.empty()) {
278       Depth++;
279       Root = Root->SuperClasses.front();
280     }
281     return Depth;
282   }
283 
284   const ClassInfo *findRoot() const {
285     const ClassInfo *Root = this;
286     while (!Root->SuperClasses.empty())
287       Root = Root->SuperClasses.front();
288     return Root;
289   }
290 
291   /// Compare two classes. This does not produce a total ordering, but does
292   /// guarantee that subclasses are sorted before their parents, and that the
293   /// ordering is transitive.
294   bool operator<(const ClassInfo &RHS) const {
295     if (this == &RHS)
296       return false;
297 
298     // First, enforce the ordering between the three different types of class.
299     // Tokens sort before registers, which sort before user classes.
300     if (Kind == Token) {
301       if (RHS.Kind != Token)
302         return true;
303       assert(RHS.Kind == Token);
304     } else if (isRegisterClass()) {
305       if (RHS.Kind == Token)
306         return false;
307       else if (RHS.isUserClass())
308         return true;
309       assert(RHS.isRegisterClass());
310     } else if (isUserClass()) {
311       if (!RHS.isUserClass())
312         return false;
313       assert(RHS.isUserClass());
314     } else {
315       llvm_unreachable("Unknown ClassInfoKind");
316     }
317 
318     if (Kind == Token || isUserClass()) {
319       // Related tokens and user classes get sorted by depth in the inheritence
320       // tree (so that subclasses are before their parents).
321       if (isRelatedTo(RHS)) {
322         if (getTreeDepth() > RHS.getTreeDepth())
323           return true;
324         if (getTreeDepth() < RHS.getTreeDepth())
325           return false;
326       } else {
327         // Unrelated tokens and user classes are ordered by the name of their
328         // root nodes, so that there is a consistent ordering between
329         // unconnected trees.
330         return findRoot()->ValueName < RHS.findRoot()->ValueName;
331       }
332     } else if (isRegisterClass()) {
333       // For register sets, sort by number of registers. This guarantees that
334       // a set will always sort before all of it's strict supersets.
335       if (Registers.size() != RHS.Registers.size())
336         return Registers.size() < RHS.Registers.size();
337     } else {
338       llvm_unreachable("Unknown ClassInfoKind");
339     }
340 
341     // FIXME: We should be able to just return false here, as we only need a
342     // partial order (we use stable sorts, so this is deterministic) and the
343     // name of a class shouldn't be significant. However, some of the backends
344     // accidentally rely on this behaviour, so it will have to stay like this
345     // until they are fixed.
346     return ValueName < RHS.ValueName;
347   }
348 };
349 
350 class AsmVariantInfo {
351 public:
352   std::string RegisterPrefix;
353   std::string TokenizingCharacters;
354   std::string SeparatorCharacters;
355   std::string BreakCharacters;
356   int AsmVariantNo;
357 };
358 
359 /// MatchableInfo - Helper class for storing the necessary information for an
360 /// instruction or alias which is capable of being matched.
361 struct MatchableInfo {
362   struct AsmOperand {
363     /// Token - This is the token that the operand came from.
364     StringRef Token;
365 
366     /// The unique class instance this operand should match.
367     ClassInfo *Class;
368 
369     /// The operand name this is, if anything.
370     StringRef SrcOpName;
371 
372     /// The suboperand index within SrcOpName, or -1 for the entire operand.
373     int SubOpIdx;
374 
375     /// Whether the token is "isolated", i.e., it is preceded and followed
376     /// by separators.
377     bool IsIsolatedToken;
378 
379     /// Register record if this token is singleton register.
380     Record *SingletonReg;
381 
382     explicit AsmOperand(bool IsIsolatedToken, StringRef T)
383         : Token(T), Class(nullptr), SubOpIdx(-1),
384           IsIsolatedToken(IsIsolatedToken), SingletonReg(nullptr) {}
385   };
386 
387   /// ResOperand - This represents a single operand in the result instruction
388   /// generated by the match.  In cases (like addressing modes) where a single
389   /// assembler operand expands to multiple MCOperands, this represents the
390   /// single assembler operand, not the MCOperand.
391   struct ResOperand {
392     enum {
393       /// RenderAsmOperand - This represents an operand result that is
394       /// generated by calling the render method on the assembly operand.  The
395       /// corresponding AsmOperand is specified by AsmOperandNum.
396       RenderAsmOperand,
397 
398       /// TiedOperand - This represents a result operand that is a duplicate of
399       /// a previous result operand.
400       TiedOperand,
401 
402       /// ImmOperand - This represents an immediate value that is dumped into
403       /// the operand.
404       ImmOperand,
405 
406       /// RegOperand - This represents a fixed register that is dumped in.
407       RegOperand
408     } Kind;
409 
410     union {
411       /// This is the operand # in the AsmOperands list that this should be
412       /// copied from.
413       unsigned AsmOperandNum;
414 
415       /// TiedOperandNum - This is the (earlier) result operand that should be
416       /// copied from.
417       unsigned TiedOperandNum;
418 
419       /// ImmVal - This is the immediate value added to the instruction.
420       int64_t ImmVal;
421 
422       /// Register - This is the register record.
423       Record *Register;
424     };
425 
426     /// MINumOperands - The number of MCInst operands populated by this
427     /// operand.
428     unsigned MINumOperands;
429 
430     static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
431       ResOperand X;
432       X.Kind = RenderAsmOperand;
433       X.AsmOperandNum = AsmOpNum;
434       X.MINumOperands = NumOperands;
435       return X;
436     }
437 
438     static ResOperand getTiedOp(unsigned TiedOperandNum) {
439       ResOperand X;
440       X.Kind = TiedOperand;
441       X.TiedOperandNum = TiedOperandNum;
442       X.MINumOperands = 1;
443       return X;
444     }
445 
446     static ResOperand getImmOp(int64_t Val) {
447       ResOperand X;
448       X.Kind = ImmOperand;
449       X.ImmVal = Val;
450       X.MINumOperands = 1;
451       return X;
452     }
453 
454     static ResOperand getRegOp(Record *Reg) {
455       ResOperand X;
456       X.Kind = RegOperand;
457       X.Register = Reg;
458       X.MINumOperands = 1;
459       return X;
460     }
461   };
462 
463   /// AsmVariantID - Target's assembly syntax variant no.
464   int AsmVariantID;
465 
466   /// AsmString - The assembly string for this instruction (with variants
467   /// removed), e.g. "movsx $src, $dst".
468   std::string AsmString;
469 
470   /// TheDef - This is the definition of the instruction or InstAlias that this
471   /// matchable came from.
472   Record *const TheDef;
473 
474   /// DefRec - This is the definition that it came from.
475   PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
476 
477   const CodeGenInstruction *getResultInst() const {
478     if (DefRec.is<const CodeGenInstruction*>())
479       return DefRec.get<const CodeGenInstruction*>();
480     return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
481   }
482 
483   /// ResOperands - This is the operand list that should be built for the result
484   /// MCInst.
485   SmallVector<ResOperand, 8> ResOperands;
486 
487   /// Mnemonic - This is the first token of the matched instruction, its
488   /// mnemonic.
489   StringRef Mnemonic;
490 
491   /// AsmOperands - The textual operands that this instruction matches,
492   /// annotated with a class and where in the OperandList they were defined.
493   /// This directly corresponds to the tokenized AsmString after the mnemonic is
494   /// removed.
495   SmallVector<AsmOperand, 8> AsmOperands;
496 
497   /// Predicates - The required subtarget features to match this instruction.
498   SmallVector<const SubtargetFeatureInfo *, 4> RequiredFeatures;
499 
500   /// ConversionFnKind - The enum value which is passed to the generated
501   /// convertToMCInst to convert parsed operands into an MCInst for this
502   /// function.
503   std::string ConversionFnKind;
504 
505   /// If this instruction is deprecated in some form.
506   bool HasDeprecation;
507 
508   /// If this is an alias, this is use to determine whether or not to using
509   /// the conversion function defined by the instruction's AsmMatchConverter
510   /// or to use the function generated by the alias.
511   bool UseInstAsmMatchConverter;
512 
513   MatchableInfo(const CodeGenInstruction &CGI)
514     : AsmVariantID(0), AsmString(CGI.AsmString), TheDef(CGI.TheDef), DefRec(&CGI),
515       UseInstAsmMatchConverter(true) {
516   }
517 
518   MatchableInfo(std::unique_ptr<const CodeGenInstAlias> Alias)
519     : AsmVariantID(0), AsmString(Alias->AsmString), TheDef(Alias->TheDef),
520       DefRec(Alias.release()),
521       UseInstAsmMatchConverter(
522         TheDef->getValueAsBit("UseInstAsmMatchConverter")) {
523   }
524 
525   // Could remove this and the dtor if PointerUnion supported unique_ptr
526   // elements with a dynamic failure/assertion (like the one below) in the case
527   // where it was copied while being in an owning state.
528   MatchableInfo(const MatchableInfo &RHS)
529       : AsmVariantID(RHS.AsmVariantID), AsmString(RHS.AsmString),
530         TheDef(RHS.TheDef), DefRec(RHS.DefRec), ResOperands(RHS.ResOperands),
531         Mnemonic(RHS.Mnemonic), AsmOperands(RHS.AsmOperands),
532         RequiredFeatures(RHS.RequiredFeatures),
533         ConversionFnKind(RHS.ConversionFnKind),
534         HasDeprecation(RHS.HasDeprecation),
535         UseInstAsmMatchConverter(RHS.UseInstAsmMatchConverter) {
536     assert(!DefRec.is<const CodeGenInstAlias *>());
537   }
538 
539   ~MatchableInfo() {
540     delete DefRec.dyn_cast<const CodeGenInstAlias*>();
541   }
542 
543   // Two-operand aliases clone from the main matchable, but mark the second
544   // operand as a tied operand of the first for purposes of the assembler.
545   void formTwoOperandAlias(StringRef Constraint);
546 
547   void initialize(const AsmMatcherInfo &Info,
548                   SmallPtrSetImpl<Record*> &SingletonRegisters,
549                   AsmVariantInfo const &Variant,
550                   bool HasMnemonicFirst);
551 
552   /// validate - Return true if this matchable is a valid thing to match against
553   /// and perform a bunch of validity checking.
554   bool validate(StringRef CommentDelimiter, bool Hack) const;
555 
556   /// findAsmOperand - Find the AsmOperand with the specified name and
557   /// suboperand index.
558   int findAsmOperand(StringRef N, int SubOpIdx) const {
559     auto I = find_if(AsmOperands, [&](const AsmOperand &Op) {
560       return Op.SrcOpName == N && Op.SubOpIdx == SubOpIdx;
561     });
562     return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
563   }
564 
565   /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
566   /// This does not check the suboperand index.
567   int findAsmOperandNamed(StringRef N) const {
568     auto I = find_if(AsmOperands,
569                      [&](const AsmOperand &Op) { return Op.SrcOpName == N; });
570     return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
571   }
572 
573   void buildInstructionResultOperands();
574   void buildAliasResultOperands();
575 
576   /// operator< - Compare two matchables.
577   bool operator<(const MatchableInfo &RHS) const {
578     // The primary comparator is the instruction mnemonic.
579     if (int Cmp = Mnemonic.compare(RHS.Mnemonic))
580       return Cmp == -1;
581 
582     if (AsmOperands.size() != RHS.AsmOperands.size())
583       return AsmOperands.size() < RHS.AsmOperands.size();
584 
585     // Compare lexicographically by operand. The matcher validates that other
586     // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
587     for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
588       if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
589         return true;
590       if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
591         return false;
592     }
593 
594     // Give matches that require more features higher precedence. This is useful
595     // because we cannot define AssemblerPredicates with the negation of
596     // processor features. For example, ARM v6 "nop" may be either a HINT or
597     // MOV. With v6, we want to match HINT. The assembler has no way to
598     // predicate MOV under "NoV6", but HINT will always match first because it
599     // requires V6 while MOV does not.
600     if (RequiredFeatures.size() != RHS.RequiredFeatures.size())
601       return RequiredFeatures.size() > RHS.RequiredFeatures.size();
602 
603     return false;
604   }
605 
606   /// couldMatchAmbiguouslyWith - Check whether this matchable could
607   /// ambiguously match the same set of operands as \p RHS (without being a
608   /// strictly superior match).
609   bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) const {
610     // The primary comparator is the instruction mnemonic.
611     if (Mnemonic != RHS.Mnemonic)
612       return false;
613 
614     // The number of operands is unambiguous.
615     if (AsmOperands.size() != RHS.AsmOperands.size())
616       return false;
617 
618     // Otherwise, make sure the ordering of the two instructions is unambiguous
619     // by checking that either (a) a token or operand kind discriminates them,
620     // or (b) the ordering among equivalent kinds is consistent.
621 
622     // Tokens and operand kinds are unambiguous (assuming a correct target
623     // specific parser).
624     for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
625       if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
626           AsmOperands[i].Class->Kind == ClassInfo::Token)
627         if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
628             *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
629           return false;
630 
631     // Otherwise, this operand could commute if all operands are equivalent, or
632     // there is a pair of operands that compare less than and a pair that
633     // compare greater than.
634     bool HasLT = false, HasGT = false;
635     for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
636       if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
637         HasLT = true;
638       if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
639         HasGT = true;
640     }
641 
642     return HasLT == HasGT;
643   }
644 
645   void dump() const;
646 
647 private:
648   void tokenizeAsmString(AsmMatcherInfo const &Info,
649                          AsmVariantInfo const &Variant);
650   void addAsmOperand(StringRef Token, bool IsIsolatedToken = false);
651 };
652 
653 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
654 /// feature which participates in instruction matching.
655 struct SubtargetFeatureInfo {
656   /// \brief The predicate record for this feature.
657   Record *TheDef;
658 
659   /// \brief An unique index assigned to represent this feature.
660   uint64_t Index;
661 
662   SubtargetFeatureInfo(Record *D, uint64_t Idx) : TheDef(D), Index(Idx) {}
663 
664   /// \brief The name of the enumerated constant identifying this feature.
665   std::string getEnumName() const {
666     return "Feature_" + TheDef->getName();
667   }
668 
669   void dump() const {
670     errs() << getEnumName() << " " << Index << "\n";
671     TheDef->dump();
672   }
673 };
674 
675 struct OperandMatchEntry {
676   unsigned OperandMask;
677   const MatchableInfo* MI;
678   ClassInfo *CI;
679 
680   static OperandMatchEntry create(const MatchableInfo *mi, ClassInfo *ci,
681                                   unsigned opMask) {
682     OperandMatchEntry X;
683     X.OperandMask = opMask;
684     X.CI = ci;
685     X.MI = mi;
686     return X;
687   }
688 };
689 
690 class AsmMatcherInfo {
691 public:
692   /// Tracked Records
693   RecordKeeper &Records;
694 
695   /// The tablegen AsmParser record.
696   Record *AsmParser;
697 
698   /// Target - The target information.
699   CodeGenTarget &Target;
700 
701   /// The classes which are needed for matching.
702   std::forward_list<ClassInfo> Classes;
703 
704   /// The information on the matchables to match.
705   std::vector<std::unique_ptr<MatchableInfo>> Matchables;
706 
707   /// Info for custom matching operands by user defined methods.
708   std::vector<OperandMatchEntry> OperandMatchInfo;
709 
710   /// Map of Register records to their class information.
711   typedef std::map<Record*, ClassInfo*, LessRecordByID> RegisterClassesTy;
712   RegisterClassesTy RegisterClasses;
713 
714   /// Map of Predicate records to their subtarget information.
715   std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures;
716 
717   /// Map of AsmOperandClass records to their class information.
718   std::map<Record*, ClassInfo*> AsmOperandClasses;
719 
720 private:
721   /// Map of token to class information which has already been constructed.
722   std::map<std::string, ClassInfo*> TokenClasses;
723 
724   /// Map of RegisterClass records to their class information.
725   std::map<Record*, ClassInfo*> RegisterClassClasses;
726 
727 private:
728   /// getTokenClass - Lookup or create the class for the given token.
729   ClassInfo *getTokenClass(StringRef Token);
730 
731   /// getOperandClass - Lookup or create the class for the given operand.
732   ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
733                              int SubOpIdx);
734   ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
735 
736   /// buildRegisterClasses - Build the ClassInfo* instances for register
737   /// classes.
738   void buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters);
739 
740   /// buildOperandClasses - Build the ClassInfo* instances for user defined
741   /// operand classes.
742   void buildOperandClasses();
743 
744   void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
745                                         unsigned AsmOpIdx);
746   void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
747                                   MatchableInfo::AsmOperand &Op);
748 
749 public:
750   AsmMatcherInfo(Record *AsmParser,
751                  CodeGenTarget &Target,
752                  RecordKeeper &Records);
753 
754   /// buildInfo - Construct the various tables used during matching.
755   void buildInfo();
756 
757   /// buildOperandMatchInfo - Build the necessary information to handle user
758   /// defined operand parsing methods.
759   void buildOperandMatchInfo();
760 
761   /// getSubtargetFeature - Lookup or create the subtarget feature info for the
762   /// given operand.
763   const SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
764     assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
765     const auto &I = SubtargetFeatures.find(Def);
766     return I == SubtargetFeatures.end() ? nullptr : &I->second;
767   }
768 
769   RecordKeeper &getRecords() const {
770     return Records;
771   }
772 
773   bool hasOptionalOperands() const {
774     return find_if(Classes, [](const ClassInfo &Class) {
775              return Class.IsOptional;
776            }) != Classes.end();
777   }
778 };
779 
780 } // end anonymous namespace
781 
782 void MatchableInfo::dump() const {
783   errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
784 
785   for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
786     const AsmOperand &Op = AsmOperands[i];
787     errs() << "  op[" << i << "] = " << Op.Class->ClassName << " - ";
788     errs() << '\"' << Op.Token << "\"\n";
789   }
790 }
791 
792 static std::pair<StringRef, StringRef>
793 parseTwoOperandConstraint(StringRef S, ArrayRef<SMLoc> Loc) {
794   // Split via the '='.
795   std::pair<StringRef, StringRef> Ops = S.split('=');
796   if (Ops.second == "")
797     PrintFatalError(Loc, "missing '=' in two-operand alias constraint");
798   // Trim whitespace and the leading '$' on the operand names.
799   size_t start = Ops.first.find_first_of('$');
800   if (start == std::string::npos)
801     PrintFatalError(Loc, "expected '$' prefix on asm operand name");
802   Ops.first = Ops.first.slice(start + 1, std::string::npos);
803   size_t end = Ops.first.find_last_of(" \t");
804   Ops.first = Ops.first.slice(0, end);
805   // Now the second operand.
806   start = Ops.second.find_first_of('$');
807   if (start == std::string::npos)
808     PrintFatalError(Loc, "expected '$' prefix on asm operand name");
809   Ops.second = Ops.second.slice(start + 1, std::string::npos);
810   end = Ops.second.find_last_of(" \t");
811   Ops.first = Ops.first.slice(0, end);
812   return Ops;
813 }
814 
815 void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
816   // Figure out which operands are aliased and mark them as tied.
817   std::pair<StringRef, StringRef> Ops =
818     parseTwoOperandConstraint(Constraint, TheDef->getLoc());
819 
820   // Find the AsmOperands that refer to the operands we're aliasing.
821   int SrcAsmOperand = findAsmOperandNamed(Ops.first);
822   int DstAsmOperand = findAsmOperandNamed(Ops.second);
823   if (SrcAsmOperand == -1)
824     PrintFatalError(TheDef->getLoc(),
825                     "unknown source two-operand alias operand '" + Ops.first +
826                     "'.");
827   if (DstAsmOperand == -1)
828     PrintFatalError(TheDef->getLoc(),
829                     "unknown destination two-operand alias operand '" +
830                     Ops.second + "'.");
831 
832   // Find the ResOperand that refers to the operand we're aliasing away
833   // and update it to refer to the combined operand instead.
834   for (ResOperand &Op : ResOperands) {
835     if (Op.Kind == ResOperand::RenderAsmOperand &&
836         Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
837       Op.AsmOperandNum = DstAsmOperand;
838       break;
839     }
840   }
841   // Remove the AsmOperand for the alias operand.
842   AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
843   // Adjust the ResOperand references to any AsmOperands that followed
844   // the one we just deleted.
845   for (ResOperand &Op : ResOperands) {
846     switch(Op.Kind) {
847     default:
848       // Nothing to do for operands that don't reference AsmOperands.
849       break;
850     case ResOperand::RenderAsmOperand:
851       if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
852         --Op.AsmOperandNum;
853       break;
854     case ResOperand::TiedOperand:
855       if (Op.TiedOperandNum > (unsigned)SrcAsmOperand)
856         --Op.TiedOperandNum;
857       break;
858     }
859   }
860 }
861 
862 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
863 /// if present, from specified token.
864 static void
865 extractSingletonRegisterForAsmOperand(MatchableInfo::AsmOperand &Op,
866                                       const AsmMatcherInfo &Info,
867                                       StringRef RegisterPrefix) {
868   StringRef Tok = Op.Token;
869 
870   // If this token is not an isolated token, i.e., it isn't separated from
871   // other tokens (e.g. with whitespace), don't interpret it as a register name.
872   if (!Op.IsIsolatedToken)
873     return;
874 
875   if (RegisterPrefix.empty()) {
876     std::string LoweredTok = Tok.lower();
877     if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
878       Op.SingletonReg = Reg->TheDef;
879     return;
880   }
881 
882   if (!Tok.startswith(RegisterPrefix))
883     return;
884 
885   StringRef RegName = Tok.substr(RegisterPrefix.size());
886   if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
887     Op.SingletonReg = Reg->TheDef;
888 
889   // If there is no register prefix (i.e. "%" in "%eax"), then this may
890   // be some random non-register token, just ignore it.
891 }
892 
893 void MatchableInfo::initialize(const AsmMatcherInfo &Info,
894                                SmallPtrSetImpl<Record*> &SingletonRegisters,
895                                AsmVariantInfo const &Variant,
896                                bool HasMnemonicFirst) {
897   AsmVariantID = Variant.AsmVariantNo;
898   AsmString =
899     CodeGenInstruction::FlattenAsmStringVariants(AsmString,
900                                                  Variant.AsmVariantNo);
901 
902   tokenizeAsmString(Info, Variant);
903 
904   // The first token of the instruction is the mnemonic, which must be a
905   // simple string, not a $foo variable or a singleton register.
906   if (AsmOperands.empty())
907     PrintFatalError(TheDef->getLoc(),
908                   "Instruction '" + TheDef->getName() + "' has no tokens");
909 
910   assert(!AsmOperands[0].Token.empty());
911   if (HasMnemonicFirst) {
912     Mnemonic = AsmOperands[0].Token;
913     if (Mnemonic[0] == '$')
914       PrintFatalError(TheDef->getLoc(),
915                       "Invalid instruction mnemonic '" + Mnemonic + "'!");
916 
917     // Remove the first operand, it is tracked in the mnemonic field.
918     AsmOperands.erase(AsmOperands.begin());
919   } else if (AsmOperands[0].Token[0] != '$')
920     Mnemonic = AsmOperands[0].Token;
921 
922   // Compute the require features.
923   for (Record *Predicate : TheDef->getValueAsListOfDefs("Predicates"))
924     if (const SubtargetFeatureInfo *Feature =
925             Info.getSubtargetFeature(Predicate))
926       RequiredFeatures.push_back(Feature);
927 
928   // Collect singleton registers, if used.
929   for (MatchableInfo::AsmOperand &Op : AsmOperands) {
930     extractSingletonRegisterForAsmOperand(Op, Info, Variant.RegisterPrefix);
931     if (Record *Reg = Op.SingletonReg)
932       SingletonRegisters.insert(Reg);
933   }
934 
935   const RecordVal *DepMask = TheDef->getValue("DeprecatedFeatureMask");
936   if (!DepMask)
937     DepMask = TheDef->getValue("ComplexDeprecationPredicate");
938 
939   HasDeprecation =
940       DepMask ? !DepMask->getValue()->getAsUnquotedString().empty() : false;
941 }
942 
943 /// Append an AsmOperand for the given substring of AsmString.
944 void MatchableInfo::addAsmOperand(StringRef Token, bool IsIsolatedToken) {
945   AsmOperands.push_back(AsmOperand(IsIsolatedToken, Token));
946 }
947 
948 /// tokenizeAsmString - Tokenize a simplified assembly string.
949 void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info,
950                                       AsmVariantInfo const &Variant) {
951   StringRef String = AsmString;
952   size_t Prev = 0;
953   bool InTok = false;
954   bool IsIsolatedToken = true;
955   for (size_t i = 0, e = String.size(); i != e; ++i) {
956     char Char = String[i];
957     if (Variant.BreakCharacters.find(Char) != std::string::npos) {
958       if (InTok) {
959         addAsmOperand(String.slice(Prev, i), false);
960         Prev = i;
961         IsIsolatedToken = false;
962       }
963       InTok = true;
964       continue;
965     }
966     if (Variant.TokenizingCharacters.find(Char) != std::string::npos) {
967       if (InTok) {
968         addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
969         InTok = false;
970         IsIsolatedToken = false;
971       }
972       addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
973       Prev = i + 1;
974       IsIsolatedToken = true;
975       continue;
976     }
977     if (Variant.SeparatorCharacters.find(Char) != std::string::npos) {
978       if (InTok) {
979         addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
980         InTok = false;
981       }
982       Prev = i + 1;
983       IsIsolatedToken = true;
984       continue;
985     }
986 
987     switch (Char) {
988     case '\\':
989       if (InTok) {
990         addAsmOperand(String.slice(Prev, i), false);
991         InTok = false;
992         IsIsolatedToken = false;
993       }
994       ++i;
995       assert(i != String.size() && "Invalid quoted character");
996       addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
997       Prev = i + 1;
998       IsIsolatedToken = false;
999       break;
1000 
1001     case '$': {
1002       if (InTok) {
1003         addAsmOperand(String.slice(Prev, i), false);
1004         InTok = false;
1005         IsIsolatedToken = false;
1006       }
1007 
1008       // If this isn't "${", start new identifier looking like "$xxx"
1009       if (i + 1 == String.size() || String[i + 1] != '{') {
1010         Prev = i;
1011         break;
1012       }
1013 
1014       size_t EndPos = String.find('}', i);
1015       assert(EndPos != StringRef::npos &&
1016              "Missing brace in operand reference!");
1017       addAsmOperand(String.slice(i, EndPos+1), IsIsolatedToken);
1018       Prev = EndPos + 1;
1019       i = EndPos;
1020       IsIsolatedToken = false;
1021       break;
1022     }
1023 
1024     default:
1025       InTok = true;
1026       break;
1027     }
1028   }
1029   if (InTok && Prev != String.size())
1030     addAsmOperand(String.substr(Prev), IsIsolatedToken);
1031 }
1032 
1033 bool MatchableInfo::validate(StringRef CommentDelimiter, bool Hack) const {
1034   // Reject matchables with no .s string.
1035   if (AsmString.empty())
1036     PrintFatalError(TheDef->getLoc(), "instruction with empty asm string");
1037 
1038   // Reject any matchables with a newline in them, they should be marked
1039   // isCodeGenOnly if they are pseudo instructions.
1040   if (AsmString.find('\n') != std::string::npos)
1041     PrintFatalError(TheDef->getLoc(),
1042                   "multiline instruction is not valid for the asmparser, "
1043                   "mark it isCodeGenOnly");
1044 
1045   // Remove comments from the asm string.  We know that the asmstring only
1046   // has one line.
1047   if (!CommentDelimiter.empty() &&
1048       StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
1049     PrintFatalError(TheDef->getLoc(),
1050                   "asmstring for instruction has comment character in it, "
1051                   "mark it isCodeGenOnly");
1052 
1053   // Reject matchables with operand modifiers, these aren't something we can
1054   // handle, the target should be refactored to use operands instead of
1055   // modifiers.
1056   //
1057   // Also, check for instructions which reference the operand multiple times;
1058   // this implies a constraint we would not honor.
1059   std::set<std::string> OperandNames;
1060   for (const AsmOperand &Op : AsmOperands) {
1061     StringRef Tok = Op.Token;
1062     if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
1063       PrintFatalError(TheDef->getLoc(),
1064                       "matchable with operand modifier '" + Tok +
1065                       "' not supported by asm matcher.  Mark isCodeGenOnly!");
1066 
1067     // Verify that any operand is only mentioned once.
1068     // We reject aliases and ignore instructions for now.
1069     if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
1070       if (!Hack)
1071         PrintFatalError(TheDef->getLoc(),
1072                         "ERROR: matchable with tied operand '" + Tok +
1073                         "' can never be matched!");
1074       // FIXME: Should reject these.  The ARM backend hits this with $lane in a
1075       // bunch of instructions.  It is unclear what the right answer is.
1076       DEBUG({
1077         errs() << "warning: '" << TheDef->getName() << "': "
1078                << "ignoring instruction with tied operand '"
1079                << Tok << "'\n";
1080       });
1081       return false;
1082     }
1083   }
1084 
1085   return true;
1086 }
1087 
1088 static std::string getEnumNameForToken(StringRef Str) {
1089   std::string Res;
1090 
1091   for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
1092     switch (*it) {
1093     case '*': Res += "_STAR_"; break;
1094     case '%': Res += "_PCT_"; break;
1095     case ':': Res += "_COLON_"; break;
1096     case '!': Res += "_EXCLAIM_"; break;
1097     case '.': Res += "_DOT_"; break;
1098     case '<': Res += "_LT_"; break;
1099     case '>': Res += "_GT_"; break;
1100     case '-': Res += "_MINUS_"; break;
1101     default:
1102       if ((*it >= 'A' && *it <= 'Z') ||
1103           (*it >= 'a' && *it <= 'z') ||
1104           (*it >= '0' && *it <= '9'))
1105         Res += *it;
1106       else
1107         Res += "_" + utostr((unsigned) *it) + "_";
1108     }
1109   }
1110 
1111   return Res;
1112 }
1113 
1114 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
1115   ClassInfo *&Entry = TokenClasses[Token];
1116 
1117   if (!Entry) {
1118     Classes.emplace_front();
1119     Entry = &Classes.front();
1120     Entry->Kind = ClassInfo::Token;
1121     Entry->ClassName = "Token";
1122     Entry->Name = "MCK_" + getEnumNameForToken(Token);
1123     Entry->ValueName = Token;
1124     Entry->PredicateMethod = "<invalid>";
1125     Entry->RenderMethod = "<invalid>";
1126     Entry->ParserMethod = "";
1127     Entry->DiagnosticType = "";
1128     Entry->IsOptional = false;
1129     Entry->DefaultMethod = "<invalid>";
1130   }
1131 
1132   return Entry;
1133 }
1134 
1135 ClassInfo *
1136 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
1137                                 int SubOpIdx) {
1138   Record *Rec = OI.Rec;
1139   if (SubOpIdx != -1)
1140     Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
1141   return getOperandClass(Rec, SubOpIdx);
1142 }
1143 
1144 ClassInfo *
1145 AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
1146   if (Rec->isSubClassOf("RegisterOperand")) {
1147     // RegisterOperand may have an associated ParserMatchClass. If it does,
1148     // use it, else just fall back to the underlying register class.
1149     const RecordVal *R = Rec->getValue("ParserMatchClass");
1150     if (!R || !R->getValue())
1151       PrintFatalError("Record `" + Rec->getName() +
1152         "' does not have a ParserMatchClass!\n");
1153 
1154     if (DefInit *DI= dyn_cast<DefInit>(R->getValue())) {
1155       Record *MatchClass = DI->getDef();
1156       if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1157         return CI;
1158     }
1159 
1160     // No custom match class. Just use the register class.
1161     Record *ClassRec = Rec->getValueAsDef("RegClass");
1162     if (!ClassRec)
1163       PrintFatalError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
1164                     "' has no associated register class!\n");
1165     if (ClassInfo *CI = RegisterClassClasses[ClassRec])
1166       return CI;
1167     PrintFatalError(Rec->getLoc(), "register class has no class info!");
1168   }
1169 
1170   if (Rec->isSubClassOf("RegisterClass")) {
1171     if (ClassInfo *CI = RegisterClassClasses[Rec])
1172       return CI;
1173     PrintFatalError(Rec->getLoc(), "register class has no class info!");
1174   }
1175 
1176   if (!Rec->isSubClassOf("Operand"))
1177     PrintFatalError(Rec->getLoc(), "Operand `" + Rec->getName() +
1178                   "' does not derive from class Operand!\n");
1179   Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1180   if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1181     return CI;
1182 
1183   PrintFatalError(Rec->getLoc(), "operand has no match class!");
1184 }
1185 
1186 struct LessRegisterSet {
1187   bool operator() (const RegisterSet &LHS, const RegisterSet & RHS) const {
1188     // std::set<T> defines its own compariso "operator<", but it
1189     // performs a lexicographical comparison by T's innate comparison
1190     // for some reason. We don't want non-deterministic pointer
1191     // comparisons so use this instead.
1192     return std::lexicographical_compare(LHS.begin(), LHS.end(),
1193                                         RHS.begin(), RHS.end(),
1194                                         LessRecordByID());
1195   }
1196 };
1197 
1198 void AsmMatcherInfo::
1199 buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters) {
1200   const auto &Registers = Target.getRegBank().getRegisters();
1201   auto &RegClassList = Target.getRegBank().getRegClasses();
1202 
1203   typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet;
1204 
1205   // The register sets used for matching.
1206   RegisterSetSet RegisterSets;
1207 
1208   // Gather the defined sets.
1209   for (const CodeGenRegisterClass &RC : RegClassList)
1210     RegisterSets.insert(
1211         RegisterSet(RC.getOrder().begin(), RC.getOrder().end()));
1212 
1213   // Add any required singleton sets.
1214   for (Record *Rec : SingletonRegisters) {
1215     RegisterSets.insert(RegisterSet(&Rec, &Rec + 1));
1216   }
1217 
1218   // Introduce derived sets where necessary (when a register does not determine
1219   // a unique register set class), and build the mapping of registers to the set
1220   // they should classify to.
1221   std::map<Record*, RegisterSet> RegisterMap;
1222   for (const CodeGenRegister &CGR : Registers) {
1223     // Compute the intersection of all sets containing this register.
1224     RegisterSet ContainingSet;
1225 
1226     for (const RegisterSet &RS : RegisterSets) {
1227       if (!RS.count(CGR.TheDef))
1228         continue;
1229 
1230       if (ContainingSet.empty()) {
1231         ContainingSet = RS;
1232         continue;
1233       }
1234 
1235       RegisterSet Tmp;
1236       std::swap(Tmp, ContainingSet);
1237       std::insert_iterator<RegisterSet> II(ContainingSet,
1238                                            ContainingSet.begin());
1239       std::set_intersection(Tmp.begin(), Tmp.end(), RS.begin(), RS.end(), II,
1240                             LessRecordByID());
1241     }
1242 
1243     if (!ContainingSet.empty()) {
1244       RegisterSets.insert(ContainingSet);
1245       RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
1246     }
1247   }
1248 
1249   // Construct the register classes.
1250   std::map<RegisterSet, ClassInfo*, LessRegisterSet> RegisterSetClasses;
1251   unsigned Index = 0;
1252   for (const RegisterSet &RS : RegisterSets) {
1253     Classes.emplace_front();
1254     ClassInfo *CI = &Classes.front();
1255     CI->Kind = ClassInfo::RegisterClass0 + Index;
1256     CI->ClassName = "Reg" + utostr(Index);
1257     CI->Name = "MCK_Reg" + utostr(Index);
1258     CI->ValueName = "";
1259     CI->PredicateMethod = ""; // unused
1260     CI->RenderMethod = "addRegOperands";
1261     CI->Registers = RS;
1262     // FIXME: diagnostic type.
1263     CI->DiagnosticType = "";
1264     CI->IsOptional = false;
1265     CI->DefaultMethod = ""; // unused
1266     RegisterSetClasses.insert(std::make_pair(RS, CI));
1267     ++Index;
1268   }
1269 
1270   // Find the superclasses; we could compute only the subgroup lattice edges,
1271   // but there isn't really a point.
1272   for (const RegisterSet &RS : RegisterSets) {
1273     ClassInfo *CI = RegisterSetClasses[RS];
1274     for (const RegisterSet &RS2 : RegisterSets)
1275       if (RS != RS2 &&
1276           std::includes(RS2.begin(), RS2.end(), RS.begin(), RS.end(),
1277                         LessRecordByID()))
1278         CI->SuperClasses.push_back(RegisterSetClasses[RS2]);
1279   }
1280 
1281   // Name the register classes which correspond to a user defined RegisterClass.
1282   for (const CodeGenRegisterClass &RC : RegClassList) {
1283     // Def will be NULL for non-user defined register classes.
1284     Record *Def = RC.getDef();
1285     if (!Def)
1286       continue;
1287     ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(),
1288                                                    RC.getOrder().end())];
1289     if (CI->ValueName.empty()) {
1290       CI->ClassName = RC.getName();
1291       CI->Name = "MCK_" + RC.getName();
1292       CI->ValueName = RC.getName();
1293     } else
1294       CI->ValueName = CI->ValueName + "," + RC.getName();
1295 
1296     RegisterClassClasses.insert(std::make_pair(Def, CI));
1297   }
1298 
1299   // Populate the map for individual registers.
1300   for (std::map<Record*, RegisterSet>::iterator it = RegisterMap.begin(),
1301          ie = RegisterMap.end(); it != ie; ++it)
1302     RegisterClasses[it->first] = RegisterSetClasses[it->second];
1303 
1304   // Name the register classes which correspond to singleton registers.
1305   for (Record *Rec : SingletonRegisters) {
1306     ClassInfo *CI = RegisterClasses[Rec];
1307     assert(CI && "Missing singleton register class info!");
1308 
1309     if (CI->ValueName.empty()) {
1310       CI->ClassName = Rec->getName();
1311       CI->Name = "MCK_" + Rec->getName();
1312       CI->ValueName = Rec->getName();
1313     } else
1314       CI->ValueName = CI->ValueName + "," + Rec->getName();
1315   }
1316 }
1317 
1318 void AsmMatcherInfo::buildOperandClasses() {
1319   std::vector<Record*> AsmOperands =
1320     Records.getAllDerivedDefinitions("AsmOperandClass");
1321 
1322   // Pre-populate AsmOperandClasses map.
1323   for (Record *Rec : AsmOperands) {
1324     Classes.emplace_front();
1325     AsmOperandClasses[Rec] = &Classes.front();
1326   }
1327 
1328   unsigned Index = 0;
1329   for (Record *Rec : AsmOperands) {
1330     ClassInfo *CI = AsmOperandClasses[Rec];
1331     CI->Kind = ClassInfo::UserClass0 + Index;
1332 
1333     ListInit *Supers = Rec->getValueAsListInit("SuperClasses");
1334     for (Init *I : Supers->getValues()) {
1335       DefInit *DI = dyn_cast<DefInit>(I);
1336       if (!DI) {
1337         PrintError(Rec->getLoc(), "Invalid super class reference!");
1338         continue;
1339       }
1340 
1341       ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1342       if (!SC)
1343         PrintError(Rec->getLoc(), "Invalid super class reference!");
1344       else
1345         CI->SuperClasses.push_back(SC);
1346     }
1347     CI->ClassName = Rec->getValueAsString("Name");
1348     CI->Name = "MCK_" + CI->ClassName;
1349     CI->ValueName = Rec->getName();
1350 
1351     // Get or construct the predicate method name.
1352     Init *PMName = Rec->getValueInit("PredicateMethod");
1353     if (StringInit *SI = dyn_cast<StringInit>(PMName)) {
1354       CI->PredicateMethod = SI->getValue();
1355     } else {
1356       assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!");
1357       CI->PredicateMethod = "is" + CI->ClassName;
1358     }
1359 
1360     // Get or construct the render method name.
1361     Init *RMName = Rec->getValueInit("RenderMethod");
1362     if (StringInit *SI = dyn_cast<StringInit>(RMName)) {
1363       CI->RenderMethod = SI->getValue();
1364     } else {
1365       assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!");
1366       CI->RenderMethod = "add" + CI->ClassName + "Operands";
1367     }
1368 
1369     // Get the parse method name or leave it as empty.
1370     Init *PRMName = Rec->getValueInit("ParserMethod");
1371     if (StringInit *SI = dyn_cast<StringInit>(PRMName))
1372       CI->ParserMethod = SI->getValue();
1373 
1374     // Get the diagnostic type or leave it as empty.
1375     // Get the parse method name or leave it as empty.
1376     Init *DiagnosticType = Rec->getValueInit("DiagnosticType");
1377     if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
1378       CI->DiagnosticType = SI->getValue();
1379 
1380     Init *IsOptional = Rec->getValueInit("IsOptional");
1381     if (BitInit *BI = dyn_cast<BitInit>(IsOptional))
1382       CI->IsOptional = BI->getValue();
1383 
1384     // Get or construct the default method name.
1385     Init *DMName = Rec->getValueInit("DefaultMethod");
1386     if (StringInit *SI = dyn_cast<StringInit>(DMName)) {
1387       CI->DefaultMethod = SI->getValue();
1388     } else {
1389       assert(isa<UnsetInit>(DMName) && "Unexpected DefaultMethod field!");
1390       CI->DefaultMethod = "default" + CI->ClassName + "Operands";
1391     }
1392 
1393     ++Index;
1394   }
1395 }
1396 
1397 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1398                                CodeGenTarget &target,
1399                                RecordKeeper &records)
1400   : Records(records), AsmParser(asmParser), Target(target) {
1401 }
1402 
1403 /// buildOperandMatchInfo - Build the necessary information to handle user
1404 /// defined operand parsing methods.
1405 void AsmMatcherInfo::buildOperandMatchInfo() {
1406 
1407   /// Map containing a mask with all operands indices that can be found for
1408   /// that class inside a instruction.
1409   typedef std::map<ClassInfo *, unsigned, less_ptr<ClassInfo>> OpClassMaskTy;
1410   OpClassMaskTy OpClassMask;
1411 
1412   for (const auto &MI : Matchables) {
1413     OpClassMask.clear();
1414 
1415     // Keep track of all operands of this instructions which belong to the
1416     // same class.
1417     for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
1418       const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
1419       if (Op.Class->ParserMethod.empty())
1420         continue;
1421       unsigned &OperandMask = OpClassMask[Op.Class];
1422       OperandMask |= (1 << i);
1423     }
1424 
1425     // Generate operand match info for each mnemonic/operand class pair.
1426     for (const auto &OCM : OpClassMask) {
1427       unsigned OpMask = OCM.second;
1428       ClassInfo *CI = OCM.first;
1429       OperandMatchInfo.push_back(OperandMatchEntry::create(MI.get(), CI,
1430                                                            OpMask));
1431     }
1432   }
1433 }
1434 
1435 void AsmMatcherInfo::buildInfo() {
1436   // Build information about all of the AssemblerPredicates.
1437   std::vector<Record*> AllPredicates =
1438     Records.getAllDerivedDefinitions("Predicate");
1439   for (Record *Pred : AllPredicates) {
1440     // Ignore predicates that are not intended for the assembler.
1441     if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
1442       continue;
1443 
1444     if (Pred->getName().empty())
1445       PrintFatalError(Pred->getLoc(), "Predicate has no name!");
1446 
1447     SubtargetFeatures.insert(std::make_pair(
1448         Pred, SubtargetFeatureInfo(Pred, SubtargetFeatures.size())));
1449     DEBUG(SubtargetFeatures.find(Pred)->second.dump());
1450     assert(SubtargetFeatures.size() <= 64 && "Too many subtarget features!");
1451   }
1452 
1453   bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
1454 
1455   // Parse the instructions; we need to do this first so that we can gather the
1456   // singleton register classes.
1457   SmallPtrSet<Record*, 16> SingletonRegisters;
1458   unsigned VariantCount = Target.getAsmParserVariantCount();
1459   for (unsigned VC = 0; VC != VariantCount; ++VC) {
1460     Record *AsmVariant = Target.getAsmParserVariant(VC);
1461     std::string CommentDelimiter =
1462       AsmVariant->getValueAsString("CommentDelimiter");
1463     AsmVariantInfo Variant;
1464     Variant.RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
1465     Variant.TokenizingCharacters =
1466         AsmVariant->getValueAsString("TokenizingCharacters");
1467     Variant.SeparatorCharacters =
1468         AsmVariant->getValueAsString("SeparatorCharacters");
1469     Variant.BreakCharacters =
1470         AsmVariant->getValueAsString("BreakCharacters");
1471     Variant.AsmVariantNo = AsmVariant->getValueAsInt("Variant");
1472 
1473     for (const CodeGenInstruction *CGI : Target.getInstructionsByEnumValue()) {
1474 
1475       // If the tblgen -match-prefix option is specified (for tblgen hackers),
1476       // filter the set of instructions we consider.
1477       if (!StringRef(CGI->TheDef->getName()).startswith(MatchPrefix))
1478         continue;
1479 
1480       // Ignore "codegen only" instructions.
1481       if (CGI->TheDef->getValueAsBit("isCodeGenOnly"))
1482         continue;
1483 
1484       auto II = llvm::make_unique<MatchableInfo>(*CGI);
1485 
1486       II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
1487 
1488       // Ignore instructions which shouldn't be matched and diagnose invalid
1489       // instruction definitions with an error.
1490       if (!II->validate(CommentDelimiter, true))
1491         continue;
1492 
1493       Matchables.push_back(std::move(II));
1494     }
1495 
1496     // Parse all of the InstAlias definitions and stick them in the list of
1497     // matchables.
1498     std::vector<Record*> AllInstAliases =
1499       Records.getAllDerivedDefinitions("InstAlias");
1500     for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
1501       auto Alias = llvm::make_unique<CodeGenInstAlias>(AllInstAliases[i],
1502                                                        Variant.AsmVariantNo,
1503                                                        Target);
1504 
1505       // If the tblgen -match-prefix option is specified (for tblgen hackers),
1506       // filter the set of instruction aliases we consider, based on the target
1507       // instruction.
1508       if (!StringRef(Alias->ResultInst->TheDef->getName())
1509             .startswith( MatchPrefix))
1510         continue;
1511 
1512       auto II = llvm::make_unique<MatchableInfo>(std::move(Alias));
1513 
1514       II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
1515 
1516       // Validate the alias definitions.
1517       II->validate(CommentDelimiter, false);
1518 
1519       Matchables.push_back(std::move(II));
1520     }
1521   }
1522 
1523   // Build info for the register classes.
1524   buildRegisterClasses(SingletonRegisters);
1525 
1526   // Build info for the user defined assembly operand classes.
1527   buildOperandClasses();
1528 
1529   // Build the information about matchables, now that we have fully formed
1530   // classes.
1531   std::vector<std::unique_ptr<MatchableInfo>> NewMatchables;
1532   for (auto &II : Matchables) {
1533     // Parse the tokens after the mnemonic.
1534     // Note: buildInstructionOperandReference may insert new AsmOperands, so
1535     // don't precompute the loop bound.
1536     for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1537       MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
1538       StringRef Token = Op.Token;
1539 
1540       // Check for singleton registers.
1541       if (Record *RegRecord = Op.SingletonReg) {
1542         Op.Class = RegisterClasses[RegRecord];
1543         assert(Op.Class && Op.Class->Registers.size() == 1 &&
1544                "Unexpected class for singleton register");
1545         continue;
1546       }
1547 
1548       // Check for simple tokens.
1549       if (Token[0] != '$') {
1550         Op.Class = getTokenClass(Token);
1551         continue;
1552       }
1553 
1554       if (Token.size() > 1 && isdigit(Token[1])) {
1555         Op.Class = getTokenClass(Token);
1556         continue;
1557       }
1558 
1559       // Otherwise this is an operand reference.
1560       StringRef OperandName;
1561       if (Token[1] == '{')
1562         OperandName = Token.substr(2, Token.size() - 3);
1563       else
1564         OperandName = Token.substr(1);
1565 
1566       if (II->DefRec.is<const CodeGenInstruction*>())
1567         buildInstructionOperandReference(II.get(), OperandName, i);
1568       else
1569         buildAliasOperandReference(II.get(), OperandName, Op);
1570     }
1571 
1572     if (II->DefRec.is<const CodeGenInstruction*>()) {
1573       II->buildInstructionResultOperands();
1574       // If the instruction has a two-operand alias, build up the
1575       // matchable here. We'll add them in bulk at the end to avoid
1576       // confusing this loop.
1577       std::string Constraint =
1578         II->TheDef->getValueAsString("TwoOperandAliasConstraint");
1579       if (Constraint != "") {
1580         // Start by making a copy of the original matchable.
1581         auto AliasII = llvm::make_unique<MatchableInfo>(*II);
1582 
1583         // Adjust it to be a two-operand alias.
1584         AliasII->formTwoOperandAlias(Constraint);
1585 
1586         // Add the alias to the matchables list.
1587         NewMatchables.push_back(std::move(AliasII));
1588       }
1589     } else
1590       II->buildAliasResultOperands();
1591   }
1592   if (!NewMatchables.empty())
1593     Matchables.insert(Matchables.end(),
1594                       std::make_move_iterator(NewMatchables.begin()),
1595                       std::make_move_iterator(NewMatchables.end()));
1596 
1597   // Process token alias definitions and set up the associated superclass
1598   // information.
1599   std::vector<Record*> AllTokenAliases =
1600     Records.getAllDerivedDefinitions("TokenAlias");
1601   for (Record *Rec : AllTokenAliases) {
1602     ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1603     ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
1604     if (FromClass == ToClass)
1605       PrintFatalError(Rec->getLoc(),
1606                     "error: Destination value identical to source value.");
1607     FromClass->SuperClasses.push_back(ToClass);
1608   }
1609 
1610   // Reorder classes so that classes precede super classes.
1611   Classes.sort();
1612 
1613 #ifndef NDEBUG
1614   // Verify that the table is now sorted
1615   for (auto I = Classes.begin(), E = Classes.end(); I != E; ++I) {
1616     for (auto J = I; J != E; ++J) {
1617       assert(!(*J < *I));
1618       assert(I == J || !J->isSubsetOf(*I));
1619     }
1620   }
1621 #endif // NDEBUG
1622 }
1623 
1624 /// buildInstructionOperandReference - The specified operand is a reference to a
1625 /// named operand such as $src.  Resolve the Class and OperandInfo pointers.
1626 void AsmMatcherInfo::
1627 buildInstructionOperandReference(MatchableInfo *II,
1628                                  StringRef OperandName,
1629                                  unsigned AsmOpIdx) {
1630   const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1631   const CGIOperandList &Operands = CGI.Operands;
1632   MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
1633 
1634   // Map this token to an operand.
1635   unsigned Idx;
1636   if (!Operands.hasOperandNamed(OperandName, Idx))
1637     PrintFatalError(II->TheDef->getLoc(),
1638                     "error: unable to find operand: '" + OperandName + "'");
1639 
1640   // If the instruction operand has multiple suboperands, but the parser
1641   // match class for the asm operand is still the default "ImmAsmOperand",
1642   // then handle each suboperand separately.
1643   if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1644     Record *Rec = Operands[Idx].Rec;
1645     assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1646     Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1647     if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1648       // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1649       StringRef Token = Op->Token; // save this in case Op gets moved
1650       for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1651         MatchableInfo::AsmOperand NewAsmOp(/*IsIsolatedToken=*/true, Token);
1652         NewAsmOp.SubOpIdx = SI;
1653         II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1654       }
1655       // Replace Op with first suboperand.
1656       Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1657       Op->SubOpIdx = 0;
1658     }
1659   }
1660 
1661   // Set up the operand class.
1662   Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
1663 
1664   // If the named operand is tied, canonicalize it to the untied operand.
1665   // For example, something like:
1666   //   (outs GPR:$dst), (ins GPR:$src)
1667   // with an asmstring of
1668   //   "inc $src"
1669   // we want to canonicalize to:
1670   //   "inc $dst"
1671   // so that we know how to provide the $dst operand when filling in the result.
1672   int OITied = -1;
1673   if (Operands[Idx].MINumOperands == 1)
1674     OITied = Operands[Idx].getTiedRegister();
1675   if (OITied != -1) {
1676     // The tied operand index is an MIOperand index, find the operand that
1677     // contains it.
1678     std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1679     OperandName = Operands[Idx.first].Name;
1680     Op->SubOpIdx = Idx.second;
1681   }
1682 
1683   Op->SrcOpName = OperandName;
1684 }
1685 
1686 /// buildAliasOperandReference - When parsing an operand reference out of the
1687 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1688 /// operand reference is by looking it up in the result pattern definition.
1689 void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
1690                                                 StringRef OperandName,
1691                                                 MatchableInfo::AsmOperand &Op) {
1692   const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
1693 
1694   // Set up the operand class.
1695   for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
1696     if (CGA.ResultOperands[i].isRecord() &&
1697         CGA.ResultOperands[i].getName() == OperandName) {
1698       // It's safe to go with the first one we find, because CodeGenInstAlias
1699       // validates that all operands with the same name have the same record.
1700       Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
1701       // Use the match class from the Alias definition, not the
1702       // destination instruction, as we may have an immediate that's
1703       // being munged by the match class.
1704       Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
1705                                  Op.SubOpIdx);
1706       Op.SrcOpName = OperandName;
1707       return;
1708     }
1709 
1710   PrintFatalError(II->TheDef->getLoc(),
1711                   "error: unable to find operand: '" + OperandName + "'");
1712 }
1713 
1714 void MatchableInfo::buildInstructionResultOperands() {
1715   const CodeGenInstruction *ResultInst = getResultInst();
1716 
1717   // Loop over all operands of the result instruction, determining how to
1718   // populate them.
1719   for (const CGIOperandList::OperandInfo &OpInfo : ResultInst->Operands) {
1720     // If this is a tied operand, just copy from the previously handled operand.
1721     int TiedOp = -1;
1722     if (OpInfo.MINumOperands == 1)
1723       TiedOp = OpInfo.getTiedRegister();
1724     if (TiedOp != -1) {
1725       ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1726       continue;
1727     }
1728 
1729     // Find out what operand from the asmparser this MCInst operand comes from.
1730     int SrcOperand = findAsmOperandNamed(OpInfo.Name);
1731     if (OpInfo.Name.empty() || SrcOperand == -1) {
1732       // This may happen for operands that are tied to a suboperand of a
1733       // complex operand.  Simply use a dummy value here; nobody should
1734       // use this operand slot.
1735       // FIXME: The long term goal is for the MCOperand list to not contain
1736       // tied operands at all.
1737       ResOperands.push_back(ResOperand::getImmOp(0));
1738       continue;
1739     }
1740 
1741     // Check if the one AsmOperand populates the entire operand.
1742     unsigned NumOperands = OpInfo.MINumOperands;
1743     if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1744       ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
1745       continue;
1746     }
1747 
1748     // Add a separate ResOperand for each suboperand.
1749     for (unsigned AI = 0; AI < NumOperands; ++AI) {
1750       assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1751              AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1752              "unexpected AsmOperands for suboperands");
1753       ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1754     }
1755   }
1756 }
1757 
1758 void MatchableInfo::buildAliasResultOperands() {
1759   const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1760   const CodeGenInstruction *ResultInst = getResultInst();
1761 
1762   // Loop over all operands of the result instruction, determining how to
1763   // populate them.
1764   unsigned AliasOpNo = 0;
1765   unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
1766   for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1767     const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
1768 
1769     // If this is a tied operand, just copy from the previously handled operand.
1770     int TiedOp = -1;
1771     if (OpInfo->MINumOperands == 1)
1772       TiedOp = OpInfo->getTiedRegister();
1773     if (TiedOp != -1) {
1774       ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1775       continue;
1776     }
1777 
1778     // Handle all the suboperands for this operand.
1779     const std::string &OpName = OpInfo->Name;
1780     for ( ; AliasOpNo <  LastOpNo &&
1781             CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1782       int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1783 
1784       // Find out what operand from the asmparser that this MCInst operand
1785       // comes from.
1786       switch (CGA.ResultOperands[AliasOpNo].Kind) {
1787       case CodeGenInstAlias::ResultOperand::K_Record: {
1788         StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1789         int SrcOperand = findAsmOperand(Name, SubIdx);
1790         if (SrcOperand == -1)
1791           PrintFatalError(TheDef->getLoc(), "Instruction '" +
1792                         TheDef->getName() + "' has operand '" + OpName +
1793                         "' that doesn't appear in asm string!");
1794         unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1795         ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1796                                                         NumOperands));
1797         break;
1798       }
1799       case CodeGenInstAlias::ResultOperand::K_Imm: {
1800         int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1801         ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1802         break;
1803       }
1804       case CodeGenInstAlias::ResultOperand::K_Reg: {
1805         Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1806         ResOperands.push_back(ResOperand::getRegOp(Reg));
1807         break;
1808       }
1809       }
1810     }
1811   }
1812 }
1813 
1814 static unsigned getConverterOperandID(const std::string &Name,
1815                                       SmallSetVector<std::string, 16> &Table,
1816                                       bool &IsNew) {
1817   IsNew = Table.insert(Name);
1818 
1819   unsigned ID = IsNew ? Table.size() - 1 : find(Table, Name) - Table.begin();
1820 
1821   assert(ID < Table.size());
1822 
1823   return ID;
1824 }
1825 
1826 static void emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName,
1827                              std::vector<std::unique_ptr<MatchableInfo>> &Infos,
1828                              bool HasMnemonicFirst, bool HasOptionalOperands,
1829                              raw_ostream &OS) {
1830   SmallSetVector<std::string, 16> OperandConversionKinds;
1831   SmallSetVector<std::string, 16> InstructionConversionKinds;
1832   std::vector<std::vector<uint8_t> > ConversionTable;
1833   size_t MaxRowLength = 2; // minimum is custom converter plus terminator.
1834 
1835   // TargetOperandClass - This is the target's operand class, like X86Operand.
1836   std::string TargetOperandClass = Target.getName() + "Operand";
1837 
1838   // Write the convert function to a separate stream, so we can drop it after
1839   // the enum. We'll build up the conversion handlers for the individual
1840   // operand types opportunistically as we encounter them.
1841   std::string ConvertFnBody;
1842   raw_string_ostream CvtOS(ConvertFnBody);
1843   // Start the unified conversion function.
1844   if (HasOptionalOperands) {
1845     CvtOS << "void " << Target.getName() << ClassName << "::\n"
1846           << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1847           << "unsigned Opcode,\n"
1848           << "                const OperandVector &Operands,\n"
1849           << "                const SmallBitVector &OptionalOperandsMask) {\n";
1850   } else {
1851     CvtOS << "void " << Target.getName() << ClassName << "::\n"
1852           << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1853           << "unsigned Opcode,\n"
1854           << "                const OperandVector &Operands) {\n";
1855   }
1856   CvtOS << "  assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
1857   CvtOS << "  const uint8_t *Converter = ConversionTable[Kind];\n";
1858   if (HasOptionalOperands) {
1859     CvtOS << "  unsigned NumDefaults = 0;\n";
1860   }
1861   CvtOS << "  unsigned OpIdx;\n";
1862   CvtOS << "  Inst.setOpcode(Opcode);\n";
1863   CvtOS << "  for (const uint8_t *p = Converter; *p; p+= 2) {\n";
1864   if (HasOptionalOperands) {
1865     CvtOS << "    OpIdx = *(p + 1) - NumDefaults;\n";
1866   } else {
1867     CvtOS << "    OpIdx = *(p + 1);\n";
1868   }
1869   CvtOS << "    switch (*p) {\n";
1870   CvtOS << "    default: llvm_unreachable(\"invalid conversion entry!\");\n";
1871   CvtOS << "    case CVT_Reg:\n";
1872   CvtOS << "      static_cast<" << TargetOperandClass
1873         << "&>(*Operands[OpIdx]).addRegOperands(Inst, 1);\n";
1874   CvtOS << "      break;\n";
1875   CvtOS << "    case CVT_Tied:\n";
1876   CvtOS << "      Inst.addOperand(Inst.getOperand(OpIdx));\n";
1877   CvtOS << "      break;\n";
1878 
1879   std::string OperandFnBody;
1880   raw_string_ostream OpOS(OperandFnBody);
1881   // Start the operand number lookup function.
1882   OpOS << "void " << Target.getName() << ClassName << "::\n"
1883        << "convertToMapAndConstraints(unsigned Kind,\n";
1884   OpOS.indent(27);
1885   OpOS << "const OperandVector &Operands) {\n"
1886        << "  assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
1887        << "  unsigned NumMCOperands = 0;\n"
1888        << "  const uint8_t *Converter = ConversionTable[Kind];\n"
1889        << "  for (const uint8_t *p = Converter; *p; p+= 2) {\n"
1890        << "    switch (*p) {\n"
1891        << "    default: llvm_unreachable(\"invalid conversion entry!\");\n"
1892        << "    case CVT_Reg:\n"
1893        << "      Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
1894        << "      Operands[*(p + 1)]->setConstraint(\"r\");\n"
1895        << "      ++NumMCOperands;\n"
1896        << "      break;\n"
1897        << "    case CVT_Tied:\n"
1898        << "      ++NumMCOperands;\n"
1899        << "      break;\n";
1900 
1901   // Pre-populate the operand conversion kinds with the standard always
1902   // available entries.
1903   OperandConversionKinds.insert("CVT_Done");
1904   OperandConversionKinds.insert("CVT_Reg");
1905   OperandConversionKinds.insert("CVT_Tied");
1906   enum { CVT_Done, CVT_Reg, CVT_Tied };
1907 
1908   for (auto &II : Infos) {
1909     // Check if we have a custom match function.
1910     std::string AsmMatchConverter =
1911       II->getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
1912     if (!AsmMatchConverter.empty() && II->UseInstAsmMatchConverter) {
1913       std::string Signature = "ConvertCustom_" + AsmMatchConverter;
1914       II->ConversionFnKind = Signature;
1915 
1916       // Check if we have already generated this signature.
1917       if (!InstructionConversionKinds.insert(Signature))
1918         continue;
1919 
1920       // Remember this converter for the kind enum.
1921       unsigned KindID = OperandConversionKinds.size();
1922       OperandConversionKinds.insert("CVT_" +
1923                                     getEnumNameForToken(AsmMatchConverter));
1924 
1925       // Add the converter row for this instruction.
1926       ConversionTable.emplace_back();
1927       ConversionTable.back().push_back(KindID);
1928       ConversionTable.back().push_back(CVT_Done);
1929 
1930       // Add the handler to the conversion driver function.
1931       CvtOS << "    case CVT_"
1932             << getEnumNameForToken(AsmMatchConverter) << ":\n"
1933             << "      " << AsmMatchConverter << "(Inst, Operands);\n"
1934             << "      break;\n";
1935 
1936       // FIXME: Handle the operand number lookup for custom match functions.
1937       continue;
1938     }
1939 
1940     // Build the conversion function signature.
1941     std::string Signature = "Convert";
1942 
1943     std::vector<uint8_t> ConversionRow;
1944 
1945     // Compute the convert enum and the case body.
1946     MaxRowLength = std::max(MaxRowLength, II->ResOperands.size()*2 + 1 );
1947 
1948     for (unsigned i = 0, e = II->ResOperands.size(); i != e; ++i) {
1949       const MatchableInfo::ResOperand &OpInfo = II->ResOperands[i];
1950 
1951       // Generate code to populate each result operand.
1952       switch (OpInfo.Kind) {
1953       case MatchableInfo::ResOperand::RenderAsmOperand: {
1954         // This comes from something we parsed.
1955         const MatchableInfo::AsmOperand &Op =
1956           II->AsmOperands[OpInfo.AsmOperandNum];
1957 
1958         // Registers are always converted the same, don't duplicate the
1959         // conversion function based on them.
1960         Signature += "__";
1961         std::string Class;
1962         Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName;
1963         Signature += Class;
1964         Signature += utostr(OpInfo.MINumOperands);
1965         Signature += "_" + itostr(OpInfo.AsmOperandNum);
1966 
1967         // Add the conversion kind, if necessary, and get the associated ID
1968         // the index of its entry in the vector).
1969         std::string Name = "CVT_" + (Op.Class->isRegisterClass() ? "Reg" :
1970                                      Op.Class->RenderMethod);
1971         if (Op.Class->IsOptional) {
1972           // For optional operands we must also care about DefaultMethod
1973           assert(HasOptionalOperands);
1974           Name += "_" + Op.Class->DefaultMethod;
1975         }
1976         Name = getEnumNameForToken(Name);
1977 
1978         bool IsNewConverter = false;
1979         unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
1980                                             IsNewConverter);
1981 
1982         // Add the operand entry to the instruction kind conversion row.
1983         ConversionRow.push_back(ID);
1984         ConversionRow.push_back(OpInfo.AsmOperandNum + HasMnemonicFirst);
1985 
1986         if (!IsNewConverter)
1987           break;
1988 
1989         // This is a new operand kind. Add a handler for it to the
1990         // converter driver.
1991         CvtOS << "    case " << Name << ":\n";
1992         if (Op.Class->IsOptional) {
1993           // If optional operand is not present in actual instruction then we
1994           // should call its DefaultMethod before RenderMethod
1995           assert(HasOptionalOperands);
1996           CvtOS << "      if (OptionalOperandsMask[*(p + 1) - 1]) {\n"
1997                 << "        " << Op.Class->DefaultMethod << "()"
1998                 << "->" << Op.Class->RenderMethod << "(Inst, "
1999                 << OpInfo.MINumOperands << ");\n"
2000                 << "        ++NumDefaults;\n"
2001                 << "      } else {\n"
2002                 << "        static_cast<" << TargetOperandClass
2003                 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod
2004                 << "(Inst, " << OpInfo.MINumOperands << ");\n"
2005                 << "      }\n";
2006         } else {
2007           CvtOS << "      static_cast<" << TargetOperandClass
2008                 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod
2009                 << "(Inst, " << OpInfo.MINumOperands << ");\n";
2010         }
2011         CvtOS << "      break;\n";
2012 
2013         // Add a handler for the operand number lookup.
2014         OpOS << "    case " << Name << ":\n"
2015              << "      Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n";
2016 
2017         if (Op.Class->isRegisterClass())
2018           OpOS << "      Operands[*(p + 1)]->setConstraint(\"r\");\n";
2019         else
2020           OpOS << "      Operands[*(p + 1)]->setConstraint(\"m\");\n";
2021         OpOS << "      NumMCOperands += " << OpInfo.MINumOperands << ";\n"
2022              << "      break;\n";
2023         break;
2024       }
2025       case MatchableInfo::ResOperand::TiedOperand: {
2026         // If this operand is tied to a previous one, just copy the MCInst
2027         // operand from the earlier one.We can only tie single MCOperand values.
2028         assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
2029         unsigned TiedOp = OpInfo.TiedOperandNum;
2030         assert(i > TiedOp && "Tied operand precedes its target!");
2031         Signature += "__Tie" + utostr(TiedOp);
2032         ConversionRow.push_back(CVT_Tied);
2033         ConversionRow.push_back(TiedOp);
2034         break;
2035       }
2036       case MatchableInfo::ResOperand::ImmOperand: {
2037         int64_t Val = OpInfo.ImmVal;
2038         std::string Ty = "imm_" + itostr(Val);
2039         Ty = getEnumNameForToken(Ty);
2040         Signature += "__" + Ty;
2041 
2042         std::string Name = "CVT_" + Ty;
2043         bool IsNewConverter = false;
2044         unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2045                                             IsNewConverter);
2046         // Add the operand entry to the instruction kind conversion row.
2047         ConversionRow.push_back(ID);
2048         ConversionRow.push_back(0);
2049 
2050         if (!IsNewConverter)
2051           break;
2052 
2053         CvtOS << "    case " << Name << ":\n"
2054               << "      Inst.addOperand(MCOperand::createImm(" << Val << "));\n"
2055               << "      break;\n";
2056 
2057         OpOS << "    case " << Name << ":\n"
2058              << "      Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2059              << "      Operands[*(p + 1)]->setConstraint(\"\");\n"
2060              << "      ++NumMCOperands;\n"
2061              << "      break;\n";
2062         break;
2063       }
2064       case MatchableInfo::ResOperand::RegOperand: {
2065         std::string Reg, Name;
2066         if (!OpInfo.Register) {
2067           Name = "reg0";
2068           Reg = "0";
2069         } else {
2070           Reg = getQualifiedName(OpInfo.Register);
2071           Name = "reg" + OpInfo.Register->getName();
2072         }
2073         Signature += "__" + Name;
2074         Name = "CVT_" + Name;
2075         bool IsNewConverter = false;
2076         unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2077                                             IsNewConverter);
2078         // Add the operand entry to the instruction kind conversion row.
2079         ConversionRow.push_back(ID);
2080         ConversionRow.push_back(0);
2081 
2082         if (!IsNewConverter)
2083           break;
2084         CvtOS << "    case " << Name << ":\n"
2085               << "      Inst.addOperand(MCOperand::createReg(" << Reg << "));\n"
2086               << "      break;\n";
2087 
2088         OpOS << "    case " << Name << ":\n"
2089              << "      Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2090              << "      Operands[*(p + 1)]->setConstraint(\"m\");\n"
2091              << "      ++NumMCOperands;\n"
2092              << "      break;\n";
2093       }
2094       }
2095     }
2096 
2097     // If there were no operands, add to the signature to that effect
2098     if (Signature == "Convert")
2099       Signature += "_NoOperands";
2100 
2101     II->ConversionFnKind = Signature;
2102 
2103     // Save the signature. If we already have it, don't add a new row
2104     // to the table.
2105     if (!InstructionConversionKinds.insert(Signature))
2106       continue;
2107 
2108     // Add the row to the table.
2109     ConversionTable.push_back(std::move(ConversionRow));
2110   }
2111 
2112   // Finish up the converter driver function.
2113   CvtOS << "    }\n  }\n}\n\n";
2114 
2115   // Finish up the operand number lookup function.
2116   OpOS << "    }\n  }\n}\n\n";
2117 
2118   OS << "namespace {\n";
2119 
2120   // Output the operand conversion kind enum.
2121   OS << "enum OperatorConversionKind {\n";
2122   for (const std::string &Converter : OperandConversionKinds)
2123     OS << "  " << Converter << ",\n";
2124   OS << "  CVT_NUM_CONVERTERS\n";
2125   OS << "};\n\n";
2126 
2127   // Output the instruction conversion kind enum.
2128   OS << "enum InstructionConversionKind {\n";
2129   for (const std::string &Signature : InstructionConversionKinds)
2130     OS << "  " << Signature << ",\n";
2131   OS << "  CVT_NUM_SIGNATURES\n";
2132   OS << "};\n\n";
2133 
2134   OS << "} // end anonymous namespace\n\n";
2135 
2136   // Output the conversion table.
2137   OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES]["
2138      << MaxRowLength << "] = {\n";
2139 
2140   for (unsigned Row = 0, ERow = ConversionTable.size(); Row != ERow; ++Row) {
2141     assert(ConversionTable[Row].size() % 2 == 0 && "bad conversion row!");
2142     OS << "  // " << InstructionConversionKinds[Row] << "\n";
2143     OS << "  { ";
2144     for (unsigned i = 0, e = ConversionTable[Row].size(); i != e; i += 2)
2145       OS << OperandConversionKinds[ConversionTable[Row][i]] << ", "
2146          << (unsigned)(ConversionTable[Row][i + 1]) << ", ";
2147     OS << "CVT_Done },\n";
2148   }
2149 
2150   OS << "};\n\n";
2151 
2152   // Spit out the conversion driver function.
2153   OS << CvtOS.str();
2154 
2155   // Spit out the operand number lookup function.
2156   OS << OpOS.str();
2157 }
2158 
2159 /// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
2160 static void emitMatchClassEnumeration(CodeGenTarget &Target,
2161                                       std::forward_list<ClassInfo> &Infos,
2162                                       raw_ostream &OS) {
2163   OS << "namespace {\n\n";
2164 
2165   OS << "/// MatchClassKind - The kinds of classes which participate in\n"
2166      << "/// instruction matching.\n";
2167   OS << "enum MatchClassKind {\n";
2168   OS << "  InvalidMatchClass = 0,\n";
2169   OS << "  OptionalMatchClass = 1,\n";
2170   for (const auto &CI : Infos) {
2171     OS << "  " << CI.Name << ", // ";
2172     if (CI.Kind == ClassInfo::Token) {
2173       OS << "'" << CI.ValueName << "'\n";
2174     } else if (CI.isRegisterClass()) {
2175       if (!CI.ValueName.empty())
2176         OS << "register class '" << CI.ValueName << "'\n";
2177       else
2178         OS << "derived register class\n";
2179     } else {
2180       OS << "user defined class '" << CI.ValueName << "'\n";
2181     }
2182   }
2183   OS << "  NumMatchClassKinds\n";
2184   OS << "};\n\n";
2185 
2186   OS << "}\n\n";
2187 }
2188 
2189 /// emitValidateOperandClass - Emit the function to validate an operand class.
2190 static void emitValidateOperandClass(AsmMatcherInfo &Info,
2191                                      raw_ostream &OS) {
2192   OS << "static unsigned validateOperandClass(MCParsedAsmOperand &GOp, "
2193      << "MatchClassKind Kind) {\n";
2194   OS << "  " << Info.Target.getName() << "Operand &Operand = ("
2195      << Info.Target.getName() << "Operand&)GOp;\n";
2196 
2197   // The InvalidMatchClass is not to match any operand.
2198   OS << "  if (Kind == InvalidMatchClass)\n";
2199   OS << "    return MCTargetAsmParser::Match_InvalidOperand;\n\n";
2200 
2201   // Check for Token operands first.
2202   // FIXME: Use a more specific diagnostic type.
2203   OS << "  if (Operand.isToken())\n";
2204   OS << "    return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
2205      << "             MCTargetAsmParser::Match_Success :\n"
2206      << "             MCTargetAsmParser::Match_InvalidOperand;\n\n";
2207 
2208   // Check the user classes. We don't care what order since we're only
2209   // actually matching against one of them.
2210   OS << "  switch (Kind) {\n"
2211         "  default: break;\n";
2212   for (const auto &CI : Info.Classes) {
2213     if (!CI.isUserClass())
2214       continue;
2215 
2216     OS << "  // '" << CI.ClassName << "' class\n";
2217     OS << "  case " << CI.Name << ":\n";
2218     OS << "    if (Operand." << CI.PredicateMethod << "())\n";
2219     OS << "      return MCTargetAsmParser::Match_Success;\n";
2220     if (!CI.DiagnosticType.empty())
2221       OS << "    return " << Info.Target.getName() << "AsmParser::Match_"
2222          << CI.DiagnosticType << ";\n";
2223     else
2224       OS << "    break;\n";
2225   }
2226   OS << "  } // end switch (Kind)\n\n";
2227 
2228   // Check for register operands, including sub-classes.
2229   OS << "  if (Operand.isReg()) {\n";
2230   OS << "    MatchClassKind OpKind;\n";
2231   OS << "    switch (Operand.getReg()) {\n";
2232   OS << "    default: OpKind = InvalidMatchClass; break;\n";
2233   for (const auto &RC : Info.RegisterClasses)
2234     OS << "    case " << Info.Target.getName() << "::"
2235        << RC.first->getName() << ": OpKind = " << RC.second->Name
2236        << "; break;\n";
2237   OS << "    }\n";
2238   OS << "    return isSubclass(OpKind, Kind) ? "
2239      << "MCTargetAsmParser::Match_Success :\n                             "
2240      << "         MCTargetAsmParser::Match_InvalidOperand;\n  }\n\n";
2241 
2242   // Generic fallthrough match failure case for operands that don't have
2243   // specialized diagnostic types.
2244   OS << "  return MCTargetAsmParser::Match_InvalidOperand;\n";
2245   OS << "}\n\n";
2246 }
2247 
2248 /// emitIsSubclass - Emit the subclass predicate function.
2249 static void emitIsSubclass(CodeGenTarget &Target,
2250                            std::forward_list<ClassInfo> &Infos,
2251                            raw_ostream &OS) {
2252   OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n";
2253   OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
2254   OS << "  if (A == B)\n";
2255   OS << "    return true;\n\n";
2256 
2257   bool EmittedSwitch = false;
2258   for (const auto &A : Infos) {
2259     std::vector<StringRef> SuperClasses;
2260     if (A.IsOptional)
2261       SuperClasses.push_back("OptionalMatchClass");
2262     for (const auto &B : Infos) {
2263       if (&A != &B && A.isSubsetOf(B))
2264         SuperClasses.push_back(B.Name);
2265     }
2266 
2267     if (SuperClasses.empty())
2268       continue;
2269 
2270     // If this is the first SuperClass, emit the switch header.
2271     if (!EmittedSwitch) {
2272       OS << "  switch (A) {\n";
2273       OS << "  default:\n";
2274       OS << "    return false;\n";
2275       EmittedSwitch = true;
2276     }
2277 
2278     OS << "\n  case " << A.Name << ":\n";
2279 
2280     if (SuperClasses.size() == 1) {
2281       OS << "    return B == " << SuperClasses.back() << ";\n";
2282       continue;
2283     }
2284 
2285     if (!SuperClasses.empty()) {
2286       OS << "    switch (B) {\n";
2287       OS << "    default: return false;\n";
2288       for (StringRef SC : SuperClasses)
2289         OS << "    case " << SC << ": return true;\n";
2290       OS << "    }\n";
2291     } else {
2292       // No case statement to emit
2293       OS << "    return false;\n";
2294     }
2295   }
2296 
2297   // If there were case statements emitted into the string stream write the
2298   // default.
2299   if (EmittedSwitch)
2300     OS << "  }\n";
2301   else
2302     OS << "  return false;\n";
2303 
2304   OS << "}\n\n";
2305 }
2306 
2307 /// emitMatchTokenString - Emit the function to match a token string to the
2308 /// appropriate match class value.
2309 static void emitMatchTokenString(CodeGenTarget &Target,
2310                                  std::forward_list<ClassInfo> &Infos,
2311                                  raw_ostream &OS) {
2312   // Construct the match list.
2313   std::vector<StringMatcher::StringPair> Matches;
2314   for (const auto &CI : Infos) {
2315     if (CI.Kind == ClassInfo::Token)
2316       Matches.emplace_back(CI.ValueName, "return " + CI.Name + ";");
2317   }
2318 
2319   OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
2320 
2321   StringMatcher("Name", Matches, OS).Emit();
2322 
2323   OS << "  return InvalidMatchClass;\n";
2324   OS << "}\n\n";
2325 }
2326 
2327 /// emitMatchRegisterName - Emit the function to match a string to the target
2328 /// specific register enum.
2329 static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
2330                                   raw_ostream &OS) {
2331   // Construct the match list.
2332   std::vector<StringMatcher::StringPair> Matches;
2333   const auto &Regs = Target.getRegBank().getRegisters();
2334   for (const CodeGenRegister &Reg : Regs) {
2335     if (Reg.TheDef->getValueAsString("AsmName").empty())
2336       continue;
2337 
2338     Matches.emplace_back(Reg.TheDef->getValueAsString("AsmName"),
2339                          "return " + utostr(Reg.EnumValue) + ";");
2340   }
2341 
2342   OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
2343 
2344   StringMatcher("Name", Matches, OS).Emit();
2345 
2346   OS << "  return 0;\n";
2347   OS << "}\n\n";
2348 }
2349 
2350 /// Emit the function to match a string to the target
2351 /// specific register enum.
2352 static void emitMatchRegisterAltName(CodeGenTarget &Target, Record *AsmParser,
2353                                      raw_ostream &OS) {
2354   // Construct the match list.
2355   std::vector<StringMatcher::StringPair> Matches;
2356   const auto &Regs = Target.getRegBank().getRegisters();
2357   for (const CodeGenRegister &Reg : Regs) {
2358 
2359     auto AltNames = Reg.TheDef->getValueAsListOfStrings("AltNames");
2360 
2361     for (auto AltName : AltNames) {
2362       AltName = StringRef(AltName).trim();
2363 
2364       // don't handle empty alternative names
2365       if (AltName.empty())
2366         continue;
2367 
2368       Matches.emplace_back(AltName,
2369                            "return " + utostr(Reg.EnumValue) + ";");
2370     }
2371   }
2372 
2373   OS << "static unsigned MatchRegisterAltName(StringRef Name) {\n";
2374 
2375   StringMatcher("Name", Matches, OS).Emit();
2376 
2377   OS << "  return 0;\n";
2378   OS << "}\n\n";
2379 }
2380 
2381 static const char *getMinimalTypeForRange(uint64_t Range) {
2382   assert(Range <= 0xFFFFFFFFFFFFFFFFULL && "Enum too large");
2383   if (Range > 0xFFFFFFFFULL)
2384     return "uint64_t";
2385   if (Range > 0xFFFF)
2386     return "uint32_t";
2387   if (Range > 0xFF)
2388     return "uint16_t";
2389   return "uint8_t";
2390 }
2391 
2392 static const char *getMinimalRequiredFeaturesType(const AsmMatcherInfo &Info) {
2393   uint64_t MaxIndex = Info.SubtargetFeatures.size();
2394   if (MaxIndex > 0)
2395     MaxIndex--;
2396   return getMinimalTypeForRange(1ULL << MaxIndex);
2397 }
2398 
2399 /// emitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
2400 /// definitions.
2401 static void emitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
2402                                                 raw_ostream &OS) {
2403   OS << "// Flags for subtarget features that participate in "
2404      << "instruction matching.\n";
2405   OS << "enum SubtargetFeatureFlag : " << getMinimalRequiredFeaturesType(Info)
2406      << " {\n";
2407   for (const auto &SF : Info.SubtargetFeatures) {
2408     const SubtargetFeatureInfo &SFI = SF.second;
2409     OS << "  " << SFI.getEnumName() << " = (1ULL << " << SFI.Index << "),\n";
2410   }
2411   OS << "  Feature_None = 0\n";
2412   OS << "};\n\n";
2413 }
2414 
2415 /// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
2416 static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) {
2417   // Get the set of diagnostic types from all of the operand classes.
2418   std::set<StringRef> Types;
2419   for (const auto &OpClassEntry : Info.AsmOperandClasses) {
2420     if (!OpClassEntry.second->DiagnosticType.empty())
2421       Types.insert(OpClassEntry.second->DiagnosticType);
2422   }
2423 
2424   if (Types.empty()) return;
2425 
2426   // Now emit the enum entries.
2427   for (StringRef Type : Types)
2428     OS << "  Match_" << Type << ",\n";
2429   OS << "  END_OPERAND_DIAGNOSTIC_TYPES\n";
2430 }
2431 
2432 /// emitGetSubtargetFeatureName - Emit the helper function to get the
2433 /// user-level name for a subtarget feature.
2434 static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
2435   OS << "// User-level names for subtarget features that participate in\n"
2436      << "// instruction matching.\n"
2437      << "static const char *getSubtargetFeatureName(uint64_t Val) {\n";
2438   if (!Info.SubtargetFeatures.empty()) {
2439     OS << "  switch(Val) {\n";
2440     for (const auto &SF : Info.SubtargetFeatures) {
2441       const SubtargetFeatureInfo &SFI = SF.second;
2442       // FIXME: Totally just a placeholder name to get the algorithm working.
2443       OS << "  case " << SFI.getEnumName() << ": return \""
2444          << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
2445     }
2446     OS << "  default: return \"(unknown)\";\n";
2447     OS << "  }\n";
2448   } else {
2449     // Nothing to emit, so skip the switch
2450     OS << "  return \"(unknown)\";\n";
2451   }
2452   OS << "}\n\n";
2453 }
2454 
2455 /// emitComputeAvailableFeatures - Emit the function to compute the list of
2456 /// available features given a subtarget.
2457 static void emitComputeAvailableFeatures(AsmMatcherInfo &Info,
2458                                          raw_ostream &OS) {
2459   std::string ClassName =
2460     Info.AsmParser->getValueAsString("AsmParserClassName");
2461 
2462   OS << "uint64_t " << Info.Target.getName() << ClassName << "::\n"
2463      << "ComputeAvailableFeatures(const FeatureBitset& FB) const {\n";
2464   OS << "  uint64_t Features = 0;\n";
2465   for (const auto &SF : Info.SubtargetFeatures) {
2466     const SubtargetFeatureInfo &SFI = SF.second;
2467 
2468     OS << "  if (";
2469     std::string CondStorage =
2470       SFI.TheDef->getValueAsString("AssemblerCondString");
2471     StringRef Conds = CondStorage;
2472     std::pair<StringRef,StringRef> Comma = Conds.split(',');
2473     bool First = true;
2474     do {
2475       if (!First)
2476         OS << " && ";
2477 
2478       bool Neg = false;
2479       StringRef Cond = Comma.first;
2480       if (Cond[0] == '!') {
2481         Neg = true;
2482         Cond = Cond.substr(1);
2483       }
2484 
2485       OS << "(";
2486       if (Neg)
2487         OS << "!";
2488       OS << "FB[" << Info.Target.getName() << "::" << Cond << "])";
2489 
2490       if (Comma.second.empty())
2491         break;
2492 
2493       First = false;
2494       Comma = Comma.second.split(',');
2495     } while (true);
2496 
2497     OS << ")\n";
2498     OS << "    Features |= " << SFI.getEnumName() << ";\n";
2499   }
2500   OS << "  return Features;\n";
2501   OS << "}\n\n";
2502 }
2503 
2504 static std::string GetAliasRequiredFeatures(Record *R,
2505                                             const AsmMatcherInfo &Info) {
2506   std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
2507   std::string Result;
2508   unsigned NumFeatures = 0;
2509   for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
2510     const SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
2511 
2512     if (!F)
2513       PrintFatalError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
2514                     "' is not marked as an AssemblerPredicate!");
2515 
2516     if (NumFeatures)
2517       Result += '|';
2518 
2519     Result += F->getEnumName();
2520     ++NumFeatures;
2521   }
2522 
2523   if (NumFeatures > 1)
2524     Result = '(' + Result + ')';
2525   return Result;
2526 }
2527 
2528 static void emitMnemonicAliasVariant(raw_ostream &OS,const AsmMatcherInfo &Info,
2529                                      std::vector<Record*> &Aliases,
2530                                      unsigned Indent = 0,
2531                                   StringRef AsmParserVariantName = StringRef()){
2532   // Keep track of all the aliases from a mnemonic.  Use an std::map so that the
2533   // iteration order of the map is stable.
2534   std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
2535 
2536   for (Record *R : Aliases) {
2537     // FIXME: Allow AssemblerVariantName to be a comma separated list.
2538     std::string AsmVariantName = R->getValueAsString("AsmVariantName");
2539     if (AsmVariantName != AsmParserVariantName)
2540       continue;
2541     AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
2542   }
2543   if (AliasesFromMnemonic.empty())
2544     return;
2545 
2546   // Process each alias a "from" mnemonic at a time, building the code executed
2547   // by the string remapper.
2548   std::vector<StringMatcher::StringPair> Cases;
2549   for (const auto &AliasEntry : AliasesFromMnemonic) {
2550     const std::vector<Record*> &ToVec = AliasEntry.second;
2551 
2552     // Loop through each alias and emit code that handles each case.  If there
2553     // are two instructions without predicates, emit an error.  If there is one,
2554     // emit it last.
2555     std::string MatchCode;
2556     int AliasWithNoPredicate = -1;
2557 
2558     for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
2559       Record *R = ToVec[i];
2560       std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
2561 
2562       // If this unconditionally matches, remember it for later and diagnose
2563       // duplicates.
2564       if (FeatureMask.empty()) {
2565         if (AliasWithNoPredicate != -1) {
2566           // We can't have two aliases from the same mnemonic with no predicate.
2567           PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
2568                      "two MnemonicAliases with the same 'from' mnemonic!");
2569           PrintFatalError(R->getLoc(), "this is the other MnemonicAlias.");
2570         }
2571 
2572         AliasWithNoPredicate = i;
2573         continue;
2574       }
2575       if (R->getValueAsString("ToMnemonic") == AliasEntry.first)
2576         PrintFatalError(R->getLoc(), "MnemonicAlias to the same string");
2577 
2578       if (!MatchCode.empty())
2579         MatchCode += "else ";
2580       MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
2581       MatchCode += "  Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
2582     }
2583 
2584     if (AliasWithNoPredicate != -1) {
2585       Record *R = ToVec[AliasWithNoPredicate];
2586       if (!MatchCode.empty())
2587         MatchCode += "else\n  ";
2588       MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
2589     }
2590 
2591     MatchCode += "return;";
2592 
2593     Cases.push_back(std::make_pair(AliasEntry.first, MatchCode));
2594   }
2595   StringMatcher("Mnemonic", Cases, OS).Emit(Indent);
2596 }
2597 
2598 /// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
2599 /// emit a function for them and return true, otherwise return false.
2600 static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info,
2601                                 CodeGenTarget &Target) {
2602   // Ignore aliases when match-prefix is set.
2603   if (!MatchPrefix.empty())
2604     return false;
2605 
2606   std::vector<Record*> Aliases =
2607     Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
2608   if (Aliases.empty()) return false;
2609 
2610   OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
2611     "uint64_t Features, unsigned VariantID) {\n";
2612   OS << "  switch (VariantID) {\n";
2613   unsigned VariantCount = Target.getAsmParserVariantCount();
2614   for (unsigned VC = 0; VC != VariantCount; ++VC) {
2615     Record *AsmVariant = Target.getAsmParserVariant(VC);
2616     int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant");
2617     std::string AsmParserVariantName = AsmVariant->getValueAsString("Name");
2618     OS << "    case " << AsmParserVariantNo << ":\n";
2619     emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2,
2620                              AsmParserVariantName);
2621     OS << "    break;\n";
2622   }
2623   OS << "  }\n";
2624 
2625   // Emit aliases that apply to all variants.
2626   emitMnemonicAliasVariant(OS, Info, Aliases);
2627 
2628   OS << "}\n\n";
2629 
2630   return true;
2631 }
2632 
2633 static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
2634                               const AsmMatcherInfo &Info, StringRef ClassName,
2635                               StringToOffsetTable &StringTable,
2636                               unsigned MaxMnemonicIndex, bool HasMnemonicFirst) {
2637   unsigned MaxMask = 0;
2638   for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
2639     MaxMask |= OMI.OperandMask;
2640   }
2641 
2642   // Emit the static custom operand parsing table;
2643   OS << "namespace {\n";
2644   OS << "  struct OperandMatchEntry {\n";
2645   OS << "    " << getMinimalRequiredFeaturesType(Info)
2646                << " RequiredFeatures;\n";
2647   OS << "    " << getMinimalTypeForRange(MaxMnemonicIndex)
2648                << " Mnemonic;\n";
2649   OS << "    " << getMinimalTypeForRange(std::distance(
2650                       Info.Classes.begin(), Info.Classes.end())) << " Class;\n";
2651   OS << "    " << getMinimalTypeForRange(MaxMask)
2652                << " OperandMask;\n\n";
2653   OS << "    StringRef getMnemonic() const {\n";
2654   OS << "      return StringRef(MnemonicTable + Mnemonic + 1,\n";
2655   OS << "                       MnemonicTable[Mnemonic]);\n";
2656   OS << "    }\n";
2657   OS << "  };\n\n";
2658 
2659   OS << "  // Predicate for searching for an opcode.\n";
2660   OS << "  struct LessOpcodeOperand {\n";
2661   OS << "    bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
2662   OS << "      return LHS.getMnemonic()  < RHS;\n";
2663   OS << "    }\n";
2664   OS << "    bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
2665   OS << "      return LHS < RHS.getMnemonic();\n";
2666   OS << "    }\n";
2667   OS << "    bool operator()(const OperandMatchEntry &LHS,";
2668   OS << " const OperandMatchEntry &RHS) {\n";
2669   OS << "      return LHS.getMnemonic() < RHS.getMnemonic();\n";
2670   OS << "    }\n";
2671   OS << "  };\n";
2672 
2673   OS << "} // end anonymous namespace.\n\n";
2674 
2675   OS << "static const OperandMatchEntry OperandMatchTable["
2676      << Info.OperandMatchInfo.size() << "] = {\n";
2677 
2678   OS << "  /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
2679   for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
2680     const MatchableInfo &II = *OMI.MI;
2681 
2682     OS << "  { ";
2683 
2684     // Write the required features mask.
2685     if (!II.RequiredFeatures.empty()) {
2686       for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2687         if (i) OS << "|";
2688         OS << II.RequiredFeatures[i]->getEnumName();
2689       }
2690     } else
2691       OS << "0";
2692 
2693     // Store a pascal-style length byte in the mnemonic.
2694     std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2695     OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2696        << " /* " << II.Mnemonic << " */, ";
2697 
2698     OS << OMI.CI->Name;
2699 
2700     OS << ", " << OMI.OperandMask;
2701     OS << " /* ";
2702     bool printComma = false;
2703     for (int i = 0, e = 31; i !=e; ++i)
2704       if (OMI.OperandMask & (1 << i)) {
2705         if (printComma)
2706           OS << ", ";
2707         OS << i;
2708         printComma = true;
2709       }
2710     OS << " */";
2711 
2712     OS << " },\n";
2713   }
2714   OS << "};\n\n";
2715 
2716   // Emit the operand class switch to call the correct custom parser for
2717   // the found operand class.
2718   OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2719      << Target.getName() << ClassName << "::\n"
2720      << "tryCustomParseOperand(OperandVector"
2721      << " &Operands,\n                      unsigned MCK) {\n\n"
2722      << "  switch(MCK) {\n";
2723 
2724   for (const auto &CI : Info.Classes) {
2725     if (CI.ParserMethod.empty())
2726       continue;
2727     OS << "  case " << CI.Name << ":\n"
2728        << "    return " << CI.ParserMethod << "(Operands);\n";
2729   }
2730 
2731   OS << "  default:\n";
2732   OS << "    return MatchOperand_NoMatch;\n";
2733   OS << "  }\n";
2734   OS << "  return MatchOperand_NoMatch;\n";
2735   OS << "}\n\n";
2736 
2737   // Emit the static custom operand parser. This code is very similar with
2738   // the other matcher. Also use MatchResultTy here just in case we go for
2739   // a better error handling.
2740   OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2741      << Target.getName() << ClassName << "::\n"
2742      << "MatchOperandParserImpl(OperandVector"
2743      << " &Operands,\n                       StringRef Mnemonic) {\n";
2744 
2745   // Emit code to get the available features.
2746   OS << "  // Get the current feature set.\n";
2747   OS << "  uint64_t AvailableFeatures = getAvailableFeatures();\n\n";
2748 
2749   OS << "  // Get the next operand index.\n";
2750   OS << "  unsigned NextOpNum = Operands.size()"
2751      << (HasMnemonicFirst ? " - 1" : "") << ";\n";
2752 
2753   // Emit code to search the table.
2754   OS << "  // Search the table.\n";
2755   if (HasMnemonicFirst) {
2756     OS << "  auto MnemonicRange =\n";
2757     OS << "    std::equal_range(std::begin(OperandMatchTable), "
2758           "std::end(OperandMatchTable),\n";
2759     OS << "                     Mnemonic, LessOpcodeOperand());\n\n";
2760   } else {
2761     OS << "  auto MnemonicRange = std::make_pair(std::begin(OperandMatchTable),"
2762           " std::end(OperandMatchTable));\n";
2763     OS << "  if (!Mnemonic.empty())\n";
2764     OS << "    MnemonicRange =\n";
2765     OS << "      std::equal_range(std::begin(OperandMatchTable), "
2766           "std::end(OperandMatchTable),\n";
2767     OS << "                       Mnemonic, LessOpcodeOperand());\n\n";
2768   }
2769 
2770   OS << "  if (MnemonicRange.first == MnemonicRange.second)\n";
2771   OS << "    return MatchOperand_NoMatch;\n\n";
2772 
2773   OS << "  for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2774      << "       *ie = MnemonicRange.second; it != ie; ++it) {\n";
2775 
2776   OS << "    // equal_range guarantees that instruction mnemonic matches.\n";
2777   OS << "    assert(Mnemonic == it->getMnemonic());\n\n";
2778 
2779   // Emit check that the required features are available.
2780   OS << "    // check if the available features match\n";
2781   OS << "    if ((AvailableFeatures & it->RequiredFeatures) "
2782      << "!= it->RequiredFeatures) {\n";
2783   OS << "      continue;\n";
2784   OS << "    }\n\n";
2785 
2786   // Emit check to ensure the operand number matches.
2787   OS << "    // check if the operand in question has a custom parser.\n";
2788   OS << "    if (!(it->OperandMask & (1 << NextOpNum)))\n";
2789   OS << "      continue;\n\n";
2790 
2791   // Emit call to the custom parser method
2792   OS << "    // call custom parse method to handle the operand\n";
2793   OS << "    OperandMatchResultTy Result = ";
2794   OS << "tryCustomParseOperand(Operands, it->Class);\n";
2795   OS << "    if (Result != MatchOperand_NoMatch)\n";
2796   OS << "      return Result;\n";
2797   OS << "  }\n\n";
2798 
2799   OS << "  // Okay, we had no match.\n";
2800   OS << "  return MatchOperand_NoMatch;\n";
2801   OS << "}\n\n";
2802 }
2803 
2804 void AsmMatcherEmitter::run(raw_ostream &OS) {
2805   CodeGenTarget Target(Records);
2806   Record *AsmParser = Target.getAsmParser();
2807   std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2808 
2809   // Compute the information on the instructions to match.
2810   AsmMatcherInfo Info(AsmParser, Target, Records);
2811   Info.buildInfo();
2812 
2813   // Sort the instruction table using the partial order on classes. We use
2814   // stable_sort to ensure that ambiguous instructions are still
2815   // deterministically ordered.
2816   std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2817                    [](const std::unique_ptr<MatchableInfo> &a,
2818                       const std::unique_ptr<MatchableInfo> &b){
2819                      return *a < *b;});
2820 
2821 #ifndef NDEBUG
2822   // Verify that the table is now sorted
2823   for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
2824        ++I) {
2825     for (auto J = I; J != E; ++J) {
2826       assert(!(**J < **I));
2827     }
2828   }
2829 #endif // NDEBUG
2830 
2831   DEBUG_WITH_TYPE("instruction_info", {
2832       for (const auto &MI : Info.Matchables)
2833         MI->dump();
2834     });
2835 
2836   // Check for ambiguous matchables.
2837   DEBUG_WITH_TYPE("ambiguous_instrs", {
2838     unsigned NumAmbiguous = 0;
2839     for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
2840          ++I) {
2841       for (auto J = std::next(I); J != E; ++J) {
2842         const MatchableInfo &A = **I;
2843         const MatchableInfo &B = **J;
2844 
2845         if (A.couldMatchAmbiguouslyWith(B)) {
2846           errs() << "warning: ambiguous matchables:\n";
2847           A.dump();
2848           errs() << "\nis incomparable with:\n";
2849           B.dump();
2850           errs() << "\n\n";
2851           ++NumAmbiguous;
2852         }
2853       }
2854     }
2855     if (NumAmbiguous)
2856       errs() << "warning: " << NumAmbiguous
2857              << " ambiguous matchables!\n";
2858   });
2859 
2860   // Compute the information on the custom operand parsing.
2861   Info.buildOperandMatchInfo();
2862 
2863   bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
2864   bool HasOptionalOperands = Info.hasOptionalOperands();
2865 
2866   // Write the output.
2867 
2868   // Information for the class declaration.
2869   OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2870   OS << "#undef GET_ASSEMBLER_HEADER\n";
2871   OS << "  // This should be included into the middle of the declaration of\n";
2872   OS << "  // your subclasses implementation of MCTargetAsmParser.\n";
2873   OS << "  uint64_t ComputeAvailableFeatures(const FeatureBitset& FB) const;\n";
2874   if (HasOptionalOperands) {
2875     OS << "  void convertToMCInst(unsigned Kind, MCInst &Inst, "
2876        << "unsigned Opcode,\n"
2877        << "                       const OperandVector &Operands,\n"
2878        << "                       const SmallBitVector &OptionalOperandsMask);\n";
2879   } else {
2880     OS << "  void convertToMCInst(unsigned Kind, MCInst &Inst, "
2881        << "unsigned Opcode,\n"
2882        << "                       const OperandVector &Operands);\n";
2883   }
2884   OS << "  void convertToMapAndConstraints(unsigned Kind,\n                ";
2885   OS << "           const OperandVector &Operands) override;\n";
2886   if (HasMnemonicFirst)
2887     OS << "  bool mnemonicIsValid(StringRef Mnemonic, unsigned VariantID);\n";
2888   OS << "  unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
2889      << "                                MCInst &Inst,\n"
2890      << "                                uint64_t &ErrorInfo,"
2891      << " bool matchingInlineAsm,\n"
2892      << "                                unsigned VariantID = 0);\n";
2893 
2894   if (!Info.OperandMatchInfo.empty()) {
2895     OS << "\n  enum OperandMatchResultTy {\n";
2896     OS << "    MatchOperand_Success,    // operand matched successfully\n";
2897     OS << "    MatchOperand_NoMatch,    // operand did not match\n";
2898     OS << "    MatchOperand_ParseFail   // operand matched but had errors\n";
2899     OS << "  };\n";
2900     OS << "  OperandMatchResultTy MatchOperandParserImpl(\n";
2901     OS << "    OperandVector &Operands,\n";
2902     OS << "    StringRef Mnemonic);\n";
2903 
2904     OS << "  OperandMatchResultTy tryCustomParseOperand(\n";
2905     OS << "    OperandVector &Operands,\n";
2906     OS << "    unsigned MCK);\n\n";
2907   }
2908 
2909   OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2910 
2911   // Emit the operand match diagnostic enum names.
2912   OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
2913   OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
2914   emitOperandDiagnosticTypes(Info, OS);
2915   OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
2916 
2917   OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2918   OS << "#undef GET_REGISTER_MATCHER\n\n";
2919 
2920   // Emit the subtarget feature enumeration.
2921   emitSubtargetFeatureFlagEnumeration(Info, OS);
2922 
2923   // Emit the function to match a register name to number.
2924   // This should be omitted for Mips target
2925   if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName"))
2926     emitMatchRegisterName(Target, AsmParser, OS);
2927 
2928   if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterAltName"))
2929     emitMatchRegisterAltName(Target, AsmParser, OS);
2930 
2931   OS << "#endif // GET_REGISTER_MATCHER\n\n";
2932 
2933   OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
2934   OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
2935 
2936   // Generate the helper function to get the names for subtarget features.
2937   emitGetSubtargetFeatureName(Info, OS);
2938 
2939   OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
2940 
2941   OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2942   OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
2943 
2944   // Generate the function that remaps for mnemonic aliases.
2945   bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target);
2946 
2947   // Generate the convertToMCInst function to convert operands into an MCInst.
2948   // Also, generate the convertToMapAndConstraints function for MS-style inline
2949   // assembly.  The latter doesn't actually generate a MCInst.
2950   emitConvertFuncs(Target, ClassName, Info.Matchables, HasMnemonicFirst,
2951                    HasOptionalOperands, OS);
2952 
2953   // Emit the enumeration for classes which participate in matching.
2954   emitMatchClassEnumeration(Target, Info.Classes, OS);
2955 
2956   // Emit the routine to match token strings to their match class.
2957   emitMatchTokenString(Target, Info.Classes, OS);
2958 
2959   // Emit the subclass predicate routine.
2960   emitIsSubclass(Target, Info.Classes, OS);
2961 
2962   // Emit the routine to validate an operand against a match class.
2963   emitValidateOperandClass(Info, OS);
2964 
2965   // Emit the available features compute function.
2966   emitComputeAvailableFeatures(Info, OS);
2967 
2968   StringToOffsetTable StringTable;
2969 
2970   size_t MaxNumOperands = 0;
2971   unsigned MaxMnemonicIndex = 0;
2972   bool HasDeprecation = false;
2973   for (const auto &MI : Info.Matchables) {
2974     MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
2975     HasDeprecation |= MI->HasDeprecation;
2976 
2977     // Store a pascal-style length byte in the mnemonic.
2978     std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
2979     MaxMnemonicIndex = std::max(MaxMnemonicIndex,
2980                         StringTable.GetOrAddStringOffset(LenMnemonic, false));
2981   }
2982 
2983   OS << "static const char *const MnemonicTable =\n";
2984   StringTable.EmitString(OS);
2985   OS << ";\n\n";
2986 
2987   // Emit the static match table; unused classes get initalized to 0 which is
2988   // guaranteed to be InvalidMatchClass.
2989   //
2990   // FIXME: We can reduce the size of this table very easily. First, we change
2991   // it so that store the kinds in separate bit-fields for each index, which
2992   // only needs to be the max width used for classes at that index (we also need
2993   // to reject based on this during classification). If we then make sure to
2994   // order the match kinds appropriately (putting mnemonics last), then we
2995   // should only end up using a few bits for each class, especially the ones
2996   // following the mnemonic.
2997   OS << "namespace {\n";
2998   OS << "  struct MatchEntry {\n";
2999   OS << "    " << getMinimalTypeForRange(MaxMnemonicIndex)
3000                << " Mnemonic;\n";
3001   OS << "    uint16_t Opcode;\n";
3002   OS << "    " << getMinimalTypeForRange(Info.Matchables.size())
3003                << " ConvertFn;\n";
3004   OS << "    " << getMinimalRequiredFeaturesType(Info)
3005                << " RequiredFeatures;\n";
3006   OS << "    " << getMinimalTypeForRange(
3007                       std::distance(Info.Classes.begin(), Info.Classes.end()))
3008      << " Classes[" << MaxNumOperands << "];\n";
3009   OS << "    StringRef getMnemonic() const {\n";
3010   OS << "      return StringRef(MnemonicTable + Mnemonic + 1,\n";
3011   OS << "                       MnemonicTable[Mnemonic]);\n";
3012   OS << "    }\n";
3013   OS << "  };\n\n";
3014 
3015   OS << "  // Predicate for searching for an opcode.\n";
3016   OS << "  struct LessOpcode {\n";
3017   OS << "    bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
3018   OS << "      return LHS.getMnemonic() < RHS;\n";
3019   OS << "    }\n";
3020   OS << "    bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
3021   OS << "      return LHS < RHS.getMnemonic();\n";
3022   OS << "    }\n";
3023   OS << "    bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
3024   OS << "      return LHS.getMnemonic() < RHS.getMnemonic();\n";
3025   OS << "    }\n";
3026   OS << "  };\n";
3027 
3028   OS << "} // end anonymous namespace.\n\n";
3029 
3030   unsigned VariantCount = Target.getAsmParserVariantCount();
3031   for (unsigned VC = 0; VC != VariantCount; ++VC) {
3032     Record *AsmVariant = Target.getAsmParserVariant(VC);
3033     int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3034 
3035     OS << "static const MatchEntry MatchTable" << VC << "[] = {\n";
3036 
3037     for (const auto &MI : Info.Matchables) {
3038       if (MI->AsmVariantID != AsmVariantNo)
3039         continue;
3040 
3041       // Store a pascal-style length byte in the mnemonic.
3042       std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
3043       OS << "  { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
3044          << " /* " << MI->Mnemonic << " */, "
3045          << Target.getName() << "::"
3046          << MI->getResultInst()->TheDef->getName() << ", "
3047          << MI->ConversionFnKind << ", ";
3048 
3049       // Write the required features mask.
3050       if (!MI->RequiredFeatures.empty()) {
3051         for (unsigned i = 0, e = MI->RequiredFeatures.size(); i != e; ++i) {
3052           if (i) OS << "|";
3053           OS << MI->RequiredFeatures[i]->getEnumName();
3054         }
3055       } else
3056         OS << "0";
3057 
3058       OS << ", { ";
3059       for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
3060         const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
3061 
3062         if (i) OS << ", ";
3063         OS << Op.Class->Name;
3064       }
3065       OS << " }, },\n";
3066     }
3067 
3068     OS << "};\n\n";
3069   }
3070 
3071   // A method to determine if a mnemonic is in the list.
3072   if (HasMnemonicFirst) {
3073     OS << "bool " << Target.getName() << ClassName << "::\n"
3074        << "mnemonicIsValid(StringRef Mnemonic, unsigned VariantID) {\n";
3075     OS << "  // Find the appropriate table for this asm variant.\n";
3076     OS << "  const MatchEntry *Start, *End;\n";
3077     OS << "  switch (VariantID) {\n";
3078     OS << "  default: llvm_unreachable(\"invalid variant!\");\n";
3079     for (unsigned VC = 0; VC != VariantCount; ++VC) {
3080       Record *AsmVariant = Target.getAsmParserVariant(VC);
3081       int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3082       OS << "  case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3083          << "); End = std::end(MatchTable" << VC << "); break;\n";
3084     }
3085     OS << "  }\n";
3086     OS << "  // Search the table.\n";
3087     OS << "  auto MnemonicRange = ";
3088     OS << "std::equal_range(Start, End, Mnemonic, LessOpcode());\n";
3089     OS << "  return MnemonicRange.first != MnemonicRange.second;\n";
3090     OS << "}\n\n";
3091   }
3092 
3093   // Finally, build the match function.
3094   OS << "unsigned " << Target.getName() << ClassName << "::\n"
3095      << "MatchInstructionImpl(const OperandVector &Operands,\n";
3096   OS << "                     MCInst &Inst, uint64_t &ErrorInfo,\n"
3097      << "                     bool matchingInlineAsm, unsigned VariantID) {\n";
3098 
3099   OS << "  // Eliminate obvious mismatches.\n";
3100   OS << "  if (Operands.size() > "
3101      << (MaxNumOperands + HasMnemonicFirst) << ") {\n";
3102   OS << "    ErrorInfo = "
3103      << (MaxNumOperands + HasMnemonicFirst) << ";\n";
3104   OS << "    return Match_InvalidOperand;\n";
3105   OS << "  }\n\n";
3106 
3107   // Emit code to get the available features.
3108   OS << "  // Get the current feature set.\n";
3109   OS << "  uint64_t AvailableFeatures = getAvailableFeatures();\n\n";
3110 
3111   OS << "  // Get the instruction mnemonic, which is the first token.\n";
3112   if (HasMnemonicFirst) {
3113     OS << "  StringRef Mnemonic = ((" << Target.getName()
3114        << "Operand&)*Operands[0]).getToken();\n\n";
3115   } else {
3116     OS << "  StringRef Mnemonic;\n";
3117     OS << "  if (Operands[0]->isToken())\n";
3118     OS << "    Mnemonic = ((" << Target.getName()
3119        << "Operand&)*Operands[0]).getToken();\n\n";
3120   }
3121 
3122   if (HasMnemonicAliases) {
3123     OS << "  // Process all MnemonicAliases to remap the mnemonic.\n";
3124     OS << "  applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n";
3125   }
3126 
3127   // Emit code to compute the class list for this operand vector.
3128   OS << "  // Some state to try to produce better error messages.\n";
3129   OS << "  bool HadMatchOtherThanFeatures = false;\n";
3130   OS << "  bool HadMatchOtherThanPredicate = false;\n";
3131   OS << "  unsigned RetCode = Match_InvalidOperand;\n";
3132   OS << "  uint64_t MissingFeatures = ~0ULL;\n";
3133   if (HasOptionalOperands) {
3134     OS << "  SmallBitVector OptionalOperandsMask(" << MaxNumOperands << ");\n";
3135   }
3136   OS << "  // Set ErrorInfo to the operand that mismatches if it is\n";
3137   OS << "  // wrong for all instances of the instruction.\n";
3138   OS << "  ErrorInfo = ~0ULL;\n";
3139 
3140   // Emit code to search the table.
3141   OS << "  // Find the appropriate table for this asm variant.\n";
3142   OS << "  const MatchEntry *Start, *End;\n";
3143   OS << "  switch (VariantID) {\n";
3144   OS << "  default: llvm_unreachable(\"invalid variant!\");\n";
3145   for (unsigned VC = 0; VC != VariantCount; ++VC) {
3146     Record *AsmVariant = Target.getAsmParserVariant(VC);
3147     int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3148     OS << "  case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3149        << "); End = std::end(MatchTable" << VC << "); break;\n";
3150   }
3151   OS << "  }\n";
3152 
3153   OS << "  // Search the table.\n";
3154   if (HasMnemonicFirst) {
3155     OS << "  auto MnemonicRange = "
3156           "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
3157   } else {
3158     OS << "  auto MnemonicRange = std::make_pair(Start, End);\n";
3159     OS << "  unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
3160     OS << "  if (!Mnemonic.empty())\n";
3161     OS << "    MnemonicRange = "
3162           "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
3163   }
3164 
3165   OS << "  // Return a more specific error code if no mnemonics match.\n";
3166   OS << "  if (MnemonicRange.first == MnemonicRange.second)\n";
3167   OS << "    return Match_MnemonicFail;\n\n";
3168 
3169   OS << "  for (const MatchEntry *it = MnemonicRange.first, "
3170      << "*ie = MnemonicRange.second;\n";
3171   OS << "       it != ie; ++it) {\n";
3172 
3173   if (HasMnemonicFirst) {
3174     OS << "    // equal_range guarantees that instruction mnemonic matches.\n";
3175     OS << "    assert(Mnemonic == it->getMnemonic());\n";
3176   }
3177 
3178   // Emit check that the subclasses match.
3179   OS << "    bool OperandsValid = true;\n";
3180   if (HasOptionalOperands) {
3181     OS << "    OptionalOperandsMask.reset(0, " << MaxNumOperands << ");\n";
3182   }
3183   OS << "    for (unsigned FormalIdx = " << (HasMnemonicFirst ? "0" : "SIndex")
3184      << ", ActualIdx = " << (HasMnemonicFirst ? "1" : "SIndex")
3185      << "; FormalIdx != " << MaxNumOperands << "; ++FormalIdx) {\n";
3186   OS << "      auto Formal = "
3187      << "static_cast<MatchClassKind>(it->Classes[FormalIdx]);\n";
3188   OS << "      if (ActualIdx >= Operands.size()) {\n";
3189   OS << "        OperandsValid = (Formal == " <<"InvalidMatchClass) || "
3190                                  "isSubclass(Formal, OptionalMatchClass);\n";
3191   OS << "        if (!OperandsValid) ErrorInfo = ActualIdx;\n";
3192   if (HasOptionalOperands) {
3193     OS << "        OptionalOperandsMask.set(FormalIdx, " << MaxNumOperands
3194        << ");\n";
3195   }
3196   OS << "        break;\n";
3197   OS << "      }\n";
3198   OS << "      MCParsedAsmOperand &Actual = *Operands[ActualIdx];\n";
3199   OS << "      unsigned Diag = validateOperandClass(Actual, Formal);\n";
3200   OS << "      if (Diag == Match_Success) {\n";
3201   OS << "        ++ActualIdx;\n";
3202   OS << "        continue;\n";
3203   OS << "      }\n";
3204   OS << "      // If the generic handler indicates an invalid operand\n";
3205   OS << "      // failure, check for a special case.\n";
3206   OS << "      if (Diag == Match_InvalidOperand) {\n";
3207   OS << "        Diag = validateTargetOperandClass(Actual, Formal);\n";
3208   OS << "        if (Diag == Match_Success) {\n";
3209   OS << "          ++ActualIdx;\n";
3210   OS << "          continue;\n";
3211   OS << "        }\n";
3212   OS << "      }\n";
3213   OS << "      // If current formal operand wasn't matched and it is optional\n"
3214      << "      // then try to match next formal operand\n";
3215   OS << "      if (Diag == Match_InvalidOperand "
3216      << "&& isSubclass(Formal, OptionalMatchClass)) {\n";
3217   if (HasOptionalOperands) {
3218     OS << "        OptionalOperandsMask.set(FormalIdx);\n";
3219   }
3220   OS << "        continue;\n";
3221   OS << "      }\n";
3222   OS << "      // If this operand is broken for all of the instances of this\n";
3223   OS << "      // mnemonic, keep track of it so we can report loc info.\n";
3224   OS << "      // If we already had a match that only failed due to a\n";
3225   OS << "      // target predicate, that diagnostic is preferred.\n";
3226   OS << "      if (!HadMatchOtherThanPredicate &&\n";
3227   OS << "          (it == MnemonicRange.first || ErrorInfo <= ActualIdx)) {\n";
3228   OS << "        ErrorInfo = ActualIdx;\n";
3229   OS << "        // InvalidOperand is the default. Prefer specificity.\n";
3230   OS << "        if (Diag != Match_InvalidOperand)\n";
3231   OS << "          RetCode = Diag;\n";
3232   OS << "      }\n";
3233   OS << "      // Otherwise, just reject this instance of the mnemonic.\n";
3234   OS << "      OperandsValid = false;\n";
3235   OS << "      break;\n";
3236   OS << "    }\n\n";
3237 
3238   OS << "    if (!OperandsValid) continue;\n";
3239 
3240   // Emit check that the required features are available.
3241   OS << "    if ((AvailableFeatures & it->RequiredFeatures) "
3242      << "!= it->RequiredFeatures) {\n";
3243   OS << "      HadMatchOtherThanFeatures = true;\n";
3244   OS << "      uint64_t NewMissingFeatures = it->RequiredFeatures & "
3245         "~AvailableFeatures;\n";
3246   OS << "      if (countPopulation(NewMissingFeatures) <=\n"
3247         "          countPopulation(MissingFeatures))\n";
3248   OS << "        MissingFeatures = NewMissingFeatures;\n";
3249   OS << "      continue;\n";
3250   OS << "    }\n";
3251   OS << "\n";
3252   OS << "    Inst.clear();\n\n";
3253   OS << "    Inst.setOpcode(it->Opcode);\n";
3254   // Verify the instruction with the target-specific match predicate function.
3255   OS << "    // We have a potential match but have not rendered the operands.\n"
3256      << "    // Check the target predicate to handle any context sensitive\n"
3257         "    // constraints.\n"
3258      << "    // For example, Ties that are referenced multiple times must be\n"
3259         "    // checked here to ensure the input is the same for each match\n"
3260         "    // constraints. If we leave it any later the ties will have been\n"
3261         "    // canonicalized\n"
3262      << "    unsigned MatchResult;\n"
3263      << "    if ((MatchResult = checkEarlyTargetMatchPredicate(Inst, "
3264         "Operands)) != Match_Success) {\n"
3265      << "      Inst.clear();\n"
3266      << "      RetCode = MatchResult;\n"
3267      << "      HadMatchOtherThanPredicate = true;\n"
3268      << "      continue;\n"
3269      << "    }\n\n";
3270   OS << "    if (matchingInlineAsm) {\n";
3271   OS << "      convertToMapAndConstraints(it->ConvertFn, Operands);\n";
3272   OS << "      return Match_Success;\n";
3273   OS << "    }\n\n";
3274   OS << "    // We have selected a definite instruction, convert the parsed\n"
3275      << "    // operands into the appropriate MCInst.\n";
3276   if (HasOptionalOperands) {
3277     OS << "    convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands,\n"
3278        << "                    OptionalOperandsMask);\n";
3279   } else {
3280     OS << "    convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
3281   }
3282   OS << "\n";
3283 
3284   // Verify the instruction with the target-specific match predicate function.
3285   OS << "    // We have a potential match. Check the target predicate to\n"
3286      << "    // handle any context sensitive constraints.\n"
3287      << "    if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
3288      << " Match_Success) {\n"
3289      << "      Inst.clear();\n"
3290      << "      RetCode = MatchResult;\n"
3291      << "      HadMatchOtherThanPredicate = true;\n"
3292      << "      continue;\n"
3293      << "    }\n\n";
3294 
3295   // Call the post-processing function, if used.
3296   std::string InsnCleanupFn =
3297     AsmParser->getValueAsString("AsmParserInstCleanup");
3298   if (!InsnCleanupFn.empty())
3299     OS << "    " << InsnCleanupFn << "(Inst);\n";
3300 
3301   if (HasDeprecation) {
3302     OS << "    std::string Info;\n";
3303     OS << "    if (MII.get(Inst.getOpcode()).getDeprecatedInfo(Inst, getSTI(), Info)) {\n";
3304     OS << "      SMLoc Loc = ((" << Target.getName()
3305        << "Operand&)*Operands[0]).getStartLoc();\n";
3306     OS << "      getParser().Warning(Loc, Info, None);\n";
3307     OS << "    }\n";
3308   }
3309 
3310   OS << "    return Match_Success;\n";
3311   OS << "  }\n\n";
3312 
3313   OS << "  // Okay, we had no match.  Try to return a useful error code.\n";
3314   OS << "  if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n";
3315   OS << "    return RetCode;\n\n";
3316   OS << "  // Missing feature matches return which features were missing\n";
3317   OS << "  ErrorInfo = MissingFeatures;\n";
3318   OS << "  return Match_MissingFeature;\n";
3319   OS << "}\n\n";
3320 
3321   if (!Info.OperandMatchInfo.empty())
3322     emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable,
3323                              MaxMnemonicIndex, HasMnemonicFirst);
3324 
3325   OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
3326 }
3327 
3328 namespace llvm {
3329 
3330 void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
3331   emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
3332   AsmMatcherEmitter(RK).run(OS);
3333 }
3334 
3335 } // end namespace llvm
3336