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