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