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