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