AsmMatcherEmitter.cpp revision ebdeeab812beec0385b445f3d4c41a114e0d972f
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 valeus 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 "AsmMatcherEmitter.h"
100#include "CodeGenTarget.h"
101#include "Error.h"
102#include "Record.h"
103#include "StringMatcher.h"
104#include "llvm/ADT/OwningPtr.h"
105#include "llvm/ADT/PointerUnion.h"
106#include "llvm/ADT/SmallPtrSet.h"
107#include "llvm/ADT/SmallVector.h"
108#include "llvm/ADT/STLExtras.h"
109#include "llvm/ADT/StringExtras.h"
110#include "llvm/Support/CommandLine.h"
111#include "llvm/Support/Debug.h"
112#include <map>
113#include <set>
114using namespace llvm;
115
116static cl::opt<std::string>
117MatchPrefix("match-prefix", cl::init(""),
118            cl::desc("Only match instructions with the given prefix"));
119
120namespace {
121class AsmMatcherInfo;
122struct SubtargetFeatureInfo;
123
124/// ClassInfo - Helper class for storing the information about a particular
125/// class of operands which can be matched.
126struct ClassInfo {
127  enum ClassInfoKind {
128    /// Invalid kind, for use as a sentinel value.
129    Invalid = 0,
130
131    /// The class for a particular token.
132    Token,
133
134    /// The (first) register class, subsequent register classes are
135    /// RegisterClass0+1, and so on.
136    RegisterClass0,
137
138    /// The (first) user defined class, subsequent user defined classes are
139    /// UserClass0+1, and so on.
140    UserClass0 = 1<<16
141  };
142
143  /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
144  /// N) for the Nth user defined class.
145  unsigned Kind;
146
147  /// SuperClasses - The super classes of this class. Note that for simplicities
148  /// sake user operands only record their immediate super class, while register
149  /// operands include all superclasses.
150  std::vector<ClassInfo*> SuperClasses;
151
152  /// Name - The full class name, suitable for use in an enum.
153  std::string Name;
154
155  /// ClassName - The unadorned generic name for this class (e.g., Token).
156  std::string ClassName;
157
158  /// ValueName - The name of the value this class represents; for a token this
159  /// is the literal token string, for an operand it is the TableGen class (or
160  /// empty if this is a derived class).
161  std::string ValueName;
162
163  /// PredicateMethod - The name of the operand method to test whether the
164  /// operand matches this class; this is not valid for Token or register kinds.
165  std::string PredicateMethod;
166
167  /// RenderMethod - The name of the operand method to add this operand to an
168  /// MCInst; this is not valid for Token or register kinds.
169  std::string RenderMethod;
170
171  /// ParserMethod - The name of the operand method to do a target specific
172  /// parsing on the operand.
173  std::string ParserMethod;
174
175  /// For register classes, the records for all the registers in this class.
176  std::set<Record*> Registers;
177
178public:
179  /// isRegisterClass() - Check if this is a register class.
180  bool isRegisterClass() const {
181    return Kind >= RegisterClass0 && Kind < UserClass0;
182  }
183
184  /// isUserClass() - Check if this is a user defined class.
185  bool isUserClass() const {
186    return Kind >= UserClass0;
187  }
188
189  /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
190  /// are related if they are in the same class hierarchy.
191  bool isRelatedTo(const ClassInfo &RHS) const {
192    // Tokens are only related to tokens.
193    if (Kind == Token || RHS.Kind == Token)
194      return Kind == Token && RHS.Kind == Token;
195
196    // Registers classes are only related to registers classes, and only if
197    // their intersection is non-empty.
198    if (isRegisterClass() || RHS.isRegisterClass()) {
199      if (!isRegisterClass() || !RHS.isRegisterClass())
200        return false;
201
202      std::set<Record*> Tmp;
203      std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
204      std::set_intersection(Registers.begin(), Registers.end(),
205                            RHS.Registers.begin(), RHS.Registers.end(),
206                            II);
207
208      return !Tmp.empty();
209    }
210
211    // Otherwise we have two users operands; they are related if they are in the
212    // same class hierarchy.
213    //
214    // FIXME: This is an oversimplification, they should only be related if they
215    // intersect, however we don't have that information.
216    assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
217    const ClassInfo *Root = this;
218    while (!Root->SuperClasses.empty())
219      Root = Root->SuperClasses.front();
220
221    const ClassInfo *RHSRoot = &RHS;
222    while (!RHSRoot->SuperClasses.empty())
223      RHSRoot = RHSRoot->SuperClasses.front();
224
225    return Root == RHSRoot;
226  }
227
228  /// isSubsetOf - Test whether this class is a subset of \arg RHS;
229  bool isSubsetOf(const ClassInfo &RHS) const {
230    // This is a subset of RHS if it is the same class...
231    if (this == &RHS)
232      return true;
233
234    // ... or if any of its super classes are a subset of RHS.
235    for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
236           ie = SuperClasses.end(); it != ie; ++it)
237      if ((*it)->isSubsetOf(RHS))
238        return true;
239
240    return false;
241  }
242
243  /// operator< - Compare two classes.
244  bool operator<(const ClassInfo &RHS) const {
245    if (this == &RHS)
246      return false;
247
248    // Unrelated classes can be ordered by kind.
249    if (!isRelatedTo(RHS))
250      return Kind < RHS.Kind;
251
252    switch (Kind) {
253    case Invalid:
254      assert(0 && "Invalid kind!");
255    case Token:
256      // Tokens are comparable by value.
257      //
258      // FIXME: Compare by enum value.
259      return ValueName < RHS.ValueName;
260
261    default:
262      // This class precedes the RHS if it is a proper subset of the RHS.
263      if (isSubsetOf(RHS))
264        return true;
265      if (RHS.isSubsetOf(*this))
266        return false;
267
268      // Otherwise, order by name to ensure we have a total ordering.
269      return ValueName < RHS.ValueName;
270    }
271  }
272};
273
274/// MatchableInfo - Helper class for storing the necessary information for an
275/// instruction or alias which is capable of being matched.
276struct MatchableInfo {
277  struct AsmOperand {
278    /// Token - This is the token that the operand came from.
279    StringRef Token;
280
281    /// The unique class instance this operand should match.
282    ClassInfo *Class;
283
284    /// The operand name this is, if anything.
285    StringRef SrcOpName;
286
287    /// The suboperand index within SrcOpName, or -1 for the entire operand.
288    int SubOpIdx;
289
290    explicit AsmOperand(StringRef T) : Token(T), Class(0), SubOpIdx(-1) {}
291  };
292
293  /// ResOperand - This represents a single operand in the result instruction
294  /// generated by the match.  In cases (like addressing modes) where a single
295  /// assembler operand expands to multiple MCOperands, this represents the
296  /// single assembler operand, not the MCOperand.
297  struct ResOperand {
298    enum {
299      /// RenderAsmOperand - This represents an operand result that is
300      /// generated by calling the render method on the assembly operand.  The
301      /// corresponding AsmOperand is specified by AsmOperandNum.
302      RenderAsmOperand,
303
304      /// TiedOperand - This represents a result operand that is a duplicate of
305      /// a previous result operand.
306      TiedOperand,
307
308      /// ImmOperand - This represents an immediate value that is dumped into
309      /// the operand.
310      ImmOperand,
311
312      /// RegOperand - This represents a fixed register that is dumped in.
313      RegOperand
314    } Kind;
315
316    union {
317      /// This is the operand # in the AsmOperands list that this should be
318      /// copied from.
319      unsigned AsmOperandNum;
320
321      /// TiedOperandNum - This is the (earlier) result operand that should be
322      /// copied from.
323      unsigned TiedOperandNum;
324
325      /// ImmVal - This is the immediate value added to the instruction.
326      int64_t ImmVal;
327
328      /// Register - This is the register record.
329      Record *Register;
330    };
331
332    /// MINumOperands - The number of MCInst operands populated by this
333    /// operand.
334    unsigned MINumOperands;
335
336    static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
337      ResOperand X;
338      X.Kind = RenderAsmOperand;
339      X.AsmOperandNum = AsmOpNum;
340      X.MINumOperands = NumOperands;
341      return X;
342    }
343
344    static ResOperand getTiedOp(unsigned TiedOperandNum) {
345      ResOperand X;
346      X.Kind = TiedOperand;
347      X.TiedOperandNum = TiedOperandNum;
348      X.MINumOperands = 1;
349      return X;
350    }
351
352    static ResOperand getImmOp(int64_t Val) {
353      ResOperand X;
354      X.Kind = ImmOperand;
355      X.ImmVal = Val;
356      X.MINumOperands = 1;
357      return X;
358    }
359
360    static ResOperand getRegOp(Record *Reg) {
361      ResOperand X;
362      X.Kind = RegOperand;
363      X.Register = Reg;
364      X.MINumOperands = 1;
365      return X;
366    }
367  };
368
369  /// TheDef - This is the definition of the instruction or InstAlias that this
370  /// matchable came from.
371  Record *const TheDef;
372
373  /// DefRec - This is the definition that it came from.
374  PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
375
376  const CodeGenInstruction *getResultInst() const {
377    if (DefRec.is<const CodeGenInstruction*>())
378      return DefRec.get<const CodeGenInstruction*>();
379    return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
380  }
381
382  /// ResOperands - This is the operand list that should be built for the result
383  /// MCInst.
384  std::vector<ResOperand> ResOperands;
385
386  /// AsmString - The assembly string for this instruction (with variants
387  /// removed), e.g. "movsx $src, $dst".
388  std::string AsmString;
389
390  /// Mnemonic - This is the first token of the matched instruction, its
391  /// mnemonic.
392  StringRef Mnemonic;
393
394  /// AsmOperands - The textual operands that this instruction matches,
395  /// annotated with a class and where in the OperandList they were defined.
396  /// This directly corresponds to the tokenized AsmString after the mnemonic is
397  /// removed.
398  SmallVector<AsmOperand, 4> AsmOperands;
399
400  /// Predicates - The required subtarget features to match this instruction.
401  SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
402
403  /// ConversionFnKind - The enum value which is passed to the generated
404  /// ConvertToMCInst to convert parsed operands into an MCInst for this
405  /// function.
406  std::string ConversionFnKind;
407
408  MatchableInfo(const CodeGenInstruction &CGI)
409    : TheDef(CGI.TheDef), DefRec(&CGI), AsmString(CGI.AsmString) {
410  }
411
412  MatchableInfo(const CodeGenInstAlias *Alias)
413    : TheDef(Alias->TheDef), DefRec(Alias), AsmString(Alias->AsmString) {
414  }
415
416  void Initialize(const AsmMatcherInfo &Info,
417                  SmallPtrSet<Record*, 16> &SingletonRegisters);
418
419  /// Validate - Return true if this matchable is a valid thing to match against
420  /// and perform a bunch of validity checking.
421  bool Validate(StringRef CommentDelimiter, bool Hack) const;
422
423  /// getSingletonRegisterForAsmOperand - If the specified token is a singleton
424  /// register, return the Record for it, otherwise return null.
425  Record *getSingletonRegisterForAsmOperand(unsigned i,
426                                            const AsmMatcherInfo &Info) const;
427
428  /// FindAsmOperand - Find the AsmOperand with the specified name and
429  /// suboperand index.
430  int FindAsmOperand(StringRef N, int SubOpIdx) const {
431    for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
432      if (N == AsmOperands[i].SrcOpName &&
433          SubOpIdx == AsmOperands[i].SubOpIdx)
434        return i;
435    return -1;
436  }
437
438  /// FindAsmOperandNamed - Find the first AsmOperand with the specified name.
439  /// This does not check the suboperand index.
440  int FindAsmOperandNamed(StringRef N) const {
441    for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
442      if (N == AsmOperands[i].SrcOpName)
443        return i;
444    return -1;
445  }
446
447  void BuildInstructionResultOperands();
448  void BuildAliasResultOperands();
449
450  /// operator< - Compare two matchables.
451  bool operator<(const MatchableInfo &RHS) const {
452    // The primary comparator is the instruction mnemonic.
453    if (Mnemonic != RHS.Mnemonic)
454      return Mnemonic < RHS.Mnemonic;
455
456    if (AsmOperands.size() != RHS.AsmOperands.size())
457      return AsmOperands.size() < RHS.AsmOperands.size();
458
459    // Compare lexicographically by operand. The matcher validates that other
460    // orderings wouldn't be ambiguous using \see CouldMatchAmbiguouslyWith().
461    for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
462      if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
463        return true;
464      if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
465        return false;
466    }
467
468    return false;
469  }
470
471  /// CouldMatchAmbiguouslyWith - Check whether this matchable could
472  /// ambiguously match the same set of operands as \arg RHS (without being a
473  /// strictly superior match).
474  bool CouldMatchAmbiguouslyWith(const MatchableInfo &RHS) {
475    // The primary comparator is the instruction mnemonic.
476    if (Mnemonic != RHS.Mnemonic)
477      return false;
478
479    // The number of operands is unambiguous.
480    if (AsmOperands.size() != RHS.AsmOperands.size())
481      return false;
482
483    // Otherwise, make sure the ordering of the two instructions is unambiguous
484    // by checking that either (a) a token or operand kind discriminates them,
485    // or (b) the ordering among equivalent kinds is consistent.
486
487    // Tokens and operand kinds are unambiguous (assuming a correct target
488    // specific parser).
489    for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
490      if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
491          AsmOperands[i].Class->Kind == ClassInfo::Token)
492        if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
493            *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
494          return false;
495
496    // Otherwise, this operand could commute if all operands are equivalent, or
497    // there is a pair of operands that compare less than and a pair that
498    // compare greater than.
499    bool HasLT = false, HasGT = false;
500    for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
501      if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
502        HasLT = true;
503      if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
504        HasGT = true;
505    }
506
507    return !(HasLT ^ HasGT);
508  }
509
510  void dump();
511
512private:
513  void TokenizeAsmString(const AsmMatcherInfo &Info);
514};
515
516/// SubtargetFeatureInfo - Helper class for storing information on a subtarget
517/// feature which participates in instruction matching.
518struct SubtargetFeatureInfo {
519  /// \brief The predicate record for this feature.
520  Record *TheDef;
521
522  /// \brief An unique index assigned to represent this feature.
523  unsigned Index;
524
525  SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
526
527  /// \brief The name of the enumerated constant identifying this feature.
528  std::string getEnumName() const {
529    return "Feature_" + TheDef->getName();
530  }
531};
532
533struct OperandMatchEntry {
534  unsigned OperandMask;
535  MatchableInfo* MI;
536  ClassInfo *CI;
537
538  static OperandMatchEntry Create(MatchableInfo* mi, ClassInfo *ci,
539                                  unsigned opMask) {
540    OperandMatchEntry X;
541    X.OperandMask = opMask;
542    X.CI = ci;
543    X.MI = mi;
544    return X;
545  }
546};
547
548
549class AsmMatcherInfo {
550public:
551  /// Tracked Records
552  RecordKeeper &Records;
553
554  /// The tablegen AsmParser record.
555  Record *AsmParser;
556
557  /// Target - The target information.
558  CodeGenTarget &Target;
559
560  /// The AsmParser "RegisterPrefix" value.
561  std::string RegisterPrefix;
562
563  /// The classes which are needed for matching.
564  std::vector<ClassInfo*> Classes;
565
566  /// The information on the matchables to match.
567  std::vector<MatchableInfo*> Matchables;
568
569  /// Info for custom matching operands by user defined methods.
570  std::vector<OperandMatchEntry> OperandMatchInfo;
571
572  /// Map of Register records to their class information.
573  std::map<Record*, ClassInfo*> RegisterClasses;
574
575  /// Map of Predicate records to their subtarget information.
576  std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
577
578private:
579  /// Map of token to class information which has already been constructed.
580  std::map<std::string, ClassInfo*> TokenClasses;
581
582  /// Map of RegisterClass records to their class information.
583  std::map<Record*, ClassInfo*> RegisterClassClasses;
584
585  /// Map of AsmOperandClass records to their class information.
586  std::map<Record*, ClassInfo*> AsmOperandClasses;
587
588private:
589  /// getTokenClass - Lookup or create the class for the given token.
590  ClassInfo *getTokenClass(StringRef Token);
591
592  /// getOperandClass - Lookup or create the class for the given operand.
593  ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
594                             int SubOpIdx = -1);
595
596  /// BuildRegisterClasses - Build the ClassInfo* instances for register
597  /// classes.
598  void BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
599
600  /// BuildOperandClasses - Build the ClassInfo* instances for user defined
601  /// operand classes.
602  void BuildOperandClasses();
603
604  void BuildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
605                                        unsigned AsmOpIdx);
606  void BuildAliasOperandReference(MatchableInfo *II, StringRef OpName,
607                                  MatchableInfo::AsmOperand &Op);
608
609public:
610  AsmMatcherInfo(Record *AsmParser,
611                 CodeGenTarget &Target,
612                 RecordKeeper &Records);
613
614  /// BuildInfo - Construct the various tables used during matching.
615  void BuildInfo();
616
617  /// BuildOperandMatchInfo - Build the necessary information to handle user
618  /// defined operand parsing methods.
619  void BuildOperandMatchInfo();
620
621  /// getSubtargetFeature - Lookup or create the subtarget feature info for the
622  /// given operand.
623  SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
624    assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
625    std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
626      SubtargetFeatures.find(Def);
627    return I == SubtargetFeatures.end() ? 0 : I->second;
628  }
629
630  RecordKeeper &getRecords() const {
631    return Records;
632  }
633};
634
635}
636
637void MatchableInfo::dump() {
638  errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
639
640  for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
641    AsmOperand &Op = AsmOperands[i];
642    errs() << "  op[" << i << "] = " << Op.Class->ClassName << " - ";
643    errs() << '\"' << Op.Token << "\"\n";
644  }
645}
646
647void MatchableInfo::Initialize(const AsmMatcherInfo &Info,
648                               SmallPtrSet<Record*, 16> &SingletonRegisters) {
649  // TODO: Eventually support asmparser for Variant != 0.
650  AsmString = CodeGenInstruction::FlattenAsmStringVariants(AsmString, 0);
651
652  TokenizeAsmString(Info);
653
654  // Compute the require features.
655  std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates");
656  for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
657    if (SubtargetFeatureInfo *Feature =
658        Info.getSubtargetFeature(Predicates[i]))
659      RequiredFeatures.push_back(Feature);
660
661  // Collect singleton registers, if used.
662  for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
663    if (Record *Reg = getSingletonRegisterForAsmOperand(i, Info))
664      SingletonRegisters.insert(Reg);
665  }
666}
667
668/// TokenizeAsmString - Tokenize a simplified assembly string.
669void MatchableInfo::TokenizeAsmString(const AsmMatcherInfo &Info) {
670  StringRef String = AsmString;
671  unsigned Prev = 0;
672  bool InTok = true;
673  for (unsigned i = 0, e = String.size(); i != e; ++i) {
674    switch (String[i]) {
675    case '[':
676    case ']':
677    case '*':
678    case '!':
679    case ' ':
680    case '\t':
681    case ',':
682      if (InTok) {
683        AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
684        InTok = false;
685      }
686      if (!isspace(String[i]) && String[i] != ',')
687        AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
688      Prev = i + 1;
689      break;
690
691    case '\\':
692      if (InTok) {
693        AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
694        InTok = false;
695      }
696      ++i;
697      assert(i != String.size() && "Invalid quoted character");
698      AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
699      Prev = i + 1;
700      break;
701
702    case '$': {
703      if (InTok) {
704        AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
705        InTok = false;
706      }
707
708      // If this isn't "${", treat like a normal token.
709      if (i + 1 == String.size() || String[i + 1] != '{') {
710        Prev = i;
711        break;
712      }
713
714      StringRef::iterator End = std::find(String.begin() + i, String.end(),'}');
715      assert(End != String.end() && "Missing brace in operand reference!");
716      size_t EndPos = End - String.begin();
717      AsmOperands.push_back(AsmOperand(String.slice(i, EndPos+1)));
718      Prev = EndPos + 1;
719      i = EndPos;
720      break;
721    }
722
723    case '.':
724      if (InTok)
725        AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
726      Prev = i;
727      InTok = true;
728      break;
729
730    default:
731      InTok = true;
732    }
733  }
734  if (InTok && Prev != String.size())
735    AsmOperands.push_back(AsmOperand(String.substr(Prev)));
736
737  // The first token of the instruction is the mnemonic, which must be a
738  // simple string, not a $foo variable or a singleton register.
739  assert(!AsmOperands.empty() && "Instruction has no tokens?");
740  Mnemonic = AsmOperands[0].Token;
741  if (Mnemonic[0] == '$' || getSingletonRegisterForAsmOperand(0, Info))
742    throw TGError(TheDef->getLoc(),
743                  "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
744
745  // Remove the first operand, it is tracked in the mnemonic field.
746  AsmOperands.erase(AsmOperands.begin());
747}
748
749bool MatchableInfo::Validate(StringRef CommentDelimiter, bool Hack) const {
750  // Reject matchables with no .s string.
751  if (AsmString.empty())
752    throw TGError(TheDef->getLoc(), "instruction with empty asm string");
753
754  // Reject any matchables with a newline in them, they should be marked
755  // isCodeGenOnly if they are pseudo instructions.
756  if (AsmString.find('\n') != std::string::npos)
757    throw TGError(TheDef->getLoc(),
758                  "multiline instruction is not valid for the asmparser, "
759                  "mark it isCodeGenOnly");
760
761  // Remove comments from the asm string.  We know that the asmstring only
762  // has one line.
763  if (!CommentDelimiter.empty() &&
764      StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
765    throw TGError(TheDef->getLoc(),
766                  "asmstring for instruction has comment character in it, "
767                  "mark it isCodeGenOnly");
768
769  // Reject matchables with operand modifiers, these aren't something we can
770  // handle, the target should be refactored to use operands instead of
771  // modifiers.
772  //
773  // Also, check for instructions which reference the operand multiple times;
774  // this implies a constraint we would not honor.
775  std::set<std::string> OperandNames;
776  for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
777    StringRef Tok = AsmOperands[i].Token;
778    if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
779      throw TGError(TheDef->getLoc(),
780                    "matchable with operand modifier '" + Tok.str() +
781                    "' not supported by asm matcher.  Mark isCodeGenOnly!");
782
783    // Verify that any operand is only mentioned once.
784    // We reject aliases and ignore instructions for now.
785    if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
786      if (!Hack)
787        throw TGError(TheDef->getLoc(),
788                      "ERROR: matchable with tied operand '" + Tok.str() +
789                      "' can never be matched!");
790      // FIXME: Should reject these.  The ARM backend hits this with $lane in a
791      // bunch of instructions.  It is unclear what the right answer is.
792      DEBUG({
793        errs() << "warning: '" << TheDef->getName() << "': "
794               << "ignoring instruction with tied operand '"
795               << Tok.str() << "'\n";
796      });
797      return false;
798    }
799  }
800
801  return true;
802}
803
804/// getSingletonRegisterForAsmOperand - If the specified token is a singleton
805/// register, return the register name, otherwise return a null StringRef.
806Record *MatchableInfo::
807getSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info) const{
808  StringRef Tok = AsmOperands[i].Token;
809  if (!Tok.startswith(Info.RegisterPrefix))
810    return 0;
811
812  StringRef RegName = Tok.substr(Info.RegisterPrefix.size());
813  if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
814    return Reg->TheDef;
815
816  // If there is no register prefix (i.e. "%" in "%eax"), then this may
817  // be some random non-register token, just ignore it.
818  if (Info.RegisterPrefix.empty())
819    return 0;
820
821  // Otherwise, we have something invalid prefixed with the register prefix,
822  // such as %foo.
823  std::string Err = "unable to find register for '" + RegName.str() +
824  "' (which matches register prefix)";
825  throw TGError(TheDef->getLoc(), Err);
826}
827
828static std::string getEnumNameForToken(StringRef Str) {
829  std::string Res;
830
831  for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
832    switch (*it) {
833    case '*': Res += "_STAR_"; break;
834    case '%': Res += "_PCT_"; break;
835    case ':': Res += "_COLON_"; break;
836    case '!': Res += "_EXCLAIM_"; break;
837    case '.': Res += "_DOT_"; break;
838    default:
839      if (isalnum(*it))
840        Res += *it;
841      else
842        Res += "_" + utostr((unsigned) *it) + "_";
843    }
844  }
845
846  return Res;
847}
848
849ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
850  ClassInfo *&Entry = TokenClasses[Token];
851
852  if (!Entry) {
853    Entry = new ClassInfo();
854    Entry->Kind = ClassInfo::Token;
855    Entry->ClassName = "Token";
856    Entry->Name = "MCK_" + getEnumNameForToken(Token);
857    Entry->ValueName = Token;
858    Entry->PredicateMethod = "<invalid>";
859    Entry->RenderMethod = "<invalid>";
860    Entry->ParserMethod = "";
861    Classes.push_back(Entry);
862  }
863
864  return Entry;
865}
866
867ClassInfo *
868AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
869                                int SubOpIdx) {
870  Record *Rec = OI.Rec;
871  if (SubOpIdx != -1)
872    Rec = dynamic_cast<DefInit*>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
873
874  if (Rec->isSubClassOf("RegisterOperand")) {
875    // RegisterOperand may have an associated ParserMatchClass. If it does,
876    // use it, else just fall back to the underlying register class.
877    const RecordVal *R = Rec->getValue("ParserMatchClass");
878    if (R == 0 || R->getValue() == 0)
879      throw "Record `" + Rec->getName() +
880        "' does not have a ParserMatchClass!\n";
881
882    if (DefInit *DI= dynamic_cast<DefInit*>(R->getValue())) {
883      Record *MatchClass = DI->getDef();
884      if (ClassInfo *CI = AsmOperandClasses[MatchClass])
885        return CI;
886    }
887
888    // No custom match class. Just use the register class.
889    Record *ClassRec = Rec->getValueAsDef("RegClass");
890    if (!ClassRec)
891      throw TGError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
892                    "' has no associated register class!\n");
893    if (ClassInfo *CI = RegisterClassClasses[ClassRec])
894      return CI;
895    throw TGError(Rec->getLoc(), "register class has no class info!");
896  }
897
898
899  if (Rec->isSubClassOf("RegisterClass")) {
900    if (ClassInfo *CI = RegisterClassClasses[Rec])
901      return CI;
902    throw TGError(Rec->getLoc(), "register class has no class info!");
903  }
904
905  assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
906  Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
907  if (ClassInfo *CI = AsmOperandClasses[MatchClass])
908    return CI;
909
910  throw TGError(Rec->getLoc(), "operand has no match class!");
911}
912
913void AsmMatcherInfo::
914BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
915  const std::vector<CodeGenRegister*> &Registers =
916    Target.getRegBank().getRegisters();
917  const std::vector<CodeGenRegisterClass> &RegClassList =
918    Target.getRegisterClasses();
919
920  // The register sets used for matching.
921  std::set< std::set<Record*> > RegisterSets;
922
923  // Gather the defined sets.
924  for (std::vector<CodeGenRegisterClass>::const_iterator it =
925       RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it)
926    RegisterSets.insert(std::set<Record*>(it->getOrder().begin(),
927                                          it->getOrder().end()));
928
929  // Add any required singleton sets.
930  for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
931       ie = SingletonRegisters.end(); it != ie; ++it) {
932    Record *Rec = *it;
933    RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
934  }
935
936  // Introduce derived sets where necessary (when a register does not determine
937  // a unique register set class), and build the mapping of registers to the set
938  // they should classify to.
939  std::map<Record*, std::set<Record*> > RegisterMap;
940  for (std::vector<CodeGenRegister*>::const_iterator it = Registers.begin(),
941         ie = Registers.end(); it != ie; ++it) {
942    const CodeGenRegister &CGR = **it;
943    // Compute the intersection of all sets containing this register.
944    std::set<Record*> ContainingSet;
945
946    for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
947           ie = RegisterSets.end(); it != ie; ++it) {
948      if (!it->count(CGR.TheDef))
949        continue;
950
951      if (ContainingSet.empty()) {
952        ContainingSet = *it;
953        continue;
954      }
955
956      std::set<Record*> Tmp;
957      std::swap(Tmp, ContainingSet);
958      std::insert_iterator< std::set<Record*> > II(ContainingSet,
959                                                   ContainingSet.begin());
960      std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(), II);
961    }
962
963    if (!ContainingSet.empty()) {
964      RegisterSets.insert(ContainingSet);
965      RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
966    }
967  }
968
969  // Construct the register classes.
970  std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
971  unsigned Index = 0;
972  for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
973         ie = RegisterSets.end(); it != ie; ++it, ++Index) {
974    ClassInfo *CI = new ClassInfo();
975    CI->Kind = ClassInfo::RegisterClass0 + Index;
976    CI->ClassName = "Reg" + utostr(Index);
977    CI->Name = "MCK_Reg" + utostr(Index);
978    CI->ValueName = "";
979    CI->PredicateMethod = ""; // unused
980    CI->RenderMethod = "addRegOperands";
981    CI->Registers = *it;
982    Classes.push_back(CI);
983    RegisterSetClasses.insert(std::make_pair(*it, CI));
984  }
985
986  // Find the superclasses; we could compute only the subgroup lattice edges,
987  // but there isn't really a point.
988  for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
989         ie = RegisterSets.end(); it != ie; ++it) {
990    ClassInfo *CI = RegisterSetClasses[*it];
991    for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
992           ie2 = RegisterSets.end(); it2 != ie2; ++it2)
993      if (*it != *it2 &&
994          std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
995        CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
996  }
997
998  // Name the register classes which correspond to a user defined RegisterClass.
999  for (std::vector<CodeGenRegisterClass>::const_iterator
1000       it = RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) {
1001    ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->getOrder().begin(),
1002                                                         it->getOrder().end())];
1003    if (CI->ValueName.empty()) {
1004      CI->ClassName = it->getName();
1005      CI->Name = "MCK_" + it->getName();
1006      CI->ValueName = it->getName();
1007    } else
1008      CI->ValueName = CI->ValueName + "," + it->getName();
1009
1010    RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
1011  }
1012
1013  // Populate the map for individual registers.
1014  for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
1015         ie = RegisterMap.end(); it != ie; ++it)
1016    RegisterClasses[it->first] = RegisterSetClasses[it->second];
1017
1018  // Name the register classes which correspond to singleton registers.
1019  for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1020         ie = SingletonRegisters.end(); it != ie; ++it) {
1021    Record *Rec = *it;
1022    ClassInfo *CI = RegisterClasses[Rec];
1023    assert(CI && "Missing singleton register class info!");
1024
1025    if (CI->ValueName.empty()) {
1026      CI->ClassName = Rec->getName();
1027      CI->Name = "MCK_" + Rec->getName();
1028      CI->ValueName = Rec->getName();
1029    } else
1030      CI->ValueName = CI->ValueName + "," + Rec->getName();
1031  }
1032}
1033
1034void AsmMatcherInfo::BuildOperandClasses() {
1035  std::vector<Record*> AsmOperands =
1036    Records.getAllDerivedDefinitions("AsmOperandClass");
1037
1038  // Pre-populate AsmOperandClasses map.
1039  for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1040         ie = AsmOperands.end(); it != ie; ++it)
1041    AsmOperandClasses[*it] = new ClassInfo();
1042
1043  unsigned Index = 0;
1044  for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1045         ie = AsmOperands.end(); it != ie; ++it, ++Index) {
1046    ClassInfo *CI = AsmOperandClasses[*it];
1047    CI->Kind = ClassInfo::UserClass0 + Index;
1048
1049    ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
1050    for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
1051      DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
1052      if (!DI) {
1053        PrintError((*it)->getLoc(), "Invalid super class reference!");
1054        continue;
1055      }
1056
1057      ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1058      if (!SC)
1059        PrintError((*it)->getLoc(), "Invalid super class reference!");
1060      else
1061        CI->SuperClasses.push_back(SC);
1062    }
1063    CI->ClassName = (*it)->getValueAsString("Name");
1064    CI->Name = "MCK_" + CI->ClassName;
1065    CI->ValueName = (*it)->getName();
1066
1067    // Get or construct the predicate method name.
1068    Init *PMName = (*it)->getValueInit("PredicateMethod");
1069    if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
1070      CI->PredicateMethod = SI->getValue();
1071    } else {
1072      assert(dynamic_cast<UnsetInit*>(PMName) &&
1073             "Unexpected PredicateMethod field!");
1074      CI->PredicateMethod = "is" + CI->ClassName;
1075    }
1076
1077    // Get or construct the render method name.
1078    Init *RMName = (*it)->getValueInit("RenderMethod");
1079    if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
1080      CI->RenderMethod = SI->getValue();
1081    } else {
1082      assert(dynamic_cast<UnsetInit*>(RMName) &&
1083             "Unexpected RenderMethod field!");
1084      CI->RenderMethod = "add" + CI->ClassName + "Operands";
1085    }
1086
1087    // Get the parse method name or leave it as empty.
1088    Init *PRMName = (*it)->getValueInit("ParserMethod");
1089    if (StringInit *SI = dynamic_cast<StringInit*>(PRMName))
1090      CI->ParserMethod = SI->getValue();
1091
1092    AsmOperandClasses[*it] = CI;
1093    Classes.push_back(CI);
1094  }
1095}
1096
1097AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1098                               CodeGenTarget &target,
1099                               RecordKeeper &records)
1100  : Records(records), AsmParser(asmParser), Target(target),
1101    RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix")) {
1102}
1103
1104/// BuildOperandMatchInfo - Build the necessary information to handle user
1105/// defined operand parsing methods.
1106void AsmMatcherInfo::BuildOperandMatchInfo() {
1107
1108  /// Map containing a mask with all operands indicies that can be found for
1109  /// that class inside a instruction.
1110  std::map<ClassInfo*, unsigned> OpClassMask;
1111
1112  for (std::vector<MatchableInfo*>::const_iterator it =
1113       Matchables.begin(), ie = Matchables.end();
1114       it != ie; ++it) {
1115    MatchableInfo &II = **it;
1116    OpClassMask.clear();
1117
1118    // Keep track of all operands of this instructions which belong to the
1119    // same class.
1120    for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
1121      MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
1122      if (Op.Class->ParserMethod.empty())
1123        continue;
1124      unsigned &OperandMask = OpClassMask[Op.Class];
1125      OperandMask |= (1 << i);
1126    }
1127
1128    // Generate operand match info for each mnemonic/operand class pair.
1129    for (std::map<ClassInfo*, unsigned>::iterator iit = OpClassMask.begin(),
1130         iie = OpClassMask.end(); iit != iie; ++iit) {
1131      unsigned OpMask = iit->second;
1132      ClassInfo *CI = iit->first;
1133      OperandMatchInfo.push_back(OperandMatchEntry::Create(&II, CI, OpMask));
1134    }
1135  }
1136}
1137
1138void AsmMatcherInfo::BuildInfo() {
1139  // Build information about all of the AssemblerPredicates.
1140  std::vector<Record*> AllPredicates =
1141    Records.getAllDerivedDefinitions("Predicate");
1142  for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
1143    Record *Pred = AllPredicates[i];
1144    // Ignore predicates that are not intended for the assembler.
1145    if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
1146      continue;
1147
1148    if (Pred->getName().empty())
1149      throw TGError(Pred->getLoc(), "Predicate has no name!");
1150
1151    unsigned FeatureNo = SubtargetFeatures.size();
1152    SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
1153    assert(FeatureNo < 32 && "Too many subtarget features!");
1154  }
1155
1156  StringRef CommentDelimiter = AsmParser->getValueAsString("CommentDelimiter");
1157
1158  // Parse the instructions; we need to do this first so that we can gather the
1159  // singleton register classes.
1160  SmallPtrSet<Record*, 16> SingletonRegisters;
1161  for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
1162       E = Target.inst_end(); I != E; ++I) {
1163    const CodeGenInstruction &CGI = **I;
1164
1165    // If the tblgen -match-prefix option is specified (for tblgen hackers),
1166    // filter the set of instructions we consider.
1167    if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
1168      continue;
1169
1170    // Ignore "codegen only" instructions.
1171    if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
1172      continue;
1173
1174    // Validate the operand list to ensure we can handle this instruction.
1175    for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1176      const CGIOperandList::OperandInfo &OI = CGI.Operands[i];
1177
1178      // Validate tied operands.
1179      if (OI.getTiedRegister() != -1) {
1180        // If we have a tied operand that consists of multiple MCOperands,
1181        // reject it.  We reject aliases and ignore instructions for now.
1182        if (OI.MINumOperands != 1) {
1183          // FIXME: Should reject these.  The ARM backend hits this with $lane
1184          // in a bunch of instructions. It is unclear what the right answer is.
1185          DEBUG({
1186            errs() << "warning: '" << CGI.TheDef->getName() << "': "
1187            << "ignoring instruction with multi-operand tied operand '"
1188            << OI.Name << "'\n";
1189          });
1190          continue;
1191        }
1192      }
1193    }
1194
1195    OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
1196
1197    II->Initialize(*this, SingletonRegisters);
1198
1199    // Ignore instructions which shouldn't be matched and diagnose invalid
1200    // instruction definitions with an error.
1201    if (!II->Validate(CommentDelimiter, true))
1202      continue;
1203
1204    // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
1205    //
1206    // FIXME: This is a total hack.
1207    if (StringRef(II->TheDef->getName()).startswith("Int_") ||
1208        StringRef(II->TheDef->getName()).endswith("_Int"))
1209      continue;
1210
1211     Matchables.push_back(II.take());
1212  }
1213
1214  // Parse all of the InstAlias definitions and stick them in the list of
1215  // matchables.
1216  std::vector<Record*> AllInstAliases =
1217    Records.getAllDerivedDefinitions("InstAlias");
1218  for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
1219    CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i], Target);
1220
1221    // If the tblgen -match-prefix option is specified (for tblgen hackers),
1222    // filter the set of instruction aliases we consider, based on the target
1223    // instruction.
1224    if (!StringRef(Alias->ResultInst->TheDef->getName()).startswith(
1225          MatchPrefix))
1226      continue;
1227
1228    OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
1229
1230    II->Initialize(*this, SingletonRegisters);
1231
1232    // Validate the alias definitions.
1233    II->Validate(CommentDelimiter, false);
1234
1235    Matchables.push_back(II.take());
1236  }
1237
1238  // Build info for the register classes.
1239  BuildRegisterClasses(SingletonRegisters);
1240
1241  // Build info for the user defined assembly operand classes.
1242  BuildOperandClasses();
1243
1244  // Build the information about matchables, now that we have fully formed
1245  // classes.
1246  for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(),
1247         ie = Matchables.end(); it != ie; ++it) {
1248    MatchableInfo *II = *it;
1249
1250    // Parse the tokens after the mnemonic.
1251    // Note: BuildInstructionOperandReference may insert new AsmOperands, so
1252    // don't precompute the loop bound.
1253    for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1254      MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
1255      StringRef Token = Op.Token;
1256
1257      // Check for singleton registers.
1258      if (Record *RegRecord = II->getSingletonRegisterForAsmOperand(i, *this)) {
1259        Op.Class = RegisterClasses[RegRecord];
1260        assert(Op.Class && Op.Class->Registers.size() == 1 &&
1261               "Unexpected class for singleton register");
1262        continue;
1263      }
1264
1265      // Check for simple tokens.
1266      if (Token[0] != '$') {
1267        Op.Class = getTokenClass(Token);
1268        continue;
1269      }
1270
1271      if (Token.size() > 1 && isdigit(Token[1])) {
1272        Op.Class = getTokenClass(Token);
1273        continue;
1274      }
1275
1276      // Otherwise this is an operand reference.
1277      StringRef OperandName;
1278      if (Token[1] == '{')
1279        OperandName = Token.substr(2, Token.size() - 3);
1280      else
1281        OperandName = Token.substr(1);
1282
1283      if (II->DefRec.is<const CodeGenInstruction*>())
1284        BuildInstructionOperandReference(II, OperandName, i);
1285      else
1286        BuildAliasOperandReference(II, OperandName, Op);
1287    }
1288
1289    if (II->DefRec.is<const CodeGenInstruction*>())
1290      II->BuildInstructionResultOperands();
1291    else
1292      II->BuildAliasResultOperands();
1293  }
1294
1295  // Reorder classes so that classes precede super classes.
1296  std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
1297}
1298
1299/// BuildInstructionOperandReference - The specified operand is a reference to a
1300/// named operand such as $src.  Resolve the Class and OperandInfo pointers.
1301void AsmMatcherInfo::
1302BuildInstructionOperandReference(MatchableInfo *II,
1303                                 StringRef OperandName,
1304                                 unsigned AsmOpIdx) {
1305  const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1306  const CGIOperandList &Operands = CGI.Operands;
1307  MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
1308
1309  // Map this token to an operand.
1310  unsigned Idx;
1311  if (!Operands.hasOperandNamed(OperandName, Idx))
1312    throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1313                  OperandName.str() + "'");
1314
1315  // If the instruction operand has multiple suboperands, but the parser
1316  // match class for the asm operand is still the default "ImmAsmOperand",
1317  // then handle each suboperand separately.
1318  if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1319    Record *Rec = Operands[Idx].Rec;
1320    assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1321    Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1322    if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1323      // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1324      StringRef Token = Op->Token; // save this in case Op gets moved
1325      for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1326        MatchableInfo::AsmOperand NewAsmOp(Token);
1327        NewAsmOp.SubOpIdx = SI;
1328        II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1329      }
1330      // Replace Op with first suboperand.
1331      Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1332      Op->SubOpIdx = 0;
1333    }
1334  }
1335
1336  // Set up the operand class.
1337  Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
1338
1339  // If the named operand is tied, canonicalize it to the untied operand.
1340  // For example, something like:
1341  //   (outs GPR:$dst), (ins GPR:$src)
1342  // with an asmstring of
1343  //   "inc $src"
1344  // we want to canonicalize to:
1345  //   "inc $dst"
1346  // so that we know how to provide the $dst operand when filling in the result.
1347  int OITied = Operands[Idx].getTiedRegister();
1348  if (OITied != -1) {
1349    // The tied operand index is an MIOperand index, find the operand that
1350    // contains it.
1351    std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1352    OperandName = Operands[Idx.first].Name;
1353    Op->SubOpIdx = Idx.second;
1354  }
1355
1356  Op->SrcOpName = OperandName;
1357}
1358
1359/// BuildAliasOperandReference - When parsing an operand reference out of the
1360/// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1361/// operand reference is by looking it up in the result pattern definition.
1362void AsmMatcherInfo::BuildAliasOperandReference(MatchableInfo *II,
1363                                                StringRef OperandName,
1364                                                MatchableInfo::AsmOperand &Op) {
1365  const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
1366
1367  // Set up the operand class.
1368  for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
1369    if (CGA.ResultOperands[i].isRecord() &&
1370        CGA.ResultOperands[i].getName() == OperandName) {
1371      // It's safe to go with the first one we find, because CodeGenInstAlias
1372      // validates that all operands with the same name have the same record.
1373      unsigned ResultIdx = CGA.ResultInstOperandIndex[i].first;
1374      Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
1375      Op.Class = getOperandClass(CGA.ResultInst->Operands[ResultIdx],
1376                                 Op.SubOpIdx);
1377      Op.SrcOpName = OperandName;
1378      return;
1379    }
1380
1381  throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1382                OperandName.str() + "'");
1383}
1384
1385void MatchableInfo::BuildInstructionResultOperands() {
1386  const CodeGenInstruction *ResultInst = getResultInst();
1387
1388  // Loop over all operands of the result instruction, determining how to
1389  // populate them.
1390  for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1391    const CGIOperandList::OperandInfo &OpInfo = ResultInst->Operands[i];
1392
1393    // If this is a tied operand, just copy from the previously handled operand.
1394    int TiedOp = OpInfo.getTiedRegister();
1395    if (TiedOp != -1) {
1396      ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1397      continue;
1398    }
1399
1400    // Find out what operand from the asmparser this MCInst operand comes from.
1401    int SrcOperand = FindAsmOperandNamed(OpInfo.Name);
1402    if (OpInfo.Name.empty() || SrcOperand == -1)
1403      throw TGError(TheDef->getLoc(), "Instruction '" +
1404                    TheDef->getName() + "' has operand '" + OpInfo.Name +
1405                    "' that doesn't appear in asm string!");
1406
1407    // Check if the one AsmOperand populates the entire operand.
1408    unsigned NumOperands = OpInfo.MINumOperands;
1409    if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1410      ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
1411      continue;
1412    }
1413
1414    // Add a separate ResOperand for each suboperand.
1415    for (unsigned AI = 0; AI < NumOperands; ++AI) {
1416      assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1417             AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1418             "unexpected AsmOperands for suboperands");
1419      ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1420    }
1421  }
1422}
1423
1424void MatchableInfo::BuildAliasResultOperands() {
1425  const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1426  const CodeGenInstruction *ResultInst = getResultInst();
1427
1428  // Loop over all operands of the result instruction, determining how to
1429  // populate them.
1430  unsigned AliasOpNo = 0;
1431  unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
1432  for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1433    const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
1434
1435    // If this is a tied operand, just copy from the previously handled operand.
1436    int TiedOp = OpInfo->getTiedRegister();
1437    if (TiedOp != -1) {
1438      ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1439      continue;
1440    }
1441
1442    // Handle all the suboperands for this operand.
1443    const std::string &OpName = OpInfo->Name;
1444    for ( ; AliasOpNo <  LastOpNo &&
1445            CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1446      int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1447
1448      // Find out what operand from the asmparser that this MCInst operand
1449      // comes from.
1450      switch (CGA.ResultOperands[AliasOpNo].Kind) {
1451      default: assert(0 && "unexpected InstAlias operand kind");
1452      case CodeGenInstAlias::ResultOperand::K_Record: {
1453        StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1454        int SrcOperand = FindAsmOperand(Name, SubIdx);
1455        if (SrcOperand == -1)
1456          throw TGError(TheDef->getLoc(), "Instruction '" +
1457                        TheDef->getName() + "' has operand '" + OpName +
1458                        "' that doesn't appear in asm string!");
1459        unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1460        ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1461                                                        NumOperands));
1462        break;
1463      }
1464      case CodeGenInstAlias::ResultOperand::K_Imm: {
1465        int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1466        ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1467        break;
1468      }
1469      case CodeGenInstAlias::ResultOperand::K_Reg: {
1470        Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1471        ResOperands.push_back(ResOperand::getRegOp(Reg));
1472        break;
1473      }
1474      }
1475    }
1476  }
1477}
1478
1479static void EmitConvertToMCInst(CodeGenTarget &Target, StringRef ClassName,
1480                                std::vector<MatchableInfo*> &Infos,
1481                                raw_ostream &OS) {
1482  // Write the convert function to a separate stream, so we can drop it after
1483  // the enum.
1484  std::string ConvertFnBody;
1485  raw_string_ostream CvtOS(ConvertFnBody);
1486
1487  // Function we have already generated.
1488  std::set<std::string> GeneratedFns;
1489
1490  // Start the unified conversion function.
1491  CvtOS << "bool " << Target.getName() << ClassName << "::\n";
1492  CvtOS << "ConvertToMCInst(unsigned Kind, MCInst &Inst, "
1493        << "unsigned Opcode,\n"
1494        << "                      const SmallVectorImpl<MCParsedAsmOperand*"
1495        << "> &Operands) {\n";
1496  CvtOS << "  Inst.setOpcode(Opcode);\n";
1497  CvtOS << "  switch (Kind) {\n";
1498  CvtOS << "  default:\n";
1499
1500  // Start the enum, which we will generate inline.
1501
1502  OS << "// Unified function for converting operands to MCInst instances.\n\n";
1503  OS << "enum ConversionKind {\n";
1504
1505  // TargetOperandClass - This is the target's operand class, like X86Operand.
1506  std::string TargetOperandClass = Target.getName() + "Operand";
1507
1508  for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(),
1509         ie = Infos.end(); it != ie; ++it) {
1510    MatchableInfo &II = **it;
1511
1512    // Check if we have a custom match function.
1513    std::string AsmMatchConverter =
1514      II.getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
1515    if (!AsmMatchConverter.empty()) {
1516      std::string Signature = "ConvertCustom_" + AsmMatchConverter;
1517      II.ConversionFnKind = Signature;
1518
1519      // Check if we have already generated this signature.
1520      if (!GeneratedFns.insert(Signature).second)
1521        continue;
1522
1523      // If not, emit it now.  Add to the enum list.
1524      OS << "  " << Signature << ",\n";
1525
1526      CvtOS << "  case " << Signature << ":\n";
1527      CvtOS << "    return " << AsmMatchConverter
1528            << "(Inst, Opcode, Operands);\n";
1529      continue;
1530    }
1531
1532    // Build the conversion function signature.
1533    std::string Signature = "Convert";
1534    std::string CaseBody;
1535    raw_string_ostream CaseOS(CaseBody);
1536
1537    // Compute the convert enum and the case body.
1538    for (unsigned i = 0, e = II.ResOperands.size(); i != e; ++i) {
1539      const MatchableInfo::ResOperand &OpInfo = II.ResOperands[i];
1540
1541      // Generate code to populate each result operand.
1542      switch (OpInfo.Kind) {
1543      case MatchableInfo::ResOperand::RenderAsmOperand: {
1544        // This comes from something we parsed.
1545        MatchableInfo::AsmOperand &Op = II.AsmOperands[OpInfo.AsmOperandNum];
1546
1547        // Registers are always converted the same, don't duplicate the
1548        // conversion function based on them.
1549        Signature += "__";
1550        if (Op.Class->isRegisterClass())
1551          Signature += "Reg";
1552        else
1553          Signature += Op.Class->ClassName;
1554        Signature += utostr(OpInfo.MINumOperands);
1555        Signature += "_" + itostr(OpInfo.AsmOperandNum);
1556
1557        CaseOS << "    ((" << TargetOperandClass << "*)Operands["
1558               << (OpInfo.AsmOperandNum+1) << "])->" << Op.Class->RenderMethod
1559               << "(Inst, " << OpInfo.MINumOperands << ");\n";
1560        break;
1561      }
1562
1563      case MatchableInfo::ResOperand::TiedOperand: {
1564        // If this operand is tied to a previous one, just copy the MCInst
1565        // operand from the earlier one.We can only tie single MCOperand values.
1566        //assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
1567        unsigned TiedOp = OpInfo.TiedOperandNum;
1568        assert(i > TiedOp && "Tied operand precedes its target!");
1569        CaseOS << "    Inst.addOperand(Inst.getOperand(" << TiedOp << "));\n";
1570        Signature += "__Tie" + utostr(TiedOp);
1571        break;
1572      }
1573      case MatchableInfo::ResOperand::ImmOperand: {
1574        int64_t Val = OpInfo.ImmVal;
1575        CaseOS << "    Inst.addOperand(MCOperand::CreateImm(" << Val << "));\n";
1576        Signature += "__imm" + itostr(Val);
1577        break;
1578      }
1579      case MatchableInfo::ResOperand::RegOperand: {
1580        if (OpInfo.Register == 0) {
1581          CaseOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
1582          Signature += "__reg0";
1583        } else {
1584          std::string N = getQualifiedName(OpInfo.Register);
1585          CaseOS << "    Inst.addOperand(MCOperand::CreateReg(" << N << "));\n";
1586          Signature += "__reg" + OpInfo.Register->getName();
1587        }
1588      }
1589      }
1590    }
1591
1592    II.ConversionFnKind = Signature;
1593
1594    // Check if we have already generated this signature.
1595    if (!GeneratedFns.insert(Signature).second)
1596      continue;
1597
1598    // If not, emit it now.  Add to the enum list.
1599    OS << "  " << Signature << ",\n";
1600
1601    CvtOS << "  case " << Signature << ":\n";
1602    CvtOS << CaseOS.str();
1603    CvtOS << "    return true;\n";
1604  }
1605
1606  // Finish the convert function.
1607
1608  CvtOS << "  }\n";
1609  CvtOS << "  return false;\n";
1610  CvtOS << "}\n\n";
1611
1612  // Finish the enum, and drop the convert function after it.
1613
1614  OS << "  NumConversionVariants\n";
1615  OS << "};\n\n";
1616
1617  OS << CvtOS.str();
1618}
1619
1620/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1621static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1622                                      std::vector<ClassInfo*> &Infos,
1623                                      raw_ostream &OS) {
1624  OS << "namespace {\n\n";
1625
1626  OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1627     << "/// instruction matching.\n";
1628  OS << "enum MatchClassKind {\n";
1629  OS << "  InvalidMatchClass = 0,\n";
1630  for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1631         ie = Infos.end(); it != ie; ++it) {
1632    ClassInfo &CI = **it;
1633    OS << "  " << CI.Name << ", // ";
1634    if (CI.Kind == ClassInfo::Token) {
1635      OS << "'" << CI.ValueName << "'\n";
1636    } else if (CI.isRegisterClass()) {
1637      if (!CI.ValueName.empty())
1638        OS << "register class '" << CI.ValueName << "'\n";
1639      else
1640        OS << "derived register class\n";
1641    } else {
1642      OS << "user defined class '" << CI.ValueName << "'\n";
1643    }
1644  }
1645  OS << "  NumMatchClassKinds\n";
1646  OS << "};\n\n";
1647
1648  OS << "}\n\n";
1649}
1650
1651/// EmitValidateOperandClass - Emit the function to validate an operand class.
1652static void EmitValidateOperandClass(AsmMatcherInfo &Info,
1653                                     raw_ostream &OS) {
1654  OS << "static bool ValidateOperandClass(MCParsedAsmOperand *GOp, "
1655     << "MatchClassKind Kind) {\n";
1656  OS << "  " << Info.Target.getName() << "Operand &Operand = *("
1657     << Info.Target.getName() << "Operand*)GOp;\n";
1658
1659  // Check for Token operands first.
1660  OS << "  if (Operand.isToken())\n";
1661  OS << "    return MatchTokenString(Operand.getToken()) == Kind;\n\n";
1662
1663  // Check for register operands, including sub-classes.
1664  OS << "  if (Operand.isReg()) {\n";
1665  OS << "    MatchClassKind OpKind;\n";
1666  OS << "    switch (Operand.getReg()) {\n";
1667  OS << "    default: OpKind = InvalidMatchClass; break;\n";
1668  for (std::map<Record*, ClassInfo*>::iterator
1669         it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1670       it != ie; ++it)
1671    OS << "    case " << Info.Target.getName() << "::"
1672       << it->first->getName() << ": OpKind = " << it->second->Name
1673       << "; break;\n";
1674  OS << "    }\n";
1675  OS << "    return IsSubclass(OpKind, Kind);\n";
1676  OS << "  }\n\n";
1677
1678  // Check the user classes. We don't care what order since we're only
1679  // actually matching against one of them.
1680  for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1681         ie = Info.Classes.end(); it != ie; ++it) {
1682    ClassInfo &CI = **it;
1683
1684    if (!CI.isUserClass())
1685      continue;
1686
1687    OS << "  // '" << CI.ClassName << "' class\n";
1688    OS << "  if (Kind == " << CI.Name
1689       << " && Operand." << CI.PredicateMethod << "()) {\n";
1690    OS << "    return true;\n";
1691    OS << "  }\n\n";
1692  }
1693
1694  OS << "  return false;\n";
1695  OS << "}\n\n";
1696}
1697
1698/// EmitIsSubclass - Emit the subclass predicate function.
1699static void EmitIsSubclass(CodeGenTarget &Target,
1700                           std::vector<ClassInfo*> &Infos,
1701                           raw_ostream &OS) {
1702  OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1703  OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1704  OS << "  if (A == B)\n";
1705  OS << "    return true;\n\n";
1706
1707  OS << "  switch (A) {\n";
1708  OS << "  default:\n";
1709  OS << "    return false;\n";
1710  for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1711         ie = Infos.end(); it != ie; ++it) {
1712    ClassInfo &A = **it;
1713
1714    if (A.Kind != ClassInfo::Token) {
1715      std::vector<StringRef> SuperClasses;
1716      for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1717             ie = Infos.end(); it != ie; ++it) {
1718        ClassInfo &B = **it;
1719
1720        if (&A != &B && A.isSubsetOf(B))
1721          SuperClasses.push_back(B.Name);
1722      }
1723
1724      if (SuperClasses.empty())
1725        continue;
1726
1727      OS << "\n  case " << A.Name << ":\n";
1728
1729      if (SuperClasses.size() == 1) {
1730        OS << "    return B == " << SuperClasses.back() << ";\n";
1731        continue;
1732      }
1733
1734      OS << "    switch (B) {\n";
1735      OS << "    default: return false;\n";
1736      for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1737        OS << "    case " << SuperClasses[i] << ": return true;\n";
1738      OS << "    }\n";
1739    }
1740  }
1741  OS << "  }\n";
1742  OS << "}\n\n";
1743}
1744
1745/// EmitMatchTokenString - Emit the function to match a token string to the
1746/// appropriate match class value.
1747static void EmitMatchTokenString(CodeGenTarget &Target,
1748                                 std::vector<ClassInfo*> &Infos,
1749                                 raw_ostream &OS) {
1750  // Construct the match list.
1751  std::vector<StringMatcher::StringPair> Matches;
1752  for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1753         ie = Infos.end(); it != ie; ++it) {
1754    ClassInfo &CI = **it;
1755
1756    if (CI.Kind == ClassInfo::Token)
1757      Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1758                                                  "return " + CI.Name + ";"));
1759  }
1760
1761  OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
1762
1763  StringMatcher("Name", Matches, OS).Emit();
1764
1765  OS << "  return InvalidMatchClass;\n";
1766  OS << "}\n\n";
1767}
1768
1769/// EmitMatchRegisterName - Emit the function to match a string to the target
1770/// specific register enum.
1771static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1772                                  raw_ostream &OS) {
1773  // Construct the match list.
1774  std::vector<StringMatcher::StringPair> Matches;
1775  const std::vector<CodeGenRegister*> &Regs =
1776    Target.getRegBank().getRegisters();
1777  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1778    const CodeGenRegister *Reg = Regs[i];
1779    if (Reg->TheDef->getValueAsString("AsmName").empty())
1780      continue;
1781
1782    Matches.push_back(StringMatcher::StringPair(
1783                                     Reg->TheDef->getValueAsString("AsmName"),
1784                                     "return " + utostr(Reg->EnumValue) + ";"));
1785  }
1786
1787  OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
1788
1789  StringMatcher("Name", Matches, OS).Emit();
1790
1791  OS << "  return 0;\n";
1792  OS << "}\n\n";
1793}
1794
1795/// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1796/// definitions.
1797static void EmitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
1798                                                raw_ostream &OS) {
1799  OS << "// Flags for subtarget features that participate in "
1800     << "instruction matching.\n";
1801  OS << "enum SubtargetFeatureFlag {\n";
1802  for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1803         it = Info.SubtargetFeatures.begin(),
1804         ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1805    SubtargetFeatureInfo &SFI = *it->second;
1806    OS << "  " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
1807  }
1808  OS << "  Feature_None = 0\n";
1809  OS << "};\n\n";
1810}
1811
1812/// EmitComputeAvailableFeatures - Emit the function to compute the list of
1813/// available features given a subtarget.
1814static void EmitComputeAvailableFeatures(AsmMatcherInfo &Info,
1815                                         raw_ostream &OS) {
1816  std::string ClassName =
1817    Info.AsmParser->getValueAsString("AsmParserClassName");
1818
1819  OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
1820     << "ComputeAvailableFeatures(uint64_t FB) const {\n";
1821  OS << "  unsigned Features = 0;\n";
1822  for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1823         it = Info.SubtargetFeatures.begin(),
1824         ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1825    SubtargetFeatureInfo &SFI = *it->second;
1826
1827    OS << "  if (";
1828    StringRef Conds = SFI.TheDef->getValueAsString("AssemblerCondString");
1829    std::pair<StringRef,StringRef> Comma = Conds.split(',');
1830    bool First = true;
1831    do {
1832      if (!First)
1833        OS << " && ";
1834
1835      bool Neg = false;
1836      StringRef Cond = Comma.first;
1837      if (Cond[0] == '!') {
1838        Neg = true;
1839        Cond = Cond.substr(1);
1840      }
1841
1842      OS << "((FB & " << Info.Target.getName() << "::" << Cond << ")";
1843      if (Neg)
1844        OS << " == 0";
1845      else
1846        OS << " != 0";
1847      OS << ")";
1848
1849      if (Comma.second.empty())
1850        break;
1851
1852      First = false;
1853      Comma = Comma.second.split(',');
1854    } while (true);
1855
1856    OS << ")\n";
1857    OS << "    Features |= " << SFI.getEnumName() << ";\n";
1858  }
1859  OS << "  return Features;\n";
1860  OS << "}\n\n";
1861}
1862
1863static std::string GetAliasRequiredFeatures(Record *R,
1864                                            const AsmMatcherInfo &Info) {
1865  std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
1866  std::string Result;
1867  unsigned NumFeatures = 0;
1868  for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
1869    SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
1870
1871    if (F == 0)
1872      throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
1873                    "' is not marked as an AssemblerPredicate!");
1874
1875    if (NumFeatures)
1876      Result += '|';
1877
1878    Result += F->getEnumName();
1879    ++NumFeatures;
1880  }
1881
1882  if (NumFeatures > 1)
1883    Result = '(' + Result + ')';
1884  return Result;
1885}
1886
1887/// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
1888/// emit a function for them and return true, otherwise return false.
1889static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
1890  // Ignore aliases when match-prefix is set.
1891  if (!MatchPrefix.empty())
1892    return false;
1893
1894  std::vector<Record*> Aliases =
1895    Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
1896  if (Aliases.empty()) return false;
1897
1898  OS << "static void ApplyMnemonicAliases(StringRef &Mnemonic, "
1899        "unsigned Features) {\n";
1900
1901  // Keep track of all the aliases from a mnemonic.  Use an std::map so that the
1902  // iteration order of the map is stable.
1903  std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1904
1905  for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1906    Record *R = Aliases[i];
1907    AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
1908  }
1909
1910  // Process each alias a "from" mnemonic at a time, building the code executed
1911  // by the string remapper.
1912  std::vector<StringMatcher::StringPair> Cases;
1913  for (std::map<std::string, std::vector<Record*> >::iterator
1914       I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1915       I != E; ++I) {
1916    const std::vector<Record*> &ToVec = I->second;
1917
1918    // Loop through each alias and emit code that handles each case.  If there
1919    // are two instructions without predicates, emit an error.  If there is one,
1920    // emit it last.
1921    std::string MatchCode;
1922    int AliasWithNoPredicate = -1;
1923
1924    for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1925      Record *R = ToVec[i];
1926      std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
1927
1928      // If this unconditionally matches, remember it for later and diagnose
1929      // duplicates.
1930      if (FeatureMask.empty()) {
1931        if (AliasWithNoPredicate != -1) {
1932          // We can't have two aliases from the same mnemonic with no predicate.
1933          PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1934                     "two MnemonicAliases with the same 'from' mnemonic!");
1935          throw TGError(R->getLoc(), "this is the other MnemonicAlias.");
1936        }
1937
1938        AliasWithNoPredicate = i;
1939        continue;
1940      }
1941      if (R->getValueAsString("ToMnemonic") == I->first)
1942        throw TGError(R->getLoc(), "MnemonicAlias to the same string");
1943
1944      if (!MatchCode.empty())
1945        MatchCode += "else ";
1946      MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1947      MatchCode += "  Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
1948    }
1949
1950    if (AliasWithNoPredicate != -1) {
1951      Record *R = ToVec[AliasWithNoPredicate];
1952      if (!MatchCode.empty())
1953        MatchCode += "else\n  ";
1954      MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
1955    }
1956
1957    MatchCode += "return;";
1958
1959    Cases.push_back(std::make_pair(I->first, MatchCode));
1960  }
1961
1962  StringMatcher("Mnemonic", Cases, OS).Emit();
1963  OS << "}\n\n";
1964
1965  return true;
1966}
1967
1968static void EmitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
1969                              const AsmMatcherInfo &Info, StringRef ClassName) {
1970  // Emit the static custom operand parsing table;
1971  OS << "namespace {\n";
1972  OS << "  struct OperandMatchEntry {\n";
1973  OS << "    const char *Mnemonic;\n";
1974  OS << "    unsigned OperandMask;\n";
1975  OS << "    MatchClassKind Class;\n";
1976  OS << "    unsigned RequiredFeatures;\n";
1977  OS << "  };\n\n";
1978
1979  OS << "  // Predicate for searching for an opcode.\n";
1980  OS << "  struct LessOpcodeOperand {\n";
1981  OS << "    bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
1982  OS << "      return StringRef(LHS.Mnemonic) < RHS;\n";
1983  OS << "    }\n";
1984  OS << "    bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
1985  OS << "      return LHS < StringRef(RHS.Mnemonic);\n";
1986  OS << "    }\n";
1987  OS << "    bool operator()(const OperandMatchEntry &LHS,";
1988  OS << " const OperandMatchEntry &RHS) {\n";
1989  OS << "      return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
1990  OS << "    }\n";
1991  OS << "  };\n";
1992
1993  OS << "} // end anonymous namespace.\n\n";
1994
1995  OS << "static const OperandMatchEntry OperandMatchTable["
1996     << Info.OperandMatchInfo.size() << "] = {\n";
1997
1998  OS << "  /* Mnemonic, Operand List Mask, Operand Class, Features */\n";
1999  for (std::vector<OperandMatchEntry>::const_iterator it =
2000       Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end();
2001       it != ie; ++it) {
2002    const OperandMatchEntry &OMI = *it;
2003    const MatchableInfo &II = *OMI.MI;
2004
2005    OS << "  { \"" << II.Mnemonic << "\""
2006       << ", " << OMI.OperandMask;
2007
2008    OS << " /* ";
2009    bool printComma = false;
2010    for (int i = 0, e = 31; i !=e; ++i)
2011      if (OMI.OperandMask & (1 << i)) {
2012        if (printComma)
2013          OS << ", ";
2014        OS << i;
2015        printComma = true;
2016      }
2017    OS << " */";
2018
2019    OS << ", " << OMI.CI->Name
2020       << ", ";
2021
2022    // Write the required features mask.
2023    if (!II.RequiredFeatures.empty()) {
2024      for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2025        if (i) OS << "|";
2026        OS << II.RequiredFeatures[i]->getEnumName();
2027      }
2028    } else
2029      OS << "0";
2030    OS << " },\n";
2031  }
2032  OS << "};\n\n";
2033
2034  // Emit the operand class switch to call the correct custom parser for
2035  // the found operand class.
2036  OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2037     << Target.getName() << ClassName << "::\n"
2038     << "TryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>"
2039     << " &Operands,\n                      unsigned MCK) {\n\n"
2040     << "  switch(MCK) {\n";
2041
2042  for (std::vector<ClassInfo*>::const_iterator it = Info.Classes.begin(),
2043       ie = Info.Classes.end(); it != ie; ++it) {
2044    ClassInfo *CI = *it;
2045    if (CI->ParserMethod.empty())
2046      continue;
2047    OS << "  case " << CI->Name << ":\n"
2048       << "    return " << CI->ParserMethod << "(Operands);\n";
2049  }
2050
2051  OS << "  default:\n";
2052  OS << "    return MatchOperand_NoMatch;\n";
2053  OS << "  }\n";
2054  OS << "  return MatchOperand_NoMatch;\n";
2055  OS << "}\n\n";
2056
2057  // Emit the static custom operand parser. This code is very similar with
2058  // the other matcher. Also use MatchResultTy here just in case we go for
2059  // a better error handling.
2060  OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2061     << Target.getName() << ClassName << "::\n"
2062     << "MatchOperandParserImpl(SmallVectorImpl<MCParsedAsmOperand*>"
2063     << " &Operands,\n                       StringRef Mnemonic) {\n";
2064
2065  // Emit code to get the available features.
2066  OS << "  // Get the current feature set.\n";
2067  OS << "  unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2068
2069  OS << "  // Get the next operand index.\n";
2070  OS << "  unsigned NextOpNum = Operands.size()-1;\n";
2071
2072  // Emit code to search the table.
2073  OS << "  // Search the table.\n";
2074  OS << "  std::pair<const OperandMatchEntry*, const OperandMatchEntry*>";
2075  OS << " MnemonicRange =\n";
2076  OS << "    std::equal_range(OperandMatchTable, OperandMatchTable+"
2077     << Info.OperandMatchInfo.size() << ", Mnemonic,\n"
2078     << "                     LessOpcodeOperand());\n\n";
2079
2080  OS << "  if (MnemonicRange.first == MnemonicRange.second)\n";
2081  OS << "    return MatchOperand_NoMatch;\n\n";
2082
2083  OS << "  for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2084     << "       *ie = MnemonicRange.second; it != ie; ++it) {\n";
2085
2086  OS << "    // equal_range guarantees that instruction mnemonic matches.\n";
2087  OS << "    assert(Mnemonic == it->Mnemonic);\n\n";
2088
2089  // Emit check that the required features are available.
2090  OS << "    // check if the available features match\n";
2091  OS << "    if ((AvailableFeatures & it->RequiredFeatures) "
2092     << "!= it->RequiredFeatures) {\n";
2093  OS << "      continue;\n";
2094  OS << "    }\n\n";
2095
2096  // Emit check to ensure the operand number matches.
2097  OS << "    // check if the operand in question has a custom parser.\n";
2098  OS << "    if (!(it->OperandMask & (1 << NextOpNum)))\n";
2099  OS << "      continue;\n\n";
2100
2101  // Emit call to the custom parser method
2102  OS << "    // call custom parse method to handle the operand\n";
2103  OS << "    OperandMatchResultTy Result = ";
2104  OS << "TryCustomParseOperand(Operands, it->Class);\n";
2105  OS << "    if (Result != MatchOperand_NoMatch)\n";
2106  OS << "      return Result;\n";
2107  OS << "  }\n\n";
2108
2109  OS << "  // Okay, we had no match.\n";
2110  OS << "  return MatchOperand_NoMatch;\n";
2111  OS << "}\n\n";
2112}
2113
2114void AsmMatcherEmitter::run(raw_ostream &OS) {
2115  CodeGenTarget Target(Records);
2116  Record *AsmParser = Target.getAsmParser();
2117  std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2118
2119  // Compute the information on the instructions to match.
2120  AsmMatcherInfo Info(AsmParser, Target, Records);
2121  Info.BuildInfo();
2122
2123  // Sort the instruction table using the partial order on classes. We use
2124  // stable_sort to ensure that ambiguous instructions are still
2125  // deterministically ordered.
2126  std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2127                   less_ptr<MatchableInfo>());
2128
2129  DEBUG_WITH_TYPE("instruction_info", {
2130      for (std::vector<MatchableInfo*>::iterator
2131             it = Info.Matchables.begin(), ie = Info.Matchables.end();
2132           it != ie; ++it)
2133        (*it)->dump();
2134    });
2135
2136  // Check for ambiguous matchables.
2137  DEBUG_WITH_TYPE("ambiguous_instrs", {
2138    unsigned NumAmbiguous = 0;
2139    for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) {
2140      for (unsigned j = i + 1; j != e; ++j) {
2141        MatchableInfo &A = *Info.Matchables[i];
2142        MatchableInfo &B = *Info.Matchables[j];
2143
2144        if (A.CouldMatchAmbiguouslyWith(B)) {
2145          errs() << "warning: ambiguous matchables:\n";
2146          A.dump();
2147          errs() << "\nis incomparable with:\n";
2148          B.dump();
2149          errs() << "\n\n";
2150          ++NumAmbiguous;
2151        }
2152      }
2153    }
2154    if (NumAmbiguous)
2155      errs() << "warning: " << NumAmbiguous
2156             << " ambiguous matchables!\n";
2157  });
2158
2159  // Compute the information on the custom operand parsing.
2160  Info.BuildOperandMatchInfo();
2161
2162  // Write the output.
2163
2164  EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
2165
2166  // Information for the class declaration.
2167  OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2168  OS << "#undef GET_ASSEMBLER_HEADER\n";
2169  OS << "  // This should be included into the middle of the declaration of\n";
2170  OS << "  // your subclasses implementation of TargetAsmParser.\n";
2171  OS << "  unsigned ComputeAvailableFeatures(uint64_t FeatureBits) const;\n";
2172  OS << "  enum MatchResultTy {\n";
2173  OS << "    Match_ConversionFail,\n";
2174  OS << "    Match_InvalidOperand,\n";
2175  OS << "    Match_MissingFeature,\n";
2176  OS << "    Match_MnemonicFail,\n";
2177  OS << "    Match_Success\n";
2178  OS << "  };\n";
2179  OS << "  bool ConvertToMCInst(unsigned Kind, MCInst &Inst, "
2180     << "unsigned Opcode,\n"
2181     << "                       const SmallVectorImpl<MCParsedAsmOperand*> "
2182     << "&Operands);\n";
2183  OS << "  bool MnemonicIsValid(StringRef Mnemonic);\n";
2184  OS << "  MatchResultTy MatchInstructionImpl(\n";
2185  OS << "    const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2186  OS << "    MCInst &Inst, unsigned &ErrorInfo);\n";
2187
2188  if (Info.OperandMatchInfo.size()) {
2189    OS << "\n  enum OperandMatchResultTy {\n";
2190    OS << "    MatchOperand_Success,    // operand matched successfully\n";
2191    OS << "    MatchOperand_NoMatch,    // operand did not match\n";
2192    OS << "    MatchOperand_ParseFail   // operand matched but had errors\n";
2193    OS << "  };\n";
2194    OS << "  OperandMatchResultTy MatchOperandParserImpl(\n";
2195    OS << "    SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2196    OS << "    StringRef Mnemonic);\n";
2197
2198    OS << "  OperandMatchResultTy TryCustomParseOperand(\n";
2199    OS << "    SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2200    OS << "    unsigned MCK);\n\n";
2201  }
2202
2203  OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2204
2205  OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2206  OS << "#undef GET_REGISTER_MATCHER\n\n";
2207
2208  // Emit the subtarget feature enumeration.
2209  EmitSubtargetFeatureFlagEnumeration(Info, OS);
2210
2211  // Emit the function to match a register name to number.
2212  EmitMatchRegisterName(Target, AsmParser, OS);
2213
2214  OS << "#endif // GET_REGISTER_MATCHER\n\n";
2215
2216
2217  OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2218  OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
2219
2220  // Generate the function that remaps for mnemonic aliases.
2221  bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
2222
2223  // Generate the unified function to convert operands into an MCInst.
2224  EmitConvertToMCInst(Target, ClassName, Info.Matchables, OS);
2225
2226  // Emit the enumeration for classes which participate in matching.
2227  EmitMatchClassEnumeration(Target, Info.Classes, OS);
2228
2229  // Emit the routine to match token strings to their match class.
2230  EmitMatchTokenString(Target, Info.Classes, OS);
2231
2232  // Emit the subclass predicate routine.
2233  EmitIsSubclass(Target, Info.Classes, OS);
2234
2235  // Emit the routine to validate an operand against a match class.
2236  EmitValidateOperandClass(Info, OS);
2237
2238  // Emit the available features compute function.
2239  EmitComputeAvailableFeatures(Info, OS);
2240
2241
2242  size_t MaxNumOperands = 0;
2243  for (std::vector<MatchableInfo*>::const_iterator it =
2244         Info.Matchables.begin(), ie = Info.Matchables.end();
2245       it != ie; ++it)
2246    MaxNumOperands = std::max(MaxNumOperands, (*it)->AsmOperands.size());
2247
2248  // Emit the static match table; unused classes get initalized to 0 which is
2249  // guaranteed to be InvalidMatchClass.
2250  //
2251  // FIXME: We can reduce the size of this table very easily. First, we change
2252  // it so that store the kinds in separate bit-fields for each index, which
2253  // only needs to be the max width used for classes at that index (we also need
2254  // to reject based on this during classification). If we then make sure to
2255  // order the match kinds appropriately (putting mnemonics last), then we
2256  // should only end up using a few bits for each class, especially the ones
2257  // following the mnemonic.
2258  OS << "namespace {\n";
2259  OS << "  struct MatchEntry {\n";
2260  OS << "    unsigned Opcode;\n";
2261  OS << "    const char *Mnemonic;\n";
2262  OS << "    ConversionKind ConvertFn;\n";
2263  OS << "    MatchClassKind Classes[" << MaxNumOperands << "];\n";
2264  OS << "    unsigned RequiredFeatures;\n";
2265  OS << "  };\n\n";
2266
2267  OS << "  // Predicate for searching for an opcode.\n";
2268  OS << "  struct LessOpcode {\n";
2269  OS << "    bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
2270  OS << "      return StringRef(LHS.Mnemonic) < RHS;\n";
2271  OS << "    }\n";
2272  OS << "    bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
2273  OS << "      return LHS < StringRef(RHS.Mnemonic);\n";
2274  OS << "    }\n";
2275  OS << "    bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
2276  OS << "      return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
2277  OS << "    }\n";
2278  OS << "  };\n";
2279
2280  OS << "} // end anonymous namespace.\n\n";
2281
2282  OS << "static const MatchEntry MatchTable["
2283     << Info.Matchables.size() << "] = {\n";
2284
2285  for (std::vector<MatchableInfo*>::const_iterator it =
2286       Info.Matchables.begin(), ie = Info.Matchables.end();
2287       it != ie; ++it) {
2288    MatchableInfo &II = **it;
2289
2290    OS << "  { " << Target.getName() << "::"
2291       << II.getResultInst()->TheDef->getName() << ", \"" << II.Mnemonic << "\""
2292       << ", " << II.ConversionFnKind << ", { ";
2293    for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
2294      MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
2295
2296      if (i) OS << ", ";
2297      OS << Op.Class->Name;
2298    }
2299    OS << " }, ";
2300
2301    // Write the required features mask.
2302    if (!II.RequiredFeatures.empty()) {
2303      for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2304        if (i) OS << "|";
2305        OS << II.RequiredFeatures[i]->getEnumName();
2306      }
2307    } else
2308      OS << "0";
2309
2310    OS << "},\n";
2311  }
2312
2313  OS << "};\n\n";
2314
2315  // A method to determine if a mnemonic is in the list.
2316  OS << "bool " << Target.getName() << ClassName << "::\n"
2317     << "MnemonicIsValid(StringRef Mnemonic) {\n";
2318  OS << "  // Search the table.\n";
2319  OS << "  std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2320  OS << "    std::equal_range(MatchTable, MatchTable+"
2321     << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n";
2322  OS << "  return MnemonicRange.first != MnemonicRange.second;\n";
2323  OS << "}\n\n";
2324
2325  // Finally, build the match function.
2326  OS << Target.getName() << ClassName << "::MatchResultTy "
2327     << Target.getName() << ClassName << "::\n"
2328     << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
2329     << " &Operands,\n";
2330  OS << "                     MCInst &Inst, unsigned &ErrorInfo) {\n";
2331
2332  // Emit code to get the available features.
2333  OS << "  // Get the current feature set.\n";
2334  OS << "  unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2335
2336  OS << "  // Get the instruction mnemonic, which is the first token.\n";
2337  OS << "  StringRef Mnemonic = ((" << Target.getName()
2338     << "Operand*)Operands[0])->getToken();\n\n";
2339
2340  if (HasMnemonicAliases) {
2341    OS << "  // Process all MnemonicAliases to remap the mnemonic.\n";
2342    OS << "  ApplyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
2343  }
2344
2345  // Emit code to compute the class list for this operand vector.
2346  OS << "  // Eliminate obvious mismatches.\n";
2347  OS << "  if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
2348  OS << "    ErrorInfo = " << (MaxNumOperands+1) << ";\n";
2349  OS << "    return Match_InvalidOperand;\n";
2350  OS << "  }\n\n";
2351
2352  OS << "  // Some state to try to produce better error messages.\n";
2353  OS << "  bool HadMatchOtherThanFeatures = false;\n\n";
2354  OS << "  // Set ErrorInfo to the operand that mismatches if it is\n";
2355  OS << "  // wrong for all instances of the instruction.\n";
2356  OS << "  ErrorInfo = ~0U;\n";
2357
2358  // Emit code to search the table.
2359  OS << "  // Search the table.\n";
2360  OS << "  std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2361  OS << "    std::equal_range(MatchTable, MatchTable+"
2362     << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n";
2363
2364  OS << "  // Return a more specific error code if no mnemonics match.\n";
2365  OS << "  if (MnemonicRange.first == MnemonicRange.second)\n";
2366  OS << "    return Match_MnemonicFail;\n\n";
2367
2368  OS << "  for (const MatchEntry *it = MnemonicRange.first, "
2369     << "*ie = MnemonicRange.second;\n";
2370  OS << "       it != ie; ++it) {\n";
2371
2372  OS << "    // equal_range guarantees that instruction mnemonic matches.\n";
2373  OS << "    assert(Mnemonic == it->Mnemonic);\n";
2374
2375  // Emit check that the subclasses match.
2376  OS << "    bool OperandsValid = true;\n";
2377  OS << "    for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
2378  OS << "      if (i + 1 >= Operands.size()) {\n";
2379  OS << "        OperandsValid = (it->Classes[i] == " <<"InvalidMatchClass);\n";
2380  OS << "        break;\n";
2381  OS << "      }\n";
2382  OS << "      if (ValidateOperandClass(Operands[i+1], it->Classes[i]))\n";
2383  OS << "        continue;\n";
2384  OS << "      // If this operand is broken for all of the instances of this\n";
2385  OS << "      // mnemonic, keep track of it so we can report loc info.\n";
2386  OS << "      if (it == MnemonicRange.first || ErrorInfo <= i+1)\n";
2387  OS << "        ErrorInfo = i+1;\n";
2388  OS << "      // Otherwise, just reject this instance of the mnemonic.\n";
2389  OS << "      OperandsValid = false;\n";
2390  OS << "      break;\n";
2391  OS << "    }\n\n";
2392
2393  OS << "    if (!OperandsValid) continue;\n";
2394
2395  // Emit check that the required features are available.
2396  OS << "    if ((AvailableFeatures & it->RequiredFeatures) "
2397     << "!= it->RequiredFeatures) {\n";
2398  OS << "      HadMatchOtherThanFeatures = true;\n";
2399  OS << "      continue;\n";
2400  OS << "    }\n";
2401  OS << "\n";
2402  OS << "    // We have selected a definite instruction, convert the parsed\n"
2403     << "    // operands into the appropriate MCInst.\n";
2404  OS << "    if (!ConvertToMCInst(it->ConvertFn, Inst,\n"
2405     << "                         it->Opcode, Operands))\n";
2406  OS << "      return Match_ConversionFail;\n";
2407  OS << "\n";
2408
2409  // Call the post-processing function, if used.
2410  std::string InsnCleanupFn =
2411    AsmParser->getValueAsString("AsmParserInstCleanup");
2412  if (!InsnCleanupFn.empty())
2413    OS << "    " << InsnCleanupFn << "(Inst);\n";
2414
2415  OS << "    return Match_Success;\n";
2416  OS << "  }\n\n";
2417
2418  OS << "  // Okay, we had no match.  Try to return a useful error code.\n";
2419  OS << "  if (HadMatchOtherThanFeatures) return Match_MissingFeature;\n";
2420  OS << "  return Match_InvalidOperand;\n";
2421  OS << "}\n\n";
2422
2423  if (Info.OperandMatchInfo.size())
2424    EmitCustomOperandParsing(OS, Target, Info, ClassName);
2425
2426  OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
2427}
2428