blob: d539b1d0cf5ff84e2a328cd38195544e76285263 [file] [log] [blame]
Daniel Dunbard51ffcf2009-07-11 19:39:44 +00001//===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a target specifier matcher for converting parsed
11// assembly operands in the MCInst structures.
12//
Daniel Dunbar20927f22009-08-07 08:26:05 +000013// The input to the target specific matcher is a list of literal tokens and
14// operands. The target specific parser should generally eliminate any syntax
15// which is not relevant for matching; for example, comma tokens should have
16// already been consumed and eliminated by the parser. Most instructions will
17// end up with a single literal token (the instruction name) and some number of
18// operands.
19//
20// Some example inputs, for X86:
21// 'addl' (immediate ...) (register ...)
22// 'add' (immediate ...) (memory ...)
Jim Grosbacha7c78222010-10-29 22:13:48 +000023// 'call' '*' %epc
Daniel Dunbar20927f22009-08-07 08:26:05 +000024//
25// The assembly matcher is responsible for converting this input into a precise
26// machine instruction (i.e., an instruction with a well defined encoding). This
27// mapping has several properties which complicate matching:
28//
29// - It may be ambiguous; many architectures can legally encode particular
30// variants of an instruction in different ways (for example, using a smaller
31// encoding for small immediates). Such ambiguities should never be
32// arbitrarily resolved by the assembler, the assembler is always responsible
33// for choosing the "best" available instruction.
34//
35// - It may depend on the subtarget or the assembler context. Instructions
36// which are invalid for the current mode, but otherwise unambiguous (e.g.,
37// an SSE instruction in a file being assembled for i486) should be accepted
38// and rejected by the assembler front end. However, if the proper encoding
39// for an instruction is dependent on the assembler context then the matcher
40// is responsible for selecting the correct machine instruction for the
41// current mode.
42//
43// The core matching algorithm attempts to exploit the regularity in most
44// instruction sets to quickly determine the set of possibly matching
45// instructions, and the simplify the generated code. Additionally, this helps
46// to ensure that the ambiguities are intentionally resolved by the user.
47//
48// The matching is divided into two distinct phases:
49//
50// 1. Classification: Each operand is mapped to the unique set which (a)
51// contains it, and (b) is the largest such subset for which a single
52// instruction could match all members.
53//
54// For register classes, we can generate these subgroups automatically. For
55// arbitrary operands, we expect the user to define the classes and their
56// relations to one another (for example, 8-bit signed immediates as a
57// subset of 32-bit immediates).
58//
59// By partitioning the operands in this way, we guarantee that for any
60// tuple of classes, any single instruction must match either all or none
61// of the sets of operands which could classify to that tuple.
62//
63// In addition, the subset relation amongst classes induces a partial order
64// on such tuples, which we use to resolve ambiguities.
65//
66// FIXME: What do we do if a crazy case shows up where this is the wrong
67// resolution?
68//
69// 2. The input can now be treated as a tuple of classes (static tokens are
70// simple singleton sets). Each such tuple should generally map to a single
71// instruction (we currently ignore cases where this isn't true, whee!!!),
72// which we can emit a simple matcher for.
73//
Daniel Dunbard51ffcf2009-07-11 19:39:44 +000074//===----------------------------------------------------------------------===//
75
76#include "AsmMatcherEmitter.h"
77#include "CodeGenTarget.h"
78#include "Record.h"
Chris Lattner5845e5c2010-09-06 02:01:51 +000079#include "StringMatcher.h"
Daniel Dunbar20927f22009-08-07 08:26:05 +000080#include "llvm/ADT/OwningPtr.h"
Daniel Dunbara027d222009-07-31 02:32:59 +000081#include "llvm/ADT/SmallVector.h"
Daniel Dunbar606e8ad2009-08-09 04:00:06 +000082#include "llvm/ADT/STLExtras.h"
Daniel Dunbar20927f22009-08-07 08:26:05 +000083#include "llvm/ADT/StringExtras.h"
84#include "llvm/Support/CommandLine.h"
Daniel Dunbara027d222009-07-31 02:32:59 +000085#include "llvm/Support/Debug.h"
Daniel Dunbara027d222009-07-31 02:32:59 +000086#include <list>
Daniel Dunbarb7479c02009-08-08 05:24:34 +000087#include <map>
88#include <set>
Daniel Dunbard51ffcf2009-07-11 19:39:44 +000089using namespace llvm;
90
Daniel Dunbar27249152009-08-07 20:33:39 +000091static cl::opt<std::string>
Daniel Dunbar606e8ad2009-08-09 04:00:06 +000092MatchPrefix("match-prefix", cl::init(""),
93 cl::desc("Only match instructions with the given prefix"));
Daniel Dunbar20927f22009-08-07 08:26:05 +000094
Daniel Dunbara027d222009-07-31 02:32:59 +000095/// TokenizeAsmString - Tokenize a simplified assembly string.
Jim Grosbacha7c78222010-10-29 22:13:48 +000096static void TokenizeAsmString(StringRef AsmString,
Daniel Dunbara027d222009-07-31 02:32:59 +000097 SmallVectorImpl<StringRef> &Tokens) {
98 unsigned Prev = 0;
99 bool InTok = true;
100 for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {
101 switch (AsmString[i]) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000102 case '[':
103 case ']':
Daniel Dunbara027d222009-07-31 02:32:59 +0000104 case '*':
105 case '!':
106 case ' ':
107 case '\t':
108 case ',':
109 if (InTok) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000110 Tokens.push_back(AsmString.slice(Prev, i));
Daniel Dunbara027d222009-07-31 02:32:59 +0000111 InTok = false;
112 }
Daniel Dunbar20927f22009-08-07 08:26:05 +0000113 if (!isspace(AsmString[i]) && AsmString[i] != ',')
114 Tokens.push_back(AsmString.substr(i, 1));
Daniel Dunbara027d222009-07-31 02:32:59 +0000115 Prev = i + 1;
116 break;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000117
Daniel Dunbar20927f22009-08-07 08:26:05 +0000118 case '\\':
119 if (InTok) {
120 Tokens.push_back(AsmString.slice(Prev, i));
121 InTok = false;
122 }
123 ++i;
124 assert(i != AsmString.size() && "Invalid quoted character");
125 Tokens.push_back(AsmString.substr(i, 1));
126 Prev = i + 1;
127 break;
128
129 case '$': {
130 // If this isn't "${", treat like a normal token.
131 if (i + 1 == AsmString.size() || AsmString[i + 1] != '{') {
132 if (InTok) {
133 Tokens.push_back(AsmString.slice(Prev, i));
134 InTok = false;
135 }
136 Prev = i;
137 break;
138 }
139
140 if (InTok) {
141 Tokens.push_back(AsmString.slice(Prev, i));
142 InTok = false;
143 }
144
145 StringRef::iterator End =
146 std::find(AsmString.begin() + i, AsmString.end(), '}');
147 assert(End != AsmString.end() && "Missing brace in operand reference!");
148 size_t EndPos = End - AsmString.begin();
149 Tokens.push_back(AsmString.slice(i, EndPos+1));
150 Prev = EndPos + 1;
151 i = EndPos;
152 break;
153 }
Daniel Dunbara027d222009-07-31 02:32:59 +0000154
Daniel Dunbar4d39b672010-08-11 06:36:59 +0000155 case '.':
156 if (InTok) {
157 Tokens.push_back(AsmString.slice(Prev, i));
158 }
159 Prev = i;
160 InTok = true;
161 break;
162
Daniel Dunbara027d222009-07-31 02:32:59 +0000163 default:
164 InTok = true;
165 }
166 }
167 if (InTok && Prev != AsmString.size())
Daniel Dunbar20927f22009-08-07 08:26:05 +0000168 Tokens.push_back(AsmString.substr(Prev));
169}
170
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000171static bool IsAssemblerInstruction(StringRef Name,
Jim Grosbacha7c78222010-10-29 22:13:48 +0000172 const CodeGenInstruction &CGI,
Daniel Dunbar20927f22009-08-07 08:26:05 +0000173 const SmallVectorImpl<StringRef> &Tokens) {
Daniel Dunbar7417b762009-08-11 22:17:52 +0000174 // Ignore "codegen only" instructions.
175 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
176 return false;
177
Daniel Dunbar72fa87f2009-08-09 08:19:00 +0000178 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
179 //
180 // FIXME: This is a total hack.
181 if (StringRef(Name).startswith("Int_") || StringRef(Name).endswith("_Int"))
182 return false;
183
Chris Lattner4d1189f2010-11-01 00:46:16 +0000184 // Reject instructions with no .s string.
Chris Lattnera4a3a5e2010-10-31 19:15:18 +0000185 if (CGI.AsmString.empty()) {
186 PrintError(CGI.TheDef->getLoc(),
187 "instruction with empty asm string");
188 throw std::string("ERROR: Invalid instruction for asm matcher");
189 }
Daniel Dunbar20927f22009-08-07 08:26:05 +0000190
Chris Lattner4d1189f2010-11-01 00:46:16 +0000191 // Reject any instructions with a newline in them, they should be marked
192 // isCodeGenOnly if they are pseudo instructions.
193 if (CGI.AsmString.find('\n') != std::string::npos) {
194 PrintError(CGI.TheDef->getLoc(),
195 "multiline instruction is not valid for the asmparser, "
196 "mark it isCodeGenOnly");
197 throw std::string("ERROR: Invalid instruction");
198 }
Jim Grosbacha7c78222010-10-29 22:13:48 +0000199
Chris Lattnera4a3a5e2010-10-31 19:15:18 +0000200 // Reject instructions with attributes, these aren't something we can handle,
201 // the target should be refactored to use operands instead of modifiers.
Daniel Dunbar20927f22009-08-07 08:26:05 +0000202 //
Daniel Dunbar7417b762009-08-11 22:17:52 +0000203 // Also, check for instructions which reference the operand multiple times;
204 // this implies a constraint we would not honor.
Daniel Dunbar20927f22009-08-07 08:26:05 +0000205 std::set<std::string> OperandNames;
206 for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {
Chris Lattner8b2f0822010-10-31 19:05:32 +0000207 if (Tokens[i][0] == '$' &&
Chris Lattner39ee0362010-10-31 19:10:56 +0000208 Tokens[i].find(':') != StringRef::npos) {
209 PrintError(CGI.TheDef->getLoc(),
210 "instruction with operand modifier '" + Tokens[i].str() +
211 "' not supported by asm matcher. Mark isCodeGenOnly!");
212 throw std::string("ERROR: Invalid instruction");
Chris Lattner8b2f0822010-10-31 19:05:32 +0000213 }
Chris Lattner39ee0362010-10-31 19:10:56 +0000214
Chris Lattner52de0ef2010-11-01 00:51:32 +0000215 // FIXME: Should reject these. The ARM backend hits this with $lane in a
216 // bunch of instructions. It is unclear what the right answer is for this.
Chris Lattner8b2f0822010-10-31 19:05:32 +0000217 if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) {
218 DEBUG({
Chris Lattner39ee0362010-10-31 19:10:56 +0000219 errs() << "warning: '" << Name << "': "
220 << "ignoring instruction with tied operand '"
221 << Tokens[i].str() << "'\n";
222 });
Chris Lattner8b2f0822010-10-31 19:05:32 +0000223 return false;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000224 }
225 }
Chris Lattner39ee0362010-10-31 19:10:56 +0000226
Daniel Dunbar20927f22009-08-07 08:26:05 +0000227 return true;
228}
229
230namespace {
Chris Lattner02bcbc92010-11-01 01:37:30 +0000231 class AsmMatcherInfo;
Daniel Dunbar54074b52010-07-19 05:44:09 +0000232struct SubtargetFeatureInfo;
233
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000234/// ClassInfo - Helper class for storing the information about a particular
235/// class of operands which can be matched.
236struct ClassInfo {
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000237 enum ClassInfoKind {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000238 /// Invalid kind, for use as a sentinel value.
239 Invalid = 0,
240
241 /// The class for a particular token.
242 Token,
243
244 /// The (first) register class, subsequent register classes are
245 /// RegisterClass0+1, and so on.
246 RegisterClass0,
247
248 /// The (first) user defined class, subsequent user defined classes are
249 /// UserClass0+1, and so on.
250 UserClass0 = 1<<16
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000251 };
252
253 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
254 /// N) for the Nth user defined class.
255 unsigned Kind;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000256
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000257 /// SuperClasses - The super classes of this class. Note that for simplicities
258 /// sake user operands only record their immediate super class, while register
259 /// operands include all superclasses.
260 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000261
Daniel Dunbar6745d422009-08-09 05:18:30 +0000262 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000263 std::string Name;
264
Daniel Dunbar6745d422009-08-09 05:18:30 +0000265 /// ClassName - The unadorned generic name for this class (e.g., Token).
266 std::string ClassName;
267
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000268 /// ValueName - The name of the value this class represents; for a token this
269 /// is the literal token string, for an operand it is the TableGen class (or
270 /// empty if this is a derived class).
271 std::string ValueName;
272
273 /// PredicateMethod - The name of the operand method to test whether the
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000274 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000275 std::string PredicateMethod;
276
277 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000278 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000279 std::string RenderMethod;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000280
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000281 /// For register classes, the records for all the registers in this class.
282 std::set<Record*> Registers;
283
284public:
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000285 /// isRegisterClass() - Check if this is a register class.
286 bool isRegisterClass() const {
287 return Kind >= RegisterClass0 && Kind < UserClass0;
288 }
289
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000290 /// isUserClass() - Check if this is a user defined class.
291 bool isUserClass() const {
292 return Kind >= UserClass0;
293 }
294
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000295 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
296 /// are related if they are in the same class hierarchy.
297 bool isRelatedTo(const ClassInfo &RHS) const {
298 // Tokens are only related to tokens.
299 if (Kind == Token || RHS.Kind == Token)
300 return Kind == Token && RHS.Kind == Token;
301
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000302 // Registers classes are only related to registers classes, and only if
303 // their intersection is non-empty.
304 if (isRegisterClass() || RHS.isRegisterClass()) {
305 if (!isRegisterClass() || !RHS.isRegisterClass())
306 return false;
307
308 std::set<Record*> Tmp;
309 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
Jim Grosbacha7c78222010-10-29 22:13:48 +0000310 std::set_intersection(Registers.begin(), Registers.end(),
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000311 RHS.Registers.begin(), RHS.Registers.end(),
312 II);
313
314 return !Tmp.empty();
315 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000316
317 // Otherwise we have two users operands; they are related if they are in the
318 // same class hierarchy.
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000319 //
320 // FIXME: This is an oversimplification, they should only be related if they
321 // intersect, however we don't have that information.
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000322 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
323 const ClassInfo *Root = this;
324 while (!Root->SuperClasses.empty())
325 Root = Root->SuperClasses.front();
326
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000327 const ClassInfo *RHSRoot = &RHS;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000328 while (!RHSRoot->SuperClasses.empty())
329 RHSRoot = RHSRoot->SuperClasses.front();
Jim Grosbacha7c78222010-10-29 22:13:48 +0000330
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000331 return Root == RHSRoot;
332 }
333
Jim Grosbacha7c78222010-10-29 22:13:48 +0000334 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000335 bool isSubsetOf(const ClassInfo &RHS) const {
336 // This is a subset of RHS if it is the same class...
337 if (this == &RHS)
338 return true;
339
340 // ... or if any of its super classes are a subset of RHS.
341 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
342 ie = SuperClasses.end(); it != ie; ++it)
343 if ((*it)->isSubsetOf(RHS))
344 return true;
345
346 return false;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000347 }
348
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000349 /// operator< - Compare two classes.
350 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar368a4562010-05-27 05:31:32 +0000351 if (this == &RHS)
352 return false;
353
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000354 // Unrelated classes can be ordered by kind.
355 if (!isRelatedTo(RHS))
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000356 return Kind < RHS.Kind;
357
358 switch (Kind) {
Daniel Dunbar6745d422009-08-09 05:18:30 +0000359 case Invalid:
360 assert(0 && "Invalid kind!");
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000361 case Token:
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000362 // Tokens are comparable by value.
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000363 //
364 // FIXME: Compare by enum value.
365 return ValueName < RHS.ValueName;
366
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000367 default:
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000368 // This class preceeds the RHS if it is a proper subset of the RHS.
Daniel Dunbar368a4562010-05-27 05:31:32 +0000369 if (isSubsetOf(RHS))
Duncan Sands34727662010-07-12 08:16:59 +0000370 return true;
Daniel Dunbar368a4562010-05-27 05:31:32 +0000371 if (RHS.isSubsetOf(*this))
Duncan Sands34727662010-07-12 08:16:59 +0000372 return false;
Daniel Dunbar368a4562010-05-27 05:31:32 +0000373
374 // Otherwise, order by name to ensure we have a total ordering.
375 return ValueName < RHS.ValueName;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000376 }
377 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000378};
379
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000380/// InstructionInfo - Helper class for storing the necessary information for an
381/// instruction which is capable of being matched.
Daniel Dunbar20927f22009-08-07 08:26:05 +0000382struct InstructionInfo {
383 struct Operand {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000384 /// The unique class instance this operand should match.
385 ClassInfo *Class;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000386
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000387 /// The original operand this corresponds to, if any.
Benjamin Kramerfa1165a2009-08-08 10:06:30 +0000388 const CodeGenInstruction::OperandInfo *OperandInfo;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000389 };
390
391 /// InstrName - The target name for this instruction.
392 std::string InstrName;
393
394 /// Instr - The instruction this matches.
395 const CodeGenInstruction *Instr;
396
397 /// AsmString - The assembly string for this instruction (with variants
398 /// removed).
399 std::string AsmString;
400
401 /// Tokens - The tokenized assembly pattern that this instruction matches.
402 SmallVector<StringRef, 4> Tokens;
403
404 /// Operands - The operands that this instruction matches.
405 SmallVector<Operand, 4> Operands;
406
Daniel Dunbar54074b52010-07-19 05:44:09 +0000407 /// Predicates - The required subtarget features to match this instruction.
408 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
409
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000410 /// ConversionFnKind - The enum value which is passed to the generated
411 /// ConvertToMCInst to convert parsed operands into an MCInst for this
412 /// function.
413 std::string ConversionFnKind;
Chris Lattner02bcbc92010-11-01 01:37:30 +0000414
415 /// getSingletonRegisterForToken - If the specified token is a singleton
416 /// register, return the register name, otherwise return a null StringRef.
417 StringRef getSingletonRegisterForToken(unsigned i,
418 const AsmMatcherInfo &Info) const;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000419
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000420 /// operator< - Compare two instructions.
421 bool operator<(const InstructionInfo &RHS) const {
Chris Lattnere206fcf2010-09-06 21:01:37 +0000422 // The primary comparator is the instruction mnemonic.
423 if (Tokens[0] != RHS.Tokens[0])
424 return Tokens[0] < RHS.Tokens[0];
Jim Grosbacha7c78222010-10-29 22:13:48 +0000425
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000426 if (Operands.size() != RHS.Operands.size())
427 return Operands.size() < RHS.Operands.size();
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000428
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000429 // Compare lexicographically by operand. The matcher validates that other
430 // orderings wouldn't be ambiguous using \see CouldMatchAmiguouslyWith().
431 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000432 if (*Operands[i].Class < *RHS.Operands[i].Class)
433 return true;
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000434 if (*RHS.Operands[i].Class < *Operands[i].Class)
435 return false;
436 }
437
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000438 return false;
439 }
440
Daniel Dunbar2b544812009-08-09 06:05:33 +0000441 /// CouldMatchAmiguouslyWith - Check whether this instruction could
442 /// ambiguously match the same set of operands as \arg RHS (without being a
443 /// strictly superior match).
444 bool CouldMatchAmiguouslyWith(const InstructionInfo &RHS) {
445 // The number of operands is unambiguous.
446 if (Operands.size() != RHS.Operands.size())
447 return false;
448
Daniel Dunbar1402f0b2010-01-23 00:26:16 +0000449 // Otherwise, make sure the ordering of the two instructions is unambiguous
450 // by checking that either (a) a token or operand kind discriminates them,
451 // or (b) the ordering among equivalent kinds is consistent.
452
Daniel Dunbar2b544812009-08-09 06:05:33 +0000453 // Tokens and operand kinds are unambiguous (assuming a correct target
454 // specific parser).
455 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
456 if (Operands[i].Class->Kind != RHS.Operands[i].Class->Kind ||
457 Operands[i].Class->Kind == ClassInfo::Token)
458 if (*Operands[i].Class < *RHS.Operands[i].Class ||
459 *RHS.Operands[i].Class < *Operands[i].Class)
460 return false;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000461
Daniel Dunbar2b544812009-08-09 06:05:33 +0000462 // Otherwise, this operand could commute if all operands are equivalent, or
463 // there is a pair of operands that compare less than and a pair that
464 // compare greater than.
465 bool HasLT = false, HasGT = false;
466 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
467 if (*Operands[i].Class < *RHS.Operands[i].Class)
468 HasLT = true;
469 if (*RHS.Operands[i].Class < *Operands[i].Class)
470 HasGT = true;
471 }
472
473 return !(HasLT ^ HasGT);
474 }
475
Daniel Dunbar20927f22009-08-07 08:26:05 +0000476 void dump();
477};
478
Daniel Dunbar54074b52010-07-19 05:44:09 +0000479/// SubtargetFeatureInfo - Helper class for storing information on a subtarget
480/// feature which participates in instruction matching.
481struct SubtargetFeatureInfo {
482 /// \brief The predicate record for this feature.
483 Record *TheDef;
484
485 /// \brief An unique index assigned to represent this feature.
486 unsigned Index;
487
Chris Lattner0aed1e72010-10-30 20:07:57 +0000488 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
489
Daniel Dunbar54074b52010-07-19 05:44:09 +0000490 /// \brief The name of the enumerated constant identifying this feature.
Chris Lattner0aed1e72010-10-30 20:07:57 +0000491 std::string getEnumName() const {
492 return "Feature_" + TheDef->getName();
493 }
Daniel Dunbar54074b52010-07-19 05:44:09 +0000494};
495
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000496class AsmMatcherInfo {
497public:
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000498 /// The tablegen AsmParser record.
499 Record *AsmParser;
500
Chris Lattner02bcbc92010-11-01 01:37:30 +0000501 /// Target - The target information.
502 CodeGenTarget &Target;
503
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000504 /// The AsmParser "CommentDelimiter" value.
505 std::string CommentDelimiter;
506
507 /// The AsmParser "RegisterPrefix" value.
508 std::string RegisterPrefix;
509
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000510 /// The classes which are needed for matching.
511 std::vector<ClassInfo*> Classes;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000512
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000513 /// The information on the instruction to match.
514 std::vector<InstructionInfo*> Instructions;
515
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000516 /// Map of Register records to their class information.
517 std::map<Record*, ClassInfo*> RegisterClasses;
518
Daniel Dunbar54074b52010-07-19 05:44:09 +0000519 /// Map of Predicate records to their subtarget information.
520 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
Chris Lattner6fa152c2010-10-30 20:15:02 +0000521
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000522private:
523 /// Map of token to class information which has already been constructed.
524 std::map<std::string, ClassInfo*> TokenClasses;
525
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000526 /// Map of RegisterClass records to their class information.
527 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000528
Daniel Dunbar338825c2009-08-10 18:41:10 +0000529 /// Map of AsmOperandClass records to their class information.
530 std::map<Record*, ClassInfo*> AsmOperandClasses;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000531
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000532private:
533 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000534 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000535
536 /// getOperandClass - Lookup or create the class for the given operand.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000537 ClassInfo *getOperandClass(StringRef Token,
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000538 const CodeGenInstruction::OperandInfo &OI);
539
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000540 /// BuildRegisterClasses - Build the ClassInfo* instances for register
541 /// classes.
Chris Lattner02bcbc92010-11-01 01:37:30 +0000542 void BuildRegisterClasses(std::set<std::string> &SingletonRegisterNames);
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000543
544 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
545 /// operand classes.
Chris Lattner02bcbc92010-11-01 01:37:30 +0000546 void BuildOperandClasses();
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000547
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000548public:
Chris Lattner02bcbc92010-11-01 01:37:30 +0000549 AsmMatcherInfo(Record *AsmParser, CodeGenTarget &Target);
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000550
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000551 /// BuildInfo - Construct the various tables used during matching.
Chris Lattner02bcbc92010-11-01 01:37:30 +0000552 void BuildInfo();
Chris Lattner6fa152c2010-10-30 20:15:02 +0000553
554 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
555 /// given operand.
556 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
557 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
558 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
559 SubtargetFeatures.find(Def);
560 return I == SubtargetFeatures.end() ? 0 : I->second;
561 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000562};
563
Daniel Dunbar20927f22009-08-07 08:26:05 +0000564}
565
566void InstructionInfo::dump() {
567 errs() << InstrName << " -- " << "flattened:\"" << AsmString << '\"'
568 << ", tokens:[";
569 for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {
570 errs() << Tokens[i];
571 if (i + 1 != e)
572 errs() << ", ";
573 }
574 errs() << "]\n";
575
576 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
577 Operand &Op = Operands[i];
Daniel Dunbar6745d422009-08-09 05:18:30 +0000578 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000579 if (Op.Class->Kind == ClassInfo::Token) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000580 errs() << '\"' << Tokens[i] << "\"\n";
581 continue;
582 }
583
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000584 if (!Op.OperandInfo) {
585 errs() << "(singleton register)\n";
586 continue;
587 }
588
Benjamin Kramerfa1165a2009-08-08 10:06:30 +0000589 const CodeGenInstruction::OperandInfo &OI = *Op.OperandInfo;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000590 errs() << OI.Name << " " << OI.Rec->getName()
591 << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n";
592 }
593}
594
Chris Lattner02bcbc92010-11-01 01:37:30 +0000595/// getRegisterRecord - Get the register record for \arg name, or 0.
596static Record *getRegisterRecord(CodeGenTarget &Target, StringRef Name) {
597 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
598 const CodeGenRegister &Reg = Target.getRegisters()[i];
599 if (Name == Reg.TheDef->getValueAsString("AsmName"))
600 return Reg.TheDef;
601 }
602
603 return 0;
604}
605
606/// getSingletonRegisterForToken - If the specified token is a singleton
607/// register, return the register name, otherwise return a null StringRef.
608StringRef InstructionInfo::
609getSingletonRegisterForToken(unsigned i, const AsmMatcherInfo &Info) const {
610 StringRef Tok = Tokens[i];
611 if (!Tok.startswith(Info.RegisterPrefix))
612 return StringRef();
613
614 StringRef RegName = Tok.substr(Info.RegisterPrefix.size());
615 Record *Rec = getRegisterRecord(Info.Target, RegName);
616
617 if (!Rec) {
618 // If there is no register prefix (i.e. "%" in "%eax"), then this may
619 // be some random non-register token, just ignore it.
620 if (Info.RegisterPrefix.empty())
621 return StringRef();
622
623 std::string Err = "unable to find register for '" + RegName.str() +
624 "' (which matches register prefix)";
625 throw TGError(Instr->TheDef->getLoc(), Err);
626 }
627
628 return RegName;
629}
630
631
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000632static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000633 std::string Res;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000634
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000635 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
636 switch (*it) {
637 case '*': Res += "_STAR_"; break;
638 case '%': Res += "_PCT_"; break;
639 case ':': Res += "_COLON_"; break;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000640 default:
Chris Lattner39ee0362010-10-31 19:10:56 +0000641 if (isalnum(*it))
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000642 Res += *it;
Chris Lattner39ee0362010-10-31 19:10:56 +0000643 else
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000644 Res += "_" + utostr((unsigned) *it) + "_";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000645 }
646 }
647
648 return Res;
649}
650
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000651ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000652 ClassInfo *&Entry = TokenClasses[Token];
Jim Grosbacha7c78222010-10-29 22:13:48 +0000653
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000654 if (!Entry) {
655 Entry = new ClassInfo();
656 Entry->Kind = ClassInfo::Token;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000657 Entry->ClassName = "Token";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000658 Entry->Name = "MCK_" + getEnumNameForToken(Token);
659 Entry->ValueName = Token;
660 Entry->PredicateMethod = "<invalid>";
661 Entry->RenderMethod = "<invalid>";
662 Classes.push_back(Entry);
663 }
664
665 return Entry;
666}
667
668ClassInfo *
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000669AsmMatcherInfo::getOperandClass(StringRef Token,
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000670 const CodeGenInstruction::OperandInfo &OI) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000671 if (OI.Rec->isSubClassOf("RegisterClass")) {
672 ClassInfo *CI = RegisterClassClasses[OI.Rec];
673
674 if (!CI) {
675 PrintError(OI.Rec->getLoc(), "register class has no class info!");
676 throw std::string("ERROR: Missing register class!");
677 }
678
679 return CI;
680 }
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000681
Daniel Dunbar338825c2009-08-10 18:41:10 +0000682 assert(OI.Rec->isSubClassOf("Operand") && "Unexpected operand!");
683 Record *MatchClass = OI.Rec->getValueAsDef("ParserMatchClass");
684 ClassInfo *CI = AsmOperandClasses[MatchClass];
685
686 if (!CI) {
687 PrintError(OI.Rec->getLoc(), "operand has no match class!");
688 throw std::string("ERROR: Missing match class!");
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000689 }
690
Daniel Dunbar338825c2009-08-10 18:41:10 +0000691 return CI;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000692}
693
Chris Lattner02bcbc92010-11-01 01:37:30 +0000694void AsmMatcherInfo::BuildRegisterClasses(std::set<std::string>
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000695 &SingletonRegisterNames) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000696 std::vector<CodeGenRegisterClass> RegisterClasses;
697 std::vector<CodeGenRegister> Registers;
Daniel Dunbar338825c2009-08-10 18:41:10 +0000698
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000699 RegisterClasses = Target.getRegisterClasses();
700 Registers = Target.getRegisters();
Daniel Dunbar338825c2009-08-10 18:41:10 +0000701
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000702 // The register sets used for matching.
703 std::set< std::set<Record*> > RegisterSets;
704
Jim Grosbacha7c78222010-10-29 22:13:48 +0000705 // Gather the defined sets.
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000706 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
707 ie = RegisterClasses.end(); it != ie; ++it)
708 RegisterSets.insert(std::set<Record*>(it->Elements.begin(),
709 it->Elements.end()));
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000710
711 // Add any required singleton sets.
712 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
713 ie = SingletonRegisterNames.end(); it != ie; ++it)
714 if (Record *Rec = getRegisterRecord(Target, *it))
715 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
Jim Grosbacha7c78222010-10-29 22:13:48 +0000716
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000717 // Introduce derived sets where necessary (when a register does not determine
718 // a unique register set class), and build the mapping of registers to the set
719 // they should classify to.
720 std::map<Record*, std::set<Record*> > RegisterMap;
721 for (std::vector<CodeGenRegister>::iterator it = Registers.begin(),
722 ie = Registers.end(); it != ie; ++it) {
723 CodeGenRegister &CGR = *it;
724 // Compute the intersection of all sets containing this register.
725 std::set<Record*> ContainingSet;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000726
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000727 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
728 ie = RegisterSets.end(); it != ie; ++it) {
729 if (!it->count(CGR.TheDef))
730 continue;
731
732 if (ContainingSet.empty()) {
733 ContainingSet = *it;
734 } else {
735 std::set<Record*> Tmp;
736 std::swap(Tmp, ContainingSet);
737 std::insert_iterator< std::set<Record*> > II(ContainingSet,
738 ContainingSet.begin());
739 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(),
740 II);
741 }
742 }
743
744 if (!ContainingSet.empty()) {
745 RegisterSets.insert(ContainingSet);
746 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
747 }
748 }
749
750 // Construct the register classes.
751 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
752 unsigned Index = 0;
753 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
754 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
755 ClassInfo *CI = new ClassInfo();
756 CI->Kind = ClassInfo::RegisterClass0 + Index;
757 CI->ClassName = "Reg" + utostr(Index);
758 CI->Name = "MCK_Reg" + utostr(Index);
759 CI->ValueName = "";
760 CI->PredicateMethod = ""; // unused
761 CI->RenderMethod = "addRegOperands";
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000762 CI->Registers = *it;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000763 Classes.push_back(CI);
764 RegisterSetClasses.insert(std::make_pair(*it, CI));
765 }
766
767 // Find the superclasses; we could compute only the subgroup lattice edges,
768 // but there isn't really a point.
769 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
770 ie = RegisterSets.end(); it != ie; ++it) {
771 ClassInfo *CI = RegisterSetClasses[*it];
772 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
773 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
Jim Grosbacha7c78222010-10-29 22:13:48 +0000774 if (*it != *it2 &&
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000775 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
776 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
777 }
778
779 // Name the register classes which correspond to a user defined RegisterClass.
780 for (std::vector<CodeGenRegisterClass>::iterator it = RegisterClasses.begin(),
781 ie = RegisterClasses.end(); it != ie; ++it) {
782 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(it->Elements.begin(),
783 it->Elements.end())];
784 if (CI->ValueName.empty()) {
785 CI->ClassName = it->getName();
786 CI->Name = "MCK_" + it->getName();
787 CI->ValueName = it->getName();
788 } else
789 CI->ValueName = CI->ValueName + "," + it->getName();
790
791 RegisterClassClasses.insert(std::make_pair(it->TheDef, CI));
792 }
793
794 // Populate the map for individual registers.
795 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
796 ie = RegisterMap.end(); it != ie; ++it)
797 this->RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000798
799 // Name the register classes which correspond to singleton registers.
800 for (std::set<std::string>::iterator it = SingletonRegisterNames.begin(),
801 ie = SingletonRegisterNames.end(); it != ie; ++it) {
802 if (Record *Rec = getRegisterRecord(Target, *it)) {
803 ClassInfo *CI = this->RegisterClasses[Rec];
804 assert(CI && "Missing singleton register class info!");
805
806 if (CI->ValueName.empty()) {
807 CI->ClassName = Rec->getName();
808 CI->Name = "MCK_" + Rec->getName();
809 CI->ValueName = Rec->getName();
810 } else
811 CI->ValueName = CI->ValueName + "," + Rec->getName();
812 }
813 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000814}
815
Chris Lattner02bcbc92010-11-01 01:37:30 +0000816void AsmMatcherInfo::BuildOperandClasses() {
Daniel Dunbar338825c2009-08-10 18:41:10 +0000817 std::vector<Record*> AsmOperands;
818 AsmOperands = Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbara2f5e002010-01-30 01:02:37 +0000819
820 // Pre-populate AsmOperandClasses map.
Jim Grosbacha7c78222010-10-29 22:13:48 +0000821 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbara2f5e002010-01-30 01:02:37 +0000822 ie = AsmOperands.end(); it != ie; ++it)
823 AsmOperandClasses[*it] = new ClassInfo();
824
Daniel Dunbar338825c2009-08-10 18:41:10 +0000825 unsigned Index = 0;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000826 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbar338825c2009-08-10 18:41:10 +0000827 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
Daniel Dunbara2f5e002010-01-30 01:02:37 +0000828 ClassInfo *CI = AsmOperandClasses[*it];
Daniel Dunbar338825c2009-08-10 18:41:10 +0000829 CI->Kind = ClassInfo::UserClass0 + Index;
830
Daniel Dunbar54ddf3d2010-05-22 21:02:29 +0000831 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
832 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
833 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
834 if (!DI) {
835 PrintError((*it)->getLoc(), "Invalid super class reference!");
836 continue;
837 }
838
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000839 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
840 if (!SC)
Daniel Dunbar338825c2009-08-10 18:41:10 +0000841 PrintError((*it)->getLoc(), "Invalid super class reference!");
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000842 else
843 CI->SuperClasses.push_back(SC);
Daniel Dunbar338825c2009-08-10 18:41:10 +0000844 }
845 CI->ClassName = (*it)->getValueAsString("Name");
846 CI->Name = "MCK_" + CI->ClassName;
847 CI->ValueName = (*it)->getName();
Daniel Dunbar5c468e32009-08-10 21:00:45 +0000848
849 // Get or construct the predicate method name.
850 Init *PMName = (*it)->getValueInit("PredicateMethod");
851 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
852 CI->PredicateMethod = SI->getValue();
853 } else {
Jim Grosbacha7c78222010-10-29 22:13:48 +0000854 assert(dynamic_cast<UnsetInit*>(PMName) &&
Daniel Dunbar5c468e32009-08-10 21:00:45 +0000855 "Unexpected PredicateMethod field!");
856 CI->PredicateMethod = "is" + CI->ClassName;
857 }
858
859 // Get or construct the render method name.
860 Init *RMName = (*it)->getValueInit("RenderMethod");
861 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
862 CI->RenderMethod = SI->getValue();
863 } else {
864 assert(dynamic_cast<UnsetInit*>(RMName) &&
865 "Unexpected RenderMethod field!");
866 CI->RenderMethod = "add" + CI->ClassName + "Operands";
867 }
868
Daniel Dunbar338825c2009-08-10 18:41:10 +0000869 AsmOperandClasses[*it] = CI;
870 Classes.push_back(CI);
871 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000872}
873
Chris Lattner02bcbc92010-11-01 01:37:30 +0000874AsmMatcherInfo::AsmMatcherInfo(Record *asmParser, CodeGenTarget &target)
875 : AsmParser(asmParser), Target(target),
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000876 CommentDelimiter(AsmParser->getValueAsString("CommentDelimiter")),
877 RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix"))
878{
879}
880
Chris Lattner02bcbc92010-11-01 01:37:30 +0000881void AsmMatcherInfo::BuildInfo() {
Chris Lattner0aed1e72010-10-30 20:07:57 +0000882 // Build information about all of the AssemblerPredicates.
883 std::vector<Record*> AllPredicates =
884 Records.getAllDerivedDefinitions("Predicate");
885 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
886 Record *Pred = AllPredicates[i];
887 // Ignore predicates that are not intended for the assembler.
888 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
889 continue;
890
891 if (Pred->getName().empty()) {
892 PrintError(Pred->getLoc(), "Predicate has no name!");
893 throw std::string("ERROR: Predicate defs must be named");
894 }
895
896 unsigned FeatureNo = SubtargetFeatures.size();
897 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
898 assert(FeatureNo < 32 && "Too many subtarget features!");
899 }
Jim Grosbacha7c78222010-10-29 22:13:48 +0000900
Chris Lattner39ee0362010-10-31 19:10:56 +0000901 // Parse the instructions; we need to do this first so that we can gather the
902 // singleton register classes.
903 std::set<std::string> SingletonRegisterNames;
Chris Lattner02bcbc92010-11-01 01:37:30 +0000904 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
905 E = Target.inst_end(); I != E; ++I) {
906 const CodeGenInstruction &CGI = **I;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000907
Chris Lattner39ee0362010-10-31 19:10:56 +0000908 // If the tblgen -match-prefix option is specified (for tblgen hackers),
909 // filter the set of instructions we consider.
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000910 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
Daniel Dunbar20927f22009-08-07 08:26:05 +0000911 continue;
912
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000913 OwningPtr<InstructionInfo> II(new InstructionInfo());
Jim Grosbacha7c78222010-10-29 22:13:48 +0000914
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000915 II->InstrName = CGI.TheDef->getName();
916 II->Instr = &CGI;
Chris Lattner4d43d0f2010-11-01 01:07:14 +0000917 // TODO: Eventually support asmparser for Variant != 0.
918 II->AsmString = CGI.FlattenAsmStringVariants(CGI.AsmString, 0);
Daniel Dunbar20927f22009-08-07 08:26:05 +0000919
Chris Lattner39ee0362010-10-31 19:10:56 +0000920 // Remove comments from the asm string. We know that the asmstring only
921 // has one line.
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000922 if (!CommentDelimiter.empty()) {
923 size_t Idx = StringRef(II->AsmString).find(CommentDelimiter);
924 if (Idx != StringRef::npos)
925 II->AsmString = II->AsmString.substr(0, Idx);
926 }
927
Daniel Dunbar20927f22009-08-07 08:26:05 +0000928 TokenizeAsmString(II->AsmString, II->Tokens);
929
Chris Lattner4d43d0f2010-11-01 01:07:14 +0000930 // Ignore instructions which shouldn't be matched and diagnose invalid
931 // instruction definitions with an error.
Chris Lattnerb61e09d2010-03-19 00:18:23 +0000932 if (!IsAssemblerInstruction(CGI.TheDef->getName(), CGI, II->Tokens))
Daniel Dunbar20927f22009-08-07 08:26:05 +0000933 continue;
Chris Lattner39ee0362010-10-31 19:10:56 +0000934
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000935 // Collect singleton registers, if used.
Chris Lattner4e692ab2010-10-28 21:28:42 +0000936 for (unsigned i = 0, e = II->Tokens.size(); i != e; ++i) {
Chris Lattner02bcbc92010-11-01 01:37:30 +0000937 StringRef RegName = II->getSingletonRegisterForToken(i, *this);
938
939 if (RegName != StringRef())
940 SingletonRegisterNames.insert(RegName);
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000941 }
Daniel Dunbar54074b52010-07-19 05:44:09 +0000942
943 // Compute the require features.
Chris Lattner0f899c72010-10-30 19:38:20 +0000944 std::vector<Record*> Predicates =
945 CGI.TheDef->getValueAsListOfDefs("Predicates");
Chris Lattner6fa152c2010-10-30 20:15:02 +0000946 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
947 if (SubtargetFeatureInfo *Feature = getSubtargetFeature(Predicates[i]))
948 II->RequiredFeatures.push_back(Feature);
Daniel Dunbar54074b52010-07-19 05:44:09 +0000949
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000950 Instructions.push_back(II.take());
951 }
952
953 // Build info for the register classes.
Chris Lattner02bcbc92010-11-01 01:37:30 +0000954 BuildRegisterClasses(SingletonRegisterNames);
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000955
956 // Build info for the user defined assembly operand classes.
Chris Lattner02bcbc92010-11-01 01:37:30 +0000957 BuildOperandClasses();
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000958
959 // Build the instruction information.
960 for (std::vector<InstructionInfo*>::iterator it = Instructions.begin(),
961 ie = Instructions.end(); it != ie; ++it) {
962 InstructionInfo *II = *it;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000963
Chris Lattnere206fcf2010-09-06 21:01:37 +0000964 // The first token of the instruction is the mnemonic, which must be a
Chris Lattner02bcbc92010-11-01 01:37:30 +0000965 // simple string, not a $foo variable or a singleton register.
Chris Lattnere206fcf2010-09-06 21:01:37 +0000966 assert(!II->Tokens.empty() && "Instruction has no tokens?");
967 StringRef Mnemonic = II->Tokens[0];
Chris Lattner02bcbc92010-11-01 01:37:30 +0000968 if (Mnemonic[0] == '$' ||
969 II->getSingletonRegisterForToken(0, *this) != StringRef())
970 throw TGError(II->Instr->TheDef->getLoc(),
971 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
Jim Grosbacha7c78222010-10-29 22:13:48 +0000972
Chris Lattnere206fcf2010-09-06 21:01:37 +0000973 // Parse the tokens after the mnemonic.
974 for (unsigned i = 1, e = II->Tokens.size(); i != e; ++i) {
Daniel Dunbar20927f22009-08-07 08:26:05 +0000975 StringRef Token = II->Tokens[i];
976
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000977 // Check for singleton registers.
Chris Lattner02bcbc92010-11-01 01:37:30 +0000978 StringRef RegName = II->getSingletonRegisterForToken(i, *this);
979 if (RegName != StringRef()) {
980 Record *RegRecord = getRegisterRecord(Target, RegName);
981 InstructionInfo::Operand Op;
982 Op.Class = RegisterClasses[RegRecord];
983 Op.OperandInfo = 0;
984 assert(Op.Class && Op.Class->Registers.size() == 1 &&
985 "Unexpected class for singleton register");
986 II->Operands.push_back(Op);
987 continue;
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000988 }
989
Daniel Dunbar20927f22009-08-07 08:26:05 +0000990 // Check for simple tokens.
991 if (Token[0] != '$') {
992 InstructionInfo::Operand Op;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000993 Op.Class = getTokenClass(Token);
Benjamin Kramerfa1165a2009-08-08 10:06:30 +0000994 Op.OperandInfo = 0;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000995 II->Operands.push_back(Op);
996 continue;
997 }
998
999 // Otherwise this is an operand reference.
Daniel Dunbar20927f22009-08-07 08:26:05 +00001000 StringRef OperandName;
1001 if (Token[1] == '{')
1002 OperandName = Token.substr(2, Token.size() - 3);
1003 else
1004 OperandName = Token.substr(1);
1005
1006 // Map this token to an operand. FIXME: Move elsewhere.
1007 unsigned Idx;
1008 try {
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001009 Idx = II->Instr->getOperandNamed(OperandName);
Daniel Dunbar20927f22009-08-07 08:26:05 +00001010 } catch(...) {
Jim Grosbacha7c78222010-10-29 22:13:48 +00001011 throw std::string("error: unable to find operand: '" +
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001012 OperandName.str() + "'");
Daniel Dunbar20927f22009-08-07 08:26:05 +00001013 }
1014
Daniel Dunbaraf616812010-02-10 08:15:48 +00001015 // FIXME: This is annoying, the named operand may be tied (e.g.,
1016 // XCHG8rm). What we want is the untied operand, which we now have to
1017 // grovel for. Only worry about this for single entry operands, we have to
1018 // clean this up anyway.
1019 const CodeGenInstruction::OperandInfo *OI = &II->Instr->OperandList[Idx];
1020 if (OI->Constraints[0].isTied()) {
1021 unsigned TiedOp = OI->Constraints[0].getTiedOperand();
1022
1023 // The tied operand index is an MIOperand index, find the operand that
1024 // contains it.
1025 for (unsigned i = 0, e = II->Instr->OperandList.size(); i != e; ++i) {
1026 if (II->Instr->OperandList[i].MIOperandNo == TiedOp) {
1027 OI = &II->Instr->OperandList[i];
1028 break;
1029 }
1030 }
1031
1032 assert(OI && "Unable to find tied operand target!");
1033 }
1034
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001035 InstructionInfo::Operand Op;
Daniel Dunbaraf616812010-02-10 08:15:48 +00001036 Op.Class = getOperandClass(Token, *OI);
1037 Op.OperandInfo = OI;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001038 II->Operands.push_back(Op);
1039 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001040 }
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001041
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001042 // Reorder classes so that classes preceed super classes.
1043 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
Daniel Dunbar20927f22009-08-07 08:26:05 +00001044}
1045
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001046static std::pair<unsigned, unsigned> *
1047GetTiedOperandAtIndex(SmallVectorImpl<std::pair<unsigned, unsigned> > &List,
1048 unsigned Index) {
1049 for (unsigned i = 0, e = List.size(); i != e; ++i)
1050 if (Index == List[i].first)
1051 return &List[i];
1052
1053 return 0;
1054}
1055
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001056static void EmitConvertToMCInst(CodeGenTarget &Target,
1057 std::vector<InstructionInfo*> &Infos,
1058 raw_ostream &OS) {
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001059 // Write the convert function to a separate stream, so we can drop it after
1060 // the enum.
1061 std::string ConvertFnBody;
1062 raw_string_ostream CvtOS(ConvertFnBody);
1063
Daniel Dunbar20927f22009-08-07 08:26:05 +00001064 // Function we have already generated.
1065 std::set<std::string> GeneratedFns;
1066
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001067 // Start the unified conversion function.
1068
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001069 CvtOS << "static void ConvertToMCInst(ConversionKind Kind, MCInst &Inst, "
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001070 << "unsigned Opcode,\n"
Chris Lattner98986712010-01-14 22:21:20 +00001071 << " const SmallVectorImpl<MCParsedAsmOperand*"
1072 << "> &Operands) {\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001073 CvtOS << " Inst.setOpcode(Opcode);\n";
1074 CvtOS << " switch (Kind) {\n";
1075 CvtOS << " default:\n";
1076
1077 // Start the enum, which we will generate inline.
1078
1079 OS << "// Unified function for converting operants to MCInst instances.\n\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001080 OS << "enum ConversionKind {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001081
Chris Lattner98986712010-01-14 22:21:20 +00001082 // TargetOperandClass - This is the target's operand class, like X86Operand.
1083 std::string TargetOperandClass = Target.getName() + "Operand";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001084
Daniel Dunbar20927f22009-08-07 08:26:05 +00001085 for (std::vector<InstructionInfo*>::const_iterator it = Infos.begin(),
1086 ie = Infos.end(); it != ie; ++it) {
1087 InstructionInfo &II = **it;
1088
1089 // Order the (class) operands by the order to convert them into an MCInst.
1090 SmallVector<std::pair<unsigned, unsigned>, 4> MIOperandList;
1091 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1092 InstructionInfo::Operand &Op = II.Operands[i];
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001093 if (Op.OperandInfo)
1094 MIOperandList.push_back(std::make_pair(Op.OperandInfo->MIOperandNo, i));
Daniel Dunbar20927f22009-08-07 08:26:05 +00001095 }
Daniel Dunbaraf616812010-02-10 08:15:48 +00001096
1097 // Find any tied operands.
1098 SmallVector<std::pair<unsigned, unsigned>, 4> TiedOperands;
1099 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1100 const CodeGenInstruction::OperandInfo &OpInfo = II.Instr->OperandList[i];
1101 for (unsigned j = 0, e = OpInfo.Constraints.size(); j != e; ++j) {
1102 const CodeGenInstruction::ConstraintInfo &CI = OpInfo.Constraints[j];
1103 if (CI.isTied())
1104 TiedOperands.push_back(std::make_pair(OpInfo.MIOperandNo + j,
1105 CI.getTiedOperand()));
1106 }
1107 }
1108
Daniel Dunbar20927f22009-08-07 08:26:05 +00001109 std::sort(MIOperandList.begin(), MIOperandList.end());
1110
1111 // Compute the total number of operands.
1112 unsigned NumMIOperands = 0;
1113 for (unsigned i = 0, e = II.Instr->OperandList.size(); i != e; ++i) {
1114 const CodeGenInstruction::OperandInfo &OI = II.Instr->OperandList[i];
Jim Grosbacha7c78222010-10-29 22:13:48 +00001115 NumMIOperands = std::max(NumMIOperands,
Daniel Dunbar20927f22009-08-07 08:26:05 +00001116 OI.MIOperandNo + OI.MINumOperands);
1117 }
1118
1119 // Build the conversion function signature.
1120 std::string Signature = "Convert";
1121 unsigned CurIndex = 0;
1122 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1123 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001124 assert(CurIndex <= Op.OperandInfo->MIOperandNo &&
Daniel Dunbar20927f22009-08-07 08:26:05 +00001125 "Duplicate match for instruction operand!");
Jim Grosbacha7c78222010-10-29 22:13:48 +00001126
Daniel Dunbar20927f22009-08-07 08:26:05 +00001127 // Skip operands which weren't matched by anything, this occurs when the
1128 // .td file encodes "implicit" operands as explicit ones.
1129 //
1130 // FIXME: This should be removed from the MCInst structure.
Daniel Dunbaraf616812010-02-10 08:15:48 +00001131 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001132 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1133 CurIndex);
1134 if (!Tie)
Daniel Dunbaraf616812010-02-10 08:15:48 +00001135 Signature += "__Imp";
1136 else
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001137 Signature += "__Tie" + utostr(Tie->second);
Daniel Dunbaraf616812010-02-10 08:15:48 +00001138 }
1139
1140 Signature += "__";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001141
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001142 // Registers are always converted the same, don't duplicate the conversion
1143 // function based on them.
1144 //
1145 // FIXME: We could generalize this based on the render method, if it
1146 // mattered.
1147 if (Op.Class->isRegisterClass())
1148 Signature += "Reg";
1149 else
1150 Signature += Op.Class->ClassName;
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001151 Signature += utostr(Op.OperandInfo->MINumOperands);
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001152 Signature += "_" + utostr(MIOperandList[i].second);
1153
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001154 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001155 }
1156
1157 // Add any trailing implicit operands.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001158 for (; CurIndex != NumMIOperands; ++CurIndex) {
1159 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1160 CurIndex);
1161 if (!Tie)
1162 Signature += "__Imp";
1163 else
1164 Signature += "__Tie" + utostr(Tie->second);
1165 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001166
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001167 II.ConversionFnKind = Signature;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001168
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001169 // Check if we have already generated this signature.
Daniel Dunbar20927f22009-08-07 08:26:05 +00001170 if (!GeneratedFns.insert(Signature).second)
1171 continue;
1172
1173 // If not, emit it now.
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001174
1175 // Add to the enum list.
1176 OS << " " << Signature << ",\n";
1177
1178 // And to the convert function.
1179 CvtOS << " case " << Signature << ":\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001180 CurIndex = 0;
1181 for (unsigned i = 0, e = MIOperandList.size(); i != e; ++i) {
1182 InstructionInfo::Operand &Op = II.Operands[MIOperandList[i].second];
1183
1184 // Add the implicit operands.
Daniel Dunbaraf616812010-02-10 08:15:48 +00001185 for (; CurIndex != Op.OperandInfo->MIOperandNo; ++CurIndex) {
1186 // See if this is a tied operand.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001187 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1188 CurIndex);
Daniel Dunbaraf616812010-02-10 08:15:48 +00001189
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001190 if (!Tie) {
Daniel Dunbaraf616812010-02-10 08:15:48 +00001191 // If not, this is some implicit operand. Just assume it is a register
1192 // for now.
1193 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1194 } else {
1195 // Copy the tied operand.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001196 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
Daniel Dunbaraf616812010-02-10 08:15:48 +00001197 CvtOS << " Inst.addOperand(Inst.getOperand("
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001198 << Tie->second << "));\n";
Daniel Dunbaraf616812010-02-10 08:15:48 +00001199 }
1200 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001201
Chris Lattner98986712010-01-14 22:21:20 +00001202 CvtOS << " ((" << TargetOperandClass << "*)Operands["
Jim Grosbacha7c78222010-10-29 22:13:48 +00001203 << MIOperandList[i].second
1204 << "+1])->" << Op.Class->RenderMethod
Benjamin Kramerfa1165a2009-08-08 10:06:30 +00001205 << "(Inst, " << Op.OperandInfo->MINumOperands << ");\n";
1206 CurIndex += Op.OperandInfo->MINumOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001207 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001208
Daniel Dunbar20927f22009-08-07 08:26:05 +00001209 // And add trailing implicit operands.
Daniel Dunbar3b6910d2010-02-12 01:46:54 +00001210 for (; CurIndex != NumMIOperands; ++CurIndex) {
1211 std::pair<unsigned, unsigned> *Tie = GetTiedOperandAtIndex(TiedOperands,
1212 CurIndex);
1213
1214 if (!Tie) {
1215 // If not, this is some implicit operand. Just assume it is a register
1216 // for now.
1217 CvtOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1218 } else {
1219 // Copy the tied operand.
1220 assert(Tie->first>Tie->second && "Tied operand preceeds its target!");
1221 CvtOS << " Inst.addOperand(Inst.getOperand("
1222 << Tie->second << "));\n";
1223 }
1224 }
1225
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001226 CvtOS << " return;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001227 }
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001228
1229 // Finish the convert function.
1230
1231 CvtOS << " }\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001232 CvtOS << "}\n\n";
1233
1234 // Finish the enum, and drop the convert function after it.
1235
1236 OS << " NumConversionVariants\n";
1237 OS << "};\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001238
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001239 OS << CvtOS.str();
Daniel Dunbara027d222009-07-31 02:32:59 +00001240}
1241
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001242/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1243static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1244 std::vector<ClassInfo*> &Infos,
1245 raw_ostream &OS) {
1246 OS << "namespace {\n\n";
1247
1248 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1249 << "/// instruction matching.\n";
1250 OS << "enum MatchClassKind {\n";
1251 OS << " InvalidMatchClass = 0,\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001252 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001253 ie = Infos.end(); it != ie; ++it) {
1254 ClassInfo &CI = **it;
1255 OS << " " << CI.Name << ", // ";
1256 if (CI.Kind == ClassInfo::Token) {
1257 OS << "'" << CI.ValueName << "'\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001258 } else if (CI.isRegisterClass()) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001259 if (!CI.ValueName.empty())
1260 OS << "register class '" << CI.ValueName << "'\n";
1261 else
1262 OS << "derived register class\n";
1263 } else {
1264 OS << "user defined class '" << CI.ValueName << "'\n";
1265 }
1266 }
1267 OS << " NumMatchClassKinds\n";
1268 OS << "};\n\n";
1269
1270 OS << "}\n\n";
1271}
1272
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001273/// EmitClassifyOperand - Emit the function to classify an operand.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001274static void EmitClassifyOperand(AsmMatcherInfo &Info,
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001275 raw_ostream &OS) {
Chris Lattner98986712010-01-14 22:21:20 +00001276 OS << "static MatchClassKind ClassifyOperand(MCParsedAsmOperand *GOp) {\n"
Chris Lattner02bcbc92010-11-01 01:37:30 +00001277 << " " << Info.Target.getName() << "Operand &Operand = *("
1278 << Info.Target.getName() << "Operand*)GOp;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001279
1280 // Classify tokens.
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001281 OS << " if (Operand.isToken())\n";
1282 OS << " return MatchTokenString(Operand.getToken());\n\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001283
1284 // Classify registers.
1285 //
1286 // FIXME: Don't hardcode isReg, getReg.
1287 OS << " if (Operand.isReg()) {\n";
1288 OS << " switch (Operand.getReg()) {\n";
1289 OS << " default: return InvalidMatchClass;\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001290 for (std::map<Record*, ClassInfo*>::iterator
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001291 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1292 it != ie; ++it)
Chris Lattner02bcbc92010-11-01 01:37:30 +00001293 OS << " case " << Info.Target.getName() << "::"
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001294 << it->first->getName() << ": return " << it->second->Name << ";\n";
1295 OS << " }\n";
1296 OS << " }\n\n";
1297
1298 // Classify user defined operands.
Jim Grosbacha7c78222010-10-29 22:13:48 +00001299 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001300 ie = Info.Classes.end(); it != ie; ++it) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001301 ClassInfo &CI = **it;
1302
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001303 if (!CI.isUserClass())
1304 continue;
1305
1306 OS << " // '" << CI.ClassName << "' class";
1307 if (!CI.SuperClasses.empty()) {
1308 OS << ", subclass of ";
1309 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i) {
1310 if (i) OS << ", ";
1311 OS << "'" << CI.SuperClasses[i]->ClassName << "'";
1312 assert(CI < *CI.SuperClasses[i] && "Invalid class relation!");
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001313 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001314 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001315 OS << "\n";
1316
1317 OS << " if (Operand." << CI.PredicateMethod << "()) {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001318
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001319 // Validate subclass relationships.
1320 if (!CI.SuperClasses.empty()) {
1321 for (unsigned i = 0, e = CI.SuperClasses.size(); i != e; ++i)
1322 OS << " assert(Operand." << CI.SuperClasses[i]->PredicateMethod
1323 << "() && \"Invalid class relationship!\");\n";
1324 }
1325
1326 OS << " return " << CI.Name << ";\n";
1327 OS << " }\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001328 }
1329 OS << " return InvalidMatchClass;\n";
1330 OS << "}\n\n";
1331}
1332
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001333/// EmitIsSubclass - Emit the subclass predicate function.
1334static void EmitIsSubclass(CodeGenTarget &Target,
1335 std::vector<ClassInfo*> &Infos,
1336 raw_ostream &OS) {
1337 OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1338 OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
1339 OS << " if (A == B)\n";
1340 OS << " return true;\n\n";
1341
1342 OS << " switch (A) {\n";
1343 OS << " default:\n";
1344 OS << " return false;\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001345 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001346 ie = Infos.end(); it != ie; ++it) {
1347 ClassInfo &A = **it;
1348
1349 if (A.Kind != ClassInfo::Token) {
1350 std::vector<StringRef> SuperClasses;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001351 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001352 ie = Infos.end(); it != ie; ++it) {
1353 ClassInfo &B = **it;
1354
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001355 if (&A != &B && A.isSubsetOf(B))
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001356 SuperClasses.push_back(B.Name);
1357 }
1358
1359 if (SuperClasses.empty())
1360 continue;
1361
1362 OS << "\n case " << A.Name << ":\n";
1363
1364 if (SuperClasses.size() == 1) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001365 OS << " return B == " << SuperClasses.back() << ";\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001366 continue;
1367 }
1368
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001369 OS << " switch (B) {\n";
1370 OS << " default: return false;\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001371 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001372 OS << " case " << SuperClasses[i] << ": return true;\n";
1373 OS << " }\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001374 }
1375 }
1376 OS << " }\n";
1377 OS << "}\n\n";
1378}
1379
Chris Lattner70add882009-08-08 20:02:57 +00001380
1381
Daniel Dunbar245f0582009-08-08 21:22:41 +00001382/// EmitMatchTokenString - Emit the function to match a token string to the
1383/// appropriate match class value.
1384static void EmitMatchTokenString(CodeGenTarget &Target,
1385 std::vector<ClassInfo*> &Infos,
1386 raw_ostream &OS) {
1387 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00001388 std::vector<StringMatcher::StringPair> Matches;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001389 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbar245f0582009-08-08 21:22:41 +00001390 ie = Infos.end(); it != ie; ++it) {
1391 ClassInfo &CI = **it;
1392
1393 if (CI.Kind == ClassInfo::Token)
Chris Lattner5845e5c2010-09-06 02:01:51 +00001394 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1395 "return " + CI.Name + ";"));
Daniel Dunbar245f0582009-08-08 21:22:41 +00001396 }
1397
Chris Lattnerb8d6e982010-02-09 00:34:28 +00001398 OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001399
Chris Lattner5845e5c2010-09-06 02:01:51 +00001400 StringMatcher("Name", Matches, OS).Emit();
Daniel Dunbar245f0582009-08-08 21:22:41 +00001401
1402 OS << " return InvalidMatchClass;\n";
1403 OS << "}\n\n";
1404}
Chris Lattner70add882009-08-08 20:02:57 +00001405
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001406/// EmitMatchRegisterName - Emit the function to match a string to the target
1407/// specific register enum.
1408static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1409 raw_ostream &OS) {
Daniel Dunbar245f0582009-08-08 21:22:41 +00001410 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00001411 std::vector<StringMatcher::StringPair> Matches;
Daniel Dunbar245f0582009-08-08 21:22:41 +00001412 for (unsigned i = 0, e = Target.getRegisters().size(); i != e; ++i) {
1413 const CodeGenRegister &Reg = Target.getRegisters()[i];
Daniel Dunbar22be5222009-07-17 18:51:11 +00001414 if (Reg.TheDef->getValueAsString("AsmName").empty())
1415 continue;
1416
Chris Lattner5845e5c2010-09-06 02:01:51 +00001417 Matches.push_back(StringMatcher::StringPair(
1418 Reg.TheDef->getValueAsString("AsmName"),
1419 "return " + utostr(i + 1) + ";"));
Daniel Dunbar22be5222009-07-17 18:51:11 +00001420 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001421
Chris Lattnerb8d6e982010-02-09 00:34:28 +00001422 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001423
Chris Lattner5845e5c2010-09-06 02:01:51 +00001424 StringMatcher("Name", Matches, OS).Emit();
Jim Grosbacha7c78222010-10-29 22:13:48 +00001425
Daniel Dunbar245f0582009-08-08 21:22:41 +00001426 OS << " return 0;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001427 OS << "}\n\n";
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001428}
Daniel Dunbara027d222009-07-31 02:32:59 +00001429
Daniel Dunbar54074b52010-07-19 05:44:09 +00001430/// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1431/// definitions.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001432static void EmitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
Daniel Dunbar54074b52010-07-19 05:44:09 +00001433 raw_ostream &OS) {
1434 OS << "// Flags for subtarget features that participate in "
1435 << "instruction matching.\n";
1436 OS << "enum SubtargetFeatureFlag {\n";
1437 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1438 it = Info.SubtargetFeatures.begin(),
1439 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1440 SubtargetFeatureInfo &SFI = *it->second;
Chris Lattner0aed1e72010-10-30 20:07:57 +00001441 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001442 }
1443 OS << " Feature_None = 0\n";
1444 OS << "};\n\n";
1445}
1446
1447/// EmitComputeAvailableFeatures - Emit the function to compute the list of
1448/// available features given a subtarget.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001449static void EmitComputeAvailableFeatures(AsmMatcherInfo &Info,
Daniel Dunbar54074b52010-07-19 05:44:09 +00001450 raw_ostream &OS) {
1451 std::string ClassName =
1452 Info.AsmParser->getValueAsString("AsmParserClassName");
1453
Chris Lattner02bcbc92010-11-01 01:37:30 +00001454 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
1455 << "ComputeAvailableFeatures(const " << Info.Target.getName()
Daniel Dunbar54074b52010-07-19 05:44:09 +00001456 << "Subtarget *Subtarget) const {\n";
1457 OS << " unsigned Features = 0;\n";
1458 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1459 it = Info.SubtargetFeatures.begin(),
1460 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1461 SubtargetFeatureInfo &SFI = *it->second;
1462 OS << " if (" << SFI.TheDef->getValueAsString("CondString")
1463 << ")\n";
Chris Lattner0aed1e72010-10-30 20:07:57 +00001464 OS << " Features |= " << SFI.getEnumName() << ";\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001465 }
1466 OS << " return Features;\n";
1467 OS << "}\n\n";
1468}
1469
Chris Lattner6fa152c2010-10-30 20:15:02 +00001470static std::string GetAliasRequiredFeatures(Record *R,
1471 const AsmMatcherInfo &Info) {
Chris Lattner693173f2010-10-30 19:23:13 +00001472 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
Chris Lattner693173f2010-10-30 19:23:13 +00001473 std::string Result;
1474 unsigned NumFeatures = 0;
1475 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
Chris Lattner6fa152c2010-10-30 20:15:02 +00001476 if (SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i])) {
1477 if (NumFeatures)
1478 Result += '|';
Chris Lattner693173f2010-10-30 19:23:13 +00001479
Chris Lattner6fa152c2010-10-30 20:15:02 +00001480 Result += F->getEnumName();
1481 ++NumFeatures;
1482 }
Chris Lattner693173f2010-10-30 19:23:13 +00001483 }
1484
1485 if (NumFeatures > 1)
1486 Result = '(' + Result + ')';
1487 return Result;
1488}
1489
Chris Lattner674c1dc2010-10-30 17:36:36 +00001490/// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
Chris Lattner7fd44892010-10-30 18:48:18 +00001491/// emit a function for them and return true, otherwise return false.
Chris Lattner0aed1e72010-10-30 20:07:57 +00001492static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
Chris Lattner674c1dc2010-10-30 17:36:36 +00001493 std::vector<Record*> Aliases =
1494 Records.getAllDerivedDefinitions("MnemonicAlias");
Chris Lattner7fd44892010-10-30 18:48:18 +00001495 if (Aliases.empty()) return false;
Chris Lattner674c1dc2010-10-30 17:36:36 +00001496
Chris Lattner8cc0a6b2010-10-30 18:57:07 +00001497 OS << "static void ApplyMnemonicAliases(StringRef &Mnemonic, "
1498 "unsigned Features) {\n";
1499
Chris Lattner4fd32c62010-10-30 18:56:12 +00001500 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
1501 // iteration order of the map is stable.
1502 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
1503
Chris Lattner674c1dc2010-10-30 17:36:36 +00001504 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1505 Record *R = Aliases[i];
Chris Lattner4fd32c62010-10-30 18:56:12 +00001506 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
Chris Lattner674c1dc2010-10-30 17:36:36 +00001507 }
Chris Lattner4fd32c62010-10-30 18:56:12 +00001508
1509 // Process each alias a "from" mnemonic at a time, building the code executed
1510 // by the string remapper.
1511 std::vector<StringMatcher::StringPair> Cases;
1512 for (std::map<std::string, std::vector<Record*> >::iterator
1513 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1514 I != E; ++I) {
Chris Lattner4fd32c62010-10-30 18:56:12 +00001515 const std::vector<Record*> &ToVec = I->second;
Chris Lattner693173f2010-10-30 19:23:13 +00001516
1517 // Loop through each alias and emit code that handles each case. If there
1518 // are two instructions without predicates, emit an error. If there is one,
1519 // emit it last.
1520 std::string MatchCode;
1521 int AliasWithNoPredicate = -1;
Chris Lattner4fd32c62010-10-30 18:56:12 +00001522
Chris Lattner693173f2010-10-30 19:23:13 +00001523 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1524 Record *R = ToVec[i];
Chris Lattner6fa152c2010-10-30 20:15:02 +00001525 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
Chris Lattner693173f2010-10-30 19:23:13 +00001526
1527 // If this unconditionally matches, remember it for later and diagnose
1528 // duplicates.
1529 if (FeatureMask.empty()) {
1530 if (AliasWithNoPredicate != -1) {
1531 // We can't have two aliases from the same mnemonic with no predicate.
1532 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1533 "two MnemonicAliases with the same 'from' mnemonic!");
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00001534 PrintError(R->getLoc(), "this is the other MnemonicAlias.");
1535 throw std::string("ERROR: Invalid MnemonicAlias definitions!");
Chris Lattner693173f2010-10-30 19:23:13 +00001536 }
1537
1538 AliasWithNoPredicate = i;
1539 continue;
1540 }
1541
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00001542 if (!MatchCode.empty())
1543 MatchCode += "else ";
Chris Lattner693173f2010-10-30 19:23:13 +00001544 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1545 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattner4fd32c62010-10-30 18:56:12 +00001546 }
1547
Chris Lattner693173f2010-10-30 19:23:13 +00001548 if (AliasWithNoPredicate != -1) {
1549 Record *R = ToVec[AliasWithNoPredicate];
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00001550 if (!MatchCode.empty())
1551 MatchCode += "else\n ";
1552 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattner693173f2010-10-30 19:23:13 +00001553 }
1554
1555 MatchCode += "return;";
1556
1557 Cases.push_back(std::make_pair(I->first, MatchCode));
Chris Lattner4fd32c62010-10-30 18:56:12 +00001558 }
1559
Chris Lattner674c1dc2010-10-30 17:36:36 +00001560
1561 StringMatcher("Mnemonic", Cases, OS).Emit();
Chris Lattner7fd44892010-10-30 18:48:18 +00001562 OS << "}\n";
1563
1564 return true;
Chris Lattner674c1dc2010-10-30 17:36:36 +00001565}
1566
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001567void AsmMatcherEmitter::run(raw_ostream &OS) {
1568 CodeGenTarget Target;
1569 Record *AsmParser = Target.getAsmParser();
1570 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
1571
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001572 // Compute the information on the instructions to match.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001573 AsmMatcherInfo Info(AsmParser, Target);
1574 Info.BuildInfo();
Daniel Dunbara027d222009-07-31 02:32:59 +00001575
Daniel Dunbare1f6de32010-02-02 23:46:36 +00001576 // Sort the instruction table using the partial order on classes. We use
1577 // stable_sort to ensure that ambiguous instructions are still
1578 // deterministically ordered.
1579 std::stable_sort(Info.Instructions.begin(), Info.Instructions.end(),
1580 less_ptr<InstructionInfo>());
Jim Grosbacha7c78222010-10-29 22:13:48 +00001581
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001582 DEBUG_WITH_TYPE("instruction_info", {
Jim Grosbacha7c78222010-10-29 22:13:48 +00001583 for (std::vector<InstructionInfo*>::iterator
1584 it = Info.Instructions.begin(), ie = Info.Instructions.end();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001585 it != ie; ++it)
Daniel Dunbar20927f22009-08-07 08:26:05 +00001586 (*it)->dump();
1587 });
Daniel Dunbara027d222009-07-31 02:32:59 +00001588
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001589 // Check for ambiguous instructions.
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00001590 DEBUG_WITH_TYPE("ambiguous_instrs", {
1591 unsigned NumAmbiguous = 0;
Chris Lattner87410362010-09-06 20:21:47 +00001592 for (unsigned i = 0, e = Info.Instructions.size(); i != e; ++i) {
1593 for (unsigned j = i + 1; j != e; ++j) {
1594 InstructionInfo &A = *Info.Instructions[i];
1595 InstructionInfo &B = *Info.Instructions[j];
Jim Grosbacha7c78222010-10-29 22:13:48 +00001596
Chris Lattner87410362010-09-06 20:21:47 +00001597 if (A.CouldMatchAmiguouslyWith(B)) {
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00001598 errs() << "warning: ambiguous instruction match:\n";
1599 A.dump();
1600 errs() << "\nis incomparable with:\n";
1601 B.dump();
1602 errs() << "\n\n";
Chris Lattner87410362010-09-06 20:21:47 +00001603 ++NumAmbiguous;
1604 }
Daniel Dunbar2b544812009-08-09 06:05:33 +00001605 }
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001606 }
Chris Lattner87410362010-09-06 20:21:47 +00001607 if (NumAmbiguous)
Jim Grosbacha7c78222010-10-29 22:13:48 +00001608 errs() << "warning: " << NumAmbiguous
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00001609 << " ambiguous instructions!\n";
1610 });
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001611
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001612 // Write the output.
1613
1614 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
1615
Chris Lattner0692ee62010-09-06 19:11:01 +00001616 // Information for the class declaration.
1617 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
1618 OS << "#undef GET_ASSEMBLER_HEADER\n";
Chris Lattner79ed3f72010-09-06 19:22:17 +00001619 OS << " // This should be included into the middle of the declaration of \n";
1620 OS << " // your subclasses implementation of TargetAsmParser.\n";
Chris Lattner0692ee62010-09-06 19:11:01 +00001621 OS << " unsigned ComputeAvailableFeatures(const " <<
1622 Target.getName() << "Subtarget *Subtarget) const;\n";
Chris Lattner79ed3f72010-09-06 19:22:17 +00001623 OS << " enum MatchResultTy {\n";
Chris Lattnera008e8a2010-09-06 21:54:15 +00001624 OS << " Match_Success, Match_MnemonicFail, Match_InvalidOperand,\n";
1625 OS << " Match_MissingFeature\n";
Chris Lattner79ed3f72010-09-06 19:22:17 +00001626 OS << " };\n";
Jim Grosbachbb168242010-10-08 18:13:57 +00001627 OS << " MatchResultTy MatchInstructionImpl(const "
1628 << "SmallVectorImpl<MCParsedAsmOperand*>"
Chris Lattnerce4a3352010-09-06 22:11:18 +00001629 << " &Operands, MCInst &Inst, unsigned &ErrorInfo);\n\n";
Chris Lattner0692ee62010-09-06 19:11:01 +00001630 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
1631
Jim Grosbacha7c78222010-10-29 22:13:48 +00001632
1633
1634
Chris Lattner0692ee62010-09-06 19:11:01 +00001635 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
1636 OS << "#undef GET_REGISTER_MATCHER\n\n";
1637
Daniel Dunbar54074b52010-07-19 05:44:09 +00001638 // Emit the subtarget feature enumeration.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001639 EmitSubtargetFeatureFlagEnumeration(Info, OS);
Daniel Dunbar54074b52010-07-19 05:44:09 +00001640
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001641 // Emit the function to match a register name to number.
1642 EmitMatchRegisterName(Target, AsmParser, OS);
Chris Lattner0692ee62010-09-06 19:11:01 +00001643
1644 OS << "#endif // GET_REGISTER_MATCHER\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001645
Chris Lattner0692ee62010-09-06 19:11:01 +00001646
1647 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
1648 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001649
Chris Lattner7fd44892010-10-30 18:48:18 +00001650 // Generate the function that remaps for mnemonic aliases.
Chris Lattner0aed1e72010-10-30 20:07:57 +00001651 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
Chris Lattner7fd44892010-10-30 18:48:18 +00001652
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001653 // Generate the unified function to convert operands into an MCInst.
1654 EmitConvertToMCInst(Target, Info.Instructions, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00001655
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001656 // Emit the enumeration for classes which participate in matching.
1657 EmitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00001658
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001659 // Emit the routine to match token strings to their match class.
1660 EmitMatchTokenString(Target, Info.Classes, OS);
1661
1662 // Emit the routine to classify an operand.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001663 EmitClassifyOperand(Info, OS);
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001664
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001665 // Emit the subclass predicate routine.
1666 EmitIsSubclass(Target, Info.Classes, OS);
1667
Daniel Dunbar54074b52010-07-19 05:44:09 +00001668 // Emit the available features compute function.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001669 EmitComputeAvailableFeatures(Info, OS);
Daniel Dunbar54074b52010-07-19 05:44:09 +00001670
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001671
1672 size_t MaxNumOperands = 0;
1673 for (std::vector<InstructionInfo*>::const_iterator it =
1674 Info.Instructions.begin(), ie = Info.Instructions.end();
1675 it != ie; ++it)
1676 MaxNumOperands = std::max(MaxNumOperands, (*it)->Operands.size());
Jim Grosbacha7c78222010-10-29 22:13:48 +00001677
1678
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001679 // Emit the static match table; unused classes get initalized to 0 which is
1680 // guaranteed to be InvalidMatchClass.
1681 //
1682 // FIXME: We can reduce the size of this table very easily. First, we change
1683 // it so that store the kinds in separate bit-fields for each index, which
1684 // only needs to be the max width used for classes at that index (we also need
1685 // to reject based on this during classification). If we then make sure to
1686 // order the match kinds appropriately (putting mnemonics last), then we
1687 // should only end up using a few bits for each class, especially the ones
1688 // following the mnemonic.
Chris Lattner96352e52010-09-06 21:08:38 +00001689 OS << "namespace {\n";
1690 OS << " struct MatchEntry {\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001691 OS << " unsigned Opcode;\n";
Chris Lattnere206fcf2010-09-06 21:01:37 +00001692 OS << " const char *Mnemonic;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001693 OS << " ConversionKind ConvertFn;\n";
1694 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001695 OS << " unsigned RequiredFeatures;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001696 OS << " };\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001697
Chris Lattner2b1f9432010-09-06 21:22:45 +00001698 OS << "// Predicate for searching for an opcode.\n";
1699 OS << " struct LessOpcode {\n";
1700 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
1701 OS << " return StringRef(LHS.Mnemonic) < RHS;\n";
1702 OS << " }\n";
1703 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
1704 OS << " return LHS < StringRef(RHS.Mnemonic);\n";
1705 OS << " }\n";
Chris Lattner32c685c2010-09-07 06:10:48 +00001706 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
1707 OS << " return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n";
1708 OS << " }\n";
Chris Lattner96352e52010-09-06 21:08:38 +00001709 OS << " };\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001710
Chris Lattner96352e52010-09-06 21:08:38 +00001711 OS << "} // end anonymous namespace.\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001712
Chris Lattner96352e52010-09-06 21:08:38 +00001713 OS << "static const MatchEntry MatchTable["
1714 << Info.Instructions.size() << "] = {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001715
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001716 for (std::vector<InstructionInfo*>::const_iterator it =
Chris Lattner96352e52010-09-06 21:08:38 +00001717 Info.Instructions.begin(), ie = Info.Instructions.end();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001718 it != ie; ++it) {
Daniel Dunbar20927f22009-08-07 08:26:05 +00001719 InstructionInfo &II = **it;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001720
Chris Lattner96352e52010-09-06 21:08:38 +00001721 OS << " { " << Target.getName() << "::" << II.InstrName
1722 << ", \"" << II.Tokens[0] << "\""
1723 << ", " << II.ConversionFnKind << ", { ";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001724 for (unsigned i = 0, e = II.Operands.size(); i != e; ++i) {
1725 InstructionInfo::Operand &Op = II.Operands[i];
Jim Grosbacha7c78222010-10-29 22:13:48 +00001726
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001727 if (i) OS << ", ";
1728 OS << Op.Class->Name;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001729 }
Daniel Dunbar54074b52010-07-19 05:44:09 +00001730 OS << " }, ";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001731
Daniel Dunbar54074b52010-07-19 05:44:09 +00001732 // Write the required features mask.
1733 if (!II.RequiredFeatures.empty()) {
1734 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
1735 if (i) OS << "|";
Chris Lattner0aed1e72010-10-30 20:07:57 +00001736 OS << II.RequiredFeatures[i]->getEnumName();
Daniel Dunbar54074b52010-07-19 05:44:09 +00001737 }
1738 } else
1739 OS << "0";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001740
Daniel Dunbar54074b52010-07-19 05:44:09 +00001741 OS << "},\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00001742 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001743
Chris Lattner96352e52010-09-06 21:08:38 +00001744 OS << "};\n\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00001745
Chris Lattner96352e52010-09-06 21:08:38 +00001746 // Finally, build the match function.
1747 OS << Target.getName() << ClassName << "::MatchResultTy "
1748 << Target.getName() << ClassName << "::\n"
1749 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
1750 << " &Operands,\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001751 OS << " MCInst &Inst, unsigned &ErrorInfo) {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001752
1753 // Emit code to get the available features.
1754 OS << " // Get the current feature set.\n";
1755 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
1756
Chris Lattner674c1dc2010-10-30 17:36:36 +00001757 OS << " // Get the instruction mnemonic, which is the first token.\n";
1758 OS << " StringRef Mnemonic = ((" << Target.getName()
1759 << "Operand*)Operands[0])->getToken();\n\n";
1760
Chris Lattner7fd44892010-10-30 18:48:18 +00001761 if (HasMnemonicAliases) {
1762 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
1763 OS << " ApplyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
1764 }
Chris Lattner674c1dc2010-10-30 17:36:36 +00001765
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001766 // Emit code to compute the class list for this operand vector.
1767 OS << " // Eliminate obvious mismatches.\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001768 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
1769 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
1770 OS << " return Match_InvalidOperand;\n";
1771 OS << " }\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001772
1773 OS << " // Compute the class list for this operand vector.\n";
1774 OS << " MatchClassKind Classes[" << MaxNumOperands << "];\n";
Chris Lattnere206fcf2010-09-06 21:01:37 +00001775 OS << " for (unsigned i = 1, e = Operands.size(); i != e; ++i) {\n";
1776 OS << " Classes[i-1] = ClassifyOperand(Operands[i]);\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001777
1778 OS << " // Check for invalid operands before matching.\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001779 OS << " if (Classes[i-1] == InvalidMatchClass) {\n";
1780 OS << " ErrorInfo = i;\n";
Chris Lattnera008e8a2010-09-06 21:54:15 +00001781 OS << " return Match_InvalidOperand;\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001782 OS << " }\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001783 OS << " }\n\n";
1784
1785 OS << " // Mark unused classes.\n";
Chris Lattnere206fcf2010-09-06 21:01:37 +00001786 OS << " for (unsigned i = Operands.size()-1, e = " << MaxNumOperands << "; "
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001787 << "i != e; ++i)\n";
1788 OS << " Classes[i] = InvalidMatchClass;\n\n";
1789
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001790 OS << " // Some state to try to produce better error messages.\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001791 OS << " bool HadMatchOtherThanFeatures = false;\n\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001792 OS << " // Set ErrorInfo to the operand that mismatches if it is \n";
1793 OS << " // wrong for all instances of the instruction.\n";
1794 OS << " ErrorInfo = ~0U;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001795
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001796 // Emit code to search the table.
1797 OS << " // Search the table.\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001798 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
1799 OS << " std::equal_range(MatchTable, MatchTable+"
1800 << Info.Instructions.size() << ", Mnemonic, LessOpcode());\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001801
Chris Lattnera008e8a2010-09-06 21:54:15 +00001802 OS << " // Return a more specific error code if no mnemonics match.\n";
1803 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
1804 OS << " return Match_MnemonicFail;\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001805
Chris Lattner2b1f9432010-09-06 21:22:45 +00001806 OS << " for (const MatchEntry *it = MnemonicRange.first, "
Chris Lattner80db4e52010-09-06 21:23:43 +00001807 << "*ie = MnemonicRange.second;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00001808 OS << " it != ie; ++it) {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001809
Gabor Greife53ee3b2010-09-07 06:06:06 +00001810 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Chris Lattner44b0daa2010-09-06 21:25:43 +00001811 OS << " assert(Mnemonic == it->Mnemonic);\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001812
Daniel Dunbar54074b52010-07-19 05:44:09 +00001813 // Emit check that the subclasses match.
Chris Lattnerce4a3352010-09-06 22:11:18 +00001814 OS << " bool OperandsValid = true;\n";
1815 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
1816 OS << " if (IsSubclass(Classes[i], it->Classes[i]))\n";
1817 OS << " continue;\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001818 OS << " // If this operand is broken for all of the instances of this\n";
1819 OS << " // mnemonic, keep track of it so we can report loc info.\n";
1820 OS << " if (it == MnemonicRange.first || ErrorInfo == i+1)\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001821 OS << " ErrorInfo = i+1;\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00001822 OS << " else\n";
1823 OS << " ErrorInfo = ~0U;";
Chris Lattnerce4a3352010-09-06 22:11:18 +00001824 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
1825 OS << " OperandsValid = false;\n";
1826 OS << " break;\n";
1827 OS << " }\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001828
Chris Lattnerce4a3352010-09-06 22:11:18 +00001829 OS << " if (!OperandsValid) continue;\n";
Chris Lattnerec6789f2010-09-06 20:08:02 +00001830
1831 // Emit check that the required features are available.
1832 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
1833 << "!= it->RequiredFeatures) {\n";
1834 OS << " HadMatchOtherThanFeatures = true;\n";
1835 OS << " continue;\n";
1836 OS << " }\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001837
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001838 OS << "\n";
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00001839 OS << " ConvertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
1840
1841 // Call the post-processing function, if used.
1842 std::string InsnCleanupFn =
1843 AsmParser->getValueAsString("AsmParserInstCleanup");
1844 if (!InsnCleanupFn.empty())
1845 OS << " " << InsnCleanupFn << "(Inst);\n";
1846
Chris Lattner79ed3f72010-09-06 19:22:17 +00001847 OS << " return Match_Success;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001848 OS << " }\n\n";
1849
Chris Lattnerec6789f2010-09-06 20:08:02 +00001850 OS << " // Okay, we had no match. Try to return a useful error code.\n";
1851 OS << " if (HadMatchOtherThanFeatures) return Match_MissingFeature;\n";
Chris Lattnera008e8a2010-09-06 21:54:15 +00001852 OS << " return Match_InvalidOperand;\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00001853 OS << "}\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001854
Chris Lattner0692ee62010-09-06 19:11:01 +00001855 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbard51ffcf2009-07-11 19:39:44 +00001856}