blob: 08353a4243b768f3de71c5c9faf25a4b57fa3fe6 [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
Daniel Dunbar7fa469a2009-08-09 08:19:00 +0000228 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
229 //
230 // FIXME: This is a total hack.
231 if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
232 return false;
233
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000234 // Ignore instructions with no .s string.
235 //
236 // FIXME: What are these?
237 if (CGI.AsmString.empty())
238 return false;
239
240 // FIXME: Hack; ignore any instructions with a newline in them.
241 if (std::find(CGI.AsmString.begin(),
242 CGI.AsmString.end(), '\n') != CGI.AsmString.end())
243 return false;
244
245 // Ignore instructions with attributes, these are always fake instructions for
246 // simplifying codegen.
247 //
248 // FIXME: Is this true?
249 //
250 // Also, we ignore instructions which reference the operand multiple times;
251 // this implies a constraint we would not currently honor. These are
252 // currently always fake instructions for simplifying codegen.
253 //
254 // FIXME: Encode this assumption in the .td, so we can error out here.
255 std::set<std::string> OperandNames;
256 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
257 if (Tokens[i][0] == '$' &&
258 std::find(Tokens[i].begin(),
259 Tokens[i].end(), ':') != Tokens[i].end()) {
260 DEBUG({
261 errs() << "warning: '" << Name << "': "
262 << "ignoring instruction; operand with attribute '"
263 << Tokens[i] << "', \n";
264 });
265 return false;
266 }
267
268 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
269 DEBUG({
270 errs() << "warning: '" << Name << "': "
271 << "ignoring instruction; tied operand '"
Daniel Dunbar33eec5d2009-08-09 06:05:33 +0000272 << Tokens[i] << "'\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000273 });
274 return false;
275 }
276 }
277
278 return true;
279}
280
281namespace {
282
Daniel Dunbar378bee92009-08-08 07:50:56 +0000283/// ClassInfo - Helper class for storing the information about a particular
284/// class of operands which can be matched.
285struct ClassInfo {
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000286 enum ClassInfoKind {
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000287 Invalid = 0, ///< Invalid kind, for use as a sentinel value.
288 Token, ///< The class for a particular token.
289 Register, ///< A register class.
290 UserClass0 ///< The (first) user defined class, subsequent user defined
291 /// classes are UserClass0+1, and so on.
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000292 };
293
294 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
295 /// N) for the Nth user defined class.
296 unsigned Kind;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000297
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000298 /// SuperClassKind - The super class kind for user classes.
299 unsigned SuperClassKind;
300
301 /// SuperClass - The super class, or 0.
302 ClassInfo *SuperClass;
303
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000304 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbar378bee92009-08-08 07:50:56 +0000305 std::string Name;
306
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000307 /// ClassName - The unadorned generic name for this class (e.g., Token).
308 std::string ClassName;
309
Daniel Dunbar378bee92009-08-08 07:50:56 +0000310 /// ValueName - The name of the value this class represents; for a token this
311 /// is the literal token string, for an operand it is the TableGen class (or
312 /// empty if this is a derived class).
313 std::string ValueName;
314
315 /// PredicateMethod - The name of the operand method to test whether the
316 /// operand matches this class; this is not valid for Token kinds.
317 std::string PredicateMethod;
318
319 /// RenderMethod - The name of the operand method to add this operand to an
320 /// MCInst; this is not valid for Token kinds.
321 std::string RenderMethod;
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000322
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000323 /// isUserClass() - Check if this is a user defined class.
324 bool isUserClass() const {
325 return Kind >= UserClass0;
326 }
327
328 /// getRootClass - Return the root class of this one.
329 const ClassInfo *getRootClass() const {
330 const ClassInfo *CI = this;
331 while (CI->SuperClass)
332 CI = CI->SuperClass;
333 return CI;
334 }
335
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000336 /// operator< - Compare two classes.
337 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000338 // Incompatible kinds are comparable for classes in disjoint hierarchies.
339 if (Kind != RHS.Kind && getRootClass() != RHS.getRootClass())
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000340 return Kind < RHS.Kind;
341
342 switch (Kind) {
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000343 case Invalid:
344 assert(0 && "Invalid kind!");
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000345 case Token:
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000346 // Tokens are comparable by value.
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000347 //
348 // FIXME: Compare by enum value.
349 return ValueName < RHS.ValueName;
350
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000351 default:
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000352 // This class preceeds the RHS if the RHS is a super class.
353 for (ClassInfo *Parent = SuperClass; Parent; Parent = Parent->SuperClass)
354 if (Parent == &RHS)
355 return true;
356
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000357 return false;
358 }
359 }
Daniel Dunbar378bee92009-08-08 07:50:56 +0000360};
361
Daniel Dunbarce82b992009-08-08 05:24:34 +0000362/// InstructionInfo - Helper class for storing the necessary information for an
363/// instruction which is capable of being matched.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000364struct InstructionInfo {
365 struct Operand {
Daniel Dunbar378bee92009-08-08 07:50:56 +0000366 /// The unique class instance this operand should match.
367 ClassInfo *Class;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000368
Daniel Dunbar378bee92009-08-08 07:50:56 +0000369 /// The original operand this corresponds to, if any.
Benjamin Kramer19afc502009-08-08 10:06:30 +0000370 const CodeGenInstruction::OperandInfo *OperandInfo;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000371 };
372
373 /// InstrName - The target name for this instruction.
374 std::string InstrName;
375
376 /// Instr - The instruction this matches.
377 const CodeGenInstruction *Instr;
378
379 /// AsmString - The assembly string for this instruction (with variants
380 /// removed).
381 std::string AsmString;
382
383 /// Tokens - The tokenized assembly pattern that this instruction matches.
384 SmallVector<StringRef, 4> Tokens;
385
386 /// Operands - The operands that this instruction matches.
387 SmallVector<Operand, 4> Operands;
388
Daniel Dunbarce82b992009-08-08 05:24:34 +0000389 /// ConversionFnKind - The enum value which is passed to the generated
390 /// ConvertToMCInst to convert parsed operands into an MCInst for this
391 /// function.
392 std::string ConversionFnKind;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000393
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000394 /// operator< - Compare two instructions.
395 bool operator<(const InstructionInfo &RHS) const {
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000396 if (Operands.size() != RHS.Operands.size())
397 return Operands.size() < RHS.Operands.size();
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000398
Daniel Dunbarfcf8e642009-08-09 08:23:23 +0000399 // Compare lexicographically by operand. The matcher validates that other
400 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
401 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000402 if (*Operands[i].Class < *RHS.Operands[i].Class)
403 return true;
Daniel Dunbarfcf8e642009-08-09 08:23:23 +0000404 if (*RHS.Operands[i].Class < *Operands[i].Class)
405 return false;
406 }
407
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000408 return false;
409 }
410
Daniel Dunbar33eec5d2009-08-09 06:05:33 +0000411 /// CouldMatchAmiguouslyWith - Check whether this instruction could
412 /// ambiguously match the same set of operands as \arg RHS (without being a
413 /// strictly superior match).
414 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
415 // The number of operands is unambiguous.
416 if (Operands.size() != RHS.Operands.size())
417 return false;
418
419 // Tokens and operand kinds are unambiguous (assuming a correct target
420 // specific parser).
421 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
422 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
423 Operands[i].Class->Kind == ClassInfo::Token)
424 if (*Operands[i].Class < *RHS.Operands[i].Class ||
425 *RHS.Operands[i].Class < *Operands[i].Class)
426 return false;
427
428 // Otherwise, this operand could commute if all operands are equivalent, or
429 // there is a pair of operands that compare less than and a pair that
430 // compare greater than.
431 bool HasLT = false, HasGT = false;
432 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
433 if (*Operands[i].Class < *RHS.Operands[i].Class)
434 HasLT = true;
435 if (*RHS.Operands[i].Class < *Operands[i].Class)
436 HasGT = true;
437 }
438
439 return !(HasLT ^ HasGT);
440 }
441
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000442public:
443 void dump();
444};
445
Daniel Dunbar378bee92009-08-08 07:50:56 +0000446class AsmMatcherInfo {
447public:
448 /// The classes which are needed for matching.
449 std::vector<ClassInfo*> Classes;
450
451 /// The information on the instruction to match.
452 std::vector<InstructionInfo*> Instructions;
453
454private:
455 /// Map of token to class information which has already been constructed.
456 std::map<std::string, ClassInfo*> TokenClasses;
457
458 /// Map of operand name to class information which has already been
459 /// constructed.
460 std::map<std::string, ClassInfo*> OperandClasses;
461
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000462 /// Map of user class names to kind value.
463 std::map<std::string, unsigned> UserClasses;
464
Daniel Dunbar378bee92009-08-08 07:50:56 +0000465private:
466 /// getTokenClass - Lookup or create the class for the given token.
467 ClassInfo *getTokenClass(const StringRef &Token);
468
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000469 /// getUserClassKind - Lookup or create the kind value for the given class
470 /// name.
471 unsigned getUserClassKind(const StringRef &Name);
472
Daniel Dunbar378bee92009-08-08 07:50:56 +0000473 /// getOperandClass - Lookup or create the class for the given operand.
474 ClassInfo *getOperandClass(const StringRef &Token,
475 const CodeGenInstruction::OperandInfo &OI);
476
477public:
478 /// BuildInfo - Construct the various tables used during matching.
479 void BuildInfo(CodeGenTarget &Target);
480};
481
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000482}
483
484void InstructionInfo::dump() {
485 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
486 << ", tokens:[";
487 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
488 errs() << Tokens[i];
489 if (i + 1 != e)
490 errs() << ", ";
491 }
492 errs() << "]\n";
493
494 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
495 Operand &Op = Operands[i];
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000496 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Daniel Dunbar378bee92009-08-08 07:50:56 +0000497 if (Op.Class->Kind == ClassInfo::Token) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000498 errs() << '\"' << Tokens[i] << "\"\n";
499 continue;
500 }
501
Benjamin Kramer19afc502009-08-08 10:06:30 +0000502 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000503 errs() << OI.Name << " " << OI.Rec->getName()
504 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
505 }
506}
507
Daniel Dunbar378bee92009-08-08 07:50:56 +0000508static std::string getEnumNameForToken(const StringRef &Str) {
509 std::string Res;
510
511 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
512 switch (*it) {
513 case '*': Res += "_STAR_"; break;
514 case '%': Res += "_PCT_"; break;
515 case ':': Res += "_COLON_"; break;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000516
Daniel Dunbar378bee92009-08-08 07:50:56 +0000517 default:
518 if (isalnum(*it)) {
519 Res += *it;
520 } else {
521 Res += "_" + utostr((unsigned) *it) + "_";
522 }
523 }
524 }
525
526 return Res;
527}
528
529ClassInfo *AsmMatcherInfo::getTokenClass(const StringRef &Token) {
530 ClassInfo *&Entry = TokenClasses[Token];
531
532 if (!Entry) {
533 Entry = new ClassInfo();
534 Entry->Kind = ClassInfo::Token;
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000535 Entry->ClassName = "Token";
Daniel Dunbar378bee92009-08-08 07:50:56 +0000536 Entry->Name = "MCK_" + getEnumNameForToken(Token);
537 Entry->ValueName = Token;
538 Entry->PredicateMethod = "<invalid>";
539 Entry->RenderMethod = "<invalid>";
540 Classes.push_back(Entry);
541 }
542
543 return Entry;
544}
545
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000546unsigned AsmMatcherInfo::getUserClassKind(const StringRef &Name) {
547 unsigned &Entry = UserClasses[Name];
548
549 if (!Entry)
550 Entry = ClassInfo::UserClass0 + UserClasses.size() - 1;
551
552 return Entry;
553}
554
Daniel Dunbar378bee92009-08-08 07:50:56 +0000555ClassInfo *
556AsmMatcherInfo::getOperandClass(const StringRef &Token,
557 const CodeGenInstruction::OperandInfo &OI) {
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000558 unsigned SuperClass = ClassInfo::Invalid;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000559 std::string ClassName;
560 if (OI.Rec->isSubClassOf("RegisterClass")) {
561 ClassName = "Reg";
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000562 } else {
563 try {
564 ClassName = OI.Rec->getValueAsString("ParserMatchClass");
565 assert(ClassName != "Reg" && "'Reg' class name is reserved!");
566 } catch(...) {
567 PrintError(OI.Rec->getLoc(), "operand has no match class!");
568 ClassName = "Invalid";
Daniel Dunbar378bee92009-08-08 07:50:56 +0000569 }
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000570
571 // Determine the super class.
572 try {
573 std::string SuperClassName =
574 OI.Rec->getValueAsString("ParserMatchSuperClass");
575 SuperClass = getUserClassKind(SuperClassName);
576 } catch(...) { }
Daniel Dunbar378bee92009-08-08 07:50:56 +0000577 }
578
579 ClassInfo *&Entry = OperandClasses[ClassName];
580
581 if (!Entry) {
582 Entry = new ClassInfo();
Daniel Dunbar378bee92009-08-08 07:50:56 +0000583 if (ClassName == "Reg") {
584 Entry->Kind = ClassInfo::Register;
Daniel Dunbar7fa469a2009-08-09 08:19:00 +0000585 Entry->SuperClassKind = SuperClass;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000586 } else {
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000587 Entry->Kind = getUserClassKind(ClassName);
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000588 Entry->SuperClassKind = SuperClass;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000589 }
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000590 Entry->ClassName = ClassName;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000591 Entry->Name = "MCK_" + ClassName;
592 Entry->ValueName = OI.Rec->getName();
593 Entry->PredicateMethod = "is" + ClassName;
594 Entry->RenderMethod = "add" + ClassName + "Operands";
595 Classes.push_back(Entry);
Daniel Dunbar7fa469a2009-08-09 08:19:00 +0000596 } else {
597 // Verify the super class matches.
598 assert(SuperClass == Entry->SuperClassKind &&
599 "Cannot redefine super class kind!");
Daniel Dunbar378bee92009-08-08 07:50:56 +0000600 }
601
602 return Entry;
603}
604
605void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000606 for (std::map<std::string, CodeGenInstruction>::const_iterator
Daniel Dunbar378bee92009-08-08 07:50:56 +0000607 it = Target.getInstructions().begin(),
608 ie = Target.getInstructions().end();
609 it != ie; ++it) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000610 const CodeGenInstruction &CGI = it->second;
611
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000612 if (!StringRef(it->first).startswith(MatchPrefix))
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000613 continue;
614
615 OwningPtr<InstructionInfo> II(new InstructionInfo);
616
617 II->InstrName = it->first;
618 II->Instr = &it->second;
619 II->AsmString = FlattenVariants(CGI.AsmString, 0);
620
621 TokenizeAsmString(II->AsmString, II->Tokens);
622
623 // Ignore instructions which shouldn't be matched.
624 if (!IsAssemblerInstruction(it->first, CGI, II->Tokens))
625 continue;
626
627 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
628 StringRef Token = II->Tokens[i];
629
630 // Check for simple tokens.
631 if (Token[0] != '$') {
632 InstructionInfo::Operand Op;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000633 Op.Class = getTokenClass(Token);
Benjamin Kramer19afc502009-08-08 10:06:30 +0000634 Op.OperandInfo = 0;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000635 II->Operands.push_back(Op);
636 continue;
637 }
638
639 // Otherwise this is an operand reference.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000640 StringRef OperandName;
641 if (Token[1] == '{')
642 OperandName = Token.substr(2, Token.size() - 3);
643 else
644 OperandName = Token.substr(1);
645
646 // Map this token to an operand. FIXME: Move elsewhere.
647 unsigned Idx;
648 try {
649 Idx = CGI.getOperandNamed(OperandName);
650 } catch(...) {
651 errs() << "error: unable to find operand: '" << OperandName << "'!\n";
652 break;
653 }
654
655 const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx];
Daniel Dunbar378bee92009-08-08 07:50:56 +0000656 InstructionInfo::Operand Op;
657 Op.Class = getOperandClass(Token, OI);
Benjamin Kramer19afc502009-08-08 10:06:30 +0000658 Op.OperandInfo = &OI;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000659 II->Operands.push_back(Op);
660 }
661
662 // If we broke out, ignore the instruction.
663 if (II->Operands.size() != II->Tokens.size())
664 continue;
665
Daniel Dunbar378bee92009-08-08 07:50:56 +0000666 Instructions.push_back(II.take());
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000667 }
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000668
669 // Bind user super classes.
670 std::map<unsigned, ClassInfo*> UserClasses;
671 for (unsigned i = 0, e = Classes.size(); i != e; ++i) {
672 ClassInfo &CI = *Classes[i];
673 if (CI.isUserClass())
674 UserClasses[CI.Kind] = &CI;
675 }
676
677 for (unsigned i = 0, e = Classes.size(); i != e; ++i) {
678 ClassInfo &CI = *Classes[i];
679 if (CI.isUserClass() && CI.SuperClassKind != ClassInfo::Invalid) {
680 CI.SuperClass = UserClasses[CI.SuperClassKind];
681 assert(CI.SuperClass && "Missing super class definition!");
682 } else {
683 CI.SuperClass = 0;
684 }
685 }
686
687 // Reorder classes so that classes preceed super classes.
688 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000689}
690
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000691static void EmitConvertToMCInst(CodeGenTarget &Target,
692 std::vector<InstructionInfo*> &Infos,
693 raw_ostream &OS) {
Daniel Dunbarce82b992009-08-08 05:24:34 +0000694 // Write the convert function to a separate stream, so we can drop it after
695 // the enum.
696 std::string ConvertFnBody;
697 raw_string_ostream CvtOS(ConvertFnBody);
698
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000699 // Function we have already generated.
700 std::set<std::string> GeneratedFns;
701
Daniel Dunbarce82b992009-08-08 05:24:34 +0000702 // Start the unified conversion function.
703
704 CvtOS << "static bool ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
705 << "unsigned Opcode,\n"
706 << " SmallVectorImpl<"
707 << Target.getName() << "Operand> &Operands) {\n";
708 CvtOS << " Inst.setOpcode(Opcode);\n";
709 CvtOS << " switch (Kind) {\n";
710 CvtOS << " default:\n";
711
712 // Start the enum, which we will generate inline.
713
714 OS << "// Unified function for converting operants to MCInst instances.\n\n";
Daniel Dunbarce82b992009-08-08 05:24:34 +0000715 OS << "enum ConversionKind {\n";
716
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000717 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
718 ie = Infos.end(); it != ie; ++it) {
719 InstructionInfo &II = **it;
720
721 // Order the (class) operands by the order to convert them into an MCInst.
722 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
723 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
724 InstructionInfo::Operand &Op = II.Operands[i];
Benjamin Kramer19afc502009-08-08 10:06:30 +0000725 if (Op.OperandInfo)
726 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000727 }
728 std::sort(MIOperandList.begin(), MIOperandList.end());
729
730 // Compute the total number of operands.
731 unsigned NumMIOperands = 0;
732 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
733 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
734 NumMIOperands = std::max(NumMIOperands,
735 OI.MIOperandNo + OI.MINumOperands);
736 }
737
738 // Build the conversion function signature.
739 std::string Signature = "Convert";
740 unsigned CurIndex = 0;
741 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
742 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
Benjamin Kramer19afc502009-08-08 10:06:30 +0000743 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000744 "Duplicate match for instruction operand!");
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000745
Daniel Dunbarce82b992009-08-08 05:24:34 +0000746 Signature += "_";
747
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000748 // Skip operands which weren't matched by anything, this occurs when the
749 // .td file encodes "implicit" operands as explicit ones.
750 //
751 // FIXME: This should be removed from the MCInst structure.
Benjamin Kramer19afc502009-08-08 10:06:30 +0000752 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000753 Signature += "Imp";
754
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000755 Signature += Op.Class->ClassName;
Benjamin Kramer19afc502009-08-08 10:06:30 +0000756 Signature += utostr(Op.OperandInfo->MINumOperands);
Daniel Dunbarce82b992009-08-08 05:24:34 +0000757 Signature += "_" + utostr(MIOperandList[i].second);
758
Benjamin Kramer19afc502009-08-08 10:06:30 +0000759 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000760 }
761
762 // Add any trailing implicit operands.
763 for (; CurIndex != NumMIOperands; ++CurIndex)
764 Signature += "Imp";
765
Daniel Dunbarce82b992009-08-08 05:24:34 +0000766 II.ConversionFnKind = Signature;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000767
Daniel Dunbarce82b992009-08-08 05:24:34 +0000768 // Check if we have already generated this signature.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000769 if (!GeneratedFns.insert(Signature).second)
770 continue;
771
772 // If not, emit it now.
Daniel Dunbarce82b992009-08-08 05:24:34 +0000773
774 // Add to the enum list.
775 OS << " " << Signature << ",\n";
776
777 // And to the convert function.
778 CvtOS << " case " << Signature << ":\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000779 CurIndex = 0;
780 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
781 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
782
783 // Add the implicit operands.
Benjamin Kramer19afc502009-08-08 10:06:30 +0000784 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
Daniel Dunbarce82b992009-08-08 05:24:34 +0000785 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000786
Daniel Dunbarce82b992009-08-08 05:24:34 +0000787 CvtOS << " Operands[" << MIOperandList[i].second
Daniel Dunbar378bee92009-08-08 07:50:56 +0000788 << "]." << Op.Class->RenderMethod
Benjamin Kramer19afc502009-08-08 10:06:30 +0000789 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
790 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000791 }
792
793 // And add trailing implicit operands.
794 for (; CurIndex != NumMIOperands; ++CurIndex)
Daniel Dunbarce82b992009-08-08 05:24:34 +0000795 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
796 CvtOS << " break;\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000797 }
Daniel Dunbarce82b992009-08-08 05:24:34 +0000798
799 // Finish the convert function.
800
801 CvtOS << " }\n";
802 CvtOS << " return false;\n";
803 CvtOS << "}\n\n";
804
805 // Finish the enum, and drop the convert function after it.
806
807 OS << " NumConversionVariants\n";
808 OS << "};\n\n";
809
Daniel Dunbarce82b992009-08-08 05:24:34 +0000810 OS << CvtOS.str();
Daniel Dunbara54716c2009-07-31 02:32:59 +0000811}
812
Daniel Dunbar378bee92009-08-08 07:50:56 +0000813/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
814static void EmitMatchClassEnumeration(CodeGenTarget &Target,
815 std::vector<ClassInfo*> &Infos,
816 raw_ostream &OS) {
817 OS << "namespace {\n\n";
818
819 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
820 << "/// instruction matching.\n";
821 OS << "enum MatchClassKind {\n";
822 OS << " InvalidMatchClass = 0,\n";
823 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
824 ie = Infos.end(); it != ie; ++it) {
825 ClassInfo &CI = **it;
826 OS << " " << CI.Name << ", // ";
827 if (CI.Kind == ClassInfo::Token) {
828 OS << "'" << CI.ValueName << "'\n";
829 } else if (CI.Kind == ClassInfo::Register) {
830 if (!CI.ValueName.empty())
831 OS << "register class '" << CI.ValueName << "'\n";
832 else
833 OS << "derived register class\n";
834 } else {
835 OS << "user defined class '" << CI.ValueName << "'\n";
836 }
837 }
838 OS << " NumMatchClassKinds\n";
839 OS << "};\n\n";
840
841 OS << "}\n\n";
842}
843
Daniel Dunbar378bee92009-08-08 07:50:56 +0000844/// EmitClassifyOperand - Emit the function to classify an operand.
845static void EmitClassifyOperand(CodeGenTarget &Target,
846 std::vector<ClassInfo*> &Infos,
847 raw_ostream &OS) {
848 OS << "static MatchClassKind ClassifyOperand("
849 << Target.getName() << "Operand &Operand) {\n";
850 OS << " if (Operand.isToken())\n";
851 OS << " return MatchTokenString(Operand.getToken());\n\n";
852 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
853 ie = Infos.end(); it != ie; ++it) {
854 ClassInfo &CI = **it;
855
856 if (CI.Kind != ClassInfo::Token) {
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000857 OS << " // '" << CI.ClassName << "' class";
858 if (CI.SuperClass) {
859 OS << ", subclass of '" << CI.SuperClass->ClassName << "'";
860 assert(CI < *CI.SuperClass && "Invalid class relation!");
861 }
862 OS << "\n";
863
864 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
865
866 // Validate subclass relationships.
867 if (CI.SuperClass)
868 OS << " assert(Operand." << CI.SuperClass->PredicateMethod
869 << "() && \"Invalid class relationship!\");\n";
870
Daniel Dunbar378bee92009-08-08 07:50:56 +0000871 OS << " return " << CI.Name << ";\n\n";
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000872 OS << " }";
Daniel Dunbar378bee92009-08-08 07:50:56 +0000873 }
874 }
875 OS << " return InvalidMatchClass;\n";
876 OS << "}\n\n";
877}
878
Daniel Dunbar14a77d42009-08-10 16:05:47 +0000879/// EmitIsSubclass - Emit the subclass predicate function.
880static void EmitIsSubclass(CodeGenTarget &Target,
881 std::vector<ClassInfo*> &Infos,
882 raw_ostream &OS) {
883 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
884 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
885 OS << " if (A == B)\n";
886 OS << " return true;\n\n";
887
888 OS << " switch (A) {\n";
889 OS << " default:\n";
890 OS << " return false;\n";
891 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
892 ie = Infos.end(); it != ie; ++it) {
893 ClassInfo &A = **it;
894
895 if (A.Kind != ClassInfo::Token) {
896 std::vector<StringRef> SuperClasses;
897 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
898 ie = Infos.end(); it != ie; ++it) {
899 ClassInfo &B = **it;
900
901 if (&A != &B && A.getRootClass() == B.getRootClass() && A < B)
902 SuperClasses.push_back(B.Name);
903 }
904
905 if (SuperClasses.empty())
906 continue;
907
908 OS << "\n case " << A.Name << ":\n";
909
910 if (SuperClasses.size() == 1) {
911 OS << " return B == " << SuperClasses.back() << ";\n\n";
912 continue;
913 }
914
915 OS << " switch (B) {\n";
916 OS << " default: return false;\n";
917 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
918 OS << " case " << SuperClasses[i] << ": return true;\n";
919 OS << " }\n\n";
920 }
921 }
922 OS << " }\n";
923 OS << "}\n\n";
924}
925
Chris Lattner042926f2009-08-08 20:02:57 +0000926typedef std::pair<std::string, std::string> StringPair;
927
928/// FindFirstNonCommonLetter - Find the first character in the keys of the
929/// string pairs that is not shared across the whole set of strings. All
930/// strings are assumed to have the same length.
931static unsigned
932FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
933 assert(!Matches.empty());
934 for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
935 // Check to see if letter i is the same across the set.
936 char Letter = Matches[0]->first[i];
937
938 for (unsigned str = 0, e = Matches.size(); str != e; ++str)
939 if (Matches[str]->first[i] != Letter)
940 return i;
941 }
942
943 return Matches[0]->first.size();
944}
945
946/// EmitStringMatcherForChar - Given a set of strings that are known to be the
947/// same length and whose characters leading up to CharNo are the same, emit
948/// code to verify that CharNo and later are the same.
Daniel Dunbar7906a642009-08-08 22:57:25 +0000949///
950/// \return - True if control can leave the emitted code fragment.
951static bool EmitStringMatcherForChar(const std::string &StrVariableName,
Chris Lattner042926f2009-08-08 20:02:57 +0000952 const std::vector<const StringPair*> &Matches,
953 unsigned CharNo, unsigned IndentCount,
954 raw_ostream &OS) {
955 assert(!Matches.empty() && "Must have at least one string to match!");
956 std::string Indent(IndentCount*2+4, ' ');
957
958 // If we have verified that the entire string matches, we're done: output the
959 // matching code.
960 if (CharNo == Matches[0]->first.size()) {
961 assert(Matches.size() == 1 && "Had duplicate keys to match on");
962
963 // FIXME: If Matches[0].first has embeded \n, this will be bad.
964 OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
965 << "\"\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +0000966 return false;
Chris Lattner042926f2009-08-08 20:02:57 +0000967 }
968
969 // Bucket the matches by the character we are comparing.
970 std::map<char, std::vector<const StringPair*> > MatchesByLetter;
971
972 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
973 MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
974
975
976 // If we have exactly one bucket to match, see how many characters are common
977 // across the whole set and match all of them at once.
Chris Lattner042926f2009-08-08 20:02:57 +0000978 if (MatchesByLetter.size() == 1) {
979 unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
980 unsigned NumChars = FirstNonCommonLetter-CharNo;
981
Daniel Dunbar7906a642009-08-08 22:57:25 +0000982 // Emit code to break out if the prefix doesn't match.
Chris Lattner042926f2009-08-08 20:02:57 +0000983 if (NumChars == 1) {
Daniel Dunbar7906a642009-08-08 22:57:25 +0000984 // Do the comparison with if (Str[1] != 'f')
Chris Lattner042926f2009-08-08 20:02:57 +0000985 // FIXME: Need to escape general characters.
Daniel Dunbar7906a642009-08-08 22:57:25 +0000986 OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
987 << Matches[0]->first[CharNo] << "')\n";
988 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +0000989 } else {
Daniel Dunbar7906a642009-08-08 22:57:25 +0000990 // Do the comparison with if (Str.substr(1,3) != "foo").
Chris Lattner042926f2009-08-08 20:02:57 +0000991 // FIXME: Need to escape general strings.
Daniel Dunbar7906a642009-08-08 22:57:25 +0000992 OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
993 << NumChars << ") != \"";
994 OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
Daniel Dunbarda3a2292009-08-08 23:43:16 +0000995 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +0000996 }
997
Daniel Dunbar7906a642009-08-08 22:57:25 +0000998 return EmitStringMatcherForChar(StrVariableName, Matches,
999 FirstNonCommonLetter, IndentCount, OS);
Chris Lattner042926f2009-08-08 20:02:57 +00001000 }
1001
1002 // Otherwise, we have multiple possible things, emit a switch on the
1003 // character.
1004 OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
1005 OS << Indent << "default: break;\n";
1006
1007 for (std::map<char, std::vector<const StringPair*> >::iterator LI =
1008 MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
1009 // TODO: escape hard stuff (like \n) if we ever care about it.
1010 OS << Indent << "case '" << LI->first << "':\t // "
1011 << LI->second.size() << " strings to match.\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001012 if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
1013 IndentCount+1, OS))
1014 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001015 }
1016
1017 OS << Indent << "}\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001018 return true;
Chris Lattner042926f2009-08-08 20:02:57 +00001019}
1020
1021
1022/// EmitStringMatcher - Given a list of strings and code to execute when they
Daniel Dunbar7906a642009-08-08 22:57:25 +00001023/// match, output a simple switch tree to classify the input string.
1024///
1025/// If a match is found, the code in Vals[i].second is executed; control must
1026/// not exit this code fragment. If nothing matches, execution falls through.
1027///
1028/// \param StrVariableName - The name of the variable to test.
Chris Lattner042926f2009-08-08 20:02:57 +00001029static void EmitStringMatcher(const std::string &StrVariableName,
1030 const std::vector<StringPair> &Matches,
1031 raw_ostream &OS) {
1032 // First level categorization: group strings by length.
1033 std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
1034
1035 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1036 MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
1037
1038 // Output a switch statement on length and categorize the elements within each
1039 // bin.
1040 OS << " switch (" << StrVariableName << ".size()) {\n";
1041 OS << " default: break;\n";
1042
Chris Lattner042926f2009-08-08 20:02:57 +00001043 for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
1044 MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
1045 OS << " case " << LI->first << ":\t // " << LI->second.size()
1046 << " strings to match.\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001047 if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
1048 OS << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001049 }
1050
Chris Lattner042926f2009-08-08 20:02:57 +00001051 OS << " }\n";
1052}
1053
1054
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001055/// EmitMatchTokenString - Emit the function to match a token string to the
1056/// appropriate match class value.
1057static void EmitMatchTokenString(CodeGenTarget &Target,
1058 std::vector<ClassInfo*> &Infos,
1059 raw_ostream &OS) {
1060 // Construct the match list.
1061 std::vector<StringPair> Matches;
1062 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1063 ie = Infos.end(); it != ie; ++it) {
1064 ClassInfo &CI = **it;
1065
1066 if (CI.Kind == ClassInfo::Token)
1067 Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
1068 }
1069
1070 OS << "static MatchClassKind MatchTokenString(const StringRef &Name) {\n";
1071
1072 EmitStringMatcher("Name", Matches, OS);
1073
1074 OS << " return InvalidMatchClass;\n";
1075 OS << "}\n\n";
1076}
Chris Lattner042926f2009-08-08 20:02:57 +00001077
Daniel Dunbar79f302e2009-08-07 21:01:44 +00001078/// EmitMatchRegisterName - Emit the function to match a string to the target
1079/// specific register enum.
1080static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1081 raw_ostream &OS) {
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001082 // Construct the match list.
Chris Lattner042926f2009-08-08 20:02:57 +00001083 std::vector<StringPair> Matches;
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001084 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1085 const CodeGenRegister &Reg = Target.getRegisters()[i];
Daniel Dunbar2f9876b2009-07-17 18:51:11 +00001086 if (Reg.TheDef->getValueAsString("AsmName").empty())
1087 continue;
1088
Chris Lattner042926f2009-08-08 20:02:57 +00001089 Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001090 "return " + utostr(i + 1) + ";"));
Daniel Dunbar2f9876b2009-07-17 18:51:11 +00001091 }
Chris Lattner042926f2009-08-08 20:02:57 +00001092
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001093 OS << "unsigned " << Target.getName()
1094 << AsmParser->getValueAsString("AsmParserClassName")
1095 << "::MatchRegisterName(const StringRef &Name) {\n";
1096
Chris Lattner042926f2009-08-08 20:02:57 +00001097 EmitStringMatcher("Name", Matches, OS);
1098
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001099 OS << " return 0;\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001100 OS << "}\n\n";
Daniel Dunbar79f302e2009-08-07 21:01:44 +00001101}
Daniel Dunbara54716c2009-07-31 02:32:59 +00001102
Daniel Dunbar79f302e2009-08-07 21:01:44 +00001103void AsmMatcherEmitter::run(raw_ostream &OS) {
1104 CodeGenTarget Target;
1105 Record *AsmParser = Target.getAsmParser();
1106 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1107
1108 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1109
1110 // Emit the function to match a register name to number.
1111 EmitMatchRegisterName(Target, AsmParser, OS);
1112
Daniel Dunbar378bee92009-08-08 07:50:56 +00001113 // Compute the information on the instructions to match.
1114 AsmMatcherInfo Info;
1115 Info.BuildInfo(Target);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001116
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001117 // Sort the instruction table using the partial order on classes.
1118 std::sort(Info.Instructions.begin(), Info.Instructions.end(),
1119 less_ptr<InstructionInfo>());
1120
Daniel Dunbarce82b992009-08-08 05:24:34 +00001121 DEBUG_WITH_TYPE("instruction_info", {
Daniel Dunbar378bee92009-08-08 07:50:56 +00001122 for (std::vector<InstructionInfo*>::iterator
1123 it = Info.Instructions.begin(), ie = Info.Instructions.end();
1124 it != ie; ++it)
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001125 (*it)->dump();
1126 });
Daniel Dunbara54716c2009-07-31 02:32:59 +00001127
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001128 // Check for ambiguous instructions.
1129 unsigned NumAmbiguous = 0;
Daniel Dunbar33eec5d2009-08-09 06:05:33 +00001130 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1131 for (unsigned j = i + 1; j != e; ++j) {
1132 InstructionInfo &A = *Info.Instructions[i];
1133 InstructionInfo &B = *Info.Instructions[j];
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001134
Daniel Dunbar33eec5d2009-08-09 06:05:33 +00001135 if (A.CouldMatchAmiguouslyWith(B)) {
1136 DEBUG_WITH_TYPE("ambiguous_instrs", {
1137 errs() << "warning: ambiguous instruction match:\n";
1138 A.dump();
1139 errs() << "\nis incomparable with:\n";
1140 B.dump();
1141 errs() << "\n\n";
1142 });
1143 ++NumAmbiguous;
1144 }
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001145 }
1146 }
1147 if (NumAmbiguous)
1148 DEBUG_WITH_TYPE("ambiguous_instrs", {
1149 errs() << "warning: " << NumAmbiguous
1150 << " ambiguous instructions!\n";
1151 });
1152
1153 // Generate the unified function to convert operands into an MCInst.
1154 EmitConvertToMCInst(Target, Info.Instructions, OS);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001155
Daniel Dunbar378bee92009-08-08 07:50:56 +00001156 // Emit the enumeration for classes which participate in matching.
1157 EmitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001158
Daniel Dunbar378bee92009-08-08 07:50:56 +00001159 // Emit the routine to match token strings to their match class.
1160 EmitMatchTokenString(Target, Info.Classes, OS);
1161
1162 // Emit the routine to classify an operand.
1163 EmitClassifyOperand(Target, Info.Classes, OS);
1164
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001165 // Emit the subclass predicate routine.
1166 EmitIsSubclass(Target, Info.Classes, OS);
1167
Daniel Dunbar378bee92009-08-08 07:50:56 +00001168 // Finally, build the match function.
1169
1170 size_t MaxNumOperands = 0;
1171 for (std::vector<InstructionInfo*>::const_iterator it =
1172 Info.Instructions.begin(), ie = Info.Instructions.end();
1173 it != ie; ++it)
1174 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1175
Daniel Dunbara54716c2009-07-31 02:32:59 +00001176 OS << "bool " << Target.getName() << ClassName
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001177 << "::MatchInstruction("
Daniel Dunbara54716c2009-07-31 02:32:59 +00001178 << "SmallVectorImpl<" << Target.getName() << "Operand> &Operands, "
1179 << "MCInst &Inst) {\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001180
Daniel Dunbar378bee92009-08-08 07:50:56 +00001181 // Emit the static match table; unused classes get initalized to 0 which is
1182 // guaranteed to be InvalidMatchClass.
1183 //
1184 // FIXME: We can reduce the size of this table very easily. First, we change
1185 // it so that store the kinds in separate bit-fields for each index, which
1186 // only needs to be the max width used for classes at that index (we also need
1187 // to reject based on this during classification). If we then make sure to
1188 // order the match kinds appropriately (putting mnemonics last), then we
1189 // should only end up using a few bits for each class, especially the ones
1190 // following the mnemonic.
Chris Lattnerde024f82009-08-08 19:15:25 +00001191 OS << " static const struct MatchEntry {\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001192 OS << " unsigned Opcode;\n";
1193 OS << " ConversionKind ConvertFn;\n";
1194 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1195 OS << " } MatchTable[" << Info.Instructions.size() << "] = {\n";
1196
1197 for (std::vector<InstructionInfo*>::const_iterator it =
1198 Info.Instructions.begin(), ie = Info.Instructions.end();
1199 it != ie; ++it) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001200 InstructionInfo &II = **it;
1201
Daniel Dunbar378bee92009-08-08 07:50:56 +00001202 OS << " { " << Target.getName() << "::" << II.InstrName
1203 << ", " << II.ConversionFnKind << ", { ";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001204 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1205 InstructionInfo::Operand &Op = II.Operands[i];
1206
Daniel Dunbar378bee92009-08-08 07:50:56 +00001207 if (i) OS << ", ";
1208 OS << Op.Class->Name;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001209 }
Daniel Dunbar378bee92009-08-08 07:50:56 +00001210 OS << " } },\n";
Daniel Dunbara54716c2009-07-31 02:32:59 +00001211 }
1212
Daniel Dunbar378bee92009-08-08 07:50:56 +00001213 OS << " };\n\n";
1214
1215 // Emit code to compute the class list for this operand vector.
1216 OS << " // Eliminate obvious mismatches.\n";
1217 OS << " if (Operands.size() > " << MaxNumOperands << ")\n";
1218 OS << " return true;\n\n";
1219
1220 OS << " // Compute the class list for this operand vector.\n";
1221 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1222 OS << " for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1223 OS << " Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1224
1225 OS << " // Check for invalid operands before matching.\n";
1226 OS << " if (Classes[i] == InvalidMatchClass)\n";
1227 OS << " return true;\n";
1228 OS << " }\n\n";
1229
1230 OS << " // Mark unused classes.\n";
1231 OS << " for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1232 << "i != e; ++i)\n";
1233 OS << " Classes[i] = InvalidMatchClass;\n\n";
1234
1235 // Emit code to search the table.
1236 OS << " // Search the table.\n";
Chris Lattnerac3daf92009-08-08 19:16:05 +00001237 OS << " for (const MatchEntry *it = MatchTable, "
Daniel Dunbar378bee92009-08-08 07:50:56 +00001238 << "*ie = MatchTable + " << Info.Instructions.size()
1239 << "; it != ie; ++it) {\n";
1240 for (unsigned i = 0; i != MaxNumOperands; ++i) {
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001241 OS << " if (!IsSubclass(Classes["
1242 << i << "], it->Classes[" << i << "]))\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001243 OS << " continue;\n";
1244 }
1245 OS << "\n";
1246 OS << " return ConvertToMCInst(it->ConvertFn, Inst, "
1247 << "it->Opcode, Operands);\n";
1248 OS << " }\n\n";
1249
Daniel Dunbara54716c2009-07-31 02:32:59 +00001250 OS << " return true;\n";
1251 OS << "}\n\n";
Daniel Dunbar3f6e3ff2009-07-11 19:39:44 +00001252}