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