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