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