blob: 08a430dc92d489e1b576b2ab496350c7e2600602 [file] [log] [blame]
Daniel Dunbard51ffcf2009-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 Dunbar20927f22009-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 Dunbard51ffcf2009-07-11 19:39:44 +000074//===----------------------------------------------------------------------===//
75
76#include "AsmMatcherEmitter.h"
77#include "CodeGenTarget.h"
78#include "Record.h"
Daniel Dunbar20927f22009-08-07 08:26:05 +000079#include "llvm/ADT/OwningPtr.h"
Daniel Dunbara027d222009-07-31 02:32:59 +000080#include "llvm/ADT/SmallVector.h"
Daniel Dunbar606e8ad2009-08-09 04:00:06 +000081#include "llvm/ADT/STLExtras.h"
Daniel Dunbar20927f22009-08-07 08:26:05 +000082#include "llvm/ADT/StringExtras.h"
83#include "llvm/Support/CommandLine.h"
Daniel Dunbara027d222009-07-31 02:32:59 +000084#include "llvm/Support/Debug.h"
Daniel Dunbara027d222009-07-31 02:32:59 +000085#include <list>
Daniel Dunbarb7479c02009-08-08 05:24:34 +000086#include <map>
87#include <set>
Daniel Dunbard51ffcf2009-07-11 19:39:44 +000088using namespace llvm;
89
Daniel Dunbar27249152009-08-07 20:33:39 +000090static cl::opt<std::string>
Daniel Dunbar606e8ad2009-08-09 04:00:06 +000091MatchPrefix("match-prefix", cl::init(""),
92 cl::desc("Only match instructions with the given prefix"));
Daniel Dunbar20927f22009-08-07 08:26:05 +000093
Daniel Dunbara027d222009-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 Dunbar53a7f162009-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 Dunbar20927f22009-08-07 08:26:05 +0000106 (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
107 Cur[VariantsStart-1] != '\\')))
Daniel Dunbar53a7f162009-08-04 20:36:45 +0000108 break;
Daniel Dunbara027d222009-07-31 02:32:59 +0000109
Daniel Dunbar53a7f162009-08-04 20:36:45 +0000110 // Add the prefix to the result.
111 Res += Cur.slice(0, VariantsStart);
112 if (VariantsStart == Cur.size())
Daniel Dunbara027d222009-07-31 02:32:59 +0000113 break;
114
Daniel Dunbar53a7f162009-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 Dunbar20927f22009-08-07 08:26:05 +0000121 if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
Daniel Dunbar53a7f162009-08-04 20:36:45 +0000122 if (--NestedBraces == 0)
123 break;
124 } else if (Cur[VariantsEnd] == '{')
125 ++NestedBraces;
126 }
Daniel Dunbara027d222009-07-31 02:32:59 +0000127
128 // Select the Nth variant (or empty).
Daniel Dunbar53a7f162009-08-04 20:36:45 +0000129 StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
Daniel Dunbara027d222009-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 Dunbar53a7f162009-08-04 20:36:45 +0000134 assert(VariantsEnd != Cur.size() &&
135 "Unterminated variants in assembly string!");
136 Cur = Cur.substr(VariantsEnd + 1);
Daniel Dunbara027d222009-07-31 02:32:59 +0000137 }
138
139 return Res;
140}
141
142/// TokenizeAsmString - Tokenize a simplified assembly string.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000143static void TokenizeAsmString(StringRef AsmString,
Daniel Dunbara027d222009-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 Dunbar20927f22009-08-07 08:26:05 +0000149 case '[':
150 case ']':
Daniel Dunbara027d222009-07-31 02:32:59 +0000151 case '*':
152 case '!':
153 case ' ':
154 case '\t':
155 case ',':
156 if (InTok) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000157 Tokens.push_back(AsmString.slice(Prev, i));
Daniel Dunbara027d222009-07-31 02:32:59 +0000158 InTok = false;
159 }
Daniel Dunbar20927f22009-08-07 08:26:05 +0000160 if (!isspace(AsmString[i]) && AsmString[i] != ',')
161 Tokens.push_back(AsmString.substr(i, 1));
Daniel Dunbara027d222009-07-31 02:32:59 +0000162 Prev = i + 1;
163 break;
Daniel Dunbar20927f22009-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 Dunbara027d222009-07-31 02:32:59 +0000201
202 default:
203 InTok = true;
204 }
205 }
206 if (InTok && Prev != AsmString.size())
Daniel Dunbar20927f22009-08-07 08:26:05 +0000207 Tokens.push_back(AsmString.substr(Prev));
208}
209
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000210static bool IsAssemblerInstruction(StringRef Name,
Daniel Dunbar20927f22009-08-07 08:26:05 +0000211 const CodeGenInstruction &CGI,
212 const SmallVectorImpl<StringRef> &Tokens) {
Daniel Dunbar7417b762009-08-11 22:17:52 +0000213 // Ignore "codegen only" instructions.
214 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
215 return false;
216
217 // Ignore pseudo ops.
Daniel Dunbar20927f22009-08-07 08:26:05 +0000218 //
Daniel Dunbar7417b762009-08-11 22:17:52 +0000219 // FIXME: This is a hack; can we convert these instructions to set the
220 // "codegen only" bit instead?
Daniel Dunbar20927f22009-08-07 08:26:05 +0000221 if (const RecordVal *Form = CGI.TheDef->getValue("Form"))
222 if (Form->getValue()->getAsString() == "Pseudo")
223 return false;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000224
Daniel Dunbar72fa87f2009-08-09 08:19:00 +0000225 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
226 //
227 // FIXME: This is a total hack.
228 if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
229 return false;
230
Daniel Dunbar20927f22009-08-07 08:26:05 +0000231 // Ignore instructions with no .s string.
232 //
233 // FIXME: What are these?
234 if (CGI.AsmString.empty())
235 return false;
236
237 // FIXME: Hack; ignore any instructions with a newline in them.
238 if (std::find(CGI.AsmString.begin(),
239 CGI.AsmString.end(), '\n') != CGI.AsmString.end())
240 return false;
241
242 // Ignore instructions with attributes, these are always fake instructions for
243 // simplifying codegen.
244 //
245 // FIXME: Is this true?
246 //
Daniel Dunbar7417b762009-08-11 22:17:52 +0000247 // Also, check for instructions which reference the operand multiple times;
248 // this implies a constraint we would not honor.
Daniel Dunbar20927f22009-08-07 08:26:05 +0000249 std::set<std::string> OperandNames;
250 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
251 if (Tokens[i][0] == '$' &&
252 std::find(Tokens[i].begin(),
253 Tokens[i].end(), ':') != Tokens[i].end()) {
254 DEBUG({
255 errs() << "warning: '" << Name << "': "
256 << "ignoring instruction; operand with attribute '"
Daniel Dunbar7417b762009-08-11 22:17:52 +0000257 << Tokens[i] << "'\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +0000258 });
259 return false;
260 }
261
262 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
Daniel Dunbar7417b762009-08-11 22:17:52 +0000263 std::string Err = "'" + Name.str() + "': " +
264 "invalid assembler instruction; tied operand '" + Tokens[i].str() + "'";
265 throw TGError(CGI.TheDef->getLoc(), Err);
Daniel Dunbar20927f22009-08-07 08:26:05 +0000266 }
267 }
268
269 return true;
270}
271
272namespace {
273
Daniel Dunbar54074b52010-07-19 05:44:09 +0000274struct SubtargetFeatureInfo;
275
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000276/// ClassInfo - Helper class for storing the information about a particular
277/// class of operands which can be matched.
278struct ClassInfo {
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000279 enum ClassInfoKind {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000280 /// Invalid kind, for use as a sentinel value.
281 Invalid = 0,
282
283 /// The class for a particular token.
284 Token,
285
286 /// The (first) register class, subsequent register classes are
287 /// RegisterClass0+1, and so on.
288 RegisterClass0,
289
290 /// The (first) user defined class, subsequent user defined classes are
291 /// UserClass0+1, and so on.
292 UserClass0 = 1<<16
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000293 };
294
295 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
296 /// N) for the Nth user defined class.
297 unsigned Kind;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000298
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000299 /// SuperClasses - The super classes of this class. Note that for simplicities
300 /// sake user operands only record their immediate super class, while register
301 /// operands include all superclasses.
302 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000303
Daniel Dunbar6745d422009-08-09 05:18:30 +0000304 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000305 std::string Name;
306
Daniel Dunbar6745d422009-08-09 05:18:30 +0000307 /// ClassName - The unadorned generic name for this class (e.g., Token).
308 std::string ClassName;
309
Daniel Dunbara3741fa2009-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
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000316 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000317 std::string PredicateMethod;
318
319 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000320 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000321 std::string RenderMethod;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000322
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000323 /// For register classes, the records for all the registers in this class.
324 std::set<Record*> Registers;
325
326public:
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000327 /// isRegisterClass() - Check if this is a register class.
328 bool isRegisterClass() const {
329 return Kind >= RegisterClass0 && Kind < UserClass0;
330 }
331
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000332 /// isUserClass() - Check if this is a user defined class.
333 bool isUserClass() const {
334 return Kind >= UserClass0;
335 }
336
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000337 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
338 /// are related if they are in the same class hierarchy.
339 bool isRelatedTo(const ClassInfo &RHS) const {
340 // Tokens are only related to tokens.
341 if (Kind == Token || RHS.Kind == Token)
342 return Kind == Token && RHS.Kind == Token;
343
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000344 // Registers classes are only related to registers classes, and only if
345 // their intersection is non-empty.
346 if (isRegisterClass() || RHS.isRegisterClass()) {
347 if (!isRegisterClass() || !RHS.isRegisterClass())
348 return false;
349
350 std::set<Record*> Tmp;
351 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
352 std::set_intersection(Registers.begin(), Registers.end(),
353 RHS.Registers.begin(), RHS.Registers.end(),
354 II);
355
356 return !Tmp.empty();
357 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000358
359 // Otherwise we have two users operands; they are related if they are in the
360 // same class hierarchy.
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000361 //
362 // FIXME: This is an oversimplification, they should only be related if they
363 // intersect, however we don't have that information.
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000364 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
365 const ClassInfo *Root = this;
366 while (!Root->SuperClasses.empty())
367 Root = Root->SuperClasses.front();
368
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000369 const ClassInfo *RHSRoot = &RHS;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000370 while (!RHSRoot->SuperClasses.empty())
371 RHSRoot = RHSRoot->SuperClasses.front();
372
373 return Root == RHSRoot;
374 }
375
376 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
377 bool isSubsetOf(const ClassInfo &RHS) const {
378 // This is a subset of RHS if it is the same class...
379 if (this == &RHS)
380 return true;
381
382 // ... or if any of its super classes are a subset of RHS.
383 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
384 ie = SuperClasses.end(); it != ie; ++it)
385 if ((*it)->isSubsetOf(RHS))
386 return true;
387
388 return false;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000389 }
390
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000391 /// operator< - Compare two classes.
392 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar368a4562010-05-27 05:31:32 +0000393 if (this == &RHS)
394 return false;
395
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000396 // Unrelated classes can be ordered by kind.
397 if (!isRelatedTo(RHS))
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000398 return Kind < RHS.Kind;
399
400 switch (Kind) {
Daniel Dunbar6745d422009-08-09 05:18:30 +0000401 case Invalid:
402 assert(0 && "Invalid kind!");
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000403 case Token:
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000404 // Tokens are comparable by value.
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000405 //
406 // FIXME: Compare by enum value.
407 return ValueName < RHS.ValueName;
408
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000409 default:
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000410 // This class preceeds the RHS if it is a proper subset of the RHS.
Daniel Dunbar368a4562010-05-27 05:31:32 +0000411 if (isSubsetOf(RHS))
Duncan Sands34727662010-07-12 08:16:59 +0000412 return true;
Daniel Dunbar368a4562010-05-27 05:31:32 +0000413 if (RHS.isSubsetOf(*this))
Duncan Sands34727662010-07-12 08:16:59 +0000414 return false;
Daniel Dunbar368a4562010-05-27 05:31:32 +0000415
416 // Otherwise, order by name to ensure we have a total ordering.
417 return ValueName < RHS.ValueName;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000418 }
419 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000420};
421
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000422/// InstructionInfo - Helper class for storing the necessary information for an
423/// instruction which is capable of being matched.
Daniel Dunbar20927f22009-08-07 08:26:05 +0000424struct InstructionInfo {
425 struct Operand {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000426 /// The unique class instance this operand should match.
427 ClassInfo *Class;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000428
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000429 /// The original operand this corresponds to, if any.
Benjamin Kramerfa1165a2009-08-08 10:06:30 +0000430 const CodeGenInstruction::OperandInfo *OperandInfo;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000431 };
432
433 /// InstrName - The target name for this instruction.
434 std::string InstrName;
435
436 /// Instr - The instruction this matches.
437 const CodeGenInstruction *Instr;
438
439 /// AsmString - The assembly string for this instruction (with variants
440 /// removed).
441 std::string AsmString;
442
443 /// Tokens - The tokenized assembly pattern that this instruction matches.
444 SmallVector<StringRef, 4> Tokens;
445
446 /// Operands - The operands that this instruction matches.
447 SmallVector<Operand, 4> Operands;
448
Daniel Dunbar54074b52010-07-19 05:44:09 +0000449 /// Predicates - The required subtarget features to match this instruction.
450 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
451
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000452 /// ConversionFnKind - The enum value which is passed to the generated
453 /// ConvertToMCInst to convert parsed operands into an MCInst for this
454 /// function.
455 std::string ConversionFnKind;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000456
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000457 /// operator< - Compare two instructions.
458 bool operator<(const InstructionInfo &RHS) const {
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000459 if (Operands.size() != RHS.Operands.size())
460 return Operands.size() < RHS.Operands.size();
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000461
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000462 // Compare lexicographically by operand. The matcher validates that other
463 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
464 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000465 if (*Operands[i].Class < *RHS.Operands[i].Class)
466 return true;
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000467 if (*RHS.Operands[i].Class < *Operands[i].Class)
468 return false;
469 }
470
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000471 return false;
472 }
473
Daniel Dunbar2b544812009-08-09 06:05:33 +0000474 /// CouldMatchAmiguouslyWith - Check whether this instruction could
475 /// ambiguously match the same set of operands as \arg RHS (without being a
476 /// strictly superior match).
477 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
478 // The number of operands is unambiguous.
479 if (Operands.size() != RHS.Operands.size())
480 return false;
481
Daniel Dunbar1402f0b2010-01-23 00:26:16 +0000482 // Otherwise, make sure the ordering of the two instructions is unambiguous
483 // by checking that either (a) a token or operand kind discriminates them,
484 // or (b) the ordering among equivalent kinds is consistent.
485
Daniel Dunbar2b544812009-08-09 06:05:33 +0000486 // Tokens and operand kinds are unambiguous (assuming a correct target
487 // specific parser).
488 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
489 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
490 Operands[i].Class->Kind == ClassInfo::Token)
491 if (*Operands[i].Class < *RHS.Operands[i].Class ||
492 *RHS.Operands[i].Class < *Operands[i].Class)
493 return false;
494
495 // Otherwise, this operand could commute if all operands are equivalent, or
496 // there is a pair of operands that compare less than and a pair that
497 // compare greater than.
498 bool HasLT = false, HasGT = false;
499 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
500 if (*Operands[i].Class < *RHS.Operands[i].Class)
501 HasLT = true;
502 if (*RHS.Operands[i].Class < *Operands[i].Class)
503 HasGT = true;
504 }
505
506 return !(HasLT ^ HasGT);
507 }
508
Daniel Dunbar20927f22009-08-07 08:26:05 +0000509public:
510 void dump();
511};
512
Daniel Dunbar54074b52010-07-19 05:44:09 +0000513/// SubtargetFeatureInfo - Helper class for storing information on a subtarget
514/// feature which participates in instruction matching.
515struct SubtargetFeatureInfo {
516 /// \brief The predicate record for this feature.
517 Record *TheDef;
518
519 /// \brief An unique index assigned to represent this feature.
520 unsigned Index;
521
522 /// \brief The name of the enumerated constant identifying this feature.
523 std::string EnumName;
524};
525
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000526class AsmMatcherInfo {
527public:
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000528 /// The tablegen AsmParser record.
529 Record *AsmParser;
530
531 /// The AsmParser "CommentDelimiter" value.
532 std::string CommentDelimiter;
533
534 /// The AsmParser "RegisterPrefix" value.
535 std::string RegisterPrefix;
536
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000537 /// The classes which are needed for matching.
538 std::vector<ClassInfo*> Classes;
539
540 /// The information on the instruction to match.
541 std::vector<InstructionInfo*> Instructions;
542
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000543 /// Map of Register records to their class information.
544 std::map<Record*, ClassInfo*> RegisterClasses;
545
Daniel Dunbar54074b52010-07-19 05:44:09 +0000546 /// Map of Predicate records to their subtarget information.
547 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
548
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000549private:
550 /// Map of token to class information which has already been constructed.
551 std::map<std::string, ClassInfo*> TokenClasses;
552
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000553 /// Map of RegisterClass records to their class information.
554 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000555
Daniel Dunbar338825c2009-08-10 18:41:10 +0000556 /// Map of AsmOperandClass records to their class information.
557 std::map<Record*, ClassInfo*> AsmOperandClasses;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000558
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000559private:
560 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000561 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000562
563 /// getOperandClass - Lookup or create the class for the given operand.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000564 ClassInfo *getOperandClass(StringRef Token,
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000565 const CodeGenInstruction::OperandInfo &OI);
566
Daniel Dunbar54074b52010-07-19 05:44:09 +0000567 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
568 /// given operand.
569 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) {
570 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
571
572 SubtargetFeatureInfo *&Entry = SubtargetFeatures[Def];
573 if (!Entry) {
574 Entry = new SubtargetFeatureInfo;
575 Entry->TheDef = Def;
576 Entry->Index = SubtargetFeatures.size() - 1;
577 Entry->EnumName = "Feature_" + Def->getName();
578 assert(Entry->Index < 32 && "Too many subtarget features!");
579 }
580
581 return Entry;
582 }
583
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000584 /// BuildRegisterClasses - Build the ClassInfo* instances for register
585 /// classes.
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000586 void BuildRegisterClasses(CodeGenTarget &Target,
587 std::set<std::string> &SingletonRegisterNames);
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000588
589 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
590 /// operand classes.
591 void BuildOperandClasses(CodeGenTarget &Target);
592
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000593public:
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000594 AsmMatcherInfo(Record *_AsmParser);
595
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000596 /// BuildInfo - Construct the various tables used during matching.
597 void BuildInfo(CodeGenTarget &Target);
598};
599
Daniel Dunbar20927f22009-08-07 08:26:05 +0000600}
601
602void InstructionInfo::dump() {
603 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
604 << ", tokens:[";
605 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
606 errs() << Tokens[i];
607 if (i + 1 != e)
608 errs() << ", ";
609 }
610 errs() << "]\n";
611
612 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
613 Operand &Op = Operands[i];
Daniel Dunbar6745d422009-08-09 05:18:30 +0000614 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000615 if (Op.Class->Kind == ClassInfo::Token) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000616 errs() << '\"' << Tokens[i] << "\"\n";
617 continue;
618 }
619
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000620 if (!Op.OperandInfo) {
621 errs() << "(singleton register)\n";
622 continue;
623 }
624
Benjamin Kramerfa1165a2009-08-08 10:06:30 +0000625 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000626 errs() << OI.Name << " " << OI.Rec->getName()
627 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
628 }
629}
630
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000631static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000632 std::string Res;
633
634 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
635 switch (*it) {
636 case '*': Res += "_STAR_"; break;
637 case '%': Res += "_PCT_"; break;
638 case ':': Res += "_COLON_"; break;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000639
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000640 default:
641 if (isalnum(*it)) {
642 Res += *it;
643 } else {
644 Res += "_" + utostr((unsigned) *it) + "_";
645 }
646 }
647 }
648
649 return Res;
650}
651
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000652/// getRegisterRecord - Get the register record for \arg name, or 0.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000653static Record *getRegisterRecord(CodeGenTarget &Target, StringRef Name) {
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000654 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
655 const CodeGenRegister &Reg = Target.getRegisters()[i];
656 if (Name == Reg.TheDef->getValueAsString("AsmName"))
657 return Reg.TheDef;
658 }
659
660 return 0;
661}
662
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000663ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000664 ClassInfo *&Entry = TokenClasses[Token];
665
666 if (!Entry) {
667 Entry = new ClassInfo();
668 Entry->Kind = ClassInfo::Token;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000669 Entry->ClassName = "Token";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000670 Entry->Name = "MCK_" + getEnumNameForToken(Token);
671 Entry->ValueName = Token;
672 Entry->PredicateMethod = "<invalid>";
673 Entry->RenderMethod = "<invalid>";
674 Classes.push_back(Entry);
675 }
676
677 return Entry;
678}
679
680ClassInfo *
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000681AsmMatcherInfo::getOperandClass(StringRef Token,
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000682 const CodeGenInstruction::OperandInfo &OI) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000683 if (OI.Rec->isSubClassOf("RegisterClass")) {
684 ClassInfo *CI = RegisterClassClasses[OI.Rec];
685
686 if (!CI) {
687 PrintError(OI.Rec->getLoc(), "register class has no class info!");
688 throw std::string("ERROR: Missing register class!");
689 }
690
691 return CI;
692 }
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000693
Daniel Dunbar338825c2009-08-10 18:41:10 +0000694 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
695 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
696 ClassInfo *CI = AsmOperandClasses[MatchClass];
697
698 if (!CI) {
699 PrintError(OI.Rec->getLoc(), "operand has no match class!");
700 throw std::string("ERROR: Missing match class!");
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000701 }
702
Daniel Dunbar338825c2009-08-10 18:41:10 +0000703 return CI;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000704}
705
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000706void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target,
707 std::set<std::string>
708 &SingletonRegisterNames) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000709 std::vector<CodeGenRegisterClass> RegisterClasses;
710 std::vector<CodeGenRegister> Registers;
Daniel Dunbar338825c2009-08-10 18:41:10 +0000711
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000712 RegisterClasses = Target.getRegisterClasses();
713 Registers = Target.getRegisters();
Daniel Dunbar338825c2009-08-10 18:41:10 +0000714
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000715 // The register sets used for matching.
716 std::set< std::set<Record*> > RegisterSets;
717
718 // Gather the defined sets.
719 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
720 ie = RegisterClasses.end(); it != ie; ++it)
721 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
722 it->Elements.end()));
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000723
724 // Add any required singleton sets.
725 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
726 ie = SingletonRegisterNames.end(); it != ie; ++it)
727 if (Record *Rec = getRegisterRecord(Target, *it))
728 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
729
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000730 // Introduce derived sets where necessary (when a register does not determine
731 // a unique register set class), and build the mapping of registers to the set
732 // they should classify to.
733 std::map<Record*, std::set<Record*> > RegisterMap;
734 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
735 ie = Registers.end(); it != ie; ++it) {
736 CodeGenRegister &CGR = *it;
737 // Compute the intersection of all sets containing this register.
738 std::set<Record*> ContainingSet;
739
740 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
741 ie = RegisterSets.end(); it != ie; ++it) {
742 if (!it->count(CGR.TheDef))
743 continue;
744
745 if (ContainingSet.empty()) {
746 ContainingSet = *it;
747 } else {
748 std::set<Record*> Tmp;
749 std::swap(Tmp, ContainingSet);
750 std::insert_iterator< std::set<Record*> > II(ContainingSet,
751 ContainingSet.begin());
752 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
753 II);
754 }
755 }
756
757 if (!ContainingSet.empty()) {
758 RegisterSets.insert(ContainingSet);
759 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
760 }
761 }
762
763 // Construct the register classes.
764 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
765 unsigned Index = 0;
766 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
767 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
768 ClassInfo *CI = new ClassInfo();
769 CI->Kind = ClassInfo::RegisterClass0 + Index;
770 CI->ClassName = "Reg" + utostr(Index);
771 CI->Name = "MCK_Reg" + utostr(Index);
772 CI->ValueName = "";
773 CI->PredicateMethod = ""; // unused
774 CI->RenderMethod = "addRegOperands";
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000775 CI->Registers = *it;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000776 Classes.push_back(CI);
777 RegisterSetClasses.insert(std::make_pair(*it, CI));
778 }
779
780 // Find the superclasses; we could compute only the subgroup lattice edges,
781 // but there isn't really a point.
782 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
783 ie = RegisterSets.end(); it != ie; ++it) {
784 ClassInfo *CI = RegisterSetClasses[*it];
785 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
786 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
787 if (*it != *it2 &&
788 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
789 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
790 }
791
792 // Name the register classes which correspond to a user defined RegisterClass.
793 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
794 ie = RegisterClasses.end(); it != ie; ++it) {
795 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
796 it->Elements.end())];
797 if (CI->ValueName.empty()) {
798 CI->ClassName = it->getName();
799 CI->Name = "MCK_" + it->getName();
800 CI->ValueName = it->getName();
801 } else
802 CI->ValueName = CI->ValueName + "," + it->getName();
803
804 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
805 }
806
807 // Populate the map for individual registers.
808 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
809 ie = RegisterMap.end(); it != ie; ++it)
810 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000811
812 // Name the register classes which correspond to singleton registers.
813 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
814 ie = SingletonRegisterNames.end(); it != ie; ++it) {
815 if (Record *Rec = getRegisterRecord(Target, *it)) {
816 ClassInfo *CI = this->RegisterClasses[Rec];
817 assert(CI && "Missing singleton register class info!");
818
819 if (CI->ValueName.empty()) {
820 CI->ClassName = Rec->getName();
821 CI->Name = "MCK_" + Rec->getName();
822 CI->ValueName = Rec->getName();
823 } else
824 CI->ValueName = CI->ValueName + "," + Rec->getName();
825 }
826 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000827}
828
829void AsmMatcherInfo::BuildOperandClasses(CodeGenTarget &Target) {
Daniel Dunbar338825c2009-08-10 18:41:10 +0000830 std::vector<Record*> AsmOperands;
831 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbara2f5e002010-01-30 01:02:37 +0000832
833 // Pre-populate AsmOperandClasses map.
834 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
835 ie = AsmOperands.end(); it != ie; ++it)
836 AsmOperandClasses[*it] = new ClassInfo();
837
Daniel Dunbar338825c2009-08-10 18:41:10 +0000838 unsigned Index = 0;
839 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
840 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
Daniel Dunbara2f5e002010-01-30 01:02:37 +0000841 ClassInfo *CI = AsmOperandClasses[*it];
Daniel Dunbar338825c2009-08-10 18:41:10 +0000842 CI->Kind = ClassInfo::UserClass0 + Index;
843
Daniel Dunbar54ddf3d2010-05-22 21:02:29 +0000844 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
845 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
846 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
847 if (!DI) {
848 PrintError((*it)->getLoc(), "Invalid super class reference!");
849 continue;
850 }
851
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000852 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
853 if (!SC)
Daniel Dunbar338825c2009-08-10 18:41:10 +0000854 PrintError((*it)->getLoc(), "Invalid super class reference!");
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000855 else
856 CI->SuperClasses.push_back(SC);
Daniel Dunbar338825c2009-08-10 18:41:10 +0000857 }
858 CI->ClassName = (*it)->getValueAsString("Name");
859 CI->Name = "MCK_" + CI->ClassName;
860 CI->ValueName = (*it)->getName();
Daniel Dunbar5c468e32009-08-10 21:00:45 +0000861
862 // Get or construct the predicate method name.
863 Init *PMName = (*it)->getValueInit("PredicateMethod");
864 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
865 CI->PredicateMethod = SI->getValue();
866 } else {
867 assert(dynamic_cast<UnsetInit*>(PMName) &&
868 "Unexpected PredicateMethod field!");
869 CI->PredicateMethod = "is" + CI->ClassName;
870 }
871
872 // Get or construct the render method name.
873 Init *RMName = (*it)->getValueInit("RenderMethod");
874 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
875 CI->RenderMethod = SI->getValue();
876 } else {
877 assert(dynamic_cast<UnsetInit*>(RMName) &&
878 "Unexpected RenderMethod field!");
879 CI->RenderMethod = "add" + CI->ClassName + "Operands";
880 }
881
Daniel Dunbar338825c2009-08-10 18:41:10 +0000882 AsmOperandClasses[*it] = CI;
883 Classes.push_back(CI);
884 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000885}
886
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000887AsmMatcherInfo::AsmMatcherInfo(Record *_AsmParser)
888 : AsmParser(_AsmParser),
889 CommentDelimiter(AsmParser->getValueAsString("CommentDelimiter")),
890 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix"))
891{
892}
893
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000894void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000895 // Parse the instructions; we need to do this first so that we can gather the
896 // singleton register classes.
897 std::set<std::string> SingletonRegisterNames;
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000898
Chris Lattnerf6502782010-03-19 00:34:35 +0000899 const std::vector<const CodeGenInstruction*> &InstrList =
900 Target.getInstructionsByEnumValue();
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000901
902 for (unsigned i = 0, e = InstrList.size(); i != e; ++i) {
903 const CodeGenInstruction &CGI = *InstrList[i];
Daniel Dunbar20927f22009-08-07 08:26:05 +0000904
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000905 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
Daniel Dunbar20927f22009-08-07 08:26:05 +0000906 continue;
907
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000908 OwningPtr<InstructionInfo> II(new InstructionInfo());
Daniel Dunbar20927f22009-08-07 08:26:05 +0000909
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000910 II->InstrName = CGI.TheDef->getName();
911 II->Instr = &CGI;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000912 II->AsmString = FlattenVariants(CGI.AsmString, 0);
913
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000914 // Remove comments from the asm string.
915 if (!CommentDelimiter.empty()) {
916 size_t Idx = StringRef(II->AsmString).find(CommentDelimiter);
917 if (Idx != StringRef::npos)
918 II->AsmString = II->AsmString.substr(0, Idx);
919 }
920
Daniel Dunbar20927f22009-08-07 08:26:05 +0000921 TokenizeAsmString(II->AsmString, II->Tokens);
922
923 // Ignore instructions which shouldn't be matched.
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000924 if (!IsAssemblerInstruction(CGI.TheDef->getName(), CGI, II->Tokens))
Daniel Dunbar20927f22009-08-07 08:26:05 +0000925 continue;
926
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000927 // Collect singleton registers, if used.
928 if (!RegisterPrefix.empty()) {
929 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
930 if (II->Tokens[i].startswith(RegisterPrefix)) {
931 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
932 Record *Rec = getRegisterRecord(Target, RegName);
933
934 if (!Rec) {
935 std::string Err = "unable to find register for '" + RegName.str() +
936 "' (which matches register prefix)";
937 throw TGError(CGI.TheDef->getLoc(), Err);
938 }
939
940 SingletonRegisterNames.insert(RegName);
941 }
942 }
943 }
Daniel Dunbar54074b52010-07-19 05:44:09 +0000944
945 // Compute the require features.
946 ListInit *Predicates = CGI.TheDef->getValueAsListInit("Predicates");
947 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
948 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
949 // Ignore OptForSize and OptForSpeed, they aren't really requirements,
950 // rather they are hints to isel.
951 //
952 // FIXME: Find better way to model this.
953 if (Pred->getDef()->getName() == "OptForSize" ||
954 Pred->getDef()->getName() == "OptForSpeed")
955 continue;
956
957 // FIXME: Total hack; for now, we just limit ourselves to In32BitMode
958 // and In64BitMode, because we aren't going to have the right feature
959 // masks for SSE and friends. We need to decide what we are going to do
960 // about CPU subtypes to implement this the right way.
961 if (Pred->getDef()->getName() != "In32BitMode" &&
962 Pred->getDef()->getName() != "In64BitMode")
963 continue;
964
965 II->RequiredFeatures.push_back(getSubtargetFeature(Pred->getDef()));
966 }
967 }
968
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000969 Instructions.push_back(II.take());
970 }
971
972 // Build info for the register classes.
973 BuildRegisterClasses(Target, SingletonRegisterNames);
974
975 // Build info for the user defined assembly operand classes.
976 BuildOperandClasses(Target);
977
978 // Build the instruction information.
979 for (std::vector<InstructionInfo*>::iterator it = Instructions.begin(),
980 ie = Instructions.end(); it != ie; ++it) {
981 InstructionInfo *II = *it;
982
Daniel Dunbar20927f22009-08-07 08:26:05 +0000983 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
984 StringRef Token = II->Tokens[i];
985
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000986 // Check for singleton registers.
987 if (!RegisterPrefix.empty() && Token.startswith(RegisterPrefix)) {
988 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
989 InstructionInfo::Operand Op;
990 Op.Class = RegisterClasses[getRegisterRecord(Target, RegName)];
991 Op.OperandInfo = 0;
992 assert(Op.Class && Op.Class->Registers.size() == 1 &&
993 "Unexpected class for singleton register");
994 II->Operands.push_back(Op);
995 continue;
996 }
997
Daniel Dunbar20927f22009-08-07 08:26:05 +0000998 // Check for simple tokens.
999 if (Token[0] != '$') {
1000 InstructionInfo::Operand Op;
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001001 Op.Class = getTokenClass(Token);
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001002 Op.OperandInfo = 0;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001003 II->Operands.push_back(Op);
1004 continue;
1005 }
1006
1007 // Otherwise this is an operand reference.
Daniel Dunbar20927f22009-08-07 08:26:05 +00001008 StringRef OperandName;
1009 if (Token[1] == '{')
1010 OperandName = Token.substr(2, Token.size() - 3);
1011 else
1012 OperandName = Token.substr(1);
1013
1014 // Map this token to an operand. FIXME: Move elsewhere.
1015 unsigned Idx;
1016 try {
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001017 Idx = II->Instr->getOperandNamed(OperandName);
Daniel Dunbar20927f22009-08-07 08:26:05 +00001018 } catch(...) {
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001019 throw std::string("error: unable to find operand: '" +
1020 OperandName.str() + "'");
Daniel Dunbar20927f22009-08-07 08:26:05 +00001021 }
1022
Daniel Dunbaraf616812010-02-10 08:15:48 +00001023 // FIXME: This is annoying, the named operand may be tied (e.g.,
1024 // XCHG8rm). What we want is the untied operand, which we now have to
1025 // grovel for. Only worry about this for single entry operands, we have to
1026 // clean this up anyway.
1027 const CodeGenInstruction::OperandInfo *OI = &II->Instr->OperandList[Idx];
1028 if (OI->Constraints[0].isTied()) {
1029 unsigned TiedOp = OI->Constraints[0].getTiedOperand();
1030
1031 // The tied operand index is an MIOperand index, find the operand that
1032 // contains it.
1033 for (unsigned i = 0, e = II->Instr->OperandList.size(); i != e; ++i) {
1034 if (II->Instr->OperandList[i].MIOperandNo == TiedOp) {
1035 OI = &II->Instr->OperandList[i];
1036 break;
1037 }
1038 }
1039
1040 assert(OI && "Unable to find tied operand target!");
1041 }
1042
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001043 InstructionInfo::Operand Op;
Daniel Dunbaraf616812010-02-10 08:15:48 +00001044 Op.Class = getOperandClass(Token, *OI);
1045 Op.OperandInfo = OI;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001046 II->Operands.push_back(Op);
1047 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001048 }
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001049
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001050 // Reorder classes so that classes preceed super classes.
1051 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
Daniel Dunbar20927f22009-08-07 08:26:05 +00001052}
1053
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001054static std::pair<unsigned, unsigned> *
1055GetTiedOperandAtIndex(SmallVectorImpl<std::pair<unsigned, unsigned> > &List,
1056 unsigned Index) {
1057 for (unsigned i = 0, e = List.size(); i != e; ++i)
1058 if (Index == List[i].first)
1059 return &List[i];
1060
1061 return 0;
1062}
1063
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001064static void EmitConvertToMCInst(CodeGenTarget &Target,
1065 std::vector<InstructionInfo*> &Infos,
1066 raw_ostream &OS) {
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001067 // Write the convert function to a separate stream, so we can drop it after
1068 // the enum.
1069 std::string ConvertFnBody;
1070 raw_string_ostream CvtOS(ConvertFnBody);
1071
Daniel Dunbar20927f22009-08-07 08:26:05 +00001072 // Function we have already generated.
1073 std::set<std::string> GeneratedFns;
1074
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001075 // Start the unified conversion function.
1076
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001077 CvtOS << "static void ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001078 << "unsigned Opcode,\n"
Chris Lattner98986712010-01-14 22:21:20 +00001079 << " const SmallVectorImpl<MCParsedAsmOperand*"
1080 << "> &Operands) {\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001081 CvtOS << " Inst.setOpcode(Opcode);\n";
1082 CvtOS << " switch (Kind) {\n";
1083 CvtOS << " default:\n";
1084
1085 // Start the enum, which we will generate inline.
1086
1087 OS << "// Unified function for converting operants to MCInst instances.\n\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001088 OS << "enum ConversionKind {\n";
1089
Chris Lattner98986712010-01-14 22:21:20 +00001090 // TargetOperandClass - This is the target's operand class, like X86Operand.
1091 std::string TargetOperandClass = Target.getName() + "Operand";
1092
Daniel Dunbar20927f22009-08-07 08:26:05 +00001093 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
1094 ie = Infos.end(); it != ie; ++it) {
1095 InstructionInfo &II = **it;
1096
1097 // Order the (class) operands by the order to convert them into an MCInst.
1098 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
1099 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1100 InstructionInfo::Operand &Op = II.Operands[i];
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001101 if (Op.OperandInfo)
1102 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
Daniel Dunbar20927f22009-08-07 08:26:05 +00001103 }
Daniel Dunbaraf616812010-02-10 08:15:48 +00001104
1105 // Find any tied operands.
1106 SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands;
1107 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1108 const CodeGenInstruction::OperandInfo &OpInfo = II.Instr->OperandList[i];
1109 for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) {
1110 const CodeGenInstruction::ConstraintInfo &CI = OpInfo.Constraints[j];
1111 if (CI.isTied())
1112 TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo + j,
1113 CI.getTiedOperand()));
1114 }
1115 }
1116
Daniel Dunbar20927f22009-08-07 08:26:05 +00001117 std::sort(MIOperandList.begin(), MIOperandList.end());
1118
1119 // Compute the total number of operands.
1120 unsigned NumMIOperands = 0;
1121 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1122 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
1123 NumMIOperands = std::max(NumMIOperands,
1124 OI.MIOperandNo + OI.MINumOperands);
1125 }
1126
1127 // Build the conversion function signature.
1128 std::string Signature = "Convert";
1129 unsigned CurIndex = 0;
1130 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1131 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001132 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
Daniel Dunbar20927f22009-08-07 08:26:05 +00001133 "Duplicate match for instruction operand!");
Daniel Dunbar20927f22009-08-07 08:26:05 +00001134
1135 // Skip operands which weren't matched by anything, this occurs when the
1136 // .td file encodes "implicit" operands as explicit ones.
1137 //
1138 // FIXME: This should be removed from the MCInst structure.
Daniel Dunbaraf616812010-02-10 08:15:48 +00001139 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001140 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1141 CurIndex);
1142 if (!Tie)
Daniel Dunbaraf616812010-02-10 08:15:48 +00001143 Signature += "__Imp";
1144 else
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001145 Signature += "__Tie" + utostr(Tie->second);
Daniel Dunbaraf616812010-02-10 08:15:48 +00001146 }
1147
1148 Signature += "__";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001149
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001150 // Registers are always converted the same, don't duplicate the conversion
1151 // function based on them.
1152 //
1153 // FIXME: We could generalize this based on the render method, if it
1154 // mattered.
1155 if (Op.Class->isRegisterClass())
1156 Signature += "Reg";
1157 else
1158 Signature += Op.Class->ClassName;
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001159 Signature += utostr(Op.OperandInfo->MINumOperands);
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001160 Signature += "_" + utostr(MIOperandList[i].second);
1161
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001162 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001163 }
1164
1165 // Add any trailing implicit operands.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001166 for (; CurIndex != NumMIOperands; ++CurIndex) {
1167 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1168 CurIndex);
1169 if (!Tie)
1170 Signature += "__Imp";
1171 else
1172 Signature += "__Tie" + utostr(Tie->second);
1173 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001174
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001175 II.ConversionFnKind = Signature;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001176
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001177 // Check if we have already generated this signature.
Daniel Dunbar20927f22009-08-07 08:26:05 +00001178 if (!GeneratedFns.insert(Signature).second)
1179 continue;
1180
1181 // If not, emit it now.
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001182
1183 // Add to the enum list.
1184 OS << " " << Signature << ",\n";
1185
1186 // And to the convert function.
1187 CvtOS << " case " << Signature << ":\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001188 CurIndex = 0;
1189 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1190 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1191
1192 // Add the implicit operands.
Daniel Dunbaraf616812010-02-10 08:15:48 +00001193 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1194 // See if this is a tied operand.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001195 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1196 CurIndex);
Daniel Dunbaraf616812010-02-10 08:15:48 +00001197
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001198 if (!Tie) {
Daniel Dunbaraf616812010-02-10 08:15:48 +00001199 // If not, this is some implicit operand. Just assume it is a register
1200 // for now.
1201 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1202 } else {
1203 // Copy the tied operand.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001204 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
Daniel Dunbaraf616812010-02-10 08:15:48 +00001205 CvtOS << " Inst.addOperand(Inst.getOperand("
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001206 << Tie->second << "));\n";
Daniel Dunbaraf616812010-02-10 08:15:48 +00001207 }
1208 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001209
Chris Lattner98986712010-01-14 22:21:20 +00001210 CvtOS << " ((" << TargetOperandClass << "*)Operands["
1211 << MIOperandList[i].second
1212 << "])->" << Op.Class->RenderMethod
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001213 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
1214 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001215 }
1216
1217 // And add trailing implicit operands.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001218 for (; CurIndex != NumMIOperands; ++CurIndex) {
1219 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1220 CurIndex);
1221
1222 if (!Tie) {
1223 // If not, this is some implicit operand. Just assume it is a register
1224 // for now.
1225 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1226 } else {
1227 // Copy the tied operand.
1228 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1229 CvtOS << " Inst.addOperand(Inst.getOperand("
1230 << Tie->second << "));\n";
1231 }
1232 }
1233
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001234 CvtOS << " return;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001235 }
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001236
1237 // Finish the convert function.
1238
1239 CvtOS << " }\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001240 CvtOS << "}\n\n";
1241
1242 // Finish the enum, and drop the convert function after it.
1243
1244 OS << " NumConversionVariants\n";
1245 OS << "};\n\n";
1246
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001247 OS << CvtOS.str();
Daniel Dunbara027d222009-07-31 02:32:59 +00001248}
1249
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001250/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1251static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1252 std::vector<ClassInfo*> &Infos,
1253 raw_ostream &OS) {
1254 OS << "namespace {\n\n";
1255
1256 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1257 << "/// instruction matching.\n";
1258 OS << "enum MatchClassKind {\n";
1259 OS << " InvalidMatchClass = 0,\n";
1260 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1261 ie = Infos.end(); it != ie; ++it) {
1262 ClassInfo &CI = **it;
1263 OS << " " << CI.Name << ", // ";
1264 if (CI.Kind == ClassInfo::Token) {
1265 OS << "'" << CI.ValueName << "'\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001266 } else if (CI.isRegisterClass()) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001267 if (!CI.ValueName.empty())
1268 OS << "register class '" << CI.ValueName << "'\n";
1269 else
1270 OS << "derived register class\n";
1271 } else {
1272 OS << "user defined class '" << CI.ValueName << "'\n";
1273 }
1274 }
1275 OS << " NumMatchClassKinds\n";
1276 OS << "};\n\n";
1277
1278 OS << "}\n\n";
1279}
1280
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001281/// EmitClassifyOperand - Emit the function to classify an operand.
1282static void EmitClassifyOperand(CodeGenTarget &Target,
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001283 AsmMatcherInfo &Info,
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001284 raw_ostream &OS) {
Chris Lattner98986712010-01-14 22:21:20 +00001285 OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
1286 << " " << Target.getName() << "Operand &Operand = *("
1287 << Target.getName() << "Operand*)GOp;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001288
1289 // Classify tokens.
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001290 OS << " if (Operand.isToken())\n";
1291 OS << " return MatchTokenString(Operand.getToken());\n\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001292
1293 // Classify registers.
1294 //
1295 // FIXME: Don't hardcode isReg, getReg.
1296 OS << " if (Operand.isReg()) {\n";
1297 OS << " switch (Operand.getReg()) {\n";
1298 OS << " default: return InvalidMatchClass;\n";
1299 for (std::map<Record*, ClassInfo*>::iterator
1300 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1301 it != ie; ++it)
1302 OS << " case " << Target.getName() << "::"
1303 << it->first->getName() << ": return " << it->second->Name << ";\n";
1304 OS << " }\n";
1305 OS << " }\n\n";
1306
1307 // Classify user defined operands.
1308 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1309 ie = Info.Classes.end(); it != ie; ++it) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001310 ClassInfo &CI = **it;
1311
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001312 if (!CI.isUserClass())
1313 continue;
1314
1315 OS << " // '" << CI.ClassName << "' class";
1316 if (!CI.SuperClasses.empty()) {
1317 OS << ", subclass of ";
1318 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1319 if (i) OS << ", ";
1320 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1321 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001322 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001323 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001324 OS << "\n";
1325
1326 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
1327
1328 // Validate subclass relationships.
1329 if (!CI.SuperClasses.empty()) {
1330 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1331 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1332 << "() && \"Invalid class relationship!\");\n";
1333 }
1334
1335 OS << " return " << CI.Name << ";\n";
1336 OS << " }\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001337 }
1338 OS << " return InvalidMatchClass;\n";
1339 OS << "}\n\n";
1340}
1341
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001342/// EmitIsSubclass - Emit the subclass predicate function.
1343static void EmitIsSubclass(CodeGenTarget &Target,
1344 std::vector<ClassInfo*> &Infos,
1345 raw_ostream &OS) {
1346 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1347 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1348 OS << " if (A == B)\n";
1349 OS << " return true;\n\n";
1350
1351 OS << " switch (A) {\n";
1352 OS << " default:\n";
1353 OS << " return false;\n";
1354 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1355 ie = Infos.end(); it != ie; ++it) {
1356 ClassInfo &A = **it;
1357
1358 if (A.Kind != ClassInfo::Token) {
1359 std::vector<StringRef> SuperClasses;
1360 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1361 ie = Infos.end(); it != ie; ++it) {
1362 ClassInfo &B = **it;
1363
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001364 if (&A != &B && A.isSubsetOf(B))
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001365 SuperClasses.push_back(B.Name);
1366 }
1367
1368 if (SuperClasses.empty())
1369 continue;
1370
1371 OS << "\n case " << A.Name << ":\n";
1372
1373 if (SuperClasses.size() == 1) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001374 OS << " return B == " << SuperClasses.back() << ";\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001375 continue;
1376 }
1377
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001378 OS << " switch (B) {\n";
1379 OS << " default: return false;\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001380 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001381 OS << " case " << SuperClasses[i] << ": return true;\n";
1382 OS << " }\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001383 }
1384 }
1385 OS << " }\n";
1386 OS << "}\n\n";
1387}
1388
Chris Lattner70add882009-08-08 20:02:57 +00001389typedef std::pair<std::string, std::string> StringPair;
1390
1391/// FindFirstNonCommonLetter - Find the first character in the keys of the
1392/// string pairs that is not shared across the whole set of strings. All
1393/// strings are assumed to have the same length.
1394static unsigned
1395FindFirstNonCommonLetter(const std::vector<const StringPair*> &Matches) {
1396 assert(!Matches.empty());
1397 for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
1398 // Check to see if letter i is the same across the set.
1399 char Letter = Matches[0]->first[i];
1400
1401 for (unsigned str = 0, e = Matches.size(); str != e; ++str)
1402 if (Matches[str]->first[i] != Letter)
1403 return i;
1404 }
1405
1406 return Matches[0]->first.size();
1407}
1408
1409/// EmitStringMatcherForChar - Given a set of strings that are known to be the
1410/// same length and whose characters leading up to CharNo are the same, emit
1411/// code to verify that CharNo and later are the same.
Daniel Dunbar72ffae92009-08-08 22:57:25 +00001412///
1413/// \return - True if control can leave the emitted code fragment.
1414static bool EmitStringMatcherForChar(const std::string &StrVariableName,
Chris Lattner70add882009-08-08 20:02:57 +00001415 const std::vector<const StringPair*> &Matches,
1416 unsigned CharNo, unsigned IndentCount,
1417 raw_ostream &OS) {
1418 assert(!Matches.empty() && "Must have at least one string to match!");
1419 std::string Indent(IndentCount*2+4, ' ');
1420
1421 // If we have verified that the entire string matches, we're done: output the
1422 // matching code.
1423 if (CharNo == Matches[0]->first.size()) {
1424 assert(Matches.size() == 1 && "Had duplicate keys to match on");
1425
1426 // FIXME: If Matches[0].first has embeded \n, this will be bad.
1427 OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
1428 << "\"\n";
Daniel Dunbar72ffae92009-08-08 22:57:25 +00001429 return false;
Chris Lattner70add882009-08-08 20:02:57 +00001430 }
1431
1432 // Bucket the matches by the character we are comparing.
1433 std::map<char, std::vector<const StringPair*> > MatchesByLetter;
1434
1435 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1436 MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
1437
1438
1439 // If we have exactly one bucket to match, see how many characters are common
1440 // across the whole set and match all of them at once.
Chris Lattner70add882009-08-08 20:02:57 +00001441 if (MatchesByLetter.size() == 1) {
1442 unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
1443 unsigned NumChars = FirstNonCommonLetter-CharNo;
1444
Daniel Dunbar72ffae92009-08-08 22:57:25 +00001445 // Emit code to break out if the prefix doesn't match.
Chris Lattner70add882009-08-08 20:02:57 +00001446 if (NumChars == 1) {
Daniel Dunbar72ffae92009-08-08 22:57:25 +00001447 // Do the comparison with if (Str[1] != 'f')
Chris Lattner70add882009-08-08 20:02:57 +00001448 // FIXME: Need to escape general characters.
Daniel Dunbar72ffae92009-08-08 22:57:25 +00001449 OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
1450 << Matches[0]->first[CharNo] << "')\n";
1451 OS << Indent << " break;\n";
Chris Lattner70add882009-08-08 20:02:57 +00001452 } else {
Daniel Dunbar72ffae92009-08-08 22:57:25 +00001453 // Do the comparison with if (Str.substr(1,3) != "foo").
Chris Lattner70add882009-08-08 20:02:57 +00001454 // FIXME: Need to escape general strings.
Daniel Dunbar72ffae92009-08-08 22:57:25 +00001455 OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
1456 << NumChars << ") != \"";
1457 OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
Daniel Dunbaraf3e9d42009-08-08 23:43:16 +00001458 OS << Indent << " break;\n";
Chris Lattner70add882009-08-08 20:02:57 +00001459 }
1460
Daniel Dunbar72ffae92009-08-08 22:57:25 +00001461 return EmitStringMatcherForChar(StrVariableName, Matches,
1462 FirstNonCommonLetter, IndentCount, OS);
Chris Lattner70add882009-08-08 20:02:57 +00001463 }
1464
1465 // Otherwise, we have multiple possible things, emit a switch on the
1466 // character.
1467 OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
1468 OS << Indent << "default: break;\n";
1469
1470 for (std::map<char, std::vector<const StringPair*> >::iterator LI =
1471 MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
1472 // TODO: escape hard stuff (like \n) if we ever care about it.
1473 OS << Indent << "case '" << LI->first << "':\t // "
1474 << LI->second.size() << " strings to match.\n";
Daniel Dunbar72ffae92009-08-08 22:57:25 +00001475 if (EmitStringMatcherForChar(StrVariableName, LI->second, CharNo+1,
1476 IndentCount+1, OS))
1477 OS << Indent << " break;\n";
Chris Lattner70add882009-08-08 20:02:57 +00001478 }
1479
1480 OS << Indent << "}\n";
Daniel Dunbar72ffae92009-08-08 22:57:25 +00001481 return true;
Chris Lattner70add882009-08-08 20:02:57 +00001482}
1483
1484
1485/// EmitStringMatcher - Given a list of strings and code to execute when they
Daniel Dunbar72ffae92009-08-08 22:57:25 +00001486/// match, output a simple switch tree to classify the input string.
1487///
1488/// If a match is found, the code in Vals[i].second is executed; control must
1489/// not exit this code fragment. If nothing matches, execution falls through.
1490///
1491/// \param StrVariableName - The name of the variable to test.
Chris Lattner70add882009-08-08 20:02:57 +00001492static void EmitStringMatcher(const std::string &StrVariableName,
1493 const std::vector<StringPair> &Matches,
1494 raw_ostream &OS) {
1495 // First level categorization: group strings by length.
1496 std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
1497
1498 for (unsigned i = 0, e = Matches.size(); i != e; ++i)
1499 MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
1500
1501 // Output a switch statement on length and categorize the elements within each
1502 // bin.
1503 OS << " switch (" << StrVariableName << ".size()) {\n";
1504 OS << " default: break;\n";
1505
Chris Lattner70add882009-08-08 20:02:57 +00001506 for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
1507 MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
1508 OS << " case " << LI->first << ":\t // " << LI->second.size()
1509 << " strings to match.\n";
Daniel Dunbar72ffae92009-08-08 22:57:25 +00001510 if (EmitStringMatcherForChar(StrVariableName, LI->second, 0, 0, OS))
1511 OS << " break;\n";
Chris Lattner70add882009-08-08 20:02:57 +00001512 }
1513
Chris Lattner70add882009-08-08 20:02:57 +00001514 OS << " }\n";
1515}
1516
1517
Daniel Dunbar245f0582009-08-08 21:22:41 +00001518/// EmitMatchTokenString - Emit the function to match a token string to the
1519/// appropriate match class value.
1520static void EmitMatchTokenString(CodeGenTarget &Target,
1521 std::vector<ClassInfo*> &Infos,
1522 raw_ostream &OS) {
1523 // Construct the match list.
1524 std::vector<StringPair> Matches;
1525 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1526 ie = Infos.end(); it != ie; ++it) {
1527 ClassInfo &CI = **it;
1528
1529 if (CI.Kind == ClassInfo::Token)
1530 Matches.push_back(StringPair(CI.ValueName, "return " + CI.Name + ";"));
1531 }
1532
Chris Lattnerb8d6e982010-02-09 00:34:28 +00001533 OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001534
1535 EmitStringMatcher("Name", Matches, OS);
1536
1537 OS << " return InvalidMatchClass;\n";
1538 OS << "}\n\n";
1539}
Chris Lattner70add882009-08-08 20:02:57 +00001540
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001541/// EmitMatchRegisterName - Emit the function to match a string to the target
1542/// specific register enum.
1543static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1544 raw_ostream &OS) {
Daniel Dunbar245f0582009-08-08 21:22:41 +00001545 // Construct the match list.
Chris Lattner70add882009-08-08 20:02:57 +00001546 std::vector<StringPair> Matches;
Daniel Dunbar245f0582009-08-08 21:22:41 +00001547 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1548 const CodeGenRegister &Reg = Target.getRegisters()[i];
Daniel Dunbar22be5222009-07-17 18:51:11 +00001549 if (Reg.TheDef->getValueAsString("AsmName").empty())
1550 continue;
1551
Chris Lattner70add882009-08-08 20:02:57 +00001552 Matches.push_back(StringPair(Reg.TheDef->getValueAsString("AsmName"),
Daniel Dunbar245f0582009-08-08 21:22:41 +00001553 "return " + utostr(i + 1) + ";"));
Daniel Dunbar22be5222009-07-17 18:51:11 +00001554 }
Chris Lattner70add882009-08-08 20:02:57 +00001555
Chris Lattnerb8d6e982010-02-09 00:34:28 +00001556 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001557
Chris Lattner70add882009-08-08 20:02:57 +00001558 EmitStringMatcher("Name", Matches, OS);
1559
Daniel Dunbar245f0582009-08-08 21:22:41 +00001560 OS << " return 0;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001561 OS << "}\n\n";
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001562}
Daniel Dunbara027d222009-07-31 02:32:59 +00001563
Daniel Dunbar54074b52010-07-19 05:44:09 +00001564/// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1565/// definitions.
1566static void EmitSubtargetFeatureFlagEnumeration(CodeGenTarget &Target,
1567 AsmMatcherInfo &Info,
1568 raw_ostream &OS) {
1569 OS << "// Flags for subtarget features that participate in "
1570 << "instruction matching.\n";
1571 OS << "enum SubtargetFeatureFlag {\n";
1572 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1573 it = Info.SubtargetFeatures.begin(),
1574 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1575 SubtargetFeatureInfo &SFI = *it->second;
1576 OS << " " << SFI.EnumName << " = (1 << " << SFI.Index << "),\n";
1577 }
1578 OS << " Feature_None = 0\n";
1579 OS << "};\n\n";
1580}
1581
1582/// EmitComputeAvailableFeatures - Emit the function to compute the list of
1583/// available features given a subtarget.
1584static void EmitComputeAvailableFeatures(CodeGenTarget &Target,
1585 AsmMatcherInfo &Info,
1586 raw_ostream &OS) {
1587 std::string ClassName =
1588 Info.AsmParser->getValueAsString("AsmParserClassName");
1589
1590 OS << "unsigned " << Target.getName() << ClassName << "::\n"
1591 << "ComputeAvailableFeatures(const " << Target.getName()
1592 << "Subtarget *Subtarget) const {\n";
1593 OS << " unsigned Features = 0;\n";
1594 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1595 it = Info.SubtargetFeatures.begin(),
1596 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1597 SubtargetFeatureInfo &SFI = *it->second;
1598 OS << " if (" << SFI.TheDef->getValueAsString("CondString")
1599 << ")\n";
1600 OS << " Features |= " << SFI.EnumName << ";\n";
1601 }
1602 OS << " return Features;\n";
1603 OS << "}\n\n";
1604}
1605
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001606void AsmMatcherEmitter::run(raw_ostream &OS) {
1607 CodeGenTarget Target;
1608 Record *AsmParser = Target.getAsmParser();
1609 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1610
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001611 // Compute the information on the instructions to match.
Daniel Dunbar59fc42d2009-08-11 20:59:47 +00001612 AsmMatcherInfo Info(AsmParser);
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001613 Info.BuildInfo(Target);
Daniel Dunbara027d222009-07-31 02:32:59 +00001614
Daniel Dunbare1f6de32010-02-02 23:46:36 +00001615 // Sort the instruction table using the partial order on classes. We use
1616 // stable_sort to ensure that ambiguous instructions are still
1617 // deterministically ordered.
1618 std::stable_sort(Info.Instructions.begin(), Info.Instructions.end(),
1619 less_ptr<InstructionInfo>());
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001620
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001621 DEBUG_WITH_TYPE("instruction_info", {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001622 for (std::vector<InstructionInfo*>::iterator
1623 it = Info.Instructions.begin(), ie = Info.Instructions.end();
1624 it != ie; ++it)
Daniel Dunbar20927f22009-08-07 08:26:05 +00001625 (*it)->dump();
1626 });
Daniel Dunbara027d222009-07-31 02:32:59 +00001627
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001628 // Check for ambiguous instructions.
1629 unsigned NumAmbiguous = 0;
Daniel Dunbar2b544812009-08-09 06:05:33 +00001630 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1631 for (unsigned j = i + 1; j != e; ++j) {
1632 InstructionInfo &A = *Info.Instructions[i];
1633 InstructionInfo &B = *Info.Instructions[j];
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001634
Daniel Dunbar2b544812009-08-09 06:05:33 +00001635 if (A.CouldMatchAmiguouslyWith(B)) {
1636 DEBUG_WITH_TYPE("ambiguous_instrs", {
1637 errs() << "warning: ambiguous instruction match:\n";
1638 A.dump();
1639 errs() << "\nis incomparable with:\n";
1640 B.dump();
1641 errs() << "\n\n";
1642 });
1643 ++NumAmbiguous;
1644 }
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001645 }
1646 }
1647 if (NumAmbiguous)
1648 DEBUG_WITH_TYPE("ambiguous_instrs", {
1649 errs() << "warning: " << NumAmbiguous
1650 << " ambiguous instructions!\n";
1651 });
1652
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001653 // Write the output.
1654
1655 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1656
Daniel Dunbar54074b52010-07-19 05:44:09 +00001657 // Emit the subtarget feature enumeration.
1658 EmitSubtargetFeatureFlagEnumeration(Target, Info, OS);
1659
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001660 // Emit the function to match a register name to number.
1661 EmitMatchRegisterName(Target, AsmParser, OS);
Sean Callanane9b466d2010-01-23 00:40:33 +00001662
1663 OS << "#ifndef REGISTERS_ONLY\n\n";
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001664
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001665 // Generate the unified function to convert operands into an MCInst.
1666 EmitConvertToMCInst(Target, Info.Instructions, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00001667
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001668 // Emit the enumeration for classes which participate in matching.
1669 EmitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00001670
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001671 // Emit the routine to match token strings to their match class.
1672 EmitMatchTokenString(Target, Info.Classes, OS);
1673
1674 // Emit the routine to classify an operand.
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001675 EmitClassifyOperand(Target, Info, OS);
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001676
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001677 // Emit the subclass predicate routine.
1678 EmitIsSubclass(Target, Info.Classes, OS);
1679
Daniel Dunbar54074b52010-07-19 05:44:09 +00001680 // Emit the available features compute function.
1681 EmitComputeAvailableFeatures(Target, Info, OS);
1682
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001683 // Finally, build the match function.
1684
1685 size_t MaxNumOperands = 0;
1686 for (std::vector<InstructionInfo*>::const_iterator it =
1687 Info.Instructions.begin(), ie = Info.Instructions.end();
1688 it != ie; ++it)
1689 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
Daniel Dunbar4f83e732010-05-04 00:33:13 +00001690
1691 const std::string &MatchName =
1692 AsmParser->getValueAsString("MatchInstructionName");
1693 OS << "bool " << Target.getName() << ClassName << "::\n"
1694 << MatchName
1695 << "(const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
1696 OS.indent(MatchName.size() + 1);
1697 OS << "MCInst &Inst) {\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001698
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001699 // Emit the static match table; unused classes get initalized to 0 which is
1700 // guaranteed to be InvalidMatchClass.
1701 //
1702 // FIXME: We can reduce the size of this table very easily. First, we change
1703 // it so that store the kinds in separate bit-fields for each index, which
1704 // only needs to be the max width used for classes at that index (we also need
1705 // to reject based on this during classification). If we then make sure to
1706 // order the match kinds appropriately (putting mnemonics last), then we
1707 // should only end up using a few bits for each class, especially the ones
1708 // following the mnemonic.
Chris Lattnerc6049532009-08-08 19:15:25 +00001709 OS << " static const struct MatchEntry {\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001710 OS << " unsigned Opcode;\n";
1711 OS << " ConversionKind ConvertFn;\n";
1712 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001713 OS << " unsigned RequiredFeatures;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001714 OS << " } MatchTable[" << Info.Instructions.size() << "] = {\n";
1715
1716 for (std::vector<InstructionInfo*>::const_iterator it =
1717 Info.Instructions.begin(), ie = Info.Instructions.end();
1718 it != ie; ++it) {
Daniel Dunbar20927f22009-08-07 08:26:05 +00001719 InstructionInfo &II = **it;
1720
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001721 OS << " { " << Target.getName() << "::" << II.InstrName
1722 << ", " << II.ConversionFnKind << ", { ";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001723 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1724 InstructionInfo::Operand &Op = II.Operands[i];
1725
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001726 if (i) OS << ", ";
1727 OS << Op.Class->Name;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001728 }
Daniel Dunbar54074b52010-07-19 05:44:09 +00001729 OS << " }, ";
1730
1731 // Write the required features mask.
1732 if (!II.RequiredFeatures.empty()) {
1733 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
1734 if (i) OS << "|";
1735 OS << II.RequiredFeatures[i]->EnumName;
1736 }
1737 } else
1738 OS << "0";
1739
1740 OS << "},\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00001741 }
1742
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001743 OS << " };\n\n";
1744
Daniel Dunbar54074b52010-07-19 05:44:09 +00001745
1746 // Emit code to get the available features.
1747 OS << " // Get the current feature set.\n";
1748 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
1749
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001750 // Emit code to compute the class list for this operand vector.
1751 OS << " // Eliminate obvious mismatches.\n";
1752 OS << " if (Operands.size() > " << MaxNumOperands << ")\n";
1753 OS << " return true;\n\n";
1754
1755 OS << " // Compute the class list for this operand vector.\n";
1756 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1757 OS << " for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1758 OS << " Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1759
1760 OS << " // Check for invalid operands before matching.\n";
1761 OS << " if (Classes[i] == InvalidMatchClass)\n";
1762 OS << " return true;\n";
1763 OS << " }\n\n";
1764
1765 OS << " // Mark unused classes.\n";
1766 OS << " for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1767 << "i != e; ++i)\n";
1768 OS << " Classes[i] = InvalidMatchClass;\n\n";
1769
1770 // Emit code to search the table.
1771 OS << " // Search the table.\n";
Chris Lattnerd39bd3a2009-08-08 19:16:05 +00001772 OS << " for (const MatchEntry *it = MatchTable, "
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001773 << "*ie = MatchTable + " << Info.Instructions.size()
1774 << "; it != ie; ++it) {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001775
1776 // Emit check that the required features are available.
1777 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
1778 << "!= it->RequiredFeatures)\n";
1779 OS << " continue;\n";
1780
1781 // Emit check that the subclasses match.
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001782 for (unsigned i = 0; i != MaxNumOperands; ++i) {
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001783 OS << " if (!IsSubclass(Classes["
1784 << i << "], it->Classes[" << i << "]))\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001785 OS << " continue;\n";
1786 }
1787 OS << "\n";
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001788 OS << " ConvertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
1789
1790 // Call the post-processing function, if used.
1791 std::string InsnCleanupFn =
1792 AsmParser->getValueAsString("AsmParserInstCleanup");
1793 if (!InsnCleanupFn.empty())
1794 OS << " " << InsnCleanupFn << "(Inst);\n";
1795
1796 OS << " return false;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001797 OS << " }\n\n";
1798
Daniel Dunbara027d222009-07-31 02:32:59 +00001799 OS << " return true;\n";
1800 OS << "}\n\n";
Sean Callanane9b466d2010-01-23 00:40:33 +00001801
1802 OS << "#endif // REGISTERS_ONLY\n";
Daniel Dunbard51ffcf2009-07-11 19:39:44 +00001803}