blob: 39a3c25d99dac5cf8876b9bc2c69760ce578690d [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
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +000011// assembly operands in the MCInst structures. It also emits a matcher for
12// custom operand parsing.
13//
14// Converting assembly operands into MCInst structures
15// ---------------------------------------------------
Daniel Dunbard51ffcf2009-07-11 19:39:44 +000016//
Daniel Dunbar20927f22009-08-07 08:26:05 +000017// The input to the target specific matcher is a list of literal tokens and
18// operands. The target specific parser should generally eliminate any syntax
19// which is not relevant for matching; for example, comma tokens should have
20// already been consumed and eliminated by the parser. Most instructions will
21// end up with a single literal token (the instruction name) and some number of
22// operands.
23//
24// Some example inputs, for X86:
25// 'addl' (immediate ...) (register ...)
26// 'add' (immediate ...) (memory ...)
Jim Grosbacha7c78222010-10-29 22:13:48 +000027// 'call' '*' %epc
Daniel Dunbar20927f22009-08-07 08:26:05 +000028//
29// The assembly matcher is responsible for converting this input into a precise
30// machine instruction (i.e., an instruction with a well defined encoding). This
31// mapping has several properties which complicate matching:
32//
33// - It may be ambiguous; many architectures can legally encode particular
34// variants of an instruction in different ways (for example, using a smaller
35// encoding for small immediates). Such ambiguities should never be
36// arbitrarily resolved by the assembler, the assembler is always responsible
37// for choosing the "best" available instruction.
38//
39// - It may depend on the subtarget or the assembler context. Instructions
40// which are invalid for the current mode, but otherwise unambiguous (e.g.,
41// an SSE instruction in a file being assembled for i486) should be accepted
42// and rejected by the assembler front end. However, if the proper encoding
43// for an instruction is dependent on the assembler context then the matcher
44// is responsible for selecting the correct machine instruction for the
45// current mode.
46//
47// The core matching algorithm attempts to exploit the regularity in most
48// instruction sets to quickly determine the set of possibly matching
49// instructions, and the simplify the generated code. Additionally, this helps
50// to ensure that the ambiguities are intentionally resolved by the user.
51//
52// The matching is divided into two distinct phases:
53//
54// 1. Classification: Each operand is mapped to the unique set which (a)
55// contains it, and (b) is the largest such subset for which a single
56// instruction could match all members.
57//
58// For register classes, we can generate these subgroups automatically. For
59// arbitrary operands, we expect the user to define the classes and their
60// relations to one another (for example, 8-bit signed immediates as a
61// subset of 32-bit immediates).
62//
63// By partitioning the operands in this way, we guarantee that for any
64// tuple of classes, any single instruction must match either all or none
65// of the sets of operands which could classify to that tuple.
66//
67// In addition, the subset relation amongst classes induces a partial order
68// on such tuples, which we use to resolve ambiguities.
69//
Daniel Dunbar20927f22009-08-07 08:26:05 +000070// 2. The input can now be treated as a tuple of classes (static tokens are
71// simple singleton sets). Each such tuple should generally map to a single
72// instruction (we currently ignore cases where this isn't true, whee!!!),
73// which we can emit a simple matcher for.
74//
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +000075// Custom Operand Parsing
76// ----------------------
77//
78// Some targets need a custom way to parse operands, some specific instructions
79// can contain arguments that can represent processor flags and other kinds of
80// identifiers that need to be mapped to specific valeus in the final encoded
81// instructions. The target specific custom operand parsing works in the
82// following way:
83//
84// 1. A operand match table is built, each entry contains a mnemonic, an
85// operand class, a mask for all operand positions for that same
86// class/mnemonic and target features to be checked while trying to match.
87//
88// 2. The operand matcher will try every possible entry with the same
89// mnemonic and will check if the target feature for this mnemonic also
90// matches. After that, if the operand to be matched has its index
Chris Lattner7a2bdde2011-04-15 05:18:47 +000091// present in the mask, a successful match occurs. Otherwise, fallback
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +000092// to the regular operand parsing.
93//
94// 3. For a match success, each operand class that has a 'ParserMethod'
95// becomes part of a switch from where the custom method is called.
96//
Daniel Dunbard51ffcf2009-07-11 19:39:44 +000097//===----------------------------------------------------------------------===//
98
99#include "AsmMatcherEmitter.h"
100#include "CodeGenTarget.h"
Chris Lattner5845e5c2010-09-06 02:01:51 +0000101#include "StringMatcher.h"
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +0000102#include "StringToOffsetTable.h"
Daniel Dunbar20927f22009-08-07 08:26:05 +0000103#include "llvm/ADT/OwningPtr.h"
Chris Lattnerc07bd402010-11-04 02:11:18 +0000104#include "llvm/ADT/PointerUnion.h"
Chris Lattner1de88232010-11-01 01:47:07 +0000105#include "llvm/ADT/SmallPtrSet.h"
Daniel Dunbara027d222009-07-31 02:32:59 +0000106#include "llvm/ADT/SmallVector.h"
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000107#include "llvm/ADT/STLExtras.h"
Daniel Dunbar20927f22009-08-07 08:26:05 +0000108#include "llvm/ADT/StringExtras.h"
109#include "llvm/Support/CommandLine.h"
Daniel Dunbara027d222009-07-31 02:32:59 +0000110#include "llvm/Support/Debug.h"
Craig Topper655b8de2012-02-05 07:21:30 +0000111#include "llvm/Support/ErrorHandling.h"
Peter Collingbourne7c788882011-10-01 16:41:13 +0000112#include "llvm/TableGen/Error.h"
113#include "llvm/TableGen/Record.h"
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000114#include <map>
115#include <set>
Daniel Dunbard51ffcf2009-07-11 19:39:44 +0000116using namespace llvm;
117
Daniel Dunbar27249152009-08-07 20:33:39 +0000118static cl::opt<std::string>
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000119MatchPrefix("match-prefix", cl::init(""),
120 cl::desc("Only match instructions with the given prefix"));
Daniel Dunbar20927f22009-08-07 08:26:05 +0000121
Daniel Dunbar20927f22009-08-07 08:26:05 +0000122namespace {
Bob Wilson828295b2011-01-26 21:26:19 +0000123class AsmMatcherInfo;
Daniel Dunbar54074b52010-07-19 05:44:09 +0000124struct SubtargetFeatureInfo;
125
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000126/// ClassInfo - Helper class for storing the information about a particular
127/// class of operands which can be matched.
128struct ClassInfo {
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000129 enum ClassInfoKind {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000130 /// Invalid kind, for use as a sentinel value.
131 Invalid = 0,
132
133 /// The class for a particular token.
134 Token,
135
136 /// The (first) register class, subsequent register classes are
137 /// RegisterClass0+1, and so on.
138 RegisterClass0,
139
140 /// The (first) user defined class, subsequent user defined classes are
141 /// UserClass0+1, and so on.
142 UserClass0 = 1<<16
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000143 };
144
145 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
146 /// N) for the Nth user defined class.
147 unsigned Kind;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000148
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000149 /// SuperClasses - The super classes of this class. Note that for simplicities
150 /// sake user operands only record their immediate super class, while register
151 /// operands include all superclasses.
152 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000153
Daniel Dunbar6745d422009-08-09 05:18:30 +0000154 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000155 std::string Name;
156
Daniel Dunbar6745d422009-08-09 05:18:30 +0000157 /// ClassName - The unadorned generic name for this class (e.g., Token).
158 std::string ClassName;
159
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000160 /// ValueName - The name of the value this class represents; for a token this
161 /// is the literal token string, for an operand it is the TableGen class (or
162 /// empty if this is a derived class).
163 std::string ValueName;
164
165 /// PredicateMethod - The name of the operand method to test whether the
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000166 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000167 std::string PredicateMethod;
168
169 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000170 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000171 std::string RenderMethod;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000172
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000173 /// ParserMethod - The name of the operand method to do a target specific
174 /// parsing on the operand.
175 std::string ParserMethod;
176
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000177 /// For register classes, the records for all the registers in this class.
178 std::set<Record*> Registers;
179
180public:
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000181 /// isRegisterClass() - Check if this is a register class.
182 bool isRegisterClass() const {
183 return Kind >= RegisterClass0 && Kind < UserClass0;
184 }
185
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000186 /// isUserClass() - Check if this is a user defined class.
187 bool isUserClass() const {
188 return Kind >= UserClass0;
189 }
190
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000191 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
192 /// are related if they are in the same class hierarchy.
193 bool isRelatedTo(const ClassInfo &RHS) const {
194 // Tokens are only related to tokens.
195 if (Kind == Token || RHS.Kind == Token)
196 return Kind == Token && RHS.Kind == Token;
197
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000198 // Registers classes are only related to registers classes, and only if
199 // their intersection is non-empty.
200 if (isRegisterClass() || RHS.isRegisterClass()) {
201 if (!isRegisterClass() || !RHS.isRegisterClass())
202 return false;
203
204 std::set<Record*> Tmp;
205 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
Jim Grosbacha7c78222010-10-29 22:13:48 +0000206 std::set_intersection(Registers.begin(), Registers.end(),
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000207 RHS.Registers.begin(), RHS.Registers.end(),
208 II);
209
210 return !Tmp.empty();
211 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000212
213 // Otherwise we have two users operands; they are related if they are in the
214 // same class hierarchy.
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000215 //
216 // FIXME: This is an oversimplification, they should only be related if they
217 // intersect, however we don't have that information.
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000218 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
219 const ClassInfo *Root = this;
220 while (!Root->SuperClasses.empty())
221 Root = Root->SuperClasses.front();
222
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000223 const ClassInfo *RHSRoot = &RHS;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000224 while (!RHSRoot->SuperClasses.empty())
225 RHSRoot = RHSRoot->SuperClasses.front();
Jim Grosbacha7c78222010-10-29 22:13:48 +0000226
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000227 return Root == RHSRoot;
228 }
229
Jim Grosbacha7c78222010-10-29 22:13:48 +0000230 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000231 bool isSubsetOf(const ClassInfo &RHS) const {
232 // This is a subset of RHS if it is the same class...
233 if (this == &RHS)
234 return true;
235
236 // ... or if any of its super classes are a subset of RHS.
237 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
238 ie = SuperClasses.end(); it != ie; ++it)
239 if ((*it)->isSubsetOf(RHS))
240 return true;
241
242 return false;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000243 }
244
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000245 /// operator< - Compare two classes.
246 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar368a4562010-05-27 05:31:32 +0000247 if (this == &RHS)
248 return false;
249
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000250 // Unrelated classes can be ordered by kind.
251 if (!isRelatedTo(RHS))
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000252 return Kind < RHS.Kind;
253
254 switch (Kind) {
Daniel Dunbar6745d422009-08-09 05:18:30 +0000255 case Invalid:
Craig Topper655b8de2012-02-05 07:21:30 +0000256 llvm_unreachable("Invalid kind!");
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000257
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000258 default:
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000259 // This class precedes the RHS if it is a proper subset of the RHS.
Daniel Dunbar368a4562010-05-27 05:31:32 +0000260 if (isSubsetOf(RHS))
Duncan Sands34727662010-07-12 08:16:59 +0000261 return true;
Daniel Dunbar368a4562010-05-27 05:31:32 +0000262 if (RHS.isSubsetOf(*this))
Duncan Sands34727662010-07-12 08:16:59 +0000263 return false;
Daniel Dunbar368a4562010-05-27 05:31:32 +0000264
265 // Otherwise, order by name to ensure we have a total ordering.
266 return ValueName < RHS.ValueName;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000267 }
268 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000269};
270
Chris Lattner22bc5c42010-11-01 05:06:45 +0000271/// MatchableInfo - Helper class for storing the necessary information for an
272/// instruction or alias which is capable of being matched.
273struct MatchableInfo {
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000274 struct AsmOperand {
Chris Lattnerd19ec052010-11-02 17:30:52 +0000275 /// Token - This is the token that the operand came from.
276 StringRef Token;
Bob Wilson828295b2011-01-26 21:26:19 +0000277
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000278 /// The unique class instance this operand should match.
279 ClassInfo *Class;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000280
Chris Lattner567820c2010-11-04 01:42:59 +0000281 /// The operand name this is, if anything.
282 StringRef SrcOpName;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000283
284 /// The suboperand index within SrcOpName, or -1 for the entire operand.
285 int SubOpIdx;
Bob Wilson828295b2011-01-26 21:26:19 +0000286
Devang Patel63faf822012-01-07 01:33:34 +0000287 /// Register record if this token is singleton register.
288 Record *SingletonReg;
289
Jim Grosbachf35307c2012-01-24 21:06:59 +0000290 explicit AsmOperand(StringRef T) : Token(T), Class(0), SubOpIdx(-1),
Jim Grosbach11fc6462012-04-11 21:02:33 +0000291 SingletonReg(0) {}
Daniel Dunbar20927f22009-08-07 08:26:05 +0000292 };
Bob Wilson828295b2011-01-26 21:26:19 +0000293
Chris Lattner1d13bda2010-11-04 00:43:46 +0000294 /// ResOperand - This represents a single operand in the result instruction
295 /// generated by the match. In cases (like addressing modes) where a single
296 /// assembler operand expands to multiple MCOperands, this represents the
297 /// single assembler operand, not the MCOperand.
298 struct ResOperand {
299 enum {
300 /// RenderAsmOperand - This represents an operand result that is
301 /// generated by calling the render method on the assembly operand. The
302 /// corresponding AsmOperand is specified by AsmOperandNum.
303 RenderAsmOperand,
Bob Wilson828295b2011-01-26 21:26:19 +0000304
Chris Lattner1d13bda2010-11-04 00:43:46 +0000305 /// TiedOperand - This represents a result operand that is a duplicate of
306 /// a previous result operand.
Chris Lattner98c870f2010-11-06 19:25:43 +0000307 TiedOperand,
Bob Wilson828295b2011-01-26 21:26:19 +0000308
Chris Lattner98c870f2010-11-06 19:25:43 +0000309 /// ImmOperand - This represents an immediate value that is dumped into
310 /// the operand.
Chris Lattner90fd7972010-11-06 19:57:21 +0000311 ImmOperand,
Bob Wilson828295b2011-01-26 21:26:19 +0000312
Chris Lattner90fd7972010-11-06 19:57:21 +0000313 /// RegOperand - This represents a fixed register that is dumped in.
314 RegOperand
Chris Lattner1d13bda2010-11-04 00:43:46 +0000315 } Kind;
Bob Wilson828295b2011-01-26 21:26:19 +0000316
Chris Lattner1d13bda2010-11-04 00:43:46 +0000317 union {
318 /// This is the operand # in the AsmOperands list that this should be
319 /// copied from.
320 unsigned AsmOperandNum;
Bob Wilson828295b2011-01-26 21:26:19 +0000321
Chris Lattner1d13bda2010-11-04 00:43:46 +0000322 /// TiedOperandNum - This is the (earlier) result operand that should be
323 /// copied from.
324 unsigned TiedOperandNum;
Bob Wilson828295b2011-01-26 21:26:19 +0000325
Chris Lattner98c870f2010-11-06 19:25:43 +0000326 /// ImmVal - This is the immediate value added to the instruction.
327 int64_t ImmVal;
Bob Wilson828295b2011-01-26 21:26:19 +0000328
Chris Lattner90fd7972010-11-06 19:57:21 +0000329 /// Register - This is the register record.
330 Record *Register;
Chris Lattner1d13bda2010-11-04 00:43:46 +0000331 };
Bob Wilson828295b2011-01-26 21:26:19 +0000332
Bob Wilsona49c7df2011-01-26 19:44:55 +0000333 /// MINumOperands - The number of MCInst operands populated by this
334 /// operand.
335 unsigned MINumOperands;
Bob Wilson828295b2011-01-26 21:26:19 +0000336
Bob Wilsona49c7df2011-01-26 19:44:55 +0000337 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
Chris Lattner1d13bda2010-11-04 00:43:46 +0000338 ResOperand X;
339 X.Kind = RenderAsmOperand;
340 X.AsmOperandNum = AsmOpNum;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000341 X.MINumOperands = NumOperands;
Chris Lattner1d13bda2010-11-04 00:43:46 +0000342 return X;
343 }
Bob Wilson828295b2011-01-26 21:26:19 +0000344
Bob Wilsona49c7df2011-01-26 19:44:55 +0000345 static ResOperand getTiedOp(unsigned TiedOperandNum) {
Chris Lattner1d13bda2010-11-04 00:43:46 +0000346 ResOperand X;
347 X.Kind = TiedOperand;
348 X.TiedOperandNum = TiedOperandNum;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000349 X.MINumOperands = 1;
Chris Lattner1d13bda2010-11-04 00:43:46 +0000350 return X;
351 }
Bob Wilson828295b2011-01-26 21:26:19 +0000352
Bob Wilsona49c7df2011-01-26 19:44:55 +0000353 static ResOperand getImmOp(int64_t Val) {
Chris Lattner98c870f2010-11-06 19:25:43 +0000354 ResOperand X;
355 X.Kind = ImmOperand;
356 X.ImmVal = Val;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000357 X.MINumOperands = 1;
Chris Lattner98c870f2010-11-06 19:25:43 +0000358 return X;
359 }
Bob Wilson828295b2011-01-26 21:26:19 +0000360
Bob Wilsona49c7df2011-01-26 19:44:55 +0000361 static ResOperand getRegOp(Record *Reg) {
Chris Lattner90fd7972010-11-06 19:57:21 +0000362 ResOperand X;
363 X.Kind = RegOperand;
364 X.Register = Reg;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000365 X.MINumOperands = 1;
Chris Lattner90fd7972010-11-06 19:57:21 +0000366 return X;
367 }
Chris Lattner1d13bda2010-11-04 00:43:46 +0000368 };
Daniel Dunbar20927f22009-08-07 08:26:05 +0000369
Devang Patel56315d32012-01-10 17:50:43 +0000370 /// AsmVariantID - Target's assembly syntax variant no.
371 int AsmVariantID;
372
Chris Lattner3b5aec62010-11-02 17:34:28 +0000373 /// TheDef - This is the definition of the instruction or InstAlias that this
374 /// matchable came from.
Chris Lattner5bc93872010-11-01 04:34:44 +0000375 Record *const TheDef;
Bob Wilson828295b2011-01-26 21:26:19 +0000376
Chris Lattnerc07bd402010-11-04 02:11:18 +0000377 /// DefRec - This is the definition that it came from.
378 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
Bob Wilson828295b2011-01-26 21:26:19 +0000379
Chris Lattner662e5a32010-11-06 07:14:44 +0000380 const CodeGenInstruction *getResultInst() const {
381 if (DefRec.is<const CodeGenInstruction*>())
382 return DefRec.get<const CodeGenInstruction*>();
383 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
384 }
Bob Wilson828295b2011-01-26 21:26:19 +0000385
Chris Lattner1d13bda2010-11-04 00:43:46 +0000386 /// ResOperands - This is the operand list that should be built for the result
387 /// MCInst.
388 std::vector<ResOperand> ResOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000389
390 /// AsmString - The assembly string for this instruction (with variants
Chris Lattner3b5aec62010-11-02 17:34:28 +0000391 /// removed), e.g. "movsx $src, $dst".
Daniel Dunbar20927f22009-08-07 08:26:05 +0000392 std::string AsmString;
393
Chris Lattnerd19ec052010-11-02 17:30:52 +0000394 /// Mnemonic - This is the first token of the matched instruction, its
395 /// mnemonic.
396 StringRef Mnemonic;
Bob Wilson828295b2011-01-26 21:26:19 +0000397
Chris Lattner3116fef2010-11-02 01:03:43 +0000398 /// AsmOperands - The textual operands that this instruction matches,
Chris Lattner3b5aec62010-11-02 17:34:28 +0000399 /// annotated with a class and where in the OperandList they were defined.
400 /// This directly corresponds to the tokenized AsmString after the mnemonic is
401 /// removed.
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000402 SmallVector<AsmOperand, 4> AsmOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000403
Daniel Dunbar54074b52010-07-19 05:44:09 +0000404 /// Predicates - The required subtarget features to match this instruction.
405 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
406
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000407 /// ConversionFnKind - The enum value which is passed to the generated
408 /// ConvertToMCInst to convert parsed operands into an MCInst for this
409 /// function.
410 std::string ConversionFnKind;
Bob Wilson828295b2011-01-26 21:26:19 +0000411
Chris Lattner22bc5c42010-11-01 05:06:45 +0000412 MatchableInfo(const CodeGenInstruction &CGI)
Jim Grosbachf35307c2012-01-24 21:06:59 +0000413 : AsmVariantID(0), TheDef(CGI.TheDef), DefRec(&CGI),
Devang Patel56315d32012-01-10 17:50:43 +0000414 AsmString(CGI.AsmString) {
Chris Lattner5bc93872010-11-01 04:34:44 +0000415 }
416
Chris Lattner22bc5c42010-11-01 05:06:45 +0000417 MatchableInfo(const CodeGenInstAlias *Alias)
Jim Grosbachf35307c2012-01-24 21:06:59 +0000418 : AsmVariantID(0), TheDef(Alias->TheDef), DefRec(Alias),
Devang Patel56315d32012-01-10 17:50:43 +0000419 AsmString(Alias->AsmString) {
Chris Lattnerc2d67bb2010-11-01 04:53:48 +0000420 }
Bob Wilson828295b2011-01-26 21:26:19 +0000421
Chris Lattnerc2d67bb2010-11-01 04:53:48 +0000422 void Initialize(const AsmMatcherInfo &Info,
Jim Grosbachf35307c2012-01-24 21:06:59 +0000423 SmallPtrSet<Record*, 16> &SingletonRegisters,
Jim Grosbach11fc6462012-04-11 21:02:33 +0000424 int AsmVariantNo, std::string &RegisterPrefix);
Bob Wilson828295b2011-01-26 21:26:19 +0000425
Chris Lattner22bc5c42010-11-01 05:06:45 +0000426 /// Validate - Return true if this matchable is a valid thing to match against
427 /// and perform a bunch of validity checking.
428 bool Validate(StringRef CommentDelimiter, bool Hack) const;
Bob Wilson828295b2011-01-26 21:26:19 +0000429
Jim Grosbachf35307c2012-01-24 21:06:59 +0000430 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
Devang Patel63faf822012-01-07 01:33:34 +0000431 /// if present, from specified token.
432 void
433 extractSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info,
434 std::string &RegisterPrefix);
Daniel Dunbar20927f22009-08-07 08:26:05 +0000435
Bob Wilsona49c7df2011-01-26 19:44:55 +0000436 /// FindAsmOperand - Find the AsmOperand with the specified name and
437 /// suboperand index.
438 int FindAsmOperand(StringRef N, int SubOpIdx) const {
439 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
440 if (N == AsmOperands[i].SrcOpName &&
441 SubOpIdx == AsmOperands[i].SubOpIdx)
442 return i;
443 return -1;
444 }
Bob Wilson828295b2011-01-26 21:26:19 +0000445
Bob Wilsona49c7df2011-01-26 19:44:55 +0000446 /// FindAsmOperandNamed - Find the first AsmOperand with the specified name.
447 /// This does not check the suboperand index.
Chris Lattnerba3b5b62010-11-04 01:55:23 +0000448 int FindAsmOperandNamed(StringRef N) const {
449 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
450 if (N == AsmOperands[i].SrcOpName)
451 return i;
452 return -1;
453 }
Bob Wilson828295b2011-01-26 21:26:19 +0000454
Chris Lattner41409852010-11-06 07:31:43 +0000455 void BuildInstructionResultOperands();
456 void BuildAliasResultOperands();
Chris Lattner1d13bda2010-11-04 00:43:46 +0000457
Chris Lattner22bc5c42010-11-01 05:06:45 +0000458 /// operator< - Compare two matchables.
459 bool operator<(const MatchableInfo &RHS) const {
Chris Lattnere206fcf2010-09-06 21:01:37 +0000460 // The primary comparator is the instruction mnemonic.
Chris Lattnerd19ec052010-11-02 17:30:52 +0000461 if (Mnemonic != RHS.Mnemonic)
462 return Mnemonic < RHS.Mnemonic;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000463
Chris Lattner3116fef2010-11-02 01:03:43 +0000464 if (AsmOperands.size() != RHS.AsmOperands.size())
465 return AsmOperands.size() < RHS.AsmOperands.size();
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000466
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000467 // Compare lexicographically by operand. The matcher validates that other
Bob Wilson1f64ac42011-01-26 21:26:21 +0000468 // orderings wouldn't be ambiguous using \see CouldMatchAmbiguouslyWith().
Chris Lattner3116fef2010-11-02 01:03:43 +0000469 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
470 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000471 return true;
Chris Lattner3116fef2010-11-02 01:03:43 +0000472 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000473 return false;
474 }
475
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000476 return false;
477 }
478
Bob Wilson1f64ac42011-01-26 21:26:21 +0000479 /// CouldMatchAmbiguouslyWith - Check whether this matchable could
Daniel Dunbar2b544812009-08-09 06:05:33 +0000480 /// ambiguously match the same set of operands as \arg RHS (without being a
481 /// strictly superior match).
Bob Wilson1f64ac42011-01-26 21:26:21 +0000482 bool CouldMatchAmbiguouslyWith(const MatchableInfo &RHS) {
Chris Lattnere66b7eb2010-11-01 23:57:23 +0000483 // The primary comparator is the instruction mnemonic.
Chris Lattnerd19ec052010-11-02 17:30:52 +0000484 if (Mnemonic != RHS.Mnemonic)
Chris Lattnere66b7eb2010-11-01 23:57:23 +0000485 return false;
Bob Wilson828295b2011-01-26 21:26:19 +0000486
Daniel Dunbar2b544812009-08-09 06:05:33 +0000487 // The number of operands is unambiguous.
Chris Lattner3116fef2010-11-02 01:03:43 +0000488 if (AsmOperands.size() != RHS.AsmOperands.size())
Daniel Dunbar2b544812009-08-09 06:05:33 +0000489 return false;
490
Daniel Dunbar1402f0b2010-01-23 00:26:16 +0000491 // Otherwise, make sure the ordering of the two instructions is unambiguous
492 // by checking that either (a) a token or operand kind discriminates them,
493 // or (b) the ordering among equivalent kinds is consistent.
494
Daniel Dunbar2b544812009-08-09 06:05:33 +0000495 // Tokens and operand kinds are unambiguous (assuming a correct target
496 // specific parser).
Chris Lattner3116fef2010-11-02 01:03:43 +0000497 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
498 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
499 AsmOperands[i].Class->Kind == ClassInfo::Token)
500 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
501 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbar2b544812009-08-09 06:05:33 +0000502 return false;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000503
Daniel Dunbar2b544812009-08-09 06:05:33 +0000504 // Otherwise, this operand could commute if all operands are equivalent, or
505 // there is a pair of operands that compare less than and a pair that
506 // compare greater than.
507 bool HasLT = false, HasGT = false;
Chris Lattner3116fef2010-11-02 01:03:43 +0000508 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
509 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbar2b544812009-08-09 06:05:33 +0000510 HasLT = true;
Chris Lattner3116fef2010-11-02 01:03:43 +0000511 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbar2b544812009-08-09 06:05:33 +0000512 HasGT = true;
513 }
514
515 return !(HasLT ^ HasGT);
516 }
517
Daniel Dunbar20927f22009-08-07 08:26:05 +0000518 void dump();
Bob Wilson828295b2011-01-26 21:26:19 +0000519
Chris Lattnerd19ec052010-11-02 17:30:52 +0000520private:
521 void TokenizeAsmString(const AsmMatcherInfo &Info);
Daniel Dunbar20927f22009-08-07 08:26:05 +0000522};
523
Daniel Dunbar54074b52010-07-19 05:44:09 +0000524/// SubtargetFeatureInfo - Helper class for storing information on a subtarget
525/// feature which participates in instruction matching.
526struct SubtargetFeatureInfo {
527 /// \brief The predicate record for this feature.
528 Record *TheDef;
529
530 /// \brief An unique index assigned to represent this feature.
531 unsigned Index;
532
Chris Lattner0aed1e72010-10-30 20:07:57 +0000533 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
Bob Wilson828295b2011-01-26 21:26:19 +0000534
Daniel Dunbar54074b52010-07-19 05:44:09 +0000535 /// \brief The name of the enumerated constant identifying this feature.
Chris Lattner0aed1e72010-10-30 20:07:57 +0000536 std::string getEnumName() const {
537 return "Feature_" + TheDef->getName();
538 }
Daniel Dunbar54074b52010-07-19 05:44:09 +0000539};
540
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000541struct OperandMatchEntry {
542 unsigned OperandMask;
543 MatchableInfo* MI;
544 ClassInfo *CI;
545
546 static OperandMatchEntry Create(MatchableInfo* mi, ClassInfo *ci,
547 unsigned opMask) {
548 OperandMatchEntry X;
549 X.OperandMask = opMask;
550 X.CI = ci;
551 X.MI = mi;
552 return X;
553 }
554};
555
556
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000557class AsmMatcherInfo {
558public:
Chris Lattner67db8832010-12-13 00:23:57 +0000559 /// Tracked Records
Chris Lattner9c6b60e2010-12-15 04:48:22 +0000560 RecordKeeper &Records;
Chris Lattner67db8832010-12-13 00:23:57 +0000561
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000562 /// The tablegen AsmParser record.
563 Record *AsmParser;
564
Chris Lattner02bcbc92010-11-01 01:37:30 +0000565 /// Target - The target information.
566 CodeGenTarget &Target;
567
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000568 /// The classes which are needed for matching.
569 std::vector<ClassInfo*> Classes;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000570
Chris Lattner22bc5c42010-11-01 05:06:45 +0000571 /// The information on the matchables to match.
572 std::vector<MatchableInfo*> Matchables;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000573
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000574 /// Info for custom matching operands by user defined methods.
575 std::vector<OperandMatchEntry> OperandMatchInfo;
576
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000577 /// Map of Register records to their class information.
578 std::map<Record*, ClassInfo*> RegisterClasses;
579
Daniel Dunbar54074b52010-07-19 05:44:09 +0000580 /// Map of Predicate records to their subtarget information.
581 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
Bob Wilson828295b2011-01-26 21:26:19 +0000582
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000583private:
584 /// Map of token to class information which has already been constructed.
585 std::map<std::string, ClassInfo*> TokenClasses;
586
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000587 /// Map of RegisterClass records to their class information.
588 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000589
Daniel Dunbar338825c2009-08-10 18:41:10 +0000590 /// Map of AsmOperandClass records to their class information.
591 std::map<Record*, ClassInfo*> AsmOperandClasses;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000592
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000593private:
594 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000595 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000596
597 /// getOperandClass - Lookup or create the class for the given operand.
Bob Wilsona49c7df2011-01-26 19:44:55 +0000598 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
Jim Grosbach48c1f842011-10-28 22:32:53 +0000599 int SubOpIdx);
600 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000601
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000602 /// BuildRegisterClasses - Build the ClassInfo* instances for register
603 /// classes.
Chris Lattner1de88232010-11-01 01:47:07 +0000604 void BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000605
606 /// BuildOperandClasses - Build the ClassInfo* instances for user defined
607 /// operand classes.
Chris Lattner02bcbc92010-11-01 01:37:30 +0000608 void BuildOperandClasses();
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000609
Bob Wilsona49c7df2011-01-26 19:44:55 +0000610 void BuildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
611 unsigned AsmOpIdx);
612 void BuildAliasOperandReference(MatchableInfo *II, StringRef OpName,
Chris Lattnerc07bd402010-11-04 02:11:18 +0000613 MatchableInfo::AsmOperand &Op);
Bob Wilson828295b2011-01-26 21:26:19 +0000614
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000615public:
Bob Wilson828295b2011-01-26 21:26:19 +0000616 AsmMatcherInfo(Record *AsmParser,
617 CodeGenTarget &Target,
Chris Lattner9c6b60e2010-12-15 04:48:22 +0000618 RecordKeeper &Records);
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000619
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000620 /// BuildInfo - Construct the various tables used during matching.
Chris Lattner02bcbc92010-11-01 01:37:30 +0000621 void BuildInfo();
Bob Wilson828295b2011-01-26 21:26:19 +0000622
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000623 /// BuildOperandMatchInfo - Build the necessary information to handle user
624 /// defined operand parsing methods.
625 void BuildOperandMatchInfo();
626
Chris Lattner6fa152c2010-10-30 20:15:02 +0000627 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
628 /// given operand.
629 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
630 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
631 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
632 SubtargetFeatures.find(Def);
633 return I == SubtargetFeatures.end() ? 0 : I->second;
634 }
Chris Lattner67db8832010-12-13 00:23:57 +0000635
Chris Lattner9c6b60e2010-12-15 04:48:22 +0000636 RecordKeeper &getRecords() const {
637 return Records;
Chris Lattner67db8832010-12-13 00:23:57 +0000638 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000639};
640
Daniel Dunbar20927f22009-08-07 08:26:05 +0000641}
642
Chris Lattner22bc5c42010-11-01 05:06:45 +0000643void MatchableInfo::dump() {
Chris Lattner5abd1eb2010-11-06 06:43:11 +0000644 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +0000645
Chris Lattner3116fef2010-11-02 01:03:43 +0000646 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000647 AsmOperand &Op = AsmOperands[i];
Daniel Dunbar6745d422009-08-09 05:18:30 +0000648 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Chris Lattner0bb780c2010-11-04 00:57:06 +0000649 errs() << '\"' << Op.Token << "\"\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +0000650 }
651}
652
Chris Lattner22bc5c42010-11-01 05:06:45 +0000653void MatchableInfo::Initialize(const AsmMatcherInfo &Info,
Devang Patel63faf822012-01-07 01:33:34 +0000654 SmallPtrSet<Record*, 16> &SingletonRegisters,
655 int AsmVariantNo, std::string &RegisterPrefix) {
Devang Patel56315d32012-01-10 17:50:43 +0000656 AsmVariantID = AsmVariantNo;
Jim Grosbachf35307c2012-01-24 21:06:59 +0000657 AsmString =
Devang Patel63faf822012-01-07 01:33:34 +0000658 CodeGenInstruction::FlattenAsmStringVariants(AsmString, AsmVariantNo);
Bob Wilson828295b2011-01-26 21:26:19 +0000659
Chris Lattnerd19ec052010-11-02 17:30:52 +0000660 TokenizeAsmString(Info);
Bob Wilson828295b2011-01-26 21:26:19 +0000661
Chris Lattnerc2d67bb2010-11-01 04:53:48 +0000662 // Compute the require features.
663 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates");
664 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
665 if (SubtargetFeatureInfo *Feature =
666 Info.getSubtargetFeature(Predicates[i]))
667 RequiredFeatures.push_back(Feature);
Bob Wilson828295b2011-01-26 21:26:19 +0000668
Chris Lattnerc2d67bb2010-11-01 04:53:48 +0000669 // Collect singleton registers, if used.
Chris Lattnerd19ec052010-11-02 17:30:52 +0000670 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
Devang Patel63faf822012-01-07 01:33:34 +0000671 extractSingletonRegisterForAsmOperand(i, Info, RegisterPrefix);
672 if (Record *Reg = AsmOperands[i].SingletonReg)
Chris Lattnerc2d67bb2010-11-01 04:53:48 +0000673 SingletonRegisters.insert(Reg);
674 }
675}
676
Chris Lattnerd19ec052010-11-02 17:30:52 +0000677/// TokenizeAsmString - Tokenize a simplified assembly string.
678void MatchableInfo::TokenizeAsmString(const AsmMatcherInfo &Info) {
679 StringRef String = AsmString;
680 unsigned Prev = 0;
681 bool InTok = true;
682 for (unsigned i = 0, e = String.size(); i != e; ++i) {
683 switch (String[i]) {
684 case '[':
685 case ']':
686 case '*':
687 case '!':
688 case ' ':
689 case '\t':
690 case ',':
691 if (InTok) {
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000692 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000693 InTok = false;
694 }
695 if (!isspace(String[i]) && String[i] != ',')
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000696 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000697 Prev = i + 1;
698 break;
699
700 case '\\':
701 if (InTok) {
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000702 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000703 InTok = false;
704 }
705 ++i;
706 assert(i != String.size() && "Invalid quoted character");
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000707 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000708 Prev = i + 1;
709 break;
710
711 case '$': {
Chris Lattnerd19ec052010-11-02 17:30:52 +0000712 if (InTok) {
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000713 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000714 InTok = false;
715 }
Bob Wilson828295b2011-01-26 21:26:19 +0000716
Chris Lattner7ad31472010-11-06 22:06:03 +0000717 // If this isn't "${", treat like a normal token.
718 if (i + 1 == String.size() || String[i + 1] != '{') {
719 Prev = i;
720 break;
721 }
Chris Lattnerd19ec052010-11-02 17:30:52 +0000722
723 StringRef::iterator End = std::find(String.begin() + i, String.end(),'}');
724 assert(End != String.end() && "Missing brace in operand reference!");
725 size_t EndPos = End - String.begin();
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000726 AsmOperands.push_back(AsmOperand(String.slice(i, EndPos+1)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000727 Prev = EndPos + 1;
728 i = EndPos;
729 break;
730 }
731
732 case '.':
733 if (InTok)
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000734 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000735 Prev = i;
736 InTok = true;
737 break;
738
739 default:
740 InTok = true;
741 }
742 }
743 if (InTok && Prev != String.size())
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000744 AsmOperands.push_back(AsmOperand(String.substr(Prev)));
Bob Wilson828295b2011-01-26 21:26:19 +0000745
Chris Lattnerd19ec052010-11-02 17:30:52 +0000746 // The first token of the instruction is the mnemonic, which must be a
747 // simple string, not a $foo variable or a singleton register.
Jim Grosbach4a2242c2011-11-30 23:16:25 +0000748 if (AsmOperands.empty())
749 throw TGError(TheDef->getLoc(),
750 "Instruction '" + TheDef->getName() + "' has no tokens");
Chris Lattnerd19ec052010-11-02 17:30:52 +0000751 Mnemonic = AsmOperands[0].Token;
Devang Patel63faf822012-01-07 01:33:34 +0000752 // FIXME : Check and raise an error if it is a register.
Devang Patelb78307f2012-01-07 01:22:23 +0000753 if (Mnemonic[0] == '$')
Chris Lattnerd19ec052010-11-02 17:30:52 +0000754 throw TGError(TheDef->getLoc(),
755 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
Bob Wilson828295b2011-01-26 21:26:19 +0000756
Chris Lattnerd19ec052010-11-02 17:30:52 +0000757 // Remove the first operand, it is tracked in the mnemonic field.
758 AsmOperands.erase(AsmOperands.begin());
759}
760
Chris Lattner22bc5c42010-11-01 05:06:45 +0000761bool MatchableInfo::Validate(StringRef CommentDelimiter, bool Hack) const {
762 // Reject matchables with no .s string.
Chris Lattner5bc93872010-11-01 04:34:44 +0000763 if (AsmString.empty())
764 throw TGError(TheDef->getLoc(), "instruction with empty asm string");
Bob Wilson828295b2011-01-26 21:26:19 +0000765
Chris Lattner22bc5c42010-11-01 05:06:45 +0000766 // Reject any matchables with a newline in them, they should be marked
Chris Lattner5bc93872010-11-01 04:34:44 +0000767 // isCodeGenOnly if they are pseudo instructions.
768 if (AsmString.find('\n') != std::string::npos)
769 throw TGError(TheDef->getLoc(),
770 "multiline instruction is not valid for the asmparser, "
771 "mark it isCodeGenOnly");
Bob Wilson828295b2011-01-26 21:26:19 +0000772
Chris Lattner4164f6b2010-11-01 04:44:29 +0000773 // Remove comments from the asm string. We know that the asmstring only
774 // has one line.
775 if (!CommentDelimiter.empty() &&
776 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
777 throw TGError(TheDef->getLoc(),
778 "asmstring for instruction has comment character in it, "
779 "mark it isCodeGenOnly");
Bob Wilson828295b2011-01-26 21:26:19 +0000780
Chris Lattner22bc5c42010-11-01 05:06:45 +0000781 // Reject matchables with operand modifiers, these aren't something we can
Bob Wilson906bc362011-01-20 18:38:07 +0000782 // handle, the target should be refactored to use operands instead of
783 // modifiers.
Chris Lattner5bc93872010-11-01 04:34:44 +0000784 //
785 // Also, check for instructions which reference the operand multiple times;
786 // this implies a constraint we would not honor.
787 std::set<std::string> OperandNames;
Chris Lattnerd19ec052010-11-02 17:30:52 +0000788 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
789 StringRef Tok = AsmOperands[i].Token;
790 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
Chris Lattner5bc93872010-11-01 04:34:44 +0000791 throw TGError(TheDef->getLoc(),
Chris Lattnerd19ec052010-11-02 17:30:52 +0000792 "matchable with operand modifier '" + Tok.str() +
Chris Lattner5bc93872010-11-01 04:34:44 +0000793 "' not supported by asm matcher. Mark isCodeGenOnly!");
Bob Wilson828295b2011-01-26 21:26:19 +0000794
Chris Lattner22bc5c42010-11-01 05:06:45 +0000795 // Verify that any operand is only mentioned once.
Chris Lattnerd51257a2010-11-02 23:18:43 +0000796 // We reject aliases and ignore instructions for now.
Chris Lattnerd19ec052010-11-02 17:30:52 +0000797 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
Chris Lattner22bc5c42010-11-01 05:06:45 +0000798 if (!Hack)
799 throw TGError(TheDef->getLoc(),
Chris Lattnerd19ec052010-11-02 17:30:52 +0000800 "ERROR: matchable with tied operand '" + Tok.str() +
Chris Lattner22bc5c42010-11-01 05:06:45 +0000801 "' can never be matched!");
802 // FIXME: Should reject these. The ARM backend hits this with $lane in a
803 // bunch of instructions. It is unclear what the right answer is.
Chris Lattner5bc93872010-11-01 04:34:44 +0000804 DEBUG({
Chris Lattner5abd1eb2010-11-06 06:43:11 +0000805 errs() << "warning: '" << TheDef->getName() << "': "
Chris Lattner22bc5c42010-11-01 05:06:45 +0000806 << "ignoring instruction with tied operand '"
Chris Lattnerd19ec052010-11-02 17:30:52 +0000807 << Tok.str() << "'\n";
Chris Lattner5bc93872010-11-01 04:34:44 +0000808 });
809 return false;
810 }
811 }
Bob Wilson828295b2011-01-26 21:26:19 +0000812
Chris Lattner5bc93872010-11-01 04:34:44 +0000813 return true;
814}
815
Jim Grosbachf35307c2012-01-24 21:06:59 +0000816/// extractSingletonRegisterForAsmOperand - Extract singleton register,
Devang Pateld06b01c2012-01-09 21:30:46 +0000817/// if present, from specified token.
Devang Patel63faf822012-01-07 01:33:34 +0000818void MatchableInfo::
Jim Grosbachf35307c2012-01-24 21:06:59 +0000819extractSingletonRegisterForAsmOperand(unsigned OperandNo,
Devang Pateld06b01c2012-01-09 21:30:46 +0000820 const AsmMatcherInfo &Info,
Jim Grosbach11fc6462012-04-11 21:02:33 +0000821 std::string &RegisterPrefix) {
Devang Pateld06b01c2012-01-09 21:30:46 +0000822 StringRef Tok = AsmOperands[OperandNo].Token;
Devang Patel63faf822012-01-07 01:33:34 +0000823 if (RegisterPrefix.empty()) {
Devang Pateld06b01c2012-01-09 21:30:46 +0000824 std::string LoweredTok = Tok.lower();
825 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
826 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
Devang Patel63faf822012-01-07 01:33:34 +0000827 return;
Jim Grosbachf35307c2012-01-24 21:06:59 +0000828 }
Bob Wilson828295b2011-01-26 21:26:19 +0000829
Devang Patel63faf822012-01-07 01:33:34 +0000830 if (!Tok.startswith(RegisterPrefix))
831 return;
832
833 StringRef RegName = Tok.substr(RegisterPrefix.size());
Chris Lattnerec6f0962010-11-02 18:10:06 +0000834 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
Devang Pateld06b01c2012-01-09 21:30:46 +0000835 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
Bob Wilson828295b2011-01-26 21:26:19 +0000836
Chris Lattner1de88232010-11-01 01:47:07 +0000837 // If there is no register prefix (i.e. "%" in "%eax"), then this may
838 // be some random non-register token, just ignore it.
Devang Patel63faf822012-01-07 01:33:34 +0000839 return;
Chris Lattner02bcbc92010-11-01 01:37:30 +0000840}
841
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000842static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000843 std::string Res;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000844
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000845 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
846 switch (*it) {
847 case '*': Res += "_STAR_"; break;
848 case '%': Res += "_PCT_"; break;
849 case ':': Res += "_COLON_"; break;
Bill Wendlingbd9c77b2010-11-18 23:36:54 +0000850 case '!': Res += "_EXCLAIM_"; break;
Bill Wendling0ef755d2011-01-22 09:44:32 +0000851 case '.': Res += "_DOT_"; break;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000852 default:
Chris Lattner39ee0362010-10-31 19:10:56 +0000853 if (isalnum(*it))
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000854 Res += *it;
Chris Lattner39ee0362010-10-31 19:10:56 +0000855 else
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000856 Res += "_" + utostr((unsigned) *it) + "_";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000857 }
858 }
859
860 return Res;
861}
862
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000863ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000864 ClassInfo *&Entry = TokenClasses[Token];
Jim Grosbacha7c78222010-10-29 22:13:48 +0000865
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000866 if (!Entry) {
867 Entry = new ClassInfo();
868 Entry->Kind = ClassInfo::Token;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000869 Entry->ClassName = "Token";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000870 Entry->Name = "MCK_" + getEnumNameForToken(Token);
871 Entry->ValueName = Token;
872 Entry->PredicateMethod = "<invalid>";
873 Entry->RenderMethod = "<invalid>";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000874 Entry->ParserMethod = "";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000875 Classes.push_back(Entry);
876 }
877
878 return Entry;
879}
880
881ClassInfo *
Bob Wilsona49c7df2011-01-26 19:44:55 +0000882AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
883 int SubOpIdx) {
884 Record *Rec = OI.Rec;
885 if (SubOpIdx != -1)
David Greene05bce0b2011-07-29 22:43:06 +0000886 Rec = dynamic_cast<DefInit*>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
Jim Grosbach48c1f842011-10-28 22:32:53 +0000887 return getOperandClass(Rec, SubOpIdx);
888}
Bob Wilsona49c7df2011-01-26 19:44:55 +0000889
Jim Grosbach48c1f842011-10-28 22:32:53 +0000890ClassInfo *
891AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
Owen Andersonbea6f612011-06-27 21:06:21 +0000892 if (Rec->isSubClassOf("RegisterOperand")) {
893 // RegisterOperand may have an associated ParserMatchClass. If it does,
894 // use it, else just fall back to the underlying register class.
895 const RecordVal *R = Rec->getValue("ParserMatchClass");
896 if (R == 0 || R->getValue() == 0)
897 throw "Record `" + Rec->getName() +
898 "' does not have a ParserMatchClass!\n";
899
David Greene05bce0b2011-07-29 22:43:06 +0000900 if (DefInit *DI= dynamic_cast<DefInit*>(R->getValue())) {
Owen Andersonbea6f612011-06-27 21:06:21 +0000901 Record *MatchClass = DI->getDef();
902 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
903 return CI;
904 }
905
906 // No custom match class. Just use the register class.
907 Record *ClassRec = Rec->getValueAsDef("RegClass");
908 if (!ClassRec)
909 throw TGError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
910 "' has no associated register class!\n");
911 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
912 return CI;
913 throw TGError(Rec->getLoc(), "register class has no class info!");
914 }
915
916
Bob Wilsona49c7df2011-01-26 19:44:55 +0000917 if (Rec->isSubClassOf("RegisterClass")) {
918 if (ClassInfo *CI = RegisterClassClasses[Rec])
Chris Lattnerec6f0962010-11-02 18:10:06 +0000919 return CI;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000920 throw TGError(Rec->getLoc(), "register class has no class info!");
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000921 }
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000922
Bob Wilsona49c7df2011-01-26 19:44:55 +0000923 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
924 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
Chris Lattnerec6f0962010-11-02 18:10:06 +0000925 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
926 return CI;
Daniel Dunbar338825c2009-08-10 18:41:10 +0000927
Bob Wilsona49c7df2011-01-26 19:44:55 +0000928 throw TGError(Rec->getLoc(), "operand has no match class!");
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000929}
930
Chris Lattner1de88232010-11-01 01:47:07 +0000931void AsmMatcherInfo::
932BuildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +0000933 const std::vector<CodeGenRegister*> &Registers =
934 Target.getRegBank().getRegisters();
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +0000935 ArrayRef<CodeGenRegisterClass*> RegClassList =
936 Target.getRegBank().getRegClasses();
Daniel Dunbar338825c2009-08-10 18:41:10 +0000937
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000938 // The register sets used for matching.
939 std::set< std::set<Record*> > RegisterSets;
940
Jim Grosbacha7c78222010-10-29 22:13:48 +0000941 // Gather the defined sets.
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +0000942 for (ArrayRef<CodeGenRegisterClass*>::const_iterator it =
Chris Lattnerec6f0962010-11-02 18:10:06 +0000943 RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it)
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +0000944 RegisterSets.insert(std::set<Record*>(
945 (*it)->getOrder().begin(), (*it)->getOrder().end()));
Daniel Dunbar1095f2a2009-08-11 23:23:44 +0000946
947 // Add any required singleton sets.
Chris Lattner1de88232010-11-01 01:47:07 +0000948 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
949 ie = SingletonRegisters.end(); it != ie; ++it) {
950 Record *Rec = *it;
951 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
952 }
Jim Grosbacha7c78222010-10-29 22:13:48 +0000953
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000954 // Introduce derived sets where necessary (when a register does not determine
955 // a unique register set class), and build the mapping of registers to the set
956 // they should classify to.
957 std::map<Record*, std::set<Record*> > RegisterMap;
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +0000958 for (std::vector<CodeGenRegister*>::const_iterator it = Registers.begin(),
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000959 ie = Registers.end(); it != ie; ++it) {
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +0000960 const CodeGenRegister &CGR = **it;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000961 // Compute the intersection of all sets containing this register.
962 std::set<Record*> ContainingSet;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000963
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000964 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
965 ie = RegisterSets.end(); it != ie; ++it) {
966 if (!it->count(CGR.TheDef))
967 continue;
968
969 if (ContainingSet.empty()) {
970 ContainingSet = *it;
Chris Lattnerec6f0962010-11-02 18:10:06 +0000971 continue;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000972 }
Bob Wilson828295b2011-01-26 21:26:19 +0000973
Chris Lattnerec6f0962010-11-02 18:10:06 +0000974 std::set<Record*> Tmp;
975 std::swap(Tmp, ContainingSet);
976 std::insert_iterator< std::set<Record*> > II(ContainingSet,
977 ContainingSet.begin());
978 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(), II);
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000979 }
980
981 if (!ContainingSet.empty()) {
982 RegisterSets.insert(ContainingSet);
983 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
984 }
985 }
986
987 // Construct the register classes.
988 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
989 unsigned Index = 0;
990 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
991 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
992 ClassInfo *CI = new ClassInfo();
993 CI->Kind = ClassInfo::RegisterClass0 + Index;
994 CI->ClassName = "Reg" + utostr(Index);
995 CI->Name = "MCK_Reg" + utostr(Index);
996 CI->ValueName = "";
997 CI->PredicateMethod = ""; // unused
998 CI->RenderMethod = "addRegOperands";
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000999 CI->Registers = *it;
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001000 Classes.push_back(CI);
1001 RegisterSetClasses.insert(std::make_pair(*it, CI));
1002 }
1003
1004 // Find the superclasses; we could compute only the subgroup lattice edges,
1005 // but there isn't really a point.
1006 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
1007 ie = RegisterSets.end(); it != ie; ++it) {
1008 ClassInfo *CI = RegisterSetClasses[*it];
1009 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
1010 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
Jim Grosbacha7c78222010-10-29 22:13:48 +00001011 if (*it != *it2 &&
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001012 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
1013 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
1014 }
1015
1016 // Name the register classes which correspond to a user defined RegisterClass.
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001017 for (ArrayRef<CodeGenRegisterClass*>::const_iterator
Chris Lattnerec6f0962010-11-02 18:10:06 +00001018 it = RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) {
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001019 const CodeGenRegisterClass &RC = **it;
Jakob Stoklund Olesen6fea31e2011-10-04 15:28:08 +00001020 // Def will be NULL for non-user defined register classes.
1021 Record *Def = RC.getDef();
1022 if (!Def)
1023 continue;
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001024 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(RC.getOrder().begin(),
1025 RC.getOrder().end())];
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001026 if (CI->ValueName.empty()) {
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001027 CI->ClassName = RC.getName();
1028 CI->Name = "MCK_" + RC.getName();
1029 CI->ValueName = RC.getName();
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001030 } else
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001031 CI->ValueName = CI->ValueName + "," + RC.getName();
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001032
Jakob Stoklund Olesen6fea31e2011-10-04 15:28:08 +00001033 RegisterClassClasses.insert(std::make_pair(Def, CI));
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001034 }
1035
1036 // Populate the map for individual registers.
1037 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
1038 ie = RegisterMap.end(); it != ie; ++it)
Chris Lattnerec6f0962010-11-02 18:10:06 +00001039 RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001040
1041 // Name the register classes which correspond to singleton registers.
Chris Lattner1de88232010-11-01 01:47:07 +00001042 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1043 ie = SingletonRegisters.end(); it != ie; ++it) {
1044 Record *Rec = *it;
Chris Lattnerec6f0962010-11-02 18:10:06 +00001045 ClassInfo *CI = RegisterClasses[Rec];
Chris Lattner1de88232010-11-01 01:47:07 +00001046 assert(CI && "Missing singleton register class info!");
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001047
Chris Lattner1de88232010-11-01 01:47:07 +00001048 if (CI->ValueName.empty()) {
1049 CI->ClassName = Rec->getName();
1050 CI->Name = "MCK_" + Rec->getName();
1051 CI->ValueName = Rec->getName();
1052 } else
1053 CI->ValueName = CI->ValueName + "," + Rec->getName();
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001054 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001055}
1056
Chris Lattner02bcbc92010-11-01 01:37:30 +00001057void AsmMatcherInfo::BuildOperandClasses() {
Chris Lattnere66b7eb2010-11-01 23:57:23 +00001058 std::vector<Record*> AsmOperands =
1059 Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbara2f5e002010-01-30 01:02:37 +00001060
1061 // Pre-populate AsmOperandClasses map.
Jim Grosbacha7c78222010-10-29 22:13:48 +00001062 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbara2f5e002010-01-30 01:02:37 +00001063 ie = AsmOperands.end(); it != ie; ++it)
1064 AsmOperandClasses[*it] = new ClassInfo();
1065
Daniel Dunbar338825c2009-08-10 18:41:10 +00001066 unsigned Index = 0;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001067 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbar338825c2009-08-10 18:41:10 +00001068 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
Daniel Dunbara2f5e002010-01-30 01:02:37 +00001069 ClassInfo *CI = AsmOperandClasses[*it];
Daniel Dunbar338825c2009-08-10 18:41:10 +00001070 CI->Kind = ClassInfo::UserClass0 + Index;
1071
David Greene05bce0b2011-07-29 22:43:06 +00001072 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
Daniel Dunbar54ddf3d2010-05-22 21:02:29 +00001073 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
David Greene05bce0b2011-07-29 22:43:06 +00001074 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
Daniel Dunbar54ddf3d2010-05-22 21:02:29 +00001075 if (!DI) {
1076 PrintError((*it)->getLoc(), "Invalid super class reference!");
1077 continue;
1078 }
1079
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001080 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1081 if (!SC)
Daniel Dunbar338825c2009-08-10 18:41:10 +00001082 PrintError((*it)->getLoc(), "Invalid super class reference!");
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001083 else
1084 CI->SuperClasses.push_back(SC);
Daniel Dunbar338825c2009-08-10 18:41:10 +00001085 }
1086 CI->ClassName = (*it)->getValueAsString("Name");
1087 CI->Name = "MCK_" + CI->ClassName;
1088 CI->ValueName = (*it)->getName();
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001089
1090 // Get or construct the predicate method name.
David Greene05bce0b2011-07-29 22:43:06 +00001091 Init *PMName = (*it)->getValueInit("PredicateMethod");
1092 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001093 CI->PredicateMethod = SI->getValue();
1094 } else {
David Greene05bce0b2011-07-29 22:43:06 +00001095 assert(dynamic_cast<UnsetInit*>(PMName) &&
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001096 "Unexpected PredicateMethod field!");
1097 CI->PredicateMethod = "is" + CI->ClassName;
1098 }
1099
1100 // Get or construct the render method name.
David Greene05bce0b2011-07-29 22:43:06 +00001101 Init *RMName = (*it)->getValueInit("RenderMethod");
1102 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001103 CI->RenderMethod = SI->getValue();
1104 } else {
David Greene05bce0b2011-07-29 22:43:06 +00001105 assert(dynamic_cast<UnsetInit*>(RMName) &&
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001106 "Unexpected RenderMethod field!");
1107 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1108 }
1109
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001110 // Get the parse method name or leave it as empty.
David Greene05bce0b2011-07-29 22:43:06 +00001111 Init *PRMName = (*it)->getValueInit("ParserMethod");
1112 if (StringInit *SI = dynamic_cast<StringInit*>(PRMName))
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001113 CI->ParserMethod = SI->getValue();
1114
Daniel Dunbar338825c2009-08-10 18:41:10 +00001115 AsmOperandClasses[*it] = CI;
1116 Classes.push_back(CI);
1117 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001118}
1119
Bob Wilson828295b2011-01-26 21:26:19 +00001120AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1121 CodeGenTarget &target,
Chris Lattner9c6b60e2010-12-15 04:48:22 +00001122 RecordKeeper &records)
Devang Patel63faf822012-01-07 01:33:34 +00001123 : Records(records), AsmParser(asmParser), Target(target) {
Daniel Dunbar59fc42d2009-08-11 20:59:47 +00001124}
1125
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001126/// BuildOperandMatchInfo - Build the necessary information to handle user
1127/// defined operand parsing methods.
1128void AsmMatcherInfo::BuildOperandMatchInfo() {
1129
1130 /// Map containing a mask with all operands indicies that can be found for
1131 /// that class inside a instruction.
1132 std::map<ClassInfo*, unsigned> OpClassMask;
1133
1134 for (std::vector<MatchableInfo*>::const_iterator it =
1135 Matchables.begin(), ie = Matchables.end();
1136 it != ie; ++it) {
1137 MatchableInfo &II = **it;
1138 OpClassMask.clear();
1139
1140 // Keep track of all operands of this instructions which belong to the
1141 // same class.
1142 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
1143 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
1144 if (Op.Class->ParserMethod.empty())
1145 continue;
1146 unsigned &OperandMask = OpClassMask[Op.Class];
1147 OperandMask |= (1 << i);
1148 }
1149
1150 // Generate operand match info for each mnemonic/operand class pair.
1151 for (std::map<ClassInfo*, unsigned>::iterator iit = OpClassMask.begin(),
1152 iie = OpClassMask.end(); iit != iie; ++iit) {
1153 unsigned OpMask = iit->second;
1154 ClassInfo *CI = iit->first;
1155 OperandMatchInfo.push_back(OperandMatchEntry::Create(&II, CI, OpMask));
1156 }
1157 }
1158}
1159
Chris Lattner02bcbc92010-11-01 01:37:30 +00001160void AsmMatcherInfo::BuildInfo() {
Chris Lattner0aed1e72010-10-30 20:07:57 +00001161 // Build information about all of the AssemblerPredicates.
1162 std::vector<Record*> AllPredicates =
1163 Records.getAllDerivedDefinitions("Predicate");
1164 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
1165 Record *Pred = AllPredicates[i];
1166 // Ignore predicates that are not intended for the assembler.
1167 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
1168 continue;
Bob Wilson828295b2011-01-26 21:26:19 +00001169
Chris Lattner4164f6b2010-11-01 04:44:29 +00001170 if (Pred->getName().empty())
1171 throw TGError(Pred->getLoc(), "Predicate has no name!");
Bob Wilson828295b2011-01-26 21:26:19 +00001172
Chris Lattner0aed1e72010-10-30 20:07:57 +00001173 unsigned FeatureNo = SubtargetFeatures.size();
1174 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
1175 assert(FeatureNo < 32 && "Too many subtarget features!");
1176 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001177
Chris Lattner39ee0362010-10-31 19:10:56 +00001178 // Parse the instructions; we need to do this first so that we can gather the
1179 // singleton register classes.
Chris Lattner1de88232010-11-01 01:47:07 +00001180 SmallPtrSet<Record*, 16> SingletonRegisters;
Devang Patel0dbcada2012-01-09 19:13:28 +00001181 unsigned VariantCount = Target.getAsmParserVariantCount();
1182 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1183 Record *AsmVariant = Target.getAsmParserVariant(VC);
1184 std::string CommentDelimiter = AsmVariant->getValueAsString("CommentDelimiter");
1185 std::string RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
1186 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Jim Grosbachf35307c2012-01-24 21:06:59 +00001187
Devang Patel0dbcada2012-01-09 19:13:28 +00001188 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
Jim Grosbach11fc6462012-04-11 21:02:33 +00001189 E = Target.inst_end(); I != E; ++I) {
Devang Patel0dbcada2012-01-09 19:13:28 +00001190 const CodeGenInstruction &CGI = **I;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001191
Devang Patel0dbcada2012-01-09 19:13:28 +00001192 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1193 // filter the set of instructions we consider.
1194 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
Jim Grosbach11fc6462012-04-11 21:02:33 +00001195 continue;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001196
Devang Patel0dbcada2012-01-09 19:13:28 +00001197 // Ignore "codegen only" instructions.
1198 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
Jim Grosbach11fc6462012-04-11 21:02:33 +00001199 continue;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001200
Devang Patel0dbcada2012-01-09 19:13:28 +00001201 // Validate the operand list to ensure we can handle this instruction.
1202 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
Jim Grosbach11fc6462012-04-11 21:02:33 +00001203 const CGIOperandList::OperandInfo &OI = CGI.Operands[i];
1204
1205 // Validate tied operands.
1206 if (OI.getTiedRegister() != -1) {
1207 // If we have a tied operand that consists of multiple MCOperands,
1208 // reject it. We reject aliases and ignore instructions for now.
1209 if (OI.MINumOperands != 1) {
1210 // FIXME: Should reject these. The ARM backend hits this with $lane
1211 // in a bunch of instructions. It is unclear what the right answer is.
1212 DEBUG({
1213 errs() << "warning: '" << CGI.TheDef->getName() << "': "
1214 << "ignoring instruction with multi-operand tied operand '"
1215 << OI.Name << "'\n";
1216 });
1217 continue;
1218 }
1219 }
Chris Lattner1d13bda2010-11-04 00:43:46 +00001220 }
Jim Grosbachf35307c2012-01-24 21:06:59 +00001221
Devang Patel0dbcada2012-01-09 19:13:28 +00001222 OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
Jim Grosbachf35307c2012-01-24 21:06:59 +00001223
Devang Patel0dbcada2012-01-09 19:13:28 +00001224 II->Initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
Jim Grosbachf35307c2012-01-24 21:06:59 +00001225
Devang Patel0dbcada2012-01-09 19:13:28 +00001226 // Ignore instructions which shouldn't be matched and diagnose invalid
1227 // instruction definitions with an error.
1228 if (!II->Validate(CommentDelimiter, true))
Jim Grosbach11fc6462012-04-11 21:02:33 +00001229 continue;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001230
Devang Patel0dbcada2012-01-09 19:13:28 +00001231 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
1232 //
1233 // FIXME: This is a total hack.
1234 if (StringRef(II->TheDef->getName()).startswith("Int_") ||
Jim Grosbach11fc6462012-04-11 21:02:33 +00001235 StringRef(II->TheDef->getName()).endswith("_Int"))
1236 continue;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001237
Devang Patel0dbcada2012-01-09 19:13:28 +00001238 Matchables.push_back(II.take());
Chris Lattner1d13bda2010-11-04 00:43:46 +00001239 }
Jim Grosbachf35307c2012-01-24 21:06:59 +00001240
Devang Patel0dbcada2012-01-09 19:13:28 +00001241 // Parse all of the InstAlias definitions and stick them in the list of
1242 // matchables.
1243 std::vector<Record*> AllInstAliases =
1244 Records.getAllDerivedDefinitions("InstAlias");
1245 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
1246 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i], Target);
Jim Grosbachf35307c2012-01-24 21:06:59 +00001247
Devang Patel0dbcada2012-01-09 19:13:28 +00001248 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1249 // filter the set of instruction aliases we consider, based on the target
1250 // instruction.
1251 if (!StringRef(Alias->ResultInst->TheDef->getName()).startswith(
Jim Grosbach11fc6462012-04-11 21:02:33 +00001252 MatchPrefix))
1253 continue;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001254
Devang Patel0dbcada2012-01-09 19:13:28 +00001255 OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
Jim Grosbachf35307c2012-01-24 21:06:59 +00001256
Devang Patel0dbcada2012-01-09 19:13:28 +00001257 II->Initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
Jim Grosbachf35307c2012-01-24 21:06:59 +00001258
Devang Patel0dbcada2012-01-09 19:13:28 +00001259 // Validate the alias definitions.
1260 II->Validate(CommentDelimiter, false);
Jim Grosbachf35307c2012-01-24 21:06:59 +00001261
Devang Patel0dbcada2012-01-09 19:13:28 +00001262 Matchables.push_back(II.take());
1263 }
Chris Lattnerc76e80d2010-11-01 04:05:41 +00001264 }
Chris Lattnerc240bb02010-11-01 04:03:32 +00001265
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001266 // Build info for the register classes.
Chris Lattner1de88232010-11-01 01:47:07 +00001267 BuildRegisterClasses(SingletonRegisters);
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001268
1269 // Build info for the user defined assembly operand classes.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001270 BuildOperandClasses();
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001271
Chris Lattner0bb780c2010-11-04 00:57:06 +00001272 // Build the information about matchables, now that we have fully formed
1273 // classes.
Chris Lattner22bc5c42010-11-01 05:06:45 +00001274 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(),
1275 ie = Matchables.end(); it != ie; ++it) {
1276 MatchableInfo *II = *it;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001277
Chris Lattnere206fcf2010-09-06 21:01:37 +00001278 // Parse the tokens after the mnemonic.
Bob Wilsona49c7df2011-01-26 19:44:55 +00001279 // Note: BuildInstructionOperandReference may insert new AsmOperands, so
1280 // don't precompute the loop bound.
1281 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
Chris Lattnerc0b14a22010-11-03 19:47:34 +00001282 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
Chris Lattnerd19ec052010-11-02 17:30:52 +00001283 StringRef Token = Op.Token;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001284
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001285 // Check for singleton registers.
Devang Patel63faf822012-01-07 01:33:34 +00001286 if (Record *RegRecord = II->AsmOperands[i].SingletonReg) {
Chris Lattnerd19ec052010-11-02 17:30:52 +00001287 Op.Class = RegisterClasses[RegRecord];
Chris Lattner02bcbc92010-11-01 01:37:30 +00001288 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1289 "Unexpected class for singleton register");
Chris Lattner02bcbc92010-11-01 01:37:30 +00001290 continue;
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001291 }
1292
Daniel Dunbar20927f22009-08-07 08:26:05 +00001293 // Check for simple tokens.
1294 if (Token[0] != '$') {
Chris Lattnerd19ec052010-11-02 17:30:52 +00001295 Op.Class = getTokenClass(Token);
Daniel Dunbar20927f22009-08-07 08:26:05 +00001296 continue;
1297 }
1298
Chris Lattner7ad31472010-11-06 22:06:03 +00001299 if (Token.size() > 1 && isdigit(Token[1])) {
1300 Op.Class = getTokenClass(Token);
1301 continue;
1302 }
Bob Wilson828295b2011-01-26 21:26:19 +00001303
Chris Lattnerc07bd402010-11-04 02:11:18 +00001304 // Otherwise this is an operand reference.
Chris Lattner5f4280c2010-11-04 01:58:23 +00001305 StringRef OperandName;
1306 if (Token[1] == '{')
1307 OperandName = Token.substr(2, Token.size() - 3);
1308 else
1309 OperandName = Token.substr(1);
Bob Wilson828295b2011-01-26 21:26:19 +00001310
Chris Lattnerc07bd402010-11-04 02:11:18 +00001311 if (II->DefRec.is<const CodeGenInstruction*>())
Bob Wilsona49c7df2011-01-26 19:44:55 +00001312 BuildInstructionOperandReference(II, OperandName, i);
Chris Lattnerc07bd402010-11-04 02:11:18 +00001313 else
Chris Lattner225549f2010-11-06 06:39:47 +00001314 BuildAliasOperandReference(II, OperandName, Op);
Daniel Dunbar20927f22009-08-07 08:26:05 +00001315 }
Bob Wilson828295b2011-01-26 21:26:19 +00001316
Chris Lattner41409852010-11-06 07:31:43 +00001317 if (II->DefRec.is<const CodeGenInstruction*>())
1318 II->BuildInstructionResultOperands();
1319 else
1320 II->BuildAliasResultOperands();
Daniel Dunbar20927f22009-08-07 08:26:05 +00001321 }
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001322
Jim Grosbacha66512e2011-12-06 23:43:54 +00001323 // Process token alias definitions and set up the associated superclass
1324 // information.
1325 std::vector<Record*> AllTokenAliases =
1326 Records.getAllDerivedDefinitions("TokenAlias");
1327 for (unsigned i = 0, e = AllTokenAliases.size(); i != e; ++i) {
1328 Record *Rec = AllTokenAliases[i];
1329 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1330 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
1331 FromClass->SuperClasses.push_back(ToClass);
1332 }
1333
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001334 // Reorder classes so that classes precede super classes.
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001335 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
Daniel Dunbar20927f22009-08-07 08:26:05 +00001336}
1337
Chris Lattner0bb780c2010-11-04 00:57:06 +00001338/// BuildInstructionOperandReference - The specified operand is a reference to a
1339/// named operand such as $src. Resolve the Class and OperandInfo pointers.
1340void AsmMatcherInfo::
1341BuildInstructionOperandReference(MatchableInfo *II,
Chris Lattner5f4280c2010-11-04 01:58:23 +00001342 StringRef OperandName,
Bob Wilsona49c7df2011-01-26 19:44:55 +00001343 unsigned AsmOpIdx) {
Chris Lattnerc07bd402010-11-04 02:11:18 +00001344 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1345 const CGIOperandList &Operands = CGI.Operands;
Bob Wilsona49c7df2011-01-26 19:44:55 +00001346 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
Bob Wilson828295b2011-01-26 21:26:19 +00001347
Chris Lattner662e5a32010-11-06 07:14:44 +00001348 // Map this token to an operand.
Chris Lattner0bb780c2010-11-04 00:57:06 +00001349 unsigned Idx;
1350 if (!Operands.hasOperandNamed(OperandName, Idx))
1351 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1352 OperandName.str() + "'");
Chris Lattnerba3b5b62010-11-04 01:55:23 +00001353
Bob Wilsona49c7df2011-01-26 19:44:55 +00001354 // If the instruction operand has multiple suboperands, but the parser
1355 // match class for the asm operand is still the default "ImmAsmOperand",
1356 // then handle each suboperand separately.
1357 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1358 Record *Rec = Operands[Idx].Rec;
1359 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1360 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1361 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1362 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1363 StringRef Token = Op->Token; // save this in case Op gets moved
1364 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1365 MatchableInfo::AsmOperand NewAsmOp(Token);
1366 NewAsmOp.SubOpIdx = SI;
1367 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1368 }
1369 // Replace Op with first suboperand.
1370 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1371 Op->SubOpIdx = 0;
1372 }
1373 }
1374
Chris Lattnerba3b5b62010-11-04 01:55:23 +00001375 // Set up the operand class.
Bob Wilsona49c7df2011-01-26 19:44:55 +00001376 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
Chris Lattnerba3b5b62010-11-04 01:55:23 +00001377
1378 // If the named operand is tied, canonicalize it to the untied operand.
1379 // For example, something like:
1380 // (outs GPR:$dst), (ins GPR:$src)
1381 // with an asmstring of
1382 // "inc $src"
1383 // we want to canonicalize to:
1384 // "inc $dst"
1385 // so that we know how to provide the $dst operand when filling in the result.
1386 int OITied = Operands[Idx].getTiedRegister();
Chris Lattner0bb780c2010-11-04 00:57:06 +00001387 if (OITied != -1) {
1388 // The tied operand index is an MIOperand index, find the operand that
1389 // contains it.
Bob Wilsona49c7df2011-01-26 19:44:55 +00001390 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1391 OperandName = Operands[Idx.first].Name;
1392 Op->SubOpIdx = Idx.second;
Chris Lattner0bb780c2010-11-04 00:57:06 +00001393 }
Bob Wilson828295b2011-01-26 21:26:19 +00001394
Bob Wilsona49c7df2011-01-26 19:44:55 +00001395 Op->SrcOpName = OperandName;
Chris Lattner0bb780c2010-11-04 00:57:06 +00001396}
1397
Chris Lattner3f2c8e42010-11-06 07:06:09 +00001398/// BuildAliasOperandReference - When parsing an operand reference out of the
1399/// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1400/// operand reference is by looking it up in the result pattern definition.
Chris Lattnerc07bd402010-11-04 02:11:18 +00001401void AsmMatcherInfo::BuildAliasOperandReference(MatchableInfo *II,
1402 StringRef OperandName,
1403 MatchableInfo::AsmOperand &Op) {
1404 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
Bob Wilson828295b2011-01-26 21:26:19 +00001405
Chris Lattnerc07bd402010-11-04 02:11:18 +00001406 // Set up the operand class.
Chris Lattner3f2c8e42010-11-06 07:06:09 +00001407 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
Chris Lattner98c870f2010-11-06 19:25:43 +00001408 if (CGA.ResultOperands[i].isRecord() &&
1409 CGA.ResultOperands[i].getName() == OperandName) {
Chris Lattner662e5a32010-11-06 07:14:44 +00001410 // It's safe to go with the first one we find, because CodeGenInstAlias
1411 // validates that all operands with the same name have the same record.
Bob Wilsona49c7df2011-01-26 19:44:55 +00001412 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
Jim Grosbach48c1f842011-10-28 22:32:53 +00001413 // Use the match class from the Alias definition, not the
1414 // destination instruction, as we may have an immediate that's
1415 // being munged by the match class.
1416 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
Bob Wilsona49c7df2011-01-26 19:44:55 +00001417 Op.SubOpIdx);
Chris Lattner3f2c8e42010-11-06 07:06:09 +00001418 Op.SrcOpName = OperandName;
1419 return;
Chris Lattnerc07bd402010-11-04 02:11:18 +00001420 }
Chris Lattner3f2c8e42010-11-06 07:06:09 +00001421
1422 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1423 OperandName.str() + "'");
Chris Lattnerc07bd402010-11-04 02:11:18 +00001424}
1425
Chris Lattner41409852010-11-06 07:31:43 +00001426void MatchableInfo::BuildInstructionResultOperands() {
Chris Lattner662e5a32010-11-06 07:14:44 +00001427 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilson828295b2011-01-26 21:26:19 +00001428
Chris Lattner662e5a32010-11-06 07:14:44 +00001429 // Loop over all operands of the result instruction, determining how to
1430 // populate them.
1431 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1432 const CGIOperandList::OperandInfo &OpInfo = ResultInst->Operands[i];
Chris Lattner567820c2010-11-04 01:42:59 +00001433
1434 // If this is a tied operand, just copy from the previously handled operand.
1435 int TiedOp = OpInfo.getTiedRegister();
1436 if (TiedOp != -1) {
Bob Wilsona49c7df2011-01-26 19:44:55 +00001437 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
Chris Lattner567820c2010-11-04 01:42:59 +00001438 continue;
1439 }
Bob Wilson828295b2011-01-26 21:26:19 +00001440
Bob Wilsona49c7df2011-01-26 19:44:55 +00001441 // Find out what operand from the asmparser this MCInst operand comes from.
Chris Lattnerba3b5b62010-11-04 01:55:23 +00001442 int SrcOperand = FindAsmOperandNamed(OpInfo.Name);
Bob Wilsona49c7df2011-01-26 19:44:55 +00001443 if (OpInfo.Name.empty() || SrcOperand == -1)
1444 throw TGError(TheDef->getLoc(), "Instruction '" +
1445 TheDef->getName() + "' has operand '" + OpInfo.Name +
1446 "' that doesn't appear in asm string!");
Chris Lattner567820c2010-11-04 01:42:59 +00001447
Bob Wilsona49c7df2011-01-26 19:44:55 +00001448 // Check if the one AsmOperand populates the entire operand.
1449 unsigned NumOperands = OpInfo.MINumOperands;
1450 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1451 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
Chris Lattner1d13bda2010-11-04 00:43:46 +00001452 continue;
1453 }
Bob Wilsona49c7df2011-01-26 19:44:55 +00001454
1455 // Add a separate ResOperand for each suboperand.
1456 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1457 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1458 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1459 "unexpected AsmOperands for suboperands");
1460 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1461 }
Chris Lattner1d13bda2010-11-04 00:43:46 +00001462 }
1463}
1464
Chris Lattner41409852010-11-06 07:31:43 +00001465void MatchableInfo::BuildAliasResultOperands() {
1466 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1467 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilson828295b2011-01-26 21:26:19 +00001468
Chris Lattner41409852010-11-06 07:31:43 +00001469 // Loop over all operands of the result instruction, determining how to
1470 // populate them.
1471 unsigned AliasOpNo = 0;
Bob Wilsona49c7df2011-01-26 19:44:55 +00001472 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
Chris Lattner41409852010-11-06 07:31:43 +00001473 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
Bob Wilsona49c7df2011-01-26 19:44:55 +00001474 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
Bob Wilson828295b2011-01-26 21:26:19 +00001475
Chris Lattner41409852010-11-06 07:31:43 +00001476 // If this is a tied operand, just copy from the previously handled operand.
Bob Wilsona49c7df2011-01-26 19:44:55 +00001477 int TiedOp = OpInfo->getTiedRegister();
Chris Lattner41409852010-11-06 07:31:43 +00001478 if (TiedOp != -1) {
Bob Wilsona49c7df2011-01-26 19:44:55 +00001479 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
Chris Lattner90fd7972010-11-06 19:57:21 +00001480 continue;
1481 }
1482
Bob Wilsona49c7df2011-01-26 19:44:55 +00001483 // Handle all the suboperands for this operand.
1484 const std::string &OpName = OpInfo->Name;
1485 for ( ; AliasOpNo < LastOpNo &&
1486 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1487 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1488
1489 // Find out what operand from the asmparser that this MCInst operand
1490 // comes from.
1491 switch (CGA.ResultOperands[AliasOpNo].Kind) {
Bob Wilsona49c7df2011-01-26 19:44:55 +00001492 case CodeGenInstAlias::ResultOperand::K_Record: {
1493 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1494 int SrcOperand = FindAsmOperand(Name, SubIdx);
1495 if (SrcOperand == -1)
1496 throw TGError(TheDef->getLoc(), "Instruction '" +
1497 TheDef->getName() + "' has operand '" + OpName +
1498 "' that doesn't appear in asm string!");
1499 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1500 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1501 NumOperands));
1502 break;
1503 }
1504 case CodeGenInstAlias::ResultOperand::K_Imm: {
1505 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1506 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1507 break;
1508 }
1509 case CodeGenInstAlias::ResultOperand::K_Reg: {
1510 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1511 ResOperands.push_back(ResOperand::getRegOp(Reg));
1512 break;
1513 }
1514 }
Chris Lattner90fd7972010-11-06 19:57:21 +00001515 }
Chris Lattner41409852010-11-06 07:31:43 +00001516 }
1517}
Chris Lattner1d13bda2010-11-04 00:43:46 +00001518
Daniel Dunbar5c228a92011-02-04 23:17:40 +00001519static void EmitConvertToMCInst(CodeGenTarget &Target, StringRef ClassName,
Chris Lattner22bc5c42010-11-01 05:06:45 +00001520 std::vector<MatchableInfo*> &Infos,
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001521 raw_ostream &OS) {
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001522 // Write the convert function to a separate stream, so we can drop it after
1523 // the enum.
1524 std::string ConvertFnBody;
1525 raw_string_ostream CvtOS(ConvertFnBody);
1526
Daniel Dunbar20927f22009-08-07 08:26:05 +00001527 // Function we have already generated.
1528 std::set<std::string> GeneratedFns;
1529
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001530 // Start the unified conversion function.
Daniel Dunbar5c228a92011-02-04 23:17:40 +00001531 CvtOS << "bool " << Target.getName() << ClassName << "::\n";
1532 CvtOS << "ConvertToMCInst(unsigned Kind, MCInst &Inst, "
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001533 << "unsigned Opcode,\n"
Chris Lattner98986712010-01-14 22:21:20 +00001534 << " const SmallVectorImpl<MCParsedAsmOperand*"
1535 << "> &Operands) {\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001536 CvtOS << " Inst.setOpcode(Opcode);\n";
1537 CvtOS << " switch (Kind) {\n";
1538 CvtOS << " default:\n";
1539
1540 // Start the enum, which we will generate inline.
1541
Chris Lattnerd51257a2010-11-02 23:18:43 +00001542 OS << "// Unified function for converting operands to MCInst instances.\n\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001543 OS << "enum ConversionKind {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001544
Chris Lattner98986712010-01-14 22:21:20 +00001545 // TargetOperandClass - This is the target's operand class, like X86Operand.
1546 std::string TargetOperandClass = Target.getName() + "Operand";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001547
Chris Lattner22bc5c42010-11-01 05:06:45 +00001548 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(),
Daniel Dunbar20927f22009-08-07 08:26:05 +00001549 ie = Infos.end(); it != ie; ++it) {
Chris Lattner22bc5c42010-11-01 05:06:45 +00001550 MatchableInfo &II = **it;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001551
Daniel Dunbarcf120672011-02-04 17:12:15 +00001552 // Check if we have a custom match function.
Daniel Dunbar27b83d42011-04-01 20:23:52 +00001553 std::string AsmMatchConverter =
1554 II.getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
Daniel Dunbarcf120672011-02-04 17:12:15 +00001555 if (!AsmMatchConverter.empty()) {
Daniel Dunbar27b83d42011-04-01 20:23:52 +00001556 std::string Signature = "ConvertCustom_" + AsmMatchConverter;
Daniel Dunbarcf120672011-02-04 17:12:15 +00001557 II.ConversionFnKind = Signature;
1558
1559 // Check if we have already generated this signature.
1560 if (!GeneratedFns.insert(Signature).second)
1561 continue;
1562
1563 // If not, emit it now. Add to the enum list.
1564 OS << " " << Signature << ",\n";
1565
1566 CvtOS << " case " << Signature << ":\n";
Daniel Dunbarb4129152011-02-04 17:12:23 +00001567 CvtOS << " return " << AsmMatchConverter
1568 << "(Inst, Opcode, Operands);\n";
Daniel Dunbarcf120672011-02-04 17:12:15 +00001569 continue;
1570 }
1571
Daniel Dunbar20927f22009-08-07 08:26:05 +00001572 // Build the conversion function signature.
1573 std::string Signature = "Convert";
Chris Lattnerdda855d2010-11-02 21:49:44 +00001574 std::string CaseBody;
1575 raw_string_ostream CaseOS(CaseBody);
Bob Wilson828295b2011-01-26 21:26:19 +00001576
Chris Lattnerdda855d2010-11-02 21:49:44 +00001577 // Compute the convert enum and the case body.
Chris Lattner1d13bda2010-11-04 00:43:46 +00001578 for (unsigned i = 0, e = II.ResOperands.size(); i != e; ++i) {
1579 const MatchableInfo::ResOperand &OpInfo = II.ResOperands[i];
Jim Grosbacha7c78222010-10-29 22:13:48 +00001580
Chris Lattner1d13bda2010-11-04 00:43:46 +00001581 // Generate code to populate each result operand.
1582 switch (OpInfo.Kind) {
Chris Lattner1d13bda2010-11-04 00:43:46 +00001583 case MatchableInfo::ResOperand::RenderAsmOperand: {
1584 // This comes from something we parsed.
1585 MatchableInfo::AsmOperand &Op = II.AsmOperands[OpInfo.AsmOperandNum];
Bob Wilson828295b2011-01-26 21:26:19 +00001586
Chris Lattner9b0d4bf2010-11-02 22:55:03 +00001587 // Registers are always converted the same, don't duplicate the
1588 // conversion function based on them.
Chris Lattner9b0d4bf2010-11-02 22:55:03 +00001589 Signature += "__";
1590 if (Op.Class->isRegisterClass())
1591 Signature += "Reg";
1592 else
1593 Signature += Op.Class->ClassName;
Bob Wilsona49c7df2011-01-26 19:44:55 +00001594 Signature += utostr(OpInfo.MINumOperands);
Chris Lattner1d13bda2010-11-04 00:43:46 +00001595 Signature += "_" + itostr(OpInfo.AsmOperandNum);
Bob Wilson828295b2011-01-26 21:26:19 +00001596
Chris Lattner9b0d4bf2010-11-02 22:55:03 +00001597 CaseOS << " ((" << TargetOperandClass << "*)Operands["
Chris Lattner1d13bda2010-11-04 00:43:46 +00001598 << (OpInfo.AsmOperandNum+1) << "])->" << Op.Class->RenderMethod
Bob Wilsona49c7df2011-01-26 19:44:55 +00001599 << "(Inst, " << OpInfo.MINumOperands << ");\n";
Chris Lattner1d13bda2010-11-04 00:43:46 +00001600 break;
Daniel Dunbaraf616812010-02-10 08:15:48 +00001601 }
Bob Wilson828295b2011-01-26 21:26:19 +00001602
Chris Lattner1d13bda2010-11-04 00:43:46 +00001603 case MatchableInfo::ResOperand::TiedOperand: {
1604 // If this operand is tied to a previous one, just copy the MCInst
1605 // operand from the earlier one.We can only tie single MCOperand values.
Bob Wilsona49c7df2011-01-26 19:44:55 +00001606 //assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
Chris Lattner1d13bda2010-11-04 00:43:46 +00001607 unsigned TiedOp = OpInfo.TiedOperandNum;
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001608 assert(i > TiedOp && "Tied operand precedes its target!");
Chris Lattner1d13bda2010-11-04 00:43:46 +00001609 CaseOS << " Inst.addOperand(Inst.getOperand(" << TiedOp << "));\n";
1610 Signature += "__Tie" + utostr(TiedOp);
1611 break;
1612 }
Chris Lattner98c870f2010-11-06 19:25:43 +00001613 case MatchableInfo::ResOperand::ImmOperand: {
1614 int64_t Val = OpInfo.ImmVal;
1615 CaseOS << " Inst.addOperand(MCOperand::CreateImm(" << Val << "));\n";
1616 Signature += "__imm" + itostr(Val);
1617 break;
1618 }
Chris Lattner90fd7972010-11-06 19:57:21 +00001619 case MatchableInfo::ResOperand::RegOperand: {
Bob Wilsondc1a2bd2011-01-14 22:58:09 +00001620 if (OpInfo.Register == 0) {
1621 CaseOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1622 Signature += "__reg0";
1623 } else {
1624 std::string N = getQualifiedName(OpInfo.Register);
1625 CaseOS << " Inst.addOperand(MCOperand::CreateReg(" << N << "));\n";
1626 Signature += "__reg" + OpInfo.Register->getName();
1627 }
Bob Wilson828295b2011-01-26 21:26:19 +00001628 }
Chris Lattner1d13bda2010-11-04 00:43:46 +00001629 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001630 }
Bob Wilson828295b2011-01-26 21:26:19 +00001631
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001632 II.ConversionFnKind = Signature;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001633
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001634 // Check if we have already generated this signature.
Daniel Dunbar20927f22009-08-07 08:26:05 +00001635 if (!GeneratedFns.insert(Signature).second)
1636 continue;
1637
Chris Lattnerdda855d2010-11-02 21:49:44 +00001638 // If not, emit it now. Add to the enum list.
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001639 OS << " " << Signature << ",\n";
1640
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001641 CvtOS << " case " << Signature << ":\n";
Chris Lattnerdda855d2010-11-02 21:49:44 +00001642 CvtOS << CaseOS.str();
Daniel Dunbarb4129152011-02-04 17:12:23 +00001643 CvtOS << " return true;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001644 }
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001645
1646 // Finish the convert function.
1647
1648 CvtOS << " }\n";
Daniel Dunbarb4129152011-02-04 17:12:23 +00001649 CvtOS << " return false;\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001650 CvtOS << "}\n\n";
1651
1652 // Finish the enum, and drop the convert function after it.
1653
1654 OS << " NumConversionVariants\n";
1655 OS << "};\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001656
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001657 OS << CvtOS.str();
Daniel Dunbara027d222009-07-31 02:32:59 +00001658}
1659
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001660/// EmitMatchClassEnumeration - Emit the enumeration for match class kinds.
1661static void EmitMatchClassEnumeration(CodeGenTarget &Target,
1662 std::vector<ClassInfo*> &Infos,
1663 raw_ostream &OS) {
1664 OS << "namespace {\n\n";
1665
1666 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1667 << "/// instruction matching.\n";
1668 OS << "enum MatchClassKind {\n";
1669 OS << " InvalidMatchClass = 0,\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001670 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001671 ie = Infos.end(); it != ie; ++it) {
1672 ClassInfo &CI = **it;
1673 OS << " " << CI.Name << ", // ";
1674 if (CI.Kind == ClassInfo::Token) {
1675 OS << "'" << CI.ValueName << "'\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001676 } else if (CI.isRegisterClass()) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001677 if (!CI.ValueName.empty())
1678 OS << "register class '" << CI.ValueName << "'\n";
1679 else
1680 OS << "derived register class\n";
1681 } else {
1682 OS << "user defined class '" << CI.ValueName << "'\n";
1683 }
1684 }
1685 OS << " NumMatchClassKinds\n";
1686 OS << "};\n\n";
1687
1688 OS << "}\n\n";
1689}
1690
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001691/// EmitValidateOperandClass - Emit the function to validate an operand class.
1692static void EmitValidateOperandClass(AsmMatcherInfo &Info,
1693 raw_ostream &OS) {
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00001694 OS << "static bool validateOperandClass(MCParsedAsmOperand *GOp, "
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001695 << "MatchClassKind Kind) {\n";
1696 OS << " " << Info.Target.getName() << "Operand &Operand = *("
Chris Lattner02bcbc92010-11-01 01:37:30 +00001697 << Info.Target.getName() << "Operand*)GOp;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001698
Kevin Enderby89381832011-07-15 18:30:43 +00001699 // The InvalidMatchClass is not to match any operand.
1700 OS << " if (Kind == InvalidMatchClass)\n";
1701 OS << " return false;\n\n";
1702
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001703 // Check for Token operands first.
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001704 OS << " if (Operand.isToken())\n";
Jim Grosbacha66512e2011-12-06 23:43:54 +00001705 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind);"
1706 << "\n\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001707
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001708 // Check for register operands, including sub-classes.
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001709 OS << " if (Operand.isReg()) {\n";
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001710 OS << " MatchClassKind OpKind;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001711 OS << " switch (Operand.getReg()) {\n";
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001712 OS << " default: OpKind = InvalidMatchClass; break;\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001713 for (std::map<Record*, ClassInfo*>::iterator
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001714 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1715 it != ie; ++it)
Chris Lattner02bcbc92010-11-01 01:37:30 +00001716 OS << " case " << Info.Target.getName() << "::"
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001717 << it->first->getName() << ": OpKind = " << it->second->Name
1718 << "; break;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001719 OS << " }\n";
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00001720 OS << " return isSubclass(OpKind, Kind);\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001721 OS << " }\n\n";
1722
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001723 // Check the user classes. We don't care what order since we're only
1724 // actually matching against one of them.
Jim Grosbacha7c78222010-10-29 22:13:48 +00001725 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001726 ie = Info.Classes.end(); it != ie; ++it) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001727 ClassInfo &CI = **it;
1728
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001729 if (!CI.isUserClass())
1730 continue;
Bob Wilson828295b2011-01-26 21:26:19 +00001731
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001732 OS << " // '" << CI.ClassName << "' class\n";
1733 OS << " if (Kind == " << CI.Name
1734 << " && Operand." << CI.PredicateMethod << "()) {\n";
1735 OS << " return true;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001736 OS << " }\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001737 }
Bob Wilson828295b2011-01-26 21:26:19 +00001738
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001739 OS << " return false;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001740 OS << "}\n\n";
1741}
1742
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001743/// EmitIsSubclass - Emit the subclass predicate function.
1744static void EmitIsSubclass(CodeGenTarget &Target,
1745 std::vector<ClassInfo*> &Infos,
1746 raw_ostream &OS) {
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00001747 OS << "/// isSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1748 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001749 OS << " if (A == B)\n";
1750 OS << " return true;\n\n";
1751
1752 OS << " switch (A) {\n";
1753 OS << " default:\n";
1754 OS << " return false;\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001755 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001756 ie = Infos.end(); it != ie; ++it) {
1757 ClassInfo &A = **it;
1758
Jim Grosbacha66512e2011-12-06 23:43:54 +00001759 std::vector<StringRef> SuperClasses;
1760 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1761 ie = Infos.end(); it != ie; ++it) {
1762 ClassInfo &B = **it;
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001763
Jim Grosbacha66512e2011-12-06 23:43:54 +00001764 if (&A != &B && A.isSubsetOf(B))
1765 SuperClasses.push_back(B.Name);
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001766 }
Jim Grosbacha66512e2011-12-06 23:43:54 +00001767
1768 if (SuperClasses.empty())
1769 continue;
1770
1771 OS << "\n case " << A.Name << ":\n";
1772
1773 if (SuperClasses.size() == 1) {
1774 OS << " return B == " << SuperClasses.back() << ";\n";
1775 continue;
1776 }
1777
1778 OS << " switch (B) {\n";
1779 OS << " default: return false;\n";
1780 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1781 OS << " case " << SuperClasses[i] << ": return true;\n";
1782 OS << " }\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001783 }
1784 OS << " }\n";
1785 OS << "}\n\n";
1786}
1787
Daniel Dunbar245f0582009-08-08 21:22:41 +00001788/// EmitMatchTokenString - Emit the function to match a token string to the
1789/// appropriate match class value.
1790static void EmitMatchTokenString(CodeGenTarget &Target,
1791 std::vector<ClassInfo*> &Infos,
1792 raw_ostream &OS) {
1793 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00001794 std::vector<StringMatcher::StringPair> Matches;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001795 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbar245f0582009-08-08 21:22:41 +00001796 ie = Infos.end(); it != ie; ++it) {
1797 ClassInfo &CI = **it;
1798
1799 if (CI.Kind == ClassInfo::Token)
Chris Lattner5845e5c2010-09-06 02:01:51 +00001800 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1801 "return " + CI.Name + ";"));
Daniel Dunbar245f0582009-08-08 21:22:41 +00001802 }
1803
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00001804 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001805
Chris Lattner5845e5c2010-09-06 02:01:51 +00001806 StringMatcher("Name", Matches, OS).Emit();
Daniel Dunbar245f0582009-08-08 21:22:41 +00001807
1808 OS << " return InvalidMatchClass;\n";
1809 OS << "}\n\n";
1810}
Chris Lattner70add882009-08-08 20:02:57 +00001811
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001812/// EmitMatchRegisterName - Emit the function to match a string to the target
1813/// specific register enum.
1814static void EmitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
1815 raw_ostream &OS) {
Daniel Dunbar245f0582009-08-08 21:22:41 +00001816 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00001817 std::vector<StringMatcher::StringPair> Matches;
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +00001818 const std::vector<CodeGenRegister*> &Regs =
1819 Target.getRegBank().getRegisters();
1820 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1821 const CodeGenRegister *Reg = Regs[i];
1822 if (Reg->TheDef->getValueAsString("AsmName").empty())
Daniel Dunbar22be5222009-07-17 18:51:11 +00001823 continue;
1824
Chris Lattner5845e5c2010-09-06 02:01:51 +00001825 Matches.push_back(StringMatcher::StringPair(
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +00001826 Reg->TheDef->getValueAsString("AsmName"),
1827 "return " + utostr(Reg->EnumValue) + ";"));
Daniel Dunbar22be5222009-07-17 18:51:11 +00001828 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001829
Chris Lattnerb8d6e982010-02-09 00:34:28 +00001830 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001831
Chris Lattner5845e5c2010-09-06 02:01:51 +00001832 StringMatcher("Name", Matches, OS).Emit();
Jim Grosbacha7c78222010-10-29 22:13:48 +00001833
Daniel Dunbar245f0582009-08-08 21:22:41 +00001834 OS << " return 0;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001835 OS << "}\n\n";
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001836}
Daniel Dunbara027d222009-07-31 02:32:59 +00001837
Daniel Dunbar54074b52010-07-19 05:44:09 +00001838/// EmitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
1839/// definitions.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001840static void EmitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
Daniel Dunbar54074b52010-07-19 05:44:09 +00001841 raw_ostream &OS) {
1842 OS << "// Flags for subtarget features that participate in "
1843 << "instruction matching.\n";
1844 OS << "enum SubtargetFeatureFlag {\n";
1845 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1846 it = Info.SubtargetFeatures.begin(),
1847 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1848 SubtargetFeatureInfo &SFI = *it->second;
Chris Lattner0aed1e72010-10-30 20:07:57 +00001849 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001850 }
1851 OS << " Feature_None = 0\n";
1852 OS << "};\n\n";
1853}
1854
1855/// EmitComputeAvailableFeatures - Emit the function to compute the list of
1856/// available features given a subtarget.
Chris Lattner02bcbc92010-11-01 01:37:30 +00001857static void EmitComputeAvailableFeatures(AsmMatcherInfo &Info,
Daniel Dunbar54074b52010-07-19 05:44:09 +00001858 raw_ostream &OS) {
1859 std::string ClassName =
1860 Info.AsmParser->getValueAsString("AsmParserClassName");
1861
Chris Lattner02bcbc92010-11-01 01:37:30 +00001862 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
Evan Chengebdeeab2011-07-08 01:53:10 +00001863 << "ComputeAvailableFeatures(uint64_t FB) const {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001864 OS << " unsigned Features = 0;\n";
1865 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1866 it = Info.SubtargetFeatures.begin(),
1867 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1868 SubtargetFeatureInfo &SFI = *it->second;
Evan Chengebdeeab2011-07-08 01:53:10 +00001869
1870 OS << " if (";
Evan Chengfbc38d22011-07-08 18:04:22 +00001871 std::string CondStorage = SFI.TheDef->getValueAsString("AssemblerCondString");
1872 StringRef Conds = CondStorage;
Evan Chengebdeeab2011-07-08 01:53:10 +00001873 std::pair<StringRef,StringRef> Comma = Conds.split(',');
1874 bool First = true;
1875 do {
1876 if (!First)
1877 OS << " && ";
1878
1879 bool Neg = false;
1880 StringRef Cond = Comma.first;
1881 if (Cond[0] == '!') {
1882 Neg = true;
1883 Cond = Cond.substr(1);
1884 }
1885
1886 OS << "((FB & " << Info.Target.getName() << "::" << Cond << ")";
1887 if (Neg)
1888 OS << " == 0";
1889 else
1890 OS << " != 0";
1891 OS << ")";
1892
1893 if (Comma.second.empty())
1894 break;
1895
1896 First = false;
1897 Comma = Comma.second.split(',');
1898 } while (true);
1899
1900 OS << ")\n";
Chris Lattner0aed1e72010-10-30 20:07:57 +00001901 OS << " Features |= " << SFI.getEnumName() << ";\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001902 }
1903 OS << " return Features;\n";
1904 OS << "}\n\n";
1905}
1906
Chris Lattner6fa152c2010-10-30 20:15:02 +00001907static std::string GetAliasRequiredFeatures(Record *R,
1908 const AsmMatcherInfo &Info) {
Chris Lattner693173f2010-10-30 19:23:13 +00001909 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
Chris Lattner693173f2010-10-30 19:23:13 +00001910 std::string Result;
1911 unsigned NumFeatures = 0;
1912 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
Chris Lattner4a74ee72010-11-01 02:09:21 +00001913 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
Bob Wilson828295b2011-01-26 21:26:19 +00001914
Chris Lattner4a74ee72010-11-01 02:09:21 +00001915 if (F == 0)
1916 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
1917 "' is not marked as an AssemblerPredicate!");
Bob Wilson828295b2011-01-26 21:26:19 +00001918
Chris Lattner4a74ee72010-11-01 02:09:21 +00001919 if (NumFeatures)
1920 Result += '|';
Bob Wilson828295b2011-01-26 21:26:19 +00001921
Chris Lattner4a74ee72010-11-01 02:09:21 +00001922 Result += F->getEnumName();
1923 ++NumFeatures;
Chris Lattner693173f2010-10-30 19:23:13 +00001924 }
Bob Wilson828295b2011-01-26 21:26:19 +00001925
Chris Lattner693173f2010-10-30 19:23:13 +00001926 if (NumFeatures > 1)
1927 Result = '(' + Result + ')';
1928 return Result;
1929}
1930
Chris Lattner674c1dc2010-10-30 17:36:36 +00001931/// EmitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
Chris Lattner7fd44892010-10-30 18:48:18 +00001932/// emit a function for them and return true, otherwise return false.
Chris Lattner0aed1e72010-10-30 20:07:57 +00001933static bool EmitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
Daniel Dunbarc0a70072011-01-24 23:26:31 +00001934 // Ignore aliases when match-prefix is set.
1935 if (!MatchPrefix.empty())
1936 return false;
1937
Chris Lattner674c1dc2010-10-30 17:36:36 +00001938 std::vector<Record*> Aliases =
Chris Lattner67db8832010-12-13 00:23:57 +00001939 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
Chris Lattner7fd44892010-10-30 18:48:18 +00001940 if (Aliases.empty()) return false;
Chris Lattner674c1dc2010-10-30 17:36:36 +00001941
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00001942 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
Chris Lattner8cc0a6b2010-10-30 18:57:07 +00001943 "unsigned Features) {\n";
Bob Wilson828295b2011-01-26 21:26:19 +00001944
Chris Lattner4fd32c62010-10-30 18:56:12 +00001945 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
1946 // iteration order of the map is stable.
1947 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
Bob Wilson828295b2011-01-26 21:26:19 +00001948
Chris Lattner674c1dc2010-10-30 17:36:36 +00001949 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
1950 Record *R = Aliases[i];
Chris Lattner4fd32c62010-10-30 18:56:12 +00001951 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
Chris Lattner674c1dc2010-10-30 17:36:36 +00001952 }
Chris Lattner4fd32c62010-10-30 18:56:12 +00001953
1954 // Process each alias a "from" mnemonic at a time, building the code executed
1955 // by the string remapper.
1956 std::vector<StringMatcher::StringPair> Cases;
1957 for (std::map<std::string, std::vector<Record*> >::iterator
1958 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
1959 I != E; ++I) {
Chris Lattner4fd32c62010-10-30 18:56:12 +00001960 const std::vector<Record*> &ToVec = I->second;
Chris Lattner693173f2010-10-30 19:23:13 +00001961
1962 // Loop through each alias and emit code that handles each case. If there
1963 // are two instructions without predicates, emit an error. If there is one,
1964 // emit it last.
1965 std::string MatchCode;
1966 int AliasWithNoPredicate = -1;
Bob Wilson828295b2011-01-26 21:26:19 +00001967
Chris Lattner693173f2010-10-30 19:23:13 +00001968 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
1969 Record *R = ToVec[i];
Chris Lattner6fa152c2010-10-30 20:15:02 +00001970 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
Bob Wilson828295b2011-01-26 21:26:19 +00001971
Chris Lattner693173f2010-10-30 19:23:13 +00001972 // If this unconditionally matches, remember it for later and diagnose
1973 // duplicates.
1974 if (FeatureMask.empty()) {
1975 if (AliasWithNoPredicate != -1) {
1976 // We can't have two aliases from the same mnemonic with no predicate.
1977 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
1978 "two MnemonicAliases with the same 'from' mnemonic!");
Chris Lattner4164f6b2010-11-01 04:44:29 +00001979 throw TGError(R->getLoc(), "this is the other MnemonicAlias.");
Chris Lattner693173f2010-10-30 19:23:13 +00001980 }
Bob Wilson828295b2011-01-26 21:26:19 +00001981
Chris Lattner693173f2010-10-30 19:23:13 +00001982 AliasWithNoPredicate = i;
1983 continue;
1984 }
Joerg Sonnenberger6ef6ced2011-02-17 23:22:19 +00001985 if (R->getValueAsString("ToMnemonic") == I->first)
1986 throw TGError(R->getLoc(), "MnemonicAlias to the same string");
Bob Wilson828295b2011-01-26 21:26:19 +00001987
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00001988 if (!MatchCode.empty())
1989 MatchCode += "else ";
Chris Lattner693173f2010-10-30 19:23:13 +00001990 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
1991 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattner4fd32c62010-10-30 18:56:12 +00001992 }
Bob Wilson828295b2011-01-26 21:26:19 +00001993
Chris Lattner693173f2010-10-30 19:23:13 +00001994 if (AliasWithNoPredicate != -1) {
1995 Record *R = ToVec[AliasWithNoPredicate];
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00001996 if (!MatchCode.empty())
1997 MatchCode += "else\n ";
1998 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattner693173f2010-10-30 19:23:13 +00001999 }
Bob Wilson828295b2011-01-26 21:26:19 +00002000
Chris Lattner693173f2010-10-30 19:23:13 +00002001 MatchCode += "return;";
2002
2003 Cases.push_back(std::make_pair(I->first, MatchCode));
Chris Lattner4fd32c62010-10-30 18:56:12 +00002004 }
Bob Wilson828295b2011-01-26 21:26:19 +00002005
Chris Lattner674c1dc2010-10-30 17:36:36 +00002006 StringMatcher("Mnemonic", Cases, OS).Emit();
Daniel Dunbar55b5e852011-01-18 01:59:30 +00002007 OS << "}\n\n";
Bob Wilson828295b2011-01-26 21:26:19 +00002008
Chris Lattner7fd44892010-10-30 18:48:18 +00002009 return true;
Chris Lattner674c1dc2010-10-30 17:36:36 +00002010}
2011
Jim Grosbach194f3fa2012-03-01 17:30:35 +00002012static const char *getMinimalTypeForRange(uint64_t Range) {
2013 assert(Range < 0xFFFFFFFFULL && "Enum too large");
2014 if (Range > 0xFFFF)
2015 return "uint32_t";
2016 if (Range > 0xFF)
2017 return "uint16_t";
2018 return "uint8_t";
2019}
2020
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002021static void EmitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
2022 const AsmMatcherInfo &Info, StringRef ClassName) {
2023 // Emit the static custom operand parsing table;
2024 OS << "namespace {\n";
2025 OS << " struct OperandMatchEntry {\n";
Jakob Stoklund Olesen7044cce2012-03-15 21:22:53 +00002026 OS << " static const char *const MnemonicTable;\n";
Craig Topperfab3f7e2012-04-02 07:48:39 +00002027 OS << " uint32_t OperandMask;\n";
2028 OS << " uint32_t Mnemonic;\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002029 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
Craig Topperfab3f7e2012-04-02 07:48:39 +00002030 << " RequiredFeatures;\n";
2031 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2032 << " Class;\n\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002033 OS << " StringRef getMnemonic() const {\n";
2034 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2035 OS << " MnemonicTable[Mnemonic]);\n";
2036 OS << " }\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002037 OS << " };\n\n";
2038
2039 OS << " // Predicate for searching for an opcode.\n";
2040 OS << " struct LessOpcodeOperand {\n";
2041 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002042 OS << " return LHS.getMnemonic() < RHS;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002043 OS << " }\n";
2044 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002045 OS << " return LHS < RHS.getMnemonic();\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002046 OS << " }\n";
2047 OS << " bool operator()(const OperandMatchEntry &LHS,";
2048 OS << " const OperandMatchEntry &RHS) {\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002049 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002050 OS << " }\n";
2051 OS << " };\n";
2052
2053 OS << "} // end anonymous namespace.\n\n";
2054
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002055 StringToOffsetTable StringTable;
2056
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002057 OS << "static const OperandMatchEntry OperandMatchTable["
2058 << Info.OperandMatchInfo.size() << "] = {\n";
2059
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002060 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002061 for (std::vector<OperandMatchEntry>::const_iterator it =
2062 Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end();
2063 it != ie; ++it) {
2064 const OperandMatchEntry &OMI = *it;
2065 const MatchableInfo &II = *OMI.MI;
2066
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002067 OS << " { " << OMI.OperandMask;
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002068
2069 OS << " /* ";
2070 bool printComma = false;
2071 for (int i = 0, e = 31; i !=e; ++i)
2072 if (OMI.OperandMask & (1 << i)) {
2073 if (printComma)
2074 OS << ", ";
2075 OS << i;
2076 printComma = true;
2077 }
2078 OS << " */";
2079
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002080 // Store a pascal-style length byte in the mnemonic.
2081 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
Jakob Stoklund Olesenbcfa9822012-03-15 18:05:57 +00002082 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
Craig Topperfab3f7e2012-04-02 07:48:39 +00002083 << " /* " << II.Mnemonic << " */, ";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002084
2085 // Write the required features mask.
2086 if (!II.RequiredFeatures.empty()) {
2087 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2088 if (i) OS << "|";
2089 OS << II.RequiredFeatures[i]->getEnumName();
2090 }
2091 } else
2092 OS << "0";
Craig Topperfab3f7e2012-04-02 07:48:39 +00002093
2094 OS << ", " << OMI.CI->Name;
2095
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002096 OS << " },\n";
2097 }
2098 OS << "};\n\n";
2099
Jakob Stoklund Olesen7044cce2012-03-15 21:22:53 +00002100 OS << "const char *const OperandMatchEntry::MnemonicTable =\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002101 StringTable.EmitString(OS);
2102 OS << ";\n\n";
2103
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002104 // Emit the operand class switch to call the correct custom parser for
2105 // the found operand class.
Jim Grosbachf922c472011-02-12 01:34:40 +00002106 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2107 << Target.getName() << ClassName << "::\n"
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00002108 << "tryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>"
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002109 << " &Operands,\n unsigned MCK) {\n\n"
2110 << " switch(MCK) {\n";
2111
2112 for (std::vector<ClassInfo*>::const_iterator it = Info.Classes.begin(),
2113 ie = Info.Classes.end(); it != ie; ++it) {
2114 ClassInfo *CI = *it;
2115 if (CI->ParserMethod.empty())
2116 continue;
2117 OS << " case " << CI->Name << ":\n"
2118 << " return " << CI->ParserMethod << "(Operands);\n";
2119 }
2120
2121 OS << " default:\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002122 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002123 OS << " }\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002124 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002125 OS << "}\n\n";
2126
2127 // Emit the static custom operand parser. This code is very similar with
2128 // the other matcher. Also use MatchResultTy here just in case we go for
2129 // a better error handling.
Jim Grosbachf922c472011-02-12 01:34:40 +00002130 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002131 << Target.getName() << ClassName << "::\n"
2132 << "MatchOperandParserImpl(SmallVectorImpl<MCParsedAsmOperand*>"
2133 << " &Operands,\n StringRef Mnemonic) {\n";
2134
2135 // Emit code to get the available features.
2136 OS << " // Get the current feature set.\n";
2137 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2138
2139 OS << " // Get the next operand index.\n";
2140 OS << " unsigned NextOpNum = Operands.size()-1;\n";
2141
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002142 // Emit code to search the table.
2143 OS << " // Search the table.\n";
2144 OS << " std::pair<const OperandMatchEntry*, const OperandMatchEntry*>";
2145 OS << " MnemonicRange =\n";
2146 OS << " std::equal_range(OperandMatchTable, OperandMatchTable+"
2147 << Info.OperandMatchInfo.size() << ", Mnemonic,\n"
2148 << " LessOpcodeOperand());\n\n";
2149
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002150 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002151 OS << " return MatchOperand_NoMatch;\n\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002152
2153 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2154 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2155
2156 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002157 OS << " assert(Mnemonic == it->getMnemonic());\n\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002158
2159 // Emit check that the required features are available.
2160 OS << " // check if the available features match\n";
2161 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2162 << "!= it->RequiredFeatures) {\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002163 OS << " continue;\n";
2164 OS << " }\n\n";
2165
2166 // Emit check to ensure the operand number matches.
2167 OS << " // check if the operand in question has a custom parser.\n";
2168 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2169 OS << " continue;\n\n";
2170
2171 // Emit call to the custom parser method
2172 OS << " // call custom parse method to handle the operand\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002173 OS << " OperandMatchResultTy Result = ";
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00002174 OS << "tryCustomParseOperand(Operands, it->Class);\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002175 OS << " if (Result != MatchOperand_NoMatch)\n";
2176 OS << " return Result;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002177 OS << " }\n\n";
2178
Jim Grosbachf922c472011-02-12 01:34:40 +00002179 OS << " // Okay, we had no match.\n";
2180 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002181 OS << "}\n\n";
2182}
2183
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00002184void AsmMatcherEmitter::run(raw_ostream &OS) {
Chris Lattner67db8832010-12-13 00:23:57 +00002185 CodeGenTarget Target(Records);
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00002186 Record *AsmParser = Target.getAsmParser();
2187 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2188
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002189 // Compute the information on the instructions to match.
Chris Lattner67db8832010-12-13 00:23:57 +00002190 AsmMatcherInfo Info(AsmParser, Target, Records);
Chris Lattner02bcbc92010-11-01 01:37:30 +00002191 Info.BuildInfo();
Daniel Dunbara027d222009-07-31 02:32:59 +00002192
Daniel Dunbare1f6de32010-02-02 23:46:36 +00002193 // Sort the instruction table using the partial order on classes. We use
2194 // stable_sort to ensure that ambiguous instructions are still
2195 // deterministically ordered.
Chris Lattner22bc5c42010-11-01 05:06:45 +00002196 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2197 less_ptr<MatchableInfo>());
Jim Grosbacha7c78222010-10-29 22:13:48 +00002198
Daniel Dunbarb7479c02009-08-08 05:24:34 +00002199 DEBUG_WITH_TYPE("instruction_info", {
Chris Lattner22bc5c42010-11-01 05:06:45 +00002200 for (std::vector<MatchableInfo*>::iterator
2201 it = Info.Matchables.begin(), ie = Info.Matchables.end();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002202 it != ie; ++it)
Daniel Dunbar20927f22009-08-07 08:26:05 +00002203 (*it)->dump();
2204 });
Daniel Dunbara027d222009-07-31 02:32:59 +00002205
Chris Lattner22bc5c42010-11-01 05:06:45 +00002206 // Check for ambiguous matchables.
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00002207 DEBUG_WITH_TYPE("ambiguous_instrs", {
2208 unsigned NumAmbiguous = 0;
Chris Lattner22bc5c42010-11-01 05:06:45 +00002209 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) {
Chris Lattner87410362010-09-06 20:21:47 +00002210 for (unsigned j = i + 1; j != e; ++j) {
Chris Lattner22bc5c42010-11-01 05:06:45 +00002211 MatchableInfo &A = *Info.Matchables[i];
2212 MatchableInfo &B = *Info.Matchables[j];
Jim Grosbacha7c78222010-10-29 22:13:48 +00002213
Bob Wilson1f64ac42011-01-26 21:26:21 +00002214 if (A.CouldMatchAmbiguouslyWith(B)) {
Chris Lattner22bc5c42010-11-01 05:06:45 +00002215 errs() << "warning: ambiguous matchables:\n";
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00002216 A.dump();
2217 errs() << "\nis incomparable with:\n";
2218 B.dump();
2219 errs() << "\n\n";
Chris Lattner87410362010-09-06 20:21:47 +00002220 ++NumAmbiguous;
2221 }
Daniel Dunbar2b544812009-08-09 06:05:33 +00002222 }
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00002223 }
Chris Lattner87410362010-09-06 20:21:47 +00002224 if (NumAmbiguous)
Jim Grosbacha7c78222010-10-29 22:13:48 +00002225 errs() << "warning: " << NumAmbiguous
Chris Lattner22bc5c42010-11-01 05:06:45 +00002226 << " ambiguous matchables!\n";
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00002227 });
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00002228
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002229 // Compute the information on the custom operand parsing.
2230 Info.BuildOperandMatchInfo();
2231
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00002232 // Write the output.
2233
2234 EmitSourceFileHeader("Assembly Matcher Source Fragment", OS);
2235
Chris Lattner0692ee62010-09-06 19:11:01 +00002236 // Information for the class declaration.
2237 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2238 OS << "#undef GET_ASSEMBLER_HEADER\n";
Jim Grosbach84cb0332011-02-11 21:31:55 +00002239 OS << " // This should be included into the middle of the declaration of\n";
Evan Cheng94b95502011-07-26 00:24:13 +00002240 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
Evan Chengebdeeab2011-07-08 01:53:10 +00002241 OS << " unsigned ComputeAvailableFeatures(uint64_t FeatureBits) const;\n";
Daniel Dunbar5c228a92011-02-04 23:17:40 +00002242 OS << " bool ConvertToMCInst(unsigned Kind, MCInst &Inst, "
2243 << "unsigned Opcode,\n"
2244 << " const SmallVectorImpl<MCParsedAsmOperand*> "
2245 << "&Operands);\n";
Bob Wilson1fe3aa12011-01-26 21:43:46 +00002246 OS << " bool MnemonicIsValid(StringRef Mnemonic);\n";
Jim Grosbach19cb7f42011-08-15 23:03:29 +00002247 OS << " unsigned MatchInstructionImpl(\n";
Daniel Dunbar083203d2011-01-10 15:26:11 +00002248 OS << " const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
Devang Patel56315d32012-01-10 17:50:43 +00002249 OS << " MCInst &Inst, unsigned &ErrorInfo, unsigned VariantID = 0);\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002250
2251 if (Info.OperandMatchInfo.size()) {
Jim Grosbachf922c472011-02-12 01:34:40 +00002252 OS << "\n enum OperandMatchResultTy {\n";
2253 OS << " MatchOperand_Success, // operand matched successfully\n";
2254 OS << " MatchOperand_NoMatch, // operand did not match\n";
2255 OS << " MatchOperand_ParseFail // operand matched but had errors\n";
2256 OS << " };\n";
2257 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002258 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2259 OS << " StringRef Mnemonic);\n";
2260
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00002261 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002262 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2263 OS << " unsigned MCK);\n\n";
2264 }
2265
Chris Lattner0692ee62010-09-06 19:11:01 +00002266 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2267
Chris Lattner0692ee62010-09-06 19:11:01 +00002268 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2269 OS << "#undef GET_REGISTER_MATCHER\n\n";
2270
Daniel Dunbar54074b52010-07-19 05:44:09 +00002271 // Emit the subtarget feature enumeration.
Chris Lattner02bcbc92010-11-01 01:37:30 +00002272 EmitSubtargetFeatureFlagEnumeration(Info, OS);
Daniel Dunbar54074b52010-07-19 05:44:09 +00002273
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00002274 // Emit the function to match a register name to number.
2275 EmitMatchRegisterName(Target, AsmParser, OS);
Chris Lattner0692ee62010-09-06 19:11:01 +00002276
2277 OS << "#endif // GET_REGISTER_MATCHER\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002278
Chris Lattner0692ee62010-09-06 19:11:01 +00002279
2280 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2281 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00002282
Chris Lattner7fd44892010-10-30 18:48:18 +00002283 // Generate the function that remaps for mnemonic aliases.
Chris Lattner0aed1e72010-10-30 20:07:57 +00002284 bool HasMnemonicAliases = EmitMnemonicAliases(OS, Info);
Bob Wilson828295b2011-01-26 21:26:19 +00002285
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00002286 // Generate the unified function to convert operands into an MCInst.
Daniel Dunbar5c228a92011-02-04 23:17:40 +00002287 EmitConvertToMCInst(Target, ClassName, Info.Matchables, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00002288
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002289 // Emit the enumeration for classes which participate in matching.
2290 EmitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00002291
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002292 // Emit the routine to match token strings to their match class.
2293 EmitMatchTokenString(Target, Info.Classes, OS);
2294
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00002295 // Emit the subclass predicate routine.
2296 EmitIsSubclass(Target, Info.Classes, OS);
2297
Jim Grosbachb9db0c52011-02-10 00:08:28 +00002298 // Emit the routine to validate an operand against a match class.
2299 EmitValidateOperandClass(Info, OS);
2300
Daniel Dunbar54074b52010-07-19 05:44:09 +00002301 // Emit the available features compute function.
Chris Lattner02bcbc92010-11-01 01:37:30 +00002302 EmitComputeAvailableFeatures(Info, OS);
Daniel Dunbar54074b52010-07-19 05:44:09 +00002303
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002304
2305 size_t MaxNumOperands = 0;
Chris Lattner22bc5c42010-11-01 05:06:45 +00002306 for (std::vector<MatchableInfo*>::const_iterator it =
2307 Info.Matchables.begin(), ie = Info.Matchables.end();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002308 it != ie; ++it)
Chris Lattner3116fef2010-11-02 01:03:43 +00002309 MaxNumOperands = std::max(MaxNumOperands, (*it)->AsmOperands.size());
Jim Grosbacha7c78222010-10-29 22:13:48 +00002310
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002311 // Emit the static match table; unused classes get initalized to 0 which is
2312 // guaranteed to be InvalidMatchClass.
2313 //
2314 // FIXME: We can reduce the size of this table very easily. First, we change
2315 // it so that store the kinds in separate bit-fields for each index, which
2316 // only needs to be the max width used for classes at that index (we also need
2317 // to reject based on this during classification). If we then make sure to
2318 // order the match kinds appropriately (putting mnemonics last), then we
2319 // should only end up using a few bits for each class, especially the ones
2320 // following the mnemonic.
Chris Lattner96352e52010-09-06 21:08:38 +00002321 OS << "namespace {\n";
2322 OS << " struct MatchEntry {\n";
Jakob Stoklund Olesen7044cce2012-03-15 21:22:53 +00002323 OS << " static const char *const MnemonicTable;\n";
Craig Topperfab3f7e2012-04-02 07:48:39 +00002324 OS << " uint32_t Mnemonic;\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002325 OS << " uint16_t Opcode;\n";
Benjamin Krameraf482cf2011-10-17 16:18:09 +00002326 OS << " " << getMinimalTypeForRange(Info.Matchables.size())
2327 << " ConvertFn;\n";
Benjamin Krameraf482cf2011-10-17 16:18:09 +00002328 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2329 << " RequiredFeatures;\n";
Craig Topperfab3f7e2012-04-02 07:48:39 +00002330 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2331 << " Classes[" << MaxNumOperands << "];\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002332 OS << " uint8_t AsmVariantID;\n\n";
2333 OS << " StringRef getMnemonic() const {\n";
2334 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2335 OS << " MnemonicTable[Mnemonic]);\n";
2336 OS << " }\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002337 OS << " };\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002338
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002339 OS << " // Predicate for searching for an opcode.\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002340 OS << " struct LessOpcode {\n";
2341 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002342 OS << " return LHS.getMnemonic() < RHS;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002343 OS << " }\n";
2344 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002345 OS << " return LHS < RHS.getMnemonic();\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002346 OS << " }\n";
Chris Lattner32c685c2010-09-07 06:10:48 +00002347 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002348 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Chris Lattner32c685c2010-09-07 06:10:48 +00002349 OS << " }\n";
Chris Lattner96352e52010-09-06 21:08:38 +00002350 OS << " };\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002351
Chris Lattner96352e52010-09-06 21:08:38 +00002352 OS << "} // end anonymous namespace.\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002353
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002354 StringToOffsetTable StringTable;
2355
Chris Lattner96352e52010-09-06 21:08:38 +00002356 OS << "static const MatchEntry MatchTable["
Chris Lattner22bc5c42010-11-01 05:06:45 +00002357 << Info.Matchables.size() << "] = {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002358
Chris Lattner22bc5c42010-11-01 05:06:45 +00002359 for (std::vector<MatchableInfo*>::const_iterator it =
2360 Info.Matchables.begin(), ie = Info.Matchables.end();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002361 it != ie; ++it) {
Chris Lattner22bc5c42010-11-01 05:06:45 +00002362 MatchableInfo &II = **it;
Jim Grosbacha7c78222010-10-29 22:13:48 +00002363
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002364 // Store a pascal-style length byte in the mnemonic.
2365 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
Craig Topperfab3f7e2012-04-02 07:48:39 +00002366 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2367 << " /* " << II.Mnemonic << " */, "
2368 << Target.getName() << "::"
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002369 << II.getResultInst()->TheDef->getName() << ", "
Craig Topperfab3f7e2012-04-02 07:48:39 +00002370 << II.ConversionFnKind << ", ";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002371
Daniel Dunbar54074b52010-07-19 05:44:09 +00002372 // Write the required features mask.
2373 if (!II.RequiredFeatures.empty()) {
2374 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2375 if (i) OS << "|";
Chris Lattner0aed1e72010-10-30 20:07:57 +00002376 OS << II.RequiredFeatures[i]->getEnumName();
Daniel Dunbar54074b52010-07-19 05:44:09 +00002377 }
2378 } else
2379 OS << "0";
Craig Topperfab3f7e2012-04-02 07:48:39 +00002380
2381 OS << ", { ";
2382 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
2383 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
2384
2385 if (i) OS << ", ";
2386 OS << Op.Class->Name;
2387 }
2388 OS << " }, " << II.AsmVariantID;
Daniel Dunbar54074b52010-07-19 05:44:09 +00002389 OS << "},\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00002390 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00002391
Chris Lattner96352e52010-09-06 21:08:38 +00002392 OS << "};\n\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00002393
Jakob Stoklund Olesen7044cce2012-03-15 21:22:53 +00002394 OS << "const char *const MatchEntry::MnemonicTable =\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002395 StringTable.EmitString(OS);
2396 OS << ";\n\n";
2397
Bob Wilson1fe3aa12011-01-26 21:43:46 +00002398 // A method to determine if a mnemonic is in the list.
2399 OS << "bool " << Target.getName() << ClassName << "::\n"
2400 << "MnemonicIsValid(StringRef Mnemonic) {\n";
2401 OS << " // Search the table.\n";
2402 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2403 OS << " std::equal_range(MatchTable, MatchTable+"
2404 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n";
2405 OS << " return MnemonicRange.first != MnemonicRange.second;\n";
2406 OS << "}\n\n";
2407
Chris Lattner96352e52010-09-06 21:08:38 +00002408 // Finally, build the match function.
Jim Grosbach19cb7f42011-08-15 23:03:29 +00002409 OS << "unsigned "
Chris Lattner96352e52010-09-06 21:08:38 +00002410 << Target.getName() << ClassName << "::\n"
2411 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
2412 << " &Operands,\n";
Devang Patel56315d32012-01-10 17:50:43 +00002413 OS << " MCInst &Inst, unsigned &ErrorInfo,\n";
2414 OS << " unsigned VariantID) {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00002415
2416 // Emit code to get the available features.
2417 OS << " // Get the current feature set.\n";
2418 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2419
Chris Lattner674c1dc2010-10-30 17:36:36 +00002420 OS << " // Get the instruction mnemonic, which is the first token.\n";
2421 OS << " StringRef Mnemonic = ((" << Target.getName()
2422 << "Operand*)Operands[0])->getToken();\n\n";
2423
Chris Lattner7fd44892010-10-30 18:48:18 +00002424 if (HasMnemonicAliases) {
2425 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
Devang Patel40bced02012-01-17 18:30:45 +00002426 OS << " // FIXME : Add an entry in AsmParserVariant to check this.\n";
2427 OS << " if (!VariantID)\n";
2428 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
Chris Lattner7fd44892010-10-30 18:48:18 +00002429 }
Bob Wilson828295b2011-01-26 21:26:19 +00002430
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002431 // Emit code to compute the class list for this operand vector.
2432 OS << " // Eliminate obvious mismatches.\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00002433 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
2434 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
2435 OS << " return Match_InvalidOperand;\n";
2436 OS << " }\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002437
Chris Lattner9bb9fa12010-09-06 23:37:39 +00002438 OS << " // Some state to try to produce better error messages.\n";
Jim Grosbach19cb7f42011-08-15 23:03:29 +00002439 OS << " bool HadMatchOtherThanFeatures = false;\n";
Jim Grosbach578071a2011-08-16 20:12:35 +00002440 OS << " bool HadMatchOtherThanPredicate = false;\n";
Jim Grosbach19cb7f42011-08-15 23:03:29 +00002441 OS << " unsigned RetCode = Match_InvalidOperand;\n";
Jim Grosbach84cb0332011-02-11 21:31:55 +00002442 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00002443 OS << " // wrong for all instances of the instruction.\n";
2444 OS << " ErrorInfo = ~0U;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002445
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002446 // Emit code to search the table.
2447 OS << " // Search the table.\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002448 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2449 OS << " std::equal_range(MatchTable, MatchTable+"
Chris Lattner22bc5c42010-11-01 05:06:45 +00002450 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002451
Chris Lattnera008e8a2010-09-06 21:54:15 +00002452 OS << " // Return a more specific error code if no mnemonics match.\n";
2453 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2454 OS << " return Match_MnemonicFail;\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002455
Chris Lattner2b1f9432010-09-06 21:22:45 +00002456 OS << " for (const MatchEntry *it = MnemonicRange.first, "
Chris Lattner80db4e52010-09-06 21:23:43 +00002457 << "*ie = MnemonicRange.second;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002458 OS << " it != ie; ++it) {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00002459
Gabor Greife53ee3b2010-09-07 06:06:06 +00002460 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002461 OS << " assert(Mnemonic == it->getMnemonic());\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002462
Daniel Dunbar54074b52010-07-19 05:44:09 +00002463 // Emit check that the subclasses match.
Devang Patel56315d32012-01-10 17:50:43 +00002464 OS << " if (VariantID != it->AsmVariantID) continue;\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00002465 OS << " bool OperandsValid = true;\n";
2466 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
Jim Grosbachb9db0c52011-02-10 00:08:28 +00002467 OS << " if (i + 1 >= Operands.size()) {\n";
2468 OS << " OperandsValid = (it->Classes[i] == " <<"InvalidMatchClass);\n";
Jim Grosbachb9d5af02011-05-03 19:09:56 +00002469 OS << " break;\n";
Jim Grosbachb9db0c52011-02-10 00:08:28 +00002470 OS << " }\n";
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00002471 OS << " if (validateOperandClass(Operands[i+1], "
Benjamin Krameraf482cf2011-10-17 16:18:09 +00002472 "(MatchClassKind)it->Classes[i]))\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00002473 OS << " continue;\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00002474 OS << " // If this operand is broken for all of the instances of this\n";
2475 OS << " // mnemonic, keep track of it so we can report loc info.\n";
Kevin Enderby79fcb6d2011-02-02 18:20:55 +00002476 OS << " if (it == MnemonicRange.first || ErrorInfo <= i+1)\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00002477 OS << " ErrorInfo = i+1;\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00002478 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
2479 OS << " OperandsValid = false;\n";
2480 OS << " break;\n";
2481 OS << " }\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002482
Chris Lattnerce4a3352010-09-06 22:11:18 +00002483 OS << " if (!OperandsValid) continue;\n";
Chris Lattnerec6789f2010-09-06 20:08:02 +00002484
2485 // Emit check that the required features are available.
2486 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2487 << "!= it->RequiredFeatures) {\n";
2488 OS << " HadMatchOtherThanFeatures = true;\n";
2489 OS << " continue;\n";
2490 OS << " }\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002491 OS << "\n";
Daniel Dunbarb4129152011-02-04 17:12:23 +00002492 OS << " // We have selected a definite instruction, convert the parsed\n"
2493 << " // operands into the appropriate MCInst.\n";
2494 OS << " if (!ConvertToMCInst(it->ConvertFn, Inst,\n"
2495 << " it->Opcode, Operands))\n";
2496 OS << " return Match_ConversionFail;\n";
2497 OS << "\n";
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00002498
Jim Grosbach19cb7f42011-08-15 23:03:29 +00002499 // Verify the instruction with the target-specific match predicate function.
2500 OS << " // We have a potential match. Check the target predicate to\n"
2501 << " // handle any context sensitive constraints.\n"
2502 << " unsigned MatchResult;\n"
2503 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
2504 << " Match_Success) {\n"
2505 << " Inst.clear();\n"
2506 << " RetCode = MatchResult;\n"
Jim Grosbach578071a2011-08-16 20:12:35 +00002507 << " HadMatchOtherThanPredicate = true;\n"
Jim Grosbach19cb7f42011-08-15 23:03:29 +00002508 << " continue;\n"
2509 << " }\n\n";
2510
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00002511 // Call the post-processing function, if used.
2512 std::string InsnCleanupFn =
2513 AsmParser->getValueAsString("AsmParserInstCleanup");
2514 if (!InsnCleanupFn.empty())
2515 OS << " " << InsnCleanupFn << "(Inst);\n";
2516
Chris Lattner79ed3f72010-09-06 19:22:17 +00002517 OS << " return Match_Success;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002518 OS << " }\n\n";
2519
Chris Lattnerec6789f2010-09-06 20:08:02 +00002520 OS << " // Okay, we had no match. Try to return a useful error code.\n";
Jim Grosbach578071a2011-08-16 20:12:35 +00002521 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)";
2522 OS << " return RetCode;\n";
2523 OS << " return Match_MissingFeature;\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00002524 OS << "}\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002525
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002526 if (Info.OperandMatchInfo.size())
2527 EmitCustomOperandParsing(OS, Target, Info, ClassName);
2528
Chris Lattner0692ee62010-09-06 19:11:01 +00002529 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbard51ffcf2009-07-11 19:39:44 +00002530}