Avoid counting InlineAsm as a call - it prevents loop unrolling.
[oota-llvm.git] / utils / TableGen / AsmMatcherEmitter.cpp
1 //===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend emits a target specifier matcher for converting parsed
11 // assembly operands in the MCInst structures.
12 //
13 // The input to the target specific matcher is a list of literal tokens and
14 // operands. The target specific parser should generally eliminate any syntax
15 // which is not relevant for matching; for example, comma tokens should have
16 // already been consumed and eliminated by the parser. Most instructions will
17 // end up with a single literal token (the instruction name) and some number of
18 // operands.
19 //
20 // Some example inputs, for X86:
21 //   'addl' (immediate ...) (register ...)
22 //   'add' (immediate ...) (memory ...)
23 //   'call' '*' %epc 
24 //
25 // The assembly matcher is responsible for converting this input into a precise
26 // machine instruction (i.e., an instruction with a well defined encoding). This
27 // mapping has several properties which complicate matching:
28 //
29 //  - It may be ambiguous; many architectures can legally encode particular
30 //    variants of an instruction in different ways (for example, using a smaller
31 //    encoding for small immediates). Such ambiguities should never be
32 //    arbitrarily resolved by the assembler, the assembler is always responsible
33 //    for choosing the "best" available instruction.
34 //
35 //  - It may depend on the subtarget or the assembler context. Instructions
36 //    which are invalid for the current mode, but otherwise unambiguous (e.g.,
37 //    an SSE instruction in a file being assembled for i486) should be accepted
38 //    and rejected by the assembler front end. However, if the proper encoding
39 //    for an instruction is dependent on the assembler context then the matcher
40 //    is responsible for selecting the correct machine instruction for the
41 //    current mode.
42 //
43 // The core matching algorithm attempts to exploit the regularity in most
44 // instruction sets to quickly determine the set of possibly matching
45 // instructions, and the simplify the generated code. Additionally, this helps
46 // to ensure that the ambiguities are intentionally resolved by the user.
47 //
48 // The matching is divided into two distinct phases:
49 //
50 //   1. Classification: Each operand is mapped to the unique set which (a)
51 //      contains it, and (b) is the largest such subset for which a single
52 //      instruction could match all members.
53 //
54 //      For register classes, we can generate these subgroups automatically. For
55 //      arbitrary operands, we expect the user to define the classes and their
56 //      relations to one another (for example, 8-bit signed immediates as a
57 //      subset of 32-bit immediates).
58 //
59 //      By partitioning the operands in this way, we guarantee that for any
60 //      tuple of classes, any single instruction must match either all or none
61 //      of the sets of operands which could classify to that tuple.
62 //
63 //      In addition, the subset relation amongst classes induces a partial order
64 //      on such tuples, which we use to resolve ambiguities.
65 //
66 //      FIXME: What do we do if a crazy case shows up where this is the wrong
67 //      resolution?
68 //
69 //   2. The input can now be treated as a tuple of classes (static tokens are
70 //      simple singleton sets). Each such tuple should generally map to a single
71 //      instruction (we currently ignore cases where this isn't true, whee!!!),
72 //      which we can emit a simple matcher for.
73 //
74 //===----------------------------------------------------------------------===//
75
76 #include "AsmMatcherEmitter.h"
77 #include "CodeGenTarget.h"
78 #include "Record.h"
79 #include "llvm/ADT/OwningPtr.h"
80 #include "llvm/ADT/SmallVector.h"
81 #include "llvm/ADT/STLExtras.h"
82 #include "llvm/ADT/StringExtras.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/Debug.h"
85 #include <list>
86 #include <map>
87 #include <set>
88 using namespace llvm;
89
90 static cl::opt<std::string>
91 MatchPrefix("match-prefix", cl::init(""),
92             cl::desc("Only match instructions with the given prefix"));
93
94 /// FlattenVariants - Flatten an .td file assembly string by selecting the
95 /// variant at index \arg N.
96 static std::string FlattenVariants(const std::string &AsmString,
97                                    unsigned N) {
98   StringRef Cur = AsmString;
99   std::string Res = "";
100   
101   for (;;) {
102     // Find the start of the next variant string.
103     size_t VariantsStart = 0;
104     for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
105       if (Cur[VariantsStart] == '{' && 
106           (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
107                                   Cur[VariantsStart-1] != '\\')))
108         break;
109
110     // Add the prefix to the result.
111     Res += Cur.slice(0, VariantsStart);
112     if (VariantsStart == Cur.size())
113       break;
114
115     ++VariantsStart; // Skip the '{'.
116
117     // Scan to the end of the variants string.
118     size_t VariantsEnd = VariantsStart;
119     unsigned NestedBraces = 1;
120     for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
121       if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
122         if (--NestedBraces == 0)
123           break;
124       } else if (Cur[VariantsEnd] == '{')
125         ++NestedBraces;
126     }
127
128     // Select the Nth variant (or empty).
129     StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
130     for (unsigned i = 0; i != N; ++i)
131       Selection = Selection.split('|').second;
132     Res += Selection.split('|').first;
133
134     assert(VariantsEnd != Cur.size() && 
135            "Unterminated variants in assembly string!");
136     Cur = Cur.substr(VariantsEnd + 1);
137   } 
138
139   return Res;
140 }
141
142 /// TokenizeAsmString - Tokenize a simplified assembly string.
143 static void TokenizeAsmString(StringRef AsmString, 
144                               SmallVectorImpl<StringRef> &Tokens) {
145   unsigned Prev = 0;
146   bool InTok = true;
147   for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {
148     switch (AsmString[i]) {
149     case '[':
150     case ']':
151     case '*':
152     case '!':
153     case ' ':
154     case '\t':
155     case ',':
156       if (InTok) {
157         Tokens.push_back(AsmString.slice(Prev, i));
158         InTok = false;
159       }
160       if (!isspace(AsmString[i]) && AsmString[i] != ',')
161         Tokens.push_back(AsmString.substr(i, 1));
162       Prev = i + 1;
163       break;
164       
165     case '\\':
166       if (InTok) {
167         Tokens.push_back(AsmString.slice(Prev, i));
168         InTok = false;
169       }
170       ++i;
171       assert(i != AsmString.size() && "Invalid quoted character");
172       Tokens.push_back(AsmString.substr(i, 1));
173       Prev = i + 1;
174       break;
175
176     case '$': {
177       // If this isn't "${", treat like a normal token.
178       if (i + 1 == AsmString.size() || AsmString[i + 1] != '{') {
179         if (InTok) {
180           Tokens.push_back(AsmString.slice(Prev, i));
181           InTok = false;
182         }
183         Prev = i;
184         break;
185       }
186
187       if (InTok) {
188         Tokens.push_back(AsmString.slice(Prev, i));
189         InTok = false;
190       }
191
192       StringRef::iterator End =
193         std::find(AsmString.begin() + i, AsmString.end(), '}');
194       assert(End != AsmString.end() && "Missing brace in operand reference!");
195       size_t EndPos = End - AsmString.begin();
196       Tokens.push_back(AsmString.slice(i, EndPos+1));
197       Prev = EndPos + 1;
198       i = EndPos;
199       break;
200     }
201
202     default:
203       InTok = true;
204     }
205   }
206   if (InTok && Prev != AsmString.size())
207     Tokens.push_back(AsmString.substr(Prev));
208 }
209
210 static bool IsAssemblerInstruction(StringRef Name,
211                                    const CodeGenInstruction &CGI, 
212                                    const SmallVectorImpl<StringRef> &Tokens) {
213   // Ignore "codegen only" instructions.
214   if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
215     return false;
216
217   // Ignore pseudo ops.
218   //
219   // FIXME: This is a hack; can we convert these instructions to set the
220   // "codegen only" bit instead?
221   if (const RecordVal *Form = CGI.TheDef->getValue("Form"))
222     if (Form->getValue()->getAsString() == "Pseudo")
223       return false;
224
225   // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
226   //
227   // FIXME: This is a total hack.
228   if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
229     return false;
230
231   // Ignore instructions with no .s string.
232   //
233   // FIXME: What are these?
234   if (CGI.AsmString.empty())
235     return false;
236
237   // FIXME: Hack; ignore any instructions with a newline in them.
238   if (std::find(CGI.AsmString.begin(), 
239                 CGI.AsmString.end(), '\n') != CGI.AsmString.end())
240     return false;
241   
242   // Ignore instructions with attributes, these are always fake instructions for
243   // simplifying codegen.
244   //
245   // FIXME: Is this true?
246   //
247   // Also, check for instructions which reference the operand multiple times;
248   // this implies a constraint we would not honor.
249   std::set<std::string> OperandNames;
250   for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
251     if (Tokens[i][0] == '$' && 
252         std::find(Tokens[i].begin(), 
253                   Tokens[i].end(), ':') != Tokens[i].end()) {
254       DEBUG({
255           errs() << "warning: '" << Name << "': "
256                  << "ignoring instruction; operand with attribute '" 
257                  << Tokens[i] << "'\n";
258         });
259       return false;
260     }
261
262     if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
263       std::string Err = "'" + Name.str() + "': " +
264         "invalid assembler instruction; tied operand '" + Tokens[i].str() + "'";
265       throw TGError(CGI.TheDef->getLoc(), Err);
266     }
267   }
268
269   return true;
270 }
271
272 namespace {
273
274 /// ClassInfo - Helper class for storing the information about a particular
275 /// class of operands which can be matched.
276 struct ClassInfo {
277   enum ClassInfoKind {
278     /// Invalid kind, for use as a sentinel value.
279     Invalid = 0,
280
281     /// The class for a particular token.
282     Token,
283
284     /// The (first) register class, subsequent register classes are
285     /// RegisterClass0+1, and so on.
286     RegisterClass0,
287
288     /// The (first) user defined class, subsequent user defined classes are
289     /// UserClass0+1, and so on.
290     UserClass0 = 1<<16
291   };
292
293   /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
294   /// N) for the Nth user defined class.
295   unsigned Kind;
296
297   /// SuperClasses - The super classes of this class. Note that for simplicities
298   /// sake user operands only record their immediate super class, while register
299   /// operands include all superclasses.
300   std::vector<ClassInfo*> SuperClasses;
301
302   /// Name - The full class name, suitable for use in an enum.
303   std::string Name;
304
305   /// ClassName - The unadorned generic name for this class (e.g., Token).
306   std::string ClassName;
307
308   /// ValueName - The name of the value this class represents; for a token this
309   /// is the literal token string, for an operand it is the TableGen class (or
310   /// empty if this is a derived class).
311   std::string ValueName;
312
313   /// PredicateMethod - The name of the operand method to test whether the
314   /// operand matches this class; this is not valid for Token or register kinds.
315   std::string PredicateMethod;
316
317   /// RenderMethod - The name of the operand method to add this operand to an
318   /// MCInst; this is not valid for Token or register kinds.
319   std::string RenderMethod;
320
321   /// For register classes, the records for all the registers in this class.
322   std::set<Record*> Registers;
323
324 public:
325   /// isRegisterClass() - Check if this is a register class.
326   bool isRegisterClass() const {
327     return Kind >= RegisterClass0 && Kind < UserClass0;
328   }
329
330   /// isUserClass() - Check if this is a user defined class.
331   bool isUserClass() const {
332     return Kind >= UserClass0;
333   }
334
335   /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
336   /// are related if they are in the same class hierarchy.
337   bool isRelatedTo(const ClassInfo &RHS) const {
338     // Tokens are only related to tokens.
339     if (Kind == Token || RHS.Kind == Token)
340       return Kind == Token && RHS.Kind == Token;
341
342     // Registers classes are only related to registers classes, and only if
343     // their intersection is non-empty.
344     if (isRegisterClass() || RHS.isRegisterClass()) {
345       if (!isRegisterClass() || !RHS.isRegisterClass())
346         return false;
347
348       std::set<Record*> Tmp;
349       std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
350       std::set_intersection(Registers.begin(), Registers.end(), 
351                             RHS.Registers.begin(), RHS.Registers.end(),
352                             II);
353
354       return !Tmp.empty();
355     }
356
357     // Otherwise we have two users operands; they are related if they are in the
358     // same class hierarchy.
359     //
360     // FIXME: This is an oversimplification, they should only be related if they
361     // intersect, however we don't have that information.
362     assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
363     const ClassInfo *Root = this;
364     while (!Root->SuperClasses.empty())
365       Root = Root->SuperClasses.front();
366
367     const ClassInfo *RHSRoot = &RHS;
368     while (!RHSRoot->SuperClasses.empty())
369       RHSRoot = RHSRoot->SuperClasses.front();
370     
371     return Root == RHSRoot;
372   }
373
374   /// isSubsetOf - Test whether this class is a subset of \arg RHS; 
375   bool isSubsetOf(const ClassInfo &RHS) const {
376     // This is a subset of RHS if it is the same class...
377     if (this == &RHS)
378       return true;
379
380     // ... or if any of its super classes are a subset of RHS.
381     for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
382            ie = SuperClasses.end(); it != ie; ++it)
383       if ((*it)->isSubsetOf(RHS))
384         return true;
385
386     return false;
387   }
388
389   /// operator< - Compare two classes.
390   bool operator<(const ClassInfo &RHS) const {
391     // Unrelated classes can be ordered by kind.
392     if (!isRelatedTo(RHS))
393       return Kind < RHS.Kind;
394
395     switch (Kind) {
396     case Invalid:
397       assert(0 && "Invalid kind!");
398     case Token:
399       // Tokens are comparable by value.
400       //
401       // FIXME: Compare by enum value.
402       return ValueName < RHS.ValueName;
403
404     default:
405       // This class preceeds the RHS if it is a proper subset of the RHS.
406       return this != &RHS && isSubsetOf(RHS);
407     }
408   }
409 };
410
411 /// InstructionInfo - Helper class for storing the necessary information for an
412 /// instruction which is capable of being matched.
413 struct InstructionInfo {
414   struct Operand {
415     /// The unique class instance this operand should match.
416     ClassInfo *Class;
417
418     /// The original operand this corresponds to, if any.
419     const CodeGenInstruction::OperandInfo *OperandInfo;
420   };
421
422   /// InstrName - The target name for this instruction.
423   std::string InstrName;
424
425   /// Instr - The instruction this matches.
426   const CodeGenInstruction *Instr;
427
428   /// AsmString - The assembly string for this instruction (with variants
429   /// removed).
430   std::string AsmString;
431
432   /// Tokens - The tokenized assembly pattern that this instruction matches.
433   SmallVector<StringRef, 4> Tokens;
434
435   /// Operands - The operands that this instruction matches.
436   SmallVector<Operand, 4> Operands;
437
438   /// ConversionFnKind - The enum value which is passed to the generated
439   /// ConvertToMCInst to convert parsed operands into an MCInst for this
440   /// function.
441   std::string ConversionFnKind;
442
443   /// operator< - Compare two instructions.
444   bool operator<(const InstructionInfo &RHS) const {
445     if (Operands.size() != RHS.Operands.size())
446       return Operands.size() < RHS.Operands.size();
447
448     // Compare lexicographically by operand. The matcher validates that other
449     // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
450     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
451       if (*Operands[i].Class < *RHS.Operands[i].Class)
452         return true;
453       if (*RHS.Operands[i].Class < *Operands[i].Class)
454         return false;
455     }
456
457     return false;
458   }
459
460   /// CouldMatchAmiguouslyWith - Check whether this instruction could
461   /// ambiguously match the same set of operands as \arg RHS (without being a
462   /// strictly superior match).
463   bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
464     // The number of operands is unambiguous.
465     if (Operands.size() != RHS.Operands.size())
466       return false;
467
468     // Otherwise, make sure the ordering of the two instructions is unambiguous
469     // by checking that either (a) a token or operand kind discriminates them,
470     // or (b) the ordering among equivalent kinds is consistent.
471
472     // Tokens and operand kinds are unambiguous (assuming a correct target
473     // specific parser).
474     for (unsigned i = 0, e = Operands.size(); i != e; ++i)
475       if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
476           Operands[i].Class->Kind == ClassInfo::Token)
477         if (*Operands[i].Class < *RHS.Operands[i].Class ||
478             *RHS.Operands[i].Class < *Operands[i].Class)
479           return false;
480     
481     // Otherwise, this operand could commute if all operands are equivalent, or
482     // there is a pair of operands that compare less than and a pair that
483     // compare greater than.
484     bool HasLT = false, HasGT = false;
485     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
486       if (*Operands[i].Class < *RHS.Operands[i].Class)
487         HasLT = true;
488       if (*RHS.Operands[i].Class < *Operands[i].Class)
489         HasGT = true;
490     }
491
492     return !(HasLT ^ HasGT);
493   }
494
495 public:
496   void dump();
497 };
498
499 class AsmMatcherInfo {
500 public:
501   /// The tablegen AsmParser record.
502   Record *AsmParser;
503
504   /// The AsmParser "CommentDelimiter" value.
505   std::string CommentDelimiter;
506
507   /// The AsmParser "RegisterPrefix" value.
508   std::string RegisterPrefix;
509
510   /// The classes which are needed for matching.
511   std::vector<ClassInfo*> Classes;
512   
513   /// The information on the instruction to match.
514   std::vector<InstructionInfo*> Instructions;
515
516   /// Map of Register records to their class information.
517   std::map<Record*, ClassInfo*> RegisterClasses;
518
519 private:
520   /// Map of token to class information which has already been constructed.
521   std::map<std::string, ClassInfo*> TokenClasses;
522
523   /// Map of RegisterClass records to their class information.
524   std::map<Record*, ClassInfo*> RegisterClassClasses;
525
526   /// Map of AsmOperandClass records to their class information.
527   std::map<Record*, ClassInfo*> AsmOperandClasses;
528
529 private:
530   /// getTokenClass - Lookup or create the class for the given token.
531   ClassInfo *getTokenClass(StringRef Token);
532
533   /// getOperandClass - Lookup or create the class for the given operand.
534   ClassInfo *getOperandClass(StringRef Token,
535                              const CodeGenInstruction::OperandInfo &OI);
536
537   /// BuildRegisterClasses - Build the ClassInfo* instances for register
538   /// classes.
539   void BuildRegisterClasses(CodeGenTarget &Target, 
540                             std::set<std::string> &SingletonRegisterNames);
541
542   /// BuildOperandClasses - Build the ClassInfo* instances for user defined
543   /// operand classes.
544   void BuildOperandClasses(CodeGenTarget &Target);
545
546 public:
547   AsmMatcherInfo(Record *_AsmParser);
548
549   /// BuildInfo - Construct the various tables used during matching.
550   void BuildInfo(CodeGenTarget &Target);
551 };
552
553 }
554
555 void InstructionInfo::dump() {
556   errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
557          << ", tokens:[";
558   for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
559     errs() << Tokens[i];
560     if (i + 1 != e)
561       errs() << ", ";
562   }
563   errs() << "]\n";
564
565   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
566     Operand &Op = Operands[i];
567     errs() << "  op[" << i << "] = " << Op.Class->ClassName << " - ";
568     if (Op.Class->Kind == ClassInfo::Token) {
569       errs() << '\"' << Tokens[i] << "\"\n";
570       continue;
571     }
572
573     if (!Op.OperandInfo) {
574       errs() << "(singleton register)\n";
575       continue;
576     }
577
578     const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
579     errs() << OI.Name << " " << OI.Rec->getName()
580            << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
581   }
582 }
583
584 static std::string getEnumNameForToken(StringRef Str) {
585   std::string Res;
586   
587   for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
588     switch (*it) {
589     case '*': Res += "_STAR_"; break;
590     case '%': Res += "_PCT_"; break;
591     case ':': Res += "_COLON_"; break;
592
593     default:
594       if (isalnum(*it))  {
595         Res += *it;
596       } else {
597         Res += "_" + utostr((unsigned) *it) + "_";
598       }
599     }
600   }
601
602   return Res;
603 }
604
605 /// getRegisterRecord - Get the register record for \arg name, or 0.
606 static Record *getRegisterRecord(CodeGenTarget &Target, StringRef Name) {
607   for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
608     const CodeGenRegister &Reg = Target.getRegisters()[i];
609     if (Name == Reg.TheDef->getValueAsString("AsmName"))
610       return Reg.TheDef;
611   }
612
613   return 0;
614 }
615
616 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
617   ClassInfo *&Entry = TokenClasses[Token];
618   
619   if (!Entry) {
620     Entry = new ClassInfo();
621     Entry->Kind = ClassInfo::Token;
622     Entry->ClassName = "Token";
623     Entry->Name = "MCK_" + getEnumNameForToken(Token);
624     Entry->ValueName = Token;
625     Entry->PredicateMethod = "<invalid>";
626     Entry->RenderMethod = "<invalid>";
627     Classes.push_back(Entry);
628   }
629
630   return Entry;
631 }
632
633 ClassInfo *
634 AsmMatcherInfo::getOperandClass(StringRef Token,
635                                 const CodeGenInstruction::OperandInfo &OI) {
636   if (OI.Rec->isSubClassOf("RegisterClass")) {
637     ClassInfo *CI = RegisterClassClasses[OI.Rec];
638
639     if (!CI) {
640       PrintError(OI.Rec->getLoc(), "register class has no class info!");
641       throw std::string("ERROR: Missing register class!");
642     }
643
644     return CI;
645   }
646
647   assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
648   Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
649   ClassInfo *CI = AsmOperandClasses[MatchClass];
650
651   if (!CI) {
652     PrintError(OI.Rec->getLoc(), "operand has no match class!");
653     throw std::string("ERROR: Missing match class!");
654   }
655
656   return CI;
657 }
658
659 void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target,
660                                           std::set<std::string>
661                                             &SingletonRegisterNames) {
662   std::vector<CodeGenRegisterClass> RegisterClasses;
663   std::vector<CodeGenRegister> Registers;
664
665   RegisterClasses = Target.getRegisterClasses();
666   Registers = Target.getRegisters();
667
668   // The register sets used for matching.
669   std::set< std::set<Record*> > RegisterSets;
670
671   // Gather the defined sets.  
672   for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
673          ie = RegisterClasses.end(); it != ie; ++it)
674     RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
675                                           it->Elements.end()));
676
677   // Add any required singleton sets.
678   for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
679          ie = SingletonRegisterNames.end(); it != ie; ++it)
680     if (Record *Rec = getRegisterRecord(Target, *it))
681       RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
682          
683   // Introduce derived sets where necessary (when a register does not determine
684   // a unique register set class), and build the mapping of registers to the set
685   // they should classify to.
686   std::map<Record*, std::set<Record*> > RegisterMap;
687   for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
688          ie = Registers.end(); it != ie; ++it) {
689     CodeGenRegister &CGR = *it;
690     // Compute the intersection of all sets containing this register.
691     std::set<Record*> ContainingSet;
692     
693     for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
694            ie = RegisterSets.end(); it != ie; ++it) {
695       if (!it->count(CGR.TheDef))
696         continue;
697
698       if (ContainingSet.empty()) {
699         ContainingSet = *it;
700       } else {
701         std::set<Record*> Tmp;
702         std::swap(Tmp, ContainingSet);
703         std::insert_iterator< std::set<Record*> > II(ContainingSet,
704                                                      ContainingSet.begin());
705         std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
706                               II);
707       }
708     }
709
710     if (!ContainingSet.empty()) {
711       RegisterSets.insert(ContainingSet);
712       RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
713     }
714   }
715
716   // Construct the register classes.
717   std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
718   unsigned Index = 0;
719   for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
720          ie = RegisterSets.end(); it != ie; ++it, ++Index) {
721     ClassInfo *CI = new ClassInfo();
722     CI->Kind = ClassInfo::RegisterClass0 + Index;
723     CI->ClassName = "Reg" + utostr(Index);
724     CI->Name = "MCK_Reg" + utostr(Index);
725     CI->ValueName = "";
726     CI->PredicateMethod = ""; // unused
727     CI->RenderMethod = "addRegOperands";
728     CI->Registers = *it;
729     Classes.push_back(CI);
730     RegisterSetClasses.insert(std::make_pair(*it, CI));
731   }
732
733   // Find the superclasses; we could compute only the subgroup lattice edges,
734   // but there isn't really a point.
735   for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
736          ie = RegisterSets.end(); it != ie; ++it) {
737     ClassInfo *CI = RegisterSetClasses[*it];
738     for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
739            ie2 = RegisterSets.end(); it2 != ie2; ++it2)
740       if (*it != *it2 && 
741           std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
742         CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
743   }
744
745   // Name the register classes which correspond to a user defined RegisterClass.
746   for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
747          ie = RegisterClasses.end(); it != ie; ++it) {
748     ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
749                                                          it->Elements.end())];
750     if (CI->ValueName.empty()) {
751       CI->ClassName = it->getName();
752       CI->Name = "MCK_" + it->getName();
753       CI->ValueName = it->getName();
754     } else
755       CI->ValueName = CI->ValueName + "," + it->getName();
756
757     RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
758   }
759
760   // Populate the map for individual registers.
761   for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
762          ie = RegisterMap.end(); it != ie; ++it)
763     this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
764
765   // Name the register classes which correspond to singleton registers.
766   for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
767          ie = SingletonRegisterNames.end(); it != ie; ++it) {
768     if (Record *Rec = getRegisterRecord(Target, *it)) {
769       ClassInfo *CI = this->RegisterClasses[Rec];
770       assert(CI && "Missing singleton register class info!");
771
772       if (CI->ValueName.empty()) {
773         CI->ClassName = Rec->getName();
774         CI->Name = "MCK_" + Rec->getName();
775         CI->ValueName = Rec->getName();
776       } else
777         CI->ValueName = CI->ValueName + "," + Rec->getName();
778     }
779   }
780 }
781
782 void AsmMatcherInfo::BuildOperandClasses(CodeGenTarget &Target) {
783   std::vector<Record*> AsmOperands;
784   AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
785
786   // Pre-populate AsmOperandClasses map.
787   for (std::vector<Record*>::iterator it = AsmOperands.begin(), 
788          ie = AsmOperands.end(); it != ie; ++it)
789     AsmOperandClasses[*it] = new ClassInfo();
790
791   unsigned Index = 0;
792   for (std::vector<Record*>::iterator it = AsmOperands.begin(), 
793          ie = AsmOperands.end(); it != ie; ++it, ++Index) {
794     ClassInfo *CI = AsmOperandClasses[*it];
795     CI->Kind = ClassInfo::UserClass0 + Index;
796
797     ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
798     for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
799       DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
800       if (!DI) {
801         PrintError((*it)->getLoc(), "Invalid super class reference!");
802         continue;
803       }
804
805       ClassInfo *SC = AsmOperandClasses[DI->getDef()];
806       if (!SC)
807         PrintError((*it)->getLoc(), "Invalid super class reference!");
808       else
809         CI->SuperClasses.push_back(SC);
810     }
811     CI->ClassName = (*it)->getValueAsString("Name");
812     CI->Name = "MCK_" + CI->ClassName;
813     CI->ValueName = (*it)->getName();
814
815     // Get or construct the predicate method name.
816     Init *PMName = (*it)->getValueInit("PredicateMethod");
817     if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
818       CI->PredicateMethod = SI->getValue();
819     } else {
820       assert(dynamic_cast<UnsetInit*>(PMName) && 
821              "Unexpected PredicateMethod field!");
822       CI->PredicateMethod = "is" + CI->ClassName;
823     }
824
825     // Get or construct the render method name.
826     Init *RMName = (*it)->getValueInit("RenderMethod");
827     if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
828       CI->RenderMethod = SI->getValue();
829     } else {
830       assert(dynamic_cast<UnsetInit*>(RMName) &&
831              "Unexpected RenderMethod field!");
832       CI->RenderMethod = "add" + CI->ClassName + "Operands";
833     }
834
835     AsmOperandClasses[*it] = CI;
836     Classes.push_back(CI);
837   }
838 }
839
840 AsmMatcherInfo::AsmMatcherInfo(Record *_AsmParser) 
841   : AsmParser(_AsmParser),
842     CommentDelimiter(AsmParser->getValueAsString("CommentDelimiter")),
843     RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix"))
844 {
845 }
846
847 void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
848   // Parse the instructions; we need to do this first so that we can gather the
849   // singleton register classes.
850   std::set<std::string> SingletonRegisterNames;
851   
852   const std::vector<const CodeGenInstruction*> &InstrList =
853     Target.getInstructionsByEnumValue();
854   
855   for (unsigned i = 0, e = InstrList.size(); i != e; ++i) {
856     const CodeGenInstruction &CGI = *InstrList[i];
857
858     if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
859       continue;
860
861     OwningPtr<InstructionInfo> II(new InstructionInfo());
862     
863     II->InstrName = CGI.TheDef->getName();
864     II->Instr = &CGI;
865     II->AsmString = FlattenVariants(CGI.AsmString, 0);
866
867     // Remove comments from the asm string.
868     if (!CommentDelimiter.empty()) {
869       size_t Idx = StringRef(II->AsmString).find(CommentDelimiter);
870       if (Idx != StringRef::npos)
871         II->AsmString = II->AsmString.substr(0, Idx);
872     }
873
874     TokenizeAsmString(II->AsmString, II->Tokens);
875
876     // Ignore instructions which shouldn't be matched.
877     if (!IsAssemblerInstruction(CGI.TheDef->getName(), CGI, II->Tokens))
878       continue;
879
880     // Collect singleton registers, if used.
881     if (!RegisterPrefix.empty()) {
882       for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
883         if (II->Tokens[i].startswith(RegisterPrefix)) {
884           StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
885           Record *Rec = getRegisterRecord(Target, RegName);
886           
887           if (!Rec) {
888             std::string Err = "unable to find register for '" + RegName.str() + 
889               "' (which matches register prefix)";
890             throw TGError(CGI.TheDef->getLoc(), Err);
891           }
892
893           SingletonRegisterNames.insert(RegName);
894         }
895       }
896     }
897     
898     Instructions.push_back(II.take());
899   }
900
901   // Build info for the register classes.
902   BuildRegisterClasses(Target, SingletonRegisterNames);
903
904   // Build info for the user defined assembly operand classes.
905   BuildOperandClasses(Target);
906
907   // Build the instruction information.
908   for (std::vector<InstructionInfo*>::iterator it = Instructions.begin(),
909          ie = Instructions.end(); it != ie; ++it) {
910     InstructionInfo *II = *it;
911
912     for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
913       StringRef Token = II->Tokens[i];
914
915       // Check for singleton registers.
916       if (!RegisterPrefix.empty() && Token.startswith(RegisterPrefix)) {
917         StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
918         InstructionInfo::Operand Op;
919         Op.Class = RegisterClasses[getRegisterRecord(Target, RegName)];
920         Op.OperandInfo = 0;
921         assert(Op.Class && Op.Class->Registers.size() == 1 &&
922                "Unexpected class for singleton register");
923         II->Operands.push_back(Op);
924         continue;
925       }
926
927       // Check for simple tokens.
928       if (Token[0] != '$') {
929         InstructionInfo::Operand Op;
930         Op.Class = getTokenClass(Token);
931         Op.OperandInfo = 0;
932         II->Operands.push_back(Op);
933         continue;
934       }
935
936       // Otherwise this is an operand reference.
937       StringRef OperandName;
938       if (Token[1] == '{')
939         OperandName = Token.substr(2, Token.size() - 3);
940       else
941         OperandName = Token.substr(1);
942
943       // Map this token to an operand. FIXME: Move elsewhere.
944       unsigned Idx;
945       try {
946         Idx = II->Instr->getOperandNamed(OperandName);
947       } catch(...) {
948         throw std::string("error: unable to find operand: '" + 
949                           OperandName.str() + "'");
950       }
951
952       // FIXME: This is annoying, the named operand may be tied (e.g.,
953       // XCHG8rm). What we want is the untied operand, which we now have to
954       // grovel for. Only worry about this for single entry operands, we have to
955       // clean this up anyway.
956       const CodeGenInstruction::OperandInfo *OI = &II->Instr->OperandList[Idx];
957       if (OI->Constraints[0].isTied()) {
958         unsigned TiedOp = OI->Constraints[0].getTiedOperand();
959
960         // The tied operand index is an MIOperand index, find the operand that
961         // contains it.
962         for (unsigned i = 0, e = II->Instr->OperandList.size(); i != e; ++i) {
963           if (II->Instr->OperandList[i].MIOperandNo == TiedOp) {
964             OI = &II->Instr->OperandList[i];
965             break;
966           }
967         }
968
969         assert(OI && "Unable to find tied operand target!");
970       }
971
972       InstructionInfo::Operand Op;
973       Op.Class = getOperandClass(Token, *OI);
974       Op.OperandInfo = OI;
975       II->Operands.push_back(Op);
976     }
977   }
978
979   // Reorder classes so that classes preceed super classes.
980   std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
981 }
982
983 static std::pair<unsigned, unsigned> *
984 GetTiedOperandAtIndex(SmallVectorImpl<std::pair<unsigned, unsigned> > &List,
985                       unsigned Index) {
986   for (unsigned i = 0, e = List.size(); i != e; ++i)
987     if (Index == List[i].first)
988       return &List[i];
989
990   return 0;
991 }
992
993 static void EmitConvertToMCInst(CodeGenTarget &Target,
994                                 std::vector<InstructionInfo*> &Infos,
995                                 raw_ostream &OS) {
996   // Write the convert function to a separate stream, so we can drop it after
997   // the enum.
998   std::string ConvertFnBody;
999   raw_string_ostream CvtOS(ConvertFnBody);
1000
1001   // Function we have already generated.
1002   std::set<std::string> GeneratedFns;
1003
1004   // Start the unified conversion function.
1005
1006   CvtOS << "static void ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
1007         << "unsigned Opcode,\n"
1008         << "                      const SmallVectorImpl<MCParsedAsmOperand*"
1009         << "> &Operands) {\n";
1010   CvtOS << "  Inst.setOpcode(Opcode);\n";
1011   CvtOS << "  switch (Kind) {\n";
1012   CvtOS << "  default:\n";
1013
1014   // Start the enum, which we will generate inline.
1015
1016   OS << "// Unified function for converting operants to MCInst instances.\n\n";
1017   OS << "enum ConversionKind {\n";
1018   
1019   // TargetOperandClass - This is the target's operand class, like X86Operand.
1020   std::string TargetOperandClass = Target.getName() + "Operand";
1021   
1022   for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
1023          ie = Infos.end(); it != ie; ++it) {
1024     InstructionInfo &II = **it;
1025
1026     // Order the (class) operands by the order to convert them into an MCInst.
1027     SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
1028     for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1029       InstructionInfo::Operand &Op = II.Operands[i];
1030       if (Op.OperandInfo)
1031         MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
1032     }
1033
1034     // Find any tied operands.
1035     SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands;
1036     for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1037       const CodeGenInstruction::OperandInfo &OpInfo = II.Instr->OperandList[i];
1038       for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) {
1039         const CodeGenInstruction::ConstraintInfo &CI = OpInfo.Constraints[j];
1040         if (CI.isTied())
1041           TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo + j,
1042                                                 CI.getTiedOperand()));
1043       }
1044     }
1045
1046     std::sort(MIOperandList.begin(), MIOperandList.end());
1047
1048     // Compute the total number of operands.
1049     unsigned NumMIOperands = 0;
1050     for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1051       const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
1052       NumMIOperands = std::max(NumMIOperands, 
1053                                OI.MIOperandNo + OI.MINumOperands);
1054     }
1055
1056     // Build the conversion function signature.
1057     std::string Signature = "Convert";
1058     unsigned CurIndex = 0;
1059     for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1060       InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1061       assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
1062              "Duplicate match for instruction operand!");
1063       
1064       // Skip operands which weren't matched by anything, this occurs when the
1065       // .td file encodes "implicit" operands as explicit ones.
1066       //
1067       // FIXME: This should be removed from the MCInst structure.
1068       for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1069         std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1070                                                                    CurIndex);
1071         if (!Tie)
1072           Signature += "__Imp";
1073         else
1074           Signature += "__Tie" + utostr(Tie->second);
1075       }
1076
1077       Signature += "__";
1078
1079       // Registers are always converted the same, don't duplicate the conversion
1080       // function based on them.
1081       //
1082       // FIXME: We could generalize this based on the render method, if it
1083       // mattered.
1084       if (Op.Class->isRegisterClass())
1085         Signature += "Reg";
1086       else
1087         Signature += Op.Class->ClassName;
1088       Signature += utostr(Op.OperandInfo->MINumOperands);
1089       Signature += "_" + utostr(MIOperandList[i].second);
1090
1091       CurIndex += Op.OperandInfo->MINumOperands;
1092     }
1093
1094     // Add any trailing implicit operands.
1095     for (; CurIndex != NumMIOperands; ++CurIndex) {
1096       std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1097                                                                  CurIndex);
1098       if (!Tie)
1099         Signature += "__Imp";
1100       else
1101         Signature += "__Tie" + utostr(Tie->second);
1102     }
1103
1104     II.ConversionFnKind = Signature;
1105
1106     // Check if we have already generated this signature.
1107     if (!GeneratedFns.insert(Signature).second)
1108       continue;
1109
1110     // If not, emit it now.
1111
1112     // Add to the enum list.
1113     OS << "  " << Signature << ",\n";
1114
1115     // And to the convert function.
1116     CvtOS << "  case " << Signature << ":\n";
1117     CurIndex = 0;
1118     for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1119       InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1120
1121       // Add the implicit operands.
1122       for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1123         // See if this is a tied operand.
1124         std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1125                                                                    CurIndex);
1126
1127         if (!Tie) {
1128           // If not, this is some implicit operand. Just assume it is a register
1129           // for now.
1130           CvtOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
1131         } else {
1132           // Copy the tied operand.
1133           assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1134           CvtOS << "    Inst.addOperand(Inst.getOperand("
1135                 << Tie->second << "));\n";
1136         }
1137       }
1138
1139       CvtOS << "    ((" << TargetOperandClass << "*)Operands["
1140          << MIOperandList[i].second 
1141          << "])->" << Op.Class->RenderMethod 
1142          << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
1143       CurIndex += Op.OperandInfo->MINumOperands;
1144     }
1145     
1146     // And add trailing implicit operands.
1147     for (; CurIndex != NumMIOperands; ++CurIndex) {
1148       std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1149                                                                  CurIndex);
1150
1151       if (!Tie) {
1152         // If not, this is some implicit operand. Just assume it is a register
1153         // for now.
1154         CvtOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
1155       } else {
1156         // Copy the tied operand.
1157         assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1158         CvtOS << "    Inst.addOperand(Inst.getOperand("
1159               << Tie->second << "));\n";
1160       }
1161     }
1162
1163     CvtOS << "    return;\n";
1164   }
1165
1166   // Finish the convert function.
1167
1168   CvtOS << "  }\n";
1169   CvtOS << "}\n\n";
1170
1171   // Finish the enum, and drop the convert function after it.
1172
1173   OS << "  NumConversionVariants\n";
1174   OS << "};\n\n";
1175   
1176   OS << CvtOS.str();
1177 }
1178
1179 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1180 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1181                                       std::vector<ClassInfo*> &Infos,
1182                                       raw_ostream &OS) {
1183   OS << "namespace {\n\n";
1184
1185   OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1186      << "/// instruction matching.\n";
1187   OS << "enum MatchClassKind {\n";
1188   OS << "  InvalidMatchClass = 0,\n";
1189   for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
1190          ie = Infos.end(); it != ie; ++it) {
1191     ClassInfo &CI = **it;
1192     OS << "  " << CI.Name << ", // ";
1193     if (CI.Kind == ClassInfo::Token) {
1194       OS << "'" << CI.ValueName << "'\n";
1195     } else if (CI.isRegisterClass()) {
1196       if (!CI.ValueName.empty())
1197         OS << "register class '" << CI.ValueName << "'\n";
1198       else
1199         OS << "derived register class\n";
1200     } else {
1201       OS << "user defined class '" << CI.ValueName << "'\n";
1202     }
1203   }
1204   OS << "  NumMatchClassKinds\n";
1205   OS << "};\n\n";
1206
1207   OS << "}\n\n";
1208 }
1209
1210 /// EmitClassifyOperand - Emit the function to classify an operand.
1211 static void EmitClassifyOperand(CodeGenTarget &Target,
1212                                 AsmMatcherInfo &Info,
1213                                 raw_ostream &OS) {
1214   OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
1215      << "  " << Target.getName() << "Operand &Operand = *("
1216      << Target.getName() << "Operand*)GOp;\n";
1217
1218   // Classify tokens.
1219   OS << "  if (Operand.isToken())\n";
1220   OS << "    return MatchTokenString(Operand.getToken());\n\n";
1221
1222   // Classify registers.
1223   //
1224   // FIXME: Don't hardcode isReg, getReg.
1225   OS << "  if (Operand.isReg()) {\n";
1226   OS << "    switch (Operand.getReg()) {\n";
1227   OS << "    default: return InvalidMatchClass;\n";
1228   for (std::map<Record*, ClassInfo*>::iterator 
1229          it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1230        it != ie; ++it)
1231     OS << "    case " << Target.getName() << "::" 
1232        << it->first->getName() << ": return " << it->second->Name << ";\n";
1233   OS << "    }\n";
1234   OS << "  }\n\n";
1235
1236   // Classify user defined operands.
1237   for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(), 
1238          ie = Info.Classes.end(); it != ie; ++it) {
1239     ClassInfo &CI = **it;
1240
1241     if (!CI.isUserClass())
1242       continue;
1243
1244     OS << "  // '" << CI.ClassName << "' class";
1245     if (!CI.SuperClasses.empty()) {
1246       OS << ", subclass of ";
1247       for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1248         if (i) OS << ", ";
1249         OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1250         assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
1251       }
1252     }
1253     OS << "\n";
1254
1255     OS << "  if (Operand." << CI.PredicateMethod << "()) {\n";
1256       
1257     // Validate subclass relationships.
1258     if (!CI.SuperClasses.empty()) {
1259       for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1260         OS << "    assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1261            << "() && \"Invalid class relationship!\");\n";
1262     }
1263
1264     OS << "    return " << CI.Name << ";\n";
1265     OS << "  }\n\n";
1266   }
1267   OS << "  return InvalidMatchClass;\n";
1268   OS << "}\n\n";
1269 }
1270
1271 /// EmitIsSubclass - Emit the subclass predicate function.
1272 static void EmitIsSubclass(CodeGenTarget &Target,
1273                            std::vector<ClassInfo*> &Infos,
1274                            raw_ostream &OS) {
1275   OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1276   OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1277   OS << "  if (A == B)\n";
1278   OS << "    return true;\n\n";
1279
1280   OS << "  switch (A) {\n";
1281   OS << "  default:\n";
1282   OS << "    return false;\n";
1283   for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
1284          ie = Infos.end(); it != ie; ++it) {
1285     ClassInfo &A = **it;
1286
1287     if (A.Kind != ClassInfo::Token) {
1288       std::vector<StringRef> SuperClasses;
1289       for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
1290              ie = Infos.end(); it != ie; ++it) {
1291         ClassInfo &B = **it;
1292
1293         if (&A != &B && A.isSubsetOf(B))
1294           SuperClasses.push_back(B.Name);
1295       }
1296
1297       if (SuperClasses.empty())
1298         continue;
1299
1300       OS << "\n  case " << A.Name << ":\n";
1301
1302       if (SuperClasses.size() == 1) {
1303         OS << "    return B == " << SuperClasses.back() << ";\n";
1304         continue;
1305       }
1306
1307       OS << "    switch (B) {\n";
1308       OS << "    default: return false;\n";
1309       for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1310         OS << "    case " << SuperClasses[i] << ": return true;\n";
1311       OS << "    }\n";
1312     }
1313   }
1314   OS << "  }\n";
1315   OS << "}\n\n";
1316 }
1317
1318 typedef std::pair<std::string, std::string> StringPair;
1319
1320 /// FindFirstNonCommonLetter - Find the first character in the keys of the
1321 /// string pairs that is not shared across the whole set of strings.  All
1322 /// strings are assumed to have the same length.
1323 static unsigned 
1324 FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
1325   assert(!Matches.empty());
1326   for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
1327     // Check to see if letter i is the same across the set.
1328     char Letter = Matches[0]->first[i];
1329     
1330     for (unsigned str = 0, e = Matches.size(); str != e; ++str)
1331       if (Matches[str]->first[i] != Letter)
1332         return i;
1333   }
1334   
1335   return Matches[0]->first.size();
1336 }
1337
1338 /// EmitStringMatcherForChar - Given a set of strings that are known to be the
1339 /// same length and whose characters leading up to CharNo are the same, emit
1340 /// code to verify that CharNo and later are the same.
1341 ///
1342 /// \return - True if control can leave the emitted code fragment.
1343 static bool EmitStringMatcherForChar(const std::string &StrVariableName,
1344                                   const std::vector<const StringPair*> &Matches,
1345                                      unsigned CharNo, unsigned IndentCount,
1346                                      raw_ostream &OS) {
1347   assert(!Matches.empty() && "Must have at least one string to match!");
1348   std::string Indent(IndentCount*2+4, ' ');
1349
1350   // If we have verified that the entire string matches, we're done: output the
1351   // matching code.
1352   if (CharNo == Matches[0]->first.size()) {
1353     assert(Matches.size() == 1 && "Had duplicate keys to match on");
1354     
1355     // FIXME: If Matches[0].first has embeded \n, this will be bad.
1356     OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
1357        << "\"\n";
1358     return false;
1359   }
1360   
1361   // Bucket the matches by the character we are comparing.
1362   std::map<char, std::vector<const StringPair*> > MatchesByLetter;
1363   
1364   for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1365     MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
1366   
1367
1368   // If we have exactly one bucket to match, see how many characters are common
1369   // across the whole set and match all of them at once.
1370   if (MatchesByLetter.size() == 1) {
1371     unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
1372     unsigned NumChars = FirstNonCommonLetter-CharNo;
1373     
1374     // Emit code to break out if the prefix doesn't match.
1375     if (NumChars == 1) {
1376       // Do the comparison with if (Str[1] != 'f')
1377       // FIXME: Need to escape general characters.
1378       OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
1379          << Matches[0]->first[CharNo] << "')\n";
1380       OS << Indent << "  break;\n";
1381     } else {
1382       // Do the comparison with if (Str.substr(1,3) != "foo").    
1383       // FIXME: Need to escape general strings.
1384       OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
1385          << NumChars << ") != \"";
1386       OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
1387       OS << Indent << "  break;\n";
1388     }
1389     
1390     return EmitStringMatcherForChar(StrVariableName, Matches, 
1391                                     FirstNonCommonLetter, IndentCount, OS);
1392   }
1393   
1394   // Otherwise, we have multiple possible things, emit a switch on the
1395   // character.
1396   OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
1397   OS << Indent << "default: break;\n";
1398   
1399   for (std::map<char, std::vector<const StringPair*> >::iterator LI = 
1400        MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
1401     // TODO: escape hard stuff (like \n) if we ever care about it.
1402     OS << Indent << "case '" << LI->first << "':\t // "
1403        << LI->second.size() << " strings to match.\n";
1404     if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
1405                                  IndentCount+1, OS))
1406       OS << Indent << "  break;\n";
1407   }
1408   
1409   OS << Indent << "}\n";
1410   return true;
1411 }
1412
1413
1414 /// EmitStringMatcher - Given a list of strings and code to execute when they
1415 /// match, output a simple switch tree to classify the input string.
1416 /// 
1417 /// If a match is found, the code in Vals[i].second is executed; control must
1418 /// not exit this code fragment.  If nothing matches, execution falls through.
1419 ///
1420 /// \param StrVariableName - The name of the variable to test.
1421 static void EmitStringMatcher(const std::string &StrVariableName,
1422                               const std::vector<StringPair> &Matches,
1423                               raw_ostream &OS) {
1424   // First level categorization: group strings by length.
1425   std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
1426   
1427   for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1428     MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
1429   
1430   // Output a switch statement on length and categorize the elements within each
1431   // bin.
1432   OS << "  switch (" << StrVariableName << ".size()) {\n";
1433   OS << "  default: break;\n";
1434   
1435   for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
1436        MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
1437     OS << "  case " << LI->first << ":\t // " << LI->second.size()
1438        << " strings to match.\n";
1439     if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
1440       OS << "    break;\n";
1441   }
1442   
1443   OS << "  }\n";
1444 }
1445
1446
1447 /// EmitMatchTokenString - Emit the function to match a token string to the
1448 /// appropriate match class value.
1449 static void EmitMatchTokenString(CodeGenTarget &Target,
1450                                  std::vector<ClassInfo*> &Infos,
1451                                  raw_ostream &OS) {
1452   // Construct the match list.
1453   std::vector<StringPair> Matches;
1454   for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
1455          ie = Infos.end(); it != ie; ++it) {
1456     ClassInfo &CI = **it;
1457
1458     if (CI.Kind == ClassInfo::Token)
1459       Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
1460   }
1461
1462   OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
1463
1464   EmitStringMatcher("Name", Matches, OS);
1465
1466   OS << "  return InvalidMatchClass;\n";
1467   OS << "}\n\n";
1468 }
1469
1470 /// EmitMatchRegisterName - Emit the function to match a string to the target
1471 /// specific register enum.
1472 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1473                                   raw_ostream &OS) {
1474   // Construct the match list.
1475   std::vector<StringPair> Matches;
1476   for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1477     const CodeGenRegister &Reg = Target.getRegisters()[i];
1478     if (Reg.TheDef->getValueAsString("AsmName").empty())
1479       continue;
1480
1481     Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
1482                                  "return " + utostr(i + 1) + ";"));
1483   }
1484   
1485   OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
1486
1487   EmitStringMatcher("Name", Matches, OS);
1488   
1489   OS << "  return 0;\n";
1490   OS << "}\n\n";
1491 }
1492
1493 void AsmMatcherEmitter::run(raw_ostream &OS) {
1494   CodeGenTarget Target;
1495   Record *AsmParser = Target.getAsmParser();
1496   std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1497
1498   // Compute the information on the instructions to match.
1499   AsmMatcherInfo Info(AsmParser);
1500   Info.BuildInfo(Target);
1501
1502   // Sort the instruction table using the partial order on classes. We use
1503   // stable_sort to ensure that ambiguous instructions are still
1504   // deterministically ordered.
1505   std::stable_sort(Info.Instructions.begin(), Info.Instructions.end(),
1506                    less_ptr<InstructionInfo>());
1507   
1508   DEBUG_WITH_TYPE("instruction_info", {
1509       for (std::vector<InstructionInfo*>::iterator 
1510              it = Info.Instructions.begin(), ie = Info.Instructions.end(); 
1511            it != ie; ++it)
1512         (*it)->dump();
1513     });
1514
1515   // Check for ambiguous instructions.
1516   unsigned NumAmbiguous = 0;
1517   for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1518     for (unsigned j = i + 1; j != e; ++j) {
1519       InstructionInfo &A = *Info.Instructions[i];
1520       InstructionInfo &B = *Info.Instructions[j];
1521     
1522       if (A.CouldMatchAmiguouslyWith(B)) {
1523         DEBUG_WITH_TYPE("ambiguous_instrs", {
1524             errs() << "warning: ambiguous instruction match:\n";
1525             A.dump();
1526             errs() << "\nis incomparable with:\n";
1527             B.dump();
1528             errs() << "\n\n";
1529           });
1530         ++NumAmbiguous;
1531       }
1532     }
1533   }
1534   if (NumAmbiguous)
1535     DEBUG_WITH_TYPE("ambiguous_instrs", {
1536         errs() << "warning: " << NumAmbiguous 
1537                << " ambiguous instructions!\n";
1538       });
1539
1540   // Write the output.
1541
1542   EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1543
1544   // Emit the function to match a register name to number.
1545   EmitMatchRegisterName(Target, AsmParser, OS);
1546   
1547   OS << "#ifndef REGISTERS_ONLY\n\n";
1548
1549   // Generate the unified function to convert operands into an MCInst.
1550   EmitConvertToMCInst(Target, Info.Instructions, OS);
1551
1552   // Emit the enumeration for classes which participate in matching.
1553   EmitMatchClassEnumeration(Target, Info.Classes, OS);
1554
1555   // Emit the routine to match token strings to their match class.
1556   EmitMatchTokenString(Target, Info.Classes, OS);
1557
1558   // Emit the routine to classify an operand.
1559   EmitClassifyOperand(Target, Info, OS);
1560
1561   // Emit the subclass predicate routine.
1562   EmitIsSubclass(Target, Info.Classes, OS);
1563
1564   // Finally, build the match function.
1565
1566   size_t MaxNumOperands = 0;
1567   for (std::vector<InstructionInfo*>::const_iterator it =
1568          Info.Instructions.begin(), ie = Info.Instructions.end();
1569        it != ie; ++it)
1570     MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1571
1572   const std::string &MatchName =
1573     AsmParser->getValueAsString("MatchInstructionName");
1574   OS << "bool " << Target.getName() << ClassName << "::\n"
1575      << MatchName
1576      << "(const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
1577   OS.indent(MatchName.size() + 1);
1578   OS << "MCInst &Inst) {\n";
1579
1580   // Emit the static match table; unused classes get initalized to 0 which is
1581   // guaranteed to be InvalidMatchClass.
1582   //
1583   // FIXME: We can reduce the size of this table very easily. First, we change
1584   // it so that store the kinds in separate bit-fields for each index, which
1585   // only needs to be the max width used for classes at that index (we also need
1586   // to reject based on this during classification). If we then make sure to
1587   // order the match kinds appropriately (putting mnemonics last), then we
1588   // should only end up using a few bits for each class, especially the ones
1589   // following the mnemonic.
1590   OS << "  static const struct MatchEntry {\n";
1591   OS << "    unsigned Opcode;\n";
1592   OS << "    ConversionKind ConvertFn;\n";
1593   OS << "    MatchClassKind Classes[" << MaxNumOperands << "];\n";
1594   OS << "  } MatchTable[" << Info.Instructions.size() << "] = {\n";
1595
1596   for (std::vector<InstructionInfo*>::const_iterator it =
1597          Info.Instructions.begin(), ie = Info.Instructions.end();
1598        it != ie; ++it) {
1599     InstructionInfo &II = **it;
1600
1601     OS << "    { " << Target.getName() << "::" << II.InstrName
1602        << ", " << II.ConversionFnKind << ", { ";
1603     for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1604       InstructionInfo::Operand &Op = II.Operands[i];
1605       
1606       if (i) OS << ", ";
1607       OS << Op.Class->Name;
1608     }
1609     OS << " } },\n";
1610   }
1611
1612   OS << "  };\n\n";
1613
1614   // Emit code to compute the class list for this operand vector.
1615   OS << "  // Eliminate obvious mismatches.\n";
1616   OS << "  if (Operands.size() > " << MaxNumOperands << ")\n";
1617   OS << "    return true;\n\n";
1618
1619   OS << "  // Compute the class list for this operand vector.\n";
1620   OS << "  MatchClassKind Classes[" << MaxNumOperands << "];\n";
1621   OS << "  for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1622   OS << "    Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1623
1624   OS << "    // Check for invalid operands before matching.\n";
1625   OS << "    if (Classes[i] == InvalidMatchClass)\n";
1626   OS << "      return true;\n";
1627   OS << "  }\n\n";
1628
1629   OS << "  // Mark unused classes.\n";
1630   OS << "  for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1631      << "i != e; ++i)\n";
1632   OS << "    Classes[i] = InvalidMatchClass;\n\n";
1633
1634   // Emit code to search the table.
1635   OS << "  // Search the table.\n";
1636   OS << "  for (const MatchEntry *it = MatchTable, "
1637      << "*ie = MatchTable + " << Info.Instructions.size()
1638      << "; it != ie; ++it) {\n";
1639   for (unsigned i = 0; i != MaxNumOperands; ++i) {
1640     OS << "    if (!IsSubclass(Classes[" 
1641        << i << "], it->Classes[" << i << "]))\n";
1642     OS << "      continue;\n";
1643   }
1644   OS << "\n";
1645   OS << "    ConvertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
1646
1647   // Call the post-processing function, if used.
1648   std::string InsnCleanupFn =
1649     AsmParser->getValueAsString("AsmParserInstCleanup");
1650   if (!InsnCleanupFn.empty())
1651     OS << "    " << InsnCleanupFn << "(Inst);\n";
1652
1653   OS << "    return false;\n";
1654   OS << "  }\n\n";
1655
1656   OS << "  return true;\n";
1657   OS << "}\n\n";
1658   
1659   OS << "#endif // REGISTERS_ONLY\n";
1660 }