9161b54c5c3cab97057d3cd9afb3686b4a74ebae
[oota-llvm.git] / utils / TableGen / AsmMatcherEmitter.cpp
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 "StringMatcher.h"
80 #include "llvm/ADT/OwningPtr.h"
81 #include "llvm/ADT/SmallVector.h"
82 #include "llvm/ADT/STLExtras.h"
83 #include "llvm/ADT/StringExtras.h"
84 #include "llvm/Support/CommandLine.h"
85 #include "llvm/Support/Debug.h"
86 #include <list>
87 #include <map>
88 #include <set>
89 using namespace llvm;
90
91 static cl::opt<std::string>
92 MatchPrefix("match-prefix", cl::init(""),
93             cl::desc("Only match instructions with the given prefix"));
94
95 /// FlattenVariants - Flatten an .td file assembly string by selecting the
96 /// variant at index \arg N.
97 static std::string FlattenVariants(const std::string &AsmString,
98                                    unsigned N) {
99   StringRef Cur = AsmString;
100   std::string Res = "";
101
102   for (;;) {
103     // Find the start of the next variant string.
104     size_t VariantsStart = 0;
105     for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
106       if (Cur[VariantsStart] == '{' &&
107           (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
108                                   Cur[VariantsStart-1] != '\\')))
109         break;
110
111     // Add the prefix to the result.
112     Res += Cur.slice(0, VariantsStart);
113     if (VariantsStart == Cur.size())
114       break;
115
116     ++VariantsStart; // Skip the '{'.
117
118     // Scan to the end of the variants string.
119     size_t VariantsEnd = VariantsStart;
120     unsigned NestedBraces = 1;
121     for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
122       if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
123         if (--NestedBraces == 0)
124           break;
125       } else if (Cur[VariantsEnd] == '{')
126         ++NestedBraces;
127     }
128
129     // Select the Nth variant (or empty).
130     StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
131     for (unsigned i = 0; i != N; ++i)
132       Selection = Selection.split('|').second;
133     Res += Selection.split('|').first;
134
135     assert(VariantsEnd != Cur.size() &&
136            "Unterminated variants in assembly string!");
137     Cur = Cur.substr(VariantsEnd + 1);
138   }
139
140   return Res;
141 }
142
143 /// TokenizeAsmString - Tokenize a simplified assembly string.
144 static void TokenizeAsmString(StringRef AsmString,
145                               SmallVectorImpl<StringRef> &Tokens) {
146   unsigned Prev = 0;
147   bool InTok = true;
148   for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {
149     switch (AsmString[i]) {
150     case '[':
151     case ']':
152     case '*':
153     case '!':
154     case ' ':
155     case '\t':
156     case ',':
157       if (InTok) {
158         Tokens.push_back(AsmString.slice(Prev, i));
159         InTok = false;
160       }
161       if (!isspace(AsmString[i]) && AsmString[i] != ',')
162         Tokens.push_back(AsmString.substr(i, 1));
163       Prev = i + 1;
164       break;
165
166     case '\\':
167       if (InTok) {
168         Tokens.push_back(AsmString.slice(Prev, i));
169         InTok = false;
170       }
171       ++i;
172       assert(i != AsmString.size() && "Invalid quoted character");
173       Tokens.push_back(AsmString.substr(i, 1));
174       Prev = i + 1;
175       break;
176
177     case '$': {
178       // If this isn't "${", treat like a normal token.
179       if (i + 1 == AsmString.size() || AsmString[i + 1] != '{') {
180         if (InTok) {
181           Tokens.push_back(AsmString.slice(Prev, i));
182           InTok = false;
183         }
184         Prev = i;
185         break;
186       }
187
188       if (InTok) {
189         Tokens.push_back(AsmString.slice(Prev, i));
190         InTok = false;
191       }
192
193       StringRef::iterator End =
194         std::find(AsmString.begin() + i, AsmString.end(), '}');
195       assert(End != AsmString.end() && "Missing brace in operand reference!");
196       size_t EndPos = End - AsmString.begin();
197       Tokens.push_back(AsmString.slice(i, EndPos+1));
198       Prev = EndPos + 1;
199       i = EndPos;
200       break;
201     }
202
203     case '.':
204       if (InTok) {
205         Tokens.push_back(AsmString.slice(Prev, i));
206       }
207       Prev = i;
208       InTok = true;
209       break;
210
211     default:
212       InTok = true;
213     }
214   }
215   if (InTok && Prev != AsmString.size())
216     Tokens.push_back(AsmString.substr(Prev));
217 }
218
219 static bool IsAssemblerInstruction(StringRef Name,
220                                    const CodeGenInstruction &CGI,
221                                    const SmallVectorImpl<StringRef> &Tokens) {
222   // Ignore "codegen only" instructions.
223   if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
224     return false;
225
226   // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
227   //
228   // FIXME: This is a total hack.
229   if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
230     return false;
231
232   // Reject instructions with no .s string.
233   if (CGI.AsmString.empty()) {
234     PrintError(CGI.TheDef->getLoc(),
235                "instruction with empty asm string");
236     throw std::string("ERROR: Invalid instruction for asm matcher");
237   }
238
239   // Reject any instructions with a newline in them, they should be marked
240   // isCodeGenOnly if they are pseudo instructions.
241   if (CGI.AsmString.find('\n') != std::string::npos) {
242     PrintError(CGI.TheDef->getLoc(),
243                "multiline instruction is not valid for the asmparser, "
244                "mark it isCodeGenOnly");
245     throw std::string("ERROR: Invalid instruction");
246   }
247
248   // Reject instructions with attributes, these aren't something we can handle,
249   // the target should be refactored to use operands instead of modifiers.
250   //
251   // Also, check for instructions which reference the operand multiple times;
252   // this implies a constraint we would not honor.
253   std::set<std::string> OperandNames;
254   for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
255     if (Tokens[i][0] == '$' &&
256         Tokens[i].find(':') != StringRef::npos) {
257       PrintError(CGI.TheDef->getLoc(),
258                  "instruction with operand modifier '" + Tokens[i].str() +
259                  "' not supported by asm matcher.  Mark isCodeGenOnly!");
260       throw std::string("ERROR: Invalid instruction");
261     }
262     
263     // FIXME: Should reject these.
264     if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
265       DEBUG({
266         errs() << "warning: '" << Name << "': "
267                << "ignoring instruction with tied operand '"
268                << Tokens[i].str() << "'\n";
269       });
270       return false;
271     }
272   }
273   
274   return true;
275 }
276
277 namespace {
278
279 struct SubtargetFeatureInfo;
280
281 /// ClassInfo - Helper class for storing the information about a particular
282 /// class of operands which can be matched.
283 struct ClassInfo {
284   enum ClassInfoKind {
285     /// Invalid kind, for use as a sentinel value.
286     Invalid = 0,
287
288     /// The class for a particular token.
289     Token,
290
291     /// The (first) register class, subsequent register classes are
292     /// RegisterClass0+1, and so on.
293     RegisterClass0,
294
295     /// The (first) user defined class, subsequent user defined classes are
296     /// UserClass0+1, and so on.
297     UserClass0 = 1<<16
298   };
299
300   /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
301   /// N) for the Nth user defined class.
302   unsigned Kind;
303
304   /// SuperClasses - The super classes of this class. Note that for simplicities
305   /// sake user operands only record their immediate super class, while register
306   /// operands include all superclasses.
307   std::vector<ClassInfo*> SuperClasses;
308
309   /// Name - The full class name, suitable for use in an enum.
310   std::string Name;
311
312   /// ClassName - The unadorned generic name for this class (e.g., Token).
313   std::string ClassName;
314
315   /// ValueName - The name of the value this class represents; for a token this
316   /// is the literal token string, for an operand it is the TableGen class (or
317   /// empty if this is a derived class).
318   std::string ValueName;
319
320   /// PredicateMethod - The name of the operand method to test whether the
321   /// operand matches this class; this is not valid for Token or register kinds.
322   std::string PredicateMethod;
323
324   /// RenderMethod - The name of the operand method to add this operand to an
325   /// MCInst; this is not valid for Token or register kinds.
326   std::string RenderMethod;
327
328   /// For register classes, the records for all the registers in this class.
329   std::set<Record*> Registers;
330
331 public:
332   /// isRegisterClass() - Check if this is a register class.
333   bool isRegisterClass() const {
334     return Kind >= RegisterClass0 && Kind < UserClass0;
335   }
336
337   /// isUserClass() - Check if this is a user defined class.
338   bool isUserClass() const {
339     return Kind >= UserClass0;
340   }
341
342   /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
343   /// are related if they are in the same class hierarchy.
344   bool isRelatedTo(const ClassInfo &RHS) const {
345     // Tokens are only related to tokens.
346     if (Kind == Token || RHS.Kind == Token)
347       return Kind == Token && RHS.Kind == Token;
348
349     // Registers classes are only related to registers classes, and only if
350     // their intersection is non-empty.
351     if (isRegisterClass() || RHS.isRegisterClass()) {
352       if (!isRegisterClass() || !RHS.isRegisterClass())
353         return false;
354
355       std::set<Record*> Tmp;
356       std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
357       std::set_intersection(Registers.begin(), Registers.end(),
358                             RHS.Registers.begin(), RHS.Registers.end(),
359                             II);
360
361       return !Tmp.empty();
362     }
363
364     // Otherwise we have two users operands; they are related if they are in the
365     // same class hierarchy.
366     //
367     // FIXME: This is an oversimplification, they should only be related if they
368     // intersect, however we don't have that information.
369     assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
370     const ClassInfo *Root = this;
371     while (!Root->SuperClasses.empty())
372       Root = Root->SuperClasses.front();
373
374     const ClassInfo *RHSRoot = &RHS;
375     while (!RHSRoot->SuperClasses.empty())
376       RHSRoot = RHSRoot->SuperClasses.front();
377
378     return Root == RHSRoot;
379   }
380
381   /// isSubsetOf - Test whether this class is a subset of \arg RHS;
382   bool isSubsetOf(const ClassInfo &RHS) const {
383     // This is a subset of RHS if it is the same class...
384     if (this == &RHS)
385       return true;
386
387     // ... or if any of its super classes are a subset of RHS.
388     for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
389            ie = SuperClasses.end(); it != ie; ++it)
390       if ((*it)->isSubsetOf(RHS))
391         return true;
392
393     return false;
394   }
395
396   /// operator< - Compare two classes.
397   bool operator<(const ClassInfo &RHS) const {
398     if (this == &RHS)
399       return false;
400
401     // Unrelated classes can be ordered by kind.
402     if (!isRelatedTo(RHS))
403       return Kind < RHS.Kind;
404
405     switch (Kind) {
406     case Invalid:
407       assert(0 && "Invalid kind!");
408     case Token:
409       // Tokens are comparable by value.
410       //
411       // FIXME: Compare by enum value.
412       return ValueName < RHS.ValueName;
413
414     default:
415       // This class preceeds the RHS if it is a proper subset of the RHS.
416       if (isSubsetOf(RHS))
417         return true;
418       if (RHS.isSubsetOf(*this))
419         return false;
420
421       // Otherwise, order by name to ensure we have a total ordering.
422       return ValueName < RHS.ValueName;
423     }
424   }
425 };
426
427 /// InstructionInfo - Helper class for storing the necessary information for an
428 /// instruction which is capable of being matched.
429 struct InstructionInfo {
430   struct Operand {
431     /// The unique class instance this operand should match.
432     ClassInfo *Class;
433
434     /// The original operand this corresponds to, if any.
435     const CodeGenInstruction::OperandInfo *OperandInfo;
436   };
437
438   /// InstrName - The target name for this instruction.
439   std::string InstrName;
440
441   /// Instr - The instruction this matches.
442   const CodeGenInstruction *Instr;
443
444   /// AsmString - The assembly string for this instruction (with variants
445   /// removed).
446   std::string AsmString;
447
448   /// Tokens - The tokenized assembly pattern that this instruction matches.
449   SmallVector<StringRef, 4> Tokens;
450
451   /// Operands - The operands that this instruction matches.
452   SmallVector<Operand, 4> Operands;
453
454   /// Predicates - The required subtarget features to match this instruction.
455   SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
456
457   /// ConversionFnKind - The enum value which is passed to the generated
458   /// ConvertToMCInst to convert parsed operands into an MCInst for this
459   /// function.
460   std::string ConversionFnKind;
461
462   /// operator< - Compare two instructions.
463   bool operator<(const InstructionInfo &RHS) const {
464     // The primary comparator is the instruction mnemonic.
465     if (Tokens[0] != RHS.Tokens[0])
466       return Tokens[0] < RHS.Tokens[0];
467
468     if (Operands.size() != RHS.Operands.size())
469       return Operands.size() < RHS.Operands.size();
470
471     // Compare lexicographically by operand. The matcher validates that other
472     // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
473     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
474       if (*Operands[i].Class < *RHS.Operands[i].Class)
475         return true;
476       if (*RHS.Operands[i].Class < *Operands[i].Class)
477         return false;
478     }
479
480     return false;
481   }
482
483   /// CouldMatchAmiguouslyWith - Check whether this instruction could
484   /// ambiguously match the same set of operands as \arg RHS (without being a
485   /// strictly superior match).
486   bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
487     // The number of operands is unambiguous.
488     if (Operands.size() != RHS.Operands.size())
489       return false;
490
491     // Otherwise, make sure the ordering of the two instructions is unambiguous
492     // by checking that either (a) a token or operand kind discriminates them,
493     // or (b) the ordering among equivalent kinds is consistent.
494
495     // Tokens and operand kinds are unambiguous (assuming a correct target
496     // specific parser).
497     for (unsigned i = 0, e = Operands.size(); i != e; ++i)
498       if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
499           Operands[i].Class->Kind == ClassInfo::Token)
500         if (*Operands[i].Class < *RHS.Operands[i].Class ||
501             *RHS.Operands[i].Class < *Operands[i].Class)
502           return false;
503
504     // Otherwise, this operand could commute if all operands are equivalent, or
505     // there is a pair of operands that compare less than and a pair that
506     // compare greater than.
507     bool HasLT = false, HasGT = false;
508     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
509       if (*Operands[i].Class < *RHS.Operands[i].Class)
510         HasLT = true;
511       if (*RHS.Operands[i].Class < *Operands[i].Class)
512         HasGT = true;
513     }
514
515     return !(HasLT ^ HasGT);
516   }
517
518 public:
519   void dump();
520 };
521
522 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
523 /// feature which participates in instruction matching.
524 struct SubtargetFeatureInfo {
525   /// \brief The predicate record for this feature.
526   Record *TheDef;
527
528   /// \brief An unique index assigned to represent this feature.
529   unsigned Index;
530
531   SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
532   
533   /// \brief The name of the enumerated constant identifying this feature.
534   std::string getEnumName() const {
535     return "Feature_" + TheDef->getName();
536   }
537 };
538
539 class AsmMatcherInfo {
540 public:
541   /// The tablegen AsmParser record.
542   Record *AsmParser;
543
544   /// The AsmParser "CommentDelimiter" value.
545   std::string CommentDelimiter;
546
547   /// The AsmParser "RegisterPrefix" value.
548   std::string RegisterPrefix;
549
550   /// The classes which are needed for matching.
551   std::vector<ClassInfo*> Classes;
552
553   /// The information on the instruction to match.
554   std::vector<InstructionInfo*> Instructions;
555
556   /// Map of Register records to their class information.
557   std::map<Record*, ClassInfo*> RegisterClasses;
558
559   /// Map of Predicate records to their subtarget information.
560   std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
561   
562 private:
563   /// Map of token to class information which has already been constructed.
564   std::map<std::string, ClassInfo*> TokenClasses;
565
566   /// Map of RegisterClass records to their class information.
567   std::map<Record*, ClassInfo*> RegisterClassClasses;
568
569   /// Map of AsmOperandClass records to their class information.
570   std::map<Record*, ClassInfo*> AsmOperandClasses;
571
572 private:
573   /// getTokenClass - Lookup or create the class for the given token.
574   ClassInfo *getTokenClass(StringRef Token);
575
576   /// getOperandClass - Lookup or create the class for the given operand.
577   ClassInfo *getOperandClass(StringRef Token,
578                              const CodeGenInstruction::OperandInfo &OI);
579
580   /// BuildRegisterClasses - Build the ClassInfo* instances for register
581   /// classes.
582   void BuildRegisterClasses(CodeGenTarget &Target,
583                             std::set<std::string> &SingletonRegisterNames);
584
585   /// BuildOperandClasses - Build the ClassInfo* instances for user defined
586   /// operand classes.
587   void BuildOperandClasses(CodeGenTarget &Target);
588
589 public:
590   AsmMatcherInfo(Record *_AsmParser);
591
592   /// BuildInfo - Construct the various tables used during matching.
593   void BuildInfo(CodeGenTarget &Target);
594   
595   /// getSubtargetFeature - Lookup or create the subtarget feature info for the
596   /// given operand.
597   SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
598     assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
599     std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
600       SubtargetFeatures.find(Def);
601     return I == SubtargetFeatures.end() ? 0 : I->second;
602   }
603 };
604
605 }
606
607 void InstructionInfo::dump() {
608   errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
609          << ", tokens:[";
610   for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
611     errs() << Tokens[i];
612     if (i + 1 != e)
613       errs() << ", ";
614   }
615   errs() << "]\n";
616
617   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
618     Operand &Op = Operands[i];
619     errs() << "  op[" << i << "] = " << Op.Class->ClassName << " - ";
620     if (Op.Class->Kind == ClassInfo::Token) {
621       errs() << '\"' << Tokens[i] << "\"\n";
622       continue;
623     }
624
625     if (!Op.OperandInfo) {
626       errs() << "(singleton register)\n";
627       continue;
628     }
629
630     const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
631     errs() << OI.Name << " " << OI.Rec->getName()
632            << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
633   }
634 }
635
636 static std::string getEnumNameForToken(StringRef Str) {
637   std::string Res;
638
639   for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
640     switch (*it) {
641     case '*': Res += "_STAR_"; break;
642     case '%': Res += "_PCT_"; break;
643     case ':': Res += "_COLON_"; break;
644     default:
645       if (isalnum(*it))
646         Res += *it;
647       else
648         Res += "_" + utostr((unsigned) *it) + "_";
649     }
650   }
651
652   return Res;
653 }
654
655 /// getRegisterRecord - Get the register record for \arg name, or 0.
656 static Record *getRegisterRecord(CodeGenTarget &Target, StringRef Name) {
657   for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
658     const CodeGenRegister &Reg = Target.getRegisters()[i];
659     if (Name == Reg.TheDef->getValueAsString("AsmName"))
660       return Reg.TheDef;
661   }
662
663   return 0;
664 }
665
666 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
667   ClassInfo *&Entry = TokenClasses[Token];
668
669   if (!Entry) {
670     Entry = new ClassInfo();
671     Entry->Kind = ClassInfo::Token;
672     Entry->ClassName = "Token";
673     Entry->Name = "MCK_" + getEnumNameForToken(Token);
674     Entry->ValueName = Token;
675     Entry->PredicateMethod = "<invalid>";
676     Entry->RenderMethod = "<invalid>";
677     Classes.push_back(Entry);
678   }
679
680   return Entry;
681 }
682
683 ClassInfo *
684 AsmMatcherInfo::getOperandClass(StringRef Token,
685                                 const CodeGenInstruction::OperandInfo &OI) {
686   if (OI.Rec->isSubClassOf("RegisterClass")) {
687     ClassInfo *CI = RegisterClassClasses[OI.Rec];
688
689     if (!CI) {
690       PrintError(OI.Rec->getLoc(), "register class has no class info!");
691       throw std::string("ERROR: Missing register class!");
692     }
693
694     return CI;
695   }
696
697   assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
698   Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
699   ClassInfo *CI = AsmOperandClasses[MatchClass];
700
701   if (!CI) {
702     PrintError(OI.Rec->getLoc(), "operand has no match class!");
703     throw std::string("ERROR: Missing match class!");
704   }
705
706   return CI;
707 }
708
709 void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target,
710                                           std::set<std::string>
711                                             &SingletonRegisterNames) {
712   std::vector<CodeGenRegisterClass> RegisterClasses;
713   std::vector<CodeGenRegister> Registers;
714
715   RegisterClasses = Target.getRegisterClasses();
716   Registers = Target.getRegisters();
717
718   // The register sets used for matching.
719   std::set< std::set<Record*> > RegisterSets;
720
721   // Gather the defined sets.
722   for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
723          ie = RegisterClasses.end(); it != ie; ++it)
724     RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
725                                           it->Elements.end()));
726
727   // Add any required singleton sets.
728   for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
729          ie = SingletonRegisterNames.end(); it != ie; ++it)
730     if (Record *Rec = getRegisterRecord(Target, *it))
731       RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
732
733   // Introduce derived sets where necessary (when a register does not determine
734   // a unique register set class), and build the mapping of registers to the set
735   // they should classify to.
736   std::map<Record*, std::set<Record*> > RegisterMap;
737   for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
738          ie = Registers.end(); it != ie; ++it) {
739     CodeGenRegister &CGR = *it;
740     // Compute the intersection of all sets containing this register.
741     std::set<Record*> ContainingSet;
742
743     for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
744            ie = RegisterSets.end(); it != ie; ++it) {
745       if (!it->count(CGR.TheDef))
746         continue;
747
748       if (ContainingSet.empty()) {
749         ContainingSet = *it;
750       } else {
751         std::set<Record*> Tmp;
752         std::swap(Tmp, ContainingSet);
753         std::insert_iterator< std::set<Record*> > II(ContainingSet,
754                                                      ContainingSet.begin());
755         std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
756                               II);
757       }
758     }
759
760     if (!ContainingSet.empty()) {
761       RegisterSets.insert(ContainingSet);
762       RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
763     }
764   }
765
766   // Construct the register classes.
767   std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
768   unsigned Index = 0;
769   for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
770          ie = RegisterSets.end(); it != ie; ++it, ++Index) {
771     ClassInfo *CI = new ClassInfo();
772     CI->Kind = ClassInfo::RegisterClass0 + Index;
773     CI->ClassName = "Reg" + utostr(Index);
774     CI->Name = "MCK_Reg" + utostr(Index);
775     CI->ValueName = "";
776     CI->PredicateMethod = ""; // unused
777     CI->RenderMethod = "addRegOperands";
778     CI->Registers = *it;
779     Classes.push_back(CI);
780     RegisterSetClasses.insert(std::make_pair(*it, CI));
781   }
782
783   // Find the superclasses; we could compute only the subgroup lattice edges,
784   // but there isn't really a point.
785   for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
786          ie = RegisterSets.end(); it != ie; ++it) {
787     ClassInfo *CI = RegisterSetClasses[*it];
788     for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
789            ie2 = RegisterSets.end(); it2 != ie2; ++it2)
790       if (*it != *it2 &&
791           std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
792         CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
793   }
794
795   // Name the register classes which correspond to a user defined RegisterClass.
796   for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
797          ie = RegisterClasses.end(); it != ie; ++it) {
798     ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
799                                                          it->Elements.end())];
800     if (CI->ValueName.empty()) {
801       CI->ClassName = it->getName();
802       CI->Name = "MCK_" + it->getName();
803       CI->ValueName = it->getName();
804     } else
805       CI->ValueName = CI->ValueName + "," + it->getName();
806
807     RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
808   }
809
810   // Populate the map for individual registers.
811   for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
812          ie = RegisterMap.end(); it != ie; ++it)
813     this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
814
815   // Name the register classes which correspond to singleton registers.
816   for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
817          ie = SingletonRegisterNames.end(); it != ie; ++it) {
818     if (Record *Rec = getRegisterRecord(Target, *it)) {
819       ClassInfo *CI = this->RegisterClasses[Rec];
820       assert(CI && "Missing singleton register class info!");
821
822       if (CI->ValueName.empty()) {
823         CI->ClassName = Rec->getName();
824         CI->Name = "MCK_" + Rec->getName();
825         CI->ValueName = Rec->getName();
826       } else
827         CI->ValueName = CI->ValueName + "," + Rec->getName();
828     }
829   }
830 }
831
832 void AsmMatcherInfo::BuildOperandClasses(CodeGenTarget &Target) {
833   std::vector<Record*> AsmOperands;
834   AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
835
836   // Pre-populate AsmOperandClasses map.
837   for (std::vector<Record*>::iterator it = AsmOperands.begin(),
838          ie = AsmOperands.end(); it != ie; ++it)
839     AsmOperandClasses[*it] = new ClassInfo();
840
841   unsigned Index = 0;
842   for (std::vector<Record*>::iterator it = AsmOperands.begin(),
843          ie = AsmOperands.end(); it != ie; ++it, ++Index) {
844     ClassInfo *CI = AsmOperandClasses[*it];
845     CI->Kind = ClassInfo::UserClass0 + Index;
846
847     ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
848     for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
849       DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
850       if (!DI) {
851         PrintError((*it)->getLoc(), "Invalid super class reference!");
852         continue;
853       }
854
855       ClassInfo *SC = AsmOperandClasses[DI->getDef()];
856       if (!SC)
857         PrintError((*it)->getLoc(), "Invalid super class reference!");
858       else
859         CI->SuperClasses.push_back(SC);
860     }
861     CI->ClassName = (*it)->getValueAsString("Name");
862     CI->Name = "MCK_" + CI->ClassName;
863     CI->ValueName = (*it)->getName();
864
865     // Get or construct the predicate method name.
866     Init *PMName = (*it)->getValueInit("PredicateMethod");
867     if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
868       CI->PredicateMethod = SI->getValue();
869     } else {
870       assert(dynamic_cast<UnsetInit*>(PMName) &&
871              "Unexpected PredicateMethod field!");
872       CI->PredicateMethod = "is" + CI->ClassName;
873     }
874
875     // Get or construct the render method name.
876     Init *RMName = (*it)->getValueInit("RenderMethod");
877     if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
878       CI->RenderMethod = SI->getValue();
879     } else {
880       assert(dynamic_cast<UnsetInit*>(RMName) &&
881              "Unexpected RenderMethod field!");
882       CI->RenderMethod = "add" + CI->ClassName + "Operands";
883     }
884
885     AsmOperandClasses[*it] = CI;
886     Classes.push_back(CI);
887   }
888 }
889
890 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser)
891   : AsmParser(asmParser),
892     CommentDelimiter(AsmParser->getValueAsString("CommentDelimiter")),
893     RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix"))
894 {
895 }
896
897 void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
898   // Build information about all of the AssemblerPredicates.
899   std::vector<Record*> AllPredicates =
900     Records.getAllDerivedDefinitions("Predicate");
901   for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
902     Record *Pred = AllPredicates[i];
903     // Ignore predicates that are not intended for the assembler.
904     if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
905       continue;
906     
907     if (Pred->getName().empty()) {
908       PrintError(Pred->getLoc(), "Predicate has no name!");
909       throw std::string("ERROR: Predicate defs must be named");
910     }
911     
912     unsigned FeatureNo = SubtargetFeatures.size();
913     SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
914     assert(FeatureNo < 32 && "Too many subtarget features!");
915   }
916
917   // Parse the instructions; we need to do this first so that we can gather the
918   // singleton register classes.
919   std::set<std::string> SingletonRegisterNames;
920   const std::vector<const CodeGenInstruction*> &InstrList =
921     Target.getInstructionsByEnumValue();
922   for (unsigned i = 0, e = InstrList.size(); i != e; ++i) {
923     const CodeGenInstruction &CGI = *InstrList[i];
924
925     // If the tblgen -match-prefix option is specified (for tblgen hackers),
926     // filter the set of instructions we consider.
927     if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
928       continue;
929
930     OwningPtr<InstructionInfo> II(new InstructionInfo());
931
932     II->InstrName = CGI.TheDef->getName();
933     II->Instr = &CGI;
934     II->AsmString = FlattenVariants(CGI.AsmString, 0);
935
936     // Remove comments from the asm string.  We know that the asmstring only
937     // has one line.
938     if (!CommentDelimiter.empty()) {
939       size_t Idx = StringRef(II->AsmString).find(CommentDelimiter);
940       if (Idx != StringRef::npos)
941         II->AsmString = II->AsmString.substr(0, Idx);
942     }
943
944     TokenizeAsmString(II->AsmString, II->Tokens);
945
946     // Ignore instructions which shouldn't be matched.
947     if (!IsAssemblerInstruction(CGI.TheDef->getName(), CGI, II->Tokens))
948       continue;
949     
950     // Collect singleton registers, if used.
951     for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
952       if (!II->Tokens[i].startswith(RegisterPrefix))
953         continue;
954
955       StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
956       Record *Rec = getRegisterRecord(Target, RegName);
957
958       if (!Rec) {
959         // If there is no register prefix (i.e. "%" in "%eax"), then this may
960         // be some random non-register token, just ignore it.
961         if (RegisterPrefix.empty())
962           continue;
963
964         std::string Err = "unable to find register for '" + RegName.str() +
965           "' (which matches register prefix)";
966         throw TGError(CGI.TheDef->getLoc(), Err);
967       }
968
969       SingletonRegisterNames.insert(RegName);
970     }
971
972     // Compute the require features.
973     std::vector<Record*> Predicates =
974       CGI.TheDef->getValueAsListOfDefs("Predicates");
975     for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
976       if (SubtargetFeatureInfo *Feature = getSubtargetFeature(Predicates[i]))
977         II->RequiredFeatures.push_back(Feature);
978
979     Instructions.push_back(II.take());
980   }
981
982   // Build info for the register classes.
983   BuildRegisterClasses(Target, SingletonRegisterNames);
984
985   // Build info for the user defined assembly operand classes.
986   BuildOperandClasses(Target);
987
988   // Build the instruction information.
989   for (std::vector<InstructionInfo*>::iterator it = Instructions.begin(),
990          ie = Instructions.end(); it != ie; ++it) {
991     InstructionInfo *II = *it;
992
993     // The first token of the instruction is the mnemonic, which must be a
994     // simple string.
995     assert(!II->Tokens.empty() && "Instruction has no tokens?");
996     StringRef Mnemonic = II->Tokens[0];
997     assert(Mnemonic[0] != '$' &&
998            (RegisterPrefix.empty() || !Mnemonic.startswith(RegisterPrefix)));
999
1000     // Parse the tokens after the mnemonic.
1001     for (unsigned i = 1, e = II->Tokens.size(); i != e; ++i) {
1002       StringRef Token = II->Tokens[i];
1003
1004       // Check for singleton registers.
1005       if (Token.startswith(RegisterPrefix)) {
1006         StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
1007         if (Record *RegRecord = getRegisterRecord(Target, RegName)) {
1008           InstructionInfo::Operand Op;
1009           Op.Class = RegisterClasses[RegRecord];
1010           Op.OperandInfo = 0;
1011           assert(Op.Class && Op.Class->Registers.size() == 1 &&
1012                  "Unexpected class for singleton register");
1013           II->Operands.push_back(Op);
1014           continue;
1015         }
1016
1017         if (!RegisterPrefix.empty()) {
1018           std::string Err = "unable to find register for '" + RegName.str() +
1019                   "' (which matches register prefix)";
1020           throw TGError(II->Instr->TheDef->getLoc(), Err);
1021         }
1022       }
1023
1024       // Check for simple tokens.
1025       if (Token[0] != '$') {
1026         InstructionInfo::Operand Op;
1027         Op.Class = getTokenClass(Token);
1028         Op.OperandInfo = 0;
1029         II->Operands.push_back(Op);
1030         continue;
1031       }
1032
1033       // Otherwise this is an operand reference.
1034       StringRef OperandName;
1035       if (Token[1] == '{')
1036         OperandName = Token.substr(2, Token.size() - 3);
1037       else
1038         OperandName = Token.substr(1);
1039
1040       // Map this token to an operand. FIXME: Move elsewhere.
1041       unsigned Idx;
1042       try {
1043         Idx = II->Instr->getOperandNamed(OperandName);
1044       } catch(...) {
1045         throw std::string("error: unable to find operand: '" +
1046                           OperandName.str() + "'");
1047       }
1048
1049       // FIXME: This is annoying, the named operand may be tied (e.g.,
1050       // XCHG8rm). What we want is the untied operand, which we now have to
1051       // grovel for. Only worry about this for single entry operands, we have to
1052       // clean this up anyway.
1053       const CodeGenInstruction::OperandInfo *OI = &II->Instr->OperandList[Idx];
1054       if (OI->Constraints[0].isTied()) {
1055         unsigned TiedOp = OI->Constraints[0].getTiedOperand();
1056
1057         // The tied operand index is an MIOperand index, find the operand that
1058         // contains it.
1059         for (unsigned i = 0, e = II->Instr->OperandList.size(); i != e; ++i) {
1060           if (II->Instr->OperandList[i].MIOperandNo == TiedOp) {
1061             OI = &II->Instr->OperandList[i];
1062             break;
1063           }
1064         }
1065
1066         assert(OI && "Unable to find tied operand target!");
1067       }
1068
1069       InstructionInfo::Operand Op;
1070       Op.Class = getOperandClass(Token, *OI);
1071       Op.OperandInfo = OI;
1072       II->Operands.push_back(Op);
1073     }
1074   }
1075
1076   // Reorder classes so that classes preceed super classes.
1077   std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
1078 }
1079
1080 static std::pair<unsigned, unsigned> *
1081 GetTiedOperandAtIndex(SmallVectorImpl<std::pair<unsigned, unsigned> > &List,
1082                       unsigned Index) {
1083   for (unsigned i = 0, e = List.size(); i != e; ++i)
1084     if (Index == List[i].first)
1085       return &List[i];
1086
1087   return 0;
1088 }
1089
1090 static void EmitConvertToMCInst(CodeGenTarget &Target,
1091                                 std::vector<InstructionInfo*> &Infos,
1092                                 raw_ostream &OS) {
1093   // Write the convert function to a separate stream, so we can drop it after
1094   // the enum.
1095   std::string ConvertFnBody;
1096   raw_string_ostream CvtOS(ConvertFnBody);
1097
1098   // Function we have already generated.
1099   std::set<std::string> GeneratedFns;
1100
1101   // Start the unified conversion function.
1102
1103   CvtOS << "static void ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
1104         << "unsigned Opcode,\n"
1105         << "                      const SmallVectorImpl<MCParsedAsmOperand*"
1106         << "> &Operands) {\n";
1107   CvtOS << "  Inst.setOpcode(Opcode);\n";
1108   CvtOS << "  switch (Kind) {\n";
1109   CvtOS << "  default:\n";
1110
1111   // Start the enum, which we will generate inline.
1112
1113   OS << "// Unified function for converting operants to MCInst instances.\n\n";
1114   OS << "enum ConversionKind {\n";
1115
1116   // TargetOperandClass - This is the target's operand class, like X86Operand.
1117   std::string TargetOperandClass = Target.getName() + "Operand";
1118
1119   for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
1120          ie = Infos.end(); it != ie; ++it) {
1121     InstructionInfo &II = **it;
1122
1123     // Order the (class) operands by the order to convert them into an MCInst.
1124     SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
1125     for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1126       InstructionInfo::Operand &Op = II.Operands[i];
1127       if (Op.OperandInfo)
1128         MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
1129     }
1130
1131     // Find any tied operands.
1132     SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands;
1133     for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1134       const CodeGenInstruction::OperandInfo &OpInfo = II.Instr->OperandList[i];
1135       for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) {
1136         const CodeGenInstruction::ConstraintInfo &CI = OpInfo.Constraints[j];
1137         if (CI.isTied())
1138           TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo + j,
1139                                                 CI.getTiedOperand()));
1140       }
1141     }
1142
1143     std::sort(MIOperandList.begin(), MIOperandList.end());
1144
1145     // Compute the total number of operands.
1146     unsigned NumMIOperands = 0;
1147     for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1148       const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
1149       NumMIOperands = std::max(NumMIOperands,
1150                                OI.MIOperandNo + OI.MINumOperands);
1151     }
1152
1153     // Build the conversion function signature.
1154     std::string Signature = "Convert";
1155     unsigned CurIndex = 0;
1156     for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1157       InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1158       assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
1159              "Duplicate match for instruction operand!");
1160
1161       // Skip operands which weren't matched by anything, this occurs when the
1162       // .td file encodes "implicit" operands as explicit ones.
1163       //
1164       // FIXME: This should be removed from the MCInst structure.
1165       for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1166         std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1167                                                                    CurIndex);
1168         if (!Tie)
1169           Signature += "__Imp";
1170         else
1171           Signature += "__Tie" + utostr(Tie->second);
1172       }
1173
1174       Signature += "__";
1175
1176       // Registers are always converted the same, don't duplicate the conversion
1177       // function based on them.
1178       //
1179       // FIXME: We could generalize this based on the render method, if it
1180       // mattered.
1181       if (Op.Class->isRegisterClass())
1182         Signature += "Reg";
1183       else
1184         Signature += Op.Class->ClassName;
1185       Signature += utostr(Op.OperandInfo->MINumOperands);
1186       Signature += "_" + utostr(MIOperandList[i].second);
1187
1188       CurIndex += Op.OperandInfo->MINumOperands;
1189     }
1190
1191     // Add any trailing implicit operands.
1192     for (; CurIndex != NumMIOperands; ++CurIndex) {
1193       std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1194                                                                  CurIndex);
1195       if (!Tie)
1196         Signature += "__Imp";
1197       else
1198         Signature += "__Tie" + utostr(Tie->second);
1199     }
1200
1201     II.ConversionFnKind = Signature;
1202
1203     // Check if we have already generated this signature.
1204     if (!GeneratedFns.insert(Signature).second)
1205       continue;
1206
1207     // If not, emit it now.
1208
1209     // Add to the enum list.
1210     OS << "  " << Signature << ",\n";
1211
1212     // And to the convert function.
1213     CvtOS << "  case " << Signature << ":\n";
1214     CurIndex = 0;
1215     for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1216       InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1217
1218       // Add the implicit operands.
1219       for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1220         // See if this is a tied operand.
1221         std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1222                                                                    CurIndex);
1223
1224         if (!Tie) {
1225           // If not, this is some implicit operand. Just assume it is a register
1226           // for now.
1227           CvtOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
1228         } else {
1229           // Copy the tied operand.
1230           assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1231           CvtOS << "    Inst.addOperand(Inst.getOperand("
1232                 << Tie->second << "));\n";
1233         }
1234       }
1235
1236       CvtOS << "    ((" << TargetOperandClass << "*)Operands["
1237          << MIOperandList[i].second
1238          << "+1])->" << Op.Class->RenderMethod
1239          << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
1240       CurIndex += Op.OperandInfo->MINumOperands;
1241     }
1242
1243     // And add trailing implicit operands.
1244     for (; CurIndex != NumMIOperands; ++CurIndex) {
1245       std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1246                                                                  CurIndex);
1247
1248       if (!Tie) {
1249         // If not, this is some implicit operand. Just assume it is a register
1250         // for now.
1251         CvtOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
1252       } else {
1253         // Copy the tied operand.
1254         assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1255         CvtOS << "    Inst.addOperand(Inst.getOperand("
1256               << Tie->second << "));\n";
1257       }
1258     }
1259
1260     CvtOS << "    return;\n";
1261   }
1262
1263   // Finish the convert function.
1264
1265   CvtOS << "  }\n";
1266   CvtOS << "}\n\n";
1267
1268   // Finish the enum, and drop the convert function after it.
1269
1270   OS << "  NumConversionVariants\n";
1271   OS << "};\n\n";
1272
1273   OS << CvtOS.str();
1274 }
1275
1276 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1277 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1278                                       std::vector<ClassInfo*> &Infos,
1279                                       raw_ostream &OS) {
1280   OS << "namespace {\n\n";
1281
1282   OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1283      << "/// instruction matching.\n";
1284   OS << "enum MatchClassKind {\n";
1285   OS << "  InvalidMatchClass = 0,\n";
1286   for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1287          ie = Infos.end(); it != ie; ++it) {
1288     ClassInfo &CI = **it;
1289     OS << "  " << CI.Name << ", // ";
1290     if (CI.Kind == ClassInfo::Token) {
1291       OS << "'" << CI.ValueName << "'\n";
1292     } else if (CI.isRegisterClass()) {
1293       if (!CI.ValueName.empty())
1294         OS << "register class '" << CI.ValueName << "'\n";
1295       else
1296         OS << "derived register class\n";
1297     } else {
1298       OS << "user defined class '" << CI.ValueName << "'\n";
1299     }
1300   }
1301   OS << "  NumMatchClassKinds\n";
1302   OS << "};\n\n";
1303
1304   OS << "}\n\n";
1305 }
1306
1307 /// EmitClassifyOperand - Emit the function to classify an operand.
1308 static void EmitClassifyOperand(CodeGenTarget &Target,
1309                                 AsmMatcherInfo &Info,
1310                                 raw_ostream &OS) {
1311   OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
1312      << "  " << Target.getName() << "Operand &Operand = *("
1313      << Target.getName() << "Operand*)GOp;\n";
1314
1315   // Classify tokens.
1316   OS << "  if (Operand.isToken())\n";
1317   OS << "    return MatchTokenString(Operand.getToken());\n\n";
1318
1319   // Classify registers.
1320   //
1321   // FIXME: Don't hardcode isReg, getReg.
1322   OS << "  if (Operand.isReg()) {\n";
1323   OS << "    switch (Operand.getReg()) {\n";
1324   OS << "    default: return InvalidMatchClass;\n";
1325   for (std::map<Record*, ClassInfo*>::iterator
1326          it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1327        it != ie; ++it)
1328     OS << "    case " << Target.getName() << "::"
1329        << it->first->getName() << ": return " << it->second->Name << ";\n";
1330   OS << "    }\n";
1331   OS << "  }\n\n";
1332
1333   // Classify user defined operands.
1334   for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1335          ie = Info.Classes.end(); it != ie; ++it) {
1336     ClassInfo &CI = **it;
1337
1338     if (!CI.isUserClass())
1339       continue;
1340
1341     OS << "  // '" << CI.ClassName << "' class";
1342     if (!CI.SuperClasses.empty()) {
1343       OS << ", subclass of ";
1344       for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1345         if (i) OS << ", ";
1346         OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1347         assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
1348       }
1349     }
1350     OS << "\n";
1351
1352     OS << "  if (Operand." << CI.PredicateMethod << "()) {\n";
1353
1354     // Validate subclass relationships.
1355     if (!CI.SuperClasses.empty()) {
1356       for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1357         OS << "    assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1358            << "() && \"Invalid class relationship!\");\n";
1359     }
1360
1361     OS << "    return " << CI.Name << ";\n";
1362     OS << "  }\n\n";
1363   }
1364   OS << "  return InvalidMatchClass;\n";
1365   OS << "}\n\n";
1366 }
1367
1368 /// EmitIsSubclass - Emit the subclass predicate function.
1369 static void EmitIsSubclass(CodeGenTarget &Target,
1370                            std::vector<ClassInfo*> &Infos,
1371                            raw_ostream &OS) {
1372   OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1373   OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1374   OS << "  if (A == B)\n";
1375   OS << "    return true;\n\n";
1376
1377   OS << "  switch (A) {\n";
1378   OS << "  default:\n";
1379   OS << "    return false;\n";
1380   for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1381          ie = Infos.end(); it != ie; ++it) {
1382     ClassInfo &A = **it;
1383
1384     if (A.Kind != ClassInfo::Token) {
1385       std::vector<StringRef> SuperClasses;
1386       for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1387              ie = Infos.end(); it != ie; ++it) {
1388         ClassInfo &B = **it;
1389
1390         if (&A != &B && A.isSubsetOf(B))
1391           SuperClasses.push_back(B.Name);
1392       }
1393
1394       if (SuperClasses.empty())
1395         continue;
1396
1397       OS << "\n  case " << A.Name << ":\n";
1398
1399       if (SuperClasses.size() == 1) {
1400         OS << "    return B == " << SuperClasses.back() << ";\n";
1401         continue;
1402       }
1403
1404       OS << "    switch (B) {\n";
1405       OS << "    default: return false;\n";
1406       for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1407         OS << "    case " << SuperClasses[i] << ": return true;\n";
1408       OS << "    }\n";
1409     }
1410   }
1411   OS << "  }\n";
1412   OS << "}\n\n";
1413 }
1414
1415
1416
1417 /// EmitMatchTokenString - Emit the function to match a token string to the
1418 /// appropriate match class value.
1419 static void EmitMatchTokenString(CodeGenTarget &Target,
1420                                  std::vector<ClassInfo*> &Infos,
1421                                  raw_ostream &OS) {
1422   // Construct the match list.
1423   std::vector<StringMatcher::StringPair> Matches;
1424   for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1425          ie = Infos.end(); it != ie; ++it) {
1426     ClassInfo &CI = **it;
1427
1428     if (CI.Kind == ClassInfo::Token)
1429       Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1430                                                   "return " + CI.Name + ";"));
1431   }
1432
1433   OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
1434
1435   StringMatcher("Name", Matches, OS).Emit();
1436
1437   OS << "  return InvalidMatchClass;\n";
1438   OS << "}\n\n";
1439 }
1440
1441 /// EmitMatchRegisterName - Emit the function to match a string to the target
1442 /// specific register enum.
1443 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1444                                   raw_ostream &OS) {
1445   // Construct the match list.
1446   std::vector<StringMatcher::StringPair> Matches;
1447   for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1448     const CodeGenRegister &Reg = Target.getRegisters()[i];
1449     if (Reg.TheDef->getValueAsString("AsmName").empty())
1450       continue;
1451
1452     Matches.push_back(StringMatcher::StringPair(
1453                                         Reg.TheDef->getValueAsString("AsmName"),
1454                                         "return " + utostr(i + 1) + ";"));
1455   }
1456
1457   OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
1458
1459   StringMatcher("Name", Matches, OS).Emit();
1460
1461   OS << "  return 0;\n";
1462   OS << "}\n\n";
1463 }
1464
1465 /// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1466 /// definitions.
1467 static void EmitSubtargetFeatureFlagEnumeration(CodeGenTarget &Target,
1468                                                 AsmMatcherInfo &Info,
1469                                                 raw_ostream &OS) {
1470   OS << "// Flags for subtarget features that participate in "
1471      << "instruction matching.\n";
1472   OS << "enum SubtargetFeatureFlag {\n";
1473   for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1474          it = Info.SubtargetFeatures.begin(),
1475          ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1476     SubtargetFeatureInfo &SFI = *it->second;
1477     OS << "  " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
1478   }
1479   OS << "  Feature_None = 0\n";
1480   OS << "};\n\n";
1481 }
1482
1483 /// EmitComputeAvailableFeatures - Emit the function to compute the list of
1484 /// available features given a subtarget.
1485 static void EmitComputeAvailableFeatures(CodeGenTarget &Target,
1486                                          AsmMatcherInfo &Info,
1487                                          raw_ostream &OS) {
1488   std::string ClassName =
1489     Info.AsmParser->getValueAsString("AsmParserClassName");
1490
1491   OS << "unsigned " << Target.getName() << ClassName << "::\n"
1492      << "ComputeAvailableFeatures(const " << Target.getName()
1493      << "Subtarget *Subtarget) const {\n";
1494   OS << "  unsigned Features = 0;\n";
1495   for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1496          it = Info.SubtargetFeatures.begin(),
1497          ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1498     SubtargetFeatureInfo &SFI = *it->second;
1499     OS << "  if (" << SFI.TheDef->getValueAsString("CondString")
1500        << ")\n";
1501     OS << "    Features |= " << SFI.getEnumName() << ";\n";
1502   }
1503   OS << "  return Features;\n";
1504   OS << "}\n\n";
1505 }
1506
1507 static std::string GetAliasRequiredFeatures(Record *R,
1508                                             const AsmMatcherInfo &Info) {
1509   std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
1510   std::string Result;
1511   unsigned NumFeatures = 0;
1512   for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
1513     if (SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i])) {
1514       if (NumFeatures)
1515         Result += '|';
1516     
1517       Result += F->getEnumName();
1518       ++NumFeatures;
1519     }
1520   }
1521   
1522   if (NumFeatures > 1)
1523     Result = '(' + Result + ')';
1524   return Result;
1525 }
1526
1527 /// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
1528 /// emit a function for them and return true, otherwise return false.
1529 static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
1530   std::vector<Record*> Aliases =
1531     Records.getAllDerivedDefinitions("MnemonicAlias");
1532   if (Aliases.empty()) return false;
1533
1534   OS << "static void ApplyMnemonicAliases(StringRef &Mnemonic, "
1535         "unsigned Features) {\n";
1536   
1537   // Keep track of all the aliases from a mnemonic.  Use an std::map so that the
1538   // iteration order of the map is stable.
1539   std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1540   
1541   for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1542     Record *R = Aliases[i];
1543     AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
1544   }
1545
1546   // Process each alias a "from" mnemonic at a time, building the code executed
1547   // by the string remapper.
1548   std::vector<StringMatcher::StringPair> Cases;
1549   for (std::map<std::string, std::vector<Record*> >::iterator
1550        I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1551        I != E; ++I) {
1552     const std::vector<Record*> &ToVec = I->second;
1553
1554     // Loop through each alias and emit code that handles each case.  If there
1555     // are two instructions without predicates, emit an error.  If there is one,
1556     // emit it last.
1557     std::string MatchCode;
1558     int AliasWithNoPredicate = -1;
1559     
1560     for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1561       Record *R = ToVec[i];
1562       std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
1563     
1564       // If this unconditionally matches, remember it for later and diagnose
1565       // duplicates.
1566       if (FeatureMask.empty()) {
1567         if (AliasWithNoPredicate != -1) {
1568           // We can't have two aliases from the same mnemonic with no predicate.
1569           PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1570                      "two MnemonicAliases with the same 'from' mnemonic!");
1571           PrintError(R->getLoc(), "this is the other MnemonicAlias.");
1572           throw std::string("ERROR: Invalid MnemonicAlias definitions!");
1573         }
1574         
1575         AliasWithNoPredicate = i;
1576         continue;
1577       }
1578      
1579       if (!MatchCode.empty())
1580         MatchCode += "else ";
1581       MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1582       MatchCode += "  Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
1583     }
1584     
1585     if (AliasWithNoPredicate != -1) {
1586       Record *R = ToVec[AliasWithNoPredicate];
1587       if (!MatchCode.empty())
1588         MatchCode += "else\n  ";
1589       MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
1590     }
1591     
1592     MatchCode += "return;";
1593
1594     Cases.push_back(std::make_pair(I->first, MatchCode));
1595   }
1596   
1597   
1598   StringMatcher("Mnemonic", Cases, OS).Emit();
1599   OS << "}\n";
1600   
1601   return true;
1602 }
1603
1604 void AsmMatcherEmitter::run(raw_ostream &OS) {
1605   CodeGenTarget Target;
1606   Record *AsmParser = Target.getAsmParser();
1607   std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1608
1609   // Compute the information on the instructions to match.
1610   AsmMatcherInfo Info(AsmParser);
1611   Info.BuildInfo(Target);
1612
1613   // Sort the instruction table using the partial order on classes. We use
1614   // stable_sort to ensure that ambiguous instructions are still
1615   // deterministically ordered.
1616   std::stable_sort(Info.Instructions.begin(), Info.Instructions.end(),
1617                    less_ptr<InstructionInfo>());
1618
1619   DEBUG_WITH_TYPE("instruction_info", {
1620       for (std::vector<InstructionInfo*>::iterator
1621              it = Info.Instructions.begin(), ie = Info.Instructions.end();
1622            it != ie; ++it)
1623         (*it)->dump();
1624     });
1625
1626   // Check for ambiguous instructions.
1627   DEBUG_WITH_TYPE("ambiguous_instrs", {
1628     unsigned NumAmbiguous = 0;
1629     for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1630       for (unsigned j = i + 1; j != e; ++j) {
1631         InstructionInfo &A = *Info.Instructions[i];
1632         InstructionInfo &B = *Info.Instructions[j];
1633
1634         if (A.CouldMatchAmiguouslyWith(B)) {
1635           errs() << "warning: ambiguous instruction match:\n";
1636           A.dump();
1637           errs() << "\nis incomparable with:\n";
1638           B.dump();
1639           errs() << "\n\n";
1640           ++NumAmbiguous;
1641         }
1642       }
1643     }
1644     if (NumAmbiguous)
1645       errs() << "warning: " << NumAmbiguous
1646              << " ambiguous instructions!\n";
1647   });
1648
1649   // Write the output.
1650
1651   EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1652
1653   // Information for the class declaration.
1654   OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
1655   OS << "#undef GET_ASSEMBLER_HEADER\n";
1656   OS << "  // This should be included into the middle of the declaration of \n";
1657   OS << "  // your subclasses implementation of TargetAsmParser.\n";
1658   OS << "  unsigned ComputeAvailableFeatures(const " <<
1659            Target.getName() << "Subtarget *Subtarget) const;\n";
1660   OS << "  enum MatchResultTy {\n";
1661   OS << "    Match_Success, Match_MnemonicFail, Match_InvalidOperand,\n";
1662   OS << "    Match_MissingFeature\n";
1663   OS << "  };\n";
1664   OS << "  MatchResultTy MatchInstructionImpl(const "
1665      << "SmallVectorImpl<MCParsedAsmOperand*>"
1666      << " &Operands, MCInst &Inst, unsigned &ErrorInfo);\n\n";
1667   OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
1668
1669
1670
1671
1672   OS << "\n#ifdef GET_REGISTER_MATCHER\n";
1673   OS << "#undef GET_REGISTER_MATCHER\n\n";
1674
1675   // Emit the subtarget feature enumeration.
1676   EmitSubtargetFeatureFlagEnumeration(Target, Info, OS);
1677
1678   // Emit the function to match a register name to number.
1679   EmitMatchRegisterName(Target, AsmParser, OS);
1680
1681   OS << "#endif // GET_REGISTER_MATCHER\n\n";
1682
1683
1684   OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
1685   OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
1686
1687   // Generate the function that remaps for mnemonic aliases.
1688   bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
1689   
1690   // Generate the unified function to convert operands into an MCInst.
1691   EmitConvertToMCInst(Target, Info.Instructions, OS);
1692
1693   // Emit the enumeration for classes which participate in matching.
1694   EmitMatchClassEnumeration(Target, Info.Classes, OS);
1695
1696   // Emit the routine to match token strings to their match class.
1697   EmitMatchTokenString(Target, Info.Classes, OS);
1698
1699   // Emit the routine to classify an operand.
1700   EmitClassifyOperand(Target, Info, OS);
1701
1702   // Emit the subclass predicate routine.
1703   EmitIsSubclass(Target, Info.Classes, OS);
1704
1705   // Emit the available features compute function.
1706   EmitComputeAvailableFeatures(Target, Info, OS);
1707
1708
1709   size_t MaxNumOperands = 0;
1710   for (std::vector<InstructionInfo*>::const_iterator it =
1711          Info.Instructions.begin(), ie = Info.Instructions.end();
1712        it != ie; ++it)
1713     MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1714
1715
1716   // Emit the static match table; unused classes get initalized to 0 which is
1717   // guaranteed to be InvalidMatchClass.
1718   //
1719   // FIXME: We can reduce the size of this table very easily. First, we change
1720   // it so that store the kinds in separate bit-fields for each index, which
1721   // only needs to be the max width used for classes at that index (we also need
1722   // to reject based on this during classification). If we then make sure to
1723   // order the match kinds appropriately (putting mnemonics last), then we
1724   // should only end up using a few bits for each class, especially the ones
1725   // following the mnemonic.
1726   OS << "namespace {\n";
1727   OS << "  struct MatchEntry {\n";
1728   OS << "    unsigned Opcode;\n";
1729   OS << "    const char *Mnemonic;\n";
1730   OS << "    ConversionKind ConvertFn;\n";
1731   OS << "    MatchClassKind Classes[" << MaxNumOperands << "];\n";
1732   OS << "    unsigned RequiredFeatures;\n";
1733   OS << "  };\n\n";
1734
1735   OS << "// Predicate for searching for an opcode.\n";
1736   OS << "  struct LessOpcode {\n";
1737   OS << "    bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
1738   OS << "      return StringRef(LHS.Mnemonic) < RHS;\n";
1739   OS << "    }\n";
1740   OS << "    bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
1741   OS << "      return LHS < StringRef(RHS.Mnemonic);\n";
1742   OS << "    }\n";
1743   OS << "    bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
1744   OS << "      return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
1745   OS << "    }\n";
1746   OS << "  };\n";
1747
1748   OS << "} // end anonymous namespace.\n\n";
1749
1750   OS << "static const MatchEntry MatchTable["
1751      << Info.Instructions.size() << "] = {\n";
1752
1753   for (std::vector<InstructionInfo*>::const_iterator it =
1754        Info.Instructions.begin(), ie = Info.Instructions.end();
1755        it != ie; ++it) {
1756     InstructionInfo &II = **it;
1757
1758     OS << "  { " << Target.getName() << "::" << II.InstrName
1759     << ", \"" << II.Tokens[0] << "\""
1760     << ", " << II.ConversionFnKind << ", { ";
1761     for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1762       InstructionInfo::Operand &Op = II.Operands[i];
1763
1764       if (i) OS << ", ";
1765       OS << Op.Class->Name;
1766     }
1767     OS << " }, ";
1768
1769     // Write the required features mask.
1770     if (!II.RequiredFeatures.empty()) {
1771       for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
1772         if (i) OS << "|";
1773         OS << II.RequiredFeatures[i]->getEnumName();
1774       }
1775     } else
1776       OS << "0";
1777
1778     OS << "},\n";
1779   }
1780
1781   OS << "};\n\n";
1782
1783   // Finally, build the match function.
1784   OS << Target.getName() << ClassName << "::MatchResultTy "
1785      << Target.getName() << ClassName << "::\n"
1786      << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
1787      << " &Operands,\n";
1788   OS << "                     MCInst &Inst, unsigned &ErrorInfo) {\n";
1789
1790   // Emit code to get the available features.
1791   OS << "  // Get the current feature set.\n";
1792   OS << "  unsigned AvailableFeatures = getAvailableFeatures();\n\n";
1793
1794   OS << "  // Get the instruction mnemonic, which is the first token.\n";
1795   OS << "  StringRef Mnemonic = ((" << Target.getName()
1796      << "Operand*)Operands[0])->getToken();\n\n";
1797
1798   if (HasMnemonicAliases) {
1799     OS << "  // Process all MnemonicAliases to remap the mnemonic.\n";
1800     OS << "  ApplyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
1801   }
1802   
1803   // Emit code to compute the class list for this operand vector.
1804   OS << "  // Eliminate obvious mismatches.\n";
1805   OS << "  if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
1806   OS << "    ErrorInfo = " << (MaxNumOperands+1) << ";\n";
1807   OS << "    return Match_InvalidOperand;\n";
1808   OS << "  }\n\n";
1809
1810   OS << "  // Compute the class list for this operand vector.\n";
1811   OS << "  MatchClassKind Classes[" << MaxNumOperands << "];\n";
1812   OS << "  for (unsigned i = 1, e = Operands.size(); i != e; ++i) {\n";
1813   OS << "    Classes[i-1] = ClassifyOperand(Operands[i]);\n\n";
1814
1815   OS << "    // Check for invalid operands before matching.\n";
1816   OS << "    if (Classes[i-1] == InvalidMatchClass) {\n";
1817   OS << "      ErrorInfo = i;\n";
1818   OS << "      return Match_InvalidOperand;\n";
1819   OS << "    }\n";
1820   OS << "  }\n\n";
1821
1822   OS << "  // Mark unused classes.\n";
1823   OS << "  for (unsigned i = Operands.size()-1, e = " << MaxNumOperands << "; "
1824      << "i != e; ++i)\n";
1825   OS << "    Classes[i] = InvalidMatchClass;\n\n";
1826
1827   OS << "  // Some state to try to produce better error messages.\n";
1828   OS << "  bool HadMatchOtherThanFeatures = false;\n\n";
1829   OS << "  // Set ErrorInfo to the operand that mismatches if it is \n";
1830   OS << "  // wrong for all instances of the instruction.\n";
1831   OS << "  ErrorInfo = ~0U;\n";
1832
1833   // Emit code to search the table.
1834   OS << "  // Search the table.\n";
1835   OS << "  std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
1836   OS << "    std::equal_range(MatchTable, MatchTable+"
1837      << Info.Instructions.size() << ", Mnemonic, LessOpcode());\n\n";
1838
1839   OS << "  // Return a more specific error code if no mnemonics match.\n";
1840   OS << "  if (MnemonicRange.first == MnemonicRange.second)\n";
1841   OS << "    return Match_MnemonicFail;\n\n";
1842
1843   OS << "  for (const MatchEntry *it = MnemonicRange.first, "
1844      << "*ie = MnemonicRange.second;\n";
1845   OS << "       it != ie; ++it) {\n";
1846
1847   OS << "    // equal_range guarantees that instruction mnemonic matches.\n";
1848   OS << "    assert(Mnemonic == it->Mnemonic);\n";
1849
1850   // Emit check that the subclasses match.
1851   OS << "    bool OperandsValid = true;\n";
1852   OS << "    for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
1853   OS << "      if (IsSubclass(Classes[i], it->Classes[i]))\n";
1854   OS << "        continue;\n";
1855   OS << "      // If this operand is broken for all of the instances of this\n";
1856   OS << "      // mnemonic, keep track of it so we can report loc info.\n";
1857   OS << "      if (it == MnemonicRange.first || ErrorInfo == i+1)\n";
1858   OS << "        ErrorInfo = i+1;\n";
1859   OS << "      else\n";
1860   OS << "        ErrorInfo = ~0U;";
1861   OS << "      // Otherwise, just reject this instance of the mnemonic.\n";
1862   OS << "      OperandsValid = false;\n";
1863   OS << "      break;\n";
1864   OS << "    }\n\n";
1865
1866   OS << "    if (!OperandsValid) continue;\n";
1867
1868   // Emit check that the required features are available.
1869   OS << "    if ((AvailableFeatures & it->RequiredFeatures) "
1870      << "!= it->RequiredFeatures) {\n";
1871   OS << "      HadMatchOtherThanFeatures = true;\n";
1872   OS << "      continue;\n";
1873   OS << "    }\n";
1874
1875   OS << "\n";
1876   OS << "    ConvertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
1877
1878   // Call the post-processing function, if used.
1879   std::string InsnCleanupFn =
1880     AsmParser->getValueAsString("AsmParserInstCleanup");
1881   if (!InsnCleanupFn.empty())
1882     OS << "    " << InsnCleanupFn << "(Inst);\n";
1883
1884   OS << "    return Match_Success;\n";
1885   OS << "  }\n\n";
1886
1887   OS << "  // Okay, we had no match.  Try to return a useful error code.\n";
1888   OS << "  if (HadMatchOtherThanFeatures) return Match_MissingFeature;\n";
1889   OS << "  return Match_InvalidOperand;\n";
1890   OS << "}\n\n";
1891
1892   OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
1893 }