4d18516d69bae15a8d023829ae3ee02d6705e657
[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. It also emits a matcher for
12 // custom operand parsing.
13 //
14 // Converting assembly operands into MCInst structures
15 // ---------------------------------------------------
16 //
17 // The input to the target specific matcher is a list of literal tokens and
18 // operands. The target specific parser should generally eliminate any syntax
19 // which is not relevant for matching; for example, comma tokens should have
20 // already been consumed and eliminated by the parser. Most instructions will
21 // end up with a single literal token (the instruction name) and some number of
22 // operands.
23 //
24 // Some example inputs, for X86:
25 //   'addl' (immediate ...) (register ...)
26 //   'add' (immediate ...) (memory ...)
27 //   'call' '*' %epc
28 //
29 // The assembly matcher is responsible for converting this input into a precise
30 // machine instruction (i.e., an instruction with a well defined encoding). This
31 // mapping has several properties which complicate matching:
32 //
33 //  - It may be ambiguous; many architectures can legally encode particular
34 //    variants of an instruction in different ways (for example, using a smaller
35 //    encoding for small immediates). Such ambiguities should never be
36 //    arbitrarily resolved by the assembler, the assembler is always responsible
37 //    for choosing the "best" available instruction.
38 //
39 //  - It may depend on the subtarget or the assembler context. Instructions
40 //    which are invalid for the current mode, but otherwise unambiguous (e.g.,
41 //    an SSE instruction in a file being assembled for i486) should be accepted
42 //    and rejected by the assembler front end. However, if the proper encoding
43 //    for an instruction is dependent on the assembler context then the matcher
44 //    is responsible for selecting the correct machine instruction for the
45 //    current mode.
46 //
47 // The core matching algorithm attempts to exploit the regularity in most
48 // instruction sets to quickly determine the set of possibly matching
49 // instructions, and the simplify the generated code. Additionally, this helps
50 // to ensure that the ambiguities are intentionally resolved by the user.
51 //
52 // The matching is divided into two distinct phases:
53 //
54 //   1. Classification: Each operand is mapped to the unique set which (a)
55 //      contains it, and (b) is the largest such subset for which a single
56 //      instruction could match all members.
57 //
58 //      For register classes, we can generate these subgroups automatically. For
59 //      arbitrary operands, we expect the user to define the classes and their
60 //      relations to one another (for example, 8-bit signed immediates as a
61 //      subset of 32-bit immediates).
62 //
63 //      By partitioning the operands in this way, we guarantee that for any
64 //      tuple of classes, any single instruction must match either all or none
65 //      of the sets of operands which could classify to that tuple.
66 //
67 //      In addition, the subset relation amongst classes induces a partial order
68 //      on such tuples, which we use to resolve ambiguities.
69 //
70 //   2. The input can now be treated as a tuple of classes (static tokens are
71 //      simple singleton sets). Each such tuple should generally map to a single
72 //      instruction (we currently ignore cases where this isn't true, whee!!!),
73 //      which we can emit a simple matcher for.
74 //
75 // Custom Operand Parsing
76 // ----------------------
77 //
78 //  Some targets need a custom way to parse operands, some specific instructions
79 //  can contain arguments that can represent processor flags and other kinds of
80 //  identifiers that need to be mapped to specific valeus in the final encoded
81 //  instructions. The target specific custom operand parsing works in the
82 //  following way:
83 //
84 //   1. A operand match table is built, each entry contains a mnemonic, an
85 //      operand class, a mask for all operand positions for that same
86 //      class/mnemonic and target features to be checked while trying to match.
87 //
88 //   2. The operand matcher will try every possible entry with the same
89 //      mnemonic and will check if the target feature for this mnemonic also
90 //      matches. After that, if the operand to be matched has its index
91 //      present in the mask, a successful match occurs. Otherwise, fallback
92 //      to the regular operand parsing.
93 //
94 //   3. For a match success, each operand class that has a 'ParserMethod'
95 //      becomes part of a switch from where the custom method is called.
96 //
97 //===----------------------------------------------------------------------===//
98
99 #include "AsmMatcherEmitter.h"
100 #include "CodeGenTarget.h"
101 #include "StringMatcher.h"
102 #include "llvm/ADT/OwningPtr.h"
103 #include "llvm/ADT/PointerUnion.h"
104 #include "llvm/ADT/SmallPtrSet.h"
105 #include "llvm/ADT/SmallVector.h"
106 #include "llvm/ADT/STLExtras.h"
107 #include "llvm/ADT/StringExtras.h"
108 #include "llvm/Support/CommandLine.h"
109 #include "llvm/Support/Debug.h"
110 #include "llvm/TableGen/Error.h"
111 #include "llvm/TableGen/Record.h"
112 #include <map>
113 #include <set>
114 using namespace llvm;
115
116 static cl::opt<std::string>
117 MatchPrefix("match-prefix", cl::init(""),
118             cl::desc("Only match instructions with the given prefix"));
119
120 namespace {
121 class AsmMatcherInfo;
122 struct SubtargetFeatureInfo;
123
124 /// ClassInfo - Helper class for storing the information about a particular
125 /// class of operands which can be matched.
126 struct ClassInfo {
127   enum ClassInfoKind {
128     /// Invalid kind, for use as a sentinel value.
129     Invalid = 0,
130
131     /// The class for a particular token.
132     Token,
133
134     /// The (first) register class, subsequent register classes are
135     /// RegisterClass0+1, and so on.
136     RegisterClass0,
137
138     /// The (first) user defined class, subsequent user defined classes are
139     /// UserClass0+1, and so on.
140     UserClass0 = 1<<16
141   };
142
143   /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
144   /// N) for the Nth user defined class.
145   unsigned Kind;
146
147   /// SuperClasses - The super classes of this class. Note that for simplicities
148   /// sake user operands only record their immediate super class, while register
149   /// operands include all superclasses.
150   std::vector<ClassInfo*> SuperClasses;
151
152   /// Name - The full class name, suitable for use in an enum.
153   std::string Name;
154
155   /// ClassName - The unadorned generic name for this class (e.g., Token).
156   std::string ClassName;
157
158   /// ValueName - The name of the value this class represents; for a token this
159   /// is the literal token string, for an operand it is the TableGen class (or
160   /// empty if this is a derived class).
161   std::string ValueName;
162
163   /// PredicateMethod - The name of the operand method to test whether the
164   /// operand matches this class; this is not valid for Token or register kinds.
165   std::string PredicateMethod;
166
167   /// RenderMethod - The name of the operand method to add this operand to an
168   /// MCInst; this is not valid for Token or register kinds.
169   std::string RenderMethod;
170
171   /// ParserMethod - The name of the operand method to do a target specific
172   /// parsing on the operand.
173   std::string ParserMethod;
174
175   /// For register classes, the records for all the registers in this class.
176   std::set<Record*> Registers;
177
178 public:
179   /// isRegisterClass() - Check if this is a register class.
180   bool isRegisterClass() const {
181     return Kind >= RegisterClass0 && Kind < UserClass0;
182   }
183
184   /// isUserClass() - Check if this is a user defined class.
185   bool isUserClass() const {
186     return Kind >= UserClass0;
187   }
188
189   /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
190   /// are related if they are in the same class hierarchy.
191   bool isRelatedTo(const ClassInfo &RHS) const {
192     // Tokens are only related to tokens.
193     if (Kind == Token || RHS.Kind == Token)
194       return Kind == Token && RHS.Kind == Token;
195
196     // Registers classes are only related to registers classes, and only if
197     // their intersection is non-empty.
198     if (isRegisterClass() || RHS.isRegisterClass()) {
199       if (!isRegisterClass() || !RHS.isRegisterClass())
200         return false;
201
202       std::set<Record*> Tmp;
203       std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
204       std::set_intersection(Registers.begin(), Registers.end(),
205                             RHS.Registers.begin(), RHS.Registers.end(),
206                             II);
207
208       return !Tmp.empty();
209     }
210
211     // Otherwise we have two users operands; they are related if they are in the
212     // same class hierarchy.
213     //
214     // FIXME: This is an oversimplification, they should only be related if they
215     // intersect, however we don't have that information.
216     assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
217     const ClassInfo *Root = this;
218     while (!Root->SuperClasses.empty())
219       Root = Root->SuperClasses.front();
220
221     const ClassInfo *RHSRoot = &RHS;
222     while (!RHSRoot->SuperClasses.empty())
223       RHSRoot = RHSRoot->SuperClasses.front();
224
225     return Root == RHSRoot;
226   }
227
228   /// isSubsetOf - Test whether this class is a subset of \arg RHS;
229   bool isSubsetOf(const ClassInfo &RHS) const {
230     // This is a subset of RHS if it is the same class...
231     if (this == &RHS)
232       return true;
233
234     // ... or if any of its super classes are a subset of RHS.
235     for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
236            ie = SuperClasses.end(); it != ie; ++it)
237       if ((*it)->isSubsetOf(RHS))
238         return true;
239
240     return false;
241   }
242
243   /// operator< - Compare two classes.
244   bool operator<(const ClassInfo &RHS) const {
245     if (this == &RHS)
246       return false;
247
248     // Unrelated classes can be ordered by kind.
249     if (!isRelatedTo(RHS))
250       return Kind < RHS.Kind;
251
252     switch (Kind) {
253     case Invalid:
254       assert(0 && "Invalid kind!");
255
256     default:
257       // This class precedes the RHS if it is a proper subset of the RHS.
258       if (isSubsetOf(RHS))
259         return true;
260       if (RHS.isSubsetOf(*this))
261         return false;
262
263       // Otherwise, order by name to ensure we have a total ordering.
264       return ValueName < RHS.ValueName;
265     }
266   }
267 };
268
269 /// MatchableInfo - Helper class for storing the necessary information for an
270 /// instruction or alias which is capable of being matched.
271 struct MatchableInfo {
272   struct AsmOperand {
273     /// Token - This is the token that the operand came from.
274     StringRef Token;
275
276     /// The unique class instance this operand should match.
277     ClassInfo *Class;
278
279     /// The operand name this is, if anything.
280     StringRef SrcOpName;
281
282     /// The suboperand index within SrcOpName, or -1 for the entire operand.
283     int SubOpIdx;
284
285     /// Register record if this token is singleton register.
286     Record *SingletonReg;
287
288     explicit AsmOperand(StringRef T) : Token(T), Class(0), SubOpIdx(-1), 
289                                        SingletonReg(0) {}
290   };
291
292   /// ResOperand - This represents a single operand in the result instruction
293   /// generated by the match.  In cases (like addressing modes) where a single
294   /// assembler operand expands to multiple MCOperands, this represents the
295   /// single assembler operand, not the MCOperand.
296   struct ResOperand {
297     enum {
298       /// RenderAsmOperand - This represents an operand result that is
299       /// generated by calling the render method on the assembly operand.  The
300       /// corresponding AsmOperand is specified by AsmOperandNum.
301       RenderAsmOperand,
302
303       /// TiedOperand - This represents a result operand that is a duplicate of
304       /// a previous result operand.
305       TiedOperand,
306
307       /// ImmOperand - This represents an immediate value that is dumped into
308       /// the operand.
309       ImmOperand,
310
311       /// RegOperand - This represents a fixed register that is dumped in.
312       RegOperand
313     } Kind;
314
315     union {
316       /// This is the operand # in the AsmOperands list that this should be
317       /// copied from.
318       unsigned AsmOperandNum;
319
320       /// TiedOperandNum - This is the (earlier) result operand that should be
321       /// copied from.
322       unsigned TiedOperandNum;
323
324       /// ImmVal - This is the immediate value added to the instruction.
325       int64_t ImmVal;
326
327       /// Register - This is the register record.
328       Record *Register;
329     };
330
331     /// MINumOperands - The number of MCInst operands populated by this
332     /// operand.
333     unsigned MINumOperands;
334
335     static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
336       ResOperand X;
337       X.Kind = RenderAsmOperand;
338       X.AsmOperandNum = AsmOpNum;
339       X.MINumOperands = NumOperands;
340       return X;
341     }
342
343     static ResOperand getTiedOp(unsigned TiedOperandNum) {
344       ResOperand X;
345       X.Kind = TiedOperand;
346       X.TiedOperandNum = TiedOperandNum;
347       X.MINumOperands = 1;
348       return X;
349     }
350
351     static ResOperand getImmOp(int64_t Val) {
352       ResOperand X;
353       X.Kind = ImmOperand;
354       X.ImmVal = Val;
355       X.MINumOperands = 1;
356       return X;
357     }
358
359     static ResOperand getRegOp(Record *Reg) {
360       ResOperand X;
361       X.Kind = RegOperand;
362       X.Register = Reg;
363       X.MINumOperands = 1;
364       return X;
365     }
366   };
367
368   /// AsmVariantID - Target's assembly syntax variant no.
369   int AsmVariantID;
370
371   /// TheDef - This is the definition of the instruction or InstAlias that this
372   /// matchable came from.
373   Record *const TheDef;
374
375   /// DefRec - This is the definition that it came from.
376   PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
377
378   const CodeGenInstruction *getResultInst() const {
379     if (DefRec.is<const CodeGenInstruction*>())
380       return DefRec.get<const CodeGenInstruction*>();
381     return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
382   }
383
384   /// ResOperands - This is the operand list that should be built for the result
385   /// MCInst.
386   std::vector<ResOperand> ResOperands;
387
388   /// AsmString - The assembly string for this instruction (with variants
389   /// removed), e.g. "movsx $src, $dst".
390   std::string AsmString;
391
392   /// Mnemonic - This is the first token of the matched instruction, its
393   /// mnemonic.
394   StringRef Mnemonic;
395
396   /// AsmOperands - The textual operands that this instruction matches,
397   /// annotated with a class and where in the OperandList they were defined.
398   /// This directly corresponds to the tokenized AsmString after the mnemonic is
399   /// removed.
400   SmallVector<AsmOperand, 4> AsmOperands;
401
402   /// Predicates - The required subtarget features to match this instruction.
403   SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
404
405   /// ConversionFnKind - The enum value which is passed to the generated
406   /// ConvertToMCInst to convert parsed operands into an MCInst for this
407   /// function.
408   std::string ConversionFnKind;
409
410   MatchableInfo(const CodeGenInstruction &CGI)
411     : AsmVariantID(0), TheDef(CGI.TheDef), DefRec(&CGI), 
412       AsmString(CGI.AsmString) {
413   }
414
415   MatchableInfo(const CodeGenInstAlias *Alias)
416     : AsmVariantID(0), TheDef(Alias->TheDef), DefRec(Alias), 
417       AsmString(Alias->AsmString) {
418   }
419
420   void Initialize(const AsmMatcherInfo &Info,
421                   SmallPtrSet<Record*, 16> &SingletonRegisters, 
422                   int AsmVariantNo, std::string &RegisterPrefix);
423
424   /// Validate - Return true if this matchable is a valid thing to match against
425   /// and perform a bunch of validity checking.
426   bool Validate(StringRef CommentDelimiter, bool Hack) const;
427
428   /// extractSingletonRegisterForAsmOperand - Extract singleton register, 
429   /// if present, from specified token.
430   void
431   extractSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info,
432                                         std::string &RegisterPrefix);
433
434   /// FindAsmOperand - Find the AsmOperand with the specified name and
435   /// suboperand index.
436   int FindAsmOperand(StringRef N, int SubOpIdx) const {
437     for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
438       if (N == AsmOperands[i].SrcOpName &&
439           SubOpIdx == AsmOperands[i].SubOpIdx)
440         return i;
441     return -1;
442   }
443
444   /// FindAsmOperandNamed - Find the first AsmOperand with the specified name.
445   /// This does not check the suboperand index.
446   int FindAsmOperandNamed(StringRef N) const {
447     for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
448       if (N == AsmOperands[i].SrcOpName)
449         return i;
450     return -1;
451   }
452
453   void BuildInstructionResultOperands();
454   void BuildAliasResultOperands();
455
456   /// operator< - Compare two matchables.
457   bool operator<(const MatchableInfo &RHS) const {
458     // The primary comparator is the instruction mnemonic.
459     if (Mnemonic != RHS.Mnemonic)
460       return Mnemonic < RHS.Mnemonic;
461
462     if (AsmOperands.size() != RHS.AsmOperands.size())
463       return AsmOperands.size() < RHS.AsmOperands.size();
464
465     // Compare lexicographically by operand. The matcher validates that other
466     // orderings wouldn't be ambiguous using \see CouldMatchAmbiguouslyWith().
467     for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
468       if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
469         return true;
470       if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
471         return false;
472     }
473
474     return false;
475   }
476
477   /// CouldMatchAmbiguouslyWith - Check whether this matchable could
478   /// ambiguously match the same set of operands as \arg RHS (without being a
479   /// strictly superior match).
480   bool CouldMatchAmbiguouslyWith(const MatchableInfo &RHS) {
481     // The primary comparator is the instruction mnemonic.
482     if (Mnemonic != RHS.Mnemonic)
483       return false;
484
485     // The number of operands is unambiguous.
486     if (AsmOperands.size() != RHS.AsmOperands.size())
487       return false;
488
489     // Otherwise, make sure the ordering of the two instructions is unambiguous
490     // by checking that either (a) a token or operand kind discriminates them,
491     // or (b) the ordering among equivalent kinds is consistent.
492
493     // Tokens and operand kinds are unambiguous (assuming a correct target
494     // specific parser).
495     for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
496       if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
497           AsmOperands[i].Class->Kind == ClassInfo::Token)
498         if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
499             *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
500           return false;
501
502     // Otherwise, this operand could commute if all operands are equivalent, or
503     // there is a pair of operands that compare less than and a pair that
504     // compare greater than.
505     bool HasLT = false, HasGT = false;
506     for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
507       if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
508         HasLT = true;
509       if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
510         HasGT = true;
511     }
512
513     return !(HasLT ^ HasGT);
514   }
515
516   void dump();
517
518 private:
519   void TokenizeAsmString(const AsmMatcherInfo &Info);
520 };
521
522 /// SubtargetFeatureInfo - Helper class for storing information on a subtarget
523 /// feature which participates in instruction matching.
524 struct SubtargetFeatureInfo {
525   /// \brief The predicate record for this feature.
526   Record *TheDef;
527
528   /// \brief An unique index assigned to represent this feature.
529   unsigned Index;
530
531   SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
532
533   /// \brief The name of the enumerated constant identifying this feature.
534   std::string getEnumName() const {
535     return "Feature_" + TheDef->getName();
536   }
537 };
538
539 struct OperandMatchEntry {
540   unsigned OperandMask;
541   MatchableInfo* MI;
542   ClassInfo *CI;
543
544   static OperandMatchEntry Create(MatchableInfo* mi, ClassInfo *ci,
545                                   unsigned opMask) {
546     OperandMatchEntry X;
547     X.OperandMask = opMask;
548     X.CI = ci;
549     X.MI = mi;
550     return X;
551   }
552 };
553
554
555 class AsmMatcherInfo {
556 public:
557   /// Tracked Records
558   RecordKeeper &Records;
559
560   /// The tablegen AsmParser record.
561   Record *AsmParser;
562
563   /// Target - The target information.
564   CodeGenTarget &Target;
565
566   /// The classes which are needed for matching.
567   std::vector<ClassInfo*> Classes;
568
569   /// The information on the matchables to match.
570   std::vector<MatchableInfo*> Matchables;
571
572   /// Info for custom matching operands by user defined methods.
573   std::vector<OperandMatchEntry> OperandMatchInfo;
574
575   /// Map of Register records to their class information.
576   std::map<Record*, ClassInfo*> RegisterClasses;
577
578   /// Map of Predicate records to their subtarget information.
579   std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
580
581 private:
582   /// Map of token to class information which has already been constructed.
583   std::map<std::string, ClassInfo*> TokenClasses;
584
585   /// Map of RegisterClass records to their class information.
586   std::map<Record*, ClassInfo*> RegisterClassClasses;
587
588   /// Map of AsmOperandClass records to their class information.
589   std::map<Record*, ClassInfo*> AsmOperandClasses;
590
591 private:
592   /// getTokenClass - Lookup or create the class for the given token.
593   ClassInfo *getTokenClass(StringRef Token);
594
595   /// getOperandClass - Lookup or create the class for the given operand.
596   ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
597                              int SubOpIdx);
598   ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
599
600   /// BuildRegisterClasses - Build the ClassInfo* instances for register
601   /// classes.
602   void BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
603
604   /// BuildOperandClasses - Build the ClassInfo* instances for user defined
605   /// operand classes.
606   void BuildOperandClasses();
607
608   void BuildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
609                                         unsigned AsmOpIdx);
610   void BuildAliasOperandReference(MatchableInfo *II, StringRef OpName,
611                                   MatchableInfo::AsmOperand &Op);
612
613 public:
614   AsmMatcherInfo(Record *AsmParser,
615                  CodeGenTarget &Target,
616                  RecordKeeper &Records);
617
618   /// BuildInfo - Construct the various tables used during matching.
619   void BuildInfo();
620
621   /// BuildOperandMatchInfo - Build the necessary information to handle user
622   /// defined operand parsing methods.
623   void BuildOperandMatchInfo();
624
625   /// getSubtargetFeature - Lookup or create the subtarget feature info for the
626   /// given operand.
627   SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
628     assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
629     std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
630       SubtargetFeatures.find(Def);
631     return I == SubtargetFeatures.end() ? 0 : I->second;
632   }
633
634   RecordKeeper &getRecords() const {
635     return Records;
636   }
637 };
638
639 }
640
641 void MatchableInfo::dump() {
642   errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
643
644   for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
645     AsmOperand &Op = AsmOperands[i];
646     errs() << "  op[" << i << "] = " << Op.Class->ClassName << " - ";
647     errs() << '\"' << Op.Token << "\"\n";
648   }
649 }
650
651 void MatchableInfo::Initialize(const AsmMatcherInfo &Info,
652                                SmallPtrSet<Record*, 16> &SingletonRegisters,
653                                int AsmVariantNo, std::string &RegisterPrefix) {
654   AsmVariantID = AsmVariantNo;
655   AsmString = 
656     CodeGenInstruction::FlattenAsmStringVariants(AsmString, AsmVariantNo);
657
658   TokenizeAsmString(Info);
659
660   // Compute the require features.
661   std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates");
662   for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
663     if (SubtargetFeatureInfo *Feature =
664         Info.getSubtargetFeature(Predicates[i]))
665       RequiredFeatures.push_back(Feature);
666
667   // Collect singleton registers, if used.
668   for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
669     extractSingletonRegisterForAsmOperand(i, Info, RegisterPrefix);
670     if (Record *Reg = AsmOperands[i].SingletonReg)
671       SingletonRegisters.insert(Reg);
672   }
673 }
674
675 /// TokenizeAsmString - Tokenize a simplified assembly string.
676 void MatchableInfo::TokenizeAsmString(const AsmMatcherInfo &Info) {
677   StringRef String = AsmString;
678   unsigned Prev = 0;
679   bool InTok = true;
680   for (unsigned i = 0, e = String.size(); i != e; ++i) {
681     switch (String[i]) {
682     case '[':
683     case ']':
684     case '*':
685     case '!':
686     case ' ':
687     case '\t':
688     case ',':
689       if (InTok) {
690         AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
691         InTok = false;
692       }
693       if (!isspace(String[i]) && String[i] != ',')
694         AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
695       Prev = i + 1;
696       break;
697
698     case '\\':
699       if (InTok) {
700         AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
701         InTok = false;
702       }
703       ++i;
704       assert(i != String.size() && "Invalid quoted character");
705       AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
706       Prev = i + 1;
707       break;
708
709     case '$': {
710       if (InTok) {
711         AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
712         InTok = false;
713       }
714
715       // If this isn't "${", treat like a normal token.
716       if (i + 1 == String.size() || String[i + 1] != '{') {
717         Prev = i;
718         break;
719       }
720
721       StringRef::iterator End = std::find(String.begin() + i, String.end(),'}');
722       assert(End != String.end() && "Missing brace in operand reference!");
723       size_t EndPos = End - String.begin();
724       AsmOperands.push_back(AsmOperand(String.slice(i, EndPos+1)));
725       Prev = EndPos + 1;
726       i = EndPos;
727       break;
728     }
729
730     case '.':
731       if (InTok)
732         AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
733       Prev = i;
734       InTok = true;
735       break;
736
737     default:
738       InTok = true;
739     }
740   }
741   if (InTok && Prev != String.size())
742     AsmOperands.push_back(AsmOperand(String.substr(Prev)));
743
744   // The first token of the instruction is the mnemonic, which must be a
745   // simple string, not a $foo variable or a singleton register.
746   if (AsmOperands.empty())
747     throw TGError(TheDef->getLoc(),
748                   "Instruction '" + TheDef->getName() + "' has no tokens");
749   Mnemonic = AsmOperands[0].Token;
750   // FIXME : Check and raise an error if it is a register.
751   if (Mnemonic[0] == '$')
752     throw TGError(TheDef->getLoc(),
753                   "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
754
755   // Remove the first operand, it is tracked in the mnemonic field.
756   AsmOperands.erase(AsmOperands.begin());
757 }
758
759 bool MatchableInfo::Validate(StringRef CommentDelimiter, bool Hack) const {
760   // Reject matchables with no .s string.
761   if (AsmString.empty())
762     throw TGError(TheDef->getLoc(), "instruction with empty asm string");
763
764   // Reject any matchables with a newline in them, they should be marked
765   // isCodeGenOnly if they are pseudo instructions.
766   if (AsmString.find('\n') != std::string::npos)
767     throw TGError(TheDef->getLoc(),
768                   "multiline instruction is not valid for the asmparser, "
769                   "mark it isCodeGenOnly");
770
771   // Remove comments from the asm string.  We know that the asmstring only
772   // has one line.
773   if (!CommentDelimiter.empty() &&
774       StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
775     throw TGError(TheDef->getLoc(),
776                   "asmstring for instruction has comment character in it, "
777                   "mark it isCodeGenOnly");
778
779   // Reject matchables with operand modifiers, these aren't something we can
780   // handle, the target should be refactored to use operands instead of
781   // modifiers.
782   //
783   // Also, check for instructions which reference the operand multiple times;
784   // this implies a constraint we would not honor.
785   std::set<std::string> OperandNames;
786   for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
787     StringRef Tok = AsmOperands[i].Token;
788     if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
789       throw TGError(TheDef->getLoc(),
790                     "matchable with operand modifier '" + Tok.str() +
791                     "' not supported by asm matcher.  Mark isCodeGenOnly!");
792
793     // Verify that any operand is only mentioned once.
794     // We reject aliases and ignore instructions for now.
795     if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
796       if (!Hack)
797         throw TGError(TheDef->getLoc(),
798                       "ERROR: matchable with tied operand '" + Tok.str() +
799                       "' can never be matched!");
800       // FIXME: Should reject these.  The ARM backend hits this with $lane in a
801       // bunch of instructions.  It is unclear what the right answer is.
802       DEBUG({
803         errs() << "warning: '" << TheDef->getName() << "': "
804                << "ignoring instruction with tied operand '"
805                << Tok.str() << "'\n";
806       });
807       return false;
808     }
809   }
810
811   return true;
812 }
813
814 /// extractSingletonRegisterForAsmOperand - Extract singleton register, 
815 /// if present, from specified token.
816 void MatchableInfo::
817 extractSingletonRegisterForAsmOperand(unsigned OperandNo, 
818                                       const AsmMatcherInfo &Info,
819                                       std::string &RegisterPrefix) {
820   StringRef Tok = AsmOperands[OperandNo].Token;
821   if (RegisterPrefix.empty()) {
822     std::string LoweredTok = Tok.lower();
823     if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
824       AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
825     return;
826   } 
827
828   if (!Tok.startswith(RegisterPrefix))
829     return;
830
831   StringRef RegName = Tok.substr(RegisterPrefix.size());
832   if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
833     AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
834
835   // If there is no register prefix (i.e. "%" in "%eax"), then this may
836   // be some random non-register token, just ignore it.
837   return;
838 }
839
840 static std::string getEnumNameForToken(StringRef Str) {
841   std::string Res;
842
843   for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
844     switch (*it) {
845     case '*': Res += "_STAR_"; break;
846     case '%': Res += "_PCT_"; break;
847     case ':': Res += "_COLON_"; break;
848     case '!': Res += "_EXCLAIM_"; break;
849     case '.': Res += "_DOT_"; break;
850     default:
851       if (isalnum(*it))
852         Res += *it;
853       else
854         Res += "_" + utostr((unsigned) *it) + "_";
855     }
856   }
857
858   return Res;
859 }
860
861 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
862   ClassInfo *&Entry = TokenClasses[Token];
863
864   if (!Entry) {
865     Entry = new ClassInfo();
866     Entry->Kind = ClassInfo::Token;
867     Entry->ClassName = "Token";
868     Entry->Name = "MCK_" + getEnumNameForToken(Token);
869     Entry->ValueName = Token;
870     Entry->PredicateMethod = "<invalid>";
871     Entry->RenderMethod = "<invalid>";
872     Entry->ParserMethod = "";
873     Classes.push_back(Entry);
874   }
875
876   return Entry;
877 }
878
879 ClassInfo *
880 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
881                                 int SubOpIdx) {
882   Record *Rec = OI.Rec;
883   if (SubOpIdx != -1)
884     Rec = dynamic_cast<DefInit*>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
885   return getOperandClass(Rec, SubOpIdx);
886 }
887
888 ClassInfo *
889 AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
890   if (Rec->isSubClassOf("RegisterOperand")) {
891     // RegisterOperand may have an associated ParserMatchClass. If it does,
892     // use it, else just fall back to the underlying register class.
893     const RecordVal *R = Rec->getValue("ParserMatchClass");
894     if (R == 0 || R->getValue() == 0)
895       throw "Record `" + Rec->getName() +
896         "' does not have a ParserMatchClass!\n";
897
898     if (DefInit *DI= dynamic_cast<DefInit*>(R->getValue())) {
899       Record *MatchClass = DI->getDef();
900       if (ClassInfo *CI = AsmOperandClasses[MatchClass])
901         return CI;
902     }
903
904     // No custom match class. Just use the register class.
905     Record *ClassRec = Rec->getValueAsDef("RegClass");
906     if (!ClassRec)
907       throw TGError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
908                     "' has no associated register class!\n");
909     if (ClassInfo *CI = RegisterClassClasses[ClassRec])
910       return CI;
911     throw TGError(Rec->getLoc(), "register class has no class info!");
912   }
913
914
915   if (Rec->isSubClassOf("RegisterClass")) {
916     if (ClassInfo *CI = RegisterClassClasses[Rec])
917       return CI;
918     throw TGError(Rec->getLoc(), "register class has no class info!");
919   }
920
921   assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
922   Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
923   if (ClassInfo *CI = AsmOperandClasses[MatchClass])
924     return CI;
925
926   throw TGError(Rec->getLoc(), "operand has no match class!");
927 }
928
929 void AsmMatcherInfo::
930 BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
931   const std::vector<CodeGenRegister*> &Registers =
932     Target.getRegBank().getRegisters();
933   ArrayRef<CodeGenRegisterClass*> RegClassList =
934     Target.getRegBank().getRegClasses();
935
936   // The register sets used for matching.
937   std::set< std::set<Record*> > RegisterSets;
938
939   // Gather the defined sets.
940   for (ArrayRef<CodeGenRegisterClass*>::const_iterator it =
941        RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it)
942     RegisterSets.insert(std::set<Record*>(
943         (*it)->getOrder().begin(), (*it)->getOrder().end()));
944
945   // Add any required singleton sets.
946   for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
947        ie = SingletonRegisters.end(); it != ie; ++it) {
948     Record *Rec = *it;
949     RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
950   }
951
952   // Introduce derived sets where necessary (when a register does not determine
953   // a unique register set class), and build the mapping of registers to the set
954   // they should classify to.
955   std::map<Record*, std::set<Record*> > RegisterMap;
956   for (std::vector<CodeGenRegister*>::const_iterator it = Registers.begin(),
957          ie = Registers.end(); it != ie; ++it) {
958     const CodeGenRegister &CGR = **it;
959     // Compute the intersection of all sets containing this register.
960     std::set<Record*> ContainingSet;
961
962     for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
963            ie = RegisterSets.end(); it != ie; ++it) {
964       if (!it->count(CGR.TheDef))
965         continue;
966
967       if (ContainingSet.empty()) {
968         ContainingSet = *it;
969         continue;
970       }
971
972       std::set<Record*> Tmp;
973       std::swap(Tmp, ContainingSet);
974       std::insert_iterator< std::set<Record*> > II(ContainingSet,
975                                                    ContainingSet.begin());
976       std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(), II);
977     }
978
979     if (!ContainingSet.empty()) {
980       RegisterSets.insert(ContainingSet);
981       RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
982     }
983   }
984
985   // Construct the register classes.
986   std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
987   unsigned Index = 0;
988   for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
989          ie = RegisterSets.end(); it != ie; ++it, ++Index) {
990     ClassInfo *CI = new ClassInfo();
991     CI->Kind = ClassInfo::RegisterClass0 + Index;
992     CI->ClassName = "Reg" + utostr(Index);
993     CI->Name = "MCK_Reg" + utostr(Index);
994     CI->ValueName = "";
995     CI->PredicateMethod = ""; // unused
996     CI->RenderMethod = "addRegOperands";
997     CI->Registers = *it;
998     Classes.push_back(CI);
999     RegisterSetClasses.insert(std::make_pair(*it, CI));
1000   }
1001
1002   // Find the superclasses; we could compute only the subgroup lattice edges,
1003   // but there isn't really a point.
1004   for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
1005          ie = RegisterSets.end(); it != ie; ++it) {
1006     ClassInfo *CI = RegisterSetClasses[*it];
1007     for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
1008            ie2 = RegisterSets.end(); it2 != ie2; ++it2)
1009       if (*it != *it2 &&
1010           std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
1011         CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
1012   }
1013
1014   // Name the register classes which correspond to a user defined RegisterClass.
1015   for (ArrayRef<CodeGenRegisterClass*>::const_iterator
1016        it = RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) {
1017     const CodeGenRegisterClass &RC = **it;
1018     // Def will be NULL for non-user defined register classes.
1019     Record *Def = RC.getDef();
1020     if (!Def)
1021       continue;
1022     ClassInfo *CI = RegisterSetClasses[std::set<Record*>(RC.getOrder().begin(),
1023                                                          RC.getOrder().end())];
1024     if (CI->ValueName.empty()) {
1025       CI->ClassName = RC.getName();
1026       CI->Name = "MCK_" + RC.getName();
1027       CI->ValueName = RC.getName();
1028     } else
1029       CI->ValueName = CI->ValueName + "," + RC.getName();
1030
1031     RegisterClassClasses.insert(std::make_pair(Def, CI));
1032   }
1033
1034   // Populate the map for individual registers.
1035   for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
1036          ie = RegisterMap.end(); it != ie; ++it)
1037     RegisterClasses[it->first] = RegisterSetClasses[it->second];
1038
1039   // Name the register classes which correspond to singleton registers.
1040   for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1041          ie = SingletonRegisters.end(); it != ie; ++it) {
1042     Record *Rec = *it;
1043     ClassInfo *CI = RegisterClasses[Rec];
1044     assert(CI && "Missing singleton register class info!");
1045
1046     if (CI->ValueName.empty()) {
1047       CI->ClassName = Rec->getName();
1048       CI->Name = "MCK_" + Rec->getName();
1049       CI->ValueName = Rec->getName();
1050     } else
1051       CI->ValueName = CI->ValueName + "," + Rec->getName();
1052   }
1053 }
1054
1055 void AsmMatcherInfo::BuildOperandClasses() {
1056   std::vector<Record*> AsmOperands =
1057     Records.getAllDerivedDefinitions("AsmOperandClass");
1058
1059   // Pre-populate AsmOperandClasses map.
1060   for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1061          ie = AsmOperands.end(); it != ie; ++it)
1062     AsmOperandClasses[*it] = new ClassInfo();
1063
1064   unsigned Index = 0;
1065   for (std::vector<Record*>::iterator it = AsmOperands.begin(),
1066          ie = AsmOperands.end(); it != ie; ++it, ++Index) {
1067     ClassInfo *CI = AsmOperandClasses[*it];
1068     CI->Kind = ClassInfo::UserClass0 + Index;
1069
1070     ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
1071     for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
1072       DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
1073       if (!DI) {
1074         PrintError((*it)->getLoc(), "Invalid super class reference!");
1075         continue;
1076       }
1077
1078       ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1079       if (!SC)
1080         PrintError((*it)->getLoc(), "Invalid super class reference!");
1081       else
1082         CI->SuperClasses.push_back(SC);
1083     }
1084     CI->ClassName = (*it)->getValueAsString("Name");
1085     CI->Name = "MCK_" + CI->ClassName;
1086     CI->ValueName = (*it)->getName();
1087
1088     // Get or construct the predicate method name.
1089     Init *PMName = (*it)->getValueInit("PredicateMethod");
1090     if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
1091       CI->PredicateMethod = SI->getValue();
1092     } else {
1093       assert(dynamic_cast<UnsetInit*>(PMName) &&
1094              "Unexpected PredicateMethod field!");
1095       CI->PredicateMethod = "is" + CI->ClassName;
1096     }
1097
1098     // Get or construct the render method name.
1099     Init *RMName = (*it)->getValueInit("RenderMethod");
1100     if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
1101       CI->RenderMethod = SI->getValue();
1102     } else {
1103       assert(dynamic_cast<UnsetInit*>(RMName) &&
1104              "Unexpected RenderMethod field!");
1105       CI->RenderMethod = "add" + CI->ClassName + "Operands";
1106     }
1107
1108     // Get the parse method name or leave it as empty.
1109     Init *PRMName = (*it)->getValueInit("ParserMethod");
1110     if (StringInit *SI = dynamic_cast<StringInit*>(PRMName))
1111       CI->ParserMethod = SI->getValue();
1112
1113     AsmOperandClasses[*it] = CI;
1114     Classes.push_back(CI);
1115   }
1116 }
1117
1118 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1119                                CodeGenTarget &target,
1120                                RecordKeeper &records)
1121   : Records(records), AsmParser(asmParser), Target(target) {
1122 }
1123
1124 /// BuildOperandMatchInfo - Build the necessary information to handle user
1125 /// defined operand parsing methods.
1126 void AsmMatcherInfo::BuildOperandMatchInfo() {
1127
1128   /// Map containing a mask with all operands indicies that can be found for
1129   /// that class inside a instruction.
1130   std::map<ClassInfo*, unsigned> OpClassMask;
1131
1132   for (std::vector<MatchableInfo*>::const_iterator it =
1133        Matchables.begin(), ie = Matchables.end();
1134        it != ie; ++it) {
1135     MatchableInfo &II = **it;
1136     OpClassMask.clear();
1137
1138     // Keep track of all operands of this instructions which belong to the
1139     // same class.
1140     for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
1141       MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
1142       if (Op.Class->ParserMethod.empty())
1143         continue;
1144       unsigned &OperandMask = OpClassMask[Op.Class];
1145       OperandMask |= (1 << i);
1146     }
1147
1148     // Generate operand match info for each mnemonic/operand class pair.
1149     for (std::map<ClassInfo*, unsigned>::iterator iit = OpClassMask.begin(),
1150          iie = OpClassMask.end(); iit != iie; ++iit) {
1151       unsigned OpMask = iit->second;
1152       ClassInfo *CI = iit->first;
1153       OperandMatchInfo.push_back(OperandMatchEntry::Create(&II, CI, OpMask));
1154     }
1155   }
1156 }
1157
1158 void AsmMatcherInfo::BuildInfo() {
1159   // Build information about all of the AssemblerPredicates.
1160   std::vector<Record*> AllPredicates =
1161     Records.getAllDerivedDefinitions("Predicate");
1162   for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
1163     Record *Pred = AllPredicates[i];
1164     // Ignore predicates that are not intended for the assembler.
1165     if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
1166       continue;
1167
1168     if (Pred->getName().empty())
1169       throw TGError(Pred->getLoc(), "Predicate has no name!");
1170
1171     unsigned FeatureNo = SubtargetFeatures.size();
1172     SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
1173     assert(FeatureNo < 32 && "Too many subtarget features!");
1174   }
1175
1176   // Parse the instructions; we need to do this first so that we can gather the
1177   // singleton register classes.
1178   SmallPtrSet<Record*, 16> SingletonRegisters;
1179   unsigned VariantCount = Target.getAsmParserVariantCount();
1180   for (unsigned VC = 0; VC != VariantCount; ++VC) {
1181     Record *AsmVariant = Target.getAsmParserVariant(VC);
1182     std::string CommentDelimiter = AsmVariant->getValueAsString("CommentDelimiter");
1183     std::string RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
1184     int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
1185     
1186     for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
1187            E = Target.inst_end(); I != E; ++I) {
1188       const CodeGenInstruction &CGI = **I;
1189       
1190       // If the tblgen -match-prefix option is specified (for tblgen hackers),
1191       // filter the set of instructions we consider.
1192       if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
1193         continue;
1194       
1195       // Ignore "codegen only" instructions.
1196       if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
1197         continue;
1198       
1199       // Validate the operand list to ensure we can handle this instruction.
1200       for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1201         const CGIOperandList::OperandInfo &OI = CGI.Operands[i];
1202         
1203         // Validate tied operands.
1204         if (OI.getTiedRegister() != -1) {
1205           // If we have a tied operand that consists of multiple MCOperands,
1206           // reject it.  We reject aliases and ignore instructions for now.
1207           if (OI.MINumOperands != 1) {
1208             // FIXME: Should reject these.  The ARM backend hits this with $lane
1209             // in a bunch of instructions. It is unclear what the right answer is.
1210             DEBUG({
1211                 errs() << "warning: '" << CGI.TheDef->getName() << "': "
1212                        << "ignoring instruction with multi-operand tied operand '"
1213                        << OI.Name << "'\n";
1214               });
1215             continue;
1216           }
1217         }
1218       }
1219       
1220       OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
1221       
1222       II->Initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
1223       
1224       // Ignore instructions which shouldn't be matched and diagnose invalid
1225       // instruction definitions with an error.
1226       if (!II->Validate(CommentDelimiter, true))
1227         continue;
1228       
1229       // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
1230       //
1231       // FIXME: This is a total hack.
1232       if (StringRef(II->TheDef->getName()).startswith("Int_") ||
1233           StringRef(II->TheDef->getName()).endswith("_Int"))
1234         continue;
1235       
1236       Matchables.push_back(II.take());
1237     }
1238     
1239     // Parse all of the InstAlias definitions and stick them in the list of
1240     // matchables.
1241     std::vector<Record*> AllInstAliases =
1242       Records.getAllDerivedDefinitions("InstAlias");
1243     for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
1244       CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i], Target);
1245       
1246       // If the tblgen -match-prefix option is specified (for tblgen hackers),
1247       // filter the set of instruction aliases we consider, based on the target
1248       // instruction.
1249       if (!StringRef(Alias->ResultInst->TheDef->getName()).startswith(
1250                                                                       MatchPrefix))
1251         continue;
1252       
1253       OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
1254       
1255       II->Initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
1256       
1257       // Validate the alias definitions.
1258       II->Validate(CommentDelimiter, false);
1259       
1260       Matchables.push_back(II.take());
1261     }
1262   }
1263
1264   // Build info for the register classes.
1265   BuildRegisterClasses(SingletonRegisters);
1266
1267   // Build info for the user defined assembly operand classes.
1268   BuildOperandClasses();
1269
1270   // Build the information about matchables, now that we have fully formed
1271   // classes.
1272   for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(),
1273          ie = Matchables.end(); it != ie; ++it) {
1274     MatchableInfo *II = *it;
1275
1276     // Parse the tokens after the mnemonic.
1277     // Note: BuildInstructionOperandReference may insert new AsmOperands, so
1278     // don't precompute the loop bound.
1279     for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1280       MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
1281       StringRef Token = Op.Token;
1282
1283       // Check for singleton registers.
1284       if (Record *RegRecord = II->AsmOperands[i].SingletonReg) {
1285         Op.Class = RegisterClasses[RegRecord];
1286         assert(Op.Class && Op.Class->Registers.size() == 1 &&
1287                "Unexpected class for singleton register");
1288         continue;
1289       }
1290
1291       // Check for simple tokens.
1292       if (Token[0] != '$') {
1293         Op.Class = getTokenClass(Token);
1294         continue;
1295       }
1296
1297       if (Token.size() > 1 && isdigit(Token[1])) {
1298         Op.Class = getTokenClass(Token);
1299         continue;
1300       }
1301
1302       // Otherwise this is an operand reference.
1303       StringRef OperandName;
1304       if (Token[1] == '{')
1305         OperandName = Token.substr(2, Token.size() - 3);
1306       else
1307         OperandName = Token.substr(1);
1308
1309       if (II->DefRec.is<const CodeGenInstruction*>())
1310         BuildInstructionOperandReference(II, OperandName, i);
1311       else
1312         BuildAliasOperandReference(II, OperandName, Op);
1313     }
1314
1315     if (II->DefRec.is<const CodeGenInstruction*>())
1316       II->BuildInstructionResultOperands();
1317     else
1318       II->BuildAliasResultOperands();
1319   }
1320
1321   // Process token alias definitions and set up the associated superclass
1322   // information.
1323   std::vector<Record*> AllTokenAliases =
1324     Records.getAllDerivedDefinitions("TokenAlias");
1325   for (unsigned i = 0, e = AllTokenAliases.size(); i != e; ++i) {
1326     Record *Rec = AllTokenAliases[i];
1327     ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1328     ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
1329     FromClass->SuperClasses.push_back(ToClass);
1330   }
1331
1332   // Reorder classes so that classes precede super classes.
1333   std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
1334 }
1335
1336 /// BuildInstructionOperandReference - The specified operand is a reference to a
1337 /// named operand such as $src.  Resolve the Class and OperandInfo pointers.
1338 void AsmMatcherInfo::
1339 BuildInstructionOperandReference(MatchableInfo *II,
1340                                  StringRef OperandName,
1341                                  unsigned AsmOpIdx) {
1342   const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1343   const CGIOperandList &Operands = CGI.Operands;
1344   MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
1345
1346   // Map this token to an operand.
1347   unsigned Idx;
1348   if (!Operands.hasOperandNamed(OperandName, Idx))
1349     throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1350                   OperandName.str() + "'");
1351
1352   // If the instruction operand has multiple suboperands, but the parser
1353   // match class for the asm operand is still the default "ImmAsmOperand",
1354   // then handle each suboperand separately.
1355   if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1356     Record *Rec = Operands[Idx].Rec;
1357     assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1358     Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1359     if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1360       // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1361       StringRef Token = Op->Token; // save this in case Op gets moved
1362       for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1363         MatchableInfo::AsmOperand NewAsmOp(Token);
1364         NewAsmOp.SubOpIdx = SI;
1365         II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1366       }
1367       // Replace Op with first suboperand.
1368       Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1369       Op->SubOpIdx = 0;
1370     }
1371   }
1372
1373   // Set up the operand class.
1374   Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
1375
1376   // If the named operand is tied, canonicalize it to the untied operand.
1377   // For example, something like:
1378   //   (outs GPR:$dst), (ins GPR:$src)
1379   // with an asmstring of
1380   //   "inc $src"
1381   // we want to canonicalize to:
1382   //   "inc $dst"
1383   // so that we know how to provide the $dst operand when filling in the result.
1384   int OITied = Operands[Idx].getTiedRegister();
1385   if (OITied != -1) {
1386     // The tied operand index is an MIOperand index, find the operand that
1387     // contains it.
1388     std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1389     OperandName = Operands[Idx.first].Name;
1390     Op->SubOpIdx = Idx.second;
1391   }
1392
1393   Op->SrcOpName = OperandName;
1394 }
1395
1396 /// BuildAliasOperandReference - When parsing an operand reference out of the
1397 /// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1398 /// operand reference is by looking it up in the result pattern definition.
1399 void AsmMatcherInfo::BuildAliasOperandReference(MatchableInfo *II,
1400                                                 StringRef OperandName,
1401                                                 MatchableInfo::AsmOperand &Op) {
1402   const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
1403
1404   // Set up the operand class.
1405   for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
1406     if (CGA.ResultOperands[i].isRecord() &&
1407         CGA.ResultOperands[i].getName() == OperandName) {
1408       // It's safe to go with the first one we find, because CodeGenInstAlias
1409       // validates that all operands with the same name have the same record.
1410       Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
1411       // Use the match class from the Alias definition, not the
1412       // destination instruction, as we may have an immediate that's
1413       // being munged by the match class.
1414       Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
1415                                  Op.SubOpIdx);
1416       Op.SrcOpName = OperandName;
1417       return;
1418     }
1419
1420   throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1421                 OperandName.str() + "'");
1422 }
1423
1424 void MatchableInfo::BuildInstructionResultOperands() {
1425   const CodeGenInstruction *ResultInst = getResultInst();
1426
1427   // Loop over all operands of the result instruction, determining how to
1428   // populate them.
1429   for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1430     const CGIOperandList::OperandInfo &OpInfo = ResultInst->Operands[i];
1431
1432     // If this is a tied operand, just copy from the previously handled operand.
1433     int TiedOp = OpInfo.getTiedRegister();
1434     if (TiedOp != -1) {
1435       ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1436       continue;
1437     }
1438
1439     // Find out what operand from the asmparser this MCInst operand comes from.
1440     int SrcOperand = FindAsmOperandNamed(OpInfo.Name);
1441     if (OpInfo.Name.empty() || SrcOperand == -1)
1442       throw TGError(TheDef->getLoc(), "Instruction '" +
1443                     TheDef->getName() + "' has operand '" + OpInfo.Name +
1444                     "' that doesn't appear in asm string!");
1445
1446     // Check if the one AsmOperand populates the entire operand.
1447     unsigned NumOperands = OpInfo.MINumOperands;
1448     if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1449       ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
1450       continue;
1451     }
1452
1453     // Add a separate ResOperand for each suboperand.
1454     for (unsigned AI = 0; AI < NumOperands; ++AI) {
1455       assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1456              AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1457              "unexpected AsmOperands for suboperands");
1458       ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1459     }
1460   }
1461 }
1462
1463 void MatchableInfo::BuildAliasResultOperands() {
1464   const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1465   const CodeGenInstruction *ResultInst = getResultInst();
1466
1467   // Loop over all operands of the result instruction, determining how to
1468   // populate them.
1469   unsigned AliasOpNo = 0;
1470   unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
1471   for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1472     const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
1473
1474     // If this is a tied operand, just copy from the previously handled operand.
1475     int TiedOp = OpInfo->getTiedRegister();
1476     if (TiedOp != -1) {
1477       ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
1478       continue;
1479     }
1480
1481     // Handle all the suboperands for this operand.
1482     const std::string &OpName = OpInfo->Name;
1483     for ( ; AliasOpNo <  LastOpNo &&
1484             CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1485       int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1486
1487       // Find out what operand from the asmparser that this MCInst operand
1488       // comes from.
1489       switch (CGA.ResultOperands[AliasOpNo].Kind) {
1490       case CodeGenInstAlias::ResultOperand::K_Record: {
1491         StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1492         int SrcOperand = FindAsmOperand(Name, SubIdx);
1493         if (SrcOperand == -1)
1494           throw TGError(TheDef->getLoc(), "Instruction '" +
1495                         TheDef->getName() + "' has operand '" + OpName +
1496                         "' that doesn't appear in asm string!");
1497         unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1498         ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1499                                                         NumOperands));
1500         break;
1501       }
1502       case CodeGenInstAlias::ResultOperand::K_Imm: {
1503         int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1504         ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1505         break;
1506       }
1507       case CodeGenInstAlias::ResultOperand::K_Reg: {
1508         Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1509         ResOperands.push_back(ResOperand::getRegOp(Reg));
1510         break;
1511       }
1512       }
1513     }
1514   }
1515 }
1516
1517 static void EmitConvertToMCInst(CodeGenTarget &Target, StringRef ClassName,
1518                                 std::vector<MatchableInfo*> &Infos,
1519                                 raw_ostream &OS) {
1520   // Write the convert function to a separate stream, so we can drop it after
1521   // the enum.
1522   std::string ConvertFnBody;
1523   raw_string_ostream CvtOS(ConvertFnBody);
1524
1525   // Function we have already generated.
1526   std::set<std::string> GeneratedFns;
1527
1528   // Start the unified conversion function.
1529   CvtOS << "bool " << Target.getName() << ClassName << "::\n";
1530   CvtOS << "ConvertToMCInst(unsigned Kind, MCInst &Inst, "
1531         << "unsigned Opcode,\n"
1532         << "                      const SmallVectorImpl<MCParsedAsmOperand*"
1533         << "> &Operands) {\n";
1534   CvtOS << "  Inst.setOpcode(Opcode);\n";
1535   CvtOS << "  switch (Kind) {\n";
1536   CvtOS << "  default:\n";
1537
1538   // Start the enum, which we will generate inline.
1539
1540   OS << "// Unified function for converting operands to MCInst instances.\n\n";
1541   OS << "enum ConversionKind {\n";
1542
1543   // TargetOperandClass - This is the target's operand class, like X86Operand.
1544   std::string TargetOperandClass = Target.getName() + "Operand";
1545
1546   for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(),
1547          ie = Infos.end(); it != ie; ++it) {
1548     MatchableInfo &II = **it;
1549
1550     // Check if we have a custom match function.
1551     std::string AsmMatchConverter =
1552       II.getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
1553     if (!AsmMatchConverter.empty()) {
1554       std::string Signature = "ConvertCustom_" + AsmMatchConverter;
1555       II.ConversionFnKind = Signature;
1556
1557       // Check if we have already generated this signature.
1558       if (!GeneratedFns.insert(Signature).second)
1559         continue;
1560
1561       // If not, emit it now.  Add to the enum list.
1562       OS << "  " << Signature << ",\n";
1563
1564       CvtOS << "  case " << Signature << ":\n";
1565       CvtOS << "    return " << AsmMatchConverter
1566             << "(Inst, Opcode, Operands);\n";
1567       continue;
1568     }
1569
1570     // Build the conversion function signature.
1571     std::string Signature = "Convert";
1572     std::string CaseBody;
1573     raw_string_ostream CaseOS(CaseBody);
1574
1575     // Compute the convert enum and the case body.
1576     for (unsigned i = 0, e = II.ResOperands.size(); i != e; ++i) {
1577       const MatchableInfo::ResOperand &OpInfo = II.ResOperands[i];
1578
1579       // Generate code to populate each result operand.
1580       switch (OpInfo.Kind) {
1581       case MatchableInfo::ResOperand::RenderAsmOperand: {
1582         // This comes from something we parsed.
1583         MatchableInfo::AsmOperand &Op = II.AsmOperands[OpInfo.AsmOperandNum];
1584
1585         // Registers are always converted the same, don't duplicate the
1586         // conversion function based on them.
1587         Signature += "__";
1588         if (Op.Class->isRegisterClass())
1589           Signature += "Reg";
1590         else
1591           Signature += Op.Class->ClassName;
1592         Signature += utostr(OpInfo.MINumOperands);
1593         Signature += "_" + itostr(OpInfo.AsmOperandNum);
1594
1595         CaseOS << "    ((" << TargetOperandClass << "*)Operands["
1596                << (OpInfo.AsmOperandNum+1) << "])->" << Op.Class->RenderMethod
1597                << "(Inst, " << OpInfo.MINumOperands << ");\n";
1598         break;
1599       }
1600
1601       case MatchableInfo::ResOperand::TiedOperand: {
1602         // If this operand is tied to a previous one, just copy the MCInst
1603         // operand from the earlier one.We can only tie single MCOperand values.
1604         //assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
1605         unsigned TiedOp = OpInfo.TiedOperandNum;
1606         assert(i > TiedOp && "Tied operand precedes its target!");
1607         CaseOS << "    Inst.addOperand(Inst.getOperand(" << TiedOp << "));\n";
1608         Signature += "__Tie" + utostr(TiedOp);
1609         break;
1610       }
1611       case MatchableInfo::ResOperand::ImmOperand: {
1612         int64_t Val = OpInfo.ImmVal;
1613         CaseOS << "    Inst.addOperand(MCOperand::CreateImm(" << Val << "));\n";
1614         Signature += "__imm" + itostr(Val);
1615         break;
1616       }
1617       case MatchableInfo::ResOperand::RegOperand: {
1618         if (OpInfo.Register == 0) {
1619           CaseOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
1620           Signature += "__reg0";
1621         } else {
1622           std::string N = getQualifiedName(OpInfo.Register);
1623           CaseOS << "    Inst.addOperand(MCOperand::CreateReg(" << N << "));\n";
1624           Signature += "__reg" + OpInfo.Register->getName();
1625         }
1626       }
1627       }
1628     }
1629
1630     II.ConversionFnKind = Signature;
1631
1632     // Check if we have already generated this signature.
1633     if (!GeneratedFns.insert(Signature).second)
1634       continue;
1635
1636     // If not, emit it now.  Add to the enum list.
1637     OS << "  " << Signature << ",\n";
1638
1639     CvtOS << "  case " << Signature << ":\n";
1640     CvtOS << CaseOS.str();
1641     CvtOS << "    return true;\n";
1642   }
1643
1644   // Finish the convert function.
1645
1646   CvtOS << "  }\n";
1647   CvtOS << "  return false;\n";
1648   CvtOS << "}\n\n";
1649
1650   // Finish the enum, and drop the convert function after it.
1651
1652   OS << "  NumConversionVariants\n";
1653   OS << "};\n\n";
1654
1655   OS << CvtOS.str();
1656 }
1657
1658 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1659 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1660                                       std::vector<ClassInfo*> &Infos,
1661                                       raw_ostream &OS) {
1662   OS << "namespace {\n\n";
1663
1664   OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1665      << "/// instruction matching.\n";
1666   OS << "enum MatchClassKind {\n";
1667   OS << "  InvalidMatchClass = 0,\n";
1668   for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1669          ie = Infos.end(); it != ie; ++it) {
1670     ClassInfo &CI = **it;
1671     OS << "  " << CI.Name << ", // ";
1672     if (CI.Kind == ClassInfo::Token) {
1673       OS << "'" << CI.ValueName << "'\n";
1674     } else if (CI.isRegisterClass()) {
1675       if (!CI.ValueName.empty())
1676         OS << "register class '" << CI.ValueName << "'\n";
1677       else
1678         OS << "derived register class\n";
1679     } else {
1680       OS << "user defined class '" << CI.ValueName << "'\n";
1681     }
1682   }
1683   OS << "  NumMatchClassKinds\n";
1684   OS << "};\n\n";
1685
1686   OS << "}\n\n";
1687 }
1688
1689 /// EmitValidateOperandClass - Emit the function to validate an operand class.
1690 static void EmitValidateOperandClass(AsmMatcherInfo &Info,
1691                                      raw_ostream &OS) {
1692   OS << "static bool validateOperandClass(MCParsedAsmOperand *GOp, "
1693      << "MatchClassKind Kind) {\n";
1694   OS << "  " << Info.Target.getName() << "Operand &Operand = *("
1695      << Info.Target.getName() << "Operand*)GOp;\n";
1696
1697   // The InvalidMatchClass is not to match any operand.
1698   OS << "  if (Kind == InvalidMatchClass)\n";
1699   OS << "    return false;\n\n";
1700
1701   // Check for Token operands first.
1702   OS << "  if (Operand.isToken())\n";
1703   OS << "    return isSubclass(matchTokenString(Operand.getToken()), Kind);"
1704      << "\n\n";
1705
1706   // Check for register operands, including sub-classes.
1707   OS << "  if (Operand.isReg()) {\n";
1708   OS << "    MatchClassKind OpKind;\n";
1709   OS << "    switch (Operand.getReg()) {\n";
1710   OS << "    default: OpKind = InvalidMatchClass; break;\n";
1711   for (std::map<Record*, ClassInfo*>::iterator
1712          it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1713        it != ie; ++it)
1714     OS << "    case " << Info.Target.getName() << "::"
1715        << it->first->getName() << ": OpKind = " << it->second->Name
1716        << "; break;\n";
1717   OS << "    }\n";
1718   OS << "    return isSubclass(OpKind, Kind);\n";
1719   OS << "  }\n\n";
1720
1721   // Check the user classes. We don't care what order since we're only
1722   // actually matching against one of them.
1723   for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1724          ie = Info.Classes.end(); it != ie; ++it) {
1725     ClassInfo &CI = **it;
1726
1727     if (!CI.isUserClass())
1728       continue;
1729
1730     OS << "  // '" << CI.ClassName << "' class\n";
1731     OS << "  if (Kind == " << CI.Name
1732        << " && Operand." << CI.PredicateMethod << "()) {\n";
1733     OS << "    return true;\n";
1734     OS << "  }\n\n";
1735   }
1736
1737   OS << "  return false;\n";
1738   OS << "}\n\n";
1739 }
1740
1741 /// EmitIsSubclass - Emit the subclass predicate function.
1742 static void EmitIsSubclass(CodeGenTarget &Target,
1743                            std::vector<ClassInfo*> &Infos,
1744                            raw_ostream &OS) {
1745   OS << "/// isSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1746   OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
1747   OS << "  if (A == B)\n";
1748   OS << "    return true;\n\n";
1749
1750   OS << "  switch (A) {\n";
1751   OS << "  default:\n";
1752   OS << "    return false;\n";
1753   for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1754          ie = Infos.end(); it != ie; ++it) {
1755     ClassInfo &A = **it;
1756
1757     std::vector<StringRef> SuperClasses;
1758     for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1759          ie = Infos.end(); it != ie; ++it) {
1760       ClassInfo &B = **it;
1761
1762       if (&A != &B && A.isSubsetOf(B))
1763         SuperClasses.push_back(B.Name);
1764     }
1765
1766     if (SuperClasses.empty())
1767       continue;
1768
1769     OS << "\n  case " << A.Name << ":\n";
1770
1771     if (SuperClasses.size() == 1) {
1772       OS << "    return B == " << SuperClasses.back() << ";\n";
1773       continue;
1774     }
1775
1776     OS << "    switch (B) {\n";
1777     OS << "    default: return false;\n";
1778     for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1779       OS << "    case " << SuperClasses[i] << ": return true;\n";
1780     OS << "    }\n";
1781   }
1782   OS << "  }\n";
1783   OS << "}\n\n";
1784 }
1785
1786 /// EmitMatchTokenString - Emit the function to match a token string to the
1787 /// appropriate match class value.
1788 static void EmitMatchTokenString(CodeGenTarget &Target,
1789                                  std::vector<ClassInfo*> &Infos,
1790                                  raw_ostream &OS) {
1791   // Construct the match list.
1792   std::vector<StringMatcher::StringPair> Matches;
1793   for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1794          ie = Infos.end(); it != ie; ++it) {
1795     ClassInfo &CI = **it;
1796
1797     if (CI.Kind == ClassInfo::Token)
1798       Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1799                                                   "return " + CI.Name + ";"));
1800   }
1801
1802   OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
1803
1804   StringMatcher("Name", Matches, OS).Emit();
1805
1806   OS << "  return InvalidMatchClass;\n";
1807   OS << "}\n\n";
1808 }
1809
1810 /// EmitMatchRegisterName - Emit the function to match a string to the target
1811 /// specific register enum.
1812 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1813                                   raw_ostream &OS) {
1814   // Construct the match list.
1815   std::vector<StringMatcher::StringPair> Matches;
1816   const std::vector<CodeGenRegister*> &Regs =
1817     Target.getRegBank().getRegisters();
1818   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1819     const CodeGenRegister *Reg = Regs[i];
1820     if (Reg->TheDef->getValueAsString("AsmName").empty())
1821       continue;
1822
1823     Matches.push_back(StringMatcher::StringPair(
1824                                      Reg->TheDef->getValueAsString("AsmName"),
1825                                      "return " + utostr(Reg->EnumValue) + ";"));
1826   }
1827
1828   OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
1829
1830   StringMatcher("Name", Matches, OS).Emit();
1831
1832   OS << "  return 0;\n";
1833   OS << "}\n\n";
1834 }
1835
1836 /// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1837 /// definitions.
1838 static void EmitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
1839                                                 raw_ostream &OS) {
1840   OS << "// Flags for subtarget features that participate in "
1841      << "instruction matching.\n";
1842   OS << "enum SubtargetFeatureFlag {\n";
1843   for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1844          it = Info.SubtargetFeatures.begin(),
1845          ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1846     SubtargetFeatureInfo &SFI = *it->second;
1847     OS << "  " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
1848   }
1849   OS << "  Feature_None = 0\n";
1850   OS << "};\n\n";
1851 }
1852
1853 /// EmitComputeAvailableFeatures - Emit the function to compute the list of
1854 /// available features given a subtarget.
1855 static void EmitComputeAvailableFeatures(AsmMatcherInfo &Info,
1856                                          raw_ostream &OS) {
1857   std::string ClassName =
1858     Info.AsmParser->getValueAsString("AsmParserClassName");
1859
1860   OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
1861      << "ComputeAvailableFeatures(uint64_t FB) const {\n";
1862   OS << "  unsigned Features = 0;\n";
1863   for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1864          it = Info.SubtargetFeatures.begin(),
1865          ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1866     SubtargetFeatureInfo &SFI = *it->second;
1867
1868     OS << "  if (";
1869     std::string CondStorage = SFI.TheDef->getValueAsString("AssemblerCondString");
1870     StringRef Conds = CondStorage;
1871     std::pair<StringRef,StringRef> Comma = Conds.split(',');
1872     bool First = true;
1873     do {
1874       if (!First)
1875         OS << " && ";
1876
1877       bool Neg = false;
1878       StringRef Cond = Comma.first;
1879       if (Cond[0] == '!') {
1880         Neg = true;
1881         Cond = Cond.substr(1);
1882       }
1883
1884       OS << "((FB & " << Info.Target.getName() << "::" << Cond << ")";
1885       if (Neg)
1886         OS << " == 0";
1887       else
1888         OS << " != 0";
1889       OS << ")";
1890
1891       if (Comma.second.empty())
1892         break;
1893
1894       First = false;
1895       Comma = Comma.second.split(',');
1896     } while (true);
1897
1898     OS << ")\n";
1899     OS << "    Features |= " << SFI.getEnumName() << ";\n";
1900   }
1901   OS << "  return Features;\n";
1902   OS << "}\n\n";
1903 }
1904
1905 static std::string GetAliasRequiredFeatures(Record *R,
1906                                             const AsmMatcherInfo &Info) {
1907   std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
1908   std::string Result;
1909   unsigned NumFeatures = 0;
1910   for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
1911     SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
1912
1913     if (F == 0)
1914       throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
1915                     "' is not marked as an AssemblerPredicate!");
1916
1917     if (NumFeatures)
1918       Result += '|';
1919
1920     Result += F->getEnumName();
1921     ++NumFeatures;
1922   }
1923
1924   if (NumFeatures > 1)
1925     Result = '(' + Result + ')';
1926   return Result;
1927 }
1928
1929 /// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
1930 /// emit a function for them and return true, otherwise return false.
1931 static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
1932   // Ignore aliases when match-prefix is set.
1933   if (!MatchPrefix.empty())
1934     return false;
1935
1936   std::vector<Record*> Aliases =
1937     Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
1938   if (Aliases.empty()) return false;
1939
1940   OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
1941         "unsigned Features) {\n";
1942
1943   // Keep track of all the aliases from a mnemonic.  Use an std::map so that the
1944   // iteration order of the map is stable.
1945   std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1946
1947   for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1948     Record *R = Aliases[i];
1949     AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
1950   }
1951
1952   // Process each alias a "from" mnemonic at a time, building the code executed
1953   // by the string remapper.
1954   std::vector<StringMatcher::StringPair> Cases;
1955   for (std::map<std::string, std::vector<Record*> >::iterator
1956        I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1957        I != E; ++I) {
1958     const std::vector<Record*> &ToVec = I->second;
1959
1960     // Loop through each alias and emit code that handles each case.  If there
1961     // are two instructions without predicates, emit an error.  If there is one,
1962     // emit it last.
1963     std::string MatchCode;
1964     int AliasWithNoPredicate = -1;
1965
1966     for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1967       Record *R = ToVec[i];
1968       std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
1969
1970       // If this unconditionally matches, remember it for later and diagnose
1971       // duplicates.
1972       if (FeatureMask.empty()) {
1973         if (AliasWithNoPredicate != -1) {
1974           // We can't have two aliases from the same mnemonic with no predicate.
1975           PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1976                      "two MnemonicAliases with the same 'from' mnemonic!");
1977           throw TGError(R->getLoc(), "this is the other MnemonicAlias.");
1978         }
1979
1980         AliasWithNoPredicate = i;
1981         continue;
1982       }
1983       if (R->getValueAsString("ToMnemonic") == I->first)
1984         throw TGError(R->getLoc(), "MnemonicAlias to the same string");
1985
1986       if (!MatchCode.empty())
1987         MatchCode += "else ";
1988       MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1989       MatchCode += "  Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
1990     }
1991
1992     if (AliasWithNoPredicate != -1) {
1993       Record *R = ToVec[AliasWithNoPredicate];
1994       if (!MatchCode.empty())
1995         MatchCode += "else\n  ";
1996       MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
1997     }
1998
1999     MatchCode += "return;";
2000
2001     Cases.push_back(std::make_pair(I->first, MatchCode));
2002   }
2003
2004   StringMatcher("Mnemonic", Cases, OS).Emit();
2005   OS << "}\n\n";
2006
2007   return true;
2008 }
2009
2010 static const char *getMinimalTypeForRange(uint64_t Range) {
2011   assert(Range < 0xFFFFFFFFULL && "Enum too large");
2012   if (Range > 0xFFFF)
2013     return "uint32_t";
2014   if (Range > 0xFF)
2015     return "uint16_t";
2016   return "uint8_t";
2017 }
2018
2019 static void EmitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
2020                               const AsmMatcherInfo &Info, StringRef ClassName) {
2021   // Emit the static custom operand parsing table;
2022   OS << "namespace {\n";
2023   OS << "  struct OperandMatchEntry {\n";
2024   OS << "    const char *Mnemonic;\n";
2025   OS << "    unsigned OperandMask;\n";
2026   OS << "    MatchClassKind Class;\n";
2027   OS << "    unsigned RequiredFeatures;\n";
2028   OS << "  };\n\n";
2029
2030   OS << "  // Predicate for searching for an opcode.\n";
2031   OS << "  struct LessOpcodeOperand {\n";
2032   OS << "    bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
2033   OS << "      return StringRef(LHS.Mnemonic) < RHS;\n";
2034   OS << "    }\n";
2035   OS << "    bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
2036   OS << "      return LHS < StringRef(RHS.Mnemonic);\n";
2037   OS << "    }\n";
2038   OS << "    bool operator()(const OperandMatchEntry &LHS,";
2039   OS << " const OperandMatchEntry &RHS) {\n";
2040   OS << "      return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
2041   OS << "    }\n";
2042   OS << "  };\n";
2043
2044   OS << "} // end anonymous namespace.\n\n";
2045
2046   OS << "static const OperandMatchEntry OperandMatchTable["
2047      << Info.OperandMatchInfo.size() << "] = {\n";
2048
2049   OS << "  /* Mnemonic, Operand List Mask, Operand Class, Features */\n";
2050   for (std::vector<OperandMatchEntry>::const_iterator it =
2051        Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end();
2052        it != ie; ++it) {
2053     const OperandMatchEntry &OMI = *it;
2054     const MatchableInfo &II = *OMI.MI;
2055
2056     OS << "  { \"" << II.Mnemonic << "\""
2057        << ", " << OMI.OperandMask;
2058
2059     OS << " /* ";
2060     bool printComma = false;
2061     for (int i = 0, e = 31; i !=e; ++i)
2062       if (OMI.OperandMask & (1 << i)) {
2063         if (printComma)
2064           OS << ", ";
2065         OS << i;
2066         printComma = true;
2067       }
2068     OS << " */";
2069
2070     OS << ", " << OMI.CI->Name
2071        << ", ";
2072
2073     // Write the required features mask.
2074     if (!II.RequiredFeatures.empty()) {
2075       for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2076         if (i) OS << "|";
2077         OS << II.RequiredFeatures[i]->getEnumName();
2078       }
2079     } else
2080       OS << "0";
2081     OS << " },\n";
2082   }
2083   OS << "};\n\n";
2084
2085   // Emit the operand class switch to call the correct custom parser for
2086   // the found operand class.
2087   OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2088      << Target.getName() << ClassName << "::\n"
2089      << "tryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>"
2090      << " &Operands,\n                      unsigned MCK) {\n\n"
2091      << "  switch(MCK) {\n";
2092
2093   for (std::vector<ClassInfo*>::const_iterator it = Info.Classes.begin(),
2094        ie = Info.Classes.end(); it != ie; ++it) {
2095     ClassInfo *CI = *it;
2096     if (CI->ParserMethod.empty())
2097       continue;
2098     OS << "  case " << CI->Name << ":\n"
2099        << "    return " << CI->ParserMethod << "(Operands);\n";
2100   }
2101
2102   OS << "  default:\n";
2103   OS << "    return MatchOperand_NoMatch;\n";
2104   OS << "  }\n";
2105   OS << "  return MatchOperand_NoMatch;\n";
2106   OS << "}\n\n";
2107
2108   // Emit the static custom operand parser. This code is very similar with
2109   // the other matcher. Also use MatchResultTy here just in case we go for
2110   // a better error handling.
2111   OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2112      << Target.getName() << ClassName << "::\n"
2113      << "MatchOperandParserImpl(SmallVectorImpl<MCParsedAsmOperand*>"
2114      << " &Operands,\n                       StringRef Mnemonic) {\n";
2115
2116   // Emit code to get the available features.
2117   OS << "  // Get the current feature set.\n";
2118   OS << "  unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2119
2120   OS << "  // Get the next operand index.\n";
2121   OS << "  unsigned NextOpNum = Operands.size()-1;\n";
2122
2123   // Emit code to search the table.
2124   OS << "  // Search the table.\n";
2125   OS << "  std::pair<const OperandMatchEntry*, const OperandMatchEntry*>";
2126   OS << " MnemonicRange =\n";
2127   OS << "    std::equal_range(OperandMatchTable, OperandMatchTable+"
2128      << Info.OperandMatchInfo.size() << ", Mnemonic,\n"
2129      << "                     LessOpcodeOperand());\n\n";
2130
2131   OS << "  if (MnemonicRange.first == MnemonicRange.second)\n";
2132   OS << "    return MatchOperand_NoMatch;\n\n";
2133
2134   OS << "  for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2135      << "       *ie = MnemonicRange.second; it != ie; ++it) {\n";
2136
2137   OS << "    // equal_range guarantees that instruction mnemonic matches.\n";
2138   OS << "    assert(Mnemonic == it->Mnemonic);\n\n";
2139
2140   // Emit check that the required features are available.
2141   OS << "    // check if the available features match\n";
2142   OS << "    if ((AvailableFeatures & it->RequiredFeatures) "
2143      << "!= it->RequiredFeatures) {\n";
2144   OS << "      continue;\n";
2145   OS << "    }\n\n";
2146
2147   // Emit check to ensure the operand number matches.
2148   OS << "    // check if the operand in question has a custom parser.\n";
2149   OS << "    if (!(it->OperandMask & (1 << NextOpNum)))\n";
2150   OS << "      continue;\n\n";
2151
2152   // Emit call to the custom parser method
2153   OS << "    // call custom parse method to handle the operand\n";
2154   OS << "    OperandMatchResultTy Result = ";
2155   OS << "tryCustomParseOperand(Operands, it->Class);\n";
2156   OS << "    if (Result != MatchOperand_NoMatch)\n";
2157   OS << "      return Result;\n";
2158   OS << "  }\n\n";
2159
2160   OS << "  // Okay, we had no match.\n";
2161   OS << "  return MatchOperand_NoMatch;\n";
2162   OS << "}\n\n";
2163 }
2164
2165 void AsmMatcherEmitter::run(raw_ostream &OS) {
2166   CodeGenTarget Target(Records);
2167   Record *AsmParser = Target.getAsmParser();
2168   std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2169
2170   // Compute the information on the instructions to match.
2171   AsmMatcherInfo Info(AsmParser, Target, Records);
2172   Info.BuildInfo();
2173
2174   // Sort the instruction table using the partial order on classes. We use
2175   // stable_sort to ensure that ambiguous instructions are still
2176   // deterministically ordered.
2177   std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2178                    less_ptr<MatchableInfo>());
2179
2180   DEBUG_WITH_TYPE("instruction_info", {
2181       for (std::vector<MatchableInfo*>::iterator
2182              it = Info.Matchables.begin(), ie = Info.Matchables.end();
2183            it != ie; ++it)
2184         (*it)->dump();
2185     });
2186
2187   // Check for ambiguous matchables.
2188   DEBUG_WITH_TYPE("ambiguous_instrs", {
2189     unsigned NumAmbiguous = 0;
2190     for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) {
2191       for (unsigned j = i + 1; j != e; ++j) {
2192         MatchableInfo &A = *Info.Matchables[i];
2193         MatchableInfo &B = *Info.Matchables[j];
2194
2195         if (A.CouldMatchAmbiguouslyWith(B)) {
2196           errs() << "warning: ambiguous matchables:\n";
2197           A.dump();
2198           errs() << "\nis incomparable with:\n";
2199           B.dump();
2200           errs() << "\n\n";
2201           ++NumAmbiguous;
2202         }
2203       }
2204     }
2205     if (NumAmbiguous)
2206       errs() << "warning: " << NumAmbiguous
2207              << " ambiguous matchables!\n";
2208   });
2209
2210   // Compute the information on the custom operand parsing.
2211   Info.BuildOperandMatchInfo();
2212
2213   // Write the output.
2214
2215   EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
2216
2217   // Information for the class declaration.
2218   OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2219   OS << "#undef GET_ASSEMBLER_HEADER\n";
2220   OS << "  // This should be included into the middle of the declaration of\n";
2221   OS << "  // your subclasses implementation of MCTargetAsmParser.\n";
2222   OS << "  unsigned ComputeAvailableFeatures(uint64_t FeatureBits) const;\n";
2223   OS << "  bool ConvertToMCInst(unsigned Kind, MCInst &Inst, "
2224      << "unsigned Opcode,\n"
2225      << "                       const SmallVectorImpl<MCParsedAsmOperand*> "
2226      << "&Operands);\n";
2227   OS << "  bool MnemonicIsValid(StringRef Mnemonic);\n";
2228   OS << "  unsigned MatchInstructionImpl(\n";
2229   OS << "    const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2230   OS << "    MCInst &Inst, unsigned &ErrorInfo, unsigned VariantID = 0);\n";
2231
2232   if (Info.OperandMatchInfo.size()) {
2233     OS << "\n  enum OperandMatchResultTy {\n";
2234     OS << "    MatchOperand_Success,    // operand matched successfully\n";
2235     OS << "    MatchOperand_NoMatch,    // operand did not match\n";
2236     OS << "    MatchOperand_ParseFail   // operand matched but had errors\n";
2237     OS << "  };\n";
2238     OS << "  OperandMatchResultTy MatchOperandParserImpl(\n";
2239     OS << "    SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2240     OS << "    StringRef Mnemonic);\n";
2241
2242     OS << "  OperandMatchResultTy tryCustomParseOperand(\n";
2243     OS << "    SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2244     OS << "    unsigned MCK);\n\n";
2245   }
2246
2247   OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2248
2249   OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2250   OS << "#undef GET_REGISTER_MATCHER\n\n";
2251
2252   // Emit the subtarget feature enumeration.
2253   EmitSubtargetFeatureFlagEnumeration(Info, OS);
2254
2255   // Emit the function to match a register name to number.
2256   EmitMatchRegisterName(Target, AsmParser, OS);
2257
2258   OS << "#endif // GET_REGISTER_MATCHER\n\n";
2259
2260
2261   OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2262   OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
2263
2264   // Generate the function that remaps for mnemonic aliases.
2265   bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
2266
2267   // Generate the unified function to convert operands into an MCInst.
2268   EmitConvertToMCInst(Target, ClassName, Info.Matchables, OS);
2269
2270   // Emit the enumeration for classes which participate in matching.
2271   EmitMatchClassEnumeration(Target, Info.Classes, OS);
2272
2273   // Emit the routine to match token strings to their match class.
2274   EmitMatchTokenString(Target, Info.Classes, OS);
2275
2276   // Emit the subclass predicate routine.
2277   EmitIsSubclass(Target, Info.Classes, OS);
2278
2279   // Emit the routine to validate an operand against a match class.
2280   EmitValidateOperandClass(Info, OS);
2281
2282   // Emit the available features compute function.
2283   EmitComputeAvailableFeatures(Info, OS);
2284
2285
2286   size_t MaxNumOperands = 0;
2287   for (std::vector<MatchableInfo*>::const_iterator it =
2288          Info.Matchables.begin(), ie = Info.Matchables.end();
2289        it != ie; ++it)
2290     MaxNumOperands = std::max(MaxNumOperands, (*it)->AsmOperands.size());
2291
2292   // Emit the static match table; unused classes get initalized to 0 which is
2293   // guaranteed to be InvalidMatchClass.
2294   //
2295   // FIXME: We can reduce the size of this table very easily. First, we change
2296   // it so that store the kinds in separate bit-fields for each index, which
2297   // only needs to be the max width used for classes at that index (we also need
2298   // to reject based on this during classification). If we then make sure to
2299   // order the match kinds appropriately (putting mnemonics last), then we
2300   // should only end up using a few bits for each class, especially the ones
2301   // following the mnemonic.
2302   OS << "namespace {\n";
2303   OS << "  struct MatchEntry {\n";
2304   OS << "    unsigned Opcode;\n";
2305   OS << "    const char *Mnemonic;\n";
2306   OS << "    " << getMinimalTypeForRange(Info.Matchables.size())
2307                << " ConvertFn;\n";
2308   OS << "    " << getMinimalTypeForRange(Info.Classes.size())
2309                << " Classes[" << MaxNumOperands << "];\n";
2310   OS << "    " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2311                << " RequiredFeatures;\n";
2312   OS << "    unsigned AsmVariantID;\n";
2313   OS << "  };\n\n";
2314
2315   OS << "  // Predicate for searching for an opcode.\n";
2316   OS << "  struct LessOpcode {\n";
2317   OS << "    bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
2318   OS << "      return StringRef(LHS.Mnemonic) < RHS;\n";
2319   OS << "    }\n";
2320   OS << "    bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
2321   OS << "      return LHS < StringRef(RHS.Mnemonic);\n";
2322   OS << "    }\n";
2323   OS << "    bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
2324   OS << "      return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
2325   OS << "    }\n";
2326   OS << "  };\n";
2327
2328   OS << "} // end anonymous namespace.\n\n";
2329
2330   OS << "static const MatchEntry MatchTable["
2331      << Info.Matchables.size() << "] = {\n";
2332
2333   for (std::vector<MatchableInfo*>::const_iterator it =
2334        Info.Matchables.begin(), ie = Info.Matchables.end();
2335        it != ie; ++it) {
2336     MatchableInfo &II = **it;
2337
2338     OS << "  { " << Target.getName() << "::"
2339        << II.getResultInst()->TheDef->getName() << ", \"" << II.Mnemonic << "\""
2340        << ", " << II.ConversionFnKind << ", { ";
2341     for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
2342       MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
2343
2344       if (i) OS << ", ";
2345       OS << Op.Class->Name;
2346     }
2347     OS << " }, ";
2348
2349     // Write the required features mask.
2350     if (!II.RequiredFeatures.empty()) {
2351       for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2352         if (i) OS << "|";
2353         OS << II.RequiredFeatures[i]->getEnumName();
2354       }
2355     } else
2356       OS << "0";
2357     OS << ", " << II.AsmVariantID;
2358     OS << "},\n";
2359   }
2360
2361   OS << "};\n\n";
2362
2363   // A method to determine if a mnemonic is in the list.
2364   OS << "bool " << Target.getName() << ClassName << "::\n"
2365      << "MnemonicIsValid(StringRef Mnemonic) {\n";
2366   OS << "  // Search the table.\n";
2367   OS << "  std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2368   OS << "    std::equal_range(MatchTable, MatchTable+"
2369      << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n";
2370   OS << "  return MnemonicRange.first != MnemonicRange.second;\n";
2371   OS << "}\n\n";
2372
2373   // Finally, build the match function.
2374   OS << "unsigned "
2375      << Target.getName() << ClassName << "::\n"
2376      << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
2377      << " &Operands,\n";
2378   OS << "                     MCInst &Inst, unsigned &ErrorInfo,\n";
2379   OS << "                     unsigned VariantID) {\n";
2380
2381   // Emit code to get the available features.
2382   OS << "  // Get the current feature set.\n";
2383   OS << "  unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2384
2385   OS << "  // Get the instruction mnemonic, which is the first token.\n";
2386   OS << "  StringRef Mnemonic = ((" << Target.getName()
2387      << "Operand*)Operands[0])->getToken();\n\n";
2388
2389   if (HasMnemonicAliases) {
2390     OS << "  // Process all MnemonicAliases to remap the mnemonic.\n";
2391     OS << "  // FIXME : Add an entry in AsmParserVariant to check this.\n";
2392     OS << "  if (!VariantID)\n";
2393     OS << "    applyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
2394   }
2395
2396   // Emit code to compute the class list for this operand vector.
2397   OS << "  // Eliminate obvious mismatches.\n";
2398   OS << "  if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
2399   OS << "    ErrorInfo = " << (MaxNumOperands+1) << ";\n";
2400   OS << "    return Match_InvalidOperand;\n";
2401   OS << "  }\n\n";
2402
2403   OS << "  // Some state to try to produce better error messages.\n";
2404   OS << "  bool HadMatchOtherThanFeatures = false;\n";
2405   OS << "  bool HadMatchOtherThanPredicate = false;\n";
2406   OS << "  unsigned RetCode = Match_InvalidOperand;\n";
2407   OS << "  // Set ErrorInfo to the operand that mismatches if it is\n";
2408   OS << "  // wrong for all instances of the instruction.\n";
2409   OS << "  ErrorInfo = ~0U;\n";
2410
2411   // Emit code to search the table.
2412   OS << "  // Search the table.\n";
2413   OS << "  std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2414   OS << "    std::equal_range(MatchTable, MatchTable+"
2415      << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n";
2416
2417   OS << "  // Return a more specific error code if no mnemonics match.\n";
2418   OS << "  if (MnemonicRange.first == MnemonicRange.second)\n";
2419   OS << "    return Match_MnemonicFail;\n\n";
2420
2421   OS << "  for (const MatchEntry *it = MnemonicRange.first, "
2422      << "*ie = MnemonicRange.second;\n";
2423   OS << "       it != ie; ++it) {\n";
2424
2425   OS << "    // equal_range guarantees that instruction mnemonic matches.\n";
2426   OS << "    assert(Mnemonic == it->Mnemonic);\n";
2427
2428   // Emit check that the subclasses match.
2429   OS << "    if (VariantID != it->AsmVariantID) continue;\n";
2430   OS << "    bool OperandsValid = true;\n";
2431   OS << "    for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
2432   OS << "      if (i + 1 >= Operands.size()) {\n";
2433   OS << "        OperandsValid = (it->Classes[i] == " <<"InvalidMatchClass);\n";
2434   OS << "        break;\n";
2435   OS << "      }\n";
2436   OS << "      if (validateOperandClass(Operands[i+1], "
2437                                        "(MatchClassKind)it->Classes[i]))\n";
2438   OS << "        continue;\n";
2439   OS << "      // If this operand is broken for all of the instances of this\n";
2440   OS << "      // mnemonic, keep track of it so we can report loc info.\n";
2441   OS << "      if (it == MnemonicRange.first || ErrorInfo <= i+1)\n";
2442   OS << "        ErrorInfo = i+1;\n";
2443   OS << "      // Otherwise, just reject this instance of the mnemonic.\n";
2444   OS << "      OperandsValid = false;\n";
2445   OS << "      break;\n";
2446   OS << "    }\n\n";
2447
2448   OS << "    if (!OperandsValid) continue;\n";
2449
2450   // Emit check that the required features are available.
2451   OS << "    if ((AvailableFeatures & it->RequiredFeatures) "
2452      << "!= it->RequiredFeatures) {\n";
2453   OS << "      HadMatchOtherThanFeatures = true;\n";
2454   OS << "      continue;\n";
2455   OS << "    }\n";
2456   OS << "\n";
2457   OS << "    // We have selected a definite instruction, convert the parsed\n"
2458      << "    // operands into the appropriate MCInst.\n";
2459   OS << "    if (!ConvertToMCInst(it->ConvertFn, Inst,\n"
2460      << "                         it->Opcode, Operands))\n";
2461   OS << "      return Match_ConversionFail;\n";
2462   OS << "\n";
2463
2464   // Verify the instruction with the target-specific match predicate function.
2465   OS << "    // We have a potential match. Check the target predicate to\n"
2466      << "    // handle any context sensitive constraints.\n"
2467      << "    unsigned MatchResult;\n"
2468      << "    if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
2469      << " Match_Success) {\n"
2470      << "      Inst.clear();\n"
2471      << "      RetCode = MatchResult;\n"
2472      << "      HadMatchOtherThanPredicate = true;\n"
2473      << "      continue;\n"
2474      << "    }\n\n";
2475
2476   // Call the post-processing function, if used.
2477   std::string InsnCleanupFn =
2478     AsmParser->getValueAsString("AsmParserInstCleanup");
2479   if (!InsnCleanupFn.empty())
2480     OS << "    " << InsnCleanupFn << "(Inst);\n";
2481
2482   OS << "    return Match_Success;\n";
2483   OS << "  }\n\n";
2484
2485   OS << "  // Okay, we had no match.  Try to return a useful error code.\n";
2486   OS << "  if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)";
2487   OS << " return RetCode;\n";
2488   OS << "  return Match_MissingFeature;\n";
2489   OS << "}\n\n";
2490
2491   if (Info.OperandMatchInfo.size())
2492     EmitCustomOperandParsing(OS, Target, Info, ClassName);
2493
2494   OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
2495 }