llvm-mc/AsmMatcher: Remove some code which has been obsoleted by move to
[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     CI->PredicateMethod = "is" + CI->ClassName;
593     CI->RenderMethod = "add" + CI->ClassName + "Operands";
594     AsmOperandClasses[*it] = CI;
595     Classes.push_back(CI);
596   }
597
598   // Build the instruction information.
599   for (std::map<std::string, CodeGenInstruction>::const_iterator 
600          it = Target.getInstructions().begin(), 
601          ie = Target.getInstructions().end(); 
602        it != ie; ++it) {
603     const CodeGenInstruction &CGI = it->second;
604
605     if (!StringRef(it->first).startswith(MatchPrefix))
606       continue;
607
608     OwningPtr<InstructionInfo> II(new InstructionInfo);
609     
610     II->InstrName = it->first;
611     II->Instr = &it->second;
612     II->AsmString = FlattenVariants(CGI.AsmString, 0);
613
614     TokenizeAsmString(II->AsmString, II->Tokens);
615
616     // Ignore instructions which shouldn't be matched.
617     if (!IsAssemblerInstruction(it->first, CGI, II->Tokens))
618       continue;
619
620     for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
621       StringRef Token = II->Tokens[i];
622
623       // Check for simple tokens.
624       if (Token[0] != '$') {
625         InstructionInfo::Operand Op;
626         Op.Class = getTokenClass(Token);
627         Op.OperandInfo = 0;
628         II->Operands.push_back(Op);
629         continue;
630       }
631
632       // Otherwise this is an operand reference.
633       StringRef OperandName;
634       if (Token[1] == '{')
635         OperandName = Token.substr(2, Token.size() - 3);
636       else
637         OperandName = Token.substr(1);
638
639       // Map this token to an operand. FIXME: Move elsewhere.
640       unsigned Idx;
641       try {
642         Idx = CGI.getOperandNamed(OperandName);
643       } catch(...) {
644         errs() << "error: unable to find operand: '" << OperandName << "'!\n";
645         break;
646       }
647
648       const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx];      
649       InstructionInfo::Operand Op;
650       Op.Class = getOperandClass(Token, OI);
651       Op.OperandInfo = &OI;
652       II->Operands.push_back(Op);
653     }
654
655     // If we broke out, ignore the instruction.
656     if (II->Operands.size() != II->Tokens.size())
657       continue;
658
659     Instructions.push_back(II.take());
660   }
661
662   // Reorder classes so that classes preceed super classes.
663   std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
664 }
665
666 static void EmitConvertToMCInst(CodeGenTarget &Target,
667                                 std::vector<InstructionInfo*> &Infos,
668                                 raw_ostream &OS) {
669   // Write the convert function to a separate stream, so we can drop it after
670   // the enum.
671   std::string ConvertFnBody;
672   raw_string_ostream CvtOS(ConvertFnBody);
673
674   // Function we have already generated.
675   std::set<std::string> GeneratedFns;
676
677   // Start the unified conversion function.
678
679   CvtOS << "static bool ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
680         << "unsigned Opcode,\n"
681         << "                            SmallVectorImpl<"
682         << Target.getName() << "Operand> &Operands) {\n";
683   CvtOS << "  Inst.setOpcode(Opcode);\n";
684   CvtOS << "  switch (Kind) {\n";
685   CvtOS << "  default:\n";
686
687   // Start the enum, which we will generate inline.
688
689   OS << "// Unified function for converting operants to MCInst instances.\n\n";
690   OS << "enum ConversionKind {\n";
691   
692   for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
693          ie = Infos.end(); it != ie; ++it) {
694     InstructionInfo &II = **it;
695
696     // Order the (class) operands by the order to convert them into an MCInst.
697     SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
698     for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
699       InstructionInfo::Operand &Op = II.Operands[i];
700       if (Op.OperandInfo)
701         MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
702     }
703     std::sort(MIOperandList.begin(), MIOperandList.end());
704
705     // Compute the total number of operands.
706     unsigned NumMIOperands = 0;
707     for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
708       const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
709       NumMIOperands = std::max(NumMIOperands, 
710                                OI.MIOperandNo + OI.MINumOperands);
711     }
712
713     // Build the conversion function signature.
714     std::string Signature = "Convert";
715     unsigned CurIndex = 0;
716     for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
717       InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
718       assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
719              "Duplicate match for instruction operand!");
720       
721       Signature += "_";
722
723       // Skip operands which weren't matched by anything, this occurs when the
724       // .td file encodes "implicit" operands as explicit ones.
725       //
726       // FIXME: This should be removed from the MCInst structure.
727       for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
728         Signature += "Imp";
729
730       Signature += Op.Class->ClassName;
731       Signature += utostr(Op.OperandInfo->MINumOperands);
732       Signature += "_" + utostr(MIOperandList[i].second);
733
734       CurIndex += Op.OperandInfo->MINumOperands;
735     }
736
737     // Add any trailing implicit operands.
738     for (; CurIndex != NumMIOperands; ++CurIndex)
739       Signature += "Imp";
740
741     II.ConversionFnKind = Signature;
742
743     // Check if we have already generated this signature.
744     if (!GeneratedFns.insert(Signature).second)
745       continue;
746
747     // If not, emit it now.
748
749     // Add to the enum list.
750     OS << "  " << Signature << ",\n";
751
752     // And to the convert function.
753     CvtOS << "  case " << Signature << ":\n";
754     CurIndex = 0;
755     for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
756       InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
757
758       // Add the implicit operands.
759       for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
760         CvtOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
761
762       CvtOS << "    Operands[" << MIOperandList[i].second 
763          << "]." << Op.Class->RenderMethod 
764          << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
765       CurIndex += Op.OperandInfo->MINumOperands;
766     }
767     
768     // And add trailing implicit operands.
769     for (; CurIndex != NumMIOperands; ++CurIndex)
770       CvtOS << "    Inst.addOperand(MCOperand::CreateReg(0));\n";
771     CvtOS << "    break;\n";
772   }
773
774   // Finish the convert function.
775
776   CvtOS << "  }\n";
777   CvtOS << "  return false;\n";
778   CvtOS << "}\n\n";
779
780   // Finish the enum, and drop the convert function after it.
781
782   OS << "  NumConversionVariants\n";
783   OS << "};\n\n";
784   
785   OS << CvtOS.str();
786 }
787
788 /// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
789 static void EmitMatchClassEnumeration(CodeGenTarget &Target,
790                                       std::vector<ClassInfo*> &Infos,
791                                       raw_ostream &OS) {
792   OS << "namespace {\n\n";
793
794   OS << "/// MatchClassKind - The kinds of classes which participate in\n"
795      << "/// instruction matching.\n";
796   OS << "enum MatchClassKind {\n";
797   OS << "  InvalidMatchClass = 0,\n";
798   for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
799          ie = Infos.end(); it != ie; ++it) {
800     ClassInfo &CI = **it;
801     OS << "  " << CI.Name << ", // ";
802     if (CI.Kind == ClassInfo::Token) {
803       OS << "'" << CI.ValueName << "'\n";
804     } else if (CI.Kind == ClassInfo::Register) {
805       if (!CI.ValueName.empty())
806         OS << "register class '" << CI.ValueName << "'\n";
807       else
808         OS << "derived register class\n";
809     } else {
810       OS << "user defined class '" << CI.ValueName << "'\n";
811     }
812   }
813   OS << "  NumMatchClassKinds\n";
814   OS << "};\n\n";
815
816   OS << "}\n\n";
817 }
818
819 /// EmitClassifyOperand - Emit the function to classify an operand.
820 static void EmitClassifyOperand(CodeGenTarget &Target,
821                                 std::vector<ClassInfo*> &Infos,
822                                 raw_ostream &OS) {
823   OS << "static MatchClassKind ClassifyOperand("
824      << Target.getName() << "Operand &Operand) {\n";
825   OS << "  if (Operand.isToken())\n";
826   OS << "    return MatchTokenString(Operand.getToken());\n\n";
827   for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
828          ie = Infos.end(); it != ie; ++it) {
829     ClassInfo &CI = **it;
830
831     if (CI.Kind != ClassInfo::Token) {
832       OS << "  // '" << CI.ClassName << "' class";
833       if (CI.SuperClass) {
834         OS << ", subclass of '" << CI.SuperClass->ClassName << "'";
835         assert(CI < *CI.SuperClass && "Invalid class relation!");
836       }
837       OS << "\n";
838
839       OS << "  if (Operand." << CI.PredicateMethod << "()) {\n";
840       
841       // Validate subclass relationships.
842       if (CI.SuperClass)
843         OS << "    assert(Operand." << CI.SuperClass->PredicateMethod
844            << "() && \"Invalid class relationship!\");\n";
845
846       OS << "    return " << CI.Name << ";\n";
847       OS << "  }\n\n";
848     }
849   }
850   OS << "  return InvalidMatchClass;\n";
851   OS << "}\n\n";
852 }
853
854 /// EmitIsSubclass - Emit the subclass predicate function.
855 static void EmitIsSubclass(CodeGenTarget &Target,
856                            std::vector<ClassInfo*> &Infos,
857                            raw_ostream &OS) {
858   OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
859   OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
860   OS << "  if (A == B)\n";
861   OS << "    return true;\n\n";
862
863   OS << "  switch (A) {\n";
864   OS << "  default:\n";
865   OS << "    return false;\n";
866   for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
867          ie = Infos.end(); it != ie; ++it) {
868     ClassInfo &A = **it;
869
870     if (A.Kind != ClassInfo::Token) {
871       std::vector<StringRef> SuperClasses;
872       for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
873              ie = Infos.end(); it != ie; ++it) {
874         ClassInfo &B = **it;
875
876         if (&A != &B && A.getRootClass() == B.getRootClass() && A < B)
877           SuperClasses.push_back(B.Name);
878       }
879
880       if (SuperClasses.empty())
881         continue;
882
883       OS << "\n  case " << A.Name << ":\n";
884
885       if (SuperClasses.size() == 1) {
886         OS << "    return B == " << SuperClasses.back() << ";\n\n";
887         continue;
888       }
889
890       OS << "      switch (B) {\n";
891       OS << "      default: return false;\n";
892       for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
893         OS << "      case " << SuperClasses[i] << ": return true;\n";
894       OS << "      }\n\n";
895     }
896   }
897   OS << "  }\n";
898   OS << "}\n\n";
899 }
900
901 typedef std::pair<std::string, std::string> StringPair;
902
903 /// FindFirstNonCommonLetter - Find the first character in the keys of the
904 /// string pairs that is not shared across the whole set of strings.  All
905 /// strings are assumed to have the same length.
906 static unsigned 
907 FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
908   assert(!Matches.empty());
909   for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
910     // Check to see if letter i is the same across the set.
911     char Letter = Matches[0]->first[i];
912     
913     for (unsigned str = 0, e = Matches.size(); str != e; ++str)
914       if (Matches[str]->first[i] != Letter)
915         return i;
916   }
917   
918   return Matches[0]->first.size();
919 }
920
921 /// EmitStringMatcherForChar - Given a set of strings that are known to be the
922 /// same length and whose characters leading up to CharNo are the same, emit
923 /// code to verify that CharNo and later are the same.
924 ///
925 /// \return - True if control can leave the emitted code fragment.
926 static bool EmitStringMatcherForChar(const std::string &StrVariableName,
927                                   const std::vector<const StringPair*> &Matches,
928                                      unsigned CharNo, unsigned IndentCount,
929                                      raw_ostream &OS) {
930   assert(!Matches.empty() && "Must have at least one string to match!");
931   std::string Indent(IndentCount*2+4, ' ');
932
933   // If we have verified that the entire string matches, we're done: output the
934   // matching code.
935   if (CharNo == Matches[0]->first.size()) {
936     assert(Matches.size() == 1 && "Had duplicate keys to match on");
937     
938     // FIXME: If Matches[0].first has embeded \n, this will be bad.
939     OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
940        << "\"\n";
941     return false;
942   }
943   
944   // Bucket the matches by the character we are comparing.
945   std::map<char, std::vector<const StringPair*> > MatchesByLetter;
946   
947   for (unsigned i = 0, e = Matches.size(); i != e; ++i)
948     MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
949   
950
951   // If we have exactly one bucket to match, see how many characters are common
952   // across the whole set and match all of them at once.
953   if (MatchesByLetter.size() == 1) {
954     unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
955     unsigned NumChars = FirstNonCommonLetter-CharNo;
956     
957     // Emit code to break out if the prefix doesn't match.
958     if (NumChars == 1) {
959       // Do the comparison with if (Str[1] != 'f')
960       // FIXME: Need to escape general characters.
961       OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
962          << Matches[0]->first[CharNo] << "')\n";
963       OS << Indent << "  break;\n";
964     } else {
965       // Do the comparison with if (Str.substr(1,3) != "foo").    
966       // FIXME: Need to escape general strings.
967       OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
968          << NumChars << ") != \"";
969       OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
970       OS << Indent << "  break;\n";
971     }
972     
973     return EmitStringMatcherForChar(StrVariableName, Matches, 
974                                     FirstNonCommonLetter, IndentCount, OS);
975   }
976   
977   // Otherwise, we have multiple possible things, emit a switch on the
978   // character.
979   OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
980   OS << Indent << "default: break;\n";
981   
982   for (std::map<char, std::vector<const StringPair*> >::iterator LI = 
983        MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
984     // TODO: escape hard stuff (like \n) if we ever care about it.
985     OS << Indent << "case '" << LI->first << "':\t // "
986        << LI->second.size() << " strings to match.\n";
987     if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
988                                  IndentCount+1, OS))
989       OS << Indent << "  break;\n";
990   }
991   
992   OS << Indent << "}\n";
993   return true;
994 }
995
996
997 /// EmitStringMatcher - Given a list of strings and code to execute when they
998 /// match, output a simple switch tree to classify the input string.
999 /// 
1000 /// If a match is found, the code in Vals[i].second is executed; control must
1001 /// not exit this code fragment.  If nothing matches, execution falls through.
1002 ///
1003 /// \param StrVariableName - The name of the variable to test.
1004 static void EmitStringMatcher(const std::string &StrVariableName,
1005                               const std::vector<StringPair> &Matches,
1006                               raw_ostream &OS) {
1007   // First level categorization: group strings by length.
1008   std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
1009   
1010   for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1011     MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
1012   
1013   // Output a switch statement on length and categorize the elements within each
1014   // bin.
1015   OS << "  switch (" << StrVariableName << ".size()) {\n";
1016   OS << "  default: break;\n";
1017   
1018   for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
1019        MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
1020     OS << "  case " << LI->first << ":\t // " << LI->second.size()
1021        << " strings to match.\n";
1022     if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
1023       OS << "    break;\n";
1024   }
1025   
1026   OS << "  }\n";
1027 }
1028
1029
1030 /// EmitMatchTokenString - Emit the function to match a token string to the
1031 /// appropriate match class value.
1032 static void EmitMatchTokenString(CodeGenTarget &Target,
1033                                  std::vector<ClassInfo*> &Infos,
1034                                  raw_ostream &OS) {
1035   // Construct the match list.
1036   std::vector<StringPair> Matches;
1037   for (std::vector<ClassInfo*>::iterator it = Infos.begin(), 
1038          ie = Infos.end(); it != ie; ++it) {
1039     ClassInfo &CI = **it;
1040
1041     if (CI.Kind == ClassInfo::Token)
1042       Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
1043   }
1044
1045   OS << "static MatchClassKind MatchTokenString(const StringRef &Name) {\n";
1046
1047   EmitStringMatcher("Name", Matches, OS);
1048
1049   OS << "  return InvalidMatchClass;\n";
1050   OS << "}\n\n";
1051 }
1052
1053 /// EmitMatchRegisterName - Emit the function to match a string to the target
1054 /// specific register enum.
1055 static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1056                                   raw_ostream &OS) {
1057   // Construct the match list.
1058   std::vector<StringPair> Matches;
1059   for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1060     const CodeGenRegister &Reg = Target.getRegisters()[i];
1061     if (Reg.TheDef->getValueAsString("AsmName").empty())
1062       continue;
1063
1064     Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
1065                                  "return " + utostr(i + 1) + ";"));
1066   }
1067   
1068   OS << "unsigned " << Target.getName() 
1069      << AsmParser->getValueAsString("AsmParserClassName")
1070      << "::MatchRegisterName(const StringRef &Name) {\n";
1071
1072   EmitStringMatcher("Name", Matches, OS);
1073   
1074   OS << "  return 0;\n";
1075   OS << "}\n\n";
1076 }
1077
1078 void AsmMatcherEmitter::run(raw_ostream &OS) {
1079   CodeGenTarget Target;
1080   Record *AsmParser = Target.getAsmParser();
1081   std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1082
1083   EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1084
1085   // Emit the function to match a register name to number.
1086   EmitMatchRegisterName(Target, AsmParser, OS);
1087
1088   // Compute the information on the instructions to match.
1089   AsmMatcherInfo Info;
1090   Info.BuildInfo(Target);
1091
1092   // Sort the instruction table using the partial order on classes.
1093   std::sort(Info.Instructions.begin(), Info.Instructions.end(),
1094             less_ptr<InstructionInfo>());
1095   
1096   DEBUG_WITH_TYPE("instruction_info", {
1097       for (std::vector<InstructionInfo*>::iterator 
1098              it = Info.Instructions.begin(), ie = Info.Instructions.end(); 
1099            it != ie; ++it)
1100         (*it)->dump();
1101     });
1102
1103   // Check for ambiguous instructions.
1104   unsigned NumAmbiguous = 0;
1105   for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1106     for (unsigned j = i + 1; j != e; ++j) {
1107       InstructionInfo &A = *Info.Instructions[i];
1108       InstructionInfo &B = *Info.Instructions[j];
1109     
1110       if (A.CouldMatchAmiguouslyWith(B)) {
1111         DEBUG_WITH_TYPE("ambiguous_instrs", {
1112             errs() << "warning: ambiguous instruction match:\n";
1113             A.dump();
1114             errs() << "\nis incomparable with:\n";
1115             B.dump();
1116             errs() << "\n\n";
1117           });
1118         ++NumAmbiguous;
1119       }
1120     }
1121   }
1122   if (NumAmbiguous)
1123     DEBUG_WITH_TYPE("ambiguous_instrs", {
1124         errs() << "warning: " << NumAmbiguous 
1125                << " ambiguous instructions!\n";
1126       });
1127
1128   // Generate the unified function to convert operands into an MCInst.
1129   EmitConvertToMCInst(Target, Info.Instructions, OS);
1130
1131   // Emit the enumeration for classes which participate in matching.
1132   EmitMatchClassEnumeration(Target, Info.Classes, OS);
1133
1134   // Emit the routine to match token strings to their match class.
1135   EmitMatchTokenString(Target, Info.Classes, OS);
1136
1137   // Emit the routine to classify an operand.
1138   EmitClassifyOperand(Target, Info.Classes, OS);
1139
1140   // Emit the subclass predicate routine.
1141   EmitIsSubclass(Target, Info.Classes, OS);
1142
1143   // Finally, build the match function.
1144
1145   size_t MaxNumOperands = 0;
1146   for (std::vector<InstructionInfo*>::const_iterator it =
1147          Info.Instructions.begin(), ie = Info.Instructions.end();
1148        it != ie; ++it)
1149     MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1150   
1151   OS << "bool " << Target.getName() << ClassName
1152      << "::MatchInstruction(" 
1153      << "SmallVectorImpl<" << Target.getName() << "Operand> &Operands, "
1154      << "MCInst &Inst) {\n";
1155
1156   // Emit the static match table; unused classes get initalized to 0 which is
1157   // guaranteed to be InvalidMatchClass.
1158   //
1159   // FIXME: We can reduce the size of this table very easily. First, we change
1160   // it so that store the kinds in separate bit-fields for each index, which
1161   // only needs to be the max width used for classes at that index (we also need
1162   // to reject based on this during classification). If we then make sure to
1163   // order the match kinds appropriately (putting mnemonics last), then we
1164   // should only end up using a few bits for each class, especially the ones
1165   // following the mnemonic.
1166   OS << "  static const struct MatchEntry {\n";
1167   OS << "    unsigned Opcode;\n";
1168   OS << "    ConversionKind ConvertFn;\n";
1169   OS << "    MatchClassKind Classes[" << MaxNumOperands << "];\n";
1170   OS << "  } MatchTable[" << Info.Instructions.size() << "] = {\n";
1171
1172   for (std::vector<InstructionInfo*>::const_iterator it =
1173          Info.Instructions.begin(), ie = Info.Instructions.end();
1174        it != ie; ++it) {
1175     InstructionInfo &II = **it;
1176
1177     OS << "    { " << Target.getName() << "::" << II.InstrName
1178        << ", " << II.ConversionFnKind << ", { ";
1179     for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1180       InstructionInfo::Operand &Op = II.Operands[i];
1181       
1182       if (i) OS << ", ";
1183       OS << Op.Class->Name;
1184     }
1185     OS << " } },\n";
1186   }
1187
1188   OS << "  };\n\n";
1189
1190   // Emit code to compute the class list for this operand vector.
1191   OS << "  // Eliminate obvious mismatches.\n";
1192   OS << "  if (Operands.size() > " << MaxNumOperands << ")\n";
1193   OS << "    return true;\n\n";
1194
1195   OS << "  // Compute the class list for this operand vector.\n";
1196   OS << "  MatchClassKind Classes[" << MaxNumOperands << "];\n";
1197   OS << "  for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1198   OS << "    Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1199
1200   OS << "    // Check for invalid operands before matching.\n";
1201   OS << "    if (Classes[i] == InvalidMatchClass)\n";
1202   OS << "      return true;\n";
1203   OS << "  }\n\n";
1204
1205   OS << "  // Mark unused classes.\n";
1206   OS << "  for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1207      << "i != e; ++i)\n";
1208   OS << "    Classes[i] = InvalidMatchClass;\n\n";
1209
1210   // Emit code to search the table.
1211   OS << "  // Search the table.\n";
1212   OS << "  for (const MatchEntry *it = MatchTable, "
1213      << "*ie = MatchTable + " << Info.Instructions.size()
1214      << "; it != ie; ++it) {\n";
1215   for (unsigned i = 0; i != MaxNumOperands; ++i) {
1216     OS << "    if (!IsSubclass(Classes[" 
1217        << i << "], it->Classes[" << i << "]))\n";
1218     OS << "      continue;\n";
1219   }
1220   OS << "\n";
1221   OS << "    return ConvertToMCInst(it->ConvertFn, Inst, "
1222      << "it->Opcode, Operands);\n";
1223   OS << "  }\n\n";
1224
1225   OS << "  return true;\n";
1226   OS << "}\n\n";
1227 }