blob: 6ddccc21b7e2711776908ae143767fd3ded0ed6b [file] [log] [blame]
Daniel Dunbar3085b572009-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 Dunbare10787e2009-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 Grosbach0eccfc22010-10-29 22:13:48 +000023// 'call' '*' %epc
Daniel Dunbare10787e2009-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 Dunbar3085b572009-07-11 19:39:44 +000074//===----------------------------------------------------------------------===//
75
76#include "AsmMatcherEmitter.h"
77#include "CodeGenTarget.h"
78#include "Record.h"
Chris Lattnerca5a3552010-09-06 02:01:51 +000079#include "StringMatcher.h"
Daniel Dunbare10787e2009-08-07 08:26:05 +000080#include "llvm/ADT/OwningPtr.h"
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +000081#include "llvm/ADT/SmallVector.h"
Daniel Dunbar3239f022009-08-09 04:00:06 +000082#include "llvm/ADT/STLExtras.h"
Daniel Dunbare10787e2009-08-07 08:26:05 +000083#include "llvm/ADT/StringExtras.h"
84#include "llvm/Support/CommandLine.h"
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +000085#include "llvm/Support/Debug.h"
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +000086#include <list>
Daniel Dunbar71330282009-08-08 05:24:34 +000087#include <map>
88#include <set>
Daniel Dunbar3085b572009-07-11 19:39:44 +000089using namespace llvm;
90
Daniel Dunbar15b80372009-08-07 20:33:39 +000091static cl::opt<std::string>
Daniel Dunbar3239f022009-08-09 04:00:06 +000092MatchPrefix("match-prefix", cl::init(""),
93 cl::desc("Only match instructions with the given prefix"));
Daniel Dunbare10787e2009-08-07 08:26:05 +000094
Daniel Dunbarb6d6aa22009-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 Grosbach0eccfc22010-10-29 22:13:48 +0000101
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000102 for (;;) {
Daniel Dunbarf30f4a52009-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 Grosbach0eccfc22010-10-29 22:13:48 +0000106 if (Cur[VariantsStart] == '{' &&
Daniel Dunbare10787e2009-08-07 08:26:05 +0000107 (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
108 Cur[VariantsStart-1] != '\\')))
Daniel Dunbarf30f4a52009-08-04 20:36:45 +0000109 break;
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000110
Daniel Dunbarf30f4a52009-08-04 20:36:45 +0000111 // Add the prefix to the result.
112 Res += Cur.slice(0, VariantsStart);
113 if (VariantsStart == Cur.size())
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000114 break;
115
Daniel Dunbarf30f4a52009-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 Dunbare10787e2009-08-07 08:26:05 +0000122 if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
Daniel Dunbarf30f4a52009-08-04 20:36:45 +0000123 if (--NestedBraces == 0)
124 break;
125 } else if (Cur[VariantsEnd] == '{')
126 ++NestedBraces;
127 }
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000128
129 // Select the Nth variant (or empty).
Daniel Dunbarf30f4a52009-08-04 20:36:45 +0000130 StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
Daniel Dunbarb6d6aa22009-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 Grosbach0eccfc22010-10-29 22:13:48 +0000135 assert(VariantsEnd != Cur.size() &&
Daniel Dunbarf30f4a52009-08-04 20:36:45 +0000136 "Unterminated variants in assembly string!");
137 Cur = Cur.substr(VariantsEnd + 1);
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000138 }
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000139
140 return Res;
141}
142
143/// TokenizeAsmString - Tokenize a simplified assembly string.
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000144static void TokenizeAsmString(StringRef AsmString,
Daniel Dunbarb6d6aa22009-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 Dunbare10787e2009-08-07 08:26:05 +0000150 case '[':
151 case ']':
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000152 case '*':
153 case '!':
154 case ' ':
155 case '\t':
156 case ',':
157 if (InTok) {
Daniel Dunbare10787e2009-08-07 08:26:05 +0000158 Tokens.push_back(AsmString.slice(Prev, i));
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000159 InTok = false;
160 }
Daniel Dunbare10787e2009-08-07 08:26:05 +0000161 if (!isspace(AsmString[i]) && AsmString[i] != ',')
162 Tokens.push_back(AsmString.substr(i, 1));
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000163 Prev = i + 1;
164 break;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000165
Daniel Dunbare10787e2009-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 Dunbarb6d6aa22009-07-31 02:32:59 +0000202
Daniel Dunbar69f024b2010-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 Dunbarb6d6aa22009-07-31 02:32:59 +0000211 default:
212 InTok = true;
213 }
214 }
215 if (InTok && Prev != AsmString.size())
Daniel Dunbare10787e2009-08-07 08:26:05 +0000216 Tokens.push_back(AsmString.substr(Prev));
217}
218
Chris Lattner60db0a62010-02-09 00:34:28 +0000219static bool IsAssemblerInstruction(StringRef Name,
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000220 const CodeGenInstruction &CGI,
Daniel Dunbare10787e2009-08-07 08:26:05 +0000221 const SmallVectorImpl<StringRef> &Tokens) {
Daniel Dunbarc4f8ea42009-08-11 22:17:52 +0000222 // Ignore "codegen only" instructions.
223 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
224 return false;
225
Daniel Dunbare0891c22009-08-09 08:19:00 +0000226 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
227 //
228 // FIXME: This is a total hack.
229 if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
230 return false;
231
Daniel Dunbare10787e2009-08-07 08:26:05 +0000232 // Ignore instructions with no .s string.
233 //
234 // FIXME: What are these?
Chris Lattner9492c172010-10-31 19:15:18 +0000235 if (CGI.AsmString.empty()) {
236 PrintError(CGI.TheDef->getLoc(),
237 "instruction with empty asm string");
238 throw std::string("ERROR: Invalid instruction for asm matcher");
239 }
Daniel Dunbare10787e2009-08-07 08:26:05 +0000240
241 // FIXME: Hack; ignore any instructions with a newline in them.
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000242 if (std::find(CGI.AsmString.begin(),
Daniel Dunbare10787e2009-08-07 08:26:05 +0000243 CGI.AsmString.end(), '\n') != CGI.AsmString.end())
244 return false;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000245
Chris Lattner9492c172010-10-31 19:15:18 +0000246 // Reject instructions with attributes, these aren't something we can handle,
247 // the target should be refactored to use operands instead of modifiers.
Daniel Dunbare10787e2009-08-07 08:26:05 +0000248 //
Daniel Dunbarc4f8ea42009-08-11 22:17:52 +0000249 // Also, check for instructions which reference the operand multiple times;
250 // this implies a constraint we would not honor.
Daniel Dunbare10787e2009-08-07 08:26:05 +0000251 std::set<std::string> OperandNames;
252 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
Chris Lattnere59eef32010-10-31 19:05:32 +0000253 if (Tokens[i][0] == '$' &&
Chris Lattner33fc3e02010-10-31 19:10:56 +0000254 Tokens[i].find(':') != StringRef::npos) {
255 PrintError(CGI.TheDef->getLoc(),
256 "instruction with operand modifier '" + Tokens[i].str() +
257 "' not supported by asm matcher. Mark isCodeGenOnly!");
258 throw std::string("ERROR: Invalid instruction");
Chris Lattnere59eef32010-10-31 19:05:32 +0000259 }
Chris Lattner33fc3e02010-10-31 19:10:56 +0000260
Chris Lattnere59eef32010-10-31 19:05:32 +0000261 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
262 DEBUG({
Chris Lattner33fc3e02010-10-31 19:10:56 +0000263 errs() << "warning: '" << Name << "': "
264 << "ignoring instruction with tied operand '"
265 << Tokens[i].str() << "'\n";
266 });
Chris Lattnere59eef32010-10-31 19:05:32 +0000267 return false;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000268 }
269 }
Chris Lattner33fc3e02010-10-31 19:10:56 +0000270
Daniel Dunbare10787e2009-08-07 08:26:05 +0000271 return true;
272}
273
274namespace {
275
Daniel Dunbareefe8612010-07-19 05:44:09 +0000276struct SubtargetFeatureInfo;
277
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000278/// ClassInfo - Helper class for storing the information about a particular
279/// class of operands which can be matched.
280struct ClassInfo {
Daniel Dunbar3239f022009-08-09 04:00:06 +0000281 enum ClassInfoKind {
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000282 /// Invalid kind, for use as a sentinel value.
283 Invalid = 0,
284
285 /// The class for a particular token.
286 Token,
287
288 /// The (first) register class, subsequent register classes are
289 /// RegisterClass0+1, and so on.
290 RegisterClass0,
291
292 /// The (first) user defined class, subsequent user defined classes are
293 /// UserClass0+1, and so on.
294 UserClass0 = 1<<16
Daniel Dunbar3239f022009-08-09 04:00:06 +0000295 };
296
297 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
298 /// N) for the Nth user defined class.
299 unsigned Kind;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000300
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000301 /// SuperClasses - The super classes of this class. Note that for simplicities
302 /// sake user operands only record their immediate super class, while register
303 /// operands include all superclasses.
304 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000305
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000306 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000307 std::string Name;
308
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000309 /// ClassName - The unadorned generic name for this class (e.g., Token).
310 std::string ClassName;
311
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000312 /// ValueName - The name of the value this class represents; for a token this
313 /// is the literal token string, for an operand it is the TableGen class (or
314 /// empty if this is a derived class).
315 std::string ValueName;
316
317 /// PredicateMethod - The name of the operand method to test whether the
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000318 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000319 std::string PredicateMethod;
320
321 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000322 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000323 std::string RenderMethod;
Daniel Dunbar3239f022009-08-09 04:00:06 +0000324
Daniel Dunbar34c87912009-08-11 20:10:07 +0000325 /// For register classes, the records for all the registers in this class.
326 std::set<Record*> Registers;
327
328public:
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000329 /// isRegisterClass() - Check if this is a register class.
330 bool isRegisterClass() const {
331 return Kind >= RegisterClass0 && Kind < UserClass0;
332 }
333
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000334 /// isUserClass() - Check if this is a user defined class.
335 bool isUserClass() const {
336 return Kind >= UserClass0;
337 }
338
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000339 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
340 /// are related if they are in the same class hierarchy.
341 bool isRelatedTo(const ClassInfo &RHS) const {
342 // Tokens are only related to tokens.
343 if (Kind == Token || RHS.Kind == Token)
344 return Kind == Token && RHS.Kind == Token;
345
Daniel Dunbar34c87912009-08-11 20:10:07 +0000346 // Registers classes are only related to registers classes, and only if
347 // their intersection is non-empty.
348 if (isRegisterClass() || RHS.isRegisterClass()) {
349 if (!isRegisterClass() || !RHS.isRegisterClass())
350 return false;
351
352 std::set<Record*> Tmp;
353 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000354 std::set_intersection(Registers.begin(), Registers.end(),
Daniel Dunbar34c87912009-08-11 20:10:07 +0000355 RHS.Registers.begin(), RHS.Registers.end(),
356 II);
357
358 return !Tmp.empty();
359 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000360
361 // Otherwise we have two users operands; they are related if they are in the
362 // same class hierarchy.
Daniel Dunbar34c87912009-08-11 20:10:07 +0000363 //
364 // FIXME: This is an oversimplification, they should only be related if they
365 // intersect, however we don't have that information.
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000366 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
367 const ClassInfo *Root = this;
368 while (!Root->SuperClasses.empty())
369 Root = Root->SuperClasses.front();
370
Daniel Dunbar34c87912009-08-11 20:10:07 +0000371 const ClassInfo *RHSRoot = &RHS;
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000372 while (!RHSRoot->SuperClasses.empty())
373 RHSRoot = RHSRoot->SuperClasses.front();
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000374
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000375 return Root == RHSRoot;
376 }
377
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000378 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000379 bool isSubsetOf(const ClassInfo &RHS) const {
380 // This is a subset of RHS if it is the same class...
381 if (this == &RHS)
382 return true;
383
384 // ... or if any of its super classes are a subset of RHS.
385 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
386 ie = SuperClasses.end(); it != ie; ++it)
387 if ((*it)->isSubsetOf(RHS))
388 return true;
389
390 return false;
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000391 }
392
Daniel Dunbar3239f022009-08-09 04:00:06 +0000393 /// operator< - Compare two classes.
394 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar97ac3af2010-05-27 05:31:32 +0000395 if (this == &RHS)
396 return false;
397
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000398 // Unrelated classes can be ordered by kind.
399 if (!isRelatedTo(RHS))
Daniel Dunbar3239f022009-08-09 04:00:06 +0000400 return Kind < RHS.Kind;
401
402 switch (Kind) {
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000403 case Invalid:
404 assert(0 && "Invalid kind!");
Daniel Dunbar3239f022009-08-09 04:00:06 +0000405 case Token:
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000406 // Tokens are comparable by value.
Daniel Dunbar3239f022009-08-09 04:00:06 +0000407 //
408 // FIXME: Compare by enum value.
409 return ValueName < RHS.ValueName;
410
Daniel Dunbar3239f022009-08-09 04:00:06 +0000411 default:
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000412 // This class preceeds the RHS if it is a proper subset of the RHS.
Daniel Dunbar97ac3af2010-05-27 05:31:32 +0000413 if (isSubsetOf(RHS))
Duncan Sands41b4a6b2010-07-12 08:16:59 +0000414 return true;
Daniel Dunbar97ac3af2010-05-27 05:31:32 +0000415 if (RHS.isSubsetOf(*this))
Duncan Sands41b4a6b2010-07-12 08:16:59 +0000416 return false;
Daniel Dunbar97ac3af2010-05-27 05:31:32 +0000417
418 // Otherwise, order by name to ensure we have a total ordering.
419 return ValueName < RHS.ValueName;
Daniel Dunbar3239f022009-08-09 04:00:06 +0000420 }
421 }
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000422};
423
Daniel Dunbar71330282009-08-08 05:24:34 +0000424/// InstructionInfo - Helper class for storing the necessary information for an
425/// instruction which is capable of being matched.
Daniel Dunbare10787e2009-08-07 08:26:05 +0000426struct InstructionInfo {
427 struct Operand {
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000428 /// The unique class instance this operand should match.
429 ClassInfo *Class;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000430
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000431 /// The original operand this corresponds to, if any.
Benjamin Kramer61130712009-08-08 10:06:30 +0000432 const CodeGenInstruction::OperandInfo *OperandInfo;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000433 };
434
435 /// InstrName - The target name for this instruction.
436 std::string InstrName;
437
438 /// Instr - The instruction this matches.
439 const CodeGenInstruction *Instr;
440
441 /// AsmString - The assembly string for this instruction (with variants
442 /// removed).
443 std::string AsmString;
444
445 /// Tokens - The tokenized assembly pattern that this instruction matches.
446 SmallVector<StringRef, 4> Tokens;
447
448 /// Operands - The operands that this instruction matches.
449 SmallVector<Operand, 4> Operands;
450
Daniel Dunbareefe8612010-07-19 05:44:09 +0000451 /// Predicates - The required subtarget features to match this instruction.
452 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
453
Daniel Dunbar71330282009-08-08 05:24:34 +0000454 /// ConversionFnKind - The enum value which is passed to the generated
455 /// ConvertToMCInst to convert parsed operands into an MCInst for this
456 /// function.
457 std::string ConversionFnKind;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000458
Daniel Dunbar3239f022009-08-09 04:00:06 +0000459 /// operator< - Compare two instructions.
460 bool operator<(const InstructionInfo &RHS) const {
Chris Lattner82d88ce2010-09-06 21:01:37 +0000461 // The primary comparator is the instruction mnemonic.
462 if (Tokens[0] != RHS.Tokens[0])
463 return Tokens[0] < RHS.Tokens[0];
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000464
Daniel Dunbar3239f022009-08-09 04:00:06 +0000465 if (Operands.size() != RHS.Operands.size())
466 return Operands.size() < RHS.Operands.size();
Daniel Dunbar3239f022009-08-09 04:00:06 +0000467
Daniel Dunbard9631912009-08-09 08:23:23 +0000468 // Compare lexicographically by operand. The matcher validates that other
469 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
470 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Daniel Dunbar3239f022009-08-09 04:00:06 +0000471 if (*Operands[i].Class < *RHS.Operands[i].Class)
472 return true;
Daniel Dunbard9631912009-08-09 08:23:23 +0000473 if (*RHS.Operands[i].Class < *Operands[i].Class)
474 return false;
475 }
476
Daniel Dunbar3239f022009-08-09 04:00:06 +0000477 return false;
478 }
479
Daniel Dunbarf573b562009-08-09 06:05:33 +0000480 /// CouldMatchAmiguouslyWith - Check whether this instruction could
481 /// ambiguously match the same set of operands as \arg RHS (without being a
482 /// strictly superior match).
483 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
484 // The number of operands is unambiguous.
485 if (Operands.size() != RHS.Operands.size())
486 return false;
487
Daniel Dunbare1974092010-01-23 00:26:16 +0000488 // Otherwise, make sure the ordering of the two instructions is unambiguous
489 // by checking that either (a) a token or operand kind discriminates them,
490 // or (b) the ordering among equivalent kinds is consistent.
491
Daniel Dunbarf573b562009-08-09 06:05:33 +0000492 // Tokens and operand kinds are unambiguous (assuming a correct target
493 // specific parser).
494 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
495 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
496 Operands[i].Class->Kind == ClassInfo::Token)
497 if (*Operands[i].Class < *RHS.Operands[i].Class ||
498 *RHS.Operands[i].Class < *Operands[i].Class)
499 return false;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000500
Daniel Dunbarf573b562009-08-09 06:05:33 +0000501 // Otherwise, this operand could commute if all operands are equivalent, or
502 // there is a pair of operands that compare less than and a pair that
503 // compare greater than.
504 bool HasLT = false, HasGT = false;
505 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
506 if (*Operands[i].Class < *RHS.Operands[i].Class)
507 HasLT = true;
508 if (*RHS.Operands[i].Class < *Operands[i].Class)
509 HasGT = true;
510 }
511
512 return !(HasLT ^ HasGT);
513 }
514
Daniel Dunbare10787e2009-08-07 08:26:05 +0000515public:
516 void dump();
517};
518
Daniel Dunbareefe8612010-07-19 05:44:09 +0000519/// SubtargetFeatureInfo - Helper class for storing information on a subtarget
520/// feature which participates in instruction matching.
521struct SubtargetFeatureInfo {
522 /// \brief The predicate record for this feature.
523 Record *TheDef;
524
525 /// \brief An unique index assigned to represent this feature.
526 unsigned Index;
527
Chris Lattnera0e87192010-10-30 20:07:57 +0000528 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
529
Daniel Dunbareefe8612010-07-19 05:44:09 +0000530 /// \brief The name of the enumerated constant identifying this feature.
Chris Lattnera0e87192010-10-30 20:07:57 +0000531 std::string getEnumName() const {
532 return "Feature_" + TheDef->getName();
533 }
Daniel Dunbareefe8612010-07-19 05:44:09 +0000534};
535
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000536class AsmMatcherInfo {
537public:
Daniel Dunbare4318712009-08-11 20:59:47 +0000538 /// The tablegen AsmParser record.
539 Record *AsmParser;
540
541 /// The AsmParser "CommentDelimiter" value.
542 std::string CommentDelimiter;
543
544 /// The AsmParser "RegisterPrefix" value.
545 std::string RegisterPrefix;
546
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000547 /// The classes which are needed for matching.
548 std::vector<ClassInfo*> Classes;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000549
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000550 /// The information on the instruction to match.
551 std::vector<InstructionInfo*> Instructions;
552
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000553 /// Map of Register records to their class information.
554 std::map<Record*, ClassInfo*> RegisterClasses;
555
Daniel Dunbareefe8612010-07-19 05:44:09 +0000556 /// Map of Predicate records to their subtarget information.
557 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
Chris Lattner43690072010-10-30 20:15:02 +0000558
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000559private:
560 /// Map of token to class information which has already been constructed.
561 std::map<std::string, ClassInfo*> TokenClasses;
562
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000563 /// Map of RegisterClass records to their class information.
564 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000565
Daniel Dunbar17410a42009-08-10 18:41:10 +0000566 /// Map of AsmOperandClass records to their class information.
567 std::map<Record*, ClassInfo*> AsmOperandClasses;
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000568
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000569private:
570 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattner60db0a62010-02-09 00:34:28 +0000571 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000572
573 /// getOperandClass - Lookup or create the class for the given operand.
Chris Lattner60db0a62010-02-09 00:34:28 +0000574 ClassInfo *getOperandClass(StringRef Token,
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000575 const CodeGenInstruction::OperandInfo &OI);
576
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000577 /// BuildRegisterClasses - Build the ClassInfo* instances for register
578 /// classes.
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000579 void BuildRegisterClasses(CodeGenTarget &Target,
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000580 std::set<std::string> &SingletonRegisterNames);
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000581
582 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
583 /// operand classes.
584 void BuildOperandClasses(CodeGenTarget &Target);
585
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000586public:
Daniel Dunbare4318712009-08-11 20:59:47 +0000587 AsmMatcherInfo(Record *_AsmParser);
588
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000589 /// BuildInfo - Construct the various tables used during matching.
590 void BuildInfo(CodeGenTarget &Target);
Chris Lattner43690072010-10-30 20:15:02 +0000591
592 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
593 /// given operand.
594 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
595 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
596 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
597 SubtargetFeatures.find(Def);
598 return I == SubtargetFeatures.end() ? 0 : I->second;
599 }
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000600};
601
Daniel Dunbare10787e2009-08-07 08:26:05 +0000602}
603
604void InstructionInfo::dump() {
605 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
606 << ", tokens:[";
607 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
608 errs() << Tokens[i];
609 if (i + 1 != e)
610 errs() << ", ";
611 }
612 errs() << "]\n";
613
614 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
615 Operand &Op = Operands[i];
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000616 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000617 if (Op.Class->Kind == ClassInfo::Token) {
Daniel Dunbare10787e2009-08-07 08:26:05 +0000618 errs() << '\"' << Tokens[i] << "\"\n";
619 continue;
620 }
621
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000622 if (!Op.OperandInfo) {
623 errs() << "(singleton register)\n";
624 continue;
625 }
626
Benjamin Kramer61130712009-08-08 10:06:30 +0000627 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000628 errs() << OI.Name << " " << OI.Rec->getName()
629 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
630 }
631}
632
Chris Lattner60db0a62010-02-09 00:34:28 +0000633static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000634 std::string Res;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000635
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000636 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
637 switch (*it) {
638 case '*': Res += "_STAR_"; break;
639 case '%': Res += "_PCT_"; break;
640 case ':': Res += "_COLON_"; break;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000641 default:
Chris Lattner33fc3e02010-10-31 19:10:56 +0000642 if (isalnum(*it))
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000643 Res += *it;
Chris Lattner33fc3e02010-10-31 19:10:56 +0000644 else
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000645 Res += "_" + utostr((unsigned) *it) + "_";
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000646 }
647 }
648
649 return Res;
650}
651
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000652/// getRegisterRecord - Get the register record for \arg name, or 0.
Chris Lattner60db0a62010-02-09 00:34:28 +0000653static Record *getRegisterRecord(CodeGenTarget &Target, StringRef Name) {
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000654 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
655 const CodeGenRegister &Reg = Target.getRegisters()[i];
656 if (Name == Reg.TheDef->getValueAsString("AsmName"))
657 return Reg.TheDef;
658 }
659
660 return 0;
661}
662
Chris Lattner60db0a62010-02-09 00:34:28 +0000663ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000664 ClassInfo *&Entry = TokenClasses[Token];
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000665
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000666 if (!Entry) {
667 Entry = new ClassInfo();
668 Entry->Kind = ClassInfo::Token;
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000669 Entry->ClassName = "Token";
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000670 Entry->Name = "MCK_" + getEnumNameForToken(Token);
671 Entry->ValueName = Token;
672 Entry->PredicateMethod = "<invalid>";
673 Entry->RenderMethod = "<invalid>";
674 Classes.push_back(Entry);
675 }
676
677 return Entry;
678}
679
680ClassInfo *
Chris Lattner60db0a62010-02-09 00:34:28 +0000681AsmMatcherInfo::getOperandClass(StringRef Token,
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000682 const CodeGenInstruction::OperandInfo &OI) {
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000683 if (OI.Rec->isSubClassOf("RegisterClass")) {
684 ClassInfo *CI = RegisterClassClasses[OI.Rec];
685
686 if (!CI) {
687 PrintError(OI.Rec->getLoc(), "register class has no class info!");
688 throw std::string("ERROR: Missing register class!");
689 }
690
691 return CI;
692 }
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000693
Daniel Dunbar17410a42009-08-10 18:41:10 +0000694 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
695 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
696 ClassInfo *CI = AsmOperandClasses[MatchClass];
697
698 if (!CI) {
699 PrintError(OI.Rec->getLoc(), "operand has no match class!");
700 throw std::string("ERROR: Missing match class!");
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000701 }
702
Daniel Dunbar17410a42009-08-10 18:41:10 +0000703 return CI;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000704}
705
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000706void AsmMatcherInfo::BuildRegisterClasses(CodeGenTarget &Target,
707 std::set<std::string>
708 &SingletonRegisterNames) {
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000709 std::vector<CodeGenRegisterClass> RegisterClasses;
710 std::vector<CodeGenRegister> Registers;
Daniel Dunbar17410a42009-08-10 18:41:10 +0000711
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000712 RegisterClasses = Target.getRegisterClasses();
713 Registers = Target.getRegisters();
Daniel Dunbar17410a42009-08-10 18:41:10 +0000714
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000715 // The register sets used for matching.
716 std::set< std::set<Record*> > RegisterSets;
717
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000718 // Gather the defined sets.
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000719 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
720 ie = RegisterClasses.end(); it != ie; ++it)
721 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
722 it->Elements.end()));
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000723
724 // Add any required singleton sets.
725 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
726 ie = SingletonRegisterNames.end(); it != ie; ++it)
727 if (Record *Rec = getRegisterRecord(Target, *it))
728 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000729
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000730 // Introduce derived sets where necessary (when a register does not determine
731 // a unique register set class), and build the mapping of registers to the set
732 // they should classify to.
733 std::map<Record*, std::set<Record*> > RegisterMap;
734 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
735 ie = Registers.end(); it != ie; ++it) {
736 CodeGenRegister &CGR = *it;
737 // Compute the intersection of all sets containing this register.
738 std::set<Record*> ContainingSet;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000739
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000740 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
741 ie = RegisterSets.end(); it != ie; ++it) {
742 if (!it->count(CGR.TheDef))
743 continue;
744
745 if (ContainingSet.empty()) {
746 ContainingSet = *it;
747 } else {
748 std::set<Record*> Tmp;
749 std::swap(Tmp, ContainingSet);
750 std::insert_iterator< std::set<Record*> > II(ContainingSet,
751 ContainingSet.begin());
752 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
753 II);
754 }
755 }
756
757 if (!ContainingSet.empty()) {
758 RegisterSets.insert(ContainingSet);
759 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
760 }
761 }
762
763 // Construct the register classes.
764 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
765 unsigned Index = 0;
766 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
767 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
768 ClassInfo *CI = new ClassInfo();
769 CI->Kind = ClassInfo::RegisterClass0 + Index;
770 CI->ClassName = "Reg" + utostr(Index);
771 CI->Name = "MCK_Reg" + utostr(Index);
772 CI->ValueName = "";
773 CI->PredicateMethod = ""; // unused
774 CI->RenderMethod = "addRegOperands";
Daniel Dunbar34c87912009-08-11 20:10:07 +0000775 CI->Registers = *it;
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000776 Classes.push_back(CI);
777 RegisterSetClasses.insert(std::make_pair(*it, CI));
778 }
779
780 // Find the superclasses; we could compute only the subgroup lattice edges,
781 // but there isn't really a point.
782 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
783 ie = RegisterSets.end(); it != ie; ++it) {
784 ClassInfo *CI = RegisterSetClasses[*it];
785 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
786 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000787 if (*it != *it2 &&
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000788 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
789 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
790 }
791
792 // Name the register classes which correspond to a user defined RegisterClass.
793 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
794 ie = RegisterClasses.end(); it != ie; ++it) {
795 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
796 it->Elements.end())];
797 if (CI->ValueName.empty()) {
798 CI->ClassName = it->getName();
799 CI->Name = "MCK_" + it->getName();
800 CI->ValueName = it->getName();
801 } else
802 CI->ValueName = CI->ValueName + "," + it->getName();
803
804 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
805 }
806
807 // Populate the map for individual registers.
808 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
809 ie = RegisterMap.end(); it != ie; ++it)
810 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000811
812 // Name the register classes which correspond to singleton registers.
813 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
814 ie = SingletonRegisterNames.end(); it != ie; ++it) {
815 if (Record *Rec = getRegisterRecord(Target, *it)) {
816 ClassInfo *CI = this->RegisterClasses[Rec];
817 assert(CI && "Missing singleton register class info!");
818
819 if (CI->ValueName.empty()) {
820 CI->ClassName = Rec->getName();
821 CI->Name = "MCK_" + Rec->getName();
822 CI->ValueName = Rec->getName();
823 } else
824 CI->ValueName = CI->ValueName + "," + Rec->getName();
825 }
826 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000827}
828
829void AsmMatcherInfo::BuildOperandClasses(CodeGenTarget &Target) {
Daniel Dunbar17410a42009-08-10 18:41:10 +0000830 std::vector<Record*> AsmOperands;
831 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbarcf181532010-01-30 01:02:37 +0000832
833 // Pre-populate AsmOperandClasses map.
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000834 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbarcf181532010-01-30 01:02:37 +0000835 ie = AsmOperands.end(); it != ie; ++it)
836 AsmOperandClasses[*it] = new ClassInfo();
837
Daniel Dunbar17410a42009-08-10 18:41:10 +0000838 unsigned Index = 0;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000839 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbar17410a42009-08-10 18:41:10 +0000840 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
Daniel Dunbarcf181532010-01-30 01:02:37 +0000841 ClassInfo *CI = AsmOperandClasses[*it];
Daniel Dunbar17410a42009-08-10 18:41:10 +0000842 CI->Kind = ClassInfo::UserClass0 + Index;
843
Daniel Dunbar346782c2010-05-22 21:02:29 +0000844 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
845 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
846 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
847 if (!DI) {
848 PrintError((*it)->getLoc(), "Invalid super class reference!");
849 continue;
850 }
851
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000852 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
853 if (!SC)
Daniel Dunbar17410a42009-08-10 18:41:10 +0000854 PrintError((*it)->getLoc(), "Invalid super class reference!");
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000855 else
856 CI->SuperClasses.push_back(SC);
Daniel Dunbar17410a42009-08-10 18:41:10 +0000857 }
858 CI->ClassName = (*it)->getValueAsString("Name");
859 CI->Name = "MCK_" + CI->ClassName;
860 CI->ValueName = (*it)->getName();
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +0000861
862 // Get or construct the predicate method name.
863 Init *PMName = (*it)->getValueInit("PredicateMethod");
864 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
865 CI->PredicateMethod = SI->getValue();
866 } else {
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000867 assert(dynamic_cast<UnsetInit*>(PMName) &&
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +0000868 "Unexpected PredicateMethod field!");
869 CI->PredicateMethod = "is" + CI->ClassName;
870 }
871
872 // Get or construct the render method name.
873 Init *RMName = (*it)->getValueInit("RenderMethod");
874 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
875 CI->RenderMethod = SI->getValue();
876 } else {
877 assert(dynamic_cast<UnsetInit*>(RMName) &&
878 "Unexpected RenderMethod field!");
879 CI->RenderMethod = "add" + CI->ClassName + "Operands";
880 }
881
Daniel Dunbar17410a42009-08-10 18:41:10 +0000882 AsmOperandClasses[*it] = CI;
883 Classes.push_back(CI);
884 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000885}
886
Chris Lattnera0e87192010-10-30 20:07:57 +0000887AsmMatcherInfo::AsmMatcherInfo(Record *asmParser)
888 : AsmParser(asmParser),
Daniel Dunbare4318712009-08-11 20:59:47 +0000889 CommentDelimiter(AsmParser->getValueAsString("CommentDelimiter")),
890 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix"))
891{
892}
893
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000894void AsmMatcherInfo::BuildInfo(CodeGenTarget &Target) {
Chris Lattnera0e87192010-10-30 20:07:57 +0000895 // Build information about all of the AssemblerPredicates.
896 std::vector<Record*> AllPredicates =
897 Records.getAllDerivedDefinitions("Predicate");
898 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
899 Record *Pred = AllPredicates[i];
900 // Ignore predicates that are not intended for the assembler.
901 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
902 continue;
903
904 if (Pred->getName().empty()) {
905 PrintError(Pred->getLoc(), "Predicate has no name!");
906 throw std::string("ERROR: Predicate defs must be named");
907 }
908
909 unsigned FeatureNo = SubtargetFeatures.size();
910 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
911 assert(FeatureNo < 32 && "Too many subtarget features!");
912 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000913
Chris Lattner33fc3e02010-10-31 19:10:56 +0000914 // Parse the instructions; we need to do this first so that we can gather the
915 // singleton register classes.
916 std::set<std::string> SingletonRegisterNames;
917 const std::vector<const CodeGenInstruction*> &InstrList =
918 Target.getInstructionsByEnumValue();
Chris Lattner70eb8972010-03-19 00:18:23 +0000919 for (unsigned i = 0, e = InstrList.size(); i != e; ++i) {
920 const CodeGenInstruction &CGI = *InstrList[i];
Daniel Dunbare10787e2009-08-07 08:26:05 +0000921
Chris Lattner33fc3e02010-10-31 19:10:56 +0000922 // If the tblgen -match-prefix option is specified (for tblgen hackers),
923 // filter the set of instructions we consider.
Chris Lattner70eb8972010-03-19 00:18:23 +0000924 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
Daniel Dunbare10787e2009-08-07 08:26:05 +0000925 continue;
926
Chris Lattner70eb8972010-03-19 00:18:23 +0000927 OwningPtr<InstructionInfo> II(new InstructionInfo());
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000928
Chris Lattner70eb8972010-03-19 00:18:23 +0000929 II->InstrName = CGI.TheDef->getName();
930 II->Instr = &CGI;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000931 II->AsmString = FlattenVariants(CGI.AsmString, 0);
932
Chris Lattner33fc3e02010-10-31 19:10:56 +0000933 // Remove comments from the asm string. We know that the asmstring only
934 // has one line.
Daniel Dunbare4318712009-08-11 20:59:47 +0000935 if (!CommentDelimiter.empty()) {
936 size_t Idx = StringRef(II->AsmString).find(CommentDelimiter);
937 if (Idx != StringRef::npos)
938 II->AsmString = II->AsmString.substr(0, Idx);
939 }
940
Daniel Dunbare10787e2009-08-07 08:26:05 +0000941 TokenizeAsmString(II->AsmString, II->Tokens);
942
943 // Ignore instructions which shouldn't be matched.
Chris Lattner70eb8972010-03-19 00:18:23 +0000944 if (!IsAssemblerInstruction(CGI.TheDef->getName(), CGI, II->Tokens))
Daniel Dunbare10787e2009-08-07 08:26:05 +0000945 continue;
Chris Lattner33fc3e02010-10-31 19:10:56 +0000946
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000947 // Collect singleton registers, if used.
Chris Lattner1be06972010-10-28 21:28:42 +0000948 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
949 if (!II->Tokens[i].startswith(RegisterPrefix))
950 continue;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000951
Chris Lattner1be06972010-10-28 21:28:42 +0000952 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
953 Record *Rec = getRegisterRecord(Target, RegName);
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000954
Chris Lattner1be06972010-10-28 21:28:42 +0000955 if (!Rec) {
956 // If there is no register prefix (i.e. "%" in "%eax"), then this may
957 // be some random non-register token, just ignore it.
958 if (RegisterPrefix.empty())
959 continue;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000960
961 std::string Err = "unable to find register for '" + RegName.str() +
Chris Lattner1be06972010-10-28 21:28:42 +0000962 "' (which matches register prefix)";
963 throw TGError(CGI.TheDef->getLoc(), Err);
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000964 }
Chris Lattner1be06972010-10-28 21:28:42 +0000965
966 SingletonRegisterNames.insert(RegName);
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000967 }
Daniel Dunbareefe8612010-07-19 05:44:09 +0000968
969 // Compute the require features.
Chris Lattneraac142c2010-10-30 19:38:20 +0000970 std::vector<Record*> Predicates =
971 CGI.TheDef->getValueAsListOfDefs("Predicates");
Chris Lattner43690072010-10-30 20:15:02 +0000972 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
973 if (SubtargetFeatureInfo *Feature = getSubtargetFeature(Predicates[i]))
974 II->RequiredFeatures.push_back(Feature);
Daniel Dunbareefe8612010-07-19 05:44:09 +0000975
Daniel Dunbar3fb754a2009-08-11 23:23:44 +0000976 Instructions.push_back(II.take());
977 }
978
979 // Build info for the register classes.
980 BuildRegisterClasses(Target, SingletonRegisterNames);
981
982 // Build info for the user defined assembly operand classes.
983 BuildOperandClasses(Target);
984
985 // Build the instruction information.
986 for (std::vector<InstructionInfo*>::iterator it = Instructions.begin(),
987 ie = Instructions.end(); it != ie; ++it) {
988 InstructionInfo *II = *it;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000989
Chris Lattner82d88ce2010-09-06 21:01:37 +0000990 // The first token of the instruction is the mnemonic, which must be a
991 // simple string.
992 assert(!II->Tokens.empty() && "Instruction has no tokens?");
993 StringRef Mnemonic = II->Tokens[0];
994 assert(Mnemonic[0] != '$' &&
995 (RegisterPrefix.empty() || !Mnemonic.startswith(RegisterPrefix)));
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000996
Chris Lattner82d88ce2010-09-06 21:01:37 +0000997 // Parse the tokens after the mnemonic.
998 for (unsigned i = 1, e = II->Tokens.size(); i != e; ++i) {
Daniel Dunbare10787e2009-08-07 08:26:05 +0000999 StringRef Token = II->Tokens[i];
1000
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001001 // Check for singleton registers.
Chris Lattner1be06972010-10-28 21:28:42 +00001002 if (Token.startswith(RegisterPrefix)) {
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001003 StringRef RegName = II->Tokens[i].substr(RegisterPrefix.size());
Chris Lattner1be06972010-10-28 21:28:42 +00001004 if (Record *RegRecord = getRegisterRecord(Target, RegName)) {
1005 InstructionInfo::Operand Op;
1006 Op.Class = RegisterClasses[RegRecord];
1007 Op.OperandInfo = 0;
1008 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1009 "Unexpected class for singleton register");
1010 II->Operands.push_back(Op);
1011 continue;
1012 }
1013
1014 if (!RegisterPrefix.empty()) {
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001015 std::string Err = "unable to find register for '" + RegName.str() +
Chris Lattner1be06972010-10-28 21:28:42 +00001016 "' (which matches register prefix)";
1017 throw TGError(II->Instr->TheDef->getLoc(), Err);
1018 }
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001019 }
1020
Daniel Dunbare10787e2009-08-07 08:26:05 +00001021 // Check for simple tokens.
1022 if (Token[0] != '$') {
1023 InstructionInfo::Operand Op;
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001024 Op.Class = getTokenClass(Token);
Benjamin Kramer61130712009-08-08 10:06:30 +00001025 Op.OperandInfo = 0;
Daniel Dunbare10787e2009-08-07 08:26:05 +00001026 II->Operands.push_back(Op);
1027 continue;
1028 }
1029
1030 // Otherwise this is an operand reference.
Daniel Dunbare10787e2009-08-07 08:26:05 +00001031 StringRef OperandName;
1032 if (Token[1] == '{')
1033 OperandName = Token.substr(2, Token.size() - 3);
1034 else
1035 OperandName = Token.substr(1);
1036
1037 // Map this token to an operand. FIXME: Move elsewhere.
1038 unsigned Idx;
1039 try {
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001040 Idx = II->Instr->getOperandNamed(OperandName);
Daniel Dunbare10787e2009-08-07 08:26:05 +00001041 } catch(...) {
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001042 throw std::string("error: unable to find operand: '" +
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001043 OperandName.str() + "'");
Daniel Dunbare10787e2009-08-07 08:26:05 +00001044 }
1045
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001046 // FIXME: This is annoying, the named operand may be tied (e.g.,
1047 // XCHG8rm). What we want is the untied operand, which we now have to
1048 // grovel for. Only worry about this for single entry operands, we have to
1049 // clean this up anyway.
1050 const CodeGenInstruction::OperandInfo *OI = &II->Instr->OperandList[Idx];
1051 if (OI->Constraints[0].isTied()) {
1052 unsigned TiedOp = OI->Constraints[0].getTiedOperand();
1053
1054 // The tied operand index is an MIOperand index, find the operand that
1055 // contains it.
1056 for (unsigned i = 0, e = II->Instr->OperandList.size(); i != e; ++i) {
1057 if (II->Instr->OperandList[i].MIOperandNo == TiedOp) {
1058 OI = &II->Instr->OperandList[i];
1059 break;
1060 }
1061 }
1062
1063 assert(OI && "Unable to find tied operand target!");
1064 }
1065
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001066 InstructionInfo::Operand Op;
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001067 Op.Class = getOperandClass(Token, *OI);
1068 Op.OperandInfo = OI;
Daniel Dunbare10787e2009-08-07 08:26:05 +00001069 II->Operands.push_back(Op);
1070 }
Daniel Dunbare10787e2009-08-07 08:26:05 +00001071 }
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001072
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001073 // Reorder classes so that classes preceed super classes.
1074 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
Daniel Dunbare10787e2009-08-07 08:26:05 +00001075}
1076
Daniel Dunbar692d06f2010-02-12 01:46:54 +00001077static std::pair<unsigned, unsigned> *
1078GetTiedOperandAtIndex(SmallVectorImpl<std::pair<unsigned, unsigned> > &List,
1079 unsigned Index) {
1080 for (unsigned i = 0, e = List.size(); i != e; ++i)
1081 if (Index == List[i].first)
1082 return &List[i];
1083
1084 return 0;
1085}
1086
Daniel Dunbar3239f022009-08-09 04:00:06 +00001087static void EmitConvertToMCInst(CodeGenTarget &Target,
1088 std::vector<InstructionInfo*> &Infos,
1089 raw_ostream &OS) {
Daniel Dunbar71330282009-08-08 05:24:34 +00001090 // Write the convert function to a separate stream, so we can drop it after
1091 // the enum.
1092 std::string ConvertFnBody;
1093 raw_string_ostream CvtOS(ConvertFnBody);
1094
Daniel Dunbare10787e2009-08-07 08:26:05 +00001095 // Function we have already generated.
1096 std::set<std::string> GeneratedFns;
1097
Daniel Dunbar71330282009-08-08 05:24:34 +00001098 // Start the unified conversion function.
1099
Daniel Dunbar451a4352010-03-18 20:05:56 +00001100 CvtOS << "static void ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
Daniel Dunbar71330282009-08-08 05:24:34 +00001101 << "unsigned Opcode,\n"
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001102 << " const SmallVectorImpl<MCParsedAsmOperand*"
1103 << "> &Operands) {\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00001104 CvtOS << " Inst.setOpcode(Opcode);\n";
1105 CvtOS << " switch (Kind) {\n";
1106 CvtOS << " default:\n";
1107
1108 // Start the enum, which we will generate inline.
1109
1110 OS << "// Unified function for converting operants to MCInst instances.\n\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00001111 OS << "enum ConversionKind {\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001112
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001113 // TargetOperandClass - This is the target's operand class, like X86Operand.
1114 std::string TargetOperandClass = Target.getName() + "Operand";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001115
Daniel Dunbare10787e2009-08-07 08:26:05 +00001116 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
1117 ie = Infos.end(); it != ie; ++it) {
1118 InstructionInfo &II = **it;
1119
1120 // Order the (class) operands by the order to convert them into an MCInst.
1121 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
1122 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1123 InstructionInfo::Operand &Op = II.Operands[i];
Benjamin Kramer61130712009-08-08 10:06:30 +00001124 if (Op.OperandInfo)
1125 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
Daniel Dunbare10787e2009-08-07 08:26:05 +00001126 }
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001127
1128 // Find any tied operands.
1129 SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands;
1130 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1131 const CodeGenInstruction::OperandInfo &OpInfo = II.Instr->OperandList[i];
1132 for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) {
1133 const CodeGenInstruction::ConstraintInfo &CI = OpInfo.Constraints[j];
1134 if (CI.isTied())
1135 TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo + j,
1136 CI.getTiedOperand()));
1137 }
1138 }
1139
Daniel Dunbare10787e2009-08-07 08:26:05 +00001140 std::sort(MIOperandList.begin(), MIOperandList.end());
1141
1142 // Compute the total number of operands.
1143 unsigned NumMIOperands = 0;
1144 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1145 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001146 NumMIOperands = std::max(NumMIOperands,
Daniel Dunbare10787e2009-08-07 08:26:05 +00001147 OI.MIOperandNo + OI.MINumOperands);
1148 }
1149
1150 // Build the conversion function signature.
1151 std::string Signature = "Convert";
1152 unsigned CurIndex = 0;
1153 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1154 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
Benjamin Kramer61130712009-08-08 10:06:30 +00001155 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
Daniel Dunbare10787e2009-08-07 08:26:05 +00001156 "Duplicate match for instruction operand!");
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001157
Daniel Dunbare10787e2009-08-07 08:26:05 +00001158 // Skip operands which weren't matched by anything, this occurs when the
1159 // .td file encodes "implicit" operands as explicit ones.
1160 //
1161 // FIXME: This should be removed from the MCInst structure.
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001162 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
Daniel Dunbar692d06f2010-02-12 01:46:54 +00001163 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1164 CurIndex);
1165 if (!Tie)
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001166 Signature += "__Imp";
1167 else
Daniel Dunbar692d06f2010-02-12 01:46:54 +00001168 Signature += "__Tie" + utostr(Tie->second);
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001169 }
1170
1171 Signature += "__";
Daniel Dunbare10787e2009-08-07 08:26:05 +00001172
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001173 // Registers are always converted the same, don't duplicate the conversion
1174 // function based on them.
1175 //
1176 // FIXME: We could generalize this based on the render method, if it
1177 // mattered.
1178 if (Op.Class->isRegisterClass())
1179 Signature += "Reg";
1180 else
1181 Signature += Op.Class->ClassName;
Benjamin Kramer61130712009-08-08 10:06:30 +00001182 Signature += utostr(Op.OperandInfo->MINumOperands);
Daniel Dunbar71330282009-08-08 05:24:34 +00001183 Signature += "_" + utostr(MIOperandList[i].second);
1184
Benjamin Kramer61130712009-08-08 10:06:30 +00001185 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbare10787e2009-08-07 08:26:05 +00001186 }
1187
1188 // Add any trailing implicit operands.
Daniel Dunbar692d06f2010-02-12 01:46:54 +00001189 for (; CurIndex != NumMIOperands; ++CurIndex) {
1190 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1191 CurIndex);
1192 if (!Tie)
1193 Signature += "__Imp";
1194 else
1195 Signature += "__Tie" + utostr(Tie->second);
1196 }
Daniel Dunbare10787e2009-08-07 08:26:05 +00001197
Daniel Dunbar71330282009-08-08 05:24:34 +00001198 II.ConversionFnKind = Signature;
Daniel Dunbare10787e2009-08-07 08:26:05 +00001199
Daniel Dunbar71330282009-08-08 05:24:34 +00001200 // Check if we have already generated this signature.
Daniel Dunbare10787e2009-08-07 08:26:05 +00001201 if (!GeneratedFns.insert(Signature).second)
1202 continue;
1203
1204 // If not, emit it now.
Daniel Dunbar71330282009-08-08 05:24:34 +00001205
1206 // Add to the enum list.
1207 OS << " " << Signature << ",\n";
1208
1209 // And to the convert function.
1210 CvtOS << " case " << Signature << ":\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +00001211 CurIndex = 0;
1212 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1213 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1214
1215 // Add the implicit operands.
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001216 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1217 // See if this is a tied operand.
Daniel Dunbar692d06f2010-02-12 01:46:54 +00001218 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1219 CurIndex);
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001220
Daniel Dunbar692d06f2010-02-12 01:46:54 +00001221 if (!Tie) {
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001222 // If not, this is some implicit operand. Just assume it is a register
1223 // for now.
1224 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1225 } else {
1226 // Copy the tied operand.
Daniel Dunbar692d06f2010-02-12 01:46:54 +00001227 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001228 CvtOS << " Inst.addOperand(Inst.getOperand("
Daniel Dunbar692d06f2010-02-12 01:46:54 +00001229 << Tie->second << "));\n";
Daniel Dunbarf22553a2010-02-10 08:15:48 +00001230 }
1231 }
Daniel Dunbare10787e2009-08-07 08:26:05 +00001232
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001233 CvtOS << " ((" << TargetOperandClass << "*)Operands["
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001234 << MIOperandList[i].second
1235 << "+1])->" << Op.Class->RenderMethod
Benjamin Kramer61130712009-08-08 10:06:30 +00001236 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
1237 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbare10787e2009-08-07 08:26:05 +00001238 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001239
Daniel Dunbare10787e2009-08-07 08:26:05 +00001240 // And add trailing implicit operands.
Daniel Dunbar692d06f2010-02-12 01:46:54 +00001241 for (; CurIndex != NumMIOperands; ++CurIndex) {
1242 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1243 CurIndex);
1244
1245 if (!Tie) {
1246 // If not, this is some implicit operand. Just assume it is a register
1247 // for now.
1248 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1249 } else {
1250 // Copy the tied operand.
1251 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1252 CvtOS << " Inst.addOperand(Inst.getOperand("
1253 << Tie->second << "));\n";
1254 }
1255 }
1256
Daniel Dunbar451a4352010-03-18 20:05:56 +00001257 CvtOS << " return;\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +00001258 }
Daniel Dunbar71330282009-08-08 05:24:34 +00001259
1260 // Finish the convert function.
1261
1262 CvtOS << " }\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00001263 CvtOS << "}\n\n";
1264
1265 // Finish the enum, and drop the convert function after it.
1266
1267 OS << " NumConversionVariants\n";
1268 OS << "};\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001269
Daniel Dunbar71330282009-08-08 05:24:34 +00001270 OS << CvtOS.str();
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00001271}
1272
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001273/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1274static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1275 std::vector<ClassInfo*> &Infos,
1276 raw_ostream &OS) {
1277 OS << "namespace {\n\n";
1278
1279 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1280 << "/// instruction matching.\n";
1281 OS << "enum MatchClassKind {\n";
1282 OS << " InvalidMatchClass = 0,\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001283 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001284 ie = Infos.end(); it != ie; ++it) {
1285 ClassInfo &CI = **it;
1286 OS << " " << CI.Name << ", // ";
1287 if (CI.Kind == ClassInfo::Token) {
1288 OS << "'" << CI.ValueName << "'\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001289 } else if (CI.isRegisterClass()) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001290 if (!CI.ValueName.empty())
1291 OS << "register class '" << CI.ValueName << "'\n";
1292 else
1293 OS << "derived register class\n";
1294 } else {
1295 OS << "user defined class '" << CI.ValueName << "'\n";
1296 }
1297 }
1298 OS << " NumMatchClassKinds\n";
1299 OS << "};\n\n";
1300
1301 OS << "}\n\n";
1302}
1303
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001304/// EmitClassifyOperand - Emit the function to classify an operand.
1305static void EmitClassifyOperand(CodeGenTarget &Target,
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001306 AsmMatcherInfo &Info,
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001307 raw_ostream &OS) {
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001308 OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
1309 << " " << Target.getName() << "Operand &Operand = *("
1310 << Target.getName() << "Operand*)GOp;\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001311
1312 // Classify tokens.
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001313 OS << " if (Operand.isToken())\n";
1314 OS << " return MatchTokenString(Operand.getToken());\n\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001315
1316 // Classify registers.
1317 //
1318 // FIXME: Don't hardcode isReg, getReg.
1319 OS << " if (Operand.isReg()) {\n";
1320 OS << " switch (Operand.getReg()) {\n";
1321 OS << " default: return InvalidMatchClass;\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001322 for (std::map<Record*, ClassInfo*>::iterator
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001323 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1324 it != ie; ++it)
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001325 OS << " case " << Target.getName() << "::"
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001326 << it->first->getName() << ": return " << it->second->Name << ";\n";
1327 OS << " }\n";
1328 OS << " }\n\n";
1329
1330 // Classify user defined operands.
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001331 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001332 ie = Info.Classes.end(); it != ie; ++it) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001333 ClassInfo &CI = **it;
1334
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001335 if (!CI.isUserClass())
1336 continue;
1337
1338 OS << " // '" << CI.ClassName << "' class";
1339 if (!CI.SuperClasses.empty()) {
1340 OS << ", subclass of ";
1341 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1342 if (i) OS << ", ";
1343 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1344 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001345 }
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001346 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001347 OS << "\n";
1348
1349 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001350
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001351 // Validate subclass relationships.
1352 if (!CI.SuperClasses.empty()) {
1353 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1354 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1355 << "() && \"Invalid class relationship!\");\n";
1356 }
1357
1358 OS << " return " << CI.Name << ";\n";
1359 OS << " }\n\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001360 }
1361 OS << " return InvalidMatchClass;\n";
1362 OS << "}\n\n";
1363}
1364
Daniel Dunbar2587b612009-08-10 16:05:47 +00001365/// EmitIsSubclass - Emit the subclass predicate function.
1366static void EmitIsSubclass(CodeGenTarget &Target,
1367 std::vector<ClassInfo*> &Infos,
1368 raw_ostream &OS) {
1369 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1370 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1371 OS << " if (A == B)\n";
1372 OS << " return true;\n\n";
1373
1374 OS << " switch (A) {\n";
1375 OS << " default:\n";
1376 OS << " return false;\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001377 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbar2587b612009-08-10 16:05:47 +00001378 ie = Infos.end(); it != ie; ++it) {
1379 ClassInfo &A = **it;
1380
1381 if (A.Kind != ClassInfo::Token) {
1382 std::vector<StringRef> SuperClasses;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001383 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbar2587b612009-08-10 16:05:47 +00001384 ie = Infos.end(); it != ie; ++it) {
1385 ClassInfo &B = **it;
1386
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001387 if (&A != &B && A.isSubsetOf(B))
Daniel Dunbar2587b612009-08-10 16:05:47 +00001388 SuperClasses.push_back(B.Name);
1389 }
1390
1391 if (SuperClasses.empty())
1392 continue;
1393
1394 OS << "\n case " << A.Name << ":\n";
1395
1396 if (SuperClasses.size() == 1) {
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001397 OS << " return B == " << SuperClasses.back() << ";\n";
Daniel Dunbar2587b612009-08-10 16:05:47 +00001398 continue;
1399 }
1400
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001401 OS << " switch (B) {\n";
1402 OS << " default: return false;\n";
Daniel Dunbar2587b612009-08-10 16:05:47 +00001403 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001404 OS << " case " << SuperClasses[i] << ": return true;\n";
1405 OS << " }\n";
Daniel Dunbar2587b612009-08-10 16:05:47 +00001406 }
1407 }
1408 OS << " }\n";
1409 OS << "}\n\n";
1410}
1411
Chris Lattner00e2e742009-08-08 20:02:57 +00001412
1413
Daniel Dunbar66f4f542009-08-08 21:22:41 +00001414/// EmitMatchTokenString - Emit the function to match a token string to the
1415/// appropriate match class value.
1416static void EmitMatchTokenString(CodeGenTarget &Target,
1417 std::vector<ClassInfo*> &Infos,
1418 raw_ostream &OS) {
1419 // Construct the match list.
Chris Lattnerca5a3552010-09-06 02:01:51 +00001420 std::vector<StringMatcher::StringPair> Matches;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001421 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbar66f4f542009-08-08 21:22:41 +00001422 ie = Infos.end(); it != ie; ++it) {
1423 ClassInfo &CI = **it;
1424
1425 if (CI.Kind == ClassInfo::Token)
Chris Lattnerca5a3552010-09-06 02:01:51 +00001426 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1427 "return " + CI.Name + ";"));
Daniel Dunbar66f4f542009-08-08 21:22:41 +00001428 }
1429
Chris Lattner60db0a62010-02-09 00:34:28 +00001430 OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
Daniel Dunbar66f4f542009-08-08 21:22:41 +00001431
Chris Lattnerca5a3552010-09-06 02:01:51 +00001432 StringMatcher("Name", Matches, OS).Emit();
Daniel Dunbar66f4f542009-08-08 21:22:41 +00001433
1434 OS << " return InvalidMatchClass;\n";
1435 OS << "}\n\n";
1436}
Chris Lattner00e2e742009-08-08 20:02:57 +00001437
Daniel Dunbard0470d72009-08-07 21:01:44 +00001438/// EmitMatchRegisterName - Emit the function to match a string to the target
1439/// specific register enum.
1440static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1441 raw_ostream &OS) {
Daniel Dunbar66f4f542009-08-08 21:22:41 +00001442 // Construct the match list.
Chris Lattnerca5a3552010-09-06 02:01:51 +00001443 std::vector<StringMatcher::StringPair> Matches;
Daniel Dunbar66f4f542009-08-08 21:22:41 +00001444 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1445 const CodeGenRegister &Reg = Target.getRegisters()[i];
Daniel Dunbare2eec052009-07-17 18:51:11 +00001446 if (Reg.TheDef->getValueAsString("AsmName").empty())
1447 continue;
1448
Chris Lattnerca5a3552010-09-06 02:01:51 +00001449 Matches.push_back(StringMatcher::StringPair(
1450 Reg.TheDef->getValueAsString("AsmName"),
1451 "return " + utostr(i + 1) + ";"));
Daniel Dunbare2eec052009-07-17 18:51:11 +00001452 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001453
Chris Lattner60db0a62010-02-09 00:34:28 +00001454 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar66f4f542009-08-08 21:22:41 +00001455
Chris Lattnerca5a3552010-09-06 02:01:51 +00001456 StringMatcher("Name", Matches, OS).Emit();
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001457
Daniel Dunbar66f4f542009-08-08 21:22:41 +00001458 OS << " return 0;\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +00001459 OS << "}\n\n";
Daniel Dunbard0470d72009-08-07 21:01:44 +00001460}
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00001461
Daniel Dunbareefe8612010-07-19 05:44:09 +00001462/// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1463/// definitions.
1464static void EmitSubtargetFeatureFlagEnumeration(CodeGenTarget &Target,
1465 AsmMatcherInfo &Info,
1466 raw_ostream &OS) {
1467 OS << "// Flags for subtarget features that participate in "
1468 << "instruction matching.\n";
1469 OS << "enum SubtargetFeatureFlag {\n";
1470 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1471 it = Info.SubtargetFeatures.begin(),
1472 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1473 SubtargetFeatureInfo &SFI = *it->second;
Chris Lattnera0e87192010-10-30 20:07:57 +00001474 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00001475 }
1476 OS << " Feature_None = 0\n";
1477 OS << "};\n\n";
1478}
1479
1480/// EmitComputeAvailableFeatures - Emit the function to compute the list of
1481/// available features given a subtarget.
1482static void EmitComputeAvailableFeatures(CodeGenTarget &Target,
1483 AsmMatcherInfo &Info,
1484 raw_ostream &OS) {
1485 std::string ClassName =
1486 Info.AsmParser->getValueAsString("AsmParserClassName");
1487
1488 OS << "unsigned " << Target.getName() << ClassName << "::\n"
1489 << "ComputeAvailableFeatures(const " << Target.getName()
1490 << "Subtarget *Subtarget) const {\n";
1491 OS << " unsigned Features = 0;\n";
1492 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1493 it = Info.SubtargetFeatures.begin(),
1494 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1495 SubtargetFeatureInfo &SFI = *it->second;
1496 OS << " if (" << SFI.TheDef->getValueAsString("CondString")
1497 << ")\n";
Chris Lattnera0e87192010-10-30 20:07:57 +00001498 OS << " Features |= " << SFI.getEnumName() << ";\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00001499 }
1500 OS << " return Features;\n";
1501 OS << "}\n\n";
1502}
1503
Chris Lattner43690072010-10-30 20:15:02 +00001504static std::string GetAliasRequiredFeatures(Record *R,
1505 const AsmMatcherInfo &Info) {
Chris Lattner2cb092d2010-10-30 19:23:13 +00001506 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
Chris Lattner2cb092d2010-10-30 19:23:13 +00001507 std::string Result;
1508 unsigned NumFeatures = 0;
1509 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
Chris Lattner43690072010-10-30 20:15:02 +00001510 if (SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i])) {
1511 if (NumFeatures)
1512 Result += '|';
Chris Lattner2cb092d2010-10-30 19:23:13 +00001513
Chris Lattner43690072010-10-30 20:15:02 +00001514 Result += F->getEnumName();
1515 ++NumFeatures;
1516 }
Chris Lattner2cb092d2010-10-30 19:23:13 +00001517 }
1518
1519 if (NumFeatures > 1)
1520 Result = '(' + Result + ')';
1521 return Result;
1522}
1523
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00001524/// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
Chris Lattner477fba4f2010-10-30 18:48:18 +00001525/// emit a function for them and return true, otherwise return false.
Chris Lattnera0e87192010-10-30 20:07:57 +00001526static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00001527 std::vector<Record*> Aliases =
1528 Records.getAllDerivedDefinitions("MnemonicAlias");
Chris Lattner477fba4f2010-10-30 18:48:18 +00001529 if (Aliases.empty()) return false;
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00001530
Chris Lattnerec563972010-10-30 18:57:07 +00001531 OS << "static void ApplyMnemonicAliases(StringRef &Mnemonic, "
1532 "unsigned Features) {\n";
1533
Chris Lattnercf9b6e32010-10-30 18:56:12 +00001534 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
1535 // iteration order of the map is stable.
1536 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1537
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00001538 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1539 Record *R = Aliases[i];
Chris Lattnercf9b6e32010-10-30 18:56:12 +00001540 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00001541 }
Chris Lattnercf9b6e32010-10-30 18:56:12 +00001542
1543 // Process each alias a "from" mnemonic at a time, building the code executed
1544 // by the string remapper.
1545 std::vector<StringMatcher::StringPair> Cases;
1546 for (std::map<std::string, std::vector<Record*> >::iterator
1547 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1548 I != E; ++I) {
Chris Lattnercf9b6e32010-10-30 18:56:12 +00001549 const std::vector<Record*> &ToVec = I->second;
Chris Lattner2cb092d2010-10-30 19:23:13 +00001550
1551 // Loop through each alias and emit code that handles each case. If there
1552 // are two instructions without predicates, emit an error. If there is one,
1553 // emit it last.
1554 std::string MatchCode;
1555 int AliasWithNoPredicate = -1;
Chris Lattnercf9b6e32010-10-30 18:56:12 +00001556
Chris Lattner2cb092d2010-10-30 19:23:13 +00001557 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1558 Record *R = ToVec[i];
Chris Lattner43690072010-10-30 20:15:02 +00001559 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
Chris Lattner2cb092d2010-10-30 19:23:13 +00001560
1561 // If this unconditionally matches, remember it for later and diagnose
1562 // duplicates.
1563 if (FeatureMask.empty()) {
1564 if (AliasWithNoPredicate != -1) {
1565 // We can't have two aliases from the same mnemonic with no predicate.
1566 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1567 "two MnemonicAliases with the same 'from' mnemonic!");
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00001568 PrintError(R->getLoc(), "this is the other MnemonicAlias.");
1569 throw std::string("ERROR: Invalid MnemonicAlias definitions!");
Chris Lattner2cb092d2010-10-30 19:23:13 +00001570 }
1571
1572 AliasWithNoPredicate = i;
1573 continue;
1574 }
1575
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00001576 if (!MatchCode.empty())
1577 MatchCode += "else ";
Chris Lattner2cb092d2010-10-30 19:23:13 +00001578 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1579 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattnercf9b6e32010-10-30 18:56:12 +00001580 }
1581
Chris Lattner2cb092d2010-10-30 19:23:13 +00001582 if (AliasWithNoPredicate != -1) {
1583 Record *R = ToVec[AliasWithNoPredicate];
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00001584 if (!MatchCode.empty())
1585 MatchCode += "else\n ";
1586 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattner2cb092d2010-10-30 19:23:13 +00001587 }
1588
1589 MatchCode += "return;";
1590
1591 Cases.push_back(std::make_pair(I->first, MatchCode));
Chris Lattnercf9b6e32010-10-30 18:56:12 +00001592 }
1593
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00001594
1595 StringMatcher("Mnemonic", Cases, OS).Emit();
Chris Lattner477fba4f2010-10-30 18:48:18 +00001596 OS << "}\n";
1597
1598 return true;
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00001599}
1600
Daniel Dunbard0470d72009-08-07 21:01:44 +00001601void AsmMatcherEmitter::run(raw_ostream &OS) {
1602 CodeGenTarget Target;
1603 Record *AsmParser = Target.getAsmParser();
1604 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1605
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001606 // Compute the information on the instructions to match.
Daniel Dunbare4318712009-08-11 20:59:47 +00001607 AsmMatcherInfo Info(AsmParser);
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001608 Info.BuildInfo(Target);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00001609
Daniel Dunbar3b8a4662010-02-02 23:46:36 +00001610 // Sort the instruction table using the partial order on classes. We use
1611 // stable_sort to ensure that ambiguous instructions are still
1612 // deterministically ordered.
1613 std::stable_sort(Info.Instructions.begin(), Info.Instructions.end(),
1614 less_ptr<InstructionInfo>());
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001615
Daniel Dunbar71330282009-08-08 05:24:34 +00001616 DEBUG_WITH_TYPE("instruction_info", {
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001617 for (std::vector<InstructionInfo*>::iterator
1618 it = Info.Instructions.begin(), ie = Info.Instructions.end();
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001619 it != ie; ++it)
Daniel Dunbare10787e2009-08-07 08:26:05 +00001620 (*it)->dump();
1621 });
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00001622
Daniel Dunbar3239f022009-08-09 04:00:06 +00001623 // Check for ambiguous instructions.
Chris Lattnerc0658cb2010-09-06 21:28:52 +00001624 DEBUG_WITH_TYPE("ambiguous_instrs", {
1625 unsigned NumAmbiguous = 0;
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00001626 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1627 for (unsigned j = i + 1; j != e; ++j) {
1628 InstructionInfo &A = *Info.Instructions[i];
1629 InstructionInfo &B = *Info.Instructions[j];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001630
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00001631 if (A.CouldMatchAmiguouslyWith(B)) {
Chris Lattnerc0658cb2010-09-06 21:28:52 +00001632 errs() << "warning: ambiguous instruction match:\n";
1633 A.dump();
1634 errs() << "\nis incomparable with:\n";
1635 B.dump();
1636 errs() << "\n\n";
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00001637 ++NumAmbiguous;
1638 }
Daniel Dunbarf573b562009-08-09 06:05:33 +00001639 }
Daniel Dunbar3239f022009-08-09 04:00:06 +00001640 }
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00001641 if (NumAmbiguous)
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001642 errs() << "warning: " << NumAmbiguous
Chris Lattnerc0658cb2010-09-06 21:28:52 +00001643 << " ambiguous instructions!\n";
1644 });
Daniel Dunbar3239f022009-08-09 04:00:06 +00001645
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001646 // Write the output.
1647
1648 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1649
Chris Lattner3e4582a2010-09-06 19:11:01 +00001650 // Information for the class declaration.
1651 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
1652 OS << "#undef GET_ASSEMBLER_HEADER\n";
Chris Lattnera22a3682010-09-06 19:22:17 +00001653 OS << " // This should be included into the middle of the declaration of \n";
1654 OS << " // your subclasses implementation of TargetAsmParser.\n";
Chris Lattner3e4582a2010-09-06 19:11:01 +00001655 OS << " unsigned ComputeAvailableFeatures(const " <<
1656 Target.getName() << "Subtarget *Subtarget) const;\n";
Chris Lattnera22a3682010-09-06 19:22:17 +00001657 OS << " enum MatchResultTy {\n";
Chris Lattner628fbec2010-09-06 21:54:15 +00001658 OS << " Match_Success, Match_MnemonicFail, Match_InvalidOperand,\n";
1659 OS << " Match_MissingFeature\n";
Chris Lattnera22a3682010-09-06 19:22:17 +00001660 OS << " };\n";
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00001661 OS << " MatchResultTy MatchInstructionImpl(const "
1662 << "SmallVectorImpl<MCParsedAsmOperand*>"
Chris Lattner339cc7b2010-09-06 22:11:18 +00001663 << " &Operands, MCInst &Inst, unsigned &ErrorInfo);\n\n";
Chris Lattner3e4582a2010-09-06 19:11:01 +00001664 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
1665
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001666
1667
1668
Chris Lattner3e4582a2010-09-06 19:11:01 +00001669 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
1670 OS << "#undef GET_REGISTER_MATCHER\n\n";
1671
Daniel Dunbareefe8612010-07-19 05:44:09 +00001672 // Emit the subtarget feature enumeration.
1673 EmitSubtargetFeatureFlagEnumeration(Target, Info, OS);
1674
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001675 // Emit the function to match a register name to number.
1676 EmitMatchRegisterName(Target, AsmParser, OS);
Chris Lattner3e4582a2010-09-06 19:11:01 +00001677
1678 OS << "#endif // GET_REGISTER_MATCHER\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001679
Chris Lattner3e4582a2010-09-06 19:11:01 +00001680
1681 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
1682 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001683
Chris Lattner477fba4f2010-10-30 18:48:18 +00001684 // Generate the function that remaps for mnemonic aliases.
Chris Lattnera0e87192010-10-30 20:07:57 +00001685 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
Chris Lattner477fba4f2010-10-30 18:48:18 +00001686
Daniel Dunbar3239f022009-08-09 04:00:06 +00001687 // Generate the unified function to convert operands into an MCInst.
1688 EmitConvertToMCInst(Target, Info.Instructions, OS);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00001689
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001690 // Emit the enumeration for classes which participate in matching.
1691 EmitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00001692
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001693 // Emit the routine to match token strings to their match class.
1694 EmitMatchTokenString(Target, Info.Classes, OS);
1695
1696 // Emit the routine to classify an operand.
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001697 EmitClassifyOperand(Target, Info, OS);
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001698
Daniel Dunbar2587b612009-08-10 16:05:47 +00001699 // Emit the subclass predicate routine.
1700 EmitIsSubclass(Target, Info.Classes, OS);
1701
Daniel Dunbareefe8612010-07-19 05:44:09 +00001702 // Emit the available features compute function.
1703 EmitComputeAvailableFeatures(Target, Info, OS);
1704
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001705
1706 size_t MaxNumOperands = 0;
1707 for (std::vector<InstructionInfo*>::const_iterator it =
1708 Info.Instructions.begin(), ie = Info.Instructions.end();
1709 it != ie; ++it)
1710 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001711
1712
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001713 // Emit the static match table; unused classes get initalized to 0 which is
1714 // guaranteed to be InvalidMatchClass.
1715 //
1716 // FIXME: We can reduce the size of this table very easily. First, we change
1717 // it so that store the kinds in separate bit-fields for each index, which
1718 // only needs to be the max width used for classes at that index (we also need
1719 // to reject based on this during classification). If we then make sure to
1720 // order the match kinds appropriately (putting mnemonics last), then we
1721 // should only end up using a few bits for each class, especially the ones
1722 // following the mnemonic.
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00001723 OS << "namespace {\n";
1724 OS << " struct MatchEntry {\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001725 OS << " unsigned Opcode;\n";
Chris Lattner82d88ce2010-09-06 21:01:37 +00001726 OS << " const char *Mnemonic;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001727 OS << " ConversionKind ConvertFn;\n";
1728 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00001729 OS << " unsigned RequiredFeatures;\n";
Chris Lattner81301972010-09-06 21:22:45 +00001730 OS << " };\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001731
Chris Lattner81301972010-09-06 21:22:45 +00001732 OS << "// Predicate for searching for an opcode.\n";
1733 OS << " struct LessOpcode {\n";
1734 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
1735 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
1736 OS << " }\n";
1737 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
1738 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
1739 OS << " }\n";
Chris Lattner62823362010-09-07 06:10:48 +00001740 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
1741 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
1742 OS << " }\n";
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00001743 OS << " };\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001744
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00001745 OS << "} // end anonymous namespace.\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001746
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00001747 OS << "static const MatchEntry MatchTable["
1748 << Info.Instructions.size() << "] = {\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001749
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001750 for (std::vector<InstructionInfo*>::const_iterator it =
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00001751 Info.Instructions.begin(), ie = Info.Instructions.end();
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001752 it != ie; ++it) {
Daniel Dunbare10787e2009-08-07 08:26:05 +00001753 InstructionInfo &II = **it;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001754
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00001755 OS << " { " << Target.getName() << "::" << II.InstrName
1756 << ", \"" << II.Tokens[0] << "\""
1757 << ", " << II.ConversionFnKind << ", { ";
Daniel Dunbare10787e2009-08-07 08:26:05 +00001758 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1759 InstructionInfo::Operand &Op = II.Operands[i];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001760
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001761 if (i) OS << ", ";
1762 OS << Op.Class->Name;
Daniel Dunbare10787e2009-08-07 08:26:05 +00001763 }
Daniel Dunbareefe8612010-07-19 05:44:09 +00001764 OS << " }, ";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001765
Daniel Dunbareefe8612010-07-19 05:44:09 +00001766 // Write the required features mask.
1767 if (!II.RequiredFeatures.empty()) {
1768 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
1769 if (i) OS << "|";
Chris Lattnera0e87192010-10-30 20:07:57 +00001770 OS << II.RequiredFeatures[i]->getEnumName();
Daniel Dunbareefe8612010-07-19 05:44:09 +00001771 }
1772 } else
1773 OS << "0";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001774
Daniel Dunbareefe8612010-07-19 05:44:09 +00001775 OS << "},\n";
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00001776 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001777
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00001778 OS << "};\n\n";
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00001779
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00001780 // Finally, build the match function.
1781 OS << Target.getName() << ClassName << "::MatchResultTy "
1782 << Target.getName() << ClassName << "::\n"
1783 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
1784 << " &Operands,\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00001785 OS << " MCInst &Inst, unsigned &ErrorInfo) {\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00001786
1787 // Emit code to get the available features.
1788 OS << " // Get the current feature set.\n";
1789 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
1790
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00001791 OS << " // Get the instruction mnemonic, which is the first token.\n";
1792 OS << " StringRef Mnemonic = ((" << Target.getName()
1793 << "Operand*)Operands[0])->getToken();\n\n";
1794
Chris Lattner477fba4f2010-10-30 18:48:18 +00001795 if (HasMnemonicAliases) {
1796 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
1797 OS << " ApplyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
1798 }
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00001799
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001800 // Emit code to compute the class list for this operand vector.
1801 OS << " // Eliminate obvious mismatches.\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00001802 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
1803 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
1804 OS << " return Match_InvalidOperand;\n";
1805 OS << " }\n\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001806
1807 OS << " // Compute the class list for this operand vector.\n";
1808 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
Chris Lattner82d88ce2010-09-06 21:01:37 +00001809 OS << " for (unsigned i = 1, e = Operands.size(); i != e; ++i) {\n";
1810 OS << " Classes[i-1] = ClassifyOperand(Operands[i]);\n\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001811
1812 OS << " // Check for invalid operands before matching.\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00001813 OS << " if (Classes[i-1] == InvalidMatchClass) {\n";
1814 OS << " ErrorInfo = i;\n";
Chris Lattner628fbec2010-09-06 21:54:15 +00001815 OS << " return Match_InvalidOperand;\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00001816 OS << " }\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001817 OS << " }\n\n";
1818
1819 OS << " // Mark unused classes.\n";
Chris Lattner82d88ce2010-09-06 21:01:37 +00001820 OS << " for (unsigned i = Operands.size()-1, e = " << MaxNumOperands << "; "
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001821 << "i != e; ++i)\n";
1822 OS << " Classes[i] = InvalidMatchClass;\n\n";
1823
Chris Lattnerabfe4222010-09-06 23:37:39 +00001824 OS << " // Some state to try to produce better error messages.\n";
Chris Lattner81301972010-09-06 21:22:45 +00001825 OS << " bool HadMatchOtherThanFeatures = false;\n\n";
Chris Lattnerabfe4222010-09-06 23:37:39 +00001826 OS << " // Set ErrorInfo to the operand that mismatches if it is \n";
1827 OS << " // wrong for all instances of the instruction.\n";
1828 OS << " ErrorInfo = ~0U;\n";
Chris Lattner81301972010-09-06 21:22:45 +00001829
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001830 // Emit code to search the table.
1831 OS << " // Search the table.\n";
Chris Lattner81301972010-09-06 21:22:45 +00001832 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
1833 OS << " std::equal_range(MatchTable, MatchTable+"
1834 << Info.Instructions.size() << ", Mnemonic, LessOpcode());\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001835
Chris Lattner628fbec2010-09-06 21:54:15 +00001836 OS << " // Return a more specific error code if no mnemonics match.\n";
1837 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
1838 OS << " return Match_MnemonicFail;\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001839
Chris Lattner81301972010-09-06 21:22:45 +00001840 OS << " for (const MatchEntry *it = MnemonicRange.first, "
Chris Lattner9026ac02010-09-06 21:23:43 +00001841 << "*ie = MnemonicRange.second;\n";
Chris Lattner81301972010-09-06 21:22:45 +00001842 OS << " it != ie; ++it) {\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00001843
Gabor Greif7f3ce252010-09-07 06:06:06 +00001844 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Chris Lattnerc4521d12010-09-06 21:25:43 +00001845 OS << " assert(Mnemonic == it->Mnemonic);\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001846
Daniel Dunbareefe8612010-07-19 05:44:09 +00001847 // Emit check that the subclasses match.
Chris Lattner339cc7b2010-09-06 22:11:18 +00001848 OS << " bool OperandsValid = true;\n";
1849 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
1850 OS << " if (IsSubclass(Classes[i], it->Classes[i]))\n";
1851 OS << " continue;\n";
Chris Lattnerabfe4222010-09-06 23:37:39 +00001852 OS << " // If this operand is broken for all of the instances of this\n";
1853 OS << " // mnemonic, keep track of it so we can report loc info.\n";
1854 OS << " if (it == MnemonicRange.first || ErrorInfo == i+1)\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00001855 OS << " ErrorInfo = i+1;\n";
Chris Lattnerabfe4222010-09-06 23:37:39 +00001856 OS << " else\n";
1857 OS << " ErrorInfo = ~0U;";
Chris Lattner339cc7b2010-09-06 22:11:18 +00001858 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
1859 OS << " OperandsValid = false;\n";
1860 OS << " break;\n";
1861 OS << " }\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001862
Chris Lattner339cc7b2010-09-06 22:11:18 +00001863 OS << " if (!OperandsValid) continue;\n";
Chris Lattnerb4be28f2010-09-06 20:08:02 +00001864
1865 // Emit check that the required features are available.
1866 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
1867 << "!= it->RequiredFeatures) {\n";
1868 OS << " HadMatchOtherThanFeatures = true;\n";
1869 OS << " continue;\n";
1870 OS << " }\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001871
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001872 OS << "\n";
Daniel Dunbar451a4352010-03-18 20:05:56 +00001873 OS << " ConvertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
1874
1875 // Call the post-processing function, if used.
1876 std::string InsnCleanupFn =
1877 AsmParser->getValueAsString("AsmParserInstCleanup");
1878 if (!InsnCleanupFn.empty())
1879 OS << " " << InsnCleanupFn << "(Inst);\n";
1880
Chris Lattnera22a3682010-09-06 19:22:17 +00001881 OS << " return Match_Success;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001882 OS << " }\n\n";
1883
Chris Lattnerb4be28f2010-09-06 20:08:02 +00001884 OS << " // Okay, we had no match. Try to return a useful error code.\n";
1885 OS << " if (HadMatchOtherThanFeatures) return Match_MissingFeature;\n";
Chris Lattner628fbec2010-09-06 21:54:15 +00001886 OS << " return Match_InvalidOperand;\n";
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00001887 OS << "}\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001888
Chris Lattner3e4582a2010-09-06 19:11:01 +00001889 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbar3085b572009-07-11 19:39:44 +00001890}