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