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