blob: d02318e2292f66bbd7ffeca17703c090a73046df [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 Dunbar62beebc2009-08-07 20:33:39 +000090static cl::opt<std::string>
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +000091MatchPrefix("match-prefix", cl::init(""),
92 cl::desc("Only match instructions with the given prefix"));
Daniel Dunbarfe6759e2009-08-07 08:26:05 +000093
Daniel Dunbara54716c2009-07-31 02:32:59 +000094/// FlattenVariants - Flatten an .td file assembly string by selecting the
95/// variant at index \arg N.
96static std::string FlattenVariants(const std::string &AsmString,
97 unsigned N) {
98 StringRef Cur = AsmString;
99 std::string Res = "";
100
101 for (;;) {
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000102 // Find the start of the next variant string.
103 size_t VariantsStart = 0;
104 for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
105 if (Cur[VariantsStart] == '{' &&
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000106 (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
107 Cur[VariantsStart-1] != '\\')))
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000108 break;
Daniel Dunbara54716c2009-07-31 02:32:59 +0000109
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000110 // Add the prefix to the result.
111 Res += Cur.slice(0, VariantsStart);
112 if (VariantsStart == Cur.size())
Daniel Dunbara54716c2009-07-31 02:32:59 +0000113 break;
114
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000115 ++VariantsStart; // Skip the '{'.
116
117 // Scan to the end of the variants string.
118 size_t VariantsEnd = VariantsStart;
119 unsigned NestedBraces = 1;
120 for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000121 if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000122 if (--NestedBraces == 0)
123 break;
124 } else if (Cur[VariantsEnd] == '{')
125 ++NestedBraces;
126 }
Daniel Dunbara54716c2009-07-31 02:32:59 +0000127
128 // Select the Nth variant (or empty).
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000129 StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
Daniel Dunbara54716c2009-07-31 02:32:59 +0000130 for (unsigned i = 0; i != N; ++i)
131 Selection = Selection.split('|').second;
132 Res += Selection.split('|').first;
133
Daniel Dunbar815c7ab2009-08-04 20:36:45 +0000134 assert(VariantsEnd != Cur.size() &&
135 "Unterminated variants in assembly string!");
136 Cur = Cur.substr(VariantsEnd + 1);
Daniel Dunbara54716c2009-07-31 02:32:59 +0000137 }
138
139 return Res;
140}
141
142/// TokenizeAsmString - Tokenize a simplified assembly string.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000143static void TokenizeAsmString(const StringRef &AsmString,
Daniel Dunbara54716c2009-07-31 02:32:59 +0000144 SmallVectorImpl<StringRef> &Tokens) {
145 unsigned Prev = 0;
146 bool InTok = true;
147 for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {
148 switch (AsmString[i]) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000149 case '[':
150 case ']':
Daniel Dunbara54716c2009-07-31 02:32:59 +0000151 case '*':
152 case '!':
153 case ' ':
154 case '\t':
155 case ',':
156 if (InTok) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000157 Tokens.push_back(AsmString.slice(Prev, i));
Daniel Dunbara54716c2009-07-31 02:32:59 +0000158 InTok = false;
159 }
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000160 if (!isspace(AsmString[i]) && AsmString[i] != ',')
161 Tokens.push_back(AsmString.substr(i, 1));
Daniel Dunbara54716c2009-07-31 02:32:59 +0000162 Prev = i + 1;
163 break;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000164
165 case '\\':
166 if (InTok) {
167 Tokens.push_back(AsmString.slice(Prev, i));
168 InTok = false;
169 }
170 ++i;
171 assert(i != AsmString.size() && "Invalid quoted character");
172 Tokens.push_back(AsmString.substr(i, 1));
173 Prev = i + 1;
174 break;
175
176 case '$': {
177 // If this isn't "${", treat like a normal token.
178 if (i + 1 == AsmString.size() || AsmString[i + 1] != '{') {
179 if (InTok) {
180 Tokens.push_back(AsmString.slice(Prev, i));
181 InTok = false;
182 }
183 Prev = i;
184 break;
185 }
186
187 if (InTok) {
188 Tokens.push_back(AsmString.slice(Prev, i));
189 InTok = false;
190 }
191
192 StringRef::iterator End =
193 std::find(AsmString.begin() + i, AsmString.end(), '}');
194 assert(End != AsmString.end() && "Missing brace in operand reference!");
195 size_t EndPos = End - AsmString.begin();
196 Tokens.push_back(AsmString.slice(i, EndPos+1));
197 Prev = EndPos + 1;
198 i = EndPos;
199 break;
200 }
Daniel Dunbara54716c2009-07-31 02:32:59 +0000201
202 default:
203 InTok = true;
204 }
205 }
206 if (InTok && Prev != AsmString.size())
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000207 Tokens.push_back(AsmString.substr(Prev));
208}
209
210static bool IsAssemblerInstruction(const StringRef &Name,
211 const CodeGenInstruction &CGI,
212 const SmallVectorImpl<StringRef> &Tokens) {
213 // Ignore psuedo ops.
214 //
215 // FIXME: This is a hack.
216 if (const RecordVal *Form = CGI.TheDef->getValue("Form"))
217 if (Form->getValue()->getAsString() == "Pseudo")
218 return false;
219
220 // Ignore "PHI" node.
221 //
222 // FIXME: This is also a hack.
223 if (Name == "PHI")
224 return false;
225
Daniel Dunbar7fa469a2009-08-09 08:19:00 +0000226 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
227 //
228 // FIXME: This is a total hack.
229 if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
230 return false;
231
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000232 // Ignore instructions with no .s string.
233 //
234 // FIXME: What are these?
235 if (CGI.AsmString.empty())
236 return false;
237
238 // FIXME: Hack; ignore any instructions with a newline in them.
239 if (std::find(CGI.AsmString.begin(),
240 CGI.AsmString.end(), '\n') != CGI.AsmString.end())
241 return false;
242
243 // Ignore instructions with attributes, these are always fake instructions for
244 // simplifying codegen.
245 //
246 // FIXME: Is this true?
247 //
248 // Also, we ignore instructions which reference the operand multiple times;
249 // this implies a constraint we would not currently honor. These are
250 // currently always fake instructions for simplifying codegen.
251 //
252 // FIXME: Encode this assumption in the .td, so we can error out here.
253 std::set<std::string> OperandNames;
254 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
255 if (Tokens[i][0] == '$' &&
256 std::find(Tokens[i].begin(),
257 Tokens[i].end(), ':') != Tokens[i].end()) {
258 DEBUG({
259 errs() << "warning: '" << Name << "': "
260 << "ignoring instruction; operand with attribute '"
261 << Tokens[i] << "', \n";
262 });
263 return false;
264 }
265
266 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
267 DEBUG({
268 errs() << "warning: '" << Name << "': "
269 << "ignoring instruction; tied operand '"
Daniel Dunbar33eec5d2009-08-09 06:05:33 +0000270 << Tokens[i] << "'\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000271 });
272 return false;
273 }
274 }
275
276 return true;
277}
278
279namespace {
280
Daniel Dunbar378bee92009-08-08 07:50:56 +0000281/// ClassInfo - Helper class for storing the information about a particular
282/// class of operands which can be matched.
283struct ClassInfo {
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000284 enum ClassInfoKind {
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000285 /// Invalid kind, for use as a sentinel value.
286 Invalid = 0,
287
288 /// The class for a particular token.
289 Token,
290
291 /// The (first) register class, subsequent register classes are
292 /// RegisterClass0+1, and so on.
293 RegisterClass0,
294
295 /// The (first) user defined class, subsequent user defined classes are
296 /// UserClass0+1, and so on.
297 UserClass0 = 1<<16
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000298 };
299
300 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
301 /// N) for the Nth user defined class.
302 unsigned Kind;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000303
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000304 /// SuperClasses - The super classes of this class. Note that for simplicities
305 /// sake user operands only record their immediate super class, while register
306 /// operands include all superclasses.
307 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000308
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000309 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbar378bee92009-08-08 07:50:56 +0000310 std::string Name;
311
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000312 /// ClassName - The unadorned generic name for this class (e.g., Token).
313 std::string ClassName;
314
Daniel Dunbar378bee92009-08-08 07:50:56 +0000315 /// ValueName - The name of the value this class represents; for a token this
316 /// is the literal token string, for an operand it is the TableGen class (or
317 /// empty if this is a derived class).
318 std::string ValueName;
319
320 /// PredicateMethod - The name of the operand method to test whether the
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000321 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbar378bee92009-08-08 07:50:56 +0000322 std::string PredicateMethod;
323
324 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000325 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbar378bee92009-08-08 07:50:56 +0000326 std::string RenderMethod;
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000327
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000328 /// isRegisterClass() - Check if this is a register class.
329 bool isRegisterClass() const {
330 return Kind >= RegisterClass0 && Kind < UserClass0;
331 }
332
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000333 /// isUserClass() - Check if this is a user defined class.
334 bool isUserClass() const {
335 return Kind >= UserClass0;
336 }
337
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000338 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
339 /// are related if they are in the same class hierarchy.
340 bool isRelatedTo(const ClassInfo &RHS) const {
341 // Tokens are only related to tokens.
342 if (Kind == Token || RHS.Kind == Token)
343 return Kind == Token && RHS.Kind == Token;
344
345 // Registers are only related to registers.
346 if (isRegisterClass() || RHS.isRegisterClass())
347 return isRegisterClass() && RHS.isRegisterClass();
348
349 // Otherwise we have two users operands; they are related if they are in the
350 // same class hierarchy.
351 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
352 const ClassInfo *Root = this;
353 while (!Root->SuperClasses.empty())
354 Root = Root->SuperClasses.front();
355
356 const ClassInfo *RHSRoot = this;
357 while (!RHSRoot->SuperClasses.empty())
358 RHSRoot = RHSRoot->SuperClasses.front();
359
360 return Root == RHSRoot;
361 }
362
363 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
364 bool isSubsetOf(const ClassInfo &RHS) const {
365 // This is a subset of RHS if it is the same class...
366 if (this == &RHS)
367 return true;
368
369 // ... or if any of its super classes are a subset of RHS.
370 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
371 ie = SuperClasses.end(); it != ie; ++it)
372 if ((*it)->isSubsetOf(RHS))
373 return true;
374
375 return false;
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000376 }
377
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000378 /// operator< - Compare two classes.
379 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000380 // Unrelated classes can be ordered by kind.
381 if (!isRelatedTo(RHS))
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000382 return Kind < RHS.Kind;
383
384 switch (Kind) {
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000385 case Invalid:
386 assert(0 && "Invalid kind!");
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000387 case Token:
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000388 // Tokens are comparable by value.
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000389 //
390 // FIXME: Compare by enum value.
391 return ValueName < RHS.ValueName;
392
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000393 default:
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000394 // This class preceeds the RHS if it is a proper subset of the RHS.
395 return this != &RHS && isSubsetOf(RHS);
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000396 }
397 }
Daniel Dunbar378bee92009-08-08 07:50:56 +0000398};
399
Daniel Dunbarce82b992009-08-08 05:24:34 +0000400/// InstructionInfo - Helper class for storing the necessary information for an
401/// instruction which is capable of being matched.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000402struct InstructionInfo {
403 struct Operand {
Daniel Dunbar378bee92009-08-08 07:50:56 +0000404 /// The unique class instance this operand should match.
405 ClassInfo *Class;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000406
Daniel Dunbar378bee92009-08-08 07:50:56 +0000407 /// The original operand this corresponds to, if any.
Benjamin Kramer19afc502009-08-08 10:06:30 +0000408 const CodeGenInstruction::OperandInfo *OperandInfo;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000409 };
410
411 /// InstrName - The target name for this instruction.
412 std::string InstrName;
413
414 /// Instr - The instruction this matches.
415 const CodeGenInstruction *Instr;
416
417 /// AsmString - The assembly string for this instruction (with variants
418 /// removed).
419 std::string AsmString;
420
421 /// Tokens - The tokenized assembly pattern that this instruction matches.
422 SmallVector<StringRef, 4> Tokens;
423
424 /// Operands - The operands that this instruction matches.
425 SmallVector<Operand, 4> Operands;
426
Daniel Dunbarce82b992009-08-08 05:24:34 +0000427 /// ConversionFnKind - The enum value which is passed to the generated
428 /// ConvertToMCInst to convert parsed operands into an MCInst for this
429 /// function.
430 std::string ConversionFnKind;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000431
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000432 /// operator< - Compare two instructions.
433 bool operator<(const InstructionInfo &RHS) const {
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000434 if (Operands.size() != RHS.Operands.size())
435 return Operands.size() < RHS.Operands.size();
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000436
Daniel Dunbarfcf8e642009-08-09 08:23:23 +0000437 // Compare lexicographically by operand. The matcher validates that other
438 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
439 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000440 if (*Operands[i].Class < *RHS.Operands[i].Class)
441 return true;
Daniel Dunbarfcf8e642009-08-09 08:23:23 +0000442 if (*RHS.Operands[i].Class < *Operands[i].Class)
443 return false;
444 }
445
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000446 return false;
447 }
448
Daniel Dunbar33eec5d2009-08-09 06:05:33 +0000449 /// CouldMatchAmiguouslyWith - Check whether this instruction could
450 /// ambiguously match the same set of operands as \arg RHS (without being a
451 /// strictly superior match).
452 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
453 // The number of operands is unambiguous.
454 if (Operands.size() != RHS.Operands.size())
455 return false;
456
457 // Tokens and operand kinds are unambiguous (assuming a correct target
458 // specific parser).
459 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
460 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
461 Operands[i].Class->Kind == ClassInfo::Token)
462 if (*Operands[i].Class < *RHS.Operands[i].Class ||
463 *RHS.Operands[i].Class < *Operands[i].Class)
464 return false;
465
466 // Otherwise, this operand could commute if all operands are equivalent, or
467 // there is a pair of operands that compare less than and a pair that
468 // compare greater than.
469 bool HasLT = false, HasGT = false;
470 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
471 if (*Operands[i].Class < *RHS.Operands[i].Class)
472 HasLT = true;
473 if (*RHS.Operands[i].Class < *Operands[i].Class)
474 HasGT = true;
475 }
476
477 return !(HasLT ^ HasGT);
478 }
479
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000480public:
481 void dump();
482};
483
Daniel Dunbar378bee92009-08-08 07:50:56 +0000484class AsmMatcherInfo {
485public:
486 /// The classes which are needed for matching.
487 std::vector<ClassInfo*> Classes;
488
489 /// The information on the instruction to match.
490 std::vector<InstructionInfo*> Instructions;
491
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000492 /// Map of Register records to their class information.
493 std::map<Record*, ClassInfo*> RegisterClasses;
494
Daniel Dunbar378bee92009-08-08 07:50:56 +0000495private:
496 /// Map of token to class information which has already been constructed.
497 std::map<std::string, ClassInfo*> TokenClasses;
498
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000499 /// Map of RegisterClass records to their class information.
500 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000501
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000502 /// Map of AsmOperandClass records to their class information.
503 std::map<Record*, ClassInfo*> AsmOperandClasses;
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000504
Daniel Dunbar378bee92009-08-08 07:50:56 +0000505private:
506 /// getTokenClass - Lookup or create the class for the given token.
507 ClassInfo *getTokenClass(const StringRef &Token);
508
509 /// getOperandClass - Lookup or create the class for the given operand.
510 ClassInfo *getOperandClass(const StringRef &Token,
511 const CodeGenInstruction::OperandInfo &OI);
512
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000513 /// BuildRegisterClasses - Build the ClassInfo* instances for register
514 /// classes.
515 void BuildRegisterClasses(CodeGenTarget &Target);
516
517 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
518 /// operand classes.
519 void BuildOperandClasses(CodeGenTarget &Target);
520
Daniel Dunbar378bee92009-08-08 07:50:56 +0000521public:
522 /// BuildInfo - Construct the various tables used during matching.
523 void BuildInfo(CodeGenTarget &Target);
524};
525
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000526}
527
528void InstructionInfo::dump() {
529 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
530 << ", tokens:[";
531 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
532 errs() << Tokens[i];
533 if (i + 1 != e)
534 errs() << ", ";
535 }
536 errs() << "]\n";
537
538 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
539 Operand &Op = Operands[i];
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000540 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Daniel Dunbar378bee92009-08-08 07:50:56 +0000541 if (Op.Class->Kind == ClassInfo::Token) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000542 errs() << '\"' << Tokens[i] << "\"\n";
543 continue;
544 }
545
Benjamin Kramer19afc502009-08-08 10:06:30 +0000546 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000547 errs() << OI.Name << " " << OI.Rec->getName()
548 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
549 }
550}
551
Daniel Dunbar378bee92009-08-08 07:50:56 +0000552static std::string getEnumNameForToken(const StringRef &Str) {
553 std::string Res;
554
555 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
556 switch (*it) {
557 case '*': Res += "_STAR_"; break;
558 case '%': Res += "_PCT_"; break;
559 case ':': Res += "_COLON_"; break;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000560
Daniel Dunbar378bee92009-08-08 07:50:56 +0000561 default:
562 if (isalnum(*it)) {
563 Res += *it;
564 } else {
565 Res += "_" + utostr((unsigned) *it) + "_";
566 }
567 }
568 }
569
570 return Res;
571}
572
573ClassInfo *AsmMatcherInfo::getTokenClass(const StringRef &Token) {
574 ClassInfo *&Entry = TokenClasses[Token];
575
576 if (!Entry) {
577 Entry = new ClassInfo();
578 Entry->Kind = ClassInfo::Token;
Daniel Dunbar5502ca52009-08-09 05:18:30 +0000579 Entry->ClassName = "Token";
Daniel Dunbar378bee92009-08-08 07:50:56 +0000580 Entry->Name = "MCK_" + getEnumNameForToken(Token);
581 Entry->ValueName = Token;
582 Entry->PredicateMethod = "<invalid>";
583 Entry->RenderMethod = "<invalid>";
584 Classes.push_back(Entry);
585 }
586
587 return Entry;
588}
589
590ClassInfo *
591AsmMatcherInfo::getOperandClass(const StringRef &Token,
592 const CodeGenInstruction::OperandInfo &OI) {
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000593 if (OI.Rec->isSubClassOf("RegisterClass")) {
594 ClassInfo *CI = RegisterClassClasses[OI.Rec];
595
596 if (!CI) {
597 PrintError(OI.Rec->getLoc(), "register class has no class info!");
598 throw std::string("ERROR: Missing register class!");
599 }
600
601 return CI;
602 }
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000603
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000604 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
605 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
606 ClassInfo *CI = AsmOperandClasses[MatchClass];
607
608 if (!CI) {
609 PrintError(OI.Rec->getLoc(), "operand has no match class!");
610 throw std::string("ERROR: Missing match class!");
Daniel Dunbar378bee92009-08-08 07:50:56 +0000611 }
612
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000613 return CI;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000614}
615
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000616void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target) {
617 std::vector<CodeGenRegisterClass> RegisterClasses;
618 std::vector<CodeGenRegister> Registers;
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000619
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000620 RegisterClasses = Target.getRegisterClasses();
621 Registers = Target.getRegisters();
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000622
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000623 // The register sets used for matching.
624 std::set< std::set<Record*> > RegisterSets;
625
626 // Gather the defined sets.
627 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
628 ie = RegisterClasses.end(); it != ie; ++it)
629 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
630 it->Elements.end()));
631
632 // Introduce derived sets where necessary (when a register does not determine
633 // a unique register set class), and build the mapping of registers to the set
634 // they should classify to.
635 std::map<Record*, std::set<Record*> > RegisterMap;
636 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
637 ie = Registers.end(); it != ie; ++it) {
638 CodeGenRegister &CGR = *it;
639 // Compute the intersection of all sets containing this register.
640 std::set<Record*> ContainingSet;
641
642 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
643 ie = RegisterSets.end(); it != ie; ++it) {
644 if (!it->count(CGR.TheDef))
645 continue;
646
647 if (ContainingSet.empty()) {
648 ContainingSet = *it;
649 } else {
650 std::set<Record*> Tmp;
651 std::swap(Tmp, ContainingSet);
652 std::insert_iterator< std::set<Record*> > II(ContainingSet,
653 ContainingSet.begin());
654 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
655 II);
656 }
657 }
658
659 if (!ContainingSet.empty()) {
660 RegisterSets.insert(ContainingSet);
661 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
662 }
663 }
664
665 // Construct the register classes.
666 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
667 unsigned Index = 0;
668 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
669 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
670 ClassInfo *CI = new ClassInfo();
671 CI->Kind = ClassInfo::RegisterClass0 + Index;
672 CI->ClassName = "Reg" + utostr(Index);
673 CI->Name = "MCK_Reg" + utostr(Index);
674 CI->ValueName = "";
675 CI->PredicateMethod = ""; // unused
676 CI->RenderMethod = "addRegOperands";
677 Classes.push_back(CI);
678 RegisterSetClasses.insert(std::make_pair(*it, CI));
679 }
680
681 // Find the superclasses; we could compute only the subgroup lattice edges,
682 // but there isn't really a point.
683 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
684 ie = RegisterSets.end(); it != ie; ++it) {
685 ClassInfo *CI = RegisterSetClasses[*it];
686 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
687 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
688 if (*it != *it2 &&
689 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
690 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
691 }
692
693 // Name the register classes which correspond to a user defined RegisterClass.
694 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
695 ie = RegisterClasses.end(); it != ie; ++it) {
696 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
697 it->Elements.end())];
698 if (CI->ValueName.empty()) {
699 CI->ClassName = it->getName();
700 CI->Name = "MCK_" + it->getName();
701 CI->ValueName = it->getName();
702 } else
703 CI->ValueName = CI->ValueName + "," + it->getName();
704
705 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
706 }
707
708 // Populate the map for individual registers.
709 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
710 ie = RegisterMap.end(); it != ie; ++it)
711 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
712}
713
714void AsmMatcherInfo::BuildOperandClasses(CodeGenTarget &Target) {
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000715 std::vector<Record*> AsmOperands;
716 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
717 unsigned Index = 0;
718 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
719 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
720 ClassInfo *CI = new ClassInfo();
721 CI->Kind = ClassInfo::UserClass0 + Index;
722
723 Init *Super = (*it)->getValueInit("SuperClass");
724 if (DefInit *DI = dynamic_cast<DefInit*>(Super)) {
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000725 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
726 if (!SC)
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000727 PrintError((*it)->getLoc(), "Invalid super class reference!");
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000728 else
729 CI->SuperClasses.push_back(SC);
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000730 } else {
731 assert(dynamic_cast<UnsetInit*>(Super) && "Unexpected SuperClass field!");
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000732 }
733 CI->ClassName = (*it)->getValueAsString("Name");
734 CI->Name = "MCK_" + CI->ClassName;
735 CI->ValueName = (*it)->getName();
Daniel Dunbarb3413d82009-08-10 21:00:45 +0000736
737 // Get or construct the predicate method name.
738 Init *PMName = (*it)->getValueInit("PredicateMethod");
739 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
740 CI->PredicateMethod = SI->getValue();
741 } else {
742 assert(dynamic_cast<UnsetInit*>(PMName) &&
743 "Unexpected PredicateMethod field!");
744 CI->PredicateMethod = "is" + CI->ClassName;
745 }
746
747 // Get or construct the render method name.
748 Init *RMName = (*it)->getValueInit("RenderMethod");
749 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
750 CI->RenderMethod = SI->getValue();
751 } else {
752 assert(dynamic_cast<UnsetInit*>(RMName) &&
753 "Unexpected RenderMethod field!");
754 CI->RenderMethod = "add" + CI->ClassName + "Operands";
755 }
756
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000757 AsmOperandClasses[*it] = CI;
758 Classes.push_back(CI);
759 }
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000760}
761
762void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
763 // Build info for the register classes.
764 BuildRegisterClasses(Target);
765
766 // Build info for the user defined assembly operand classes.
767 BuildOperandClasses(Target);
Daniel Dunbar0f10cbf2009-08-10 18:41:10 +0000768
769 // Build the instruction information.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000770 for (std::map<std::string, CodeGenInstruction>::const_iterator
Daniel Dunbar378bee92009-08-08 07:50:56 +0000771 it = Target.getInstructions().begin(),
772 ie = Target.getInstructions().end();
773 it != ie; ++it) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000774 const CodeGenInstruction &CGI = it->second;
775
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000776 if (!StringRef(it->first).startswith(MatchPrefix))
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000777 continue;
778
779 OwningPtr<InstructionInfo> II(new InstructionInfo);
780
781 II->InstrName = it->first;
782 II->Instr = &it->second;
783 II->AsmString = FlattenVariants(CGI.AsmString, 0);
784
785 TokenizeAsmString(II->AsmString, II->Tokens);
786
787 // Ignore instructions which shouldn't be matched.
788 if (!IsAssemblerInstruction(it->first, CGI, II->Tokens))
789 continue;
790
791 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
792 StringRef Token = II->Tokens[i];
793
794 // Check for simple tokens.
795 if (Token[0] != '$') {
796 InstructionInfo::Operand Op;
Daniel Dunbar378bee92009-08-08 07:50:56 +0000797 Op.Class = getTokenClass(Token);
Benjamin Kramer19afc502009-08-08 10:06:30 +0000798 Op.OperandInfo = 0;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000799 II->Operands.push_back(Op);
800 continue;
801 }
802
803 // Otherwise this is an operand reference.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000804 StringRef OperandName;
805 if (Token[1] == '{')
806 OperandName = Token.substr(2, Token.size() - 3);
807 else
808 OperandName = Token.substr(1);
809
810 // Map this token to an operand. FIXME: Move elsewhere.
811 unsigned Idx;
812 try {
813 Idx = CGI.getOperandNamed(OperandName);
814 } catch(...) {
815 errs() << "error: unable to find operand: '" << OperandName << "'!\n";
816 break;
817 }
818
819 const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx];
Daniel Dunbar378bee92009-08-08 07:50:56 +0000820 InstructionInfo::Operand Op;
821 Op.Class = getOperandClass(Token, OI);
Benjamin Kramer19afc502009-08-08 10:06:30 +0000822 Op.OperandInfo = &OI;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000823 II->Operands.push_back(Op);
824 }
825
826 // If we broke out, ignore the instruction.
827 if (II->Operands.size() != II->Tokens.size())
828 continue;
829
Daniel Dunbar378bee92009-08-08 07:50:56 +0000830 Instructions.push_back(II.take());
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000831 }
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000832
Daniel Dunbar06d5cb62009-08-09 07:20:21 +0000833 // Reorder classes so that classes preceed super classes.
834 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000835}
836
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +0000837static void EmitConvertToMCInst(CodeGenTarget &Target,
838 std::vector<InstructionInfo*> &Infos,
839 raw_ostream &OS) {
Daniel Dunbarce82b992009-08-08 05:24:34 +0000840 // Write the convert function to a separate stream, so we can drop it after
841 // the enum.
842 std::string ConvertFnBody;
843 raw_string_ostream CvtOS(ConvertFnBody);
844
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000845 // Function we have already generated.
846 std::set<std::string> GeneratedFns;
847
Daniel Dunbarce82b992009-08-08 05:24:34 +0000848 // Start the unified conversion function.
849
850 CvtOS << "static bool ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
851 << "unsigned Opcode,\n"
852 << " SmallVectorImpl<"
853 << Target.getName() << "Operand> &Operands) {\n";
854 CvtOS << " Inst.setOpcode(Opcode);\n";
855 CvtOS << " switch (Kind) {\n";
856 CvtOS << " default:\n";
857
858 // Start the enum, which we will generate inline.
859
860 OS << "// Unified function for converting operants to MCInst instances.\n\n";
Daniel Dunbarce82b992009-08-08 05:24:34 +0000861 OS << "enum ConversionKind {\n";
862
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000863 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
864 ie = Infos.end(); it != ie; ++it) {
865 InstructionInfo &II = **it;
866
867 // Order the (class) operands by the order to convert them into an MCInst.
868 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
869 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
870 InstructionInfo::Operand &Op = II.Operands[i];
Benjamin Kramer19afc502009-08-08 10:06:30 +0000871 if (Op.OperandInfo)
872 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000873 }
874 std::sort(MIOperandList.begin(), MIOperandList.end());
875
876 // Compute the total number of operands.
877 unsigned NumMIOperands = 0;
878 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
879 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
880 NumMIOperands = std::max(NumMIOperands,
881 OI.MIOperandNo + OI.MINumOperands);
882 }
883
884 // Build the conversion function signature.
885 std::string Signature = "Convert";
886 unsigned CurIndex = 0;
887 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
888 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
Benjamin Kramer19afc502009-08-08 10:06:30 +0000889 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000890 "Duplicate match for instruction operand!");
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000891
Daniel Dunbarce82b992009-08-08 05:24:34 +0000892 Signature += "_";
893
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000894 // Skip operands which weren't matched by anything, this occurs when the
895 // .td file encodes "implicit" operands as explicit ones.
896 //
897 // FIXME: This should be removed from the MCInst structure.
Benjamin Kramer19afc502009-08-08 10:06:30 +0000898 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000899 Signature += "Imp";
900
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000901 // Registers are always converted the same, don't duplicate the conversion
902 // function based on them.
903 //
904 // FIXME: We could generalize this based on the render method, if it
905 // mattered.
906 if (Op.Class->isRegisterClass())
907 Signature += "Reg";
908 else
909 Signature += Op.Class->ClassName;
Benjamin Kramer19afc502009-08-08 10:06:30 +0000910 Signature += utostr(Op.OperandInfo->MINumOperands);
Daniel Dunbarce82b992009-08-08 05:24:34 +0000911 Signature += "_" + utostr(MIOperandList[i].second);
912
Benjamin Kramer19afc502009-08-08 10:06:30 +0000913 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000914 }
915
916 // Add any trailing implicit operands.
917 for (; CurIndex != NumMIOperands; ++CurIndex)
918 Signature += "Imp";
919
Daniel Dunbarce82b992009-08-08 05:24:34 +0000920 II.ConversionFnKind = Signature;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000921
Daniel Dunbarce82b992009-08-08 05:24:34 +0000922 // Check if we have already generated this signature.
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000923 if (!GeneratedFns.insert(Signature).second)
924 continue;
925
926 // If not, emit it now.
Daniel Dunbarce82b992009-08-08 05:24:34 +0000927
928 // Add to the enum list.
929 OS << " " << Signature << ",\n";
930
931 // And to the convert function.
932 CvtOS << " case " << Signature << ":\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000933 CurIndex = 0;
934 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
935 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
936
937 // Add the implicit operands.
Benjamin Kramer19afc502009-08-08 10:06:30 +0000938 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex)
Daniel Dunbarce82b992009-08-08 05:24:34 +0000939 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000940
Daniel Dunbarce82b992009-08-08 05:24:34 +0000941 CvtOS << " Operands[" << MIOperandList[i].second
Daniel Dunbar378bee92009-08-08 07:50:56 +0000942 << "]." << Op.Class->RenderMethod
Benjamin Kramer19afc502009-08-08 10:06:30 +0000943 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
944 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000945 }
946
947 // And add trailing implicit operands.
948 for (; CurIndex != NumMIOperands; ++CurIndex)
Daniel Dunbarce82b992009-08-08 05:24:34 +0000949 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
950 CvtOS << " break;\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +0000951 }
Daniel Dunbarce82b992009-08-08 05:24:34 +0000952
953 // Finish the convert function.
954
955 CvtOS << " }\n";
956 CvtOS << " return false;\n";
957 CvtOS << "}\n\n";
958
959 // Finish the enum, and drop the convert function after it.
960
961 OS << " NumConversionVariants\n";
962 OS << "};\n\n";
963
Daniel Dunbarce82b992009-08-08 05:24:34 +0000964 OS << CvtOS.str();
Daniel Dunbara54716c2009-07-31 02:32:59 +0000965}
966
Daniel Dunbar378bee92009-08-08 07:50:56 +0000967/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
968static void EmitMatchClassEnumeration(CodeGenTarget &Target,
969 std::vector<ClassInfo*> &Infos,
970 raw_ostream &OS) {
971 OS << "namespace {\n\n";
972
973 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
974 << "/// instruction matching.\n";
975 OS << "enum MatchClassKind {\n";
976 OS << " InvalidMatchClass = 0,\n";
977 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
978 ie = Infos.end(); it != ie; ++it) {
979 ClassInfo &CI = **it;
980 OS << " " << CI.Name << ", // ";
981 if (CI.Kind == ClassInfo::Token) {
982 OS << "'" << CI.ValueName << "'\n";
Daniel Dunbar171a05b2009-08-11 02:59:53 +0000983 } else if (CI.isRegisterClass()) {
Daniel Dunbar378bee92009-08-08 07:50:56 +0000984 if (!CI.ValueName.empty())
985 OS << "register class '" << CI.ValueName << "'\n";
986 else
987 OS << "derived register class\n";
988 } else {
989 OS << "user defined class '" << CI.ValueName << "'\n";
990 }
991 }
992 OS << " NumMatchClassKinds\n";
993 OS << "};\n\n";
994
995 OS << "}\n\n";
996}
997
Daniel Dunbar378bee92009-08-08 07:50:56 +0000998/// EmitClassifyOperand - Emit the function to classify an operand.
999static void EmitClassifyOperand(CodeGenTarget &Target,
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001000 AsmMatcherInfo &Info,
Daniel Dunbar378bee92009-08-08 07:50:56 +00001001 raw_ostream &OS) {
1002 OS << "static MatchClassKind ClassifyOperand("
1003 << Target.getName() << "Operand &Operand) {\n";
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001004
1005 // Classify tokens.
Daniel Dunbar378bee92009-08-08 07:50:56 +00001006 OS << " if (Operand.isToken())\n";
1007 OS << " return MatchTokenString(Operand.getToken());\n\n";
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001008
1009 // Classify registers.
1010 //
1011 // FIXME: Don't hardcode isReg, getReg.
1012 OS << " if (Operand.isReg()) {\n";
1013 OS << " switch (Operand.getReg()) {\n";
1014 OS << " default: return InvalidMatchClass;\n";
1015 for (std::map<Record*, ClassInfo*>::iterator
1016 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1017 it != ie; ++it)
1018 OS << " case " << Target.getName() << "::"
1019 << it->first->getName() << ": return " << it->second->Name << ";\n";
1020 OS << " }\n";
1021 OS << " }\n\n";
1022
1023 // Classify user defined operands.
1024 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1025 ie = Info.Classes.end(); it != ie; ++it) {
Daniel Dunbar378bee92009-08-08 07:50:56 +00001026 ClassInfo &CI = **it;
1027
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001028 if (!CI.isUserClass())
1029 continue;
1030
1031 OS << " // '" << CI.ClassName << "' class";
1032 if (!CI.SuperClasses.empty()) {
1033 OS << ", subclass of ";
1034 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1035 if (i) OS << ", ";
1036 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1037 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
Daniel Dunbar06d5cb62009-08-09 07:20:21 +00001038 }
Daniel Dunbar378bee92009-08-08 07:50:56 +00001039 }
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001040 OS << "\n";
1041
1042 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
1043
1044 // Validate subclass relationships.
1045 if (!CI.SuperClasses.empty()) {
1046 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1047 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1048 << "() && \"Invalid class relationship!\");\n";
1049 }
1050
1051 OS << " return " << CI.Name << ";\n";
1052 OS << " }\n\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001053 }
1054 OS << " return InvalidMatchClass;\n";
1055 OS << "}\n\n";
1056}
1057
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001058/// EmitIsSubclass - Emit the subclass predicate function.
1059static void EmitIsSubclass(CodeGenTarget &Target,
1060 std::vector<ClassInfo*> &Infos,
1061 raw_ostream &OS) {
1062 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1063 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1064 OS << " if (A == B)\n";
1065 OS << " return true;\n\n";
1066
1067 OS << " switch (A) {\n";
1068 OS << " default:\n";
1069 OS << " return false;\n";
1070 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1071 ie = Infos.end(); it != ie; ++it) {
1072 ClassInfo &A = **it;
1073
1074 if (A.Kind != ClassInfo::Token) {
1075 std::vector<StringRef> SuperClasses;
1076 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1077 ie = Infos.end(); it != ie; ++it) {
1078 ClassInfo &B = **it;
1079
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001080 if (&A != &B && A.isSubsetOf(B))
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001081 SuperClasses.push_back(B.Name);
1082 }
1083
1084 if (SuperClasses.empty())
1085 continue;
1086
1087 OS << "\n case " << A.Name << ":\n";
1088
1089 if (SuperClasses.size() == 1) {
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001090 OS << " return B == " << SuperClasses.back() << ";\n";
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001091 continue;
1092 }
1093
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001094 OS << " switch (B) {\n";
1095 OS << " default: return false;\n";
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001096 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001097 OS << " case " << SuperClasses[i] << ": return true;\n";
1098 OS << " }\n";
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001099 }
1100 }
1101 OS << " }\n";
1102 OS << "}\n\n";
1103}
1104
Chris Lattner042926f2009-08-08 20:02:57 +00001105typedef std::pair<std::string, std::string> StringPair;
1106
1107/// FindFirstNonCommonLetter - Find the first character in the keys of the
1108/// string pairs that is not shared across the whole set of strings. All
1109/// strings are assumed to have the same length.
1110static unsigned
1111FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
1112 assert(!Matches.empty());
1113 for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
1114 // Check to see if letter i is the same across the set.
1115 char Letter = Matches[0]->first[i];
1116
1117 for (unsigned str = 0, e = Matches.size(); str != e; ++str)
1118 if (Matches[str]->first[i] != Letter)
1119 return i;
1120 }
1121
1122 return Matches[0]->first.size();
1123}
1124
1125/// EmitStringMatcherForChar - Given a set of strings that are known to be the
1126/// same length and whose characters leading up to CharNo are the same, emit
1127/// code to verify that CharNo and later are the same.
Daniel Dunbar7906a642009-08-08 22:57:25 +00001128///
1129/// \return - True if control can leave the emitted code fragment.
1130static bool EmitStringMatcherForChar(const std::string &StrVariableName,
Chris Lattner042926f2009-08-08 20:02:57 +00001131 const std::vector<const StringPair*> &Matches,
1132 unsigned CharNo, unsigned IndentCount,
1133 raw_ostream &OS) {
1134 assert(!Matches.empty() && "Must have at least one string to match!");
1135 std::string Indent(IndentCount*2+4, ' ');
1136
1137 // If we have verified that the entire string matches, we're done: output the
1138 // matching code.
1139 if (CharNo == Matches[0]->first.size()) {
1140 assert(Matches.size() == 1 && "Had duplicate keys to match on");
1141
1142 // FIXME: If Matches[0].first has embeded \n, this will be bad.
1143 OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
1144 << "\"\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001145 return false;
Chris Lattner042926f2009-08-08 20:02:57 +00001146 }
1147
1148 // Bucket the matches by the character we are comparing.
1149 std::map<char, std::vector<const StringPair*> > MatchesByLetter;
1150
1151 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1152 MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
1153
1154
1155 // If we have exactly one bucket to match, see how many characters are common
1156 // across the whole set and match all of them at once.
Chris Lattner042926f2009-08-08 20:02:57 +00001157 if (MatchesByLetter.size() == 1) {
1158 unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
1159 unsigned NumChars = FirstNonCommonLetter-CharNo;
1160
Daniel Dunbar7906a642009-08-08 22:57:25 +00001161 // Emit code to break out if the prefix doesn't match.
Chris Lattner042926f2009-08-08 20:02:57 +00001162 if (NumChars == 1) {
Daniel Dunbar7906a642009-08-08 22:57:25 +00001163 // Do the comparison with if (Str[1] != 'f')
Chris Lattner042926f2009-08-08 20:02:57 +00001164 // FIXME: Need to escape general characters.
Daniel Dunbar7906a642009-08-08 22:57:25 +00001165 OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
1166 << Matches[0]->first[CharNo] << "')\n";
1167 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001168 } else {
Daniel Dunbar7906a642009-08-08 22:57:25 +00001169 // Do the comparison with if (Str.substr(1,3) != "foo").
Chris Lattner042926f2009-08-08 20:02:57 +00001170 // FIXME: Need to escape general strings.
Daniel Dunbar7906a642009-08-08 22:57:25 +00001171 OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
1172 << NumChars << ") != \"";
1173 OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
Daniel Dunbarda3a2292009-08-08 23:43:16 +00001174 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001175 }
1176
Daniel Dunbar7906a642009-08-08 22:57:25 +00001177 return EmitStringMatcherForChar(StrVariableName, Matches,
1178 FirstNonCommonLetter, IndentCount, OS);
Chris Lattner042926f2009-08-08 20:02:57 +00001179 }
1180
1181 // Otherwise, we have multiple possible things, emit a switch on the
1182 // character.
1183 OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
1184 OS << Indent << "default: break;\n";
1185
1186 for (std::map<char, std::vector<const StringPair*> >::iterator LI =
1187 MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
1188 // TODO: escape hard stuff (like \n) if we ever care about it.
1189 OS << Indent << "case '" << LI->first << "':\t // "
1190 << LI->second.size() << " strings to match.\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001191 if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
1192 IndentCount+1, OS))
1193 OS << Indent << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001194 }
1195
1196 OS << Indent << "}\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001197 return true;
Chris Lattner042926f2009-08-08 20:02:57 +00001198}
1199
1200
1201/// EmitStringMatcher - Given a list of strings and code to execute when they
Daniel Dunbar7906a642009-08-08 22:57:25 +00001202/// match, output a simple switch tree to classify the input string.
1203///
1204/// If a match is found, the code in Vals[i].second is executed; control must
1205/// not exit this code fragment. If nothing matches, execution falls through.
1206///
1207/// \param StrVariableName - The name of the variable to test.
Chris Lattner042926f2009-08-08 20:02:57 +00001208static void EmitStringMatcher(const std::string &StrVariableName,
1209 const std::vector<StringPair> &Matches,
1210 raw_ostream &OS) {
1211 // First level categorization: group strings by length.
1212 std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
1213
1214 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1215 MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
1216
1217 // Output a switch statement on length and categorize the elements within each
1218 // bin.
1219 OS << " switch (" << StrVariableName << ".size()) {\n";
1220 OS << " default: break;\n";
1221
Chris Lattner042926f2009-08-08 20:02:57 +00001222 for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
1223 MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
1224 OS << " case " << LI->first << ":\t // " << LI->second.size()
1225 << " strings to match.\n";
Daniel Dunbar7906a642009-08-08 22:57:25 +00001226 if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
1227 OS << " break;\n";
Chris Lattner042926f2009-08-08 20:02:57 +00001228 }
1229
Chris Lattner042926f2009-08-08 20:02:57 +00001230 OS << " }\n";
1231}
1232
1233
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001234/// EmitMatchTokenString - Emit the function to match a token string to the
1235/// appropriate match class value.
1236static void EmitMatchTokenString(CodeGenTarget &Target,
1237 std::vector<ClassInfo*> &Infos,
1238 raw_ostream &OS) {
1239 // Construct the match list.
1240 std::vector<StringPair> Matches;
1241 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1242 ie = Infos.end(); it != ie; ++it) {
1243 ClassInfo &CI = **it;
1244
1245 if (CI.Kind == ClassInfo::Token)
1246 Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
1247 }
1248
1249 OS << "static MatchClassKind MatchTokenString(const StringRef &Name) {\n";
1250
1251 EmitStringMatcher("Name", Matches, OS);
1252
1253 OS << " return InvalidMatchClass;\n";
1254 OS << "}\n\n";
1255}
Chris Lattner042926f2009-08-08 20:02:57 +00001256
Daniel Dunbar79f302e2009-08-07 21:01:44 +00001257/// EmitMatchRegisterName - Emit the function to match a string to the target
1258/// specific register enum.
1259static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1260 raw_ostream &OS) {
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001261 // Construct the match list.
Chris Lattner042926f2009-08-08 20:02:57 +00001262 std::vector<StringPair> Matches;
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001263 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1264 const CodeGenRegister &Reg = Target.getRegisters()[i];
Daniel Dunbar2f9876b2009-07-17 18:51:11 +00001265 if (Reg.TheDef->getValueAsString("AsmName").empty())
1266 continue;
1267
Chris Lattner042926f2009-08-08 20:02:57 +00001268 Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001269 "return " + utostr(i + 1) + ";"));
Daniel Dunbar2f9876b2009-07-17 18:51:11 +00001270 }
Chris Lattner042926f2009-08-08 20:02:57 +00001271
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001272 OS << "unsigned " << Target.getName()
1273 << AsmParser->getValueAsString("AsmParserClassName")
1274 << "::MatchRegisterName(const StringRef &Name) {\n";
1275
Chris Lattner042926f2009-08-08 20:02:57 +00001276 EmitStringMatcher("Name", Matches, OS);
1277
Daniel Dunbarb0e6abe2009-08-08 21:22:41 +00001278 OS << " return 0;\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001279 OS << "}\n\n";
Daniel Dunbar79f302e2009-08-07 21:01:44 +00001280}
Daniel Dunbara54716c2009-07-31 02:32:59 +00001281
Daniel Dunbar79f302e2009-08-07 21:01:44 +00001282void AsmMatcherEmitter::run(raw_ostream &OS) {
1283 CodeGenTarget Target;
1284 Record *AsmParser = Target.getAsmParser();
1285 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1286
1287 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1288
1289 // Emit the function to match a register name to number.
1290 EmitMatchRegisterName(Target, AsmParser, OS);
1291
Daniel Dunbar378bee92009-08-08 07:50:56 +00001292 // Compute the information on the instructions to match.
1293 AsmMatcherInfo Info;
1294 Info.BuildInfo(Target);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001295
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001296 // Sort the instruction table using the partial order on classes.
1297 std::sort(Info.Instructions.begin(), Info.Instructions.end(),
1298 less_ptr<InstructionInfo>());
1299
Daniel Dunbarce82b992009-08-08 05:24:34 +00001300 DEBUG_WITH_TYPE("instruction_info", {
Daniel Dunbar378bee92009-08-08 07:50:56 +00001301 for (std::vector<InstructionInfo*>::iterator
1302 it = Info.Instructions.begin(), ie = Info.Instructions.end();
1303 it != ie; ++it)
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001304 (*it)->dump();
1305 });
Daniel Dunbara54716c2009-07-31 02:32:59 +00001306
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001307 // Check for ambiguous instructions.
1308 unsigned NumAmbiguous = 0;
Daniel Dunbar33eec5d2009-08-09 06:05:33 +00001309 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1310 for (unsigned j = i + 1; j != e; ++j) {
1311 InstructionInfo &A = *Info.Instructions[i];
1312 InstructionInfo &B = *Info.Instructions[j];
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001313
Daniel Dunbar33eec5d2009-08-09 06:05:33 +00001314 if (A.CouldMatchAmiguouslyWith(B)) {
1315 DEBUG_WITH_TYPE("ambiguous_instrs", {
1316 errs() << "warning: ambiguous instruction match:\n";
1317 A.dump();
1318 errs() << "\nis incomparable with:\n";
1319 B.dump();
1320 errs() << "\n\n";
1321 });
1322 ++NumAmbiguous;
1323 }
Daniel Dunbar9c1feeb2009-08-09 04:00:06 +00001324 }
1325 }
1326 if (NumAmbiguous)
1327 DEBUG_WITH_TYPE("ambiguous_instrs", {
1328 errs() << "warning: " << NumAmbiguous
1329 << " ambiguous instructions!\n";
1330 });
1331
1332 // Generate the unified function to convert operands into an MCInst.
1333 EmitConvertToMCInst(Target, Info.Instructions, OS);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001334
Daniel Dunbar378bee92009-08-08 07:50:56 +00001335 // Emit the enumeration for classes which participate in matching.
1336 EmitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbara54716c2009-07-31 02:32:59 +00001337
Daniel Dunbar378bee92009-08-08 07:50:56 +00001338 // Emit the routine to match token strings to their match class.
1339 EmitMatchTokenString(Target, Info.Classes, OS);
1340
1341 // Emit the routine to classify an operand.
Daniel Dunbar171a05b2009-08-11 02:59:53 +00001342 EmitClassifyOperand(Target, Info, OS);
Daniel Dunbar378bee92009-08-08 07:50:56 +00001343
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001344 // Emit the subclass predicate routine.
1345 EmitIsSubclass(Target, Info.Classes, OS);
1346
Daniel Dunbar378bee92009-08-08 07:50:56 +00001347 // Finally, build the match function.
1348
1349 size_t MaxNumOperands = 0;
1350 for (std::vector<InstructionInfo*>::const_iterator it =
1351 Info.Instructions.begin(), ie = Info.Instructions.end();
1352 it != ie; ++it)
1353 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
1354
Daniel Dunbara54716c2009-07-31 02:32:59 +00001355 OS << "bool " << Target.getName() << ClassName
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001356 << "::MatchInstruction("
Daniel Dunbara54716c2009-07-31 02:32:59 +00001357 << "SmallVectorImpl<" << Target.getName() << "Operand> &Operands, "
1358 << "MCInst &Inst) {\n";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001359
Daniel Dunbar378bee92009-08-08 07:50:56 +00001360 // Emit the static match table; unused classes get initalized to 0 which is
1361 // guaranteed to be InvalidMatchClass.
1362 //
1363 // FIXME: We can reduce the size of this table very easily. First, we change
1364 // it so that store the kinds in separate bit-fields for each index, which
1365 // only needs to be the max width used for classes at that index (we also need
1366 // to reject based on this during classification). If we then make sure to
1367 // order the match kinds appropriately (putting mnemonics last), then we
1368 // should only end up using a few bits for each class, especially the ones
1369 // following the mnemonic.
Chris Lattnerde024f82009-08-08 19:15:25 +00001370 OS << " static const struct MatchEntry {\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001371 OS << " unsigned Opcode;\n";
1372 OS << " ConversionKind ConvertFn;\n";
1373 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1374 OS << " } MatchTable[" << Info.Instructions.size() << "] = {\n";
1375
1376 for (std::vector<InstructionInfo*>::const_iterator it =
1377 Info.Instructions.begin(), ie = Info.Instructions.end();
1378 it != ie; ++it) {
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001379 InstructionInfo &II = **it;
1380
Daniel Dunbar378bee92009-08-08 07:50:56 +00001381 OS << " { " << Target.getName() << "::" << II.InstrName
1382 << ", " << II.ConversionFnKind << ", { ";
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001383 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1384 InstructionInfo::Operand &Op = II.Operands[i];
1385
Daniel Dunbar378bee92009-08-08 07:50:56 +00001386 if (i) OS << ", ";
1387 OS << Op.Class->Name;
Daniel Dunbarfe6759e2009-08-07 08:26:05 +00001388 }
Daniel Dunbar378bee92009-08-08 07:50:56 +00001389 OS << " } },\n";
Daniel Dunbara54716c2009-07-31 02:32:59 +00001390 }
1391
Daniel Dunbar378bee92009-08-08 07:50:56 +00001392 OS << " };\n\n";
1393
1394 // Emit code to compute the class list for this operand vector.
1395 OS << " // Eliminate obvious mismatches.\n";
1396 OS << " if (Operands.size() > " << MaxNumOperands << ")\n";
1397 OS << " return true;\n\n";
1398
1399 OS << " // Compute the class list for this operand vector.\n";
1400 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1401 OS << " for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1402 OS << " Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1403
1404 OS << " // Check for invalid operands before matching.\n";
1405 OS << " if (Classes[i] == InvalidMatchClass)\n";
1406 OS << " return true;\n";
1407 OS << " }\n\n";
1408
1409 OS << " // Mark unused classes.\n";
1410 OS << " for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1411 << "i != e; ++i)\n";
1412 OS << " Classes[i] = InvalidMatchClass;\n\n";
1413
1414 // Emit code to search the table.
1415 OS << " // Search the table.\n";
Chris Lattnerac3daf92009-08-08 19:16:05 +00001416 OS << " for (const MatchEntry *it = MatchTable, "
Daniel Dunbar378bee92009-08-08 07:50:56 +00001417 << "*ie = MatchTable + " << Info.Instructions.size()
1418 << "; it != ie; ++it) {\n";
1419 for (unsigned i = 0; i != MaxNumOperands; ++i) {
Daniel Dunbar14a77d42009-08-10 16:05:47 +00001420 OS << " if (!IsSubclass(Classes["
1421 << i << "], it->Classes[" << i << "]))\n";
Daniel Dunbar378bee92009-08-08 07:50:56 +00001422 OS << " continue;\n";
1423 }
1424 OS << "\n";
1425 OS << " return ConvertToMCInst(it->ConvertFn, Inst, "
1426 << "it->Opcode, Operands);\n";
1427 OS << " }\n\n";
1428
Daniel Dunbara54716c2009-07-31 02:32:59 +00001429 OS << " return true;\n";
1430 OS << "}\n\n";
Daniel Dunbar3f6e3ff2009-07-11 19:39:44 +00001431}