AsmMatcherEmitter.cpp revision 2b54481a77696d47dc9220cd7a36155599750904
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.
12//
13// The input to the target specific matcher is a list of literal tokens and
14// operands. The target specific parser should generally eliminate any syntax
15// which is not relevant for matching; for example, comma tokens should have
16// already been consumed and eliminated by the parser. Most instructions will
17// end up with a single literal token (the instruction name) and some number of
18// operands.
19//
20// Some example inputs, for X86:
21//   'addl' (immediate ...) (register ...)
22//   'add' (immediate ...) (memory ...)
23//   'call' '*' %epc
24//
25// The assembly matcher is responsible for converting this input into a precise
26// machine instruction (i.e., an instruction with a well defined encoding). This
27// mapping has several properties which complicate matching:
28//
29//  - It may be ambiguous; many architectures can legally encode particular
30//    variants of an instruction in different ways (for example, using a smaller
31//    encoding for small immediates). Such ambiguities should never be
32//    arbitrarily resolved by the assembler, the assembler is always responsible
33//    for choosing the "best" available instruction.
34//
35//  - It may depend on the subtarget or the assembler context. Instructions
36//    which are invalid for the current mode, but otherwise unambiguous (e.g.,
37//    an SSE instruction in a file being assembled for i486) should be accepted
38//    and rejected by the assembler front end. However, if the proper encoding
39//    for an instruction is dependent on the assembler context then the matcher
40//    is responsible for selecting the correct machine instruction for the
41//    current mode.
42//
43// The core matching algorithm attempts to exploit the regularity in most
44// instruction sets to quickly determine the set of possibly matching
45// instructions, and the simplify the generated code. Additionally, this helps
46// to ensure that the ambiguities are intentionally resolved by the user.
47//
48// The matching is divided into two distinct phases:
49//
50//   1. Classification: Each operand is mapped to the unique set which (a)
51//      contains it, and (b) is the largest such subset for which a single
52//      instruction could match all members.
53//
54//      For register classes, we can generate these subgroups automatically. For
55//      arbitrary operands, we expect the user to define the classes and their
56//      relations to one another (for example, 8-bit signed immediates as a
57//      subset of 32-bit immediates).
58//
59//      By partitioning the operands in this way, we guarantee that for any
60//      tuple of classes, any single instruction must match either all or none
61//      of the sets of operands which could classify to that tuple.
62//
63//      In addition, the subset relation amongst classes induces a partial order
64//      on such tuples, which we use to resolve ambiguities.
65//
66//      FIXME: What do we do if a crazy case shows up where this is the wrong
67//      resolution?
68//
69//   2. The input can now be treated as a tuple of classes (static tokens are
70//      simple singleton sets). Each such tuple should generally map to a single
71//      instruction (we currently ignore cases where this isn't true, whee!!!),
72//      which we can emit a simple matcher for.
73//
74//===----------------------------------------------------------------------===//
75
76#include "AsmMatcherEmitter.h"
77#include "CodeGenTarget.h"
78#include "Record.h"
79#include "llvm/ADT/OwningPtr.h"
80#include "llvm/ADT/SmallVector.h"
81#include "llvm/ADT/STLExtras.h"
82#include "llvm/ADT/StringExtras.h"
83#include "llvm/Support/CommandLine.h"
84#include "llvm/Support/Debug.h"
85#include <list>
86#include <map>
87#include <set>
88using namespace llvm;
89
90namespace {
91static cl::opt<std::string>
92MatchPrefix("match-prefix", cl::init(""),
93            cl::desc("Only match instructions with the given prefix"));
94}
95
96/// FlattenVariants - Flatten an .td file assembly string by selecting the
97/// variant at index \arg N.
98static std::string FlattenVariants(const std::string &AsmString,
99                                   unsigned N) {
100  StringRef Cur = AsmString;
101  std::string Res = "";
102
103  for (;;) {
104    // Find the start of the next variant string.
105    size_t VariantsStart = 0;
106    for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
107      if (Cur[VariantsStart] == '{' &&
108          (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
109                                  Cur[VariantsStart-1] != '\\')))
110        break;
111
112    // Add the prefix to the result.
113    Res += Cur.slice(0, VariantsStart);
114    if (VariantsStart == Cur.size())
115      break;
116
117    ++VariantsStart; // Skip the '{'.
118
119    // Scan to the end of the variants string.
120    size_t VariantsEnd = VariantsStart;
121    unsigned NestedBraces = 1;
122    for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
123      if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
124        if (--NestedBraces == 0)
125          break;
126      } else if (Cur[VariantsEnd] == '{')
127        ++NestedBraces;
128    }
129
130    // Select the Nth variant (or empty).
131    StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
132    for (unsigned i = 0; i != N; ++i)
133      Selection = Selection.split('|').second;
134    Res += Selection.split('|').first;
135
136    assert(VariantsEnd != Cur.size() &&
137           "Unterminated variants in assembly string!");
138    Cur = Cur.substr(VariantsEnd + 1);
139  }
140
141  return Res;
142}
143
144/// TokenizeAsmString - Tokenize a simplified assembly string.
145static void TokenizeAsmString(const StringRef &AsmString,
146                              SmallVectorImpl<StringRef> &Tokens) {
147  unsigned Prev = 0;
148  bool InTok = true;
149  for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {
150    switch (AsmString[i]) {
151    case '[':
152    case ']':
153    case '*':
154    case '!':
155    case ' ':
156    case '\t':
157    case ',':
158      if (InTok) {
159        Tokens.push_back(AsmString.slice(Prev, i));
160        InTok = false;
161      }
162      if (!isspace(AsmString[i]) && AsmString[i] != ',')
163        Tokens.push_back(AsmString.substr(i, 1));
164      Prev = i + 1;
165      break;
166
167    case '\\':
168      if (InTok) {
169        Tokens.push_back(AsmString.slice(Prev, i));
170        InTok = false;
171      }
172      ++i;
173      assert(i != AsmString.size() && "Invalid quoted character");
174      Tokens.push_back(AsmString.substr(i, 1));
175      Prev = i + 1;
176      break;
177
178    case '$': {
179      // If this isn't "${", treat like a normal token.
180      if (i + 1 == AsmString.size() || AsmString[i + 1] != '{') {
181        if (InTok) {
182          Tokens.push_back(AsmString.slice(Prev, i));
183          InTok = false;
184        }
185        Prev = i;
186        break;
187      }
188
189      if (InTok) {
190        Tokens.push_back(AsmString.slice(Prev, i));
191        InTok = false;
192      }
193
194      StringRef::iterator End =
195        std::find(AsmString.begin() + i, AsmString.end(), '}');
196      assert(End != AsmString.end() && "Missing brace in operand reference!");
197      size_t EndPos = End - AsmString.begin();
198      Tokens.push_back(AsmString.slice(i, EndPos+1));
199      Prev = EndPos + 1;
200      i = EndPos;
201      break;
202    }
203
204    default:
205      InTok = true;
206    }
207  }
208  if (InTok && Prev != AsmString.size())
209    Tokens.push_back(AsmString.substr(Prev));
210}
211
212static bool IsAssemblerInstruction(const StringRef &Name,
213                                   const CodeGenInstruction &CGI,
214                                   const SmallVectorImpl<StringRef> &Tokens) {
215  // Ignore psuedo ops.
216  //
217  // FIXME: This is a hack.
218  if (const RecordVal *Form = CGI.TheDef->getValue("Form"))
219    if (Form->getValue()->getAsString() == "Pseudo")
220      return false;
221
222  // Ignore "PHI" node.
223  //
224  // FIXME: This is also a hack.
225  if (Name == "PHI")
226    return false;
227
228  // Ignore instructions with no .s string.
229  //
230  // FIXME: What are these?
231  if (CGI.AsmString.empty())
232    return false;
233
234  // FIXME: Hack; ignore any instructions with a newline in them.
235  if (std::find(CGI.AsmString.begin(),
236                CGI.AsmString.end(), '\n') != CGI.AsmString.end())
237    return false;
238
239  // Ignore instructions with attributes, these are always fake instructions for
240  // simplifying codegen.
241  //
242  // FIXME: Is this true?
243  //
244  // Also, we ignore instructions which reference the operand multiple times;
245  // this implies a constraint we would not currently honor. These are
246  // currently always fake instructions for simplifying codegen.
247  //
248  // FIXME: Encode this assumption in the .td, so we can error out here.
249  std::set<std::string> OperandNames;
250  for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
251    if (Tokens[i][0] == '$' &&
252        std::find(Tokens[i].begin(),
253                  Tokens[i].end(), ':') != Tokens[i].end()) {
254      DEBUG({
255          errs() << "warning: '" << Name << "': "
256                 << "ignoring instruction; operand with attribute '"
257                 << Tokens[i] << "', \n";
258        });
259      return false;
260    }
261
262    if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
263      DEBUG({
264          errs() << "warning: '" << Name << "': "
265                 << "ignoring instruction; tied operand '"
266                 << Tokens[i] << "'\n";
267        });
268      return false;
269    }
270  }
271
272  return true;
273}
274
275namespace {
276
277/// ClassInfo - Helper class for storing the information about a particular
278/// class of operands which can be matched.
279struct ClassInfo {
280  enum ClassInfoKind {
281    Invalid = 0, ///< Invalid kind, for use as a sentinel value.
282    Token,       ///< The class for a particular token.
283    Register,    ///< A register class.
284    UserClass0   ///< The (first) user defined class, subsequent user defined
285                 /// classes are UserClass0+1, and so on.
286  };
287
288  /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
289  /// N) for the Nth user defined class.
290  unsigned Kind;
291
292  /// Name - The full class name, suitable for use in an enum.
293  std::string Name;
294
295  /// ClassName - The unadorned generic name for this class (e.g., Token).
296  std::string ClassName;
297
298  /// ValueName - The name of the value this class represents; for a token this
299  /// is the literal token string, for an operand it is the TableGen class (or
300  /// empty if this is a derived class).
301  std::string ValueName;
302
303  /// PredicateMethod - The name of the operand method to test whether the
304  /// operand matches this class; this is not valid for Token kinds.
305  std::string PredicateMethod;
306
307  /// RenderMethod - The name of the operand method to add this operand to an
308  /// MCInst; this is not valid for Token kinds.
309  std::string RenderMethod;
310
311  /// operator< - Compare two classes.
312  bool operator<(const ClassInfo &RHS) const {
313    // Incompatible kinds are comparable.
314    if (Kind != RHS.Kind)
315      return Kind < RHS.Kind;
316
317    switch (Kind) {
318    case Invalid:
319      assert(0 && "Invalid kind!");
320    case Token:
321      // Tokens are always comparable.
322      //
323      // FIXME: Compare by enum value.
324      return ValueName < RHS.ValueName;
325
326    case Register:
327      // FIXME: Compare by subset relation.
328      return false;
329
330    default:
331      // FIXME: Allow user defined relation.
332      return false;
333    }
334  }
335};
336
337/// InstructionInfo - Helper class for storing the necessary information for an
338/// instruction which is capable of being matched.
339struct InstructionInfo {
340  struct Operand {
341    /// The unique class instance this operand should match.
342    ClassInfo *Class;
343
344    /// The original operand this corresponds to, if any.
345    const CodeGenInstruction::OperandInfo *OperandInfo;
346  };
347
348  /// InstrName - The target name for this instruction.
349  std::string InstrName;
350
351  /// Instr - The instruction this matches.
352  const CodeGenInstruction *Instr;
353
354  /// AsmString - The assembly string for this instruction (with variants
355  /// removed).
356  std::string AsmString;
357
358  /// Tokens - The tokenized assembly pattern that this instruction matches.
359  SmallVector<StringRef, 4> Tokens;
360
361  /// Operands - The operands that this instruction matches.
362  SmallVector<Operand, 4> Operands;
363
364  /// ConversionFnKind - The enum value which is passed to the generated
365  /// ConvertToMCInst to convert parsed operands into an MCInst for this
366  /// function.
367  std::string ConversionFnKind;
368
369  /// operator< - Compare two instructions.
370  bool operator<(const InstructionInfo &RHS) const {
371    if (Operands.size() != RHS.Operands.size())
372      return Operands.size() < RHS.Operands.size();
373
374    for (unsigned i = 0, e = Operands.size(); i != e; ++i)
375      if (*Operands[i].Class < *RHS.Operands[i].Class)
376        return true;
377
378    return false;
379  }
380
381  /// CouldMatchAmiguouslyWith - Check whether this instruction could
382  /// ambiguously match the same set of operands as \arg RHS (without being a
383  /// strictly superior match).
384  bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
385    // The number of operands is unambiguous.
386    if (Operands.size() != RHS.Operands.size())
387      return false;
388
389    // Tokens and operand kinds are unambiguous (assuming a correct target
390    // specific parser).
391    for (unsigned i = 0, e = Operands.size(); i != e; ++i)
392      if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
393          Operands[i].Class->Kind == ClassInfo::Token)
394        if (*Operands[i].Class < *RHS.Operands[i].Class ||
395            *RHS.Operands[i].Class < *Operands[i].Class)
396          return false;
397
398    // Otherwise, this operand could commute if all operands are equivalent, or
399    // there is a pair of operands that compare less than and a pair that
400    // compare greater than.
401    bool HasLT = false, HasGT = false;
402    for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
403      if (*Operands[i].Class < *RHS.Operands[i].Class)
404        HasLT = true;
405      if (*RHS.Operands[i].Class < *Operands[i].Class)
406        HasGT = true;
407    }
408
409    return !(HasLT ^ HasGT);
410  }
411
412public:
413  void dump();
414};
415
416class AsmMatcherInfo {
417public:
418  /// The classes which are needed for matching.
419  std::vector<ClassInfo*> Classes;
420
421  /// The information on the instruction to match.
422  std::vector<InstructionInfo*> Instructions;
423
424private:
425  /// Map of token to class information which has already been constructed.
426  std::map<std::string, ClassInfo*> TokenClasses;
427
428  /// Map of operand name to class information which has already been
429  /// constructed.
430  std::map<std::string, ClassInfo*> OperandClasses;
431
432  /// Map of user class names to kind value.
433  std::map<std::string, unsigned> UserClasses;
434
435private:
436  /// getTokenClass - Lookup or create the class for the given token.
437  ClassInfo *getTokenClass(const StringRef &Token);
438
439  /// getUserClassKind - Lookup or create the kind value for the given class
440  /// name.
441  unsigned getUserClassKind(const StringRef &Name);
442
443  /// getOperandClass - Lookup or create the class for the given operand.
444  ClassInfo *getOperandClass(const StringRef &Token,
445                             const CodeGenInstruction::OperandInfo &OI);
446
447public:
448  /// BuildInfo - Construct the various tables used during matching.
449  void BuildInfo(CodeGenTarget &Target);
450};
451
452}
453
454void InstructionInfo::dump() {
455  errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
456         << ", tokens:[";
457  for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
458    errs() << Tokens[i];
459    if (i + 1 != e)
460      errs() << ", ";
461  }
462  errs() << "]\n";
463
464  for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
465    Operand &Op = Operands[i];
466    errs() << "  op[" << i << "] = " << Op.Class->ClassName << " - ";
467    if (Op.Class->Kind == ClassInfo::Token) {
468      errs() << '\"' << Tokens[i] << "\"\n";
469      continue;
470    }
471
472    const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
473    errs() << OI.Name << " " << OI.Rec->getName()
474           << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
475  }
476}
477
478static std::string getEnumNameForToken(const StringRef &Str) {
479  std::string Res;
480
481  for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
482    switch (*it) {
483    case '*': Res += "_STAR_"; break;
484    case '%': Res += "_PCT_"; break;
485    case ':': Res += "_COLON_"; break;
486
487    default:
488      if (isalnum(*it))  {
489        Res += *it;
490      } else {
491        Res += "_" + utostr((unsigned) *it) + "_";
492      }
493    }
494  }
495
496  return Res;
497}
498
499ClassInfo *AsmMatcherInfo::getTokenClass(const StringRef &Token) {
500  ClassInfo *&Entry = TokenClasses[Token];
501
502  if (!Entry) {
503    Entry = new ClassInfo();
504    Entry->Kind = ClassInfo::Token;
505    Entry->ClassName = "Token";
506    Entry->Name = "MCK_" + getEnumNameForToken(Token);
507    Entry->ValueName = Token;
508    Entry->PredicateMethod = "<invalid>";
509    Entry->RenderMethod = "<invalid>";
510    Classes.push_back(Entry);
511  }
512
513  return Entry;
514}
515
516unsigned AsmMatcherInfo::getUserClassKind(const StringRef &Name) {
517  unsigned &Entry = UserClasses[Name];
518
519  if (!Entry)
520    Entry = ClassInfo::UserClass0 + UserClasses.size() - 1;
521
522  return Entry;
523}
524
525ClassInfo *
526AsmMatcherInfo::getOperandClass(const StringRef &Token,
527                                const CodeGenInstruction::OperandInfo &OI) {
528  std::string ClassName;
529  if (OI.Rec->isSubClassOf("RegisterClass")) {
530    ClassName = "Reg";
531  } else {
532    try {
533      ClassName = OI.Rec->getValueAsString("ParserMatchClass");
534      assert(ClassName != "Reg" && "'Reg' class name is reserved!");
535    } catch(...) {
536      PrintError(OI.Rec->getLoc(), "operand has no match class!");
537      ClassName = "Invalid";
538    }
539  }
540
541  ClassInfo *&Entry = OperandClasses[ClassName];
542
543  if (!Entry) {
544    Entry = new ClassInfo();
545    // FIXME: Hack.
546    if (ClassName == "Reg") {
547      Entry->Kind = ClassInfo::Register;
548    } else {
549      Entry->Kind = getUserClassKind(ClassName);
550    }
551    Entry->ClassName = ClassName;
552    Entry->Name = "MCK_" + ClassName;
553    Entry->ValueName = OI.Rec->getName();
554    Entry->PredicateMethod = "is" + ClassName;
555    Entry->RenderMethod = "add" + ClassName + "Operands";
556    Classes.push_back(Entry);
557  }
558
559  return Entry;
560}
561
562void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
563  for (std::map<std::string, CodeGenInstruction>::const_iterator
564         it = Target.getInstructions().begin(),
565         ie = Target.getInstructions().end();
566       it != ie; ++it) {
567    const CodeGenInstruction &CGI = it->second;
568
569    if (!StringRef(it->first).startswith(MatchPrefix))
570      continue;
571
572    OwningPtr<InstructionInfo> II(new InstructionInfo);
573
574    II->InstrName = it->first;
575    II->Instr = &it->second;
576    II->AsmString = FlattenVariants(CGI.AsmString, 0);
577
578    TokenizeAsmString(II->AsmString, II->Tokens);
579
580    // Ignore instructions which shouldn't be matched.
581    if (!IsAssemblerInstruction(it->first, CGI, II->Tokens))
582      continue;
583
584    for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
585      StringRef Token = II->Tokens[i];
586
587      // Check for simple tokens.
588      if (Token[0] != '$') {
589        InstructionInfo::Operand Op;
590        Op.Class = getTokenClass(Token);
591        Op.OperandInfo = 0;
592        II->Operands.push_back(Op);
593        continue;
594      }
595
596      // Otherwise this is an operand reference.
597      StringRef OperandName;
598      if (Token[1] == '{')
599        OperandName = Token.substr(2, Token.size() - 3);
600      else
601        OperandName = Token.substr(1);
602
603      // Map this token to an operand. FIXME: Move elsewhere.
604      unsigned Idx;
605      try {
606        Idx = CGI.getOperandNamed(OperandName);
607      } catch(...) {
608        errs() << "error: unable to find operand: '" << OperandName << "'!\n";
609        break;
610      }
611
612      const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx];
613      InstructionInfo::Operand Op;
614      Op.Class = getOperandClass(Token, OI);
615      Op.OperandInfo = &OI;
616      II->Operands.push_back(Op);
617    }
618
619    // If we broke out, ignore the instruction.
620    if (II->Operands.size() != II->Tokens.size())
621      continue;
622
623    Instructions.push_back(II.take());
624  }
625}
626
627static void EmitConvertToMCInst(CodeGenTarget &Target,
628                                std::vector<InstructionInfo*> &Infos,
629                                raw_ostream &OS) {
630  // Write the convert function to a separate stream, so we can drop it after
631  // the enum.
632  std::string ConvertFnBody;
633  raw_string_ostream CvtOS(ConvertFnBody);
634
635  // Function we have already generated.
636  std::set<std::string> GeneratedFns;
637
638  // Start the unified conversion function.
639
640  CvtOS << "static bool ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
641        << "unsigned Opcode,\n"
642        << "                            SmallVectorImpl<"
643        << Target.getName() << "Operand> &Operands) {\n";
644  CvtOS << "  Inst.setOpcode(Opcode);\n";
645  CvtOS << "  switch (Kind) {\n";
646  CvtOS << "  default:\n";
647
648  // Start the enum, which we will generate inline.
649
650  OS << "// Unified function for converting operants to MCInst instances.\n\n";
651  OS << "enum ConversionKind {\n";
652
653  for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
654         ie = Infos.end(); it != ie; ++it) {
655    InstructionInfo &II = **it;
656
657    // Order the (class) operands by the order to convert them into an MCInst.
658    SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
659    for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
660      InstructionInfo::Operand &Op = II.Operands[i];
661      if (Op.OperandInfo)
662        MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
663    }
664    std::sort(MIOperandList.begin(), MIOperandList.end());
665
666    // Compute the total number of operands.
667    unsigned NumMIOperands = 0;
668    for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
669      const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
670      NumMIOperands = std::max(NumMIOperands,
671                               OI.MIOperandNo + OI.MINumOperands);
672    }
673
674    // Build the conversion function signature.
675    std::string Signature = "Convert";
676    unsigned CurIndex = 0;
677    for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
678      InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
679      assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
680             "Duplicate match for instruction operand!");
681
682      Signature += "_";
683
684      // Skip operands which weren't matched by anything, this occurs when the
685      // .td file encodes "implicit" operands as explicit ones.
686      //
687      // FIXME: This should be removed from the MCInst structure.
688      for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
689        Signature += "Imp";
690
691      Signature += Op.Class->ClassName;
692      Signature += utostr(Op.OperandInfo->MINumOperands);
693      Signature += "_" + utostr(MIOperandList[i].second);
694
695      CurIndex += Op.OperandInfo->MINumOperands;
696    }
697
698    // Add any trailing implicit operands.
699    for (; CurIndex != NumMIOperands; ++CurIndex)
700      Signature += "Imp";
701
702    II.ConversionFnKind = Signature;
703
704    // Check if we have already generated this signature.
705    if (!GeneratedFns.insert(Signature).second)
706      continue;
707
708    // If not, emit it now.
709
710    // Add to the enum list.
711    OS << "  " << Signature << ",\n";
712
713    // And to the convert function.
714    CvtOS << "  case " << Signature << ":\n";
715    CurIndex = 0;
716    for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
717      InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
718
719      // Add the implicit operands.
720      for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
721        CvtOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
722
723      CvtOS << "    Operands[" << MIOperandList[i].second
724         << "]." << Op.Class->RenderMethod
725         << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
726      CurIndex += Op.OperandInfo->MINumOperands;
727    }
728
729    // And add trailing implicit operands.
730    for (; CurIndex != NumMIOperands; ++CurIndex)
731      CvtOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
732    CvtOS << "    break;\n";
733  }
734
735  // Finish the convert function.
736
737  CvtOS << "  }\n";
738  CvtOS << "  return false;\n";
739  CvtOS << "}\n\n";
740
741  // Finish the enum, and drop the convert function after it.
742
743  OS << "  NumConversionVariants\n";
744  OS << "};\n\n";
745
746  OS << CvtOS.str();
747}
748
749/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
750static void EmitMatchClassEnumeration(CodeGenTarget &Target,
751                                      std::vector<ClassInfo*> &Infos,
752                                      raw_ostream &OS) {
753  OS << "namespace {\n\n";
754
755  OS << "/// MatchClassKind - The kinds of classes which participate in\n"
756     << "/// instruction matching.\n";
757  OS << "enum MatchClassKind {\n";
758  OS << "  InvalidMatchClass = 0,\n";
759  for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
760         ie = Infos.end(); it != ie; ++it) {
761    ClassInfo &CI = **it;
762    OS << "  " << CI.Name << ", // ";
763    if (CI.Kind == ClassInfo::Token) {
764      OS << "'" << CI.ValueName << "'\n";
765    } else if (CI.Kind == ClassInfo::Register) {
766      if (!CI.ValueName.empty())
767        OS << "register class '" << CI.ValueName << "'\n";
768      else
769        OS << "derived register class\n";
770    } else {
771      OS << "user defined class '" << CI.ValueName << "'\n";
772    }
773  }
774  OS << "  NumMatchClassKinds\n";
775  OS << "};\n\n";
776
777  OS << "}\n\n";
778}
779
780/// EmitClassifyOperand - Emit the function to classify an operand.
781static void EmitClassifyOperand(CodeGenTarget &Target,
782                                std::vector<ClassInfo*> &Infos,
783                                raw_ostream &OS) {
784  OS << "static MatchClassKind ClassifyOperand("
785     << Target.getName() << "Operand &Operand) {\n";
786  OS << "  if (Operand.isToken())\n";
787  OS << "    return MatchTokenString(Operand.getToken());\n\n";
788  for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
789         ie = Infos.end(); it != ie; ++it) {
790    ClassInfo &CI = **it;
791
792    if (CI.Kind != ClassInfo::Token) {
793      OS << "  if (Operand." << CI.PredicateMethod << "())\n";
794      OS << "    return " << CI.Name << ";\n\n";
795    }
796  }
797  OS << "  return InvalidMatchClass;\n";
798  OS << "}\n\n";
799}
800
801typedef std::pair<std::string, std::string> StringPair;
802
803/// FindFirstNonCommonLetter - Find the first character in the keys of the
804/// string pairs that is not shared across the whole set of strings.  All
805/// strings are assumed to have the same length.
806static unsigned
807FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
808  assert(!Matches.empty());
809  for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
810    // Check to see if letter i is the same across the set.
811    char Letter = Matches[0]->first[i];
812
813    for (unsigned str = 0, e = Matches.size(); str != e; ++str)
814      if (Matches[str]->first[i] != Letter)
815        return i;
816  }
817
818  return Matches[0]->first.size();
819}
820
821/// EmitStringMatcherForChar - Given a set of strings that are known to be the
822/// same length and whose characters leading up to CharNo are the same, emit
823/// code to verify that CharNo and later are the same.
824///
825/// \return - True if control can leave the emitted code fragment.
826static bool EmitStringMatcherForChar(const std::string &StrVariableName,
827                                  const std::vector<const StringPair*> &Matches,
828                                     unsigned CharNo, unsigned IndentCount,
829                                     raw_ostream &OS) {
830  assert(!Matches.empty() && "Must have at least one string to match!");
831  std::string Indent(IndentCount*2+4, ' ');
832
833  // If we have verified that the entire string matches, we're done: output the
834  // matching code.
835  if (CharNo == Matches[0]->first.size()) {
836    assert(Matches.size() == 1 && "Had duplicate keys to match on");
837
838    // FIXME: If Matches[0].first has embeded \n, this will be bad.
839    OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
840       << "\"\n";
841    return false;
842  }
843
844  // Bucket the matches by the character we are comparing.
845  std::map<char, std::vector<const StringPair*> > MatchesByLetter;
846
847  for (unsigned i = 0, e = Matches.size(); i != e; ++i)
848    MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
849
850
851  // If we have exactly one bucket to match, see how many characters are common
852  // across the whole set and match all of them at once.
853  if (MatchesByLetter.size() == 1) {
854    unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
855    unsigned NumChars = FirstNonCommonLetter-CharNo;
856
857    // Emit code to break out if the prefix doesn't match.
858    if (NumChars == 1) {
859      // Do the comparison with if (Str[1] != 'f')
860      // FIXME: Need to escape general characters.
861      OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
862         << Matches[0]->first[CharNo] << "')\n";
863      OS << Indent << "  break;\n";
864    } else {
865      // Do the comparison with if (Str.substr(1,3) != "foo").
866      // FIXME: Need to escape general strings.
867      OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
868         << NumChars << ") != \"";
869      OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
870      OS << Indent << "  break;\n";
871    }
872
873    return EmitStringMatcherForChar(StrVariableName, Matches,
874                                    FirstNonCommonLetter, IndentCount, OS);
875  }
876
877  // Otherwise, we have multiple possible things, emit a switch on the
878  // character.
879  OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
880  OS << Indent << "default: break;\n";
881
882  for (std::map<char, std::vector<const StringPair*> >::iterator LI =
883       MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
884    // TODO: escape hard stuff (like \n) if we ever care about it.
885    OS << Indent << "case '" << LI->first << "':\t // "
886       << LI->second.size() << " strings to match.\n";
887    if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
888                                 IndentCount+1, OS))
889      OS << Indent << "  break;\n";
890  }
891
892  OS << Indent << "}\n";
893  return true;
894}
895
896
897/// EmitStringMatcher - Given a list of strings and code to execute when they
898/// match, output a simple switch tree to classify the input string.
899///
900/// If a match is found, the code in Vals[i].second is executed; control must
901/// not exit this code fragment.  If nothing matches, execution falls through.
902///
903/// \param StrVariableName - The name of the variable to test.
904static void EmitStringMatcher(const std::string &StrVariableName,
905                              const std::vector<StringPair> &Matches,
906                              raw_ostream &OS) {
907  // First level categorization: group strings by length.
908  std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
909
910  for (unsigned i = 0, e = Matches.size(); i != e; ++i)
911    MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
912
913  // Output a switch statement on length and categorize the elements within each
914  // bin.
915  OS << "  switch (" << StrVariableName << ".size()) {\n";
916  OS << "  default: break;\n";
917
918  for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
919       MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
920    OS << "  case " << LI->first << ":\t // " << LI->second.size()
921       << " strings to match.\n";
922    if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
923      OS << "    break;\n";
924  }
925
926  OS << "  }\n";
927}
928
929
930/// EmitMatchTokenString - Emit the function to match a token string to the
931/// appropriate match class value.
932static void EmitMatchTokenString(CodeGenTarget &Target,
933                                 std::vector<ClassInfo*> &Infos,
934                                 raw_ostream &OS) {
935  // Construct the match list.
936  std::vector<StringPair> Matches;
937  for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
938         ie = Infos.end(); it != ie; ++it) {
939    ClassInfo &CI = **it;
940
941    if (CI.Kind == ClassInfo::Token)
942      Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
943  }
944
945  OS << "static MatchClassKind MatchTokenString(const StringRef &Name) {\n";
946
947  EmitStringMatcher("Name", Matches, OS);
948
949  OS << "  return InvalidMatchClass;\n";
950  OS << "}\n\n";
951}
952
953/// EmitMatchRegisterName - Emit the function to match a string to the target
954/// specific register enum.
955static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
956                                  raw_ostream &OS) {
957  // Construct the match list.
958  std::vector<StringPair> Matches;
959  for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
960    const CodeGenRegister &Reg = Target.getRegisters()[i];
961    if (Reg.TheDef->getValueAsString("AsmName").empty())
962      continue;
963
964    Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
965                                 "return " + utostr(i + 1) + ";"));
966  }
967
968  OS << "unsigned " << Target.getName()
969     << AsmParser->getValueAsString("AsmParserClassName")
970     << "::MatchRegisterName(const StringRef &Name) {\n";
971
972  EmitStringMatcher("Name", Matches, OS);
973
974  OS << "  return 0;\n";
975  OS << "}\n\n";
976}
977
978void AsmMatcherEmitter::run(raw_ostream &OS) {
979  CodeGenTarget Target;
980  Record *AsmParser = Target.getAsmParser();
981  std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
982
983  EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
984
985  // Emit the function to match a register name to number.
986  EmitMatchRegisterName(Target, AsmParser, OS);
987
988  // Compute the information on the instructions to match.
989  AsmMatcherInfo Info;
990  Info.BuildInfo(Target);
991
992  // Sort the instruction table using the partial order on classes.
993  std::sort(Info.Instructions.begin(), Info.Instructions.end(),
994            less_ptr<InstructionInfo>());
995
996  DEBUG_WITH_TYPE("instruction_info", {
997      for (std::vector<InstructionInfo*>::iterator
998             it = Info.Instructions.begin(), ie = Info.Instructions.end();
999           it != ie; ++it)
1000        (*it)->dump();
1001    });
1002
1003  // Check for ambiguous instructions.
1004  unsigned NumAmbiguous = 0;
1005  for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1006    for (unsigned j = i + 1; j != e; ++j) {
1007      InstructionInfo &A = *Info.Instructions[i];
1008      InstructionInfo &B = *Info.Instructions[j];
1009
1010      if (A.CouldMatchAmiguouslyWith(B)) {
1011        DEBUG_WITH_TYPE("ambiguous_instrs", {
1012            errs() << "warning: ambiguous instruction match:\n";
1013            A.dump();
1014            errs() << "\nis incomparable with:\n";
1015            B.dump();
1016            errs() << "\n\n";
1017          });
1018        ++NumAmbiguous;
1019      }
1020    }
1021  }
1022  if (NumAmbiguous)
1023    DEBUG_WITH_TYPE("ambiguous_instrs", {
1024        errs() << "warning: " << NumAmbiguous
1025               << " ambiguous instructions!\n";
1026      });
1027
1028  // Generate the unified function to convert operands into an MCInst.
1029  EmitConvertToMCInst(Target, Info.Instructions, OS);
1030
1031  // Emit the enumeration for classes which participate in matching.
1032  EmitMatchClassEnumeration(Target, Info.Classes, OS);
1033
1034  // Emit the routine to match token strings to their match class.
1035  EmitMatchTokenString(Target, Info.Classes, OS);
1036
1037  // Emit the routine to classify an operand.
1038  EmitClassifyOperand(Target, Info.Classes, OS);
1039
1040  // Finally, build the match function.
1041
1042  size_t MaxNumOperands = 0;
1043  for (std::vector<InstructionInfo*>::const_iterator it =
1044         Info.Instructions.begin(), ie = Info.Instructions.end();
1045       it != ie; ++it)
1046    MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1047
1048  OS << "bool " << Target.getName() << ClassName
1049     << "::MatchInstruction("
1050     << "SmallVectorImpl<" << Target.getName() << "Operand> &Operands, "
1051     << "MCInst &Inst) {\n";
1052
1053  // Emit the static match table; unused classes get initalized to 0 which is
1054  // guaranteed to be InvalidMatchClass.
1055  //
1056  // FIXME: We can reduce the size of this table very easily. First, we change
1057  // it so that store the kinds in separate bit-fields for each index, which
1058  // only needs to be the max width used for classes at that index (we also need
1059  // to reject based on this during classification). If we then make sure to
1060  // order the match kinds appropriately (putting mnemonics last), then we
1061  // should only end up using a few bits for each class, especially the ones
1062  // following the mnemonic.
1063  OS << "  static const struct MatchEntry {\n";
1064  OS << "    unsigned Opcode;\n";
1065  OS << "    ConversionKind ConvertFn;\n";
1066  OS << "    MatchClassKind Classes[" << MaxNumOperands << "];\n";
1067  OS << "  } MatchTable[" << Info.Instructions.size() << "] = {\n";
1068
1069  for (std::vector<InstructionInfo*>::const_iterator it =
1070         Info.Instructions.begin(), ie = Info.Instructions.end();
1071       it != ie; ++it) {
1072    InstructionInfo &II = **it;
1073
1074    OS << "    { " << Target.getName() << "::" << II.InstrName
1075       << ", " << II.ConversionFnKind << ", { ";
1076    for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1077      InstructionInfo::Operand &Op = II.Operands[i];
1078
1079      if (i) OS << ", ";
1080      OS << Op.Class->Name;
1081    }
1082    OS << " } },\n";
1083  }
1084
1085  OS << "  };\n\n";
1086
1087  // Emit code to compute the class list for this operand vector.
1088  OS << "  // Eliminate obvious mismatches.\n";
1089  OS << "  if (Operands.size() > " << MaxNumOperands << ")\n";
1090  OS << "    return true;\n\n";
1091
1092  OS << "  // Compute the class list for this operand vector.\n";
1093  OS << "  MatchClassKind Classes[" << MaxNumOperands << "];\n";
1094  OS << "  for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1095  OS << "    Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1096
1097  OS << "    // Check for invalid operands before matching.\n";
1098  OS << "    if (Classes[i] == InvalidMatchClass)\n";
1099  OS << "      return true;\n";
1100  OS << "  }\n\n";
1101
1102  OS << "  // Mark unused classes.\n";
1103  OS << "  for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1104     << "i != e; ++i)\n";
1105  OS << "    Classes[i] = InvalidMatchClass;\n\n";
1106
1107  // Emit code to search the table.
1108  OS << "  // Search the table.\n";
1109  OS << "  for (const MatchEntry *it = MatchTable, "
1110     << "*ie = MatchTable + " << Info.Instructions.size()
1111     << "; it != ie; ++it) {\n";
1112  for (unsigned i = 0; i != MaxNumOperands; ++i) {
1113    OS << "    if (Classes[" << i << "] != it->Classes[" << i << "])\n";
1114    OS << "      continue;\n";
1115  }
1116  OS << "\n";
1117  OS << "    return ConvertToMCInst(it->ConvertFn, Inst, "
1118     << "it->Opcode, Operands);\n";
1119  OS << "  }\n\n";
1120
1121  OS << "  return true;\n";
1122  OS << "}\n\n";
1123}
1124