blob: 2fa44b1b136b1af61a1b2bbd5a0de6b555363680 [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 ...)
Jim Grosbacha7c78222010-10-29 22:13:48 +000023// 'call' '*' %epc
Daniel Dunbar20927f22009-08-07 08:26:05 +000024//
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 = "";
Jim Grosbacha7c78222010-10-29 22:13:48 +0000101
Daniel Dunbara027d222009-07-31 02:32:59 +0000102 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)
Jim Grosbacha7c78222010-10-29 22:13:48 +0000106 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
Jim Grosbacha7c78222010-10-29 22:13:48 +0000135 assert(VariantsEnd != Cur.size() &&
Daniel Dunbar53a7f162009-08-04 20:36:45 +0000136 "Unterminated variants in assembly string!");
137 Cur = Cur.substr(VariantsEnd + 1);
Jim Grosbacha7c78222010-10-29 22:13:48 +0000138 }
Daniel Dunbara027d222009-07-31 02:32:59 +0000139
140 return Res;
141}
142
143/// TokenizeAsmString - Tokenize a simplified assembly string.
Jim Grosbacha7c78222010-10-29 22:13:48 +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;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000165
Daniel Dunbar20927f22009-08-07 08:26:05 +0000166 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,
Jim Grosbacha7c78222010-10-29 22:13:48 +0000220 const CodeGenInstruction &CGI,
Daniel Dunbar20927f22009-08-07 08:26:05 +0000221 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.
Jim Grosbacha7c78222010-10-29 22:13:48 +0000247 if (std::find(CGI.AsmString.begin(),
Daniel Dunbar20927f22009-08-07 08:26:05 +0000248 CGI.AsmString.end(), '\n') != CGI.AsmString.end())
249 return false;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000250
Daniel Dunbar20927f22009-08-07 08:26:05 +0000251 // 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) {
Jim Grosbacha7c78222010-10-29 22:13:48 +0000260 if (Tokens[i][0] == '$' &&
261 std::find(Tokens[i].begin(),
Daniel Dunbar20927f22009-08-07 08:26:05 +0000262 Tokens[i].end(), ':') != Tokens[i].end()) {
263 DEBUG({
264 errs() << "warning: '" << Name << "': "
Jim Grosbacha7c78222010-10-29 22:13:48 +0000265 << "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());
Jim Grosbacha7c78222010-10-29 22:13:48 +0000364 std::set_intersection(Registers.begin(), Registers.end(),
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000365 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();
Jim Grosbacha7c78222010-10-29 22:13:48 +0000384
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000385 return Root == RHSRoot;
386 }
387
Jim Grosbacha7c78222010-10-29 22:13:48 +0000388 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000389 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 {
Chris Lattnere206fcf2010-09-06 21:01:37 +0000471 // The primary comparator is the instruction mnemonic.
472 if (Tokens[0] != RHS.Tokens[0])
473 return Tokens[0] < RHS.Tokens[0];
Jim Grosbacha7c78222010-10-29 22:13:48 +0000474
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000475 if (Operands.size() != RHS.Operands.size())
476 return Operands.size() < RHS.Operands.size();
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000477
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000478 // Compare lexicographically by operand. The matcher validates that other
479 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
480 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000481 if (*Operands[i].Class < *RHS.Operands[i].Class)
482 return true;
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000483 if (*RHS.Operands[i].Class < *Operands[i].Class)
484 return false;
485 }
486
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000487 return false;
488 }
489
Daniel Dunbar2b544812009-08-09 06:05:33 +0000490 /// CouldMatchAmiguouslyWith - Check whether this instruction could
491 /// ambiguously match the same set of operands as \arg RHS (without being a
492 /// strictly superior match).
493 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
494 // The number of operands is unambiguous.
495 if (Operands.size() != RHS.Operands.size())
496 return false;
497
Daniel Dunbar1402f0b2010-01-23 00:26:16 +0000498 // Otherwise, make sure the ordering of the two instructions is unambiguous
499 // by checking that either (a) a token or operand kind discriminates them,
500 // or (b) the ordering among equivalent kinds is consistent.
501
Daniel Dunbar2b544812009-08-09 06:05:33 +0000502 // Tokens and operand kinds are unambiguous (assuming a correct target
503 // specific parser).
504 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
505 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
506 Operands[i].Class->Kind == ClassInfo::Token)
507 if (*Operands[i].Class < *RHS.Operands[i].Class ||
508 *RHS.Operands[i].Class < *Operands[i].Class)
509 return false;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000510
Daniel Dunbar2b544812009-08-09 06:05:33 +0000511 // Otherwise, this operand could commute if all operands are equivalent, or
512 // there is a pair of operands that compare less than and a pair that
513 // compare greater than.
514 bool HasLT = false, HasGT = false;
515 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
516 if (*Operands[i].Class < *RHS.Operands[i].Class)
517 HasLT = true;
518 if (*RHS.Operands[i].Class < *Operands[i].Class)
519 HasGT = true;
520 }
521
522 return !(HasLT ^ HasGT);
523 }
524
Daniel Dunbar20927f22009-08-07 08:26:05 +0000525public:
526 void dump();
527};
528
Daniel Dunbar54074b52010-07-19 05:44:09 +0000529/// SubtargetFeatureInfo - Helper class for storing information on a subtarget
530/// feature which participates in instruction matching.
531struct SubtargetFeatureInfo {
532 /// \brief The predicate record for this feature.
533 Record *TheDef;
534
535 /// \brief An unique index assigned to represent this feature.
536 unsigned Index;
537
538 /// \brief The name of the enumerated constant identifying this feature.
539 std::string EnumName;
540};
541
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000542class AsmMatcherInfo {
543public:
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000544 /// The tablegen AsmParser record.
545 Record *AsmParser;
546
547 /// The AsmParser "CommentDelimiter" value.
548 std::string CommentDelimiter;
549
550 /// The AsmParser "RegisterPrefix" value.
551 std::string RegisterPrefix;
552
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000553 /// The classes which are needed for matching.
554 std::vector<ClassInfo*> Classes;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000555
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000556 /// The information on the instruction to match.
557 std::vector<InstructionInfo*> Instructions;
558
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000559 /// Map of Register records to their class information.
560 std::map<Record*, ClassInfo*> RegisterClasses;
561
Daniel Dunbar54074b52010-07-19 05:44:09 +0000562 /// Map of Predicate records to their subtarget information.
563 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
564
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000565private:
566 /// Map of token to class information which has already been constructed.
567 std::map<std::string, ClassInfo*> TokenClasses;
568
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000569 /// Map of RegisterClass records to their class information.
570 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000571
Daniel Dunbar338825c2009-08-10 18:41:10 +0000572 /// Map of AsmOperandClass records to their class information.
573 std::map<Record*, ClassInfo*> AsmOperandClasses;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000574
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000575private:
576 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000577 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000578
579 /// getOperandClass - Lookup or create the class for the given operand.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000580 ClassInfo *getOperandClass(StringRef Token,
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000581 const CodeGenInstruction::OperandInfo &OI);
582
Daniel Dunbar54074b52010-07-19 05:44:09 +0000583 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
584 /// given operand.
585 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) {
586 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
587
588 SubtargetFeatureInfo *&Entry = SubtargetFeatures[Def];
589 if (!Entry) {
590 Entry = new SubtargetFeatureInfo;
591 Entry->TheDef = Def;
592 Entry->Index = SubtargetFeatures.size() - 1;
593 Entry->EnumName = "Feature_" + Def->getName();
594 assert(Entry->Index < 32 && "Too many subtarget features!");
595 }
596
597 return Entry;
598 }
599
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000600 /// BuildRegisterClasses - Build the ClassInfo* instances for register
601 /// classes.
Jim Grosbacha7c78222010-10-29 22:13:48 +0000602 void BuildRegisterClasses(CodeGenTarget &Target,
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000603 std::set<std::string> &SingletonRegisterNames);
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000604
605 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
606 /// operand classes.
607 void BuildOperandClasses(CodeGenTarget &Target);
608
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000609public:
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000610 AsmMatcherInfo(Record *_AsmParser);
611
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000612 /// BuildInfo - Construct the various tables used during matching.
613 void BuildInfo(CodeGenTarget &Target);
614};
615
Daniel Dunbar20927f22009-08-07 08:26:05 +0000616}
617
618void InstructionInfo::dump() {
619 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
620 << ", tokens:[";
621 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
622 errs() << Tokens[i];
623 if (i + 1 != e)
624 errs() << ", ";
625 }
626 errs() << "]\n";
627
628 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
629 Operand &Op = Operands[i];
Daniel Dunbar6745d422009-08-09 05:18:30 +0000630 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000631 if (Op.Class->Kind == ClassInfo::Token) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000632 errs() << '\"' << Tokens[i] << "\"\n";
633 continue;
634 }
635
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000636 if (!Op.OperandInfo) {
637 errs() << "(singleton register)\n";
638 continue;
639 }
640
Benjamin Kramerfa1165a2009-08-08 10:06:30 +0000641 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000642 errs() << OI.Name << " " << OI.Rec->getName()
643 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
644 }
645}
646
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000647static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000648 std::string Res;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000649
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000650 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
651 switch (*it) {
652 case '*': Res += "_STAR_"; break;
653 case '%': Res += "_PCT_"; break;
654 case ':': Res += "_COLON_"; break;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000655
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000656 default:
657 if (isalnum(*it)) {
658 Res += *it;
659 } else {
660 Res += "_" + utostr((unsigned) *it) + "_";
661 }
662 }
663 }
664
665 return Res;
666}
667
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000668/// getRegisterRecord - Get the register record for \arg name, or 0.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000669static Record *getRegisterRecord(CodeGenTarget &Target, StringRef Name) {
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000670 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
671 const CodeGenRegister &Reg = Target.getRegisters()[i];
672 if (Name == Reg.TheDef->getValueAsString("AsmName"))
673 return Reg.TheDef;
674 }
675
676 return 0;
677}
678
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000679ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000680 ClassInfo *&Entry = TokenClasses[Token];
Jim Grosbacha7c78222010-10-29 22:13:48 +0000681
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000682 if (!Entry) {
683 Entry = new ClassInfo();
684 Entry->Kind = ClassInfo::Token;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000685 Entry->ClassName = "Token";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000686 Entry->Name = "MCK_" + getEnumNameForToken(Token);
687 Entry->ValueName = Token;
688 Entry->PredicateMethod = "<invalid>";
689 Entry->RenderMethod = "<invalid>";
690 Classes.push_back(Entry);
691 }
692
693 return Entry;
694}
695
696ClassInfo *
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000697AsmMatcherInfo::getOperandClass(StringRef Token,
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000698 const CodeGenInstruction::OperandInfo &OI) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000699 if (OI.Rec->isSubClassOf("RegisterClass")) {
700 ClassInfo *CI = RegisterClassClasses[OI.Rec];
701
702 if (!CI) {
703 PrintError(OI.Rec->getLoc(), "register class has no class info!");
704 throw std::string("ERROR: Missing register class!");
705 }
706
707 return CI;
708 }
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000709
Daniel Dunbar338825c2009-08-10 18:41:10 +0000710 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
711 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
712 ClassInfo *CI = AsmOperandClasses[MatchClass];
713
714 if (!CI) {
715 PrintError(OI.Rec->getLoc(), "operand has no match class!");
716 throw std::string("ERROR: Missing match class!");
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000717 }
718
Daniel Dunbar338825c2009-08-10 18:41:10 +0000719 return CI;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000720}
721
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000722void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target,
723 std::set<std::string>
724 &SingletonRegisterNames) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000725 std::vector<CodeGenRegisterClass> RegisterClasses;
726 std::vector<CodeGenRegister> Registers;
Daniel Dunbar338825c2009-08-10 18:41:10 +0000727
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000728 RegisterClasses = Target.getRegisterClasses();
729 Registers = Target.getRegisters();
Daniel Dunbar338825c2009-08-10 18:41:10 +0000730
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000731 // The register sets used for matching.
732 std::set< std::set<Record*> > RegisterSets;
733
Jim Grosbacha7c78222010-10-29 22:13:48 +0000734 // Gather the defined sets.
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000735 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
736 ie = RegisterClasses.end(); it != ie; ++it)
737 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
738 it->Elements.end()));
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000739
740 // Add any required singleton sets.
741 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
742 ie = SingletonRegisterNames.end(); it != ie; ++it)
743 if (Record *Rec = getRegisterRecord(Target, *it))
744 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
Jim Grosbacha7c78222010-10-29 22:13:48 +0000745
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000746 // Introduce derived sets where necessary (when a register does not determine
747 // a unique register set class), and build the mapping of registers to the set
748 // they should classify to.
749 std::map<Record*, std::set<Record*> > RegisterMap;
750 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
751 ie = Registers.end(); it != ie; ++it) {
752 CodeGenRegister &CGR = *it;
753 // Compute the intersection of all sets containing this register.
754 std::set<Record*> ContainingSet;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000755
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000756 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
757 ie = RegisterSets.end(); it != ie; ++it) {
758 if (!it->count(CGR.TheDef))
759 continue;
760
761 if (ContainingSet.empty()) {
762 ContainingSet = *it;
763 } else {
764 std::set<Record*> Tmp;
765 std::swap(Tmp, ContainingSet);
766 std::insert_iterator< std::set<Record*> > II(ContainingSet,
767 ContainingSet.begin());
768 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
769 II);
770 }
771 }
772
773 if (!ContainingSet.empty()) {
774 RegisterSets.insert(ContainingSet);
775 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
776 }
777 }
778
779 // Construct the register classes.
780 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
781 unsigned Index = 0;
782 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
783 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
784 ClassInfo *CI = new ClassInfo();
785 CI->Kind = ClassInfo::RegisterClass0 + Index;
786 CI->ClassName = "Reg" + utostr(Index);
787 CI->Name = "MCK_Reg" + utostr(Index);
788 CI->ValueName = "";
789 CI->PredicateMethod = ""; // unused
790 CI->RenderMethod = "addRegOperands";
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000791 CI->Registers = *it;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000792 Classes.push_back(CI);
793 RegisterSetClasses.insert(std::make_pair(*it, CI));
794 }
795
796 // Find the superclasses; we could compute only the subgroup lattice edges,
797 // but there isn't really a point.
798 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
799 ie = RegisterSets.end(); it != ie; ++it) {
800 ClassInfo *CI = RegisterSetClasses[*it];
801 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
802 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
Jim Grosbacha7c78222010-10-29 22:13:48 +0000803 if (*it != *it2 &&
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000804 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
805 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
806 }
807
808 // Name the register classes which correspond to a user defined RegisterClass.
809 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
810 ie = RegisterClasses.end(); it != ie; ++it) {
811 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
812 it->Elements.end())];
813 if (CI->ValueName.empty()) {
814 CI->ClassName = it->getName();
815 CI->Name = "MCK_" + it->getName();
816 CI->ValueName = it->getName();
817 } else
818 CI->ValueName = CI->ValueName + "," + it->getName();
819
820 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
821 }
822
823 // Populate the map for individual registers.
824 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
825 ie = RegisterMap.end(); it != ie; ++it)
826 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000827
828 // Name the register classes which correspond to singleton registers.
829 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
830 ie = SingletonRegisterNames.end(); it != ie; ++it) {
831 if (Record *Rec = getRegisterRecord(Target, *it)) {
832 ClassInfo *CI = this->RegisterClasses[Rec];
833 assert(CI && "Missing singleton register class info!");
834
835 if (CI->ValueName.empty()) {
836 CI->ClassName = Rec->getName();
837 CI->Name = "MCK_" + Rec->getName();
838 CI->ValueName = Rec->getName();
839 } else
840 CI->ValueName = CI->ValueName + "," + Rec->getName();
841 }
842 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000843}
844
845void AsmMatcherInfo::BuildOperandClasses(CodeGenTarget &Target) {
Daniel Dunbar338825c2009-08-10 18:41:10 +0000846 std::vector<Record*> AsmOperands;
847 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbara2f5e002010-01-30 01:02:37 +0000848
849 // Pre-populate AsmOperandClasses map.
Jim Grosbacha7c78222010-10-29 22:13:48 +0000850 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbara2f5e002010-01-30 01:02:37 +0000851 ie = AsmOperands.end(); it != ie; ++it)
852 AsmOperandClasses[*it] = new ClassInfo();
853
Daniel Dunbar338825c2009-08-10 18:41:10 +0000854 unsigned Index = 0;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000855 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbar338825c2009-08-10 18:41:10 +0000856 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
Daniel Dunbara2f5e002010-01-30 01:02:37 +0000857 ClassInfo *CI = AsmOperandClasses[*it];
Daniel Dunbar338825c2009-08-10 18:41:10 +0000858 CI->Kind = ClassInfo::UserClass0 + Index;
859
Daniel Dunbar54ddf3d2010-05-22 21:02:29 +0000860 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
861 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
862 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
863 if (!DI) {
864 PrintError((*it)->getLoc(), "Invalid super class reference!");
865 continue;
866 }
867
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000868 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
869 if (!SC)
Daniel Dunbar338825c2009-08-10 18:41:10 +0000870 PrintError((*it)->getLoc(), "Invalid super class reference!");
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000871 else
872 CI->SuperClasses.push_back(SC);
Daniel Dunbar338825c2009-08-10 18:41:10 +0000873 }
874 CI->ClassName = (*it)->getValueAsString("Name");
875 CI->Name = "MCK_" + CI->ClassName;
876 CI->ValueName = (*it)->getName();
Daniel Dunbar5c468e32009-08-10 21:00:45 +0000877
878 // Get or construct the predicate method name.
879 Init *PMName = (*it)->getValueInit("PredicateMethod");
880 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
881 CI->PredicateMethod = SI->getValue();
882 } else {
Jim Grosbacha7c78222010-10-29 22:13:48 +0000883 assert(dynamic_cast<UnsetInit*>(PMName) &&
Daniel Dunbar5c468e32009-08-10 21:00:45 +0000884 "Unexpected PredicateMethod field!");
885 CI->PredicateMethod = "is" + CI->ClassName;
886 }
887
888 // Get or construct the render method name.
889 Init *RMName = (*it)->getValueInit("RenderMethod");
890 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
891 CI->RenderMethod = SI->getValue();
892 } else {
893 assert(dynamic_cast<UnsetInit*>(RMName) &&
894 "Unexpected RenderMethod field!");
895 CI->RenderMethod = "add" + CI->ClassName + "Operands";
896 }
897
Daniel Dunbar338825c2009-08-10 18:41:10 +0000898 AsmOperandClasses[*it] = CI;
899 Classes.push_back(CI);
900 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000901}
902
Jim Grosbacha7c78222010-10-29 22:13:48 +0000903AsmMatcherInfo::AsmMatcherInfo(Record *_AsmParser)
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000904 : AsmParser(_AsmParser),
905 CommentDelimiter(AsmParser->getValueAsString("CommentDelimiter")),
906 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix"))
907{
908}
909
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000910void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000911 // Parse the instructions; we need to do this first so that we can gather the
912 // singleton register classes.
913 std::set<std::string> SingletonRegisterNames;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000914
Chris Lattnerf6502782010-03-19 00:34:35 +0000915 const std::vector<const CodeGenInstruction*> &InstrList =
916 Target.getInstructionsByEnumValue();
Jim Grosbacha7c78222010-10-29 22:13:48 +0000917
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000918 for (unsigned i = 0, e = InstrList.size(); i != e; ++i) {
919 const CodeGenInstruction &CGI = *InstrList[i];
Daniel Dunbar20927f22009-08-07 08:26:05 +0000920
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000921 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
Daniel Dunbar20927f22009-08-07 08:26:05 +0000922 continue;
923
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000924 OwningPtr<InstructionInfo> II(new InstructionInfo());
Jim Grosbacha7c78222010-10-29 22:13:48 +0000925
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000926 II->InstrName = CGI.TheDef->getName();
927 II->Instr = &CGI;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000928 II->AsmString = FlattenVariants(CGI.AsmString, 0);
929
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000930 // Remove comments from the asm string.
931 if (!CommentDelimiter.empty()) {
932 size_t Idx = StringRef(II->AsmString).find(CommentDelimiter);
933 if (Idx != StringRef::npos)
934 II->AsmString = II->AsmString.substr(0, Idx);
935 }
936
Daniel Dunbar20927f22009-08-07 08:26:05 +0000937 TokenizeAsmString(II->AsmString, II->Tokens);
938
939 // Ignore instructions which shouldn't be matched.
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000940 if (!IsAssemblerInstruction(CGI.TheDef->getName(), CGI, II->Tokens))
Daniel Dunbar20927f22009-08-07 08:26:05 +0000941 continue;
942
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000943 // Collect singleton registers, if used.
Chris Lattner4e692ab2010-10-28 21:28:42 +0000944 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
945 if (!II->Tokens[i].startswith(RegisterPrefix))
946 continue;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000947
Chris Lattner4e692ab2010-10-28 21:28:42 +0000948 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
949 Record *Rec = getRegisterRecord(Target, RegName);
Jim Grosbacha7c78222010-10-29 22:13:48 +0000950
Chris Lattner4e692ab2010-10-28 21:28:42 +0000951 if (!Rec) {
952 // If there is no register prefix (i.e. "%" in "%eax"), then this may
953 // be some random non-register token, just ignore it.
954 if (RegisterPrefix.empty())
955 continue;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000956
957 std::string Err = "unable to find register for '" + RegName.str() +
Chris Lattner4e692ab2010-10-28 21:28:42 +0000958 "' (which matches register prefix)";
959 throw TGError(CGI.TheDef->getLoc(), Err);
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000960 }
Chris Lattner4e692ab2010-10-28 21:28:42 +0000961
962 SingletonRegisterNames.insert(RegName);
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000963 }
Daniel Dunbar54074b52010-07-19 05:44:09 +0000964
965 // Compute the require features.
966 ListInit *Predicates = CGI.TheDef->getValueAsListInit("Predicates");
967 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
968 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
969 // Ignore OptForSize and OptForSpeed, they aren't really requirements,
970 // rather they are hints to isel.
971 //
972 // FIXME: Find better way to model this.
973 if (Pred->getDef()->getName() == "OptForSize" ||
974 Pred->getDef()->getName() == "OptForSpeed")
975 continue;
976
977 // FIXME: Total hack; for now, we just limit ourselves to In32BitMode
978 // and In64BitMode, because we aren't going to have the right feature
979 // masks for SSE and friends. We need to decide what we are going to do
980 // about CPU subtypes to implement this the right way.
981 if (Pred->getDef()->getName() != "In32BitMode" &&
982 Pred->getDef()->getName() != "In64BitMode")
983 continue;
984
985 II->RequiredFeatures.push_back(getSubtargetFeature(Pred->getDef()));
986 }
987 }
988
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000989 Instructions.push_back(II.take());
990 }
991
992 // Build info for the register classes.
993 BuildRegisterClasses(Target, SingletonRegisterNames);
994
995 // Build info for the user defined assembly operand classes.
996 BuildOperandClasses(Target);
997
998 // Build the instruction information.
999 for (std::vector<InstructionInfo*>::iterator it = Instructions.begin(),
1000 ie = Instructions.end(); it != ie; ++it) {
1001 InstructionInfo *II = *it;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001002
Chris Lattnere206fcf2010-09-06 21:01:37 +00001003 // The first token of the instruction is the mnemonic, which must be a
1004 // simple string.
1005 assert(!II->Tokens.empty() && "Instruction has no tokens?");
1006 StringRef Mnemonic = II->Tokens[0];
1007 assert(Mnemonic[0] != '$' &&
1008 (RegisterPrefix.empty() || !Mnemonic.startswith(RegisterPrefix)));
Jim Grosbacha7c78222010-10-29 22:13:48 +00001009
Chris Lattnere206fcf2010-09-06 21:01:37 +00001010 // Parse the tokens after the mnemonic.
1011 for (unsigned i = 1, e = II->Tokens.size(); i != e; ++i) {
Daniel Dunbar20927f22009-08-07 08:26:05 +00001012 StringRef Token = II->Tokens[i];
1013
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001014 // Check for singleton registers.
Chris Lattner4e692ab2010-10-28 21:28:42 +00001015 if (Token.startswith(RegisterPrefix)) {
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001016 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
Chris Lattner4e692ab2010-10-28 21:28:42 +00001017 if (Record *RegRecord = getRegisterRecord(Target, RegName)) {
1018 InstructionInfo::Operand Op;
1019 Op.Class = RegisterClasses[RegRecord];
1020 Op.OperandInfo = 0;
1021 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1022 "Unexpected class for singleton register");
1023 II->Operands.push_back(Op);
1024 continue;
1025 }
1026
1027 if (!RegisterPrefix.empty()) {
Jim Grosbacha7c78222010-10-29 22:13:48 +00001028 std::string Err = "unable to find register for '" + RegName.str() +
Chris Lattner4e692ab2010-10-28 21:28:42 +00001029 "' (which matches register prefix)";
1030 throw TGError(II->Instr->TheDef->getLoc(), Err);
1031 }
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001032 }
1033
Daniel Dunbar20927f22009-08-07 08:26:05 +00001034 // Check for simple tokens.
1035 if (Token[0] != '$') {
1036 InstructionInfo::Operand Op;
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001037 Op.Class = getTokenClass(Token);
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001038 Op.OperandInfo = 0;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001039 II->Operands.push_back(Op);
1040 continue;
1041 }
1042
1043 // Otherwise this is an operand reference.
Daniel Dunbar20927f22009-08-07 08:26:05 +00001044 StringRef OperandName;
1045 if (Token[1] == '{')
1046 OperandName = Token.substr(2, Token.size() - 3);
1047 else
1048 OperandName = Token.substr(1);
1049
1050 // Map this token to an operand. FIXME: Move elsewhere.
1051 unsigned Idx;
1052 try {
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001053 Idx = II->Instr->getOperandNamed(OperandName);
Daniel Dunbar20927f22009-08-07 08:26:05 +00001054 } catch(...) {
Jim Grosbacha7c78222010-10-29 22:13:48 +00001055 throw std::string("error: unable to find operand: '" +
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001056 OperandName.str() + "'");
Daniel Dunbar20927f22009-08-07 08:26:05 +00001057 }
1058
Daniel Dunbaraf616812010-02-10 08:15:48 +00001059 // FIXME: This is annoying, the named operand may be tied (e.g.,
1060 // XCHG8rm). What we want is the untied operand, which we now have to
1061 // grovel for. Only worry about this for single entry operands, we have to
1062 // clean this up anyway.
1063 const CodeGenInstruction::OperandInfo *OI = &II->Instr->OperandList[Idx];
1064 if (OI->Constraints[0].isTied()) {
1065 unsigned TiedOp = OI->Constraints[0].getTiedOperand();
1066
1067 // The tied operand index is an MIOperand index, find the operand that
1068 // contains it.
1069 for (unsigned i = 0, e = II->Instr->OperandList.size(); i != e; ++i) {
1070 if (II->Instr->OperandList[i].MIOperandNo == TiedOp) {
1071 OI = &II->Instr->OperandList[i];
1072 break;
1073 }
1074 }
1075
1076 assert(OI && "Unable to find tied operand target!");
1077 }
1078
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001079 InstructionInfo::Operand Op;
Daniel Dunbaraf616812010-02-10 08:15:48 +00001080 Op.Class = getOperandClass(Token, *OI);
1081 Op.OperandInfo = OI;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001082 II->Operands.push_back(Op);
1083 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001084 }
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001085
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001086 // Reorder classes so that classes preceed super classes.
1087 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
Daniel Dunbar20927f22009-08-07 08:26:05 +00001088}
1089
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001090static std::pair<unsigned, unsigned> *
1091GetTiedOperandAtIndex(SmallVectorImpl<std::pair<unsigned, unsigned> > &List,
1092 unsigned Index) {
1093 for (unsigned i = 0, e = List.size(); i != e; ++i)
1094 if (Index == List[i].first)
1095 return &List[i];
1096
1097 return 0;
1098}
1099
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001100static void EmitConvertToMCInst(CodeGenTarget &Target,
1101 std::vector<InstructionInfo*> &Infos,
1102 raw_ostream &OS) {
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001103 // Write the convert function to a separate stream, so we can drop it after
1104 // the enum.
1105 std::string ConvertFnBody;
1106 raw_string_ostream CvtOS(ConvertFnBody);
1107
Daniel Dunbar20927f22009-08-07 08:26:05 +00001108 // Function we have already generated.
1109 std::set<std::string> GeneratedFns;
1110
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001111 // Start the unified conversion function.
1112
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001113 CvtOS << "static void ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001114 << "unsigned Opcode,\n"
Chris Lattner98986712010-01-14 22:21:20 +00001115 << " const SmallVectorImpl<MCParsedAsmOperand*"
1116 << "> &Operands) {\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001117 CvtOS << " Inst.setOpcode(Opcode);\n";
1118 CvtOS << " switch (Kind) {\n";
1119 CvtOS << " default:\n";
1120
1121 // Start the enum, which we will generate inline.
1122
1123 OS << "// Unified function for converting operants to MCInst instances.\n\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001124 OS << "enum ConversionKind {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001125
Chris Lattner98986712010-01-14 22:21:20 +00001126 // TargetOperandClass - This is the target's operand class, like X86Operand.
1127 std::string TargetOperandClass = Target.getName() + "Operand";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001128
Daniel Dunbar20927f22009-08-07 08:26:05 +00001129 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
1130 ie = Infos.end(); it != ie; ++it) {
1131 InstructionInfo &II = **it;
1132
1133 // Order the (class) operands by the order to convert them into an MCInst.
1134 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
1135 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1136 InstructionInfo::Operand &Op = II.Operands[i];
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001137 if (Op.OperandInfo)
1138 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
Daniel Dunbar20927f22009-08-07 08:26:05 +00001139 }
Daniel Dunbaraf616812010-02-10 08:15:48 +00001140
1141 // Find any tied operands.
1142 SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands;
1143 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1144 const CodeGenInstruction::OperandInfo &OpInfo = II.Instr->OperandList[i];
1145 for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) {
1146 const CodeGenInstruction::ConstraintInfo &CI = OpInfo.Constraints[j];
1147 if (CI.isTied())
1148 TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo + j,
1149 CI.getTiedOperand()));
1150 }
1151 }
1152
Daniel Dunbar20927f22009-08-07 08:26:05 +00001153 std::sort(MIOperandList.begin(), MIOperandList.end());
1154
1155 // Compute the total number of operands.
1156 unsigned NumMIOperands = 0;
1157 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1158 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
Jim Grosbacha7c78222010-10-29 22:13:48 +00001159 NumMIOperands = std::max(NumMIOperands,
Daniel Dunbar20927f22009-08-07 08:26:05 +00001160 OI.MIOperandNo + OI.MINumOperands);
1161 }
1162
1163 // Build the conversion function signature.
1164 std::string Signature = "Convert";
1165 unsigned CurIndex = 0;
1166 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1167 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001168 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
Daniel Dunbar20927f22009-08-07 08:26:05 +00001169 "Duplicate match for instruction operand!");
Jim Grosbacha7c78222010-10-29 22:13:48 +00001170
Daniel Dunbar20927f22009-08-07 08:26:05 +00001171 // Skip operands which weren't matched by anything, this occurs when the
1172 // .td file encodes "implicit" operands as explicit ones.
1173 //
1174 // FIXME: This should be removed from the MCInst structure.
Daniel Dunbaraf616812010-02-10 08:15:48 +00001175 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001176 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1177 CurIndex);
1178 if (!Tie)
Daniel Dunbaraf616812010-02-10 08:15:48 +00001179 Signature += "__Imp";
1180 else
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001181 Signature += "__Tie" + utostr(Tie->second);
Daniel Dunbaraf616812010-02-10 08:15:48 +00001182 }
1183
1184 Signature += "__";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001185
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001186 // Registers are always converted the same, don't duplicate the conversion
1187 // function based on them.
1188 //
1189 // FIXME: We could generalize this based on the render method, if it
1190 // mattered.
1191 if (Op.Class->isRegisterClass())
1192 Signature += "Reg";
1193 else
1194 Signature += Op.Class->ClassName;
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001195 Signature += utostr(Op.OperandInfo->MINumOperands);
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001196 Signature += "_" + utostr(MIOperandList[i].second);
1197
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001198 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001199 }
1200
1201 // Add any trailing implicit operands.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001202 for (; CurIndex != NumMIOperands; ++CurIndex) {
1203 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1204 CurIndex);
1205 if (!Tie)
1206 Signature += "__Imp";
1207 else
1208 Signature += "__Tie" + utostr(Tie->second);
1209 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001210
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001211 II.ConversionFnKind = Signature;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001212
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001213 // Check if we have already generated this signature.
Daniel Dunbar20927f22009-08-07 08:26:05 +00001214 if (!GeneratedFns.insert(Signature).second)
1215 continue;
1216
1217 // If not, emit it now.
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001218
1219 // Add to the enum list.
1220 OS << " " << Signature << ",\n";
1221
1222 // And to the convert function.
1223 CvtOS << " case " << Signature << ":\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001224 CurIndex = 0;
1225 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1226 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1227
1228 // Add the implicit operands.
Daniel Dunbaraf616812010-02-10 08:15:48 +00001229 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1230 // See if this is a tied operand.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001231 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1232 CurIndex);
Daniel Dunbaraf616812010-02-10 08:15:48 +00001233
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001234 if (!Tie) {
Daniel Dunbaraf616812010-02-10 08:15:48 +00001235 // 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.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001240 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
Daniel Dunbaraf616812010-02-10 08:15:48 +00001241 CvtOS << " Inst.addOperand(Inst.getOperand("
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001242 << Tie->second << "));\n";
Daniel Dunbaraf616812010-02-10 08:15:48 +00001243 }
1244 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001245
Chris Lattner98986712010-01-14 22:21:20 +00001246 CvtOS << " ((" << TargetOperandClass << "*)Operands["
Jim Grosbacha7c78222010-10-29 22:13:48 +00001247 << MIOperandList[i].second
1248 << "+1])->" << Op.Class->RenderMethod
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001249 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
1250 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001251 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001252
Daniel Dunbar20927f22009-08-07 08:26:05 +00001253 // And add trailing implicit operands.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001254 for (; CurIndex != NumMIOperands; ++CurIndex) {
1255 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1256 CurIndex);
1257
1258 if (!Tie) {
1259 // If not, this is some implicit operand. Just assume it is a register
1260 // for now.
1261 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1262 } else {
1263 // Copy the tied operand.
1264 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1265 CvtOS << " Inst.addOperand(Inst.getOperand("
1266 << Tie->second << "));\n";
1267 }
1268 }
1269
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001270 CvtOS << " return;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001271 }
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001272
1273 // Finish the convert function.
1274
1275 CvtOS << " }\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001276 CvtOS << "}\n\n";
1277
1278 // Finish the enum, and drop the convert function after it.
1279
1280 OS << " NumConversionVariants\n";
1281 OS << "};\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001282
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001283 OS << CvtOS.str();
Daniel Dunbara027d222009-07-31 02:32:59 +00001284}
1285
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001286/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1287static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1288 std::vector<ClassInfo*> &Infos,
1289 raw_ostream &OS) {
1290 OS << "namespace {\n\n";
1291
1292 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1293 << "/// instruction matching.\n";
1294 OS << "enum MatchClassKind {\n";
1295 OS << " InvalidMatchClass = 0,\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001296 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001297 ie = Infos.end(); it != ie; ++it) {
1298 ClassInfo &CI = **it;
1299 OS << " " << CI.Name << ", // ";
1300 if (CI.Kind == ClassInfo::Token) {
1301 OS << "'" << CI.ValueName << "'\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001302 } else if (CI.isRegisterClass()) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001303 if (!CI.ValueName.empty())
1304 OS << "register class '" << CI.ValueName << "'\n";
1305 else
1306 OS << "derived register class\n";
1307 } else {
1308 OS << "user defined class '" << CI.ValueName << "'\n";
1309 }
1310 }
1311 OS << " NumMatchClassKinds\n";
1312 OS << "};\n\n";
1313
1314 OS << "}\n\n";
1315}
1316
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001317/// EmitClassifyOperand - Emit the function to classify an operand.
1318static void EmitClassifyOperand(CodeGenTarget &Target,
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001319 AsmMatcherInfo &Info,
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001320 raw_ostream &OS) {
Chris Lattner98986712010-01-14 22:21:20 +00001321 OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
1322 << " " << Target.getName() << "Operand &Operand = *("
1323 << Target.getName() << "Operand*)GOp;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001324
1325 // Classify tokens.
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001326 OS << " if (Operand.isToken())\n";
1327 OS << " return MatchTokenString(Operand.getToken());\n\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001328
1329 // Classify registers.
1330 //
1331 // FIXME: Don't hardcode isReg, getReg.
1332 OS << " if (Operand.isReg()) {\n";
1333 OS << " switch (Operand.getReg()) {\n";
1334 OS << " default: return InvalidMatchClass;\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001335 for (std::map<Record*, ClassInfo*>::iterator
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001336 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1337 it != ie; ++it)
Jim Grosbacha7c78222010-10-29 22:13:48 +00001338 OS << " case " << Target.getName() << "::"
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001339 << it->first->getName() << ": return " << it->second->Name << ";\n";
1340 OS << " }\n";
1341 OS << " }\n\n";
1342
1343 // Classify user defined operands.
Jim Grosbacha7c78222010-10-29 22:13:48 +00001344 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001345 ie = Info.Classes.end(); it != ie; ++it) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001346 ClassInfo &CI = **it;
1347
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001348 if (!CI.isUserClass())
1349 continue;
1350
1351 OS << " // '" << CI.ClassName << "' class";
1352 if (!CI.SuperClasses.empty()) {
1353 OS << ", subclass of ";
1354 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1355 if (i) OS << ", ";
1356 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1357 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001358 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001359 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001360 OS << "\n";
1361
1362 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001363
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001364 // Validate subclass relationships.
1365 if (!CI.SuperClasses.empty()) {
1366 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1367 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1368 << "() && \"Invalid class relationship!\");\n";
1369 }
1370
1371 OS << " return " << CI.Name << ";\n";
1372 OS << " }\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001373 }
1374 OS << " return InvalidMatchClass;\n";
1375 OS << "}\n\n";
1376}
1377
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001378/// EmitIsSubclass - Emit the subclass predicate function.
1379static void EmitIsSubclass(CodeGenTarget &Target,
1380 std::vector<ClassInfo*> &Infos,
1381 raw_ostream &OS) {
1382 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1383 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1384 OS << " if (A == B)\n";
1385 OS << " return true;\n\n";
1386
1387 OS << " switch (A) {\n";
1388 OS << " default:\n";
1389 OS << " return false;\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001390 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001391 ie = Infos.end(); it != ie; ++it) {
1392 ClassInfo &A = **it;
1393
1394 if (A.Kind != ClassInfo::Token) {
1395 std::vector<StringRef> SuperClasses;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001396 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001397 ie = Infos.end(); it != ie; ++it) {
1398 ClassInfo &B = **it;
1399
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001400 if (&A != &B && A.isSubsetOf(B))
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001401 SuperClasses.push_back(B.Name);
1402 }
1403
1404 if (SuperClasses.empty())
1405 continue;
1406
1407 OS << "\n case " << A.Name << ":\n";
1408
1409 if (SuperClasses.size() == 1) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001410 OS << " return B == " << SuperClasses.back() << ";\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001411 continue;
1412 }
1413
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001414 OS << " switch (B) {\n";
1415 OS << " default: return false;\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001416 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001417 OS << " case " << SuperClasses[i] << ": return true;\n";
1418 OS << " }\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001419 }
1420 }
1421 OS << " }\n";
1422 OS << "}\n\n";
1423}
1424
Chris Lattner70add882009-08-08 20:02:57 +00001425
1426
Daniel Dunbar245f0582009-08-08 21:22:41 +00001427/// EmitMatchTokenString - Emit the function to match a token string to the
1428/// appropriate match class value.
1429static void EmitMatchTokenString(CodeGenTarget &Target,
1430 std::vector<ClassInfo*> &Infos,
1431 raw_ostream &OS) {
1432 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00001433 std::vector<StringMatcher::StringPair> Matches;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001434 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbar245f0582009-08-08 21:22:41 +00001435 ie = Infos.end(); it != ie; ++it) {
1436 ClassInfo &CI = **it;
1437
1438 if (CI.Kind == ClassInfo::Token)
Chris Lattner5845e5c2010-09-06 02:01:51 +00001439 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1440 "return " + CI.Name + ";"));
Daniel Dunbar245f0582009-08-08 21:22:41 +00001441 }
1442
Chris Lattnerb8d6e982010-02-09 00:34:28 +00001443 OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001444
Chris Lattner5845e5c2010-09-06 02:01:51 +00001445 StringMatcher("Name", Matches, OS).Emit();
Daniel Dunbar245f0582009-08-08 21:22:41 +00001446
1447 OS << " return InvalidMatchClass;\n";
1448 OS << "}\n\n";
1449}
Chris Lattner70add882009-08-08 20:02:57 +00001450
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001451/// EmitMatchRegisterName - Emit the function to match a string to the target
1452/// specific register enum.
1453static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1454 raw_ostream &OS) {
Daniel Dunbar245f0582009-08-08 21:22:41 +00001455 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00001456 std::vector<StringMatcher::StringPair> Matches;
Daniel Dunbar245f0582009-08-08 21:22:41 +00001457 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1458 const CodeGenRegister &Reg = Target.getRegisters()[i];
Daniel Dunbar22be5222009-07-17 18:51:11 +00001459 if (Reg.TheDef->getValueAsString("AsmName").empty())
1460 continue;
1461
Chris Lattner5845e5c2010-09-06 02:01:51 +00001462 Matches.push_back(StringMatcher::StringPair(
1463 Reg.TheDef->getValueAsString("AsmName"),
1464 "return " + utostr(i + 1) + ";"));
Daniel Dunbar22be5222009-07-17 18:51:11 +00001465 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001466
Chris Lattnerb8d6e982010-02-09 00:34:28 +00001467 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001468
Chris Lattner5845e5c2010-09-06 02:01:51 +00001469 StringMatcher("Name", Matches, OS).Emit();
Jim Grosbacha7c78222010-10-29 22:13:48 +00001470
Daniel Dunbar245f0582009-08-08 21:22:41 +00001471 OS << " return 0;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001472 OS << "}\n\n";
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001473}
Daniel Dunbara027d222009-07-31 02:32:59 +00001474
Daniel Dunbar54074b52010-07-19 05:44:09 +00001475/// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1476/// definitions.
1477static void EmitSubtargetFeatureFlagEnumeration(CodeGenTarget &Target,
1478 AsmMatcherInfo &Info,
1479 raw_ostream &OS) {
1480 OS << "// Flags for subtarget features that participate in "
1481 << "instruction matching.\n";
1482 OS << "enum SubtargetFeatureFlag {\n";
1483 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1484 it = Info.SubtargetFeatures.begin(),
1485 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1486 SubtargetFeatureInfo &SFI = *it->second;
1487 OS << " " << SFI.EnumName << " = (1 << " << SFI.Index << "),\n";
1488 }
1489 OS << " Feature_None = 0\n";
1490 OS << "};\n\n";
1491}
1492
1493/// EmitComputeAvailableFeatures - Emit the function to compute the list of
1494/// available features given a subtarget.
1495static void EmitComputeAvailableFeatures(CodeGenTarget &Target,
1496 AsmMatcherInfo &Info,
1497 raw_ostream &OS) {
1498 std::string ClassName =
1499 Info.AsmParser->getValueAsString("AsmParserClassName");
1500
1501 OS << "unsigned " << Target.getName() << ClassName << "::\n"
1502 << "ComputeAvailableFeatures(const " << Target.getName()
1503 << "Subtarget *Subtarget) const {\n";
1504 OS << " unsigned Features = 0;\n";
1505 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1506 it = Info.SubtargetFeatures.begin(),
1507 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1508 SubtargetFeatureInfo &SFI = *it->second;
1509 OS << " if (" << SFI.TheDef->getValueAsString("CondString")
1510 << ")\n";
1511 OS << " Features |= " << SFI.EnumName << ";\n";
1512 }
1513 OS << " return Features;\n";
1514 OS << "}\n\n";
1515}
1516
Chris Lattner674c1dc2010-10-30 17:36:36 +00001517/// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
Chris Lattner7fd44892010-10-30 18:48:18 +00001518/// emit a function for them and return true, otherwise return false.
1519static bool EmitMnemonicAliases(raw_ostream &OS) {
Chris Lattner674c1dc2010-10-30 17:36:36 +00001520 std::vector<Record*> Aliases =
1521 Records.getAllDerivedDefinitions("MnemonicAlias");
Chris Lattner7fd44892010-10-30 18:48:18 +00001522 if (Aliases.empty()) return false;
Chris Lattner674c1dc2010-10-30 17:36:36 +00001523
Chris Lattner8cc0a6b2010-10-30 18:57:07 +00001524 OS << "static void ApplyMnemonicAliases(StringRef &Mnemonic, "
1525 "unsigned Features) {\n";
1526
Chris Lattner4fd32c62010-10-30 18:56:12 +00001527 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
1528 // iteration order of the map is stable.
1529 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1530
Chris Lattner674c1dc2010-10-30 17:36:36 +00001531 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1532 Record *R = Aliases[i];
Chris Lattner4fd32c62010-10-30 18:56:12 +00001533 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
Chris Lattner674c1dc2010-10-30 17:36:36 +00001534 }
Chris Lattner4fd32c62010-10-30 18:56:12 +00001535
1536 // Process each alias a "from" mnemonic at a time, building the code executed
1537 // by the string remapper.
1538 std::vector<StringMatcher::StringPair> Cases;
1539 for (std::map<std::string, std::vector<Record*> >::iterator
1540 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1541 I != E; ++I) {
1542 const std::string &From = I->first;
1543 const std::vector<Record*> &ToVec = I->second;
1544
1545 // If there is only one destination mnemonic, generate simple code.
1546 if (ToVec.size() == 1) {
1547 Cases.push_back(std::make_pair(From, "Mnemonic = \"" +
1548 ToVec[0]->getValueAsString("ToMnemonic") +
1549 "\"; return;"));
1550 continue;
1551 }
1552
1553 // Otherwise, diagnose an error, can't have two aliases from the same
1554 // mnemonic.
1555 PrintError(ToVec[0]->getLoc(), "two MnemonicAliases with the same 'from' mnemonic!");
1556 PrintError(ToVec[1]->getLoc(), "this is the other MnemonicAliases.");
1557 throw std::string("ERROR: Invalid MnemonicAliases definitions!");
1558 }
1559
Chris Lattner674c1dc2010-10-30 17:36:36 +00001560
1561 StringMatcher("Mnemonic", Cases, OS).Emit();
Chris Lattner7fd44892010-10-30 18:48:18 +00001562 OS << "}\n";
1563
1564 return true;
Chris Lattner674c1dc2010-10-30 17:36:36 +00001565}
1566
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001567void AsmMatcherEmitter::run(raw_ostream &OS) {
1568 CodeGenTarget Target;
1569 Record *AsmParser = Target.getAsmParser();
1570 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1571
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001572 // Compute the information on the instructions to match.
Daniel Dunbar59fc42d2009-08-11 20:59:47 +00001573 AsmMatcherInfo Info(AsmParser);
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001574 Info.BuildInfo(Target);
Daniel Dunbara027d222009-07-31 02:32:59 +00001575
Daniel Dunbare1f6de32010-02-02 23:46:36 +00001576 // Sort the instruction table using the partial order on classes. We use
1577 // stable_sort to ensure that ambiguous instructions are still
1578 // deterministically ordered.
1579 std::stable_sort(Info.Instructions.begin(), Info.Instructions.end(),
1580 less_ptr<InstructionInfo>());
Jim Grosbacha7c78222010-10-29 22:13:48 +00001581
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001582 DEBUG_WITH_TYPE("instruction_info", {
Jim Grosbacha7c78222010-10-29 22:13:48 +00001583 for (std::vector<InstructionInfo*>::iterator
1584 it = Info.Instructions.begin(), ie = Info.Instructions.end();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001585 it != ie; ++it)
Daniel Dunbar20927f22009-08-07 08:26:05 +00001586 (*it)->dump();
1587 });
Daniel Dunbara027d222009-07-31 02:32:59 +00001588
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001589 // Check for ambiguous instructions.
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00001590 DEBUG_WITH_TYPE("ambiguous_instrs", {
1591 unsigned NumAmbiguous = 0;
Chris Lattner87410362010-09-06 20:21:47 +00001592 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1593 for (unsigned j = i + 1; j != e; ++j) {
1594 InstructionInfo &A = *Info.Instructions[i];
1595 InstructionInfo &B = *Info.Instructions[j];
Jim Grosbacha7c78222010-10-29 22:13:48 +00001596
Chris Lattner87410362010-09-06 20:21:47 +00001597 if (A.CouldMatchAmiguouslyWith(B)) {
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00001598 errs() << "warning: ambiguous instruction match:\n";
1599 A.dump();
1600 errs() << "\nis incomparable with:\n";
1601 B.dump();
1602 errs() << "\n\n";
Chris Lattner87410362010-09-06 20:21:47 +00001603 ++NumAmbiguous;
1604 }
Daniel Dunbar2b544812009-08-09 06:05:33 +00001605 }
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001606 }
Chris Lattner87410362010-09-06 20:21:47 +00001607 if (NumAmbiguous)
Jim Grosbacha7c78222010-10-29 22:13:48 +00001608 errs() << "warning: " << NumAmbiguous
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00001609 << " ambiguous instructions!\n";
1610 });
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001611
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001612 // Write the output.
1613
1614 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1615
Chris Lattner0692ee62010-09-06 19:11:01 +00001616 // Information for the class declaration.
1617 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
1618 OS << "#undef GET_ASSEMBLER_HEADER\n";
Chris Lattner79ed3f72010-09-06 19:22:17 +00001619 OS << " // This should be included into the middle of the declaration of \n";
1620 OS << " // your subclasses implementation of TargetAsmParser.\n";
Chris Lattner0692ee62010-09-06 19:11:01 +00001621 OS << " unsigned ComputeAvailableFeatures(const " <<
1622 Target.getName() << "Subtarget *Subtarget) const;\n";
Chris Lattner79ed3f72010-09-06 19:22:17 +00001623 OS << " enum MatchResultTy {\n";
Chris Lattnera008e8a2010-09-06 21:54:15 +00001624 OS << " Match_Success, Match_MnemonicFail, Match_InvalidOperand,\n";
1625 OS << " Match_MissingFeature\n";
Chris Lattner79ed3f72010-09-06 19:22:17 +00001626 OS << " };\n";
Jim Grosbachbb168242010-10-08 18:13:57 +00001627 OS << " MatchResultTy MatchInstructionImpl(const "
1628 << "SmallVectorImpl<MCParsedAsmOperand*>"
Chris Lattnerce4a3352010-09-06 22:11:18 +00001629 << " &Operands, MCInst &Inst, unsigned &ErrorInfo);\n\n";
Chris Lattner0692ee62010-09-06 19:11:01 +00001630 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
1631
Jim Grosbacha7c78222010-10-29 22:13:48 +00001632
1633
1634
Chris Lattner0692ee62010-09-06 19:11:01 +00001635 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
1636 OS << "#undef GET_REGISTER_MATCHER\n\n";
1637
Daniel Dunbar54074b52010-07-19 05:44:09 +00001638 // Emit the subtarget feature enumeration.
1639 EmitSubtargetFeatureFlagEnumeration(Target, Info, OS);
1640
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001641 // Emit the function to match a register name to number.
1642 EmitMatchRegisterName(Target, AsmParser, OS);
Chris Lattner0692ee62010-09-06 19:11:01 +00001643
1644 OS << "#endif // GET_REGISTER_MATCHER\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001645
Chris Lattner0692ee62010-09-06 19:11:01 +00001646
1647 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
1648 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001649
Chris Lattner7fd44892010-10-30 18:48:18 +00001650 // Generate the function that remaps for mnemonic aliases.
1651 bool HasMnemonicAliases = EmitMnemonicAliases(OS);
1652
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001653 // Generate the unified function to convert operands into an MCInst.
1654 EmitConvertToMCInst(Target, Info.Instructions, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00001655
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001656 // Emit the enumeration for classes which participate in matching.
1657 EmitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00001658
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001659 // Emit the routine to match token strings to their match class.
1660 EmitMatchTokenString(Target, Info.Classes, OS);
1661
1662 // Emit the routine to classify an operand.
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001663 EmitClassifyOperand(Target, Info, OS);
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001664
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001665 // Emit the subclass predicate routine.
1666 EmitIsSubclass(Target, Info.Classes, OS);
1667
Daniel Dunbar54074b52010-07-19 05:44:09 +00001668 // Emit the available features compute function.
1669 EmitComputeAvailableFeatures(Target, Info, OS);
1670
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001671
1672 size_t MaxNumOperands = 0;
1673 for (std::vector<InstructionInfo*>::const_iterator it =
1674 Info.Instructions.begin(), ie = Info.Instructions.end();
1675 it != ie; ++it)
1676 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
Jim Grosbacha7c78222010-10-29 22:13:48 +00001677
1678
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001679 // Emit the static match table; unused classes get initalized to 0 which is
1680 // guaranteed to be InvalidMatchClass.
1681 //
1682 // FIXME: We can reduce the size of this table very easily. First, we change
1683 // it so that store the kinds in separate bit-fields for each index, which
1684 // only needs to be the max width used for classes at that index (we also need
1685 // to reject based on this during classification). If we then make sure to
1686 // order the match kinds appropriately (putting mnemonics last), then we
1687 // should only end up using a few bits for each class, especially the ones
1688 // following the mnemonic.
Chris Lattner96352e52010-09-06 21:08:38 +00001689 OS << "namespace {\n";
1690 OS << " struct MatchEntry {\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001691 OS << " unsigned Opcode;\n";
Chris Lattnere206fcf2010-09-06 21:01:37 +00001692 OS << " const char *Mnemonic;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001693 OS << " ConversionKind ConvertFn;\n";
1694 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001695 OS << " unsigned RequiredFeatures;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001696 OS << " };\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001697
Chris Lattner2b1f9432010-09-06 21:22:45 +00001698 OS << "// Predicate for searching for an opcode.\n";
1699 OS << " struct LessOpcode {\n";
1700 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
1701 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
1702 OS << " }\n";
1703 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
1704 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
1705 OS << " }\n";
Chris Lattner32c685c2010-09-07 06:10:48 +00001706 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
1707 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
1708 OS << " }\n";
Chris Lattner96352e52010-09-06 21:08:38 +00001709 OS << " };\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001710
Chris Lattner96352e52010-09-06 21:08:38 +00001711 OS << "} // end anonymous namespace.\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001712
Chris Lattner96352e52010-09-06 21:08:38 +00001713 OS << "static const MatchEntry MatchTable["
1714 << Info.Instructions.size() << "] = {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001715
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001716 for (std::vector<InstructionInfo*>::const_iterator it =
Chris Lattner96352e52010-09-06 21:08:38 +00001717 Info.Instructions.begin(), ie = Info.Instructions.end();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001718 it != ie; ++it) {
Daniel Dunbar20927f22009-08-07 08:26:05 +00001719 InstructionInfo &II = **it;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001720
Chris Lattner96352e52010-09-06 21:08:38 +00001721 OS << " { " << Target.getName() << "::" << II.InstrName
1722 << ", \"" << II.Tokens[0] << "\""
1723 << ", " << II.ConversionFnKind << ", { ";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001724 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1725 InstructionInfo::Operand &Op = II.Operands[i];
Jim Grosbacha7c78222010-10-29 22:13:48 +00001726
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001727 if (i) OS << ", ";
1728 OS << Op.Class->Name;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001729 }
Daniel Dunbar54074b52010-07-19 05:44:09 +00001730 OS << " }, ";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001731
Daniel Dunbar54074b52010-07-19 05:44:09 +00001732 // Write the required features mask.
1733 if (!II.RequiredFeatures.empty()) {
1734 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
1735 if (i) OS << "|";
1736 OS << II.RequiredFeatures[i]->EnumName;
1737 }
1738 } else
1739 OS << "0";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001740
Daniel Dunbar54074b52010-07-19 05:44:09 +00001741 OS << "},\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00001742 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001743
Chris Lattner96352e52010-09-06 21:08:38 +00001744 OS << "};\n\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00001745
Chris Lattner96352e52010-09-06 21:08:38 +00001746 // Finally, build the match function.
1747 OS << Target.getName() << ClassName << "::MatchResultTy "
1748 << Target.getName() << ClassName << "::\n"
1749 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
1750 << " &Operands,\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001751 OS << " MCInst &Inst, unsigned &ErrorInfo) {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001752
1753 // Emit code to get the available features.
1754 OS << " // Get the current feature set.\n";
1755 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
1756
Chris Lattner674c1dc2010-10-30 17:36:36 +00001757 OS << " // Get the instruction mnemonic, which is the first token.\n";
1758 OS << " StringRef Mnemonic = ((" << Target.getName()
1759 << "Operand*)Operands[0])->getToken();\n\n";
1760
Chris Lattner7fd44892010-10-30 18:48:18 +00001761 if (HasMnemonicAliases) {
1762 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
1763 OS << " ApplyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
1764 }
Chris Lattner674c1dc2010-10-30 17:36:36 +00001765
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001766 // Emit code to compute the class list for this operand vector.
1767 OS << " // Eliminate obvious mismatches.\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001768 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
1769 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
1770 OS << " return Match_InvalidOperand;\n";
1771 OS << " }\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001772
1773 OS << " // Compute the class list for this operand vector.\n";
1774 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
Chris Lattnere206fcf2010-09-06 21:01:37 +00001775 OS << " for (unsigned i = 1, e = Operands.size(); i != e; ++i) {\n";
1776 OS << " Classes[i-1] = ClassifyOperand(Operands[i]);\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001777
1778 OS << " // Check for invalid operands before matching.\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001779 OS << " if (Classes[i-1] == InvalidMatchClass) {\n";
1780 OS << " ErrorInfo = i;\n";
Chris Lattnera008e8a2010-09-06 21:54:15 +00001781 OS << " return Match_InvalidOperand;\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001782 OS << " }\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001783 OS << " }\n\n";
1784
1785 OS << " // Mark unused classes.\n";
Chris Lattnere206fcf2010-09-06 21:01:37 +00001786 OS << " for (unsigned i = Operands.size()-1, e = " << MaxNumOperands << "; "
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001787 << "i != e; ++i)\n";
1788 OS << " Classes[i] = InvalidMatchClass;\n\n";
1789
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001790 OS << " // Some state to try to produce better error messages.\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001791 OS << " bool HadMatchOtherThanFeatures = false;\n\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001792 OS << " // Set ErrorInfo to the operand that mismatches if it is \n";
1793 OS << " // wrong for all instances of the instruction.\n";
1794 OS << " ErrorInfo = ~0U;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001795
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001796 // Emit code to search the table.
1797 OS << " // Search the table.\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001798 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
1799 OS << " std::equal_range(MatchTable, MatchTable+"
1800 << Info.Instructions.size() << ", Mnemonic, LessOpcode());\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001801
Chris Lattnera008e8a2010-09-06 21:54:15 +00001802 OS << " // Return a more specific error code if no mnemonics match.\n";
1803 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
1804 OS << " return Match_MnemonicFail;\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001805
Chris Lattner2b1f9432010-09-06 21:22:45 +00001806 OS << " for (const MatchEntry *it = MnemonicRange.first, "
Chris Lattner80db4e52010-09-06 21:23:43 +00001807 << "*ie = MnemonicRange.second;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001808 OS << " it != ie; ++it) {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001809
Gabor Greife53ee3b2010-09-07 06:06:06 +00001810 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Chris Lattner44b0daa2010-09-06 21:25:43 +00001811 OS << " assert(Mnemonic == it->Mnemonic);\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001812
Daniel Dunbar54074b52010-07-19 05:44:09 +00001813 // Emit check that the subclasses match.
Chris Lattnerce4a3352010-09-06 22:11:18 +00001814 OS << " bool OperandsValid = true;\n";
1815 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
1816 OS << " if (IsSubclass(Classes[i], it->Classes[i]))\n";
1817 OS << " continue;\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001818 OS << " // If this operand is broken for all of the instances of this\n";
1819 OS << " // mnemonic, keep track of it so we can report loc info.\n";
1820 OS << " if (it == MnemonicRange.first || ErrorInfo == i+1)\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001821 OS << " ErrorInfo = i+1;\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001822 OS << " else\n";
1823 OS << " ErrorInfo = ~0U;";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001824 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
1825 OS << " OperandsValid = false;\n";
1826 OS << " break;\n";
1827 OS << " }\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001828
Chris Lattnerce4a3352010-09-06 22:11:18 +00001829 OS << " if (!OperandsValid) continue;\n";
Chris Lattnerec6789f2010-09-06 20:08:02 +00001830
1831 // Emit check that the required features are available.
1832 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
1833 << "!= it->RequiredFeatures) {\n";
1834 OS << " HadMatchOtherThanFeatures = true;\n";
1835 OS << " continue;\n";
1836 OS << " }\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001837
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001838 OS << "\n";
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001839 OS << " ConvertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
1840
1841 // Call the post-processing function, if used.
1842 std::string InsnCleanupFn =
1843 AsmParser->getValueAsString("AsmParserInstCleanup");
1844 if (!InsnCleanupFn.empty())
1845 OS << " " << InsnCleanupFn << "(Inst);\n";
1846
Chris Lattner79ed3f72010-09-06 19:22:17 +00001847 OS << " return Match_Success;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001848 OS << " }\n\n";
1849
Chris Lattnerec6789f2010-09-06 20:08:02 +00001850 OS << " // Okay, we had no match. Try to return a useful error code.\n";
1851 OS << " if (HadMatchOtherThanFeatures) return Match_MissingFeature;\n";
Chris Lattnera008e8a2010-09-06 21:54:15 +00001852 OS << " return Match_InvalidOperand;\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00001853 OS << "}\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001854
Chris Lattner0692ee62010-09-06 19:11:01 +00001855 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbard51ffcf2009-07-11 19:39:44 +00001856}