blob: 9b12927521f77fcb67dec59c265a1d66b6417dd4 [file] [log] [blame]
Daniel Dunbar3f6e3ff2009-07-11 19:39:44 +00001//===- 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//
Daniel Dunbarfe6759e2009-08-07 08:26:05 +000013// 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//
Daniel Dunbar3f6e3ff2009-07-11 19:39:44 +000074//===----------------------------------------------------------------------===//
75
76#include "AsmMatcherEmitter.h"
77#include "CodeGenTarget.h"
78#include "Record.h"
Daniel Dunbarfe6759e2009-08-07 08:26:05 +000079#include "llvm/ADT/OwningPtr.h"
Daniel Dunbara54716c2009-07-31 02:32:59 +000080#include "llvm/ADT/SmallVector.h"
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +000081#include "llvm/ADT/STLExtras.h"
Daniel Dunbarfe6759e2009-08-07 08:26:05 +000082#include "llvm/ADT/StringExtras.h"
83#include "llvm/Support/CommandLine.h"
Daniel Dunbara54716c2009-07-31 02:32:59 +000084#include "llvm/Support/Debug.h"
Daniel Dunbara54716c2009-07-31 02:32:59 +000085#include <list>
Daniel Dunbarce82b992009-08-08 05:24:34 +000086#include <map>
87#include <set>
Daniel Dunbar3f6e3ff2009-07-11 19:39:44 +000088using namespace llvm;
89
Daniel Dunbarfe6759e2009-08-07 08:26:05 +000090namespace {
Daniel Dunbar62beebc2009-08-07 20:33:39 +000091static cl::opt<std::string>
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +000092MatchPrefix("match-prefix", cl::init(""),
93 cl::desc("Only match instructions with the given prefix"));
Daniel Dunbarfe6759e2009-08-07 08:26:05 +000094}
95
Daniel Dunbara54716c2009-07-31 02:32:59 +000096/// FlattenVariants - Flatten an .td file assembly string by selecting the
97/// variant at index \arg N.
98static std::string FlattenVariants(const std::string &AsmString,
99 unsigned N) {
100 StringRef Cur = AsmString;
101 std::string Res = "";
102
103 for (;;) {
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000104 // 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] == '{' &&
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000108 (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
109 Cur[VariantsStart-1] != '\\')))
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000110 break;
Daniel Dunbara54716c2009-07-31 02:32:59 +0000111
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000112 // Add the prefix to the result.
113 Res += Cur.slice(0, VariantsStart);
114 if (VariantsStart == Cur.size())
Daniel Dunbara54716c2009-07-31 02:32:59 +0000115 break;
116
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000117 ++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) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000123 if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000124 if (--NestedBraces == 0)
125 break;
126 } else if (Cur[VariantsEnd] == '{')
127 ++NestedBraces;
128 }
Daniel Dunbara54716c2009-07-31 02:32:59 +0000129
130 // Select the Nth variant (or empty).
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000131 StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
Daniel Dunbara54716c2009-07-31 02:32:59 +0000132 for (unsigned i = 0; i != N; ++i)
133 Selection = Selection.split('|').second;
134 Res += Selection.split('|').first;
135
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000136 assert(VariantsEnd != Cur.size() &&
137 "Unterminated variants in assembly string!");
138 Cur = Cur.substr(VariantsEnd + 1);
Daniel Dunbara54716c2009-07-31 02:32:59 +0000139 }
140
141 return Res;
142}
143
144/// TokenizeAsmString - Tokenize a simplified assembly string.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000145static void TokenizeAsmString(const StringRef &AsmString,
Daniel Dunbara54716c2009-07-31 02:32:59 +0000146 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]) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000151 case '[':
152 case ']':
Daniel Dunbara54716c2009-07-31 02:32:59 +0000153 case '*':
154 case '!':
155 case ' ':
156 case '\t':
157 case ',':
158 if (InTok) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000159 Tokens.push_back(AsmString.slice(Prev, i));
Daniel Dunbara54716c2009-07-31 02:32:59 +0000160 InTok = false;
161 }
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000162 if (!isspace(AsmString[i]) && AsmString[i] != ',')
163 Tokens.push_back(AsmString.substr(i, 1));
Daniel Dunbara54716c2009-07-31 02:32:59 +0000164 Prev = i + 1;
165 break;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000166
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 }
Daniel Dunbara54716c2009-07-31 02:32:59 +0000203
204 default:
205 InTok = true;
206 }
207 }
208 if (InTok && Prev != AsmString.size())
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000209 Tokens.push_back(AsmString.substr(Prev));
210}
211
212static 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
275namespace {
276
Daniel Dunbar378bee92009-08-08 07:50:56 +0000277/// ClassInfo - Helper class for storing the information about a particular
278/// class of operands which can be matched.
279struct ClassInfo {
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000280 enum ClassInfoKind {
Daniel Dunbar378bee92009-08-08 07:50:56 +0000281 Token, ///< The class for a particular token.
282 Register, ///< A register class.
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000283 UserClass0 ///< The (first) user defined class, subsequent user defined
284 /// classes are UserClass0+1, and so on.
285 };
286
287 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
288 /// N) for the Nth user defined class.
289 unsigned Kind;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000290
291 /// Name - The class name, suitable for use as an enum.
292 std::string Name;
293
294 /// ValueName - The name of the value this class represents; for a token this
295 /// is the literal token string, for an operand it is the TableGen class (or
296 /// empty if this is a derived class).
297 std::string ValueName;
298
299 /// PredicateMethod - The name of the operand method to test whether the
300 /// operand matches this class; this is not valid for Token kinds.
301 std::string PredicateMethod;
302
303 /// RenderMethod - The name of the operand method to add this operand to an
304 /// MCInst; this is not valid for Token kinds.
305 std::string RenderMethod;
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000306
307 /// operator< - Compare two classes.
308 bool operator<(const ClassInfo &RHS) const {
309 // Incompatible kinds are comparable.
310 if (Kind != RHS.Kind)
311 return Kind < RHS.Kind;
312
313 switch (Kind) {
314 case Token:
315 // Tokens are always comparable.
316 //
317 // FIXME: Compare by enum value.
318 return ValueName < RHS.ValueName;
319
320 case Register:
321 // FIXME: Compare by subset relation.
322 return false;
323
324 default:
325 // FIXME: Allow user defined relation.
326 return false;
327 }
328 }
Daniel Dunbar378bee92009-08-08 07:50:56 +0000329};
330
Daniel Dunbarce82b992009-08-08 05:24:34 +0000331/// InstructionInfo - Helper class for storing the necessary information for an
332/// instruction which is capable of being matched.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000333struct InstructionInfo {
334 struct Operand {
Daniel Dunbar378bee92009-08-08 07:50:56 +0000335 /// The unique class instance this operand should match.
336 ClassInfo *Class;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000337
Daniel Dunbar378bee92009-08-08 07:50:56 +0000338 /// The original operand this corresponds to, if any.
Benjamin Kramer19afc502009-08-08 10:06:30 +0000339 const CodeGenInstruction::OperandInfo *OperandInfo;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000340 };
341
342 /// InstrName - The target name for this instruction.
343 std::string InstrName;
344
345 /// Instr - The instruction this matches.
346 const CodeGenInstruction *Instr;
347
348 /// AsmString - The assembly string for this instruction (with variants
349 /// removed).
350 std::string AsmString;
351
352 /// Tokens - The tokenized assembly pattern that this instruction matches.
353 SmallVector<StringRef, 4> Tokens;
354
355 /// Operands - The operands that this instruction matches.
356 SmallVector<Operand, 4> Operands;
357
Daniel Dunbarce82b992009-08-08 05:24:34 +0000358 /// ConversionFnKind - The enum value which is passed to the generated
359 /// ConvertToMCInst to convert parsed operands into an MCInst for this
360 /// function.
361 std::string ConversionFnKind;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000362
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000363 /// operator< - Compare two instructions.
364 bool operator<(const InstructionInfo &RHS) const {
365 // Order first by the number of operands (which is unambiguous).
366 if (Operands.size() != RHS.Operands.size())
367 return Operands.size() < RHS.Operands.size();
368
369 // Otherwise, order by lexicographic comparison of tokens and operand kinds
370 // (these can never be ambiguous).
371 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
372 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
373 Operands[i].Class->Kind == ClassInfo::Token)
374 if (*Operands[i].Class < *RHS.Operands[i].Class)
375 return true;
376
377 // Finally, order by the component wise comparison of operand classes. We
378 // don't want to rely on the lexigraphic ordering of elements, so we define
379 // only define the ordering when it is unambiguous. That is, when some pair
380 // compares less than and no pair compares greater than.
381
382 // Check that no pair compares greater than.
383 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
384 if (*RHS.Operands[i].Class < *Operands[i].Class)
385 return false;
386
387 // Otherwise, return true if some pair compares less than.
388 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
389 if (*Operands[i].Class < *RHS.Operands[i].Class)
390 return true;
391
392 return false;
393 }
394
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000395public:
396 void dump();
397};
398
Daniel Dunbar378bee92009-08-08 07:50:56 +0000399class AsmMatcherInfo {
400public:
401 /// The classes which are needed for matching.
402 std::vector<ClassInfo*> Classes;
403
404 /// The information on the instruction to match.
405 std::vector<InstructionInfo*> Instructions;
406
407private:
408 /// Map of token to class information which has already been constructed.
409 std::map<std::string, ClassInfo*> TokenClasses;
410
411 /// Map of operand name to class information which has already been
412 /// constructed.
413 std::map<std::string, ClassInfo*> OperandClasses;
414
415private:
416 /// getTokenClass - Lookup or create the class for the given token.
417 ClassInfo *getTokenClass(const StringRef &Token);
418
419 /// getOperandClass - Lookup or create the class for the given operand.
420 ClassInfo *getOperandClass(const StringRef &Token,
421 const CodeGenInstruction::OperandInfo &OI);
422
423public:
424 /// BuildInfo - Construct the various tables used during matching.
425 void BuildInfo(CodeGenTarget &Target);
426};
427
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000428}
429
430void InstructionInfo::dump() {
431 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
432 << ", tokens:[";
433 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
434 errs() << Tokens[i];
435 if (i + 1 != e)
436 errs() << ", ";
437 }
438 errs() << "]\n";
439
440 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
441 Operand &Op = Operands[i];
442 errs() << " op[" << i << "] = ";
Daniel Dunbar378bee92009-08-08 07:50:56 +0000443 if (Op.Class->Kind == ClassInfo::Token) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000444 errs() << '\"' << Tokens[i] << "\"\n";
445 continue;
446 }
447
Benjamin Kramer19afc502009-08-08 10:06:30 +0000448 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000449 errs() << OI.Name << " " << OI.Rec->getName()
450 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
451 }
452}
453
Daniel Dunbar378bee92009-08-08 07:50:56 +0000454static std::string getEnumNameForToken(const StringRef &Str) {
455 std::string Res;
456
457 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
458 switch (*it) {
459 case '*': Res += "_STAR_"; break;
460 case '%': Res += "_PCT_"; break;
461 case ':': Res += "_COLON_"; break;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000462
Daniel Dunbar378bee92009-08-08 07:50:56 +0000463 default:
464 if (isalnum(*it)) {
465 Res += *it;
466 } else {
467 Res += "_" + utostr((unsigned) *it) + "_";
468 }
469 }
470 }
471
472 return Res;
473}
474
475ClassInfo *AsmMatcherInfo::getTokenClass(const StringRef &Token) {
476 ClassInfo *&Entry = TokenClasses[Token];
477
478 if (!Entry) {
479 Entry = new ClassInfo();
480 Entry->Kind = ClassInfo::Token;
481 Entry->Name = "MCK_" + getEnumNameForToken(Token);
482 Entry->ValueName = Token;
483 Entry->PredicateMethod = "<invalid>";
484 Entry->RenderMethod = "<invalid>";
485 Classes.push_back(Entry);
486 }
487
488 return Entry;
489}
490
491ClassInfo *
492AsmMatcherInfo::getOperandClass(const StringRef &Token,
493 const CodeGenInstruction::OperandInfo &OI) {
494 std::string ClassName;
495 if (OI.Rec->isSubClassOf("RegisterClass")) {
496 ClassName = "Reg";
497 } else if (OI.Rec->isSubClassOf("Operand")) {
498 // FIXME: This should not be hard coded.
499 const RecordVal *RV = OI.Rec->getValue("Type");
500
501 // FIXME: Yet another total hack.
502 if (RV->getValue()->getAsString() == "iPTR" ||
503 OI.Rec->getName() == "i8mem_NOREX" ||
504 OI.Rec->getName() == "lea32mem" ||
505 OI.Rec->getName() == "lea64mem" ||
506 OI.Rec->getName() == "i128mem" ||
507 OI.Rec->getName() == "sdmem" ||
508 OI.Rec->getName() == "ssmem" ||
509 OI.Rec->getName() == "lea64_32mem") {
510 ClassName = "Mem";
511 } else {
512 ClassName = "Imm";
513 }
514 }
515
516 ClassInfo *&Entry = OperandClasses[ClassName];
517
518 if (!Entry) {
519 Entry = new ClassInfo();
520 // FIXME: Hack.
521 if (ClassName == "Reg") {
522 Entry->Kind = ClassInfo::Register;
523 } else {
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000524 if (ClassName == "Mem")
525 Entry->Kind = ClassInfo::UserClass0;
526 else
527 Entry->Kind = ClassInfo::UserClass0 + 1;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000528 }
529 Entry->Name = "MCK_" + ClassName;
530 Entry->ValueName = OI.Rec->getName();
531 Entry->PredicateMethod = "is" + ClassName;
532 Entry->RenderMethod = "add" + ClassName + "Operands";
533 Classes.push_back(Entry);
534 }
535
536 return Entry;
537}
538
539void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000540 for (std::map<std::string, CodeGenInstruction>::const_iterator
Daniel Dunbar378bee92009-08-08 07:50:56 +0000541 it = Target.getInstructions().begin(),
542 ie = Target.getInstructions().end();
543 it != ie; ++it) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000544 const CodeGenInstruction &CGI = it->second;
545
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000546 if (!StringRef(it->first).startswith(MatchPrefix))
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000547 continue;
548
549 OwningPtr<InstructionInfo> II(new InstructionInfo);
550
551 II->InstrName = it->first;
552 II->Instr = &it->second;
553 II->AsmString = FlattenVariants(CGI.AsmString, 0);
554
555 TokenizeAsmString(II->AsmString, II->Tokens);
556
557 // Ignore instructions which shouldn't be matched.
558 if (!IsAssemblerInstruction(it->first, CGI, II->Tokens))
559 continue;
560
561 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
562 StringRef Token = II->Tokens[i];
563
564 // Check for simple tokens.
565 if (Token[0] != '$') {
566 InstructionInfo::Operand Op;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000567 Op.Class = getTokenClass(Token);
Benjamin Kramer19afc502009-08-08 10:06:30 +0000568 Op.OperandInfo = 0;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000569 II->Operands.push_back(Op);
570 continue;
571 }
572
573 // Otherwise this is an operand reference.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000574 StringRef OperandName;
575 if (Token[1] == '{')
576 OperandName = Token.substr(2, Token.size() - 3);
577 else
578 OperandName = Token.substr(1);
579
580 // Map this token to an operand. FIXME: Move elsewhere.
581 unsigned Idx;
582 try {
583 Idx = CGI.getOperandNamed(OperandName);
584 } catch(...) {
585 errs() << "error: unable to find operand: '" << OperandName << "'!\n";
586 break;
587 }
588
589 const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx];
Daniel Dunbar378bee92009-08-08 07:50:56 +0000590 InstructionInfo::Operand Op;
591 Op.Class = getOperandClass(Token, OI);
Benjamin Kramer19afc502009-08-08 10:06:30 +0000592 Op.OperandInfo = &OI;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000593 II->Operands.push_back(Op);
594 }
595
596 // If we broke out, ignore the instruction.
597 if (II->Operands.size() != II->Tokens.size())
598 continue;
599
Daniel Dunbar378bee92009-08-08 07:50:56 +0000600 Instructions.push_back(II.take());
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000601 }
602}
603
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000604static void EmitConvertToMCInst(CodeGenTarget &Target,
605 std::vector<InstructionInfo*> &Infos,
606 raw_ostream &OS) {
Daniel Dunbarce82b992009-08-08 05:24:34 +0000607 // Write the convert function to a separate stream, so we can drop it after
608 // the enum.
609 std::string ConvertFnBody;
610 raw_string_ostream CvtOS(ConvertFnBody);
611
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000612 // Function we have already generated.
613 std::set<std::string> GeneratedFns;
614
Daniel Dunbarce82b992009-08-08 05:24:34 +0000615 // Start the unified conversion function.
616
617 CvtOS << "static bool ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
618 << "unsigned Opcode,\n"
619 << " SmallVectorImpl<"
620 << Target.getName() << "Operand> &Operands) {\n";
621 CvtOS << " Inst.setOpcode(Opcode);\n";
622 CvtOS << " switch (Kind) {\n";
623 CvtOS << " default:\n";
624
625 // Start the enum, which we will generate inline.
626
627 OS << "// Unified function for converting operants to MCInst instances.\n\n";
Daniel Dunbarce82b992009-08-08 05:24:34 +0000628 OS << "enum ConversionKind {\n";
629
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000630 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
631 ie = Infos.end(); it != ie; ++it) {
632 InstructionInfo &II = **it;
633
634 // Order the (class) operands by the order to convert them into an MCInst.
635 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
636 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
637 InstructionInfo::Operand &Op = II.Operands[i];
Benjamin Kramer19afc502009-08-08 10:06:30 +0000638 if (Op.OperandInfo)
639 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000640 }
641 std::sort(MIOperandList.begin(), MIOperandList.end());
642
643 // Compute the total number of operands.
644 unsigned NumMIOperands = 0;
645 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
646 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
647 NumMIOperands = std::max(NumMIOperands,
648 OI.MIOperandNo + OI.MINumOperands);
649 }
650
651 // Build the conversion function signature.
652 std::string Signature = "Convert";
653 unsigned CurIndex = 0;
654 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
655 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
Benjamin Kramer19afc502009-08-08 10:06:30 +0000656 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000657 "Duplicate match for instruction operand!");
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000658
Daniel Dunbarce82b992009-08-08 05:24:34 +0000659 Signature += "_";
660
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000661 // Skip operands which weren't matched by anything, this occurs when the
662 // .td file encodes "implicit" operands as explicit ones.
663 //
664 // FIXME: This should be removed from the MCInst structure.
Benjamin Kramer19afc502009-08-08 10:06:30 +0000665 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000666 Signature += "Imp";
667
Daniel Dunbar378bee92009-08-08 07:50:56 +0000668 Signature += Op.Class->Name;
Benjamin Kramer19afc502009-08-08 10:06:30 +0000669 Signature += utostr(Op.OperandInfo->MINumOperands);
Daniel Dunbarce82b992009-08-08 05:24:34 +0000670 Signature += "_" + utostr(MIOperandList[i].second);
671
Benjamin Kramer19afc502009-08-08 10:06:30 +0000672 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000673 }
674
675 // Add any trailing implicit operands.
676 for (; CurIndex != NumMIOperands; ++CurIndex)
677 Signature += "Imp";
678
Daniel Dunbarce82b992009-08-08 05:24:34 +0000679 II.ConversionFnKind = Signature;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000680
Daniel Dunbarce82b992009-08-08 05:24:34 +0000681 // Check if we have already generated this signature.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000682 if (!GeneratedFns.insert(Signature).second)
683 continue;
684
685 // If not, emit it now.
Daniel Dunbarce82b992009-08-08 05:24:34 +0000686
687 // Add to the enum list.
688 OS << " " << Signature << ",\n";
689
690 // And to the convert function.
691 CvtOS << " case " << Signature << ":\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000692 CurIndex = 0;
693 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
694 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
695
696 // Add the implicit operands.
Benjamin Kramer19afc502009-08-08 10:06:30 +0000697 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
Daniel Dunbarce82b992009-08-08 05:24:34 +0000698 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000699
Daniel Dunbarce82b992009-08-08 05:24:34 +0000700 CvtOS << " Operands[" << MIOperandList[i].second
Daniel Dunbar378bee92009-08-08 07:50:56 +0000701 << "]." << Op.Class->RenderMethod
Benjamin Kramer19afc502009-08-08 10:06:30 +0000702 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
703 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000704 }
705
706 // And add trailing implicit operands.
707 for (; CurIndex != NumMIOperands; ++CurIndex)
Daniel Dunbarce82b992009-08-08 05:24:34 +0000708 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
709 CvtOS << " break;\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000710 }
Daniel Dunbarce82b992009-08-08 05:24:34 +0000711
712 // Finish the convert function.
713
714 CvtOS << " }\n";
715 CvtOS << " return false;\n";
716 CvtOS << "}\n\n";
717
718 // Finish the enum, and drop the convert function after it.
719
720 OS << " NumConversionVariants\n";
721 OS << "};\n\n";
722
Daniel Dunbarce82b992009-08-08 05:24:34 +0000723 OS << CvtOS.str();
Daniel Dunbara54716c2009-07-31 02:32:59 +0000724}
725
Daniel Dunbar378bee92009-08-08 07:50:56 +0000726/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
727static void EmitMatchClassEnumeration(CodeGenTarget &Target,
728 std::vector<ClassInfo*> &Infos,
729 raw_ostream &OS) {
730 OS << "namespace {\n\n";
731
732 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
733 << "/// instruction matching.\n";
734 OS << "enum MatchClassKind {\n";
735 OS << " InvalidMatchClass = 0,\n";
736 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
737 ie = Infos.end(); it != ie; ++it) {
738 ClassInfo &CI = **it;
739 OS << " " << CI.Name << ", // ";
740 if (CI.Kind == ClassInfo::Token) {
741 OS << "'" << CI.ValueName << "'\n";
742 } else if (CI.Kind == ClassInfo::Register) {
743 if (!CI.ValueName.empty())
744 OS << "register class '" << CI.ValueName << "'\n";
745 else
746 OS << "derived register class\n";
747 } else {
748 OS << "user defined class '" << CI.ValueName << "'\n";
749 }
750 }
751 OS << " NumMatchClassKinds\n";
752 OS << "};\n\n";
753
754 OS << "}\n\n";
755}
756
Daniel Dunbar378bee92009-08-08 07:50:56 +0000757/// EmitClassifyOperand - Emit the function to classify an operand.
758static void EmitClassifyOperand(CodeGenTarget &Target,
759 std::vector<ClassInfo*> &Infos,
760 raw_ostream &OS) {
761 OS << "static MatchClassKind ClassifyOperand("
762 << Target.getName() << "Operand &Operand) {\n";
763 OS << " if (Operand.isToken())\n";
764 OS << " return MatchTokenString(Operand.getToken());\n\n";
765 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
766 ie = Infos.end(); it != ie; ++it) {
767 ClassInfo &CI = **it;
768
769 if (CI.Kind != ClassInfo::Token) {
770 OS << " if (Operand." << CI.PredicateMethod << "())\n";
771 OS << " return " << CI.Name << ";\n\n";
772 }
773 }
774 OS << " return InvalidMatchClass;\n";
775 OS << "}\n\n";
776}
777
Chris Lattner042926f2009-08-08 20:02:57 +0000778typedef std::pair<std::string, std::string> StringPair;
779
780/// FindFirstNonCommonLetter - Find the first character in the keys of the
781/// string pairs that is not shared across the whole set of strings. All
782/// strings are assumed to have the same length.
783static unsigned
784FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
785 assert(!Matches.empty());
786 for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
787 // Check to see if letter i is the same across the set.
788 char Letter = Matches[0]->first[i];
789
790 for (unsigned str = 0, e = Matches.size(); str != e; ++str)
791 if (Matches[str]->first[i] != Letter)
792 return i;
793 }
794
795 return Matches[0]->first.size();
796}
797
798/// EmitStringMatcherForChar - Given a set of strings that are known to be the
799/// same length and whose characters leading up to CharNo are the same, emit
800/// code to verify that CharNo and later are the same.
Daniel Dunbar7906a642009-08-08 22:57:25 +0000801///
802/// \return - True if control can leave the emitted code fragment.
803static bool EmitStringMatcherForChar(const std::string &StrVariableName,
Chris Lattner042926f2009-08-08 20:02:57 +0000804 const std::vector<const StringPair*> &Matches,
805 unsigned CharNo, unsigned IndentCount,
806 raw_ostream &OS) {
807 assert(!Matches.empty() && "Must have at least one string to match!");
808 std::string Indent(IndentCount*2+4, ' ');
809
810 // If we have verified that the entire string matches, we're done: output the
811 // matching code.
812 if (CharNo == Matches[0]->first.size()) {
813 assert(Matches.size() == 1 && "Had duplicate keys to match on");
814
815 // FIXME: If Matches[0].first has embeded \n, this will be bad.
816 OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
817 << "\"\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +0000818 return false;
Chris Lattner042926f2009-08-08 20:02:57 +0000819 }
820
821 // Bucket the matches by the character we are comparing.
822 std::map<char, std::vector<const StringPair*> > MatchesByLetter;
823
824 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
825 MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
826
827
828 // If we have exactly one bucket to match, see how many characters are common
829 // across the whole set and match all of them at once.
Chris Lattner042926f2009-08-08 20:02:57 +0000830 if (MatchesByLetter.size() == 1) {
831 unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
832 unsigned NumChars = FirstNonCommonLetter-CharNo;
833
Daniel Dunbar7906a642009-08-08 22:57:25 +0000834 // Emit code to break out if the prefix doesn't match.
Chris Lattner042926f2009-08-08 20:02:57 +0000835 if (NumChars == 1) {
Daniel Dunbar7906a642009-08-08 22:57:25 +0000836 // Do the comparison with if (Str[1] != 'f')
Chris Lattner042926f2009-08-08 20:02:57 +0000837 // FIXME: Need to escape general characters.
Daniel Dunbar7906a642009-08-08 22:57:25 +0000838 OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
839 << Matches[0]->first[CharNo] << "')\n";
840 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +0000841 } else {
Daniel Dunbar7906a642009-08-08 22:57:25 +0000842 // Do the comparison with if (Str.substr(1,3) != "foo").
Chris Lattner042926f2009-08-08 20:02:57 +0000843 // FIXME: Need to escape general strings.
Daniel Dunbar7906a642009-08-08 22:57:25 +0000844 OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
845 << NumChars << ") != \"";
846 OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
Daniel Dunbarda3a2292009-08-08 23:43:16 +0000847 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +0000848 }
849
Daniel Dunbar7906a642009-08-08 22:57:25 +0000850 return EmitStringMatcherForChar(StrVariableName, Matches,
851 FirstNonCommonLetter, IndentCount, OS);
Chris Lattner042926f2009-08-08 20:02:57 +0000852 }
853
854 // Otherwise, we have multiple possible things, emit a switch on the
855 // character.
856 OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
857 OS << Indent << "default: break;\n";
858
859 for (std::map<char, std::vector<const StringPair*> >::iterator LI =
860 MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
861 // TODO: escape hard stuff (like \n) if we ever care about it.
862 OS << Indent << "case '" << LI->first << "':\t // "
863 << LI->second.size() << " strings to match.\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +0000864 if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
865 IndentCount+1, OS))
866 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +0000867 }
868
869 OS << Indent << "}\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +0000870 return true;
Chris Lattner042926f2009-08-08 20:02:57 +0000871}
872
873
874/// EmitStringMatcher - Given a list of strings and code to execute when they
Daniel Dunbar7906a642009-08-08 22:57:25 +0000875/// match, output a simple switch tree to classify the input string.
876///
877/// If a match is found, the code in Vals[i].second is executed; control must
878/// not exit this code fragment. If nothing matches, execution falls through.
879///
880/// \param StrVariableName - The name of the variable to test.
Chris Lattner042926f2009-08-08 20:02:57 +0000881static void EmitStringMatcher(const std::string &StrVariableName,
882 const std::vector<StringPair> &Matches,
883 raw_ostream &OS) {
884 // First level categorization: group strings by length.
885 std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
886
887 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
888 MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
889
890 // Output a switch statement on length and categorize the elements within each
891 // bin.
892 OS << " switch (" << StrVariableName << ".size()) {\n";
893 OS << " default: break;\n";
894
Chris Lattner042926f2009-08-08 20:02:57 +0000895 for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
896 MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
897 OS << " case " << LI->first << ":\t // " << LI->second.size()
898 << " strings to match.\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +0000899 if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
900 OS << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +0000901 }
902
Chris Lattner042926f2009-08-08 20:02:57 +0000903 OS << " }\n";
904}
905
906
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +0000907/// EmitMatchTokenString - Emit the function to match a token string to the
908/// appropriate match class value.
909static void EmitMatchTokenString(CodeGenTarget &Target,
910 std::vector<ClassInfo*> &Infos,
911 raw_ostream &OS) {
912 // Construct the match list.
913 std::vector<StringPair> Matches;
914 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
915 ie = Infos.end(); it != ie; ++it) {
916 ClassInfo &CI = **it;
917
918 if (CI.Kind == ClassInfo::Token)
919 Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
920 }
921
922 OS << "static MatchClassKind MatchTokenString(const StringRef &Name) {\n";
923
924 EmitStringMatcher("Name", Matches, OS);
925
926 OS << " return InvalidMatchClass;\n";
927 OS << "}\n\n";
928}
Chris Lattner042926f2009-08-08 20:02:57 +0000929
Daniel Dunbar79f302e2009-08-07 21:01:44 +0000930/// EmitMatchRegisterName - Emit the function to match a string to the target
931/// specific register enum.
932static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
933 raw_ostream &OS) {
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +0000934 // Construct the match list.
Chris Lattner042926f2009-08-08 20:02:57 +0000935 std::vector<StringPair> Matches;
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +0000936 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
937 const CodeGenRegister &Reg = Target.getRegisters()[i];
Daniel Dunbar2f9876b2009-07-17 18:51:11 +0000938 if (Reg.TheDef->getValueAsString("AsmName").empty())
939 continue;
940
Chris Lattner042926f2009-08-08 20:02:57 +0000941 Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +0000942 "return " + utostr(i + 1) + ";"));
Daniel Dunbar2f9876b2009-07-17 18:51:11 +0000943 }
Chris Lattner042926f2009-08-08 20:02:57 +0000944
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +0000945 OS << "unsigned " << Target.getName()
946 << AsmParser->getValueAsString("AsmParserClassName")
947 << "::MatchRegisterName(const StringRef &Name) {\n";
948
Chris Lattner042926f2009-08-08 20:02:57 +0000949 EmitStringMatcher("Name", Matches, OS);
950
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +0000951 OS << " return 0;\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000952 OS << "}\n\n";
Daniel Dunbar79f302e2009-08-07 21:01:44 +0000953}
Daniel Dunbara54716c2009-07-31 02:32:59 +0000954
Daniel Dunbar79f302e2009-08-07 21:01:44 +0000955void AsmMatcherEmitter::run(raw_ostream &OS) {
956 CodeGenTarget Target;
957 Record *AsmParser = Target.getAsmParser();
958 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
959
960 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
961
962 // Emit the function to match a register name to number.
963 EmitMatchRegisterName(Target, AsmParser, OS);
964
Daniel Dunbar378bee92009-08-08 07:50:56 +0000965 // Compute the information on the instructions to match.
966 AsmMatcherInfo Info;
967 Info.BuildInfo(Target);
Daniel Dunbara54716c2009-07-31 02:32:59 +0000968
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000969 // Sort the instruction table using the partial order on classes.
970 std::sort(Info.Instructions.begin(), Info.Instructions.end(),
971 less_ptr<InstructionInfo>());
972
Daniel Dunbarce82b992009-08-08 05:24:34 +0000973 DEBUG_WITH_TYPE("instruction_info", {
Daniel Dunbar378bee92009-08-08 07:50:56 +0000974 for (std::vector<InstructionInfo*>::iterator
975 it = Info.Instructions.begin(), ie = Info.Instructions.end();
976 it != ie; ++it)
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000977 (*it)->dump();
978 });
Daniel Dunbara54716c2009-07-31 02:32:59 +0000979
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000980 // Check for ambiguous instructions.
981 unsigned NumAmbiguous = 0;
982 for (std::vector<InstructionInfo*>::const_iterator it =
983 Info.Instructions.begin(), ie = Info.Instructions.end() - 1;
984 it != ie;) {
985 InstructionInfo &II = **it;
986 ++it;
Daniel Dunbara54716c2009-07-31 02:32:59 +0000987
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000988 InstructionInfo &Next = **it;
989
990 if (!(II < Next)){
991 DEBUG_WITH_TYPE("ambiguous_instrs", {
992 errs() << "warning: ambiguous instruction match:\n";
993 II.dump();
994 errs() << "\nis incomparable with:\n";
995 Next.dump();
996 errs() << "\n\n";
997 });
998 ++NumAmbiguous;
999 }
1000 }
1001 if (NumAmbiguous)
1002 DEBUG_WITH_TYPE("ambiguous_instrs", {
1003 errs() << "warning: " << NumAmbiguous
1004 << " ambiguous instructions!\n";
1005 });
1006
1007 // Generate the unified function to convert operands into an MCInst.
1008 EmitConvertToMCInst(Target, Info.Instructions, OS);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001009
Daniel Dunbar378bee92009-08-08 07:50:56 +00001010 // Emit the enumeration for classes which participate in matching.
1011 EmitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001012
Daniel Dunbar378bee92009-08-08 07:50:56 +00001013 // Emit the routine to match token strings to their match class.
1014 EmitMatchTokenString(Target, Info.Classes, OS);
1015
1016 // Emit the routine to classify an operand.
1017 EmitClassifyOperand(Target, Info.Classes, OS);
1018
1019 // Finally, build the match function.
1020
1021 size_t MaxNumOperands = 0;
1022 for (std::vector<InstructionInfo*>::const_iterator it =
1023 Info.Instructions.begin(), ie = Info.Instructions.end();
1024 it != ie; ++it)
1025 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1026
Daniel Dunbara54716c2009-07-31 02:32:59 +00001027 OS << "bool " << Target.getName() << ClassName
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001028 << "::MatchInstruction("
Daniel Dunbara54716c2009-07-31 02:32:59 +00001029 << "SmallVectorImpl<" << Target.getName() << "Operand> &Operands, "
1030 << "MCInst &Inst) {\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001031
Daniel Dunbar378bee92009-08-08 07:50:56 +00001032 // Emit the static match table; unused classes get initalized to 0 which is
1033 // guaranteed to be InvalidMatchClass.
1034 //
1035 // FIXME: We can reduce the size of this table very easily. First, we change
1036 // it so that store the kinds in separate bit-fields for each index, which
1037 // only needs to be the max width used for classes at that index (we also need
1038 // to reject based on this during classification). If we then make sure to
1039 // order the match kinds appropriately (putting mnemonics last), then we
1040 // should only end up using a few bits for each class, especially the ones
1041 // following the mnemonic.
Chris Lattnerde024f82009-08-08 19:15:25 +00001042 OS << " static const struct MatchEntry {\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001043 OS << " unsigned Opcode;\n";
1044 OS << " ConversionKind ConvertFn;\n";
1045 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1046 OS << " } MatchTable[" << Info.Instructions.size() << "] = {\n";
1047
1048 for (std::vector<InstructionInfo*>::const_iterator it =
1049 Info.Instructions.begin(), ie = Info.Instructions.end();
1050 it != ie; ++it) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001051 InstructionInfo &II = **it;
1052
Daniel Dunbar378bee92009-08-08 07:50:56 +00001053 OS << " { " << Target.getName() << "::" << II.InstrName
1054 << ", " << II.ConversionFnKind << ", { ";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001055 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1056 InstructionInfo::Operand &Op = II.Operands[i];
1057
Daniel Dunbar378bee92009-08-08 07:50:56 +00001058 if (i) OS << ", ";
1059 OS << Op.Class->Name;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001060 }
Daniel Dunbar378bee92009-08-08 07:50:56 +00001061 OS << " } },\n";
Daniel Dunbara54716c2009-07-31 02:32:59 +00001062 }
1063
Daniel Dunbar378bee92009-08-08 07:50:56 +00001064 OS << " };\n\n";
1065
1066 // Emit code to compute the class list for this operand vector.
1067 OS << " // Eliminate obvious mismatches.\n";
1068 OS << " if (Operands.size() > " << MaxNumOperands << ")\n";
1069 OS << " return true;\n\n";
1070
1071 OS << " // Compute the class list for this operand vector.\n";
1072 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1073 OS << " for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1074 OS << " Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1075
1076 OS << " // Check for invalid operands before matching.\n";
1077 OS << " if (Classes[i] == InvalidMatchClass)\n";
1078 OS << " return true;\n";
1079 OS << " }\n\n";
1080
1081 OS << " // Mark unused classes.\n";
1082 OS << " for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1083 << "i != e; ++i)\n";
1084 OS << " Classes[i] = InvalidMatchClass;\n\n";
1085
1086 // Emit code to search the table.
1087 OS << " // Search the table.\n";
Chris Lattnerac3daf92009-08-08 19:16:05 +00001088 OS << " for (const MatchEntry *it = MatchTable, "
Daniel Dunbar378bee92009-08-08 07:50:56 +00001089 << "*ie = MatchTable + " << Info.Instructions.size()
1090 << "; it != ie; ++it) {\n";
1091 for (unsigned i = 0; i != MaxNumOperands; ++i) {
1092 OS << " if (Classes[" << i << "] != it->Classes[" << i << "])\n";
1093 OS << " continue;\n";
1094 }
1095 OS << "\n";
1096 OS << " return ConvertToMCInst(it->ConvertFn, Inst, "
1097 << "it->Opcode, Operands);\n";
1098 OS << " }\n\n";
1099
Daniel Dunbara54716c2009-07-31 02:32:59 +00001100 OS << " return true;\n";
1101 OS << "}\n\n";
Daniel Dunbar3f6e3ff2009-07-11 19:39:44 +00001102}