blob: 515916efde7694da025ed43d52f60f67280df358 [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"
Chris Lattner5845e5c2010-09-06 02:01:51 +000079#include "StringMatcher.h"
Daniel Dunbar20927f22009-08-07 08:26:05 +000080#include "llvm/ADT/OwningPtr.h"
Daniel Dunbara027d222009-07-31 02:32:59 +000081#include "llvm/ADT/SmallVector.h"
Daniel Dunbar606e8ad2009-08-09 04:00:06 +000082#include "llvm/ADT/STLExtras.h"
Daniel Dunbar20927f22009-08-07 08:26:05 +000083#include "llvm/ADT/StringExtras.h"
84#include "llvm/Support/CommandLine.h"
Daniel Dunbara027d222009-07-31 02:32:59 +000085#include "llvm/Support/Debug.h"
Daniel Dunbara027d222009-07-31 02:32:59 +000086#include <list>
Daniel Dunbarb7479c02009-08-08 05:24:34 +000087#include <map>
88#include <set>
Daniel Dunbard51ffcf2009-07-11 19:39:44 +000089using namespace llvm;
90
Daniel Dunbar27249152009-08-07 20:33:39 +000091static cl::opt<std::string>
Daniel Dunbar606e8ad2009-08-09 04:00:06 +000092MatchPrefix("match-prefix", cl::init(""),
93 cl::desc("Only match instructions with the given prefix"));
Daniel Dunbar20927f22009-08-07 08:26:05 +000094
Daniel Dunbara027d222009-07-31 02:32:59 +000095/// FlattenVariants - Flatten an .td file assembly string by selecting the
96/// variant at index \arg N.
97static std::string FlattenVariants(const std::string &AsmString,
98 unsigned N) {
99 StringRef Cur = AsmString;
100 std::string Res = "";
101
102 for (;;) {
Daniel Dunbar53a7f162009-08-04 20:36:45 +0000103 // Find the start of the next variant string.
104 size_t VariantsStart = 0;
105 for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
106 if (Cur[VariantsStart] == '{' &&
Daniel Dunbar20927f22009-08-07 08:26:05 +0000107 (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
108 Cur[VariantsStart-1] != '\\')))
Daniel Dunbar53a7f162009-08-04 20:36:45 +0000109 break;
Daniel Dunbara027d222009-07-31 02:32:59 +0000110
Daniel Dunbar53a7f162009-08-04 20:36:45 +0000111 // Add the prefix to the result.
112 Res += Cur.slice(0, VariantsStart);
113 if (VariantsStart == Cur.size())
Daniel Dunbara027d222009-07-31 02:32:59 +0000114 break;
115
Daniel Dunbar53a7f162009-08-04 20:36:45 +0000116 ++VariantsStart; // Skip the '{'.
117
118 // Scan to the end of the variants string.
119 size_t VariantsEnd = VariantsStart;
120 unsigned NestedBraces = 1;
121 for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000122 if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
Daniel Dunbar53a7f162009-08-04 20:36:45 +0000123 if (--NestedBraces == 0)
124 break;
125 } else if (Cur[VariantsEnd] == '{')
126 ++NestedBraces;
127 }
Daniel Dunbara027d222009-07-31 02:32:59 +0000128
129 // Select the Nth variant (or empty).
Daniel Dunbar53a7f162009-08-04 20:36:45 +0000130 StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
Daniel Dunbara027d222009-07-31 02:32:59 +0000131 for (unsigned i = 0; i != N; ++i)
132 Selection = Selection.split('|').second;
133 Res += Selection.split('|').first;
134
Daniel Dunbar53a7f162009-08-04 20:36:45 +0000135 assert(VariantsEnd != Cur.size() &&
136 "Unterminated variants in assembly string!");
137 Cur = Cur.substr(VariantsEnd + 1);
Daniel Dunbara027d222009-07-31 02:32:59 +0000138 }
139
140 return Res;
141}
142
143/// TokenizeAsmString - Tokenize a simplified assembly string.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000144static void TokenizeAsmString(StringRef AsmString,
Daniel Dunbara027d222009-07-31 02:32:59 +0000145 SmallVectorImpl<StringRef> &Tokens) {
146 unsigned Prev = 0;
147 bool InTok = true;
148 for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {
149 switch (AsmString[i]) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000150 case '[':
151 case ']':
Daniel Dunbara027d222009-07-31 02:32:59 +0000152 case '*':
153 case '!':
154 case ' ':
155 case '\t':
156 case ',':
157 if (InTok) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000158 Tokens.push_back(AsmString.slice(Prev, i));
Daniel Dunbara027d222009-07-31 02:32:59 +0000159 InTok = false;
160 }
Daniel Dunbar20927f22009-08-07 08:26:05 +0000161 if (!isspace(AsmString[i]) && AsmString[i] != ',')
162 Tokens.push_back(AsmString.substr(i, 1));
Daniel Dunbara027d222009-07-31 02:32:59 +0000163 Prev = i + 1;
164 break;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000165
166 case '\\':
167 if (InTok) {
168 Tokens.push_back(AsmString.slice(Prev, i));
169 InTok = false;
170 }
171 ++i;
172 assert(i != AsmString.size() && "Invalid quoted character");
173 Tokens.push_back(AsmString.substr(i, 1));
174 Prev = i + 1;
175 break;
176
177 case '$': {
178 // If this isn't "${", treat like a normal token.
179 if (i + 1 == AsmString.size() || AsmString[i + 1] != '{') {
180 if (InTok) {
181 Tokens.push_back(AsmString.slice(Prev, i));
182 InTok = false;
183 }
184 Prev = i;
185 break;
186 }
187
188 if (InTok) {
189 Tokens.push_back(AsmString.slice(Prev, i));
190 InTok = false;
191 }
192
193 StringRef::iterator End =
194 std::find(AsmString.begin() + i, AsmString.end(), '}');
195 assert(End != AsmString.end() && "Missing brace in operand reference!");
196 size_t EndPos = End - AsmString.begin();
197 Tokens.push_back(AsmString.slice(i, EndPos+1));
198 Prev = EndPos + 1;
199 i = EndPos;
200 break;
201 }
Daniel Dunbara027d222009-07-31 02:32:59 +0000202
Daniel Dunbar4d39b672010-08-11 06:36:59 +0000203 case '.':
204 if (InTok) {
205 Tokens.push_back(AsmString.slice(Prev, i));
206 }
207 Prev = i;
208 InTok = true;
209 break;
210
Daniel Dunbara027d222009-07-31 02:32:59 +0000211 default:
212 InTok = true;
213 }
214 }
215 if (InTok && Prev != AsmString.size())
Daniel Dunbar20927f22009-08-07 08:26:05 +0000216 Tokens.push_back(AsmString.substr(Prev));
217}
218
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000219static bool IsAssemblerInstruction(StringRef Name,
Daniel Dunbar20927f22009-08-07 08:26:05 +0000220 const CodeGenInstruction &CGI,
221 const SmallVectorImpl<StringRef> &Tokens) {
Daniel Dunbar7417b762009-08-11 22:17:52 +0000222 // Ignore "codegen only" instructions.
223 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
224 return false;
225
226 // Ignore pseudo ops.
Daniel Dunbar20927f22009-08-07 08:26:05 +0000227 //
Daniel Dunbar7417b762009-08-11 22:17:52 +0000228 // FIXME: This is a hack; can we convert these instructions to set the
229 // "codegen only" bit instead?
Daniel Dunbar20927f22009-08-07 08:26:05 +0000230 if (const RecordVal *Form = CGI.TheDef->getValue("Form"))
231 if (Form->getValue()->getAsString() == "Pseudo")
232 return false;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000233
Daniel Dunbar72fa87f2009-08-09 08:19:00 +0000234 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
235 //
236 // FIXME: This is a total hack.
237 if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
238 return false;
239
Daniel Dunbar20927f22009-08-07 08:26:05 +0000240 // Ignore instructions with no .s string.
241 //
242 // FIXME: What are these?
243 if (CGI.AsmString.empty())
244 return false;
245
246 // FIXME: Hack; ignore any instructions with a newline in them.
247 if (std::find(CGI.AsmString.begin(),
248 CGI.AsmString.end(), '\n') != CGI.AsmString.end())
249 return false;
250
251 // Ignore instructions with attributes, these are always fake instructions for
252 // simplifying codegen.
253 //
254 // FIXME: Is this true?
255 //
Daniel Dunbar7417b762009-08-11 22:17:52 +0000256 // Also, check for instructions which reference the operand multiple times;
257 // this implies a constraint we would not honor.
Daniel Dunbar20927f22009-08-07 08:26:05 +0000258 std::set<std::string> OperandNames;
259 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
260 if (Tokens[i][0] == '$' &&
261 std::find(Tokens[i].begin(),
262 Tokens[i].end(), ':') != Tokens[i].end()) {
263 DEBUG({
264 errs() << "warning: '" << Name << "': "
265 << "ignoring instruction; operand with attribute '"
Daniel Dunbar7417b762009-08-11 22:17:52 +0000266 << Tokens[i] << "'\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +0000267 });
268 return false;
269 }
270
271 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
Daniel Dunbara9ba5fe2010-08-11 04:46:08 +0000272 DEBUG({
273 errs() << "warning: '" << Name << "': "
274 << "ignoring instruction with tied operand '"
275 << Tokens[i].str() << "'\n";
276 });
277 return false;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000278 }
279 }
280
281 return true;
282}
283
284namespace {
285
Daniel Dunbar54074b52010-07-19 05:44:09 +0000286struct SubtargetFeatureInfo;
287
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000288/// ClassInfo - Helper class for storing the information about a particular
289/// class of operands which can be matched.
290struct ClassInfo {
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000291 enum ClassInfoKind {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000292 /// Invalid kind, for use as a sentinel value.
293 Invalid = 0,
294
295 /// The class for a particular token.
296 Token,
297
298 /// The (first) register class, subsequent register classes are
299 /// RegisterClass0+1, and so on.
300 RegisterClass0,
301
302 /// The (first) user defined class, subsequent user defined classes are
303 /// UserClass0+1, and so on.
304 UserClass0 = 1<<16
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000305 };
306
307 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
308 /// N) for the Nth user defined class.
309 unsigned Kind;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000310
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000311 /// SuperClasses - The super classes of this class. Note that for simplicities
312 /// sake user operands only record their immediate super class, while register
313 /// operands include all superclasses.
314 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000315
Daniel Dunbar6745d422009-08-09 05:18:30 +0000316 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000317 std::string Name;
318
Daniel Dunbar6745d422009-08-09 05:18:30 +0000319 /// ClassName - The unadorned generic name for this class (e.g., Token).
320 std::string ClassName;
321
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000322 /// ValueName - The name of the value this class represents; for a token this
323 /// is the literal token string, for an operand it is the TableGen class (or
324 /// empty if this is a derived class).
325 std::string ValueName;
326
327 /// PredicateMethod - The name of the operand method to test whether the
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000328 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000329 std::string PredicateMethod;
330
331 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000332 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000333 std::string RenderMethod;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000334
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000335 /// For register classes, the records for all the registers in this class.
336 std::set<Record*> Registers;
337
338public:
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000339 /// isRegisterClass() - Check if this is a register class.
340 bool isRegisterClass() const {
341 return Kind >= RegisterClass0 && Kind < UserClass0;
342 }
343
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000344 /// isUserClass() - Check if this is a user defined class.
345 bool isUserClass() const {
346 return Kind >= UserClass0;
347 }
348
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000349 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
350 /// are related if they are in the same class hierarchy.
351 bool isRelatedTo(const ClassInfo &RHS) const {
352 // Tokens are only related to tokens.
353 if (Kind == Token || RHS.Kind == Token)
354 return Kind == Token && RHS.Kind == Token;
355
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000356 // Registers classes are only related to registers classes, and only if
357 // their intersection is non-empty.
358 if (isRegisterClass() || RHS.isRegisterClass()) {
359 if (!isRegisterClass() || !RHS.isRegisterClass())
360 return false;
361
362 std::set<Record*> Tmp;
363 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
364 std::set_intersection(Registers.begin(), Registers.end(),
365 RHS.Registers.begin(), RHS.Registers.end(),
366 II);
367
368 return !Tmp.empty();
369 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000370
371 // Otherwise we have two users operands; they are related if they are in the
372 // same class hierarchy.
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000373 //
374 // FIXME: This is an oversimplification, they should only be related if they
375 // intersect, however we don't have that information.
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000376 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
377 const ClassInfo *Root = this;
378 while (!Root->SuperClasses.empty())
379 Root = Root->SuperClasses.front();
380
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000381 const ClassInfo *RHSRoot = &RHS;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000382 while (!RHSRoot->SuperClasses.empty())
383 RHSRoot = RHSRoot->SuperClasses.front();
384
385 return Root == RHSRoot;
386 }
387
388 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
389 bool isSubsetOf(const ClassInfo &RHS) const {
390 // This is a subset of RHS if it is the same class...
391 if (this == &RHS)
392 return true;
393
394 // ... or if any of its super classes are a subset of RHS.
395 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
396 ie = SuperClasses.end(); it != ie; ++it)
397 if ((*it)->isSubsetOf(RHS))
398 return true;
399
400 return false;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000401 }
402
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000403 /// operator< - Compare two classes.
404 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar368a4562010-05-27 05:31:32 +0000405 if (this == &RHS)
406 return false;
407
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000408 // Unrelated classes can be ordered by kind.
409 if (!isRelatedTo(RHS))
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000410 return Kind < RHS.Kind;
411
412 switch (Kind) {
Daniel Dunbar6745d422009-08-09 05:18:30 +0000413 case Invalid:
414 assert(0 && "Invalid kind!");
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000415 case Token:
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000416 // Tokens are comparable by value.
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000417 //
418 // FIXME: Compare by enum value.
419 return ValueName < RHS.ValueName;
420
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000421 default:
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000422 // This class preceeds the RHS if it is a proper subset of the RHS.
Daniel Dunbar368a4562010-05-27 05:31:32 +0000423 if (isSubsetOf(RHS))
Duncan Sands34727662010-07-12 08:16:59 +0000424 return true;
Daniel Dunbar368a4562010-05-27 05:31:32 +0000425 if (RHS.isSubsetOf(*this))
Duncan Sands34727662010-07-12 08:16:59 +0000426 return false;
Daniel Dunbar368a4562010-05-27 05:31:32 +0000427
428 // Otherwise, order by name to ensure we have a total ordering.
429 return ValueName < RHS.ValueName;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000430 }
431 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000432};
433
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000434/// InstructionInfo - Helper class for storing the necessary information for an
435/// instruction which is capable of being matched.
Daniel Dunbar20927f22009-08-07 08:26:05 +0000436struct InstructionInfo {
437 struct Operand {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000438 /// The unique class instance this operand should match.
439 ClassInfo *Class;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000440
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000441 /// The original operand this corresponds to, if any.
Benjamin Kramerfa1165a2009-08-08 10:06:30 +0000442 const CodeGenInstruction::OperandInfo *OperandInfo;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000443 };
444
445 /// InstrName - The target name for this instruction.
446 std::string InstrName;
447
448 /// Instr - The instruction this matches.
449 const CodeGenInstruction *Instr;
450
451 /// AsmString - The assembly string for this instruction (with variants
452 /// removed).
453 std::string AsmString;
454
455 /// Tokens - The tokenized assembly pattern that this instruction matches.
456 SmallVector<StringRef, 4> Tokens;
457
458 /// Operands - The operands that this instruction matches.
459 SmallVector<Operand, 4> Operands;
460
Daniel Dunbar54074b52010-07-19 05:44:09 +0000461 /// Predicates - The required subtarget features to match this instruction.
462 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
463
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000464 /// ConversionFnKind - The enum value which is passed to the generated
465 /// ConvertToMCInst to convert parsed operands into an MCInst for this
466 /// function.
467 std::string ConversionFnKind;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000468
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000469 /// operator< - Compare two instructions.
470 bool operator<(const InstructionInfo &RHS) const {
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000471 if (Operands.size() != RHS.Operands.size())
472 return Operands.size() < RHS.Operands.size();
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000473
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000474 // Compare lexicographically by operand. The matcher validates that other
475 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
476 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000477 if (*Operands[i].Class < *RHS.Operands[i].Class)
478 return true;
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000479 if (*RHS.Operands[i].Class < *Operands[i].Class)
480 return false;
481 }
482
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000483 return false;
484 }
485
Daniel Dunbar2b544812009-08-09 06:05:33 +0000486 /// CouldMatchAmiguouslyWith - Check whether this instruction could
487 /// ambiguously match the same set of operands as \arg RHS (without being a
488 /// strictly superior match).
489 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
490 // The number of operands is unambiguous.
491 if (Operands.size() != RHS.Operands.size())
492 return false;
493
Daniel Dunbar1402f0b2010-01-23 00:26:16 +0000494 // Otherwise, make sure the ordering of the two instructions is unambiguous
495 // by checking that either (a) a token or operand kind discriminates them,
496 // or (b) the ordering among equivalent kinds is consistent.
497
Daniel Dunbar2b544812009-08-09 06:05:33 +0000498 // Tokens and operand kinds are unambiguous (assuming a correct target
499 // specific parser).
500 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
501 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
502 Operands[i].Class->Kind == ClassInfo::Token)
503 if (*Operands[i].Class < *RHS.Operands[i].Class ||
504 *RHS.Operands[i].Class < *Operands[i].Class)
505 return false;
506
507 // Otherwise, this operand could commute if all operands are equivalent, or
508 // there is a pair of operands that compare less than and a pair that
509 // compare greater than.
510 bool HasLT = false, HasGT = false;
511 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
512 if (*Operands[i].Class < *RHS.Operands[i].Class)
513 HasLT = true;
514 if (*RHS.Operands[i].Class < *Operands[i].Class)
515 HasGT = true;
516 }
517
518 return !(HasLT ^ HasGT);
519 }
520
Daniel Dunbar20927f22009-08-07 08:26:05 +0000521public:
522 void dump();
523};
524
Daniel Dunbar54074b52010-07-19 05:44:09 +0000525/// SubtargetFeatureInfo - Helper class for storing information on a subtarget
526/// feature which participates in instruction matching.
527struct SubtargetFeatureInfo {
528 /// \brief The predicate record for this feature.
529 Record *TheDef;
530
531 /// \brief An unique index assigned to represent this feature.
532 unsigned Index;
533
534 /// \brief The name of the enumerated constant identifying this feature.
535 std::string EnumName;
536};
537
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000538class AsmMatcherInfo {
539public:
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000540 /// The tablegen AsmParser record.
541 Record *AsmParser;
542
543 /// The AsmParser "CommentDelimiter" value.
544 std::string CommentDelimiter;
545
546 /// The AsmParser "RegisterPrefix" value.
547 std::string RegisterPrefix;
548
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000549 /// The classes which are needed for matching.
550 std::vector<ClassInfo*> Classes;
551
552 /// The information on the instruction to match.
553 std::vector<InstructionInfo*> Instructions;
554
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000555 /// Map of Register records to their class information.
556 std::map<Record*, ClassInfo*> RegisterClasses;
557
Daniel Dunbar54074b52010-07-19 05:44:09 +0000558 /// Map of Predicate records to their subtarget information.
559 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
560
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000561private:
562 /// Map of token to class information which has already been constructed.
563 std::map<std::string, ClassInfo*> TokenClasses;
564
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000565 /// Map of RegisterClass records to their class information.
566 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000567
Daniel Dunbar338825c2009-08-10 18:41:10 +0000568 /// Map of AsmOperandClass records to their class information.
569 std::map<Record*, ClassInfo*> AsmOperandClasses;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000570
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000571private:
572 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000573 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000574
575 /// getOperandClass - Lookup or create the class for the given operand.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000576 ClassInfo *getOperandClass(StringRef Token,
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000577 const CodeGenInstruction::OperandInfo &OI);
578
Daniel Dunbar54074b52010-07-19 05:44:09 +0000579 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
580 /// given operand.
581 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) {
582 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
583
584 SubtargetFeatureInfo *&Entry = SubtargetFeatures[Def];
585 if (!Entry) {
586 Entry = new SubtargetFeatureInfo;
587 Entry->TheDef = Def;
588 Entry->Index = SubtargetFeatures.size() - 1;
589 Entry->EnumName = "Feature_" + Def->getName();
590 assert(Entry->Index < 32 && "Too many subtarget features!");
591 }
592
593 return Entry;
594 }
595
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000596 /// BuildRegisterClasses - Build the ClassInfo* instances for register
597 /// classes.
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000598 void BuildRegisterClasses(CodeGenTarget &Target,
599 std::set<std::string> &SingletonRegisterNames);
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000600
601 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
602 /// operand classes.
603 void BuildOperandClasses(CodeGenTarget &Target);
604
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000605public:
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000606 AsmMatcherInfo(Record *_AsmParser);
607
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000608 /// BuildInfo - Construct the various tables used during matching.
609 void BuildInfo(CodeGenTarget &Target);
610};
611
Daniel Dunbar20927f22009-08-07 08:26:05 +0000612}
613
614void InstructionInfo::dump() {
615 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
616 << ", tokens:[";
617 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
618 errs() << Tokens[i];
619 if (i + 1 != e)
620 errs() << ", ";
621 }
622 errs() << "]\n";
623
624 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
625 Operand &Op = Operands[i];
Daniel Dunbar6745d422009-08-09 05:18:30 +0000626 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000627 if (Op.Class->Kind == ClassInfo::Token) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000628 errs() << '\"' << Tokens[i] << "\"\n";
629 continue;
630 }
631
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000632 if (!Op.OperandInfo) {
633 errs() << "(singleton register)\n";
634 continue;
635 }
636
Benjamin Kramerfa1165a2009-08-08 10:06:30 +0000637 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000638 errs() << OI.Name << " " << OI.Rec->getName()
639 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
640 }
641}
642
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000643static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000644 std::string Res;
645
646 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
647 switch (*it) {
648 case '*': Res += "_STAR_"; break;
649 case '%': Res += "_PCT_"; break;
650 case ':': Res += "_COLON_"; break;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000651
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000652 default:
653 if (isalnum(*it)) {
654 Res += *it;
655 } else {
656 Res += "_" + utostr((unsigned) *it) + "_";
657 }
658 }
659 }
660
661 return Res;
662}
663
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000664/// getRegisterRecord - Get the register record for \arg name, or 0.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000665static Record *getRegisterRecord(CodeGenTarget &Target, StringRef Name) {
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000666 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
667 const CodeGenRegister &Reg = Target.getRegisters()[i];
668 if (Name == Reg.TheDef->getValueAsString("AsmName"))
669 return Reg.TheDef;
670 }
671
672 return 0;
673}
674
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000675ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000676 ClassInfo *&Entry = TokenClasses[Token];
677
678 if (!Entry) {
679 Entry = new ClassInfo();
680 Entry->Kind = ClassInfo::Token;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000681 Entry->ClassName = "Token";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000682 Entry->Name = "MCK_" + getEnumNameForToken(Token);
683 Entry->ValueName = Token;
684 Entry->PredicateMethod = "<invalid>";
685 Entry->RenderMethod = "<invalid>";
686 Classes.push_back(Entry);
687 }
688
689 return Entry;
690}
691
692ClassInfo *
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000693AsmMatcherInfo::getOperandClass(StringRef Token,
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000694 const CodeGenInstruction::OperandInfo &OI) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000695 if (OI.Rec->isSubClassOf("RegisterClass")) {
696 ClassInfo *CI = RegisterClassClasses[OI.Rec];
697
698 if (!CI) {
699 PrintError(OI.Rec->getLoc(), "register class has no class info!");
700 throw std::string("ERROR: Missing register class!");
701 }
702
703 return CI;
704 }
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000705
Daniel Dunbar338825c2009-08-10 18:41:10 +0000706 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
707 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
708 ClassInfo *CI = AsmOperandClasses[MatchClass];
709
710 if (!CI) {
711 PrintError(OI.Rec->getLoc(), "operand has no match class!");
712 throw std::string("ERROR: Missing match class!");
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000713 }
714
Daniel Dunbar338825c2009-08-10 18:41:10 +0000715 return CI;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000716}
717
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000718void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target,
719 std::set<std::string>
720 &SingletonRegisterNames) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000721 std::vector<CodeGenRegisterClass> RegisterClasses;
722 std::vector<CodeGenRegister> Registers;
Daniel Dunbar338825c2009-08-10 18:41:10 +0000723
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000724 RegisterClasses = Target.getRegisterClasses();
725 Registers = Target.getRegisters();
Daniel Dunbar338825c2009-08-10 18:41:10 +0000726
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000727 // The register sets used for matching.
728 std::set< std::set<Record*> > RegisterSets;
729
730 // Gather the defined sets.
731 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
732 ie = RegisterClasses.end(); it != ie; ++it)
733 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
734 it->Elements.end()));
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000735
736 // Add any required singleton sets.
737 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
738 ie = SingletonRegisterNames.end(); it != ie; ++it)
739 if (Record *Rec = getRegisterRecord(Target, *it))
740 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
741
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000742 // Introduce derived sets where necessary (when a register does not determine
743 // a unique register set class), and build the mapping of registers to the set
744 // they should classify to.
745 std::map<Record*, std::set<Record*> > RegisterMap;
746 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
747 ie = Registers.end(); it != ie; ++it) {
748 CodeGenRegister &CGR = *it;
749 // Compute the intersection of all sets containing this register.
750 std::set<Record*> ContainingSet;
751
752 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
753 ie = RegisterSets.end(); it != ie; ++it) {
754 if (!it->count(CGR.TheDef))
755 continue;
756
757 if (ContainingSet.empty()) {
758 ContainingSet = *it;
759 } else {
760 std::set<Record*> Tmp;
761 std::swap(Tmp, ContainingSet);
762 std::insert_iterator< std::set<Record*> > II(ContainingSet,
763 ContainingSet.begin());
764 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
765 II);
766 }
767 }
768
769 if (!ContainingSet.empty()) {
770 RegisterSets.insert(ContainingSet);
771 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
772 }
773 }
774
775 // Construct the register classes.
776 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
777 unsigned Index = 0;
778 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
779 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
780 ClassInfo *CI = new ClassInfo();
781 CI->Kind = ClassInfo::RegisterClass0 + Index;
782 CI->ClassName = "Reg" + utostr(Index);
783 CI->Name = "MCK_Reg" + utostr(Index);
784 CI->ValueName = "";
785 CI->PredicateMethod = ""; // unused
786 CI->RenderMethod = "addRegOperands";
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000787 CI->Registers = *it;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000788 Classes.push_back(CI);
789 RegisterSetClasses.insert(std::make_pair(*it, CI));
790 }
791
792 // Find the superclasses; we could compute only the subgroup lattice edges,
793 // but there isn't really a point.
794 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
795 ie = RegisterSets.end(); it != ie; ++it) {
796 ClassInfo *CI = RegisterSetClasses[*it];
797 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
798 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
799 if (*it != *it2 &&
800 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
801 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
802 }
803
804 // Name the register classes which correspond to a user defined RegisterClass.
805 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
806 ie = RegisterClasses.end(); it != ie; ++it) {
807 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
808 it->Elements.end())];
809 if (CI->ValueName.empty()) {
810 CI->ClassName = it->getName();
811 CI->Name = "MCK_" + it->getName();
812 CI->ValueName = it->getName();
813 } else
814 CI->ValueName = CI->ValueName + "," + it->getName();
815
816 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
817 }
818
819 // Populate the map for individual registers.
820 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
821 ie = RegisterMap.end(); it != ie; ++it)
822 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000823
824 // Name the register classes which correspond to singleton registers.
825 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
826 ie = SingletonRegisterNames.end(); it != ie; ++it) {
827 if (Record *Rec = getRegisterRecord(Target, *it)) {
828 ClassInfo *CI = this->RegisterClasses[Rec];
829 assert(CI && "Missing singleton register class info!");
830
831 if (CI->ValueName.empty()) {
832 CI->ClassName = Rec->getName();
833 CI->Name = "MCK_" + Rec->getName();
834 CI->ValueName = Rec->getName();
835 } else
836 CI->ValueName = CI->ValueName + "," + Rec->getName();
837 }
838 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000839}
840
841void AsmMatcherInfo::BuildOperandClasses(CodeGenTarget &Target) {
Daniel Dunbar338825c2009-08-10 18:41:10 +0000842 std::vector<Record*> AsmOperands;
843 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbara2f5e002010-01-30 01:02:37 +0000844
845 // Pre-populate AsmOperandClasses map.
846 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
847 ie = AsmOperands.end(); it != ie; ++it)
848 AsmOperandClasses[*it] = new ClassInfo();
849
Daniel Dunbar338825c2009-08-10 18:41:10 +0000850 unsigned Index = 0;
851 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
852 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
Daniel Dunbara2f5e002010-01-30 01:02:37 +0000853 ClassInfo *CI = AsmOperandClasses[*it];
Daniel Dunbar338825c2009-08-10 18:41:10 +0000854 CI->Kind = ClassInfo::UserClass0 + Index;
855
Daniel Dunbar54ddf3d2010-05-22 21:02:29 +0000856 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
857 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
858 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
859 if (!DI) {
860 PrintError((*it)->getLoc(), "Invalid super class reference!");
861 continue;
862 }
863
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000864 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
865 if (!SC)
Daniel Dunbar338825c2009-08-10 18:41:10 +0000866 PrintError((*it)->getLoc(), "Invalid super class reference!");
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000867 else
868 CI->SuperClasses.push_back(SC);
Daniel Dunbar338825c2009-08-10 18:41:10 +0000869 }
870 CI->ClassName = (*it)->getValueAsString("Name");
871 CI->Name = "MCK_" + CI->ClassName;
872 CI->ValueName = (*it)->getName();
Daniel Dunbar5c468e32009-08-10 21:00:45 +0000873
874 // Get or construct the predicate method name.
875 Init *PMName = (*it)->getValueInit("PredicateMethod");
876 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
877 CI->PredicateMethod = SI->getValue();
878 } else {
879 assert(dynamic_cast<UnsetInit*>(PMName) &&
880 "Unexpected PredicateMethod field!");
881 CI->PredicateMethod = "is" + CI->ClassName;
882 }
883
884 // Get or construct the render method name.
885 Init *RMName = (*it)->getValueInit("RenderMethod");
886 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
887 CI->RenderMethod = SI->getValue();
888 } else {
889 assert(dynamic_cast<UnsetInit*>(RMName) &&
890 "Unexpected RenderMethod field!");
891 CI->RenderMethod = "add" + CI->ClassName + "Operands";
892 }
893
Daniel Dunbar338825c2009-08-10 18:41:10 +0000894 AsmOperandClasses[*it] = CI;
895 Classes.push_back(CI);
896 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000897}
898
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000899AsmMatcherInfo::AsmMatcherInfo(Record *_AsmParser)
900 : AsmParser(_AsmParser),
901 CommentDelimiter(AsmParser->getValueAsString("CommentDelimiter")),
902 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix"))
903{
904}
905
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000906void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000907 // Parse the instructions; we need to do this first so that we can gather the
908 // singleton register classes.
909 std::set<std::string> SingletonRegisterNames;
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000910
Chris Lattnerf6502782010-03-19 00:34:35 +0000911 const std::vector<const CodeGenInstruction*> &InstrList =
912 Target.getInstructionsByEnumValue();
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000913
914 for (unsigned i = 0, e = InstrList.size(); i != e; ++i) {
915 const CodeGenInstruction &CGI = *InstrList[i];
Daniel Dunbar20927f22009-08-07 08:26:05 +0000916
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000917 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
Daniel Dunbar20927f22009-08-07 08:26:05 +0000918 continue;
919
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000920 OwningPtr<InstructionInfo> II(new InstructionInfo());
Daniel Dunbar20927f22009-08-07 08:26:05 +0000921
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000922 II->InstrName = CGI.TheDef->getName();
923 II->Instr = &CGI;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000924 II->AsmString = FlattenVariants(CGI.AsmString, 0);
925
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000926 // Remove comments from the asm string.
927 if (!CommentDelimiter.empty()) {
928 size_t Idx = StringRef(II->AsmString).find(CommentDelimiter);
929 if (Idx != StringRef::npos)
930 II->AsmString = II->AsmString.substr(0, Idx);
931 }
932
Daniel Dunbar20927f22009-08-07 08:26:05 +0000933 TokenizeAsmString(II->AsmString, II->Tokens);
934
935 // Ignore instructions which shouldn't be matched.
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000936 if (!IsAssemblerInstruction(CGI.TheDef->getName(), CGI, II->Tokens))
Daniel Dunbar20927f22009-08-07 08:26:05 +0000937 continue;
938
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000939 // Collect singleton registers, if used.
940 if (!RegisterPrefix.empty()) {
941 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
942 if (II->Tokens[i].startswith(RegisterPrefix)) {
943 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
944 Record *Rec = getRegisterRecord(Target, RegName);
945
946 if (!Rec) {
947 std::string Err = "unable to find register for '" + RegName.str() +
948 "' (which matches register prefix)";
949 throw TGError(CGI.TheDef->getLoc(), Err);
950 }
951
952 SingletonRegisterNames.insert(RegName);
953 }
954 }
955 }
Daniel Dunbar54074b52010-07-19 05:44:09 +0000956
957 // Compute the require features.
958 ListInit *Predicates = CGI.TheDef->getValueAsListInit("Predicates");
959 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
960 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
961 // Ignore OptForSize and OptForSpeed, they aren't really requirements,
962 // rather they are hints to isel.
963 //
964 // FIXME: Find better way to model this.
965 if (Pred->getDef()->getName() == "OptForSize" ||
966 Pred->getDef()->getName() == "OptForSpeed")
967 continue;
968
969 // FIXME: Total hack; for now, we just limit ourselves to In32BitMode
970 // and In64BitMode, because we aren't going to have the right feature
971 // masks for SSE and friends. We need to decide what we are going to do
972 // about CPU subtypes to implement this the right way.
973 if (Pred->getDef()->getName() != "In32BitMode" &&
974 Pred->getDef()->getName() != "In64BitMode")
975 continue;
976
977 II->RequiredFeatures.push_back(getSubtargetFeature(Pred->getDef()));
978 }
979 }
980
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000981 Instructions.push_back(II.take());
982 }
983
984 // Build info for the register classes.
985 BuildRegisterClasses(Target, SingletonRegisterNames);
986
987 // Build info for the user defined assembly operand classes.
988 BuildOperandClasses(Target);
989
990 // Build the instruction information.
991 for (std::vector<InstructionInfo*>::iterator it = Instructions.begin(),
992 ie = Instructions.end(); it != ie; ++it) {
993 InstructionInfo *II = *it;
994
Daniel Dunbar20927f22009-08-07 08:26:05 +0000995 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
996 StringRef Token = II->Tokens[i];
997
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000998 // Check for singleton registers.
999 if (!RegisterPrefix.empty() && Token.startswith(RegisterPrefix)) {
1000 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
1001 InstructionInfo::Operand Op;
1002 Op.Class = RegisterClasses[getRegisterRecord(Target, RegName)];
1003 Op.OperandInfo = 0;
1004 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1005 "Unexpected class for singleton register");
1006 II->Operands.push_back(Op);
1007 continue;
1008 }
1009
Daniel Dunbar20927f22009-08-07 08:26:05 +00001010 // Check for simple tokens.
1011 if (Token[0] != '$') {
1012 InstructionInfo::Operand Op;
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001013 Op.Class = getTokenClass(Token);
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001014 Op.OperandInfo = 0;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001015 II->Operands.push_back(Op);
1016 continue;
1017 }
1018
1019 // Otherwise this is an operand reference.
Daniel Dunbar20927f22009-08-07 08:26:05 +00001020 StringRef OperandName;
1021 if (Token[1] == '{')
1022 OperandName = Token.substr(2, Token.size() - 3);
1023 else
1024 OperandName = Token.substr(1);
1025
1026 // Map this token to an operand. FIXME: Move elsewhere.
1027 unsigned Idx;
1028 try {
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001029 Idx = II->Instr->getOperandNamed(OperandName);
Daniel Dunbar20927f22009-08-07 08:26:05 +00001030 } catch(...) {
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001031 throw std::string("error: unable to find operand: '" +
1032 OperandName.str() + "'");
Daniel Dunbar20927f22009-08-07 08:26:05 +00001033 }
1034
Daniel Dunbaraf616812010-02-10 08:15:48 +00001035 // FIXME: This is annoying, the named operand may be tied (e.g.,
1036 // XCHG8rm). What we want is the untied operand, which we now have to
1037 // grovel for. Only worry about this for single entry operands, we have to
1038 // clean this up anyway.
1039 const CodeGenInstruction::OperandInfo *OI = &II->Instr->OperandList[Idx];
1040 if (OI->Constraints[0].isTied()) {
1041 unsigned TiedOp = OI->Constraints[0].getTiedOperand();
1042
1043 // The tied operand index is an MIOperand index, find the operand that
1044 // contains it.
1045 for (unsigned i = 0, e = II->Instr->OperandList.size(); i != e; ++i) {
1046 if (II->Instr->OperandList[i].MIOperandNo == TiedOp) {
1047 OI = &II->Instr->OperandList[i];
1048 break;
1049 }
1050 }
1051
1052 assert(OI && "Unable to find tied operand target!");
1053 }
1054
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001055 InstructionInfo::Operand Op;
Daniel Dunbaraf616812010-02-10 08:15:48 +00001056 Op.Class = getOperandClass(Token, *OI);
1057 Op.OperandInfo = OI;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001058 II->Operands.push_back(Op);
1059 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001060 }
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001061
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001062 // Reorder classes so that classes preceed super classes.
1063 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
Daniel Dunbar20927f22009-08-07 08:26:05 +00001064}
1065
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001066static std::pair<unsigned, unsigned> *
1067GetTiedOperandAtIndex(SmallVectorImpl<std::pair<unsigned, unsigned> > &List,
1068 unsigned Index) {
1069 for (unsigned i = 0, e = List.size(); i != e; ++i)
1070 if (Index == List[i].first)
1071 return &List[i];
1072
1073 return 0;
1074}
1075
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001076static void EmitConvertToMCInst(CodeGenTarget &Target,
1077 std::vector<InstructionInfo*> &Infos,
1078 raw_ostream &OS) {
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001079 // Write the convert function to a separate stream, so we can drop it after
1080 // the enum.
1081 std::string ConvertFnBody;
1082 raw_string_ostream CvtOS(ConvertFnBody);
1083
Daniel Dunbar20927f22009-08-07 08:26:05 +00001084 // Function we have already generated.
1085 std::set<std::string> GeneratedFns;
1086
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001087 // Start the unified conversion function.
1088
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001089 CvtOS << "static void ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001090 << "unsigned Opcode,\n"
Chris Lattner98986712010-01-14 22:21:20 +00001091 << " const SmallVectorImpl<MCParsedAsmOperand*"
1092 << "> &Operands) {\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001093 CvtOS << " Inst.setOpcode(Opcode);\n";
1094 CvtOS << " switch (Kind) {\n";
1095 CvtOS << " default:\n";
1096
1097 // Start the enum, which we will generate inline.
1098
1099 OS << "// Unified function for converting operants to MCInst instances.\n\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001100 OS << "enum ConversionKind {\n";
1101
Chris Lattner98986712010-01-14 22:21:20 +00001102 // TargetOperandClass - This is the target's operand class, like X86Operand.
1103 std::string TargetOperandClass = Target.getName() + "Operand";
1104
Daniel Dunbar20927f22009-08-07 08:26:05 +00001105 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
1106 ie = Infos.end(); it != ie; ++it) {
1107 InstructionInfo &II = **it;
1108
1109 // Order the (class) operands by the order to convert them into an MCInst.
1110 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
1111 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1112 InstructionInfo::Operand &Op = II.Operands[i];
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001113 if (Op.OperandInfo)
1114 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
Daniel Dunbar20927f22009-08-07 08:26:05 +00001115 }
Daniel Dunbaraf616812010-02-10 08:15:48 +00001116
1117 // Find any tied operands.
1118 SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands;
1119 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1120 const CodeGenInstruction::OperandInfo &OpInfo = II.Instr->OperandList[i];
1121 for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) {
1122 const CodeGenInstruction::ConstraintInfo &CI = OpInfo.Constraints[j];
1123 if (CI.isTied())
1124 TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo + j,
1125 CI.getTiedOperand()));
1126 }
1127 }
1128
Daniel Dunbar20927f22009-08-07 08:26:05 +00001129 std::sort(MIOperandList.begin(), MIOperandList.end());
1130
1131 // Compute the total number of operands.
1132 unsigned NumMIOperands = 0;
1133 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1134 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
1135 NumMIOperands = std::max(NumMIOperands,
1136 OI.MIOperandNo + OI.MINumOperands);
1137 }
1138
1139 // Build the conversion function signature.
1140 std::string Signature = "Convert";
1141 unsigned CurIndex = 0;
1142 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1143 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001144 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
Daniel Dunbar20927f22009-08-07 08:26:05 +00001145 "Duplicate match for instruction operand!");
Daniel Dunbar20927f22009-08-07 08:26:05 +00001146
1147 // Skip operands which weren't matched by anything, this occurs when the
1148 // .td file encodes "implicit" operands as explicit ones.
1149 //
1150 // FIXME: This should be removed from the MCInst structure.
Daniel Dunbaraf616812010-02-10 08:15:48 +00001151 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001152 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1153 CurIndex);
1154 if (!Tie)
Daniel Dunbaraf616812010-02-10 08:15:48 +00001155 Signature += "__Imp";
1156 else
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001157 Signature += "__Tie" + utostr(Tie->second);
Daniel Dunbaraf616812010-02-10 08:15:48 +00001158 }
1159
1160 Signature += "__";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001161
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001162 // Registers are always converted the same, don't duplicate the conversion
1163 // function based on them.
1164 //
1165 // FIXME: We could generalize this based on the render method, if it
1166 // mattered.
1167 if (Op.Class->isRegisterClass())
1168 Signature += "Reg";
1169 else
1170 Signature += Op.Class->ClassName;
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001171 Signature += utostr(Op.OperandInfo->MINumOperands);
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001172 Signature += "_" + utostr(MIOperandList[i].second);
1173
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001174 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001175 }
1176
1177 // Add any trailing implicit operands.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001178 for (; CurIndex != NumMIOperands; ++CurIndex) {
1179 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1180 CurIndex);
1181 if (!Tie)
1182 Signature += "__Imp";
1183 else
1184 Signature += "__Tie" + utostr(Tie->second);
1185 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001186
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001187 II.ConversionFnKind = Signature;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001188
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001189 // Check if we have already generated this signature.
Daniel Dunbar20927f22009-08-07 08:26:05 +00001190 if (!GeneratedFns.insert(Signature).second)
1191 continue;
1192
1193 // If not, emit it now.
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001194
1195 // Add to the enum list.
1196 OS << " " << Signature << ",\n";
1197
1198 // And to the convert function.
1199 CvtOS << " case " << Signature << ":\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001200 CurIndex = 0;
1201 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1202 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1203
1204 // Add the implicit operands.
Daniel Dunbaraf616812010-02-10 08:15:48 +00001205 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1206 // See if this is a tied operand.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001207 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1208 CurIndex);
Daniel Dunbaraf616812010-02-10 08:15:48 +00001209
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001210 if (!Tie) {
Daniel Dunbaraf616812010-02-10 08:15:48 +00001211 // If not, this is some implicit operand. Just assume it is a register
1212 // for now.
1213 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1214 } else {
1215 // Copy the tied operand.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001216 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
Daniel Dunbaraf616812010-02-10 08:15:48 +00001217 CvtOS << " Inst.addOperand(Inst.getOperand("
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001218 << Tie->second << "));\n";
Daniel Dunbaraf616812010-02-10 08:15:48 +00001219 }
1220 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001221
Chris Lattner98986712010-01-14 22:21:20 +00001222 CvtOS << " ((" << TargetOperandClass << "*)Operands["
1223 << MIOperandList[i].second
1224 << "])->" << Op.Class->RenderMethod
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001225 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
1226 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001227 }
1228
1229 // And add trailing implicit operands.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001230 for (; CurIndex != NumMIOperands; ++CurIndex) {
1231 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1232 CurIndex);
1233
1234 if (!Tie) {
1235 // If not, this is some implicit operand. Just assume it is a register
1236 // for now.
1237 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1238 } else {
1239 // Copy the tied operand.
1240 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1241 CvtOS << " Inst.addOperand(Inst.getOperand("
1242 << Tie->second << "));\n";
1243 }
1244 }
1245
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001246 CvtOS << " return;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001247 }
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001248
1249 // Finish the convert function.
1250
1251 CvtOS << " }\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001252 CvtOS << "}\n\n";
1253
1254 // Finish the enum, and drop the convert function after it.
1255
1256 OS << " NumConversionVariants\n";
1257 OS << "};\n\n";
1258
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001259 OS << CvtOS.str();
Daniel Dunbara027d222009-07-31 02:32:59 +00001260}
1261
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001262/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1263static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1264 std::vector<ClassInfo*> &Infos,
1265 raw_ostream &OS) {
1266 OS << "namespace {\n\n";
1267
1268 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1269 << "/// instruction matching.\n";
1270 OS << "enum MatchClassKind {\n";
1271 OS << " InvalidMatchClass = 0,\n";
1272 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1273 ie = Infos.end(); it != ie; ++it) {
1274 ClassInfo &CI = **it;
1275 OS << " " << CI.Name << ", // ";
1276 if (CI.Kind == ClassInfo::Token) {
1277 OS << "'" << CI.ValueName << "'\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001278 } else if (CI.isRegisterClass()) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001279 if (!CI.ValueName.empty())
1280 OS << "register class '" << CI.ValueName << "'\n";
1281 else
1282 OS << "derived register class\n";
1283 } else {
1284 OS << "user defined class '" << CI.ValueName << "'\n";
1285 }
1286 }
1287 OS << " NumMatchClassKinds\n";
1288 OS << "};\n\n";
1289
1290 OS << "}\n\n";
1291}
1292
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001293/// EmitClassifyOperand - Emit the function to classify an operand.
1294static void EmitClassifyOperand(CodeGenTarget &Target,
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001295 AsmMatcherInfo &Info,
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001296 raw_ostream &OS) {
Chris Lattner98986712010-01-14 22:21:20 +00001297 OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
1298 << " " << Target.getName() << "Operand &Operand = *("
1299 << Target.getName() << "Operand*)GOp;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001300
1301 // Classify tokens.
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001302 OS << " if (Operand.isToken())\n";
1303 OS << " return MatchTokenString(Operand.getToken());\n\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001304
1305 // Classify registers.
1306 //
1307 // FIXME: Don't hardcode isReg, getReg.
1308 OS << " if (Operand.isReg()) {\n";
1309 OS << " switch (Operand.getReg()) {\n";
1310 OS << " default: return InvalidMatchClass;\n";
1311 for (std::map<Record*, ClassInfo*>::iterator
1312 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1313 it != ie; ++it)
1314 OS << " case " << Target.getName() << "::"
1315 << it->first->getName() << ": return " << it->second->Name << ";\n";
1316 OS << " }\n";
1317 OS << " }\n\n";
1318
1319 // Classify user defined operands.
1320 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
1321 ie = Info.Classes.end(); it != ie; ++it) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001322 ClassInfo &CI = **it;
1323
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001324 if (!CI.isUserClass())
1325 continue;
1326
1327 OS << " // '" << CI.ClassName << "' class";
1328 if (!CI.SuperClasses.empty()) {
1329 OS << ", subclass of ";
1330 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1331 if (i) OS << ", ";
1332 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1333 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001334 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001335 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001336 OS << "\n";
1337
1338 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
1339
1340 // Validate subclass relationships.
1341 if (!CI.SuperClasses.empty()) {
1342 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1343 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1344 << "() && \"Invalid class relationship!\");\n";
1345 }
1346
1347 OS << " return " << CI.Name << ";\n";
1348 OS << " }\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001349 }
1350 OS << " return InvalidMatchClass;\n";
1351 OS << "}\n\n";
1352}
1353
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001354/// EmitIsSubclass - Emit the subclass predicate function.
1355static void EmitIsSubclass(CodeGenTarget &Target,
1356 std::vector<ClassInfo*> &Infos,
1357 raw_ostream &OS) {
1358 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1359 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1360 OS << " if (A == B)\n";
1361 OS << " return true;\n\n";
1362
1363 OS << " switch (A) {\n";
1364 OS << " default:\n";
1365 OS << " return false;\n";
1366 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1367 ie = Infos.end(); it != ie; ++it) {
1368 ClassInfo &A = **it;
1369
1370 if (A.Kind != ClassInfo::Token) {
1371 std::vector<StringRef> SuperClasses;
1372 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1373 ie = Infos.end(); it != ie; ++it) {
1374 ClassInfo &B = **it;
1375
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001376 if (&A != &B && A.isSubsetOf(B))
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001377 SuperClasses.push_back(B.Name);
1378 }
1379
1380 if (SuperClasses.empty())
1381 continue;
1382
1383 OS << "\n case " << A.Name << ":\n";
1384
1385 if (SuperClasses.size() == 1) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001386 OS << " return B == " << SuperClasses.back() << ";\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001387 continue;
1388 }
1389
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001390 OS << " switch (B) {\n";
1391 OS << " default: return false;\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001392 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001393 OS << " case " << SuperClasses[i] << ": return true;\n";
1394 OS << " }\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001395 }
1396 }
1397 OS << " }\n";
1398 OS << "}\n\n";
1399}
1400
Chris Lattner70add882009-08-08 20:02:57 +00001401
1402
Daniel Dunbar245f0582009-08-08 21:22:41 +00001403/// EmitMatchTokenString - Emit the function to match a token string to the
1404/// appropriate match class value.
1405static void EmitMatchTokenString(CodeGenTarget &Target,
1406 std::vector<ClassInfo*> &Infos,
1407 raw_ostream &OS) {
1408 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00001409 std::vector<StringMatcher::StringPair> Matches;
Daniel Dunbar245f0582009-08-08 21:22:41 +00001410 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1411 ie = Infos.end(); it != ie; ++it) {
1412 ClassInfo &CI = **it;
1413
1414 if (CI.Kind == ClassInfo::Token)
Chris Lattner5845e5c2010-09-06 02:01:51 +00001415 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1416 "return " + CI.Name + ";"));
Daniel Dunbar245f0582009-08-08 21:22:41 +00001417 }
1418
Chris Lattnerb8d6e982010-02-09 00:34:28 +00001419 OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001420
Chris Lattner5845e5c2010-09-06 02:01:51 +00001421 StringMatcher("Name", Matches, OS).Emit();
Daniel Dunbar245f0582009-08-08 21:22:41 +00001422
1423 OS << " return InvalidMatchClass;\n";
1424 OS << "}\n\n";
1425}
Chris Lattner70add882009-08-08 20:02:57 +00001426
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001427/// EmitMatchRegisterName - Emit the function to match a string to the target
1428/// specific register enum.
1429static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1430 raw_ostream &OS) {
Daniel Dunbar245f0582009-08-08 21:22:41 +00001431 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00001432 std::vector<StringMatcher::StringPair> Matches;
Daniel Dunbar245f0582009-08-08 21:22:41 +00001433 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1434 const CodeGenRegister &Reg = Target.getRegisters()[i];
Daniel Dunbar22be5222009-07-17 18:51:11 +00001435 if (Reg.TheDef->getValueAsString("AsmName").empty())
1436 continue;
1437
Chris Lattner5845e5c2010-09-06 02:01:51 +00001438 Matches.push_back(StringMatcher::StringPair(
1439 Reg.TheDef->getValueAsString("AsmName"),
1440 "return " + utostr(i + 1) + ";"));
Daniel Dunbar22be5222009-07-17 18:51:11 +00001441 }
Chris Lattner70add882009-08-08 20:02:57 +00001442
Chris Lattnerb8d6e982010-02-09 00:34:28 +00001443 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001444
Chris Lattner5845e5c2010-09-06 02:01:51 +00001445 StringMatcher("Name", Matches, OS).Emit();
Chris Lattner70add882009-08-08 20:02:57 +00001446
Daniel Dunbar245f0582009-08-08 21:22:41 +00001447 OS << " return 0;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001448 OS << "}\n\n";
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001449}
Daniel Dunbara027d222009-07-31 02:32:59 +00001450
Daniel Dunbar54074b52010-07-19 05:44:09 +00001451/// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1452/// definitions.
1453static void EmitSubtargetFeatureFlagEnumeration(CodeGenTarget &Target,
1454 AsmMatcherInfo &Info,
1455 raw_ostream &OS) {
1456 OS << "// Flags for subtarget features that participate in "
1457 << "instruction matching.\n";
1458 OS << "enum SubtargetFeatureFlag {\n";
1459 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1460 it = Info.SubtargetFeatures.begin(),
1461 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1462 SubtargetFeatureInfo &SFI = *it->second;
1463 OS << " " << SFI.EnumName << " = (1 << " << SFI.Index << "),\n";
1464 }
1465 OS << " Feature_None = 0\n";
1466 OS << "};\n\n";
1467}
1468
1469/// EmitComputeAvailableFeatures - Emit the function to compute the list of
1470/// available features given a subtarget.
1471static void EmitComputeAvailableFeatures(CodeGenTarget &Target,
1472 AsmMatcherInfo &Info,
1473 raw_ostream &OS) {
1474 std::string ClassName =
1475 Info.AsmParser->getValueAsString("AsmParserClassName");
1476
1477 OS << "unsigned " << Target.getName() << ClassName << "::\n"
1478 << "ComputeAvailableFeatures(const " << Target.getName()
1479 << "Subtarget *Subtarget) const {\n";
1480 OS << " unsigned Features = 0;\n";
1481 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1482 it = Info.SubtargetFeatures.begin(),
1483 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1484 SubtargetFeatureInfo &SFI = *it->second;
1485 OS << " if (" << SFI.TheDef->getValueAsString("CondString")
1486 << ")\n";
1487 OS << " Features |= " << SFI.EnumName << ";\n";
1488 }
1489 OS << " return Features;\n";
1490 OS << "}\n\n";
1491}
1492
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001493void AsmMatcherEmitter::run(raw_ostream &OS) {
1494 CodeGenTarget Target;
1495 Record *AsmParser = Target.getAsmParser();
1496 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1497
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001498 // Compute the information on the instructions to match.
Daniel Dunbar59fc42d2009-08-11 20:59:47 +00001499 AsmMatcherInfo Info(AsmParser);
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001500 Info.BuildInfo(Target);
Daniel Dunbara027d222009-07-31 02:32:59 +00001501
Daniel Dunbare1f6de32010-02-02 23:46:36 +00001502 // Sort the instruction table using the partial order on classes. We use
1503 // stable_sort to ensure that ambiguous instructions are still
1504 // deterministically ordered.
1505 std::stable_sort(Info.Instructions.begin(), Info.Instructions.end(),
1506 less_ptr<InstructionInfo>());
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001507
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001508 DEBUG_WITH_TYPE("instruction_info", {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001509 for (std::vector<InstructionInfo*>::iterator
1510 it = Info.Instructions.begin(), ie = Info.Instructions.end();
1511 it != ie; ++it)
Daniel Dunbar20927f22009-08-07 08:26:05 +00001512 (*it)->dump();
1513 });
Daniel Dunbara027d222009-07-31 02:32:59 +00001514
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001515 // Check for ambiguous instructions.
1516 unsigned NumAmbiguous = 0;
Daniel Dunbar2b544812009-08-09 06:05:33 +00001517 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1518 for (unsigned j = i + 1; j != e; ++j) {
1519 InstructionInfo &A = *Info.Instructions[i];
1520 InstructionInfo &B = *Info.Instructions[j];
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001521
Daniel Dunbar2b544812009-08-09 06:05:33 +00001522 if (A.CouldMatchAmiguouslyWith(B)) {
1523 DEBUG_WITH_TYPE("ambiguous_instrs", {
1524 errs() << "warning: ambiguous instruction match:\n";
1525 A.dump();
1526 errs() << "\nis incomparable with:\n";
1527 B.dump();
1528 errs() << "\n\n";
1529 });
1530 ++NumAmbiguous;
1531 }
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001532 }
1533 }
1534 if (NumAmbiguous)
1535 DEBUG_WITH_TYPE("ambiguous_instrs", {
1536 errs() << "warning: " << NumAmbiguous
1537 << " ambiguous instructions!\n";
1538 });
1539
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001540 // Write the output.
1541
1542 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1543
Chris Lattner0692ee62010-09-06 19:11:01 +00001544 // Information for the class declaration.
1545 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
1546 OS << "#undef GET_ASSEMBLER_HEADER\n";
1547 OS << " unsigned ComputeAvailableFeatures(const " <<
1548 Target.getName() << "Subtarget *Subtarget) const;\n";
1549 OS << "bool MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
1550 << " &Operands, MCInst &Inst);\n\n";
1551 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
1552
1553
1554
1555
1556 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
1557 OS << "#undef GET_REGISTER_MATCHER\n\n";
1558
Daniel Dunbar54074b52010-07-19 05:44:09 +00001559 // Emit the subtarget feature enumeration.
1560 EmitSubtargetFeatureFlagEnumeration(Target, Info, OS);
1561
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001562 // Emit the function to match a register name to number.
1563 EmitMatchRegisterName(Target, AsmParser, OS);
Chris Lattner0692ee62010-09-06 19:11:01 +00001564
1565 OS << "#endif // GET_REGISTER_MATCHER\n\n";
Sean Callanane9b466d2010-01-23 00:40:33 +00001566
Chris Lattner0692ee62010-09-06 19:11:01 +00001567
1568 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
1569 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001570
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001571 // Generate the unified function to convert operands into an MCInst.
1572 EmitConvertToMCInst(Target, Info.Instructions, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00001573
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001574 // Emit the enumeration for classes which participate in matching.
1575 EmitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00001576
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001577 // Emit the routine to match token strings to their match class.
1578 EmitMatchTokenString(Target, Info.Classes, OS);
1579
1580 // Emit the routine to classify an operand.
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001581 EmitClassifyOperand(Target, Info, OS);
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001582
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001583 // Emit the subclass predicate routine.
1584 EmitIsSubclass(Target, Info.Classes, OS);
1585
Daniel Dunbar54074b52010-07-19 05:44:09 +00001586 // Emit the available features compute function.
1587 EmitComputeAvailableFeatures(Target, Info, OS);
1588
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001589 // Finally, build the match function.
1590
1591 size_t MaxNumOperands = 0;
1592 for (std::vector<InstructionInfo*>::const_iterator it =
1593 Info.Instructions.begin(), ie = Info.Instructions.end();
1594 it != ie; ++it)
1595 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
Daniel Dunbar4f83e732010-05-04 00:33:13 +00001596
Daniel Dunbar4f83e732010-05-04 00:33:13 +00001597 OS << "bool " << Target.getName() << ClassName << "::\n"
Daniel Dunbar4f98f832010-08-12 00:55:32 +00001598 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
1599 << " &Operands,\n";
1600 OS << " MCInst &Inst) {\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001601
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001602 // Emit the static match table; unused classes get initalized to 0 which is
1603 // guaranteed to be InvalidMatchClass.
1604 //
1605 // FIXME: We can reduce the size of this table very easily. First, we change
1606 // it so that store the kinds in separate bit-fields for each index, which
1607 // only needs to be the max width used for classes at that index (we also need
1608 // to reject based on this during classification). If we then make sure to
1609 // order the match kinds appropriately (putting mnemonics last), then we
1610 // should only end up using a few bits for each class, especially the ones
1611 // following the mnemonic.
Chris Lattnerc6049532009-08-08 19:15:25 +00001612 OS << " static const struct MatchEntry {\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001613 OS << " unsigned Opcode;\n";
1614 OS << " ConversionKind ConvertFn;\n";
1615 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001616 OS << " unsigned RequiredFeatures;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001617 OS << " } MatchTable[" << Info.Instructions.size() << "] = {\n";
1618
1619 for (std::vector<InstructionInfo*>::const_iterator it =
1620 Info.Instructions.begin(), ie = Info.Instructions.end();
1621 it != ie; ++it) {
Daniel Dunbar20927f22009-08-07 08:26:05 +00001622 InstructionInfo &II = **it;
1623
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001624 OS << " { " << Target.getName() << "::" << II.InstrName
1625 << ", " << II.ConversionFnKind << ", { ";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001626 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1627 InstructionInfo::Operand &Op = II.Operands[i];
1628
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001629 if (i) OS << ", ";
1630 OS << Op.Class->Name;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001631 }
Daniel Dunbar54074b52010-07-19 05:44:09 +00001632 OS << " }, ";
1633
1634 // Write the required features mask.
1635 if (!II.RequiredFeatures.empty()) {
1636 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
1637 if (i) OS << "|";
1638 OS << II.RequiredFeatures[i]->EnumName;
1639 }
1640 } else
1641 OS << "0";
1642
1643 OS << "},\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00001644 }
1645
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001646 OS << " };\n\n";
1647
Daniel Dunbar54074b52010-07-19 05:44:09 +00001648
1649 // Emit code to get the available features.
1650 OS << " // Get the current feature set.\n";
1651 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
1652
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001653 // Emit code to compute the class list for this operand vector.
1654 OS << " // Eliminate obvious mismatches.\n";
1655 OS << " if (Operands.size() > " << MaxNumOperands << ")\n";
1656 OS << " return true;\n\n";
1657
1658 OS << " // Compute the class list for this operand vector.\n";
1659 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
1660 OS << " for (unsigned i = 0, e = Operands.size(); i != e; ++i) {\n";
1661 OS << " Classes[i] = ClassifyOperand(Operands[i]);\n\n";
1662
1663 OS << " // Check for invalid operands before matching.\n";
1664 OS << " if (Classes[i] == InvalidMatchClass)\n";
1665 OS << " return true;\n";
1666 OS << " }\n\n";
1667
1668 OS << " // Mark unused classes.\n";
1669 OS << " for (unsigned i = Operands.size(), e = " << MaxNumOperands << "; "
1670 << "i != e; ++i)\n";
1671 OS << " Classes[i] = InvalidMatchClass;\n\n";
1672
1673 // Emit code to search the table.
1674 OS << " // Search the table.\n";
Chris Lattnerd39bd3a2009-08-08 19:16:05 +00001675 OS << " for (const MatchEntry *it = MatchTable, "
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001676 << "*ie = MatchTable + " << Info.Instructions.size()
1677 << "; it != ie; ++it) {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001678
1679 // Emit check that the required features are available.
Chris Lattner0692ee62010-09-06 19:11:01 +00001680 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
1681 << "!= it->RequiredFeatures)\n";
1682 OS << " continue;\n";
1683
Daniel Dunbar54074b52010-07-19 05:44:09 +00001684 // Emit check that the subclasses match.
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001685 for (unsigned i = 0; i != MaxNumOperands; ++i) {
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001686 OS << " if (!IsSubclass(Classes["
1687 << i << "], it->Classes[" << i << "]))\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001688 OS << " continue;\n";
1689 }
Chris Lattner0692ee62010-09-06 19:11:01 +00001690
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001691 OS << "\n";
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001692 OS << " ConvertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
1693
1694 // Call the post-processing function, if used.
1695 std::string InsnCleanupFn =
1696 AsmParser->getValueAsString("AsmParserInstCleanup");
1697 if (!InsnCleanupFn.empty())
1698 OS << " " << InsnCleanupFn << "(Inst);\n";
1699
1700 OS << " return false;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001701 OS << " }\n\n";
1702
Daniel Dunbara027d222009-07-31 02:32:59 +00001703 OS << " return true;\n";
1704 OS << "}\n\n";
Sean Callanane9b466d2010-01-23 00:40:33 +00001705
Chris Lattner0692ee62010-09-06 19:11:01 +00001706 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbard51ffcf2009-07-11 19:39:44 +00001707}