llvm-mc/AsmParser: Allow .td users to redefine the names of the methods to call
[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(const 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(const StringRef &Name,
211                                    const CodeGenInstruction &CGI, 
212                                    const SmallVectorImpl<StringRef> &Tokens) {
213   // Ignore psuedo ops.
214   //
215   // FIXME: This is a hack.
216   if (const RecordVal *Form = CGI.TheDef->getValue("Form"))
217     if (Form->getValue()->getAsString() == "Pseudo")
218       return false;
219   
220   // Ignore "PHI" node.
221   //
222   // FIXME: This is also a hack.
223   if (Name == "PHI")
224     return false;
225
226   // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
227   //
228   // FIXME: This is a total hack.
229   if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
230     return false;
231
232   // Ignore instructions with no .s string.
233   //
234   // FIXME: What are these?
235   if (CGI.AsmString.empty())
236     return false;
237
238   // FIXME: Hack; ignore any instructions with a newline in them.
239   if (std::find(CGI.AsmString.begin(), 
240                 CGI.AsmString.end(), '\n') != CGI.AsmString.end())
241     return false;
242   
243   // Ignore instructions with attributes, these are always fake instructions for
244   // simplifying codegen.
245   //
246   // FIXME: Is this true?
247   //
248   // Also, we ignore instructions which reference the operand multiple times;
249   // this implies a constraint we would not currently honor. These are
250   // currently always fake instructions for simplifying codegen.
251   //
252   // FIXME: Encode this assumption in the .td, so we can error out here.
253   std::set<std::string> OperandNames;
254   for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
255     if (Tokens[i][0] == '$' && 
256         std::find(Tokens[i].begin(), 
257                   Tokens[i].end(), ':') != Tokens[i].end()) {
258       DEBUG({
259           errs() << "warning: '" << Name << "': "
260                  << "ignoring instruction; operand with attribute '" 
261                  << Tokens[i] << "', \n";
262         });
263       return false;
264     }
265
266     if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
267       DEBUG({
268           errs() << "warning: '" << Name << "': "
269                  << "ignoring instruction; tied operand '" 
270                  << Tokens[i] << "'\n";
271         });
272       return false;
273     }
274   }
275
276   return true;
277 }
278
279 namespace {
280
281 /// ClassInfo - Helper class for storing the information about a particular
282 /// class of operands which can be matched.
283 struct ClassInfo {
284   enum ClassInfoKind {
285     Invalid = 0, ///< Invalid kind, for use as a sentinel value.
286     Token,       ///< The class for a particular token.
287     Register,    ///< A register class.
288     UserClass0   ///< The (first) user defined class, subsequent user defined
289                  /// classes are UserClass0+1, and so on.
290   };
291
292   /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
293   /// N) for the Nth user defined class.
294   unsigned Kind;
295
296   /// SuperClass - The super class, or 0.
297   ClassInfo *SuperClass;
298
299   /// Name - The full class name, suitable for use in an enum.
300   std::string Name;
301
302   /// ClassName - The unadorned generic name for this class (e.g., Token).
303   std::string ClassName;
304
305   /// ValueName - The name of the value this class represents; for a token this
306   /// is the literal token string, for an operand it is the TableGen class (or
307   /// empty if this is a derived class).
308   std::string ValueName;
309
310   /// PredicateMethod - The name of the operand method to test whether the
311   /// operand matches this class; this is not valid for Token kinds.
312   std::string PredicateMethod;
313
314   /// RenderMethod - The name of the operand method to add this operand to an
315   /// MCInst; this is not valid for Token kinds.
316   std::string RenderMethod;
317
318   /// isUserClass() - Check if this is a user defined class.
319   bool isUserClass() const {
320     return Kind >= UserClass0;
321   }
322
323   /// getRootClass - Return the root class of this one.
324   const ClassInfo *getRootClass() const {
325     const ClassInfo *CI = this;
326     while (CI->SuperClass)
327       CI = CI->SuperClass;
328     return CI;
329   }
330
331   /// operator< - Compare two classes.
332   bool operator<(const ClassInfo &RHS) const {
333     // Incompatible kinds are comparable for classes in disjoint hierarchies.
334     if (Kind != RHS.Kind && getRootClass() != RHS.getRootClass())
335       return Kind < RHS.Kind;
336
337     switch (Kind) {
338     case Invalid:
339       assert(0 && "Invalid kind!");
340     case Token:
341       // Tokens are comparable by value.
342       //
343       // FIXME: Compare by enum value.
344       return ValueName < RHS.ValueName;
345
346     default:
347       // This class preceeds the RHS if the RHS is a super class.
348       for (ClassInfo *Parent = SuperClass; Parent; Parent = Parent->SuperClass)
349         if (Parent == &RHS)
350           return true;
351
352       return false;
353     }
354   }
355 };
356
357 /// InstructionInfo - Helper class for storing the necessary information for an
358 /// instruction which is capable of being matched.
359 struct InstructionInfo {
360   struct Operand {
361     /// The unique class instance this operand should match.
362     ClassInfo *Class;
363
364     /// The original operand this corresponds to, if any.
365     const CodeGenInstruction::OperandInfo *OperandInfo;
366   };
367
368   /// InstrName - The target name for this instruction.
369   std::string InstrName;
370
371   /// Instr - The instruction this matches.
372   const CodeGenInstruction *Instr;
373
374   /// AsmString - The assembly string for this instruction (with variants
375   /// removed).
376   std::string AsmString;
377
378   /// Tokens - The tokenized assembly pattern that this instruction matches.
379   SmallVector<StringRef, 4> Tokens;
380
381   /// Operands - The operands that this instruction matches.
382   SmallVector<Operand, 4> Operands;
383
384   /// ConversionFnKind - The enum value which is passed to the generated
385   /// ConvertToMCInst to convert parsed operands into an MCInst for this
386   /// function.
387   std::string ConversionFnKind;
388
389   /// operator< - Compare two instructions.
390   bool operator<(const InstructionInfo &RHS) const {
391     if (Operands.size() != RHS.Operands.size())
392       return Operands.size() < RHS.Operands.size();
393
394     // Compare lexicographically by operand. The matcher validates that other
395     // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
396     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
397       if (*Operands[i].Class < *RHS.Operands[i].Class)
398         return true;
399       if (*RHS.Operands[i].Class < *Operands[i].Class)
400         return false;
401     }
402
403     return false;
404   }
405
406   /// CouldMatchAmiguouslyWith - Check whether this instruction could
407   /// ambiguously match the same set of operands as \arg RHS (without being a
408   /// strictly superior match).
409   bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
410     // The number of operands is unambiguous.
411     if (Operands.size() != RHS.Operands.size())
412       return false;
413
414     // Tokens and operand kinds are unambiguous (assuming a correct target
415     // specific parser).
416     for (unsigned i = 0, e = Operands.size(); i != e; ++i)
417       if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
418           Operands[i].Class->Kind == ClassInfo::Token)
419         if (*Operands[i].Class < *RHS.Operands[i].Class ||
420             *RHS.Operands[i].Class < *Operands[i].Class)
421           return false;
422     
423     // Otherwise, this operand could commute if all operands are equivalent, or
424     // there is a pair of operands that compare less than and a pair that
425     // compare greater than.
426     bool HasLT = false, HasGT = false;
427     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
428       if (*Operands[i].Class < *RHS.Operands[i].Class)
429         HasLT = true;
430       if (*RHS.Operands[i].Class < *Operands[i].Class)
431         HasGT = true;
432     }
433
434     return !(HasLT ^ HasGT);
435   }
436
437 public:
438   void dump();
439 };
440
441 class AsmMatcherInfo {
442 public:
443   /// The classes which are needed for matching.
444   std::vector<ClassInfo*> Classes;
445   
446   /// The information on the instruction to match.
447   std::vector<InstructionInfo*> Instructions;
448
449 private:
450   /// Map of token to class information which has already been constructed.
451   std::map<std::string, ClassInfo*> TokenClasses;
452
453   /// The ClassInfo instance for registers.
454   ClassInfo *TheRegisterClass;
455
456   /// Map of AsmOperandClass records to their class information.
457   std::map<Record*, ClassInfo*> AsmOperandClasses;
458
459 private:
460   /// getTokenClass - Lookup or create the class for the given token.
461   ClassInfo *getTokenClass(const StringRef &Token);
462
463   /// getOperandClass - Lookup or create the class for the given operand.
464   ClassInfo *getOperandClass(const StringRef &Token,
465                              const CodeGenInstruction::OperandInfo &OI);
466
467 public:
468   /// BuildInfo - Construct the various tables used during matching.
469   void BuildInfo(CodeGenTarget &Target);
470 };
471
472 }
473
474 void InstructionInfo::dump() {
475   errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
476          << ", tokens:[";
477   for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
478     errs() << Tokens[i];
479     if (i + 1 != e)
480       errs() << ", ";
481   }
482   errs() << "]\n";
483
484   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
485     Operand &Op = Operands[i];
486     errs() << "  op[" << i << "] = " << Op.Class->ClassName << " - ";
487     if (Op.Class->Kind == ClassInfo::Token) {
488       errs() << '\"' << Tokens[i] << "\"\n";
489       continue;
490     }
491
492     const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
493     errs() << OI.Name << " " << OI.Rec->getName()
494            << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
495   }
496 }
497
498 static std::string getEnumNameForToken(const StringRef &Str) {
499   std::string Res;
500   
501   for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
502     switch (*it) {
503     case '*': Res += "_STAR_"; break;
504     case '%': Res += "_PCT_"; break;
505     case ':': Res += "_COLON_"; break;
506
507     default:
508       if (isalnum(*it))  {
509         Res += *it;
510       } else {
511         Res += "_" + utostr((unsigned) *it) + "_";
512       }
513     }
514   }
515
516   return Res;
517 }
518
519 ClassInfo *AsmMatcherInfo::getTokenClass(const StringRef &Token) {
520   ClassInfo *&Entry = TokenClasses[Token];
521   
522   if (!Entry) {
523     Entry = new ClassInfo();
524     Entry->Kind = ClassInfo::Token;
525     Entry->SuperClass = 0;
526     Entry->ClassName = "Token";
527     Entry->Name = "MCK_" + getEnumNameForToken(Token);
528     Entry->ValueName = Token;
529     Entry->PredicateMethod = "<invalid>";
530     Entry->RenderMethod = "<invalid>";
531     Classes.push_back(Entry);
532   }
533
534   return Entry;
535 }
536
537 ClassInfo *
538 AsmMatcherInfo::getOperandClass(const StringRef &Token,
539                                 const CodeGenInstruction::OperandInfo &OI) {
540   if (OI.Rec->isSubClassOf("RegisterClass"))
541     return TheRegisterClass;
542
543   assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
544   Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
545   ClassInfo *CI = AsmOperandClasses[MatchClass];
546
547   if (!CI) {
548     PrintError(OI.Rec->getLoc(), "operand has no match class!");
549     throw std::string("ERROR: Missing match class!");
550   }
551
552   return CI;
553 }
554
555 void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
556   // Build the assembly match class information.
557
558   // Construct the "Reg" class.
559   //
560   // FIXME: This needs to dice up the RegisterClass instances.
561   ClassInfo *RegClass = TheRegisterClass = new ClassInfo();
562   RegClass->Kind = ClassInfo::Register;
563   RegClass->SuperClass = 0;
564   RegClass->ClassName = "Reg";
565   RegClass->Name = "MCK_Reg";
566   RegClass->ValueName = "<register class>";
567   RegClass->PredicateMethod = "isReg";
568   RegClass->RenderMethod = "addRegOperands";
569   Classes.push_back(RegClass);
570
571   // Build info for the user defined assembly operand classes.
572   std::vector<Record*> AsmOperands;
573   AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
574   unsigned Index = 0;
575   for (std::vector<Record*>::iterator it = AsmOperands.begin(), 
576          ie = AsmOperands.end(); it != ie; ++it, ++Index) {
577     ClassInfo *CI = new ClassInfo();
578     CI->Kind = ClassInfo::UserClass0 + Index;
579
580     Init *Super = (*it)->getValueInit("SuperClass");
581     if (DefInit *DI = dynamic_cast<DefInit*>(Super)) {
582       CI->SuperClass = AsmOperandClasses[DI->getDef()];
583       if (!CI->SuperClass)
584         PrintError((*it)->getLoc(), "Invalid super class reference!");
585     } else {
586       assert(dynamic_cast<UnsetInit*>(Super) && "Unexpected SuperClass field!");
587       CI->SuperClass = 0;
588     }
589     CI->ClassName = (*it)->getValueAsString("Name");
590     CI->Name = "MCK_" + CI->ClassName;
591     CI->ValueName = (*it)->getName();
592
593     // Get or construct the predicate method name.
594     Init *PMName = (*it)->getValueInit("PredicateMethod");
595     if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
596       CI->PredicateMethod = SI->getValue();
597     } else {
598       assert(dynamic_cast<UnsetInit*>(PMName) && 
599              "Unexpected PredicateMethod field!");
600       CI->PredicateMethod = "is" + CI->ClassName;
601     }
602
603     // Get or construct the render method name.
604     Init *RMName = (*it)->getValueInit("RenderMethod");
605     if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
606       CI->RenderMethod = SI->getValue();
607     } else {
608       assert(dynamic_cast<UnsetInit*>(RMName) &&
609              "Unexpected RenderMethod field!");
610       CI->RenderMethod = "add" + CI->ClassName + "Operands";
611     }
612
613     AsmOperandClasses[*it] = CI;
614     Classes.push_back(CI);
615   }
616
617   // Build the instruction information.
618   for (std::map<std::string, CodeGenInstruction>::const_iterator 
619          it = Target.getInstructions().begin(), 
620          ie = Target.getInstructions().end(); 
621        it != ie; ++it) {
622     const CodeGenInstruction &CGI = it->second;
623
624     if (!StringRef(it->first).startswith(MatchPrefix))
625       continue;
626
627     OwningPtr<InstructionInfo> II(new InstructionInfo);
628     
629     II->InstrName = it->first;
630     II->Instr = &it->second;
631     II->AsmString = FlattenVariants(CGI.AsmString, 0);
632
633     TokenizeAsmString(II->AsmString, II->Tokens);
634
635     // Ignore instructions which shouldn't be matched.
636     if (!IsAssemblerInstruction(it->first, CGI, II->Tokens))
637       continue;
638
639     for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
640       StringRef Token = II->Tokens[i];
641
642       // Check for simple tokens.
643       if (Token[0] != '$') {
644         InstructionInfo::Operand Op;
645         Op.Class = getTokenClass(Token);
646         Op.OperandInfo = 0;
647         II->Operands.push_back(Op);
648         continue;
649       }
650
651       // Otherwise this is an operand reference.
652       StringRef OperandName;
653       if (Token[1] == '{')
654         OperandName = Token.substr(2, Token.size() - 3);
655       else
656         OperandName = Token.substr(1);
657
658       // Map this token to an operand. FIXME: Move elsewhere.
659       unsigned Idx;
660       try {
661         Idx = CGI.getOperandNamed(OperandName);
662       } catch(...) {
663         errs() << "error: unable to find operand: '" << OperandName << "'!\n";
664         break;
665       }
666
667       const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx];      
668       InstructionInfo::Operand Op;
669       Op.Class = getOperandClass(Token, OI);
670       Op.OperandInfo = &OI;
671       II->Operands.push_back(Op);
672     }
673
674     // If we broke out, ignore the instruction.
675     if (II->Operands.size() != II->Tokens.size())
676       continue;
677
678     Instructions.push_back(II.take());
679   }
680
681   // Reorder classes so that classes preceed super classes.
682   std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
683 }
684
685 static void EmitConvertToMCInst(CodeGenTarget &Target,
686                                 std::vector<InstructionInfo*> &Infos,
687                                 raw_ostream &OS) {
688   // Write the convert function to a separate stream, so we can drop it after
689   // the enum.
690   std::string ConvertFnBody;
691   raw_string_ostream CvtOS(ConvertFnBody);
692
693   // Function we have already generated.
694   std::set<std::string> GeneratedFns;
695
696   // Start the unified conversion function.
697
698   CvtOS << "static bool ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
699         << "unsigned Opcode,\n"
700         << "                            SmallVectorImpl<"
701         << Target.getName() << "Operand> &Operands) {\n";
702   CvtOS << "  Inst.setOpcode(Opcode);\n";
703   CvtOS << "  switch (Kind) {\n";
704   CvtOS << "  default:\n";
705
706   // Start the enum, which we will generate inline.
707
708   OS << "// Unified function for converting operants to MCInst instances.\n\n";
709   OS << "enum ConversionKind {\n";
710   
711   for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
712          ie = Infos.end(); it != ie; ++it) {
713     InstructionInfo &II = **it;
714
715     // Order the (class) operands by the order to convert them into an MCInst.
716     SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
717     for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
718       InstructionInfo::Operand &Op = II.Operands[i];
719       if (Op.OperandInfo)
720         MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
721     }
722     std::sort(MIOperandList.begin(), MIOperandList.end());
723
724     // Compute the total number of operands.
725     unsigned NumMIOperands = 0;
726     for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
727       const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
728       NumMIOperands = std::max(NumMIOperands, 
729                                OI.MIOperandNo + OI.MINumOperands);
730     }
731
732     // Build the conversion function signature.
733     std::string Signature = "Convert";
734     unsigned CurIndex = 0;
735     for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
736       InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
737       assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
738              "Duplicate match for instruction operand!");
739       
740       Signature += "_";
741
742       // Skip operands which weren't matched by anything, this occurs when the
743       // .td file encodes "implicit" operands as explicit ones.
744       //
745       // FIXME: This should be removed from the MCInst structure.
746       for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
747         Signature += "Imp";
748
749       Signature += Op.Class->ClassName;
750       Signature += utostr(Op.OperandInfo->MINumOperands);
751       Signature += "_" + utostr(MIOperandList[i].second);
752
753       CurIndex += Op.OperandInfo->MINumOperands;
754     }
755
756     // Add any trailing implicit operands.
757     for (; CurIndex != NumMIOperands; ++CurIndex)
758       Signature += "Imp";
759
760     II.ConversionFnKind = Signature;
761
762     // Check if we have already generated this signature.
763     if (!GeneratedFns.insert(Signature).second)
764       continue;
765
766     // If not, emit it now.
767
768     // Add to the enum list.
769     OS << "  " << Signature << ",\n";
770
771     // And to the convert function.
772     CvtOS << "  case " << Signature << ":\n";
773     CurIndex = 0;
774     for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
775       InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
776
777       // Add the implicit operands.
778       for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
779         CvtOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
780
781       CvtOS << "    Operands[" << MIOperandList[i].second 
782          << "]." << Op.Class->RenderMethod 
783          << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
784       CurIndex += Op.OperandInfo->MINumOperands;
785     }
786     
787     // And add trailing implicit operands.
788     for (; CurIndex != NumMIOperands; ++CurIndex)
789       CvtOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
790     CvtOS << "    break;\n";
791   }
792
793   // Finish the convert function.
794
795   CvtOS << "  }\n";
796   CvtOS << "  return false;\n";
797   CvtOS << "}\n\n";
798
799   // Finish the enum, and drop the convert function after it.
800
801   OS << "  NumConversionVariants\n";
802   OS << "};\n\n";
803   
804   OS << CvtOS.str();
805 }
806
807 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
808 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
809                                       std::vector<ClassInfo*> &Infos,
810                                       raw_ostream &OS) {
811   OS << "namespace {\n\n";
812
813   OS << "/// MatchClassKind - The kinds of classes which participate in\n"
814      << "/// instruction matching.\n";
815   OS << "enum MatchClassKind {\n";
816   OS << "  InvalidMatchClass = 0,\n";
817   for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
818          ie = Infos.end(); it != ie; ++it) {
819     ClassInfo &CI = **it;
820     OS << "  " << CI.Name << ", // ";
821     if (CI.Kind == ClassInfo::Token) {
822       OS << "'" << CI.ValueName << "'\n";
823     } else if (CI.Kind == ClassInfo::Register) {
824       if (!CI.ValueName.empty())
825         OS << "register class '" << CI.ValueName << "'\n";
826       else
827         OS << "derived register class\n";
828     } else {
829       OS << "user defined class '" << CI.ValueName << "'\n";
830     }
831   }
832   OS << "  NumMatchClassKinds\n";
833   OS << "};\n\n";
834
835   OS << "}\n\n";
836 }
837
838 /// EmitClassifyOperand - Emit the function to classify an operand.
839 static void EmitClassifyOperand(CodeGenTarget &Target,
840                                 std::vector<ClassInfo*> &Infos,
841                                 raw_ostream &OS) {
842   OS << "static MatchClassKind ClassifyOperand("
843      << Target.getName() << "Operand &Operand) {\n";
844   OS << "  if (Operand.isToken())\n";
845   OS << "    return MatchTokenString(Operand.getToken());\n\n";
846   for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
847          ie = Infos.end(); it != ie; ++it) {
848     ClassInfo &CI = **it;
849
850     if (CI.Kind != ClassInfo::Token) {
851       OS << "  // '" << CI.ClassName << "' class";
852       if (CI.SuperClass) {
853         OS << ", subclass of '" << CI.SuperClass->ClassName << "'";
854         assert(CI < *CI.SuperClass && "Invalid class relation!");
855       }
856       OS << "\n";
857
858       OS << "  if (Operand." << CI.PredicateMethod << "()) {\n";
859       
860       // Validate subclass relationships.
861       if (CI.SuperClass)
862         OS << "    assert(Operand." << CI.SuperClass->PredicateMethod
863            << "() && \"Invalid class relationship!\");\n";
864
865       OS << "    return " << CI.Name << ";\n";
866       OS << "  }\n\n";
867     }
868   }
869   OS << "  return InvalidMatchClass;\n";
870   OS << "}\n\n";
871 }
872
873 /// EmitIsSubclass - Emit the subclass predicate function.
874 static void EmitIsSubclass(CodeGenTarget &Target,
875                            std::vector<ClassInfo*> &Infos,
876                            raw_ostream &OS) {
877   OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
878   OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
879   OS << "  if (A == B)\n";
880   OS << "    return true;\n\n";
881
882   OS << "  switch (A) {\n";
883   OS << "  default:\n";
884   OS << "    return false;\n";
885   for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
886          ie = Infos.end(); it != ie; ++it) {
887     ClassInfo &A = **it;
888
889     if (A.Kind != ClassInfo::Token) {
890       std::vector<StringRef> SuperClasses;
891       for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
892              ie = Infos.end(); it != ie; ++it) {
893         ClassInfo &B = **it;
894
895         if (&A != &B && A.getRootClass() == B.getRootClass() && A < B)
896           SuperClasses.push_back(B.Name);
897       }
898
899       if (SuperClasses.empty())
900         continue;
901
902       OS << "\n  case " << A.Name << ":\n";
903
904       if (SuperClasses.size() == 1) {
905         OS << "    return B == " << SuperClasses.back() << ";\n\n";
906         continue;
907       }
908
909       OS << "      switch (B) {\n";
910       OS << "      default: return false;\n";
911       for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
912         OS << "      case " << SuperClasses[i] << ": return true;\n";
913       OS << "      }\n\n";
914     }
915   }
916   OS << "  }\n";
917   OS << "}\n\n";
918 }
919
920 typedef std::pair<std::string, std::string> StringPair;
921
922 /// FindFirstNonCommonLetter - Find the first character in the keys of the
923 /// string pairs that is not shared across the whole set of strings.  All
924 /// strings are assumed to have the same length.
925 static unsigned 
926 FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
927   assert(!Matches.empty());
928   for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
929     // Check to see if letter i is the same across the set.
930     char Letter = Matches[0]->first[i];
931     
932     for (unsigned str = 0, e = Matches.size(); str != e; ++str)
933       if (Matches[str]->first[i] != Letter)
934         return i;
935   }
936   
937   return Matches[0]->first.size();
938 }
939
940 /// EmitStringMatcherForChar - Given a set of strings that are known to be the
941 /// same length and whose characters leading up to CharNo are the same, emit
942 /// code to verify that CharNo and later are the same.
943 ///
944 /// \return - True if control can leave the emitted code fragment.
945 static bool EmitStringMatcherForChar(const std::string &StrVariableName,
946                                   const std::vector<const StringPair*> &Matches,
947                                      unsigned CharNo, unsigned IndentCount,
948                                      raw_ostream &OS) {
949   assert(!Matches.empty() && "Must have at least one string to match!");
950   std::string Indent(IndentCount*2+4, ' ');
951
952   // If we have verified that the entire string matches, we're done: output the
953   // matching code.
954   if (CharNo == Matches[0]->first.size()) {
955     assert(Matches.size() == 1 && "Had duplicate keys to match on");
956     
957     // FIXME: If Matches[0].first has embeded \n, this will be bad.
958     OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
959        << "\"\n";
960     return false;
961   }
962   
963   // Bucket the matches by the character we are comparing.
964   std::map<char, std::vector<const StringPair*> > MatchesByLetter;
965   
966   for (unsigned i = 0, e = Matches.size(); i != e; ++i)
967     MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
968   
969
970   // If we have exactly one bucket to match, see how many characters are common
971   // across the whole set and match all of them at once.
972   if (MatchesByLetter.size() == 1) {
973     unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
974     unsigned NumChars = FirstNonCommonLetter-CharNo;
975     
976     // Emit code to break out if the prefix doesn't match.
977     if (NumChars == 1) {
978       // Do the comparison with if (Str[1] != 'f')
979       // FIXME: Need to escape general characters.
980       OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
981          << Matches[0]->first[CharNo] << "')\n";
982       OS << Indent << "  break;\n";
983     } else {
984       // Do the comparison with if (Str.substr(1,3) != "foo").    
985       // FIXME: Need to escape general strings.
986       OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
987          << NumChars << ") != \"";
988       OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
989       OS << Indent << "  break;\n";
990     }
991     
992     return EmitStringMatcherForChar(StrVariableName, Matches, 
993                                     FirstNonCommonLetter, IndentCount, OS);
994   }
995   
996   // Otherwise, we have multiple possible things, emit a switch on the
997   // character.
998   OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
999   OS << Indent << "default: break;\n";
1000   
1001   for (std::map<char, std::vector<const StringPair*> >::iterator LI = 
1002        MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
1003     // TODO: escape hard stuff (like \n) if we ever care about it.
1004     OS << Indent << "case '" << LI->first << "':\t // "
1005        << LI->second.size() << " strings to match.\n";
1006     if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
1007                                  IndentCount+1, OS))
1008       OS << Indent << "  break;\n";
1009   }
1010   
1011   OS << Indent << "}\n";
1012   return true;
1013 }
1014
1015
1016 /// EmitStringMatcher - Given a list of strings and code to execute when they
1017 /// match, output a simple switch tree to classify the input string.
1018 /// 
1019 /// If a match is found, the code in Vals[i].second is executed; control must
1020 /// not exit this code fragment.  If nothing matches, execution falls through.
1021 ///
1022 /// \param StrVariableName - The name of the variable to test.
1023 static void EmitStringMatcher(const std::string &StrVariableName,
1024                               const std::vector<StringPair> &Matches,
1025                               raw_ostream &OS) {
1026   // First level categorization: group strings by length.
1027   std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
1028   
1029   for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1030     MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
1031   
1032   // Output a switch statement on length and categorize the elements within each
1033   // bin.
1034   OS << "  switch (" << StrVariableName << ".size()) {\n";
1035   OS << "  default: break;\n";
1036   
1037   for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
1038        MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
1039     OS << "  case " << LI->first << ":\t // " << LI->second.size()
1040        << " strings to match.\n";
1041     if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
1042       OS << "    break;\n";
1043   }
1044   
1045   OS << "  }\n";
1046 }
1047
1048
1049 /// EmitMatchTokenString - Emit the function to match a token string to the
1050 /// appropriate match class value.
1051 static void EmitMatchTokenString(CodeGenTarget &Target,
1052                                  std::vector<ClassInfo*> &Infos,
1053                                  raw_ostream &OS) {
1054   // Construct the match list.
1055   std::vector<StringPair> Matches;
1056   for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
1057          ie = Infos.end(); it != ie; ++it) {
1058     ClassInfo &CI = **it;
1059
1060     if (CI.Kind == ClassInfo::Token)
1061       Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
1062   }
1063
1064   OS << "static MatchClassKind MatchTokenString(const StringRef &Name) {\n";
1065
1066   EmitStringMatcher("Name", Matches, OS);
1067
1068   OS << "  return InvalidMatchClass;\n";
1069   OS << "}\n\n";
1070 }
1071
1072 /// EmitMatchRegisterName - Emit the function to match a string to the target
1073 /// specific register enum.
1074 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1075                                   raw_ostream &OS) {
1076   // Construct the match list.
1077   std::vector<StringPair> Matches;
1078   for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1079     const CodeGenRegister &Reg = Target.getRegisters()[i];
1080     if (Reg.TheDef->getValueAsString("AsmName").empty())
1081       continue;
1082
1083     Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
1084                                  "return " + utostr(i + 1) + ";"));
1085   }
1086   
1087   OS << "unsigned " << Target.getName() 
1088      << AsmParser->getValueAsString("AsmParserClassName")
1089      << "::MatchRegisterName(const StringRef &Name) {\n";
1090
1091   EmitStringMatcher("Name", Matches, OS);
1092   
1093   OS << "  return 0;\n";
1094   OS << "}\n\n";
1095 }
1096
1097 void AsmMatcherEmitter::run(raw_ostream &OS) {
1098   CodeGenTarget Target;
1099   Record *AsmParser = Target.getAsmParser();
1100   std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1101
1102   EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1103
1104   // Emit the function to match a register name to number.
1105   EmitMatchRegisterName(Target, AsmParser, OS);
1106
1107   // Compute the information on the instructions to match.
1108   AsmMatcherInfo Info;
1109   Info.BuildInfo(Target);
1110
1111   // Sort the instruction table using the partial order on classes.
1112   std::sort(Info.Instructions.begin(), Info.Instructions.end(),
1113             less_ptr<InstructionInfo>());
1114   
1115   DEBUG_WITH_TYPE("instruction_info", {
1116       for (std::vector<InstructionInfo*>::iterator 
1117              it = Info.Instructions.begin(), ie = Info.Instructions.end(); 
1118            it != ie; ++it)
1119         (*it)->dump();
1120     });
1121
1122   // Check for ambiguous instructions.
1123   unsigned NumAmbiguous = 0;
1124   for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1125     for (unsigned j = i + 1; j != e; ++j) {
1126       InstructionInfo &A = *Info.Instructions[i];
1127       InstructionInfo &B = *Info.Instructions[j];
1128     
1129       if (A.CouldMatchAmiguouslyWith(B)) {
1130         DEBUG_WITH_TYPE("ambiguous_instrs", {
1131             errs() << "warning: ambiguous instruction match:\n";
1132             A.dump();
1133             errs() << "\nis incomparable with:\n";
1134             B.dump();
1135             errs() << "\n\n";
1136           });
1137         ++NumAmbiguous;
1138       }
1139     }
1140   }
1141   if (NumAmbiguous)
1142     DEBUG_WITH_TYPE("ambiguous_instrs", {
1143         errs() << "warning: " << NumAmbiguous 
1144                << " ambiguous instructions!\n";
1145       });
1146
1147   // Generate the unified function to convert operands into an MCInst.
1148   EmitConvertToMCInst(Target, Info.Instructions, OS);
1149
1150   // Emit the enumeration for classes which participate in matching.
1151   EmitMatchClassEnumeration(Target, Info.Classes, OS);
1152
1153   // Emit the routine to match token strings to their match class.
1154   EmitMatchTokenString(Target, Info.Classes, OS);
1155
1156   // Emit the routine to classify an operand.
1157   EmitClassifyOperand(Target, Info.Classes, OS);
1158
1159   // Emit the subclass predicate routine.
1160   EmitIsSubclass(Target, Info.Classes, OS);
1161
1162   // Finally, build the match function.
1163
1164   size_t MaxNumOperands = 0;
1165   for (std::vector<InstructionInfo*>::const_iterator it =
1166          Info.Instructions.begin(), ie = Info.Instructions.end();
1167        it != ie; ++it)
1168     MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1169   
1170   OS << "bool " << Target.getName() << ClassName
1171      << "::MatchInstruction(" 
1172      << "SmallVectorImpl<" << Target.getName() << "Operand> &Operands, "
1173      << "MCInst &Inst) {\n";
1174
1175   // Emit the static match table; unused classes get initalized to 0 which is
1176   // guaranteed to be InvalidMatchClass.
1177   //
1178   // FIXME: We can reduce the size of this table very easily. First, we change
1179   // it so that store the kinds in separate bit-fields for each index, which
1180   // only needs to be the max width used for classes at that index (we also need
1181   // to reject based on this during classification). If we then make sure to
1182   // order the match kinds appropriately (putting mnemonics last), then we
1183   // should only end up using a few bits for each class, especially the ones
1184   // following the mnemonic.
1185   OS << "  static const struct MatchEntry {\n";
1186   OS << "    unsigned Opcode;\n";
1187   OS << "    ConversionKind ConvertFn;\n";
1188   OS << "    MatchClassKind Classes[" << MaxNumOperands << "];\n";
1189   OS << "  } MatchTable[" << Info.Instructions.size() << "] = {\n";
1190
1191   for (std::vector<InstructionInfo*>::const_iterator it =
1192          Info.Instructions.begin(), ie = Info.Instructions.end();
1193        it != ie; ++it) {
1194     InstructionInfo &II = **it;
1195
1196     OS << "    { " << Target.getName() << "::" << II.InstrName
1197        << ", " << II.ConversionFnKind << ", { ";
1198     for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1199       InstructionInfo::Operand &Op = II.Operands[i];
1200       
1201       if (i) OS << ", ";
1202       OS << Op.Class->Name;
1203     }
1204     OS << " } },\n";
1205   }
1206
1207   OS << "  };\n\n";
1208
1209   // Emit code to compute the class list for this operand vector.
1210   OS << "  // Eliminate obvious mismatches.\n";
1211   OS << "  if (Operands.size() > " << MaxNumOperands << ")\n";
1212   OS << "    return true;\n\n";
1213
1214   OS << "  // Compute the class list for this operand vector.\n";
1215   OS << "  MatchClassKind Classes[" << MaxNumOperands << "];\n";
1216   OS << "  for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1217   OS << "    Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1218
1219   OS << "    // Check for invalid operands before matching.\n";
1220   OS << "    if (Classes[i] == InvalidMatchClass)\n";
1221   OS << "      return true;\n";
1222   OS << "  }\n\n";
1223
1224   OS << "  // Mark unused classes.\n";
1225   OS << "  for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1226      << "i != e; ++i)\n";
1227   OS << "    Classes[i] = InvalidMatchClass;\n\n";
1228
1229   // Emit code to search the table.
1230   OS << "  // Search the table.\n";
1231   OS << "  for (const MatchEntry *it = MatchTable, "
1232      << "*ie = MatchTable + " << Info.Instructions.size()
1233      << "; it != ie; ++it) {\n";
1234   for (unsigned i = 0; i != MaxNumOperands; ++i) {
1235     OS << "    if (!IsSubclass(Classes[" 
1236        << i << "], it->Classes[" << i << "]))\n";
1237     OS << "      continue;\n";
1238   }
1239   OS << "\n";
1240   OS << "    return ConvertToMCInst(it->ConvertFn, Inst, "
1241      << "it->Opcode, Operands);\n";
1242   OS << "  }\n\n";
1243
1244   OS << "  return true;\n";
1245   OS << "}\n\n";
1246 }