blob: e980b1a7d9d4bf178e4c8eddc00a1d0e8bd79f8d [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
Daniel Dunbard51ffcf2009-07-11 19:39:44 +000099#include "CodeGenTarget.h"
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +0000100#include "StringToOffsetTable.h"
Daniel Dunbar20927f22009-08-07 08:26:05 +0000101#include "llvm/ADT/OwningPtr.h"
Chris Lattnerc07bd402010-11-04 02:11:18 +0000102#include "llvm/ADT/PointerUnion.h"
Chris Lattner1de88232010-11-01 01:47:07 +0000103#include "llvm/ADT/SmallPtrSet.h"
Daniel Dunbara027d222009-07-31 02:32:59 +0000104#include "llvm/ADT/SmallVector.h"
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000105#include "llvm/ADT/STLExtras.h"
Daniel Dunbar20927f22009-08-07 08:26:05 +0000106#include "llvm/ADT/StringExtras.h"
107#include "llvm/Support/CommandLine.h"
Daniel Dunbara027d222009-07-31 02:32:59 +0000108#include "llvm/Support/Debug.h"
Craig Topper655b8de2012-02-05 07:21:30 +0000109#include "llvm/Support/ErrorHandling.h"
Peter Collingbourne7c788882011-10-01 16:41:13 +0000110#include "llvm/TableGen/Error.h"
111#include "llvm/TableGen/Record.h"
Douglas Gregorf657da22012-05-02 17:32:48 +0000112#include "llvm/TableGen/StringMatcher.h"
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000113#include "llvm/TableGen/TableGenBackend.h"
114#include <cassert>
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000115#include <map>
116#include <set>
Daniel Dunbard51ffcf2009-07-11 19:39:44 +0000117using namespace llvm;
118
Daniel Dunbar27249152009-08-07 20:33:39 +0000119static cl::opt<std::string>
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000120MatchPrefix("match-prefix", cl::init(""),
121 cl::desc("Only match instructions with the given prefix"));
Daniel Dunbar20927f22009-08-07 08:26:05 +0000122
Daniel Dunbar20927f22009-08-07 08:26:05 +0000123namespace {
Bob Wilson828295b2011-01-26 21:26:19 +0000124class AsmMatcherInfo;
Daniel Dunbar54074b52010-07-19 05:44:09 +0000125struct SubtargetFeatureInfo;
126
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000127class AsmMatcherEmitter {
128 RecordKeeper &Records;
129public:
130 AsmMatcherEmitter(RecordKeeper &R) : Records(R) {}
131
132 void run(raw_ostream &o);
133};
134
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000135/// ClassInfo - Helper class for storing the information about a particular
136/// class of operands which can be matched.
137struct ClassInfo {
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000138 enum ClassInfoKind {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000139 /// Invalid kind, for use as a sentinel value.
140 Invalid = 0,
141
142 /// The class for a particular token.
143 Token,
144
145 /// The (first) register class, subsequent register classes are
146 /// RegisterClass0+1, and so on.
147 RegisterClass0,
148
149 /// The (first) user defined class, subsequent user defined classes are
150 /// UserClass0+1, and so on.
151 UserClass0 = 1<<16
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000152 };
153
154 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
155 /// N) for the Nth user defined class.
156 unsigned Kind;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000157
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000158 /// SuperClasses - The super classes of this class. Note that for simplicities
159 /// sake user operands only record their immediate super class, while register
160 /// operands include all superclasses.
161 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000162
Daniel Dunbar6745d422009-08-09 05:18:30 +0000163 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000164 std::string Name;
165
Daniel Dunbar6745d422009-08-09 05:18:30 +0000166 /// ClassName - The unadorned generic name for this class (e.g., Token).
167 std::string ClassName;
168
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000169 /// ValueName - The name of the value this class represents; for a token this
170 /// is the literal token string, for an operand it is the TableGen class (or
171 /// empty if this is a derived class).
172 std::string ValueName;
173
174 /// PredicateMethod - The name of the operand method to test whether the
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000175 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000176 std::string PredicateMethod;
177
178 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000179 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000180 std::string RenderMethod;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000181
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000182 /// ParserMethod - The name of the operand method to do a target specific
183 /// parsing on the operand.
184 std::string ParserMethod;
185
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000186 /// For register classes, the records for all the registers in this class.
187 std::set<Record*> Registers;
188
189public:
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000190 /// isRegisterClass() - Check if this is a register class.
191 bool isRegisterClass() const {
192 return Kind >= RegisterClass0 && Kind < UserClass0;
193 }
194
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000195 /// isUserClass() - Check if this is a user defined class.
196 bool isUserClass() const {
197 return Kind >= UserClass0;
198 }
199
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000200 /// isRelatedTo - Check whether this class is "related" to \arg RHS. Classes
201 /// are related if they are in the same class hierarchy.
202 bool isRelatedTo(const ClassInfo &RHS) const {
203 // Tokens are only related to tokens.
204 if (Kind == Token || RHS.Kind == Token)
205 return Kind == Token && RHS.Kind == Token;
206
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000207 // Registers classes are only related to registers classes, and only if
208 // their intersection is non-empty.
209 if (isRegisterClass() || RHS.isRegisterClass()) {
210 if (!isRegisterClass() || !RHS.isRegisterClass())
211 return false;
212
213 std::set<Record*> Tmp;
214 std::insert_iterator< std::set<Record*> > II(Tmp, Tmp.begin());
Jim Grosbacha7c78222010-10-29 22:13:48 +0000215 std::set_intersection(Registers.begin(), Registers.end(),
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000216 RHS.Registers.begin(), RHS.Registers.end(),
217 II);
218
219 return !Tmp.empty();
220 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000221
222 // Otherwise we have two users operands; they are related if they are in the
223 // same class hierarchy.
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000224 //
225 // FIXME: This is an oversimplification, they should only be related if they
226 // intersect, however we don't have that information.
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000227 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
228 const ClassInfo *Root = this;
229 while (!Root->SuperClasses.empty())
230 Root = Root->SuperClasses.front();
231
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000232 const ClassInfo *RHSRoot = &RHS;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000233 while (!RHSRoot->SuperClasses.empty())
234 RHSRoot = RHSRoot->SuperClasses.front();
Jim Grosbacha7c78222010-10-29 22:13:48 +0000235
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000236 return Root == RHSRoot;
237 }
238
Jim Grosbacha7c78222010-10-29 22:13:48 +0000239 /// isSubsetOf - Test whether this class is a subset of \arg RHS;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000240 bool isSubsetOf(const ClassInfo &RHS) const {
241 // This is a subset of RHS if it is the same class...
242 if (this == &RHS)
243 return true;
244
245 // ... or if any of its super classes are a subset of RHS.
246 for (std::vector<ClassInfo*>::const_iterator it = SuperClasses.begin(),
247 ie = SuperClasses.end(); it != ie; ++it)
248 if ((*it)->isSubsetOf(RHS))
249 return true;
250
251 return false;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000252 }
253
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000254 /// operator< - Compare two classes.
255 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar368a4562010-05-27 05:31:32 +0000256 if (this == &RHS)
257 return false;
258
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000259 // Unrelated classes can be ordered by kind.
260 if (!isRelatedTo(RHS))
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000261 return Kind < RHS.Kind;
262
263 switch (Kind) {
Daniel Dunbar6745d422009-08-09 05:18:30 +0000264 case Invalid:
Craig Topper655b8de2012-02-05 07:21:30 +0000265 llvm_unreachable("Invalid kind!");
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000266
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000267 default:
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000268 // This class precedes the RHS if it is a proper subset of the RHS.
Daniel Dunbar368a4562010-05-27 05:31:32 +0000269 if (isSubsetOf(RHS))
Duncan Sands34727662010-07-12 08:16:59 +0000270 return true;
Daniel Dunbar368a4562010-05-27 05:31:32 +0000271 if (RHS.isSubsetOf(*this))
Duncan Sands34727662010-07-12 08:16:59 +0000272 return false;
Daniel Dunbar368a4562010-05-27 05:31:32 +0000273
274 // Otherwise, order by name to ensure we have a total ordering.
275 return ValueName < RHS.ValueName;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000276 }
277 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000278};
279
Chris Lattner22bc5c42010-11-01 05:06:45 +0000280/// MatchableInfo - Helper class for storing the necessary information for an
281/// instruction or alias which is capable of being matched.
282struct MatchableInfo {
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000283 struct AsmOperand {
Chris Lattnerd19ec052010-11-02 17:30:52 +0000284 /// Token - This is the token that the operand came from.
285 StringRef Token;
Bob Wilson828295b2011-01-26 21:26:19 +0000286
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000287 /// The unique class instance this operand should match.
288 ClassInfo *Class;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000289
Chris Lattner567820c2010-11-04 01:42:59 +0000290 /// The operand name this is, if anything.
291 StringRef SrcOpName;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000292
293 /// The suboperand index within SrcOpName, or -1 for the entire operand.
294 int SubOpIdx;
Bob Wilson828295b2011-01-26 21:26:19 +0000295
Devang Patel63faf822012-01-07 01:33:34 +0000296 /// Register record if this token is singleton register.
297 Record *SingletonReg;
298
Jim Grosbachf35307c2012-01-24 21:06:59 +0000299 explicit AsmOperand(StringRef T) : Token(T), Class(0), SubOpIdx(-1),
Jim Grosbach11fc6462012-04-11 21:02:33 +0000300 SingletonReg(0) {}
Daniel Dunbar20927f22009-08-07 08:26:05 +0000301 };
Bob Wilson828295b2011-01-26 21:26:19 +0000302
Chris Lattner1d13bda2010-11-04 00:43:46 +0000303 /// ResOperand - This represents a single operand in the result instruction
304 /// generated by the match. In cases (like addressing modes) where a single
305 /// assembler operand expands to multiple MCOperands, this represents the
306 /// single assembler operand, not the MCOperand.
307 struct ResOperand {
308 enum {
309 /// RenderAsmOperand - This represents an operand result that is
310 /// generated by calling the render method on the assembly operand. The
311 /// corresponding AsmOperand is specified by AsmOperandNum.
312 RenderAsmOperand,
Bob Wilson828295b2011-01-26 21:26:19 +0000313
Chris Lattner1d13bda2010-11-04 00:43:46 +0000314 /// TiedOperand - This represents a result operand that is a duplicate of
315 /// a previous result operand.
Chris Lattner98c870f2010-11-06 19:25:43 +0000316 TiedOperand,
Bob Wilson828295b2011-01-26 21:26:19 +0000317
Chris Lattner98c870f2010-11-06 19:25:43 +0000318 /// ImmOperand - This represents an immediate value that is dumped into
319 /// the operand.
Chris Lattner90fd7972010-11-06 19:57:21 +0000320 ImmOperand,
Bob Wilson828295b2011-01-26 21:26:19 +0000321
Chris Lattner90fd7972010-11-06 19:57:21 +0000322 /// RegOperand - This represents a fixed register that is dumped in.
323 RegOperand
Chris Lattner1d13bda2010-11-04 00:43:46 +0000324 } Kind;
Bob Wilson828295b2011-01-26 21:26:19 +0000325
Chris Lattner1d13bda2010-11-04 00:43:46 +0000326 union {
327 /// This is the operand # in the AsmOperands list that this should be
328 /// copied from.
329 unsigned AsmOperandNum;
Bob Wilson828295b2011-01-26 21:26:19 +0000330
Chris Lattner1d13bda2010-11-04 00:43:46 +0000331 /// TiedOperandNum - This is the (earlier) result operand that should be
332 /// copied from.
333 unsigned TiedOperandNum;
Bob Wilson828295b2011-01-26 21:26:19 +0000334
Chris Lattner98c870f2010-11-06 19:25:43 +0000335 /// ImmVal - This is the immediate value added to the instruction.
336 int64_t ImmVal;
Bob Wilson828295b2011-01-26 21:26:19 +0000337
Chris Lattner90fd7972010-11-06 19:57:21 +0000338 /// Register - This is the register record.
339 Record *Register;
Chris Lattner1d13bda2010-11-04 00:43:46 +0000340 };
Bob Wilson828295b2011-01-26 21:26:19 +0000341
Bob Wilsona49c7df2011-01-26 19:44:55 +0000342 /// MINumOperands - The number of MCInst operands populated by this
343 /// operand.
344 unsigned MINumOperands;
Bob Wilson828295b2011-01-26 21:26:19 +0000345
Bob Wilsona49c7df2011-01-26 19:44:55 +0000346 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
Chris Lattner1d13bda2010-11-04 00:43:46 +0000347 ResOperand X;
348 X.Kind = RenderAsmOperand;
349 X.AsmOperandNum = AsmOpNum;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000350 X.MINumOperands = NumOperands;
Chris Lattner1d13bda2010-11-04 00:43:46 +0000351 return X;
352 }
Bob Wilson828295b2011-01-26 21:26:19 +0000353
Bob Wilsona49c7df2011-01-26 19:44:55 +0000354 static ResOperand getTiedOp(unsigned TiedOperandNum) {
Chris Lattner1d13bda2010-11-04 00:43:46 +0000355 ResOperand X;
356 X.Kind = TiedOperand;
357 X.TiedOperandNum = TiedOperandNum;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000358 X.MINumOperands = 1;
Chris Lattner1d13bda2010-11-04 00:43:46 +0000359 return X;
360 }
Bob Wilson828295b2011-01-26 21:26:19 +0000361
Bob Wilsona49c7df2011-01-26 19:44:55 +0000362 static ResOperand getImmOp(int64_t Val) {
Chris Lattner98c870f2010-11-06 19:25:43 +0000363 ResOperand X;
364 X.Kind = ImmOperand;
365 X.ImmVal = Val;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000366 X.MINumOperands = 1;
Chris Lattner98c870f2010-11-06 19:25:43 +0000367 return X;
368 }
Bob Wilson828295b2011-01-26 21:26:19 +0000369
Bob Wilsona49c7df2011-01-26 19:44:55 +0000370 static ResOperand getRegOp(Record *Reg) {
Chris Lattner90fd7972010-11-06 19:57:21 +0000371 ResOperand X;
372 X.Kind = RegOperand;
373 X.Register = Reg;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000374 X.MINumOperands = 1;
Chris Lattner90fd7972010-11-06 19:57:21 +0000375 return X;
376 }
Chris Lattner1d13bda2010-11-04 00:43:46 +0000377 };
Daniel Dunbar20927f22009-08-07 08:26:05 +0000378
Devang Patel56315d32012-01-10 17:50:43 +0000379 /// AsmVariantID - Target's assembly syntax variant no.
380 int AsmVariantID;
381
Chris Lattner3b5aec62010-11-02 17:34:28 +0000382 /// TheDef - This is the definition of the instruction or InstAlias that this
383 /// matchable came from.
Chris Lattner5bc93872010-11-01 04:34:44 +0000384 Record *const TheDef;
Bob Wilson828295b2011-01-26 21:26:19 +0000385
Chris Lattnerc07bd402010-11-04 02:11:18 +0000386 /// DefRec - This is the definition that it came from.
387 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
Bob Wilson828295b2011-01-26 21:26:19 +0000388
Chris Lattner662e5a32010-11-06 07:14:44 +0000389 const CodeGenInstruction *getResultInst() const {
390 if (DefRec.is<const CodeGenInstruction*>())
391 return DefRec.get<const CodeGenInstruction*>();
392 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
393 }
Bob Wilson828295b2011-01-26 21:26:19 +0000394
Chris Lattner1d13bda2010-11-04 00:43:46 +0000395 /// ResOperands - This is the operand list that should be built for the result
396 /// MCInst.
Jim Grosbachb423d182012-04-19 17:52:34 +0000397 SmallVector<ResOperand, 8> ResOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000398
399 /// AsmString - The assembly string for this instruction (with variants
Chris Lattner3b5aec62010-11-02 17:34:28 +0000400 /// removed), e.g. "movsx $src, $dst".
Daniel Dunbar20927f22009-08-07 08:26:05 +0000401 std::string AsmString;
402
Chris Lattnerd19ec052010-11-02 17:30:52 +0000403 /// Mnemonic - This is the first token of the matched instruction, its
404 /// mnemonic.
405 StringRef Mnemonic;
Bob Wilson828295b2011-01-26 21:26:19 +0000406
Chris Lattner3116fef2010-11-02 01:03:43 +0000407 /// AsmOperands - The textual operands that this instruction matches,
Chris Lattner3b5aec62010-11-02 17:34:28 +0000408 /// annotated with a class and where in the OperandList they were defined.
409 /// This directly corresponds to the tokenized AsmString after the mnemonic is
410 /// removed.
Jim Grosbachb423d182012-04-19 17:52:34 +0000411 SmallVector<AsmOperand, 8> AsmOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000412
Daniel Dunbar54074b52010-07-19 05:44:09 +0000413 /// Predicates - The required subtarget features to match this instruction.
414 SmallVector<SubtargetFeatureInfo*, 4> RequiredFeatures;
415
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000416 /// ConversionFnKind - The enum value which is passed to the generated
417 /// ConvertToMCInst to convert parsed operands into an MCInst for this
418 /// function.
419 std::string ConversionFnKind;
Bob Wilson828295b2011-01-26 21:26:19 +0000420
Chris Lattner22bc5c42010-11-01 05:06:45 +0000421 MatchableInfo(const CodeGenInstruction &CGI)
Jim Grosbachf35307c2012-01-24 21:06:59 +0000422 : AsmVariantID(0), TheDef(CGI.TheDef), DefRec(&CGI),
Devang Patel56315d32012-01-10 17:50:43 +0000423 AsmString(CGI.AsmString) {
Chris Lattner5bc93872010-11-01 04:34:44 +0000424 }
425
Chris Lattner22bc5c42010-11-01 05:06:45 +0000426 MatchableInfo(const CodeGenInstAlias *Alias)
Jim Grosbachf35307c2012-01-24 21:06:59 +0000427 : AsmVariantID(0), TheDef(Alias->TheDef), DefRec(Alias),
Devang Patel56315d32012-01-10 17:50:43 +0000428 AsmString(Alias->AsmString) {
Chris Lattnerc2d67bb2010-11-01 04:53:48 +0000429 }
Bob Wilson828295b2011-01-26 21:26:19 +0000430
Jim Grosbachc1922c72012-04-19 23:59:23 +0000431 // Two-operand aliases clone from the main matchable, but mark the second
432 // operand as a tied operand of the first for purposes of the assembler.
433 void formTwoOperandAlias(StringRef Constraint);
434
Jim Grosbach8caecde2012-04-19 17:52:32 +0000435 void initialize(const AsmMatcherInfo &Info,
Jim Grosbachf35307c2012-01-24 21:06:59 +0000436 SmallPtrSet<Record*, 16> &SingletonRegisters,
Jim Grosbach11fc6462012-04-11 21:02:33 +0000437 int AsmVariantNo, std::string &RegisterPrefix);
Bob Wilson828295b2011-01-26 21:26:19 +0000438
Jim Grosbach8caecde2012-04-19 17:52:32 +0000439 /// validate - Return true if this matchable is a valid thing to match against
Chris Lattner22bc5c42010-11-01 05:06:45 +0000440 /// and perform a bunch of validity checking.
Jim Grosbach8caecde2012-04-19 17:52:32 +0000441 bool validate(StringRef CommentDelimiter, bool Hack) const;
Bob Wilson828295b2011-01-26 21:26:19 +0000442
Jim Grosbachf35307c2012-01-24 21:06:59 +0000443 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
Devang Patel63faf822012-01-07 01:33:34 +0000444 /// if present, from specified token.
445 void
446 extractSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info,
447 std::string &RegisterPrefix);
Daniel Dunbar20927f22009-08-07 08:26:05 +0000448
Jim Grosbach8caecde2012-04-19 17:52:32 +0000449 /// findAsmOperand - Find the AsmOperand with the specified name and
Bob Wilsona49c7df2011-01-26 19:44:55 +0000450 /// suboperand index.
Jim Grosbach8caecde2012-04-19 17:52:32 +0000451 int findAsmOperand(StringRef N, int SubOpIdx) const {
Bob Wilsona49c7df2011-01-26 19:44:55 +0000452 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
453 if (N == AsmOperands[i].SrcOpName &&
454 SubOpIdx == AsmOperands[i].SubOpIdx)
455 return i;
456 return -1;
457 }
Bob Wilson828295b2011-01-26 21:26:19 +0000458
Jim Grosbach8caecde2012-04-19 17:52:32 +0000459 /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
Bob Wilsona49c7df2011-01-26 19:44:55 +0000460 /// This does not check the suboperand index.
Jim Grosbach8caecde2012-04-19 17:52:32 +0000461 int findAsmOperandNamed(StringRef N) const {
Chris Lattnerba3b5b62010-11-04 01:55:23 +0000462 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
463 if (N == AsmOperands[i].SrcOpName)
464 return i;
465 return -1;
466 }
Bob Wilson828295b2011-01-26 21:26:19 +0000467
Jim Grosbach8caecde2012-04-19 17:52:32 +0000468 void buildInstructionResultOperands();
469 void buildAliasResultOperands();
Chris Lattner1d13bda2010-11-04 00:43:46 +0000470
Chris Lattner22bc5c42010-11-01 05:06:45 +0000471 /// operator< - Compare two matchables.
472 bool operator<(const MatchableInfo &RHS) const {
Chris Lattnere206fcf2010-09-06 21:01:37 +0000473 // The primary comparator is the instruction mnemonic.
Chris Lattnerd19ec052010-11-02 17:30:52 +0000474 if (Mnemonic != RHS.Mnemonic)
475 return Mnemonic < RHS.Mnemonic;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000476
Chris Lattner3116fef2010-11-02 01:03:43 +0000477 if (AsmOperands.size() != RHS.AsmOperands.size())
478 return AsmOperands.size() < RHS.AsmOperands.size();
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000479
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000480 // Compare lexicographically by operand. The matcher validates that other
Jim Grosbach8caecde2012-04-19 17:52:32 +0000481 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
Chris Lattner3116fef2010-11-02 01:03:43 +0000482 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
483 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000484 return true;
Chris Lattner3116fef2010-11-02 01:03:43 +0000485 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000486 return false;
487 }
488
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000489 return false;
490 }
491
Jim Grosbach8caecde2012-04-19 17:52:32 +0000492 /// couldMatchAmbiguouslyWith - Check whether this matchable could
Daniel Dunbar2b544812009-08-09 06:05:33 +0000493 /// ambiguously match the same set of operands as \arg RHS (without being a
494 /// strictly superior match).
Jim Grosbach8caecde2012-04-19 17:52:32 +0000495 bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) {
Chris Lattnere66b7eb2010-11-01 23:57:23 +0000496 // The primary comparator is the instruction mnemonic.
Chris Lattnerd19ec052010-11-02 17:30:52 +0000497 if (Mnemonic != RHS.Mnemonic)
Chris Lattnere66b7eb2010-11-01 23:57:23 +0000498 return false;
Bob Wilson828295b2011-01-26 21:26:19 +0000499
Daniel Dunbar2b544812009-08-09 06:05:33 +0000500 // The number of operands is unambiguous.
Chris Lattner3116fef2010-11-02 01:03:43 +0000501 if (AsmOperands.size() != RHS.AsmOperands.size())
Daniel Dunbar2b544812009-08-09 06:05:33 +0000502 return false;
503
Daniel Dunbar1402f0b2010-01-23 00:26:16 +0000504 // Otherwise, make sure the ordering of the two instructions is unambiguous
505 // by checking that either (a) a token or operand kind discriminates them,
506 // or (b) the ordering among equivalent kinds is consistent.
507
Daniel Dunbar2b544812009-08-09 06:05:33 +0000508 // Tokens and operand kinds are unambiguous (assuming a correct target
509 // specific parser).
Chris Lattner3116fef2010-11-02 01:03:43 +0000510 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
511 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
512 AsmOperands[i].Class->Kind == ClassInfo::Token)
513 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
514 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbar2b544812009-08-09 06:05:33 +0000515 return false;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000516
Daniel Dunbar2b544812009-08-09 06:05:33 +0000517 // Otherwise, this operand could commute if all operands are equivalent, or
518 // there is a pair of operands that compare less than and a pair that
519 // compare greater than.
520 bool HasLT = false, HasGT = false;
Chris Lattner3116fef2010-11-02 01:03:43 +0000521 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
522 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbar2b544812009-08-09 06:05:33 +0000523 HasLT = true;
Chris Lattner3116fef2010-11-02 01:03:43 +0000524 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbar2b544812009-08-09 06:05:33 +0000525 HasGT = true;
526 }
527
528 return !(HasLT ^ HasGT);
529 }
530
Daniel Dunbar20927f22009-08-07 08:26:05 +0000531 void dump();
Bob Wilson828295b2011-01-26 21:26:19 +0000532
Chris Lattnerd19ec052010-11-02 17:30:52 +0000533private:
Jim Grosbach8caecde2012-04-19 17:52:32 +0000534 void tokenizeAsmString(const AsmMatcherInfo &Info);
Daniel Dunbar20927f22009-08-07 08:26:05 +0000535};
536
Daniel Dunbar54074b52010-07-19 05:44:09 +0000537/// SubtargetFeatureInfo - Helper class for storing information on a subtarget
538/// feature which participates in instruction matching.
539struct SubtargetFeatureInfo {
540 /// \brief The predicate record for this feature.
541 Record *TheDef;
542
543 /// \brief An unique index assigned to represent this feature.
544 unsigned Index;
545
Chris Lattner0aed1e72010-10-30 20:07:57 +0000546 SubtargetFeatureInfo(Record *D, unsigned Idx) : TheDef(D), Index(Idx) {}
Bob Wilson828295b2011-01-26 21:26:19 +0000547
Daniel Dunbar54074b52010-07-19 05:44:09 +0000548 /// \brief The name of the enumerated constant identifying this feature.
Chris Lattner0aed1e72010-10-30 20:07:57 +0000549 std::string getEnumName() const {
550 return "Feature_" + TheDef->getName();
551 }
Daniel Dunbar54074b52010-07-19 05:44:09 +0000552};
553
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000554struct OperandMatchEntry {
555 unsigned OperandMask;
556 MatchableInfo* MI;
557 ClassInfo *CI;
558
Jim Grosbach8caecde2012-04-19 17:52:32 +0000559 static OperandMatchEntry create(MatchableInfo* mi, ClassInfo *ci,
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000560 unsigned opMask) {
561 OperandMatchEntry X;
562 X.OperandMask = opMask;
563 X.CI = ci;
564 X.MI = mi;
565 return X;
566 }
567};
568
569
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000570class AsmMatcherInfo {
571public:
Chris Lattner67db8832010-12-13 00:23:57 +0000572 /// Tracked Records
Chris Lattner9c6b60e2010-12-15 04:48:22 +0000573 RecordKeeper &Records;
Chris Lattner67db8832010-12-13 00:23:57 +0000574
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000575 /// The tablegen AsmParser record.
576 Record *AsmParser;
577
Chris Lattner02bcbc92010-11-01 01:37:30 +0000578 /// Target - The target information.
579 CodeGenTarget &Target;
580
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000581 /// The classes which are needed for matching.
582 std::vector<ClassInfo*> Classes;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000583
Chris Lattner22bc5c42010-11-01 05:06:45 +0000584 /// The information on the matchables to match.
585 std::vector<MatchableInfo*> Matchables;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000586
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000587 /// Info for custom matching operands by user defined methods.
588 std::vector<OperandMatchEntry> OperandMatchInfo;
589
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000590 /// Map of Register records to their class information.
591 std::map<Record*, ClassInfo*> RegisterClasses;
592
Daniel Dunbar54074b52010-07-19 05:44:09 +0000593 /// Map of Predicate records to their subtarget information.
594 std::map<Record*, SubtargetFeatureInfo*> SubtargetFeatures;
Bob Wilson828295b2011-01-26 21:26:19 +0000595
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000596private:
597 /// Map of token to class information which has already been constructed.
598 std::map<std::string, ClassInfo*> TokenClasses;
599
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000600 /// Map of RegisterClass records to their class information.
601 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000602
Daniel Dunbar338825c2009-08-10 18:41:10 +0000603 /// Map of AsmOperandClass records to their class information.
604 std::map<Record*, ClassInfo*> AsmOperandClasses;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000605
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000606private:
607 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000608 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000609
610 /// getOperandClass - Lookup or create the class for the given operand.
Bob Wilsona49c7df2011-01-26 19:44:55 +0000611 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
Jim Grosbach48c1f842011-10-28 22:32:53 +0000612 int SubOpIdx);
613 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000614
Jim Grosbach8caecde2012-04-19 17:52:32 +0000615 /// buildRegisterClasses - Build the ClassInfo* instances for register
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000616 /// classes.
Jim Grosbach8caecde2012-04-19 17:52:32 +0000617 void buildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters);
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000618
Jim Grosbach8caecde2012-04-19 17:52:32 +0000619 /// buildOperandClasses - Build the ClassInfo* instances for user defined
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000620 /// operand classes.
Jim Grosbach8caecde2012-04-19 17:52:32 +0000621 void buildOperandClasses();
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000622
Jim Grosbach8caecde2012-04-19 17:52:32 +0000623 void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
Bob Wilsona49c7df2011-01-26 19:44:55 +0000624 unsigned AsmOpIdx);
Jim Grosbach8caecde2012-04-19 17:52:32 +0000625 void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
Chris Lattnerc07bd402010-11-04 02:11:18 +0000626 MatchableInfo::AsmOperand &Op);
Bob Wilson828295b2011-01-26 21:26:19 +0000627
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000628public:
Bob Wilson828295b2011-01-26 21:26:19 +0000629 AsmMatcherInfo(Record *AsmParser,
630 CodeGenTarget &Target,
Chris Lattner9c6b60e2010-12-15 04:48:22 +0000631 RecordKeeper &Records);
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000632
Jim Grosbach8caecde2012-04-19 17:52:32 +0000633 /// buildInfo - Construct the various tables used during matching.
634 void buildInfo();
Bob Wilson828295b2011-01-26 21:26:19 +0000635
Jim Grosbach8caecde2012-04-19 17:52:32 +0000636 /// buildOperandMatchInfo - Build the necessary information to handle user
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000637 /// defined operand parsing methods.
Jim Grosbach8caecde2012-04-19 17:52:32 +0000638 void buildOperandMatchInfo();
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000639
Chris Lattner6fa152c2010-10-30 20:15:02 +0000640 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
641 /// given operand.
642 SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
643 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
644 std::map<Record*, SubtargetFeatureInfo*>::const_iterator I =
645 SubtargetFeatures.find(Def);
646 return I == SubtargetFeatures.end() ? 0 : I->second;
647 }
Chris Lattner67db8832010-12-13 00:23:57 +0000648
Chris Lattner9c6b60e2010-12-15 04:48:22 +0000649 RecordKeeper &getRecords() const {
650 return Records;
Chris Lattner67db8832010-12-13 00:23:57 +0000651 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000652};
653
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000654} // End anonymous namespace
Daniel Dunbar20927f22009-08-07 08:26:05 +0000655
Chris Lattner22bc5c42010-11-01 05:06:45 +0000656void MatchableInfo::dump() {
Chris Lattner5abd1eb2010-11-06 06:43:11 +0000657 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +0000658
Chris Lattner3116fef2010-11-02 01:03:43 +0000659 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000660 AsmOperand &Op = AsmOperands[i];
Daniel Dunbar6745d422009-08-09 05:18:30 +0000661 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Chris Lattner0bb780c2010-11-04 00:57:06 +0000662 errs() << '\"' << Op.Token << "\"\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +0000663 }
664}
665
Jim Grosbachc1922c72012-04-19 23:59:23 +0000666static std::pair<StringRef, StringRef>
667parseTwoOperandConstraint(StringRef S, SMLoc Loc) {
668 // Split via the '='.
669 std::pair<StringRef, StringRef> Ops = S.split('=');
670 if (Ops.second == "")
671 throw TGError(Loc, "missing '=' in two-operand alias constraint");
672 // Trim whitespace and the leading '$' on the operand names.
673 size_t start = Ops.first.find_first_of('$');
674 if (start == std::string::npos)
675 throw TGError(Loc, "expected '$' prefix on asm operand name");
676 Ops.first = Ops.first.slice(start + 1, std::string::npos);
677 size_t end = Ops.first.find_last_of(" \t");
678 Ops.first = Ops.first.slice(0, end);
679 // Now the second operand.
680 start = Ops.second.find_first_of('$');
681 if (start == std::string::npos)
682 throw TGError(Loc, "expected '$' prefix on asm operand name");
683 Ops.second = Ops.second.slice(start + 1, std::string::npos);
684 end = Ops.second.find_last_of(" \t");
685 Ops.first = Ops.first.slice(0, end);
686 return Ops;
687}
688
689void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
690 // Figure out which operands are aliased and mark them as tied.
691 std::pair<StringRef, StringRef> Ops =
692 parseTwoOperandConstraint(Constraint, TheDef->getLoc());
693
694 // Find the AsmOperands that refer to the operands we're aliasing.
695 int SrcAsmOperand = findAsmOperandNamed(Ops.first);
696 int DstAsmOperand = findAsmOperandNamed(Ops.second);
697 if (SrcAsmOperand == -1)
698 throw TGError(TheDef->getLoc(),
699 "unknown source two-operand alias operand '" +
700 Ops.first.str() + "'.");
701 if (DstAsmOperand == -1)
702 throw TGError(TheDef->getLoc(),
703 "unknown destination two-operand alias operand '" +
704 Ops.second.str() + "'.");
705
706 // Find the ResOperand that refers to the operand we're aliasing away
707 // and update it to refer to the combined operand instead.
708 for (unsigned i = 0, e = ResOperands.size(); i != e; ++i) {
709 ResOperand &Op = ResOperands[i];
710 if (Op.Kind == ResOperand::RenderAsmOperand &&
711 Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
712 Op.AsmOperandNum = DstAsmOperand;
713 break;
714 }
715 }
716 // Remove the AsmOperand for the alias operand.
717 AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
718 // Adjust the ResOperand references to any AsmOperands that followed
719 // the one we just deleted.
720 for (unsigned i = 0, e = ResOperands.size(); i != e; ++i) {
721 ResOperand &Op = ResOperands[i];
722 switch(Op.Kind) {
723 default:
724 // Nothing to do for operands that don't reference AsmOperands.
725 break;
726 case ResOperand::RenderAsmOperand:
727 if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
728 --Op.AsmOperandNum;
729 break;
730 case ResOperand::TiedOperand:
731 if (Op.TiedOperandNum > (unsigned)SrcAsmOperand)
732 --Op.TiedOperandNum;
733 break;
734 }
735 }
736}
737
Jim Grosbach8caecde2012-04-19 17:52:32 +0000738void MatchableInfo::initialize(const AsmMatcherInfo &Info,
Devang Patel63faf822012-01-07 01:33:34 +0000739 SmallPtrSet<Record*, 16> &SingletonRegisters,
740 int AsmVariantNo, std::string &RegisterPrefix) {
Devang Patel56315d32012-01-10 17:50:43 +0000741 AsmVariantID = AsmVariantNo;
Jim Grosbachf35307c2012-01-24 21:06:59 +0000742 AsmString =
Devang Patel63faf822012-01-07 01:33:34 +0000743 CodeGenInstruction::FlattenAsmStringVariants(AsmString, AsmVariantNo);
Bob Wilson828295b2011-01-26 21:26:19 +0000744
Jim Grosbach8caecde2012-04-19 17:52:32 +0000745 tokenizeAsmString(Info);
Bob Wilson828295b2011-01-26 21:26:19 +0000746
Chris Lattnerc2d67bb2010-11-01 04:53:48 +0000747 // Compute the require features.
748 std::vector<Record*> Predicates =TheDef->getValueAsListOfDefs("Predicates");
749 for (unsigned i = 0, e = Predicates.size(); i != e; ++i)
750 if (SubtargetFeatureInfo *Feature =
751 Info.getSubtargetFeature(Predicates[i]))
752 RequiredFeatures.push_back(Feature);
Bob Wilson828295b2011-01-26 21:26:19 +0000753
Chris Lattnerc2d67bb2010-11-01 04:53:48 +0000754 // Collect singleton registers, if used.
Chris Lattnerd19ec052010-11-02 17:30:52 +0000755 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
Devang Patel63faf822012-01-07 01:33:34 +0000756 extractSingletonRegisterForAsmOperand(i, Info, RegisterPrefix);
757 if (Record *Reg = AsmOperands[i].SingletonReg)
Chris Lattnerc2d67bb2010-11-01 04:53:48 +0000758 SingletonRegisters.insert(Reg);
759 }
760}
761
Jim Grosbach8caecde2012-04-19 17:52:32 +0000762/// tokenizeAsmString - Tokenize a simplified assembly string.
763void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info) {
Chris Lattnerd19ec052010-11-02 17:30:52 +0000764 StringRef String = AsmString;
765 unsigned Prev = 0;
766 bool InTok = true;
767 for (unsigned i = 0, e = String.size(); i != e; ++i) {
768 switch (String[i]) {
769 case '[':
770 case ']':
771 case '*':
772 case '!':
773 case ' ':
774 case '\t':
775 case ',':
776 if (InTok) {
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000777 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000778 InTok = false;
779 }
780 if (!isspace(String[i]) && String[i] != ',')
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000781 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000782 Prev = i + 1;
783 break;
784
785 case '\\':
786 if (InTok) {
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000787 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000788 InTok = false;
789 }
790 ++i;
791 assert(i != String.size() && "Invalid quoted character");
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000792 AsmOperands.push_back(AsmOperand(String.substr(i, 1)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000793 Prev = i + 1;
794 break;
795
796 case '$': {
Chris Lattnerd19ec052010-11-02 17:30:52 +0000797 if (InTok) {
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000798 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000799 InTok = false;
800 }
Bob Wilson828295b2011-01-26 21:26:19 +0000801
Chris Lattner7ad31472010-11-06 22:06:03 +0000802 // If this isn't "${", treat like a normal token.
803 if (i + 1 == String.size() || String[i + 1] != '{') {
804 Prev = i;
805 break;
806 }
Chris Lattnerd19ec052010-11-02 17:30:52 +0000807
808 StringRef::iterator End = std::find(String.begin() + i, String.end(),'}');
809 assert(End != String.end() && "Missing brace in operand reference!");
810 size_t EndPos = End - String.begin();
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000811 AsmOperands.push_back(AsmOperand(String.slice(i, EndPos+1)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000812 Prev = EndPos + 1;
813 i = EndPos;
814 break;
815 }
816
817 case '.':
818 if (InTok)
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000819 AsmOperands.push_back(AsmOperand(String.slice(Prev, i)));
Chris Lattnerd19ec052010-11-02 17:30:52 +0000820 Prev = i;
821 InTok = true;
822 break;
823
824 default:
825 InTok = true;
826 }
827 }
828 if (InTok && Prev != String.size())
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000829 AsmOperands.push_back(AsmOperand(String.substr(Prev)));
Bob Wilson828295b2011-01-26 21:26:19 +0000830
Chris Lattnerd19ec052010-11-02 17:30:52 +0000831 // The first token of the instruction is the mnemonic, which must be a
832 // simple string, not a $foo variable or a singleton register.
Jim Grosbach4a2242c2011-11-30 23:16:25 +0000833 if (AsmOperands.empty())
834 throw TGError(TheDef->getLoc(),
835 "Instruction '" + TheDef->getName() + "' has no tokens");
Chris Lattnerd19ec052010-11-02 17:30:52 +0000836 Mnemonic = AsmOperands[0].Token;
Jim Grosbach8e27c962012-05-06 17:33:14 +0000837 if (Mnemonic.empty())
838 throw TGError(TheDef->getLoc(),
839 "Missing instruction mnemonic");
Devang Patel63faf822012-01-07 01:33:34 +0000840 // FIXME : Check and raise an error if it is a register.
Devang Patelb78307f2012-01-07 01:22:23 +0000841 if (Mnemonic[0] == '$')
Chris Lattnerd19ec052010-11-02 17:30:52 +0000842 throw TGError(TheDef->getLoc(),
843 "Invalid instruction mnemonic '" + Mnemonic.str() + "'!");
Bob Wilson828295b2011-01-26 21:26:19 +0000844
Chris Lattnerd19ec052010-11-02 17:30:52 +0000845 // Remove the first operand, it is tracked in the mnemonic field.
846 AsmOperands.erase(AsmOperands.begin());
847}
848
Jim Grosbach8caecde2012-04-19 17:52:32 +0000849bool MatchableInfo::validate(StringRef CommentDelimiter, bool Hack) const {
Chris Lattner22bc5c42010-11-01 05:06:45 +0000850 // Reject matchables with no .s string.
Chris Lattner5bc93872010-11-01 04:34:44 +0000851 if (AsmString.empty())
852 throw TGError(TheDef->getLoc(), "instruction with empty asm string");
Bob Wilson828295b2011-01-26 21:26:19 +0000853
Chris Lattner22bc5c42010-11-01 05:06:45 +0000854 // Reject any matchables with a newline in them, they should be marked
Chris Lattner5bc93872010-11-01 04:34:44 +0000855 // isCodeGenOnly if they are pseudo instructions.
856 if (AsmString.find('\n') != std::string::npos)
857 throw TGError(TheDef->getLoc(),
858 "multiline instruction is not valid for the asmparser, "
859 "mark it isCodeGenOnly");
Bob Wilson828295b2011-01-26 21:26:19 +0000860
Chris Lattner4164f6b2010-11-01 04:44:29 +0000861 // Remove comments from the asm string. We know that the asmstring only
862 // has one line.
863 if (!CommentDelimiter.empty() &&
864 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
865 throw TGError(TheDef->getLoc(),
866 "asmstring for instruction has comment character in it, "
867 "mark it isCodeGenOnly");
Bob Wilson828295b2011-01-26 21:26:19 +0000868
Chris Lattner22bc5c42010-11-01 05:06:45 +0000869 // Reject matchables with operand modifiers, these aren't something we can
Bob Wilson906bc362011-01-20 18:38:07 +0000870 // handle, the target should be refactored to use operands instead of
871 // modifiers.
Chris Lattner5bc93872010-11-01 04:34:44 +0000872 //
873 // Also, check for instructions which reference the operand multiple times;
874 // this implies a constraint we would not honor.
875 std::set<std::string> OperandNames;
Chris Lattnerd19ec052010-11-02 17:30:52 +0000876 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
877 StringRef Tok = AsmOperands[i].Token;
878 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
Chris Lattner5bc93872010-11-01 04:34:44 +0000879 throw TGError(TheDef->getLoc(),
Chris Lattnerd19ec052010-11-02 17:30:52 +0000880 "matchable with operand modifier '" + Tok.str() +
Chris Lattner5bc93872010-11-01 04:34:44 +0000881 "' not supported by asm matcher. Mark isCodeGenOnly!");
Bob Wilson828295b2011-01-26 21:26:19 +0000882
Chris Lattner22bc5c42010-11-01 05:06:45 +0000883 // Verify that any operand is only mentioned once.
Chris Lattnerd51257a2010-11-02 23:18:43 +0000884 // We reject aliases and ignore instructions for now.
Chris Lattnerd19ec052010-11-02 17:30:52 +0000885 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
Chris Lattner22bc5c42010-11-01 05:06:45 +0000886 if (!Hack)
887 throw TGError(TheDef->getLoc(),
Chris Lattnerd19ec052010-11-02 17:30:52 +0000888 "ERROR: matchable with tied operand '" + Tok.str() +
Chris Lattner22bc5c42010-11-01 05:06:45 +0000889 "' can never be matched!");
890 // FIXME: Should reject these. The ARM backend hits this with $lane in a
891 // bunch of instructions. It is unclear what the right answer is.
Chris Lattner5bc93872010-11-01 04:34:44 +0000892 DEBUG({
Chris Lattner5abd1eb2010-11-06 06:43:11 +0000893 errs() << "warning: '" << TheDef->getName() << "': "
Chris Lattner22bc5c42010-11-01 05:06:45 +0000894 << "ignoring instruction with tied operand '"
Chris Lattnerd19ec052010-11-02 17:30:52 +0000895 << Tok.str() << "'\n";
Chris Lattner5bc93872010-11-01 04:34:44 +0000896 });
897 return false;
898 }
899 }
Bob Wilson828295b2011-01-26 21:26:19 +0000900
Chris Lattner5bc93872010-11-01 04:34:44 +0000901 return true;
902}
903
Jim Grosbachf35307c2012-01-24 21:06:59 +0000904/// extractSingletonRegisterForAsmOperand - Extract singleton register,
Devang Pateld06b01c2012-01-09 21:30:46 +0000905/// if present, from specified token.
Devang Patel63faf822012-01-07 01:33:34 +0000906void MatchableInfo::
Jim Grosbachf35307c2012-01-24 21:06:59 +0000907extractSingletonRegisterForAsmOperand(unsigned OperandNo,
Devang Pateld06b01c2012-01-09 21:30:46 +0000908 const AsmMatcherInfo &Info,
Jim Grosbach11fc6462012-04-11 21:02:33 +0000909 std::string &RegisterPrefix) {
Devang Pateld06b01c2012-01-09 21:30:46 +0000910 StringRef Tok = AsmOperands[OperandNo].Token;
Devang Patel63faf822012-01-07 01:33:34 +0000911 if (RegisterPrefix.empty()) {
Devang Pateld06b01c2012-01-09 21:30:46 +0000912 std::string LoweredTok = Tok.lower();
913 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
914 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
Devang Patel63faf822012-01-07 01:33:34 +0000915 return;
Jim Grosbachf35307c2012-01-24 21:06:59 +0000916 }
Bob Wilson828295b2011-01-26 21:26:19 +0000917
Devang Patel63faf822012-01-07 01:33:34 +0000918 if (!Tok.startswith(RegisterPrefix))
919 return;
920
921 StringRef RegName = Tok.substr(RegisterPrefix.size());
Chris Lattnerec6f0962010-11-02 18:10:06 +0000922 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
Devang Pateld06b01c2012-01-09 21:30:46 +0000923 AsmOperands[OperandNo].SingletonReg = Reg->TheDef;
Bob Wilson828295b2011-01-26 21:26:19 +0000924
Chris Lattner1de88232010-11-01 01:47:07 +0000925 // If there is no register prefix (i.e. "%" in "%eax"), then this may
926 // be some random non-register token, just ignore it.
Devang Patel63faf822012-01-07 01:33:34 +0000927 return;
Chris Lattner02bcbc92010-11-01 01:37:30 +0000928}
929
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000930static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000931 std::string Res;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000932
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000933 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
934 switch (*it) {
935 case '*': Res += "_STAR_"; break;
936 case '%': Res += "_PCT_"; break;
937 case ':': Res += "_COLON_"; break;
Bill Wendlingbd9c77b2010-11-18 23:36:54 +0000938 case '!': Res += "_EXCLAIM_"; break;
Bill Wendling0ef755d2011-01-22 09:44:32 +0000939 case '.': Res += "_DOT_"; break;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000940 default:
Chris Lattner39ee0362010-10-31 19:10:56 +0000941 if (isalnum(*it))
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000942 Res += *it;
Chris Lattner39ee0362010-10-31 19:10:56 +0000943 else
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000944 Res += "_" + utostr((unsigned) *it) + "_";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000945 }
946 }
947
948 return Res;
949}
950
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000951ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000952 ClassInfo *&Entry = TokenClasses[Token];
Jim Grosbacha7c78222010-10-29 22:13:48 +0000953
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000954 if (!Entry) {
955 Entry = new ClassInfo();
956 Entry->Kind = ClassInfo::Token;
Daniel Dunbar6745d422009-08-09 05:18:30 +0000957 Entry->ClassName = "Token";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000958 Entry->Name = "MCK_" + getEnumNameForToken(Token);
959 Entry->ValueName = Token;
960 Entry->PredicateMethod = "<invalid>";
961 Entry->RenderMethod = "<invalid>";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000962 Entry->ParserMethod = "";
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000963 Classes.push_back(Entry);
964 }
965
966 return Entry;
967}
968
969ClassInfo *
Bob Wilsona49c7df2011-01-26 19:44:55 +0000970AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
971 int SubOpIdx) {
972 Record *Rec = OI.Rec;
973 if (SubOpIdx != -1)
David Greene05bce0b2011-07-29 22:43:06 +0000974 Rec = dynamic_cast<DefInit*>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
Jim Grosbach48c1f842011-10-28 22:32:53 +0000975 return getOperandClass(Rec, SubOpIdx);
976}
Bob Wilsona49c7df2011-01-26 19:44:55 +0000977
Jim Grosbach48c1f842011-10-28 22:32:53 +0000978ClassInfo *
979AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
Owen Andersonbea6f612011-06-27 21:06:21 +0000980 if (Rec->isSubClassOf("RegisterOperand")) {
981 // RegisterOperand may have an associated ParserMatchClass. If it does,
982 // use it, else just fall back to the underlying register class.
983 const RecordVal *R = Rec->getValue("ParserMatchClass");
984 if (R == 0 || R->getValue() == 0)
985 throw "Record `" + Rec->getName() +
986 "' does not have a ParserMatchClass!\n";
987
David Greene05bce0b2011-07-29 22:43:06 +0000988 if (DefInit *DI= dynamic_cast<DefInit*>(R->getValue())) {
Owen Andersonbea6f612011-06-27 21:06:21 +0000989 Record *MatchClass = DI->getDef();
990 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
991 return CI;
992 }
993
994 // No custom match class. Just use the register class.
995 Record *ClassRec = Rec->getValueAsDef("RegClass");
996 if (!ClassRec)
997 throw TGError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
998 "' has no associated register class!\n");
999 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
1000 return CI;
1001 throw TGError(Rec->getLoc(), "register class has no class info!");
1002 }
1003
1004
Bob Wilsona49c7df2011-01-26 19:44:55 +00001005 if (Rec->isSubClassOf("RegisterClass")) {
1006 if (ClassInfo *CI = RegisterClassClasses[Rec])
Chris Lattnerec6f0962010-11-02 18:10:06 +00001007 return CI;
Bob Wilsona49c7df2011-01-26 19:44:55 +00001008 throw TGError(Rec->getLoc(), "register class has no class info!");
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001009 }
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001010
Bob Wilsona49c7df2011-01-26 19:44:55 +00001011 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1012 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
Chris Lattnerec6f0962010-11-02 18:10:06 +00001013 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1014 return CI;
Daniel Dunbar338825c2009-08-10 18:41:10 +00001015
Bob Wilsona49c7df2011-01-26 19:44:55 +00001016 throw TGError(Rec->getLoc(), "operand has no match class!");
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001017}
1018
Chris Lattner1de88232010-11-01 01:47:07 +00001019void AsmMatcherInfo::
Jim Grosbach8caecde2012-04-19 17:52:32 +00001020buildRegisterClasses(SmallPtrSet<Record*, 16> &SingletonRegisters) {
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +00001021 const std::vector<CodeGenRegister*> &Registers =
1022 Target.getRegBank().getRegisters();
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001023 ArrayRef<CodeGenRegisterClass*> RegClassList =
1024 Target.getRegBank().getRegClasses();
Daniel Dunbar338825c2009-08-10 18:41:10 +00001025
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001026 // The register sets used for matching.
1027 std::set< std::set<Record*> > RegisterSets;
1028
Jim Grosbacha7c78222010-10-29 22:13:48 +00001029 // Gather the defined sets.
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001030 for (ArrayRef<CodeGenRegisterClass*>::const_iterator it =
Chris Lattnerec6f0962010-11-02 18:10:06 +00001031 RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it)
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001032 RegisterSets.insert(std::set<Record*>(
1033 (*it)->getOrder().begin(), (*it)->getOrder().end()));
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001034
1035 // Add any required singleton sets.
Chris Lattner1de88232010-11-01 01:47:07 +00001036 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1037 ie = SingletonRegisters.end(); it != ie; ++it) {
1038 Record *Rec = *it;
1039 RegisterSets.insert(std::set<Record*>(&Rec, &Rec + 1));
1040 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001041
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001042 // Introduce derived sets where necessary (when a register does not determine
1043 // a unique register set class), and build the mapping of registers to the set
1044 // they should classify to.
1045 std::map<Record*, std::set<Record*> > RegisterMap;
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +00001046 for (std::vector<CodeGenRegister*>::const_iterator it = Registers.begin(),
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001047 ie = Registers.end(); it != ie; ++it) {
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +00001048 const CodeGenRegister &CGR = **it;
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001049 // Compute the intersection of all sets containing this register.
1050 std::set<Record*> ContainingSet;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001051
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001052 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
1053 ie = RegisterSets.end(); it != ie; ++it) {
1054 if (!it->count(CGR.TheDef))
1055 continue;
1056
1057 if (ContainingSet.empty()) {
1058 ContainingSet = *it;
Chris Lattnerec6f0962010-11-02 18:10:06 +00001059 continue;
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001060 }
Bob Wilson828295b2011-01-26 21:26:19 +00001061
Chris Lattnerec6f0962010-11-02 18:10:06 +00001062 std::set<Record*> Tmp;
1063 std::swap(Tmp, ContainingSet);
1064 std::insert_iterator< std::set<Record*> > II(ContainingSet,
1065 ContainingSet.begin());
1066 std::set_intersection(Tmp.begin(), Tmp.end(), it->begin(), it->end(), II);
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001067 }
1068
1069 if (!ContainingSet.empty()) {
1070 RegisterSets.insert(ContainingSet);
1071 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
1072 }
1073 }
1074
1075 // Construct the register classes.
1076 std::map<std::set<Record*>, ClassInfo*> RegisterSetClasses;
1077 unsigned Index = 0;
1078 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
1079 ie = RegisterSets.end(); it != ie; ++it, ++Index) {
1080 ClassInfo *CI = new ClassInfo();
1081 CI->Kind = ClassInfo::RegisterClass0 + Index;
1082 CI->ClassName = "Reg" + utostr(Index);
1083 CI->Name = "MCK_Reg" + utostr(Index);
1084 CI->ValueName = "";
1085 CI->PredicateMethod = ""; // unused
1086 CI->RenderMethod = "addRegOperands";
Daniel Dunbar8409bfb2009-08-11 20:10:07 +00001087 CI->Registers = *it;
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001088 Classes.push_back(CI);
1089 RegisterSetClasses.insert(std::make_pair(*it, CI));
1090 }
1091
1092 // Find the superclasses; we could compute only the subgroup lattice edges,
1093 // but there isn't really a point.
1094 for (std::set< std::set<Record*> >::iterator it = RegisterSets.begin(),
1095 ie = RegisterSets.end(); it != ie; ++it) {
1096 ClassInfo *CI = RegisterSetClasses[*it];
1097 for (std::set< std::set<Record*> >::iterator it2 = RegisterSets.begin(),
1098 ie2 = RegisterSets.end(); it2 != ie2; ++it2)
Jim Grosbacha7c78222010-10-29 22:13:48 +00001099 if (*it != *it2 &&
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001100 std::includes(it2->begin(), it2->end(), it->begin(), it->end()))
1101 CI->SuperClasses.push_back(RegisterSetClasses[*it2]);
1102 }
1103
1104 // Name the register classes which correspond to a user defined RegisterClass.
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001105 for (ArrayRef<CodeGenRegisterClass*>::const_iterator
Chris Lattnerec6f0962010-11-02 18:10:06 +00001106 it = RegClassList.begin(), ie = RegClassList.end(); it != ie; ++it) {
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001107 const CodeGenRegisterClass &RC = **it;
Jakob Stoklund Olesen6fea31e2011-10-04 15:28:08 +00001108 // Def will be NULL for non-user defined register classes.
1109 Record *Def = RC.getDef();
1110 if (!Def)
1111 continue;
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001112 ClassInfo *CI = RegisterSetClasses[std::set<Record*>(RC.getOrder().begin(),
1113 RC.getOrder().end())];
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001114 if (CI->ValueName.empty()) {
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001115 CI->ClassName = RC.getName();
1116 CI->Name = "MCK_" + RC.getName();
1117 CI->ValueName = RC.getName();
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001118 } else
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +00001119 CI->ValueName = CI->ValueName + "," + RC.getName();
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001120
Jakob Stoklund Olesen6fea31e2011-10-04 15:28:08 +00001121 RegisterClassClasses.insert(std::make_pair(Def, CI));
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001122 }
1123
1124 // Populate the map for individual registers.
1125 for (std::map<Record*, std::set<Record*> >::iterator it = RegisterMap.begin(),
1126 ie = RegisterMap.end(); it != ie; ++it)
Chris Lattnerec6f0962010-11-02 18:10:06 +00001127 RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001128
1129 // Name the register classes which correspond to singleton registers.
Chris Lattner1de88232010-11-01 01:47:07 +00001130 for (SmallPtrSet<Record*, 16>::iterator it = SingletonRegisters.begin(),
1131 ie = SingletonRegisters.end(); it != ie; ++it) {
1132 Record *Rec = *it;
Chris Lattnerec6f0962010-11-02 18:10:06 +00001133 ClassInfo *CI = RegisterClasses[Rec];
Chris Lattner1de88232010-11-01 01:47:07 +00001134 assert(CI && "Missing singleton register class info!");
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001135
Chris Lattner1de88232010-11-01 01:47:07 +00001136 if (CI->ValueName.empty()) {
1137 CI->ClassName = Rec->getName();
1138 CI->Name = "MCK_" + Rec->getName();
1139 CI->ValueName = Rec->getName();
1140 } else
1141 CI->ValueName = CI->ValueName + "," + Rec->getName();
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001142 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001143}
1144
Jim Grosbach8caecde2012-04-19 17:52:32 +00001145void AsmMatcherInfo::buildOperandClasses() {
Chris Lattnere66b7eb2010-11-01 23:57:23 +00001146 std::vector<Record*> AsmOperands =
1147 Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbara2f5e002010-01-30 01:02:37 +00001148
1149 // Pre-populate AsmOperandClasses map.
Jim Grosbacha7c78222010-10-29 22:13:48 +00001150 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbara2f5e002010-01-30 01:02:37 +00001151 ie = AsmOperands.end(); it != ie; ++it)
1152 AsmOperandClasses[*it] = new ClassInfo();
1153
Daniel Dunbar338825c2009-08-10 18:41:10 +00001154 unsigned Index = 0;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001155 for (std::vector<Record*>::iterator it = AsmOperands.begin(),
Daniel Dunbar338825c2009-08-10 18:41:10 +00001156 ie = AsmOperands.end(); it != ie; ++it, ++Index) {
Daniel Dunbara2f5e002010-01-30 01:02:37 +00001157 ClassInfo *CI = AsmOperandClasses[*it];
Daniel Dunbar338825c2009-08-10 18:41:10 +00001158 CI->Kind = ClassInfo::UserClass0 + Index;
1159
David Greene05bce0b2011-07-29 22:43:06 +00001160 ListInit *Supers = (*it)->getValueAsListInit("SuperClasses");
Daniel Dunbar54ddf3d2010-05-22 21:02:29 +00001161 for (unsigned i = 0, e = Supers->getSize(); i != e; ++i) {
David Greene05bce0b2011-07-29 22:43:06 +00001162 DefInit *DI = dynamic_cast<DefInit*>(Supers->getElement(i));
Daniel Dunbar54ddf3d2010-05-22 21:02:29 +00001163 if (!DI) {
1164 PrintError((*it)->getLoc(), "Invalid super class reference!");
1165 continue;
1166 }
1167
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001168 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1169 if (!SC)
Daniel Dunbar338825c2009-08-10 18:41:10 +00001170 PrintError((*it)->getLoc(), "Invalid super class reference!");
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001171 else
1172 CI->SuperClasses.push_back(SC);
Daniel Dunbar338825c2009-08-10 18:41:10 +00001173 }
1174 CI->ClassName = (*it)->getValueAsString("Name");
1175 CI->Name = "MCK_" + CI->ClassName;
1176 CI->ValueName = (*it)->getName();
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001177
1178 // Get or construct the predicate method name.
David Greene05bce0b2011-07-29 22:43:06 +00001179 Init *PMName = (*it)->getValueInit("PredicateMethod");
1180 if (StringInit *SI = dynamic_cast<StringInit*>(PMName)) {
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001181 CI->PredicateMethod = SI->getValue();
1182 } else {
David Greene05bce0b2011-07-29 22:43:06 +00001183 assert(dynamic_cast<UnsetInit*>(PMName) &&
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001184 "Unexpected PredicateMethod field!");
1185 CI->PredicateMethod = "is" + CI->ClassName;
1186 }
1187
1188 // Get or construct the render method name.
David Greene05bce0b2011-07-29 22:43:06 +00001189 Init *RMName = (*it)->getValueInit("RenderMethod");
1190 if (StringInit *SI = dynamic_cast<StringInit*>(RMName)) {
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001191 CI->RenderMethod = SI->getValue();
1192 } else {
David Greene05bce0b2011-07-29 22:43:06 +00001193 assert(dynamic_cast<UnsetInit*>(RMName) &&
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001194 "Unexpected RenderMethod field!");
1195 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1196 }
1197
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001198 // Get the parse method name or leave it as empty.
David Greene05bce0b2011-07-29 22:43:06 +00001199 Init *PRMName = (*it)->getValueInit("ParserMethod");
1200 if (StringInit *SI = dynamic_cast<StringInit*>(PRMName))
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001201 CI->ParserMethod = SI->getValue();
1202
Daniel Dunbar338825c2009-08-10 18:41:10 +00001203 AsmOperandClasses[*it] = CI;
1204 Classes.push_back(CI);
1205 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001206}
1207
Bob Wilson828295b2011-01-26 21:26:19 +00001208AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1209 CodeGenTarget &target,
Chris Lattner9c6b60e2010-12-15 04:48:22 +00001210 RecordKeeper &records)
Devang Patel63faf822012-01-07 01:33:34 +00001211 : Records(records), AsmParser(asmParser), Target(target) {
Daniel Dunbar59fc42d2009-08-11 20:59:47 +00001212}
1213
Jim Grosbach8caecde2012-04-19 17:52:32 +00001214/// buildOperandMatchInfo - Build the necessary information to handle user
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001215/// defined operand parsing methods.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001216void AsmMatcherInfo::buildOperandMatchInfo() {
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001217
Jim Grosbachd4824fc2012-04-18 23:46:25 +00001218 /// Map containing a mask with all operands indices that can be found for
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001219 /// that class inside a instruction.
1220 std::map<ClassInfo*, unsigned> OpClassMask;
1221
1222 for (std::vector<MatchableInfo*>::const_iterator it =
1223 Matchables.begin(), ie = Matchables.end();
1224 it != ie; ++it) {
1225 MatchableInfo &II = **it;
1226 OpClassMask.clear();
1227
1228 // Keep track of all operands of this instructions which belong to the
1229 // same class.
1230 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
1231 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
1232 if (Op.Class->ParserMethod.empty())
1233 continue;
1234 unsigned &OperandMask = OpClassMask[Op.Class];
1235 OperandMask |= (1 << i);
1236 }
1237
1238 // Generate operand match info for each mnemonic/operand class pair.
1239 for (std::map<ClassInfo*, unsigned>::iterator iit = OpClassMask.begin(),
1240 iie = OpClassMask.end(); iit != iie; ++iit) {
1241 unsigned OpMask = iit->second;
1242 ClassInfo *CI = iit->first;
Jim Grosbach8caecde2012-04-19 17:52:32 +00001243 OperandMatchInfo.push_back(OperandMatchEntry::create(&II, CI, OpMask));
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001244 }
1245 }
1246}
1247
Jim Grosbach8caecde2012-04-19 17:52:32 +00001248void AsmMatcherInfo::buildInfo() {
Chris Lattner0aed1e72010-10-30 20:07:57 +00001249 // Build information about all of the AssemblerPredicates.
1250 std::vector<Record*> AllPredicates =
1251 Records.getAllDerivedDefinitions("Predicate");
1252 for (unsigned i = 0, e = AllPredicates.size(); i != e; ++i) {
1253 Record *Pred = AllPredicates[i];
1254 // Ignore predicates that are not intended for the assembler.
1255 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
1256 continue;
Bob Wilson828295b2011-01-26 21:26:19 +00001257
Chris Lattner4164f6b2010-11-01 04:44:29 +00001258 if (Pred->getName().empty())
1259 throw TGError(Pred->getLoc(), "Predicate has no name!");
Bob Wilson828295b2011-01-26 21:26:19 +00001260
Chris Lattner0aed1e72010-10-30 20:07:57 +00001261 unsigned FeatureNo = SubtargetFeatures.size();
1262 SubtargetFeatures[Pred] = new SubtargetFeatureInfo(Pred, FeatureNo);
1263 assert(FeatureNo < 32 && "Too many subtarget features!");
1264 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001265
Chris Lattner39ee0362010-10-31 19:10:56 +00001266 // Parse the instructions; we need to do this first so that we can gather the
1267 // singleton register classes.
Chris Lattner1de88232010-11-01 01:47:07 +00001268 SmallPtrSet<Record*, 16> SingletonRegisters;
Devang Patel0dbcada2012-01-09 19:13:28 +00001269 unsigned VariantCount = Target.getAsmParserVariantCount();
1270 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1271 Record *AsmVariant = Target.getAsmParserVariant(VC);
Jim Grosbach65da6fc2012-04-17 00:01:04 +00001272 std::string CommentDelimiter =
1273 AsmVariant->getValueAsString("CommentDelimiter");
Devang Patel0dbcada2012-01-09 19:13:28 +00001274 std::string RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
1275 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Jim Grosbachf35307c2012-01-24 21:06:59 +00001276
Devang Patel0dbcada2012-01-09 19:13:28 +00001277 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
Jim Grosbach11fc6462012-04-11 21:02:33 +00001278 E = Target.inst_end(); I != E; ++I) {
Devang Patel0dbcada2012-01-09 19:13:28 +00001279 const CodeGenInstruction &CGI = **I;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001280
Devang Patel0dbcada2012-01-09 19:13:28 +00001281 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1282 // filter the set of instructions we consider.
1283 if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
Jim Grosbach11fc6462012-04-11 21:02:33 +00001284 continue;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001285
Devang Patel0dbcada2012-01-09 19:13:28 +00001286 // Ignore "codegen only" instructions.
1287 if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
Jim Grosbach11fc6462012-04-11 21:02:33 +00001288 continue;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001289
Devang Patel0dbcada2012-01-09 19:13:28 +00001290 // Validate the operand list to ensure we can handle this instruction.
1291 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
Jim Grosbach11fc6462012-04-11 21:02:33 +00001292 const CGIOperandList::OperandInfo &OI = CGI.Operands[i];
1293
1294 // Validate tied operands.
1295 if (OI.getTiedRegister() != -1) {
1296 // If we have a tied operand that consists of multiple MCOperands,
1297 // reject it. We reject aliases and ignore instructions for now.
1298 if (OI.MINumOperands != 1) {
1299 // FIXME: Should reject these. The ARM backend hits this with $lane
Jim Grosbach65da6fc2012-04-17 00:01:04 +00001300 // in a bunch of instructions. The right answer is unclear.
Jim Grosbach11fc6462012-04-11 21:02:33 +00001301 DEBUG({
1302 errs() << "warning: '" << CGI.TheDef->getName() << "': "
Jim Grosbach65da6fc2012-04-17 00:01:04 +00001303 << "ignoring instruction with multi-operand tied operand '"
1304 << OI.Name << "'\n";
Jim Grosbach11fc6462012-04-11 21:02:33 +00001305 });
1306 continue;
1307 }
1308 }
Chris Lattner1d13bda2010-11-04 00:43:46 +00001309 }
Jim Grosbachf35307c2012-01-24 21:06:59 +00001310
Devang Patel0dbcada2012-01-09 19:13:28 +00001311 OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
Jim Grosbachf35307c2012-01-24 21:06:59 +00001312
Jim Grosbach8caecde2012-04-19 17:52:32 +00001313 II->initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
Jim Grosbachf35307c2012-01-24 21:06:59 +00001314
Devang Patel0dbcada2012-01-09 19:13:28 +00001315 // Ignore instructions which shouldn't be matched and diagnose invalid
1316 // instruction definitions with an error.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001317 if (!II->validate(CommentDelimiter, true))
Jim Grosbach11fc6462012-04-11 21:02:33 +00001318 continue;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001319
Devang Patel0dbcada2012-01-09 19:13:28 +00001320 // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
1321 //
1322 // FIXME: This is a total hack.
1323 if (StringRef(II->TheDef->getName()).startswith("Int_") ||
Jim Grosbach11fc6462012-04-11 21:02:33 +00001324 StringRef(II->TheDef->getName()).endswith("_Int"))
1325 continue;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001326
Devang Patel0dbcada2012-01-09 19:13:28 +00001327 Matchables.push_back(II.take());
Chris Lattner1d13bda2010-11-04 00:43:46 +00001328 }
Jim Grosbachf35307c2012-01-24 21:06:59 +00001329
Devang Patel0dbcada2012-01-09 19:13:28 +00001330 // Parse all of the InstAlias definitions and stick them in the list of
1331 // matchables.
1332 std::vector<Record*> AllInstAliases =
1333 Records.getAllDerivedDefinitions("InstAlias");
1334 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
1335 CodeGenInstAlias *Alias = new CodeGenInstAlias(AllInstAliases[i], Target);
Jim Grosbachf35307c2012-01-24 21:06:59 +00001336
Devang Patel0dbcada2012-01-09 19:13:28 +00001337 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1338 // filter the set of instruction aliases we consider, based on the target
1339 // instruction.
Jim Grosbach65da6fc2012-04-17 00:01:04 +00001340 if (!StringRef(Alias->ResultInst->TheDef->getName())
1341 .startswith( MatchPrefix))
Jim Grosbach11fc6462012-04-11 21:02:33 +00001342 continue;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001343
Devang Patel0dbcada2012-01-09 19:13:28 +00001344 OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
Jim Grosbachf35307c2012-01-24 21:06:59 +00001345
Jim Grosbach8caecde2012-04-19 17:52:32 +00001346 II->initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPrefix);
Jim Grosbachf35307c2012-01-24 21:06:59 +00001347
Devang Patel0dbcada2012-01-09 19:13:28 +00001348 // Validate the alias definitions.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001349 II->validate(CommentDelimiter, false);
Jim Grosbachf35307c2012-01-24 21:06:59 +00001350
Devang Patel0dbcada2012-01-09 19:13:28 +00001351 Matchables.push_back(II.take());
1352 }
Chris Lattnerc76e80d2010-11-01 04:05:41 +00001353 }
Chris Lattnerc240bb02010-11-01 04:03:32 +00001354
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001355 // Build info for the register classes.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001356 buildRegisterClasses(SingletonRegisters);
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001357
1358 // Build info for the user defined assembly operand classes.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001359 buildOperandClasses();
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001360
Chris Lattner0bb780c2010-11-04 00:57:06 +00001361 // Build the information about matchables, now that we have fully formed
1362 // classes.
Jim Grosbachc1922c72012-04-19 23:59:23 +00001363 std::vector<MatchableInfo*> NewMatchables;
Chris Lattner22bc5c42010-11-01 05:06:45 +00001364 for (std::vector<MatchableInfo*>::iterator it = Matchables.begin(),
1365 ie = Matchables.end(); it != ie; ++it) {
1366 MatchableInfo *II = *it;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001367
Chris Lattnere206fcf2010-09-06 21:01:37 +00001368 // Parse the tokens after the mnemonic.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001369 // Note: buildInstructionOperandReference may insert new AsmOperands, so
Bob Wilsona49c7df2011-01-26 19:44:55 +00001370 // don't precompute the loop bound.
1371 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
Chris Lattnerc0b14a22010-11-03 19:47:34 +00001372 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
Chris Lattnerd19ec052010-11-02 17:30:52 +00001373 StringRef Token = Op.Token;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001374
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001375 // Check for singleton registers.
Devang Patel63faf822012-01-07 01:33:34 +00001376 if (Record *RegRecord = II->AsmOperands[i].SingletonReg) {
Chris Lattnerd19ec052010-11-02 17:30:52 +00001377 Op.Class = RegisterClasses[RegRecord];
Chris Lattner02bcbc92010-11-01 01:37:30 +00001378 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1379 "Unexpected class for singleton register");
Chris Lattner02bcbc92010-11-01 01:37:30 +00001380 continue;
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001381 }
1382
Daniel Dunbar20927f22009-08-07 08:26:05 +00001383 // Check for simple tokens.
1384 if (Token[0] != '$') {
Chris Lattnerd19ec052010-11-02 17:30:52 +00001385 Op.Class = getTokenClass(Token);
Daniel Dunbar20927f22009-08-07 08:26:05 +00001386 continue;
1387 }
1388
Chris Lattner7ad31472010-11-06 22:06:03 +00001389 if (Token.size() > 1 && isdigit(Token[1])) {
1390 Op.Class = getTokenClass(Token);
1391 continue;
1392 }
Bob Wilson828295b2011-01-26 21:26:19 +00001393
Chris Lattnerc07bd402010-11-04 02:11:18 +00001394 // Otherwise this is an operand reference.
Chris Lattner5f4280c2010-11-04 01:58:23 +00001395 StringRef OperandName;
1396 if (Token[1] == '{')
1397 OperandName = Token.substr(2, Token.size() - 3);
1398 else
1399 OperandName = Token.substr(1);
Bob Wilson828295b2011-01-26 21:26:19 +00001400
Chris Lattnerc07bd402010-11-04 02:11:18 +00001401 if (II->DefRec.is<const CodeGenInstruction*>())
Jim Grosbach8caecde2012-04-19 17:52:32 +00001402 buildInstructionOperandReference(II, OperandName, i);
Chris Lattnerc07bd402010-11-04 02:11:18 +00001403 else
Jim Grosbach8caecde2012-04-19 17:52:32 +00001404 buildAliasOperandReference(II, OperandName, Op);
Daniel Dunbar20927f22009-08-07 08:26:05 +00001405 }
Bob Wilson828295b2011-01-26 21:26:19 +00001406
Jim Grosbachc1922c72012-04-19 23:59:23 +00001407 if (II->DefRec.is<const CodeGenInstruction*>()) {
Jim Grosbach8caecde2012-04-19 17:52:32 +00001408 II->buildInstructionResultOperands();
Jim Grosbachc1922c72012-04-19 23:59:23 +00001409 // If the instruction has a two-operand alias, build up the
1410 // matchable here. We'll add them in bulk at the end to avoid
1411 // confusing this loop.
1412 std::string Constraint =
1413 II->TheDef->getValueAsString("TwoOperandAliasConstraint");
1414 if (Constraint != "") {
1415 // Start by making a copy of the original matchable.
1416 OwningPtr<MatchableInfo> AliasII(new MatchableInfo(*II));
1417
1418 // Adjust it to be a two-operand alias.
1419 AliasII->formTwoOperandAlias(Constraint);
1420
1421 // Add the alias to the matchables list.
1422 NewMatchables.push_back(AliasII.take());
1423 }
1424 } else
Jim Grosbach8caecde2012-04-19 17:52:32 +00001425 II->buildAliasResultOperands();
Daniel Dunbar20927f22009-08-07 08:26:05 +00001426 }
Jim Grosbachc1922c72012-04-19 23:59:23 +00001427 if (!NewMatchables.empty())
1428 Matchables.insert(Matchables.end(), NewMatchables.begin(),
1429 NewMatchables.end());
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001430
Jim Grosbacha66512e2011-12-06 23:43:54 +00001431 // Process token alias definitions and set up the associated superclass
1432 // information.
1433 std::vector<Record*> AllTokenAliases =
1434 Records.getAllDerivedDefinitions("TokenAlias");
1435 for (unsigned i = 0, e = AllTokenAliases.size(); i != e; ++i) {
1436 Record *Rec = AllTokenAliases[i];
1437 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1438 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
Jim Grosbach67cd20d2012-04-17 21:23:52 +00001439 if (FromClass == ToClass)
1440 throw TGError(Rec->getLoc(),
1441 "error: Destination value identical to source value.");
Jim Grosbacha66512e2011-12-06 23:43:54 +00001442 FromClass->SuperClasses.push_back(ToClass);
1443 }
1444
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001445 // Reorder classes so that classes precede super classes.
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001446 std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
Daniel Dunbar20927f22009-08-07 08:26:05 +00001447}
1448
Jim Grosbach8caecde2012-04-19 17:52:32 +00001449/// buildInstructionOperandReference - The specified operand is a reference to a
Chris Lattner0bb780c2010-11-04 00:57:06 +00001450/// named operand such as $src. Resolve the Class and OperandInfo pointers.
1451void AsmMatcherInfo::
Jim Grosbach8caecde2012-04-19 17:52:32 +00001452buildInstructionOperandReference(MatchableInfo *II,
Chris Lattner5f4280c2010-11-04 01:58:23 +00001453 StringRef OperandName,
Bob Wilsona49c7df2011-01-26 19:44:55 +00001454 unsigned AsmOpIdx) {
Chris Lattnerc07bd402010-11-04 02:11:18 +00001455 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1456 const CGIOperandList &Operands = CGI.Operands;
Bob Wilsona49c7df2011-01-26 19:44:55 +00001457 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
Bob Wilson828295b2011-01-26 21:26:19 +00001458
Chris Lattner662e5a32010-11-06 07:14:44 +00001459 // Map this token to an operand.
Chris Lattner0bb780c2010-11-04 00:57:06 +00001460 unsigned Idx;
1461 if (!Operands.hasOperandNamed(OperandName, Idx))
1462 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1463 OperandName.str() + "'");
Chris Lattnerba3b5b62010-11-04 01:55:23 +00001464
Bob Wilsona49c7df2011-01-26 19:44:55 +00001465 // If the instruction operand has multiple suboperands, but the parser
1466 // match class for the asm operand is still the default "ImmAsmOperand",
1467 // then handle each suboperand separately.
1468 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1469 Record *Rec = Operands[Idx].Rec;
1470 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1471 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1472 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1473 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1474 StringRef Token = Op->Token; // save this in case Op gets moved
1475 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
1476 MatchableInfo::AsmOperand NewAsmOp(Token);
1477 NewAsmOp.SubOpIdx = SI;
1478 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1479 }
1480 // Replace Op with first suboperand.
1481 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1482 Op->SubOpIdx = 0;
1483 }
1484 }
1485
Chris Lattnerba3b5b62010-11-04 01:55:23 +00001486 // Set up the operand class.
Bob Wilsona49c7df2011-01-26 19:44:55 +00001487 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
Chris Lattnerba3b5b62010-11-04 01:55:23 +00001488
1489 // If the named operand is tied, canonicalize it to the untied operand.
1490 // For example, something like:
1491 // (outs GPR:$dst), (ins GPR:$src)
1492 // with an asmstring of
1493 // "inc $src"
1494 // we want to canonicalize to:
1495 // "inc $dst"
1496 // so that we know how to provide the $dst operand when filling in the result.
1497 int OITied = Operands[Idx].getTiedRegister();
Chris Lattner0bb780c2010-11-04 00:57:06 +00001498 if (OITied != -1) {
1499 // The tied operand index is an MIOperand index, find the operand that
1500 // contains it.
Bob Wilsona49c7df2011-01-26 19:44:55 +00001501 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1502 OperandName = Operands[Idx.first].Name;
1503 Op->SubOpIdx = Idx.second;
Chris Lattner0bb780c2010-11-04 00:57:06 +00001504 }
Bob Wilson828295b2011-01-26 21:26:19 +00001505
Bob Wilsona49c7df2011-01-26 19:44:55 +00001506 Op->SrcOpName = OperandName;
Chris Lattner0bb780c2010-11-04 00:57:06 +00001507}
1508
Jim Grosbach8caecde2012-04-19 17:52:32 +00001509/// buildAliasOperandReference - When parsing an operand reference out of the
Chris Lattner3f2c8e42010-11-06 07:06:09 +00001510/// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1511/// operand reference is by looking it up in the result pattern definition.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001512void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
Chris Lattnerc07bd402010-11-04 02:11:18 +00001513 StringRef OperandName,
1514 MatchableInfo::AsmOperand &Op) {
1515 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
Bob Wilson828295b2011-01-26 21:26:19 +00001516
Chris Lattnerc07bd402010-11-04 02:11:18 +00001517 // Set up the operand class.
Chris Lattner3f2c8e42010-11-06 07:06:09 +00001518 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
Chris Lattner98c870f2010-11-06 19:25:43 +00001519 if (CGA.ResultOperands[i].isRecord() &&
1520 CGA.ResultOperands[i].getName() == OperandName) {
Chris Lattner662e5a32010-11-06 07:14:44 +00001521 // It's safe to go with the first one we find, because CodeGenInstAlias
1522 // validates that all operands with the same name have the same record.
Bob Wilsona49c7df2011-01-26 19:44:55 +00001523 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
Jim Grosbach48c1f842011-10-28 22:32:53 +00001524 // Use the match class from the Alias definition, not the
1525 // destination instruction, as we may have an immediate that's
1526 // being munged by the match class.
1527 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
Bob Wilsona49c7df2011-01-26 19:44:55 +00001528 Op.SubOpIdx);
Chris Lattner3f2c8e42010-11-06 07:06:09 +00001529 Op.SrcOpName = OperandName;
1530 return;
Chris Lattnerc07bd402010-11-04 02:11:18 +00001531 }
Chris Lattner3f2c8e42010-11-06 07:06:09 +00001532
1533 throw TGError(II->TheDef->getLoc(), "error: unable to find operand: '" +
1534 OperandName.str() + "'");
Chris Lattnerc07bd402010-11-04 02:11:18 +00001535}
1536
Jim Grosbach8caecde2012-04-19 17:52:32 +00001537void MatchableInfo::buildInstructionResultOperands() {
Chris Lattner662e5a32010-11-06 07:14:44 +00001538 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilson828295b2011-01-26 21:26:19 +00001539
Chris Lattner662e5a32010-11-06 07:14:44 +00001540 // Loop over all operands of the result instruction, determining how to
1541 // populate them.
1542 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1543 const CGIOperandList::OperandInfo &OpInfo = ResultInst->Operands[i];
Chris Lattner567820c2010-11-04 01:42:59 +00001544
1545 // If this is a tied operand, just copy from the previously handled operand.
1546 int TiedOp = OpInfo.getTiedRegister();
1547 if (TiedOp != -1) {
Bob Wilsona49c7df2011-01-26 19:44:55 +00001548 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
Chris Lattner567820c2010-11-04 01:42:59 +00001549 continue;
1550 }
Bob Wilson828295b2011-01-26 21:26:19 +00001551
Bob Wilsona49c7df2011-01-26 19:44:55 +00001552 // Find out what operand from the asmparser this MCInst operand comes from.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001553 int SrcOperand = findAsmOperandNamed(OpInfo.Name);
Bob Wilsona49c7df2011-01-26 19:44:55 +00001554 if (OpInfo.Name.empty() || SrcOperand == -1)
1555 throw TGError(TheDef->getLoc(), "Instruction '" +
1556 TheDef->getName() + "' has operand '" + OpInfo.Name +
1557 "' that doesn't appear in asm string!");
Chris Lattner567820c2010-11-04 01:42:59 +00001558
Bob Wilsona49c7df2011-01-26 19:44:55 +00001559 // Check if the one AsmOperand populates the entire operand.
1560 unsigned NumOperands = OpInfo.MINumOperands;
1561 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1562 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
Chris Lattner1d13bda2010-11-04 00:43:46 +00001563 continue;
1564 }
Bob Wilsona49c7df2011-01-26 19:44:55 +00001565
1566 // Add a separate ResOperand for each suboperand.
1567 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1568 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1569 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1570 "unexpected AsmOperands for suboperands");
1571 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1572 }
Chris Lattner1d13bda2010-11-04 00:43:46 +00001573 }
1574}
1575
Jim Grosbach8caecde2012-04-19 17:52:32 +00001576void MatchableInfo::buildAliasResultOperands() {
Chris Lattner41409852010-11-06 07:31:43 +00001577 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1578 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilson828295b2011-01-26 21:26:19 +00001579
Chris Lattner41409852010-11-06 07:31:43 +00001580 // Loop over all operands of the result instruction, determining how to
1581 // populate them.
1582 unsigned AliasOpNo = 0;
Bob Wilsona49c7df2011-01-26 19:44:55 +00001583 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
Chris Lattner41409852010-11-06 07:31:43 +00001584 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
Bob Wilsona49c7df2011-01-26 19:44:55 +00001585 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
Bob Wilson828295b2011-01-26 21:26:19 +00001586
Chris Lattner41409852010-11-06 07:31:43 +00001587 // If this is a tied operand, just copy from the previously handled operand.
Bob Wilsona49c7df2011-01-26 19:44:55 +00001588 int TiedOp = OpInfo->getTiedRegister();
Chris Lattner41409852010-11-06 07:31:43 +00001589 if (TiedOp != -1) {
Bob Wilsona49c7df2011-01-26 19:44:55 +00001590 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
Chris Lattner90fd7972010-11-06 19:57:21 +00001591 continue;
1592 }
1593
Bob Wilsona49c7df2011-01-26 19:44:55 +00001594 // Handle all the suboperands for this operand.
1595 const std::string &OpName = OpInfo->Name;
1596 for ( ; AliasOpNo < LastOpNo &&
1597 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1598 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1599
1600 // Find out what operand from the asmparser that this MCInst operand
1601 // comes from.
1602 switch (CGA.ResultOperands[AliasOpNo].Kind) {
Bob Wilsona49c7df2011-01-26 19:44:55 +00001603 case CodeGenInstAlias::ResultOperand::K_Record: {
1604 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
Jim Grosbach8caecde2012-04-19 17:52:32 +00001605 int SrcOperand = findAsmOperand(Name, SubIdx);
Bob Wilsona49c7df2011-01-26 19:44:55 +00001606 if (SrcOperand == -1)
1607 throw TGError(TheDef->getLoc(), "Instruction '" +
1608 TheDef->getName() + "' has operand '" + OpName +
1609 "' that doesn't appear in asm string!");
1610 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1611 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1612 NumOperands));
1613 break;
1614 }
1615 case CodeGenInstAlias::ResultOperand::K_Imm: {
1616 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1617 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1618 break;
1619 }
1620 case CodeGenInstAlias::ResultOperand::K_Reg: {
1621 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1622 ResOperands.push_back(ResOperand::getRegOp(Reg));
1623 break;
1624 }
1625 }
Chris Lattner90fd7972010-11-06 19:57:21 +00001626 }
Chris Lattner41409852010-11-06 07:31:43 +00001627 }
1628}
Chris Lattner1d13bda2010-11-04 00:43:46 +00001629
Jim Grosbach8caecde2012-04-19 17:52:32 +00001630static void emitConvertToMCInst(CodeGenTarget &Target, StringRef ClassName,
Chris Lattner22bc5c42010-11-01 05:06:45 +00001631 std::vector<MatchableInfo*> &Infos,
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00001632 raw_ostream &OS) {
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001633 // Write the convert function to a separate stream, so we can drop it after
1634 // the enum.
1635 std::string ConvertFnBody;
1636 raw_string_ostream CvtOS(ConvertFnBody);
1637
Daniel Dunbar20927f22009-08-07 08:26:05 +00001638 // Function we have already generated.
1639 std::set<std::string> GeneratedFns;
1640
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001641 // Start the unified conversion function.
Daniel Dunbar5c228a92011-02-04 23:17:40 +00001642 CvtOS << "bool " << Target.getName() << ClassName << "::\n";
1643 CvtOS << "ConvertToMCInst(unsigned Kind, MCInst &Inst, "
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001644 << "unsigned Opcode,\n"
Chris Lattner98986712010-01-14 22:21:20 +00001645 << " const SmallVectorImpl<MCParsedAsmOperand*"
1646 << "> &Operands) {\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001647 CvtOS << " Inst.setOpcode(Opcode);\n";
1648 CvtOS << " switch (Kind) {\n";
1649 CvtOS << " default:\n";
1650
1651 // Start the enum, which we will generate inline.
1652
Chris Lattnerd51257a2010-11-02 23:18:43 +00001653 OS << "// Unified function for converting operands to MCInst instances.\n\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001654 OS << "enum ConversionKind {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001655
Chris Lattner98986712010-01-14 22:21:20 +00001656 // TargetOperandClass - This is the target's operand class, like X86Operand.
1657 std::string TargetOperandClass = Target.getName() + "Operand";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001658
Chris Lattner22bc5c42010-11-01 05:06:45 +00001659 for (std::vector<MatchableInfo*>::const_iterator it = Infos.begin(),
Daniel Dunbar20927f22009-08-07 08:26:05 +00001660 ie = Infos.end(); it != ie; ++it) {
Chris Lattner22bc5c42010-11-01 05:06:45 +00001661 MatchableInfo &II = **it;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001662
Daniel Dunbarcf120672011-02-04 17:12:15 +00001663 // Check if we have a custom match function.
Daniel Dunbar27b83d42011-04-01 20:23:52 +00001664 std::string AsmMatchConverter =
1665 II.getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
Daniel Dunbarcf120672011-02-04 17:12:15 +00001666 if (!AsmMatchConverter.empty()) {
Daniel Dunbar27b83d42011-04-01 20:23:52 +00001667 std::string Signature = "ConvertCustom_" + AsmMatchConverter;
Daniel Dunbarcf120672011-02-04 17:12:15 +00001668 II.ConversionFnKind = Signature;
1669
1670 // Check if we have already generated this signature.
1671 if (!GeneratedFns.insert(Signature).second)
1672 continue;
1673
1674 // If not, emit it now. Add to the enum list.
1675 OS << " " << Signature << ",\n";
1676
1677 CvtOS << " case " << Signature << ":\n";
Daniel Dunbarb4129152011-02-04 17:12:23 +00001678 CvtOS << " return " << AsmMatchConverter
1679 << "(Inst, Opcode, Operands);\n";
Daniel Dunbarcf120672011-02-04 17:12:15 +00001680 continue;
1681 }
1682
Daniel Dunbar20927f22009-08-07 08:26:05 +00001683 // Build the conversion function signature.
1684 std::string Signature = "Convert";
Chris Lattnerdda855d2010-11-02 21:49:44 +00001685 std::string CaseBody;
1686 raw_string_ostream CaseOS(CaseBody);
Bob Wilson828295b2011-01-26 21:26:19 +00001687
Chris Lattnerdda855d2010-11-02 21:49:44 +00001688 // Compute the convert enum and the case body.
Chris Lattner1d13bda2010-11-04 00:43:46 +00001689 for (unsigned i = 0, e = II.ResOperands.size(); i != e; ++i) {
1690 const MatchableInfo::ResOperand &OpInfo = II.ResOperands[i];
Jim Grosbacha7c78222010-10-29 22:13:48 +00001691
Chris Lattner1d13bda2010-11-04 00:43:46 +00001692 // Generate code to populate each result operand.
1693 switch (OpInfo.Kind) {
Chris Lattner1d13bda2010-11-04 00:43:46 +00001694 case MatchableInfo::ResOperand::RenderAsmOperand: {
1695 // This comes from something we parsed.
1696 MatchableInfo::AsmOperand &Op = II.AsmOperands[OpInfo.AsmOperandNum];
Bob Wilson828295b2011-01-26 21:26:19 +00001697
Chris Lattner9b0d4bf2010-11-02 22:55:03 +00001698 // Registers are always converted the same, don't duplicate the
1699 // conversion function based on them.
Chris Lattner9b0d4bf2010-11-02 22:55:03 +00001700 Signature += "__";
1701 if (Op.Class->isRegisterClass())
1702 Signature += "Reg";
1703 else
1704 Signature += Op.Class->ClassName;
Bob Wilsona49c7df2011-01-26 19:44:55 +00001705 Signature += utostr(OpInfo.MINumOperands);
Chris Lattner1d13bda2010-11-04 00:43:46 +00001706 Signature += "_" + itostr(OpInfo.AsmOperandNum);
Bob Wilson828295b2011-01-26 21:26:19 +00001707
Chris Lattner9b0d4bf2010-11-02 22:55:03 +00001708 CaseOS << " ((" << TargetOperandClass << "*)Operands["
Chris Lattner1d13bda2010-11-04 00:43:46 +00001709 << (OpInfo.AsmOperandNum+1) << "])->" << Op.Class->RenderMethod
Bob Wilsona49c7df2011-01-26 19:44:55 +00001710 << "(Inst, " << OpInfo.MINumOperands << ");\n";
Chris Lattner1d13bda2010-11-04 00:43:46 +00001711 break;
Daniel Dunbaraf616812010-02-10 08:15:48 +00001712 }
Bob Wilson828295b2011-01-26 21:26:19 +00001713
Chris Lattner1d13bda2010-11-04 00:43:46 +00001714 case MatchableInfo::ResOperand::TiedOperand: {
1715 // If this operand is tied to a previous one, just copy the MCInst
1716 // operand from the earlier one.We can only tie single MCOperand values.
Bob Wilsona49c7df2011-01-26 19:44:55 +00001717 //assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
Chris Lattner1d13bda2010-11-04 00:43:46 +00001718 unsigned TiedOp = OpInfo.TiedOperandNum;
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001719 assert(i > TiedOp && "Tied operand precedes its target!");
Chris Lattner1d13bda2010-11-04 00:43:46 +00001720 CaseOS << " Inst.addOperand(Inst.getOperand(" << TiedOp << "));\n";
1721 Signature += "__Tie" + utostr(TiedOp);
1722 break;
1723 }
Chris Lattner98c870f2010-11-06 19:25:43 +00001724 case MatchableInfo::ResOperand::ImmOperand: {
1725 int64_t Val = OpInfo.ImmVal;
1726 CaseOS << " Inst.addOperand(MCOperand::CreateImm(" << Val << "));\n";
1727 Signature += "__imm" + itostr(Val);
1728 break;
1729 }
Chris Lattner90fd7972010-11-06 19:57:21 +00001730 case MatchableInfo::ResOperand::RegOperand: {
Bob Wilsondc1a2bd2011-01-14 22:58:09 +00001731 if (OpInfo.Register == 0) {
1732 CaseOS << " Inst.addOperand(MCOperand::CreateReg(0));\n";
1733 Signature += "__reg0";
1734 } else {
1735 std::string N = getQualifiedName(OpInfo.Register);
1736 CaseOS << " Inst.addOperand(MCOperand::CreateReg(" << N << "));\n";
1737 Signature += "__reg" + OpInfo.Register->getName();
1738 }
Bob Wilson828295b2011-01-26 21:26:19 +00001739 }
Chris Lattner1d13bda2010-11-04 00:43:46 +00001740 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00001741 }
Bob Wilson828295b2011-01-26 21:26:19 +00001742
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001743 II.ConversionFnKind = Signature;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001744
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001745 // Check if we have already generated this signature.
Daniel Dunbar20927f22009-08-07 08:26:05 +00001746 if (!GeneratedFns.insert(Signature).second)
1747 continue;
1748
Chris Lattnerdda855d2010-11-02 21:49:44 +00001749 // If not, emit it now. Add to the enum list.
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001750 OS << " " << Signature << ",\n";
1751
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001752 CvtOS << " case " << Signature << ":\n";
Chris Lattnerdda855d2010-11-02 21:49:44 +00001753 CvtOS << CaseOS.str();
Daniel Dunbarb4129152011-02-04 17:12:23 +00001754 CvtOS << " return true;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001755 }
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001756
1757 // Finish the convert function.
1758
1759 CvtOS << " }\n";
Daniel Dunbarb4129152011-02-04 17:12:23 +00001760 CvtOS << " return false;\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001761 CvtOS << "}\n\n";
1762
1763 // Finish the enum, and drop the convert function after it.
1764
1765 OS << " NumConversionVariants\n";
1766 OS << "};\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001767
Daniel Dunbarb7479c02009-08-08 05:24:34 +00001768 OS << CvtOS.str();
Daniel Dunbara027d222009-07-31 02:32:59 +00001769}
1770
Jim Grosbach8caecde2012-04-19 17:52:32 +00001771/// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
1772static void emitMatchClassEnumeration(CodeGenTarget &Target,
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001773 std::vector<ClassInfo*> &Infos,
1774 raw_ostream &OS) {
1775 OS << "namespace {\n\n";
1776
1777 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
1778 << "/// instruction matching.\n";
1779 OS << "enum MatchClassKind {\n";
1780 OS << " InvalidMatchClass = 0,\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001781 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001782 ie = Infos.end(); it != ie; ++it) {
1783 ClassInfo &CI = **it;
1784 OS << " " << CI.Name << ", // ";
1785 if (CI.Kind == ClassInfo::Token) {
1786 OS << "'" << CI.ValueName << "'\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001787 } else if (CI.isRegisterClass()) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001788 if (!CI.ValueName.empty())
1789 OS << "register class '" << CI.ValueName << "'\n";
1790 else
1791 OS << "derived register class\n";
1792 } else {
1793 OS << "user defined class '" << CI.ValueName << "'\n";
1794 }
1795 }
1796 OS << " NumMatchClassKinds\n";
1797 OS << "};\n\n";
1798
1799 OS << "}\n\n";
1800}
1801
Jim Grosbach8caecde2012-04-19 17:52:32 +00001802/// emitValidateOperandClass - Emit the function to validate an operand class.
1803static void emitValidateOperandClass(AsmMatcherInfo &Info,
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001804 raw_ostream &OS) {
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00001805 OS << "static bool validateOperandClass(MCParsedAsmOperand *GOp, "
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001806 << "MatchClassKind Kind) {\n";
1807 OS << " " << Info.Target.getName() << "Operand &Operand = *("
Chris Lattner02bcbc92010-11-01 01:37:30 +00001808 << Info.Target.getName() << "Operand*)GOp;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001809
Kevin Enderby89381832011-07-15 18:30:43 +00001810 // The InvalidMatchClass is not to match any operand.
1811 OS << " if (Kind == InvalidMatchClass)\n";
1812 OS << " return false;\n\n";
1813
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001814 // Check for Token operands first.
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001815 OS << " if (Operand.isToken())\n";
Jim Grosbacha66512e2011-12-06 23:43:54 +00001816 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind);"
1817 << "\n\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001818
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001819 // Check for register operands, including sub-classes.
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001820 OS << " if (Operand.isReg()) {\n";
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001821 OS << " MatchClassKind OpKind;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001822 OS << " switch (Operand.getReg()) {\n";
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001823 OS << " default: OpKind = InvalidMatchClass; break;\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001824 for (std::map<Record*, ClassInfo*>::iterator
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001825 it = Info.RegisterClasses.begin(), ie = Info.RegisterClasses.end();
1826 it != ie; ++it)
Chris Lattner02bcbc92010-11-01 01:37:30 +00001827 OS << " case " << Info.Target.getName() << "::"
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001828 << it->first->getName() << ": OpKind = " << it->second->Name
1829 << "; break;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001830 OS << " }\n";
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00001831 OS << " return isSubclass(OpKind, Kind);\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001832 OS << " }\n\n";
1833
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001834 // Check the user classes. We don't care what order since we're only
1835 // actually matching against one of them.
Jim Grosbacha7c78222010-10-29 22:13:48 +00001836 for (std::vector<ClassInfo*>::iterator it = Info.Classes.begin(),
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001837 ie = Info.Classes.end(); it != ie; ++it) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001838 ClassInfo &CI = **it;
1839
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001840 if (!CI.isUserClass())
1841 continue;
Bob Wilson828295b2011-01-26 21:26:19 +00001842
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001843 OS << " // '" << CI.ClassName << "' class\n";
1844 OS << " if (Kind == " << CI.Name
1845 << " && Operand." << CI.PredicateMethod << "()) {\n";
1846 OS << " return true;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001847 OS << " }\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001848 }
Bob Wilson828295b2011-01-26 21:26:19 +00001849
Jim Grosbachb9db0c52011-02-10 00:08:28 +00001850 OS << " return false;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001851 OS << "}\n\n";
1852}
1853
Jim Grosbach8caecde2012-04-19 17:52:32 +00001854/// emitIsSubclass - Emit the subclass predicate function.
1855static void emitIsSubclass(CodeGenTarget &Target,
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001856 std::vector<ClassInfo*> &Infos,
1857 raw_ostream &OS) {
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00001858 OS << "/// isSubclass - Compute whether \\arg A is a subclass of \\arg B.\n";
1859 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001860 OS << " if (A == B)\n";
1861 OS << " return true;\n\n";
1862
1863 OS << " switch (A) {\n";
1864 OS << " default:\n";
1865 OS << " return false;\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001866 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001867 ie = Infos.end(); it != ie; ++it) {
1868 ClassInfo &A = **it;
1869
Jim Grosbacha66512e2011-12-06 23:43:54 +00001870 std::vector<StringRef> SuperClasses;
1871 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
1872 ie = Infos.end(); it != ie; ++it) {
1873 ClassInfo &B = **it;
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001874
Jim Grosbacha66512e2011-12-06 23:43:54 +00001875 if (&A != &B && A.isSubsetOf(B))
1876 SuperClasses.push_back(B.Name);
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001877 }
Jim Grosbacha66512e2011-12-06 23:43:54 +00001878
1879 if (SuperClasses.empty())
1880 continue;
1881
1882 OS << "\n case " << A.Name << ":\n";
1883
1884 if (SuperClasses.size() == 1) {
1885 OS << " return B == " << SuperClasses.back() << ";\n";
1886 continue;
1887 }
1888
1889 OS << " switch (B) {\n";
1890 OS << " default: return false;\n";
1891 for (unsigned i = 0, e = SuperClasses.size(); i != e; ++i)
1892 OS << " case " << SuperClasses[i] << ": return true;\n";
1893 OS << " }\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00001894 }
1895 OS << " }\n";
1896 OS << "}\n\n";
1897}
1898
Jim Grosbach8caecde2012-04-19 17:52:32 +00001899/// emitMatchTokenString - Emit the function to match a token string to the
Daniel Dunbar245f0582009-08-08 21:22:41 +00001900/// appropriate match class value.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001901static void emitMatchTokenString(CodeGenTarget &Target,
Daniel Dunbar245f0582009-08-08 21:22:41 +00001902 std::vector<ClassInfo*> &Infos,
1903 raw_ostream &OS) {
1904 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00001905 std::vector<StringMatcher::StringPair> Matches;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001906 for (std::vector<ClassInfo*>::iterator it = Infos.begin(),
Daniel Dunbar245f0582009-08-08 21:22:41 +00001907 ie = Infos.end(); it != ie; ++it) {
1908 ClassInfo &CI = **it;
1909
1910 if (CI.Kind == ClassInfo::Token)
Chris Lattner5845e5c2010-09-06 02:01:51 +00001911 Matches.push_back(StringMatcher::StringPair(CI.ValueName,
1912 "return " + CI.Name + ";"));
Daniel Dunbar245f0582009-08-08 21:22:41 +00001913 }
1914
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00001915 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001916
Chris Lattner5845e5c2010-09-06 02:01:51 +00001917 StringMatcher("Name", Matches, OS).Emit();
Daniel Dunbar245f0582009-08-08 21:22:41 +00001918
1919 OS << " return InvalidMatchClass;\n";
1920 OS << "}\n\n";
1921}
Chris Lattner70add882009-08-08 20:02:57 +00001922
Jim Grosbach8caecde2012-04-19 17:52:32 +00001923/// emitMatchRegisterName - Emit the function to match a string to the target
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001924/// specific register enum.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001925static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001926 raw_ostream &OS) {
Daniel Dunbar245f0582009-08-08 21:22:41 +00001927 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00001928 std::vector<StringMatcher::StringPair> Matches;
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +00001929 const std::vector<CodeGenRegister*> &Regs =
1930 Target.getRegBank().getRegisters();
1931 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
1932 const CodeGenRegister *Reg = Regs[i];
1933 if (Reg->TheDef->getValueAsString("AsmName").empty())
Daniel Dunbar22be5222009-07-17 18:51:11 +00001934 continue;
1935
Chris Lattner5845e5c2010-09-06 02:01:51 +00001936 Matches.push_back(StringMatcher::StringPair(
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +00001937 Reg->TheDef->getValueAsString("AsmName"),
1938 "return " + utostr(Reg->EnumValue) + ";"));
Daniel Dunbar22be5222009-07-17 18:51:11 +00001939 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001940
Chris Lattnerb8d6e982010-02-09 00:34:28 +00001941 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00001942
Chris Lattner5845e5c2010-09-06 02:01:51 +00001943 StringMatcher("Name", Matches, OS).Emit();
Jim Grosbacha7c78222010-10-29 22:13:48 +00001944
Daniel Dunbar245f0582009-08-08 21:22:41 +00001945 OS << " return 0;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00001946 OS << "}\n\n";
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00001947}
Daniel Dunbara027d222009-07-31 02:32:59 +00001948
Jim Grosbach8caecde2012-04-19 17:52:32 +00001949/// emitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
Daniel Dunbar54074b52010-07-19 05:44:09 +00001950/// definitions.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001951static void emitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
Daniel Dunbar54074b52010-07-19 05:44:09 +00001952 raw_ostream &OS) {
1953 OS << "// Flags for subtarget features that participate in "
1954 << "instruction matching.\n";
1955 OS << "enum SubtargetFeatureFlag {\n";
1956 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1957 it = Info.SubtargetFeatures.begin(),
1958 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1959 SubtargetFeatureInfo &SFI = *it->second;
Chris Lattner0aed1e72010-10-30 20:07:57 +00001960 OS << " " << SFI.getEnumName() << " = (1 << " << SFI.Index << "),\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001961 }
1962 OS << " Feature_None = 0\n";
1963 OS << "};\n\n";
1964}
1965
Jim Grosbach14ce6fa2012-04-24 22:40:08 +00001966/// emitGetSubtargetFeatureName - Emit the helper function to get the
1967/// user-level name for a subtarget feature.
1968static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
1969 OS << "// User-level names for subtarget features that participate in\n"
1970 << "// instruction matching.\n"
1971 << "static const char *getSubtargetFeatureName(unsigned Val) {\n"
1972 << " switch(Val) {\n";
1973 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1974 it = Info.SubtargetFeatures.begin(),
1975 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1976 SubtargetFeatureInfo &SFI = *it->second;
1977 // FIXME: Totally just a placeholder name to get the algorithm working.
1978 OS << " case " << SFI.getEnumName() << ": return \""
1979 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
1980 }
1981 OS << " default: return \"(unknown)\";\n";
1982 OS << " }\n}\n\n";
1983}
1984
Jim Grosbach8caecde2012-04-19 17:52:32 +00001985/// emitComputeAvailableFeatures - Emit the function to compute the list of
Daniel Dunbar54074b52010-07-19 05:44:09 +00001986/// available features given a subtarget.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001987static void emitComputeAvailableFeatures(AsmMatcherInfo &Info,
Daniel Dunbar54074b52010-07-19 05:44:09 +00001988 raw_ostream &OS) {
1989 std::string ClassName =
1990 Info.AsmParser->getValueAsString("AsmParserClassName");
1991
Chris Lattner02bcbc92010-11-01 01:37:30 +00001992 OS << "unsigned " << Info.Target.getName() << ClassName << "::\n"
Evan Chengebdeeab2011-07-08 01:53:10 +00001993 << "ComputeAvailableFeatures(uint64_t FB) const {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00001994 OS << " unsigned Features = 0;\n";
1995 for (std::map<Record*, SubtargetFeatureInfo*>::const_iterator
1996 it = Info.SubtargetFeatures.begin(),
1997 ie = Info.SubtargetFeatures.end(); it != ie; ++it) {
1998 SubtargetFeatureInfo &SFI = *it->second;
Evan Chengebdeeab2011-07-08 01:53:10 +00001999
2000 OS << " if (";
Jim Grosbach65da6fc2012-04-17 00:01:04 +00002001 std::string CondStorage =
2002 SFI.TheDef->getValueAsString("AssemblerCondString");
Evan Chengfbc38d22011-07-08 18:04:22 +00002003 StringRef Conds = CondStorage;
Evan Chengebdeeab2011-07-08 01:53:10 +00002004 std::pair<StringRef,StringRef> Comma = Conds.split(',');
2005 bool First = true;
2006 do {
2007 if (!First)
2008 OS << " && ";
2009
2010 bool Neg = false;
2011 StringRef Cond = Comma.first;
2012 if (Cond[0] == '!') {
2013 Neg = true;
2014 Cond = Cond.substr(1);
2015 }
2016
2017 OS << "((FB & " << Info.Target.getName() << "::" << Cond << ")";
2018 if (Neg)
2019 OS << " == 0";
2020 else
2021 OS << " != 0";
2022 OS << ")";
2023
2024 if (Comma.second.empty())
2025 break;
2026
2027 First = false;
2028 Comma = Comma.second.split(',');
2029 } while (true);
2030
2031 OS << ")\n";
Chris Lattner0aed1e72010-10-30 20:07:57 +00002032 OS << " Features |= " << SFI.getEnumName() << ";\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00002033 }
2034 OS << " return Features;\n";
2035 OS << "}\n\n";
2036}
2037
Chris Lattner6fa152c2010-10-30 20:15:02 +00002038static std::string GetAliasRequiredFeatures(Record *R,
2039 const AsmMatcherInfo &Info) {
Chris Lattner693173f2010-10-30 19:23:13 +00002040 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
Chris Lattner693173f2010-10-30 19:23:13 +00002041 std::string Result;
2042 unsigned NumFeatures = 0;
2043 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
Chris Lattner4a74ee72010-11-01 02:09:21 +00002044 SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
Bob Wilson828295b2011-01-26 21:26:19 +00002045
Chris Lattner4a74ee72010-11-01 02:09:21 +00002046 if (F == 0)
2047 throw TGError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
2048 "' is not marked as an AssemblerPredicate!");
Bob Wilson828295b2011-01-26 21:26:19 +00002049
Chris Lattner4a74ee72010-11-01 02:09:21 +00002050 if (NumFeatures)
2051 Result += '|';
Bob Wilson828295b2011-01-26 21:26:19 +00002052
Chris Lattner4a74ee72010-11-01 02:09:21 +00002053 Result += F->getEnumName();
2054 ++NumFeatures;
Chris Lattner693173f2010-10-30 19:23:13 +00002055 }
Bob Wilson828295b2011-01-26 21:26:19 +00002056
Chris Lattner693173f2010-10-30 19:23:13 +00002057 if (NumFeatures > 1)
2058 Result = '(' + Result + ')';
2059 return Result;
2060}
2061
Jim Grosbach8caecde2012-04-19 17:52:32 +00002062/// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
Chris Lattner7fd44892010-10-30 18:48:18 +00002063/// emit a function for them and return true, otherwise return false.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002064static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info) {
Daniel Dunbarc0a70072011-01-24 23:26:31 +00002065 // Ignore aliases when match-prefix is set.
2066 if (!MatchPrefix.empty())
2067 return false;
2068
Chris Lattner674c1dc2010-10-30 17:36:36 +00002069 std::vector<Record*> Aliases =
Chris Lattner67db8832010-12-13 00:23:57 +00002070 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
Chris Lattner7fd44892010-10-30 18:48:18 +00002071 if (Aliases.empty()) return false;
Chris Lattner674c1dc2010-10-30 17:36:36 +00002072
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00002073 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
Chris Lattner8cc0a6b2010-10-30 18:57:07 +00002074 "unsigned Features) {\n";
Bob Wilson828295b2011-01-26 21:26:19 +00002075
Chris Lattner4fd32c62010-10-30 18:56:12 +00002076 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
2077 // iteration order of the map is stable.
2078 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
Bob Wilson828295b2011-01-26 21:26:19 +00002079
Chris Lattner674c1dc2010-10-30 17:36:36 +00002080 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
2081 Record *R = Aliases[i];
Chris Lattner4fd32c62010-10-30 18:56:12 +00002082 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
Chris Lattner674c1dc2010-10-30 17:36:36 +00002083 }
Chris Lattner4fd32c62010-10-30 18:56:12 +00002084
2085 // Process each alias a "from" mnemonic at a time, building the code executed
2086 // by the string remapper.
2087 std::vector<StringMatcher::StringPair> Cases;
2088 for (std::map<std::string, std::vector<Record*> >::iterator
2089 I = AliasesFromMnemonic.begin(), E = AliasesFromMnemonic.end();
2090 I != E; ++I) {
Chris Lattner4fd32c62010-10-30 18:56:12 +00002091 const std::vector<Record*> &ToVec = I->second;
Chris Lattner693173f2010-10-30 19:23:13 +00002092
2093 // Loop through each alias and emit code that handles each case. If there
2094 // are two instructions without predicates, emit an error. If there is one,
2095 // emit it last.
2096 std::string MatchCode;
2097 int AliasWithNoPredicate = -1;
Bob Wilson828295b2011-01-26 21:26:19 +00002098
Chris Lattner693173f2010-10-30 19:23:13 +00002099 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
2100 Record *R = ToVec[i];
Chris Lattner6fa152c2010-10-30 20:15:02 +00002101 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
Bob Wilson828295b2011-01-26 21:26:19 +00002102
Chris Lattner693173f2010-10-30 19:23:13 +00002103 // If this unconditionally matches, remember it for later and diagnose
2104 // duplicates.
2105 if (FeatureMask.empty()) {
2106 if (AliasWithNoPredicate != -1) {
2107 // We can't have two aliases from the same mnemonic with no predicate.
2108 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
2109 "two MnemonicAliases with the same 'from' mnemonic!");
Chris Lattner4164f6b2010-11-01 04:44:29 +00002110 throw TGError(R->getLoc(), "this is the other MnemonicAlias.");
Chris Lattner693173f2010-10-30 19:23:13 +00002111 }
Bob Wilson828295b2011-01-26 21:26:19 +00002112
Chris Lattner693173f2010-10-30 19:23:13 +00002113 AliasWithNoPredicate = i;
2114 continue;
2115 }
Joerg Sonnenberger6ef6ced2011-02-17 23:22:19 +00002116 if (R->getValueAsString("ToMnemonic") == I->first)
2117 throw TGError(R->getLoc(), "MnemonicAlias to the same string");
Bob Wilson828295b2011-01-26 21:26:19 +00002118
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00002119 if (!MatchCode.empty())
2120 MatchCode += "else ";
Chris Lattner693173f2010-10-30 19:23:13 +00002121 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
2122 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattner4fd32c62010-10-30 18:56:12 +00002123 }
Bob Wilson828295b2011-01-26 21:26:19 +00002124
Chris Lattner693173f2010-10-30 19:23:13 +00002125 if (AliasWithNoPredicate != -1) {
2126 Record *R = ToVec[AliasWithNoPredicate];
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00002127 if (!MatchCode.empty())
2128 MatchCode += "else\n ";
2129 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattner693173f2010-10-30 19:23:13 +00002130 }
Bob Wilson828295b2011-01-26 21:26:19 +00002131
Chris Lattner693173f2010-10-30 19:23:13 +00002132 MatchCode += "return;";
2133
2134 Cases.push_back(std::make_pair(I->first, MatchCode));
Chris Lattner4fd32c62010-10-30 18:56:12 +00002135 }
Bob Wilson828295b2011-01-26 21:26:19 +00002136
Chris Lattner674c1dc2010-10-30 17:36:36 +00002137 StringMatcher("Mnemonic", Cases, OS).Emit();
Daniel Dunbar55b5e852011-01-18 01:59:30 +00002138 OS << "}\n\n";
Bob Wilson828295b2011-01-26 21:26:19 +00002139
Chris Lattner7fd44892010-10-30 18:48:18 +00002140 return true;
Chris Lattner674c1dc2010-10-30 17:36:36 +00002141}
2142
Jim Grosbach194f3fa2012-03-01 17:30:35 +00002143static const char *getMinimalTypeForRange(uint64_t Range) {
2144 assert(Range < 0xFFFFFFFFULL && "Enum too large");
2145 if (Range > 0xFFFF)
2146 return "uint32_t";
2147 if (Range > 0xFF)
2148 return "uint16_t";
2149 return "uint8_t";
2150}
2151
Jim Grosbach8caecde2012-04-19 17:52:32 +00002152static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002153 const AsmMatcherInfo &Info, StringRef ClassName) {
2154 // Emit the static custom operand parsing table;
2155 OS << "namespace {\n";
2156 OS << " struct OperandMatchEntry {\n";
Jakob Stoklund Olesen7044cce2012-03-15 21:22:53 +00002157 OS << " static const char *const MnemonicTable;\n";
Craig Topperfab3f7e2012-04-02 07:48:39 +00002158 OS << " uint32_t OperandMask;\n";
2159 OS << " uint32_t Mnemonic;\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002160 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
Craig Topperfab3f7e2012-04-02 07:48:39 +00002161 << " RequiredFeatures;\n";
2162 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2163 << " Class;\n\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002164 OS << " StringRef getMnemonic() const {\n";
2165 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2166 OS << " MnemonicTable[Mnemonic]);\n";
2167 OS << " }\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002168 OS << " };\n\n";
2169
2170 OS << " // Predicate for searching for an opcode.\n";
2171 OS << " struct LessOpcodeOperand {\n";
2172 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002173 OS << " return LHS.getMnemonic() < RHS;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002174 OS << " }\n";
2175 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002176 OS << " return LHS < RHS.getMnemonic();\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002177 OS << " }\n";
2178 OS << " bool operator()(const OperandMatchEntry &LHS,";
2179 OS << " const OperandMatchEntry &RHS) {\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002180 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002181 OS << " }\n";
2182 OS << " };\n";
2183
2184 OS << "} // end anonymous namespace.\n\n";
2185
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002186 StringToOffsetTable StringTable;
2187
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002188 OS << "static const OperandMatchEntry OperandMatchTable["
2189 << Info.OperandMatchInfo.size() << "] = {\n";
2190
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002191 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002192 for (std::vector<OperandMatchEntry>::const_iterator it =
2193 Info.OperandMatchInfo.begin(), ie = Info.OperandMatchInfo.end();
2194 it != ie; ++it) {
2195 const OperandMatchEntry &OMI = *it;
2196 const MatchableInfo &II = *OMI.MI;
2197
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002198 OS << " { " << OMI.OperandMask;
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002199
2200 OS << " /* ";
2201 bool printComma = false;
2202 for (int i = 0, e = 31; i !=e; ++i)
2203 if (OMI.OperandMask & (1 << i)) {
2204 if (printComma)
2205 OS << ", ";
2206 OS << i;
2207 printComma = true;
2208 }
2209 OS << " */";
2210
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002211 // Store a pascal-style length byte in the mnemonic.
2212 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
Jakob Stoklund Olesenbcfa9822012-03-15 18:05:57 +00002213 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
Craig Topperfab3f7e2012-04-02 07:48:39 +00002214 << " /* " << II.Mnemonic << " */, ";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002215
2216 // Write the required features mask.
2217 if (!II.RequiredFeatures.empty()) {
2218 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2219 if (i) OS << "|";
2220 OS << II.RequiredFeatures[i]->getEnumName();
2221 }
2222 } else
2223 OS << "0";
Craig Topperfab3f7e2012-04-02 07:48:39 +00002224
2225 OS << ", " << OMI.CI->Name;
2226
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002227 OS << " },\n";
2228 }
2229 OS << "};\n\n";
2230
Jakob Stoklund Olesen7044cce2012-03-15 21:22:53 +00002231 OS << "const char *const OperandMatchEntry::MnemonicTable =\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002232 StringTable.EmitString(OS);
2233 OS << ";\n\n";
2234
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002235 // Emit the operand class switch to call the correct custom parser for
2236 // the found operand class.
Jim Grosbachf922c472011-02-12 01:34:40 +00002237 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2238 << Target.getName() << ClassName << "::\n"
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00002239 << "tryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>"
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002240 << " &Operands,\n unsigned MCK) {\n\n"
2241 << " switch(MCK) {\n";
2242
2243 for (std::vector<ClassInfo*>::const_iterator it = Info.Classes.begin(),
2244 ie = Info.Classes.end(); it != ie; ++it) {
2245 ClassInfo *CI = *it;
2246 if (CI->ParserMethod.empty())
2247 continue;
2248 OS << " case " << CI->Name << ":\n"
2249 << " return " << CI->ParserMethod << "(Operands);\n";
2250 }
2251
2252 OS << " default:\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002253 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002254 OS << " }\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002255 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002256 OS << "}\n\n";
2257
2258 // Emit the static custom operand parser. This code is very similar with
2259 // the other matcher. Also use MatchResultTy here just in case we go for
2260 // a better error handling.
Jim Grosbachf922c472011-02-12 01:34:40 +00002261 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002262 << Target.getName() << ClassName << "::\n"
2263 << "MatchOperandParserImpl(SmallVectorImpl<MCParsedAsmOperand*>"
2264 << " &Operands,\n StringRef Mnemonic) {\n";
2265
2266 // Emit code to get the available features.
2267 OS << " // Get the current feature set.\n";
2268 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2269
2270 OS << " // Get the next operand index.\n";
2271 OS << " unsigned NextOpNum = Operands.size()-1;\n";
2272
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002273 // Emit code to search the table.
2274 OS << " // Search the table.\n";
2275 OS << " std::pair<const OperandMatchEntry*, const OperandMatchEntry*>";
2276 OS << " MnemonicRange =\n";
2277 OS << " std::equal_range(OperandMatchTable, OperandMatchTable+"
2278 << Info.OperandMatchInfo.size() << ", Mnemonic,\n"
2279 << " LessOpcodeOperand());\n\n";
2280
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002281 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002282 OS << " return MatchOperand_NoMatch;\n\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002283
2284 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2285 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2286
2287 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002288 OS << " assert(Mnemonic == it->getMnemonic());\n\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002289
2290 // Emit check that the required features are available.
2291 OS << " // check if the available features match\n";
2292 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2293 << "!= it->RequiredFeatures) {\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002294 OS << " continue;\n";
2295 OS << " }\n\n";
2296
2297 // Emit check to ensure the operand number matches.
2298 OS << " // check if the operand in question has a custom parser.\n";
2299 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2300 OS << " continue;\n\n";
2301
2302 // Emit call to the custom parser method
2303 OS << " // call custom parse method to handle the operand\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002304 OS << " OperandMatchResultTy Result = ";
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00002305 OS << "tryCustomParseOperand(Operands, it->Class);\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002306 OS << " if (Result != MatchOperand_NoMatch)\n";
2307 OS << " return Result;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002308 OS << " }\n\n";
2309
Jim Grosbachf922c472011-02-12 01:34:40 +00002310 OS << " // Okay, we had no match.\n";
2311 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002312 OS << "}\n\n";
2313}
2314
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00002315void AsmMatcherEmitter::run(raw_ostream &OS) {
Chris Lattner67db8832010-12-13 00:23:57 +00002316 CodeGenTarget Target(Records);
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00002317 Record *AsmParser = Target.getAsmParser();
2318 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2319
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002320 // Compute the information on the instructions to match.
Chris Lattner67db8832010-12-13 00:23:57 +00002321 AsmMatcherInfo Info(AsmParser, Target, Records);
Jim Grosbach8caecde2012-04-19 17:52:32 +00002322 Info.buildInfo();
Daniel Dunbara027d222009-07-31 02:32:59 +00002323
Daniel Dunbare1f6de32010-02-02 23:46:36 +00002324 // Sort the instruction table using the partial order on classes. We use
2325 // stable_sort to ensure that ambiguous instructions are still
2326 // deterministically ordered.
Chris Lattner22bc5c42010-11-01 05:06:45 +00002327 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2328 less_ptr<MatchableInfo>());
Jim Grosbacha7c78222010-10-29 22:13:48 +00002329
Daniel Dunbarb7479c02009-08-08 05:24:34 +00002330 DEBUG_WITH_TYPE("instruction_info", {
Chris Lattner22bc5c42010-11-01 05:06:45 +00002331 for (std::vector<MatchableInfo*>::iterator
2332 it = Info.Matchables.begin(), ie = Info.Matchables.end();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002333 it != ie; ++it)
Daniel Dunbar20927f22009-08-07 08:26:05 +00002334 (*it)->dump();
2335 });
Daniel Dunbara027d222009-07-31 02:32:59 +00002336
Chris Lattner22bc5c42010-11-01 05:06:45 +00002337 // Check for ambiguous matchables.
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00002338 DEBUG_WITH_TYPE("ambiguous_instrs", {
2339 unsigned NumAmbiguous = 0;
Chris Lattner22bc5c42010-11-01 05:06:45 +00002340 for (unsigned i = 0, e = Info.Matchables.size(); i != e; ++i) {
Chris Lattner87410362010-09-06 20:21:47 +00002341 for (unsigned j = i + 1; j != e; ++j) {
Chris Lattner22bc5c42010-11-01 05:06:45 +00002342 MatchableInfo &A = *Info.Matchables[i];
2343 MatchableInfo &B = *Info.Matchables[j];
Jim Grosbacha7c78222010-10-29 22:13:48 +00002344
Jim Grosbach8caecde2012-04-19 17:52:32 +00002345 if (A.couldMatchAmbiguouslyWith(B)) {
Chris Lattner22bc5c42010-11-01 05:06:45 +00002346 errs() << "warning: ambiguous matchables:\n";
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00002347 A.dump();
2348 errs() << "\nis incomparable with:\n";
2349 B.dump();
2350 errs() << "\n\n";
Chris Lattner87410362010-09-06 20:21:47 +00002351 ++NumAmbiguous;
2352 }
Daniel Dunbar2b544812009-08-09 06:05:33 +00002353 }
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00002354 }
Chris Lattner87410362010-09-06 20:21:47 +00002355 if (NumAmbiguous)
Jim Grosbacha7c78222010-10-29 22:13:48 +00002356 errs() << "warning: " << NumAmbiguous
Chris Lattner22bc5c42010-11-01 05:06:45 +00002357 << " ambiguous matchables!\n";
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00002358 });
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00002359
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002360 // Compute the information on the custom operand parsing.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002361 Info.buildOperandMatchInfo();
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002362
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00002363 // Write the output.
2364
Chris Lattner0692ee62010-09-06 19:11:01 +00002365 // Information for the class declaration.
2366 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2367 OS << "#undef GET_ASSEMBLER_HEADER\n";
Jim Grosbach84cb0332011-02-11 21:31:55 +00002368 OS << " // This should be included into the middle of the declaration of\n";
Evan Cheng94b95502011-07-26 00:24:13 +00002369 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
Evan Chengebdeeab2011-07-08 01:53:10 +00002370 OS << " unsigned ComputeAvailableFeatures(uint64_t FeatureBits) const;\n";
Daniel Dunbar5c228a92011-02-04 23:17:40 +00002371 OS << " bool ConvertToMCInst(unsigned Kind, MCInst &Inst, "
2372 << "unsigned Opcode,\n"
2373 << " const SmallVectorImpl<MCParsedAsmOperand*> "
2374 << "&Operands);\n";
Bob Wilson1fe3aa12011-01-26 21:43:46 +00002375 OS << " bool MnemonicIsValid(StringRef Mnemonic);\n";
Jim Grosbach19cb7f42011-08-15 23:03:29 +00002376 OS << " unsigned MatchInstructionImpl(\n";
Daniel Dunbar083203d2011-01-10 15:26:11 +00002377 OS << " const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
Devang Patel56315d32012-01-10 17:50:43 +00002378 OS << " MCInst &Inst, unsigned &ErrorInfo, unsigned VariantID = 0);\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002379
2380 if (Info.OperandMatchInfo.size()) {
Jim Grosbachf922c472011-02-12 01:34:40 +00002381 OS << "\n enum OperandMatchResultTy {\n";
2382 OS << " MatchOperand_Success, // operand matched successfully\n";
2383 OS << " MatchOperand_NoMatch, // operand did not match\n";
2384 OS << " MatchOperand_ParseFail // operand matched but had errors\n";
2385 OS << " };\n";
2386 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002387 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2388 OS << " StringRef Mnemonic);\n";
2389
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00002390 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002391 OS << " SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
2392 OS << " unsigned MCK);\n\n";
2393 }
2394
Chris Lattner0692ee62010-09-06 19:11:01 +00002395 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2396
Chris Lattner0692ee62010-09-06 19:11:01 +00002397 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2398 OS << "#undef GET_REGISTER_MATCHER\n\n";
2399
Daniel Dunbar54074b52010-07-19 05:44:09 +00002400 // Emit the subtarget feature enumeration.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002401 emitSubtargetFeatureFlagEnumeration(Info, OS);
Daniel Dunbar54074b52010-07-19 05:44:09 +00002402
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00002403 // Emit the function to match a register name to number.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002404 emitMatchRegisterName(Target, AsmParser, OS);
Chris Lattner0692ee62010-09-06 19:11:01 +00002405
2406 OS << "#endif // GET_REGISTER_MATCHER\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002407
Craig Topper8030e1a2012-04-25 06:56:34 +00002408 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
2409 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00002410
Jim Grosbach14ce6fa2012-04-24 22:40:08 +00002411 // Generate the helper function to get the names for subtarget features.
2412 emitGetSubtargetFeatureName(Info, OS);
2413
Craig Topper8030e1a2012-04-25 06:56:34 +00002414 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
2415
2416 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2417 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
2418
Chris Lattner7fd44892010-10-30 18:48:18 +00002419 // Generate the function that remaps for mnemonic aliases.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002420 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info);
Bob Wilson828295b2011-01-26 21:26:19 +00002421
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00002422 // Generate the unified function to convert operands into an MCInst.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002423 emitConvertToMCInst(Target, ClassName, Info.Matchables, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00002424
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002425 // Emit the enumeration for classes which participate in matching.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002426 emitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00002427
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002428 // Emit the routine to match token strings to their match class.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002429 emitMatchTokenString(Target, Info.Classes, OS);
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002430
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00002431 // Emit the subclass predicate routine.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002432 emitIsSubclass(Target, Info.Classes, OS);
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00002433
Jim Grosbachb9db0c52011-02-10 00:08:28 +00002434 // Emit the routine to validate an operand against a match class.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002435 emitValidateOperandClass(Info, OS);
Jim Grosbachb9db0c52011-02-10 00:08:28 +00002436
Daniel Dunbar54074b52010-07-19 05:44:09 +00002437 // Emit the available features compute function.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002438 emitComputeAvailableFeatures(Info, OS);
Daniel Dunbar54074b52010-07-19 05:44:09 +00002439
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002440
2441 size_t MaxNumOperands = 0;
Chris Lattner22bc5c42010-11-01 05:06:45 +00002442 for (std::vector<MatchableInfo*>::const_iterator it =
2443 Info.Matchables.begin(), ie = Info.Matchables.end();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002444 it != ie; ++it)
Chris Lattner3116fef2010-11-02 01:03:43 +00002445 MaxNumOperands = std::max(MaxNumOperands, (*it)->AsmOperands.size());
Jim Grosbacha7c78222010-10-29 22:13:48 +00002446
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002447 // Emit the static match table; unused classes get initalized to 0 which is
2448 // guaranteed to be InvalidMatchClass.
2449 //
2450 // FIXME: We can reduce the size of this table very easily. First, we change
2451 // it so that store the kinds in separate bit-fields for each index, which
2452 // only needs to be the max width used for classes at that index (we also need
2453 // to reject based on this during classification). If we then make sure to
2454 // order the match kinds appropriately (putting mnemonics last), then we
2455 // should only end up using a few bits for each class, especially the ones
2456 // following the mnemonic.
Chris Lattner96352e52010-09-06 21:08:38 +00002457 OS << "namespace {\n";
2458 OS << " struct MatchEntry {\n";
Jakob Stoklund Olesen7044cce2012-03-15 21:22:53 +00002459 OS << " static const char *const MnemonicTable;\n";
Craig Topperfab3f7e2012-04-02 07:48:39 +00002460 OS << " uint32_t Mnemonic;\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002461 OS << " uint16_t Opcode;\n";
Benjamin Krameraf482cf2011-10-17 16:18:09 +00002462 OS << " " << getMinimalTypeForRange(Info.Matchables.size())
2463 << " ConvertFn;\n";
Benjamin Krameraf482cf2011-10-17 16:18:09 +00002464 OS << " " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.size())
2465 << " RequiredFeatures;\n";
Craig Topperfab3f7e2012-04-02 07:48:39 +00002466 OS << " " << getMinimalTypeForRange(Info.Classes.size())
2467 << " Classes[" << MaxNumOperands << "];\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002468 OS << " uint8_t AsmVariantID;\n\n";
2469 OS << " StringRef getMnemonic() const {\n";
2470 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2471 OS << " MnemonicTable[Mnemonic]);\n";
2472 OS << " }\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002473 OS << " };\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002474
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002475 OS << " // Predicate for searching for an opcode.\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002476 OS << " struct LessOpcode {\n";
2477 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002478 OS << " return LHS.getMnemonic() < RHS;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002479 OS << " }\n";
2480 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002481 OS << " return LHS < RHS.getMnemonic();\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002482 OS << " }\n";
Chris Lattner32c685c2010-09-07 06:10:48 +00002483 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002484 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Chris Lattner32c685c2010-09-07 06:10:48 +00002485 OS << " }\n";
Chris Lattner96352e52010-09-06 21:08:38 +00002486 OS << " };\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002487
Chris Lattner96352e52010-09-06 21:08:38 +00002488 OS << "} // end anonymous namespace.\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002489
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002490 StringToOffsetTable StringTable;
2491
Chris Lattner96352e52010-09-06 21:08:38 +00002492 OS << "static const MatchEntry MatchTable["
Chris Lattner22bc5c42010-11-01 05:06:45 +00002493 << Info.Matchables.size() << "] = {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002494
Chris Lattner22bc5c42010-11-01 05:06:45 +00002495 for (std::vector<MatchableInfo*>::const_iterator it =
2496 Info.Matchables.begin(), ie = Info.Matchables.end();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002497 it != ie; ++it) {
Chris Lattner22bc5c42010-11-01 05:06:45 +00002498 MatchableInfo &II = **it;
Jim Grosbacha7c78222010-10-29 22:13:48 +00002499
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002500 // Store a pascal-style length byte in the mnemonic.
2501 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
Craig Topperfab3f7e2012-04-02 07:48:39 +00002502 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2503 << " /* " << II.Mnemonic << " */, "
2504 << Target.getName() << "::"
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002505 << II.getResultInst()->TheDef->getName() << ", "
Craig Topperfab3f7e2012-04-02 07:48:39 +00002506 << II.ConversionFnKind << ", ";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002507
Daniel Dunbar54074b52010-07-19 05:44:09 +00002508 // Write the required features mask.
2509 if (!II.RequiredFeatures.empty()) {
2510 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2511 if (i) OS << "|";
Chris Lattner0aed1e72010-10-30 20:07:57 +00002512 OS << II.RequiredFeatures[i]->getEnumName();
Daniel Dunbar54074b52010-07-19 05:44:09 +00002513 }
2514 } else
2515 OS << "0";
Craig Topperfab3f7e2012-04-02 07:48:39 +00002516
2517 OS << ", { ";
2518 for (unsigned i = 0, e = II.AsmOperands.size(); i != e; ++i) {
2519 MatchableInfo::AsmOperand &Op = II.AsmOperands[i];
2520
2521 if (i) OS << ", ";
2522 OS << Op.Class->Name;
2523 }
2524 OS << " }, " << II.AsmVariantID;
Daniel Dunbar54074b52010-07-19 05:44:09 +00002525 OS << "},\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00002526 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00002527
Chris Lattner96352e52010-09-06 21:08:38 +00002528 OS << "};\n\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00002529
Jakob Stoklund Olesen7044cce2012-03-15 21:22:53 +00002530 OS << "const char *const MatchEntry::MnemonicTable =\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002531 StringTable.EmitString(OS);
2532 OS << ";\n\n";
2533
Bob Wilson1fe3aa12011-01-26 21:43:46 +00002534 // A method to determine if a mnemonic is in the list.
2535 OS << "bool " << Target.getName() << ClassName << "::\n"
2536 << "MnemonicIsValid(StringRef Mnemonic) {\n";
2537 OS << " // Search the table.\n";
2538 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2539 OS << " std::equal_range(MatchTable, MatchTable+"
2540 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n";
2541 OS << " return MnemonicRange.first != MnemonicRange.second;\n";
2542 OS << "}\n\n";
2543
Chris Lattner96352e52010-09-06 21:08:38 +00002544 // Finally, build the match function.
Jim Grosbach19cb7f42011-08-15 23:03:29 +00002545 OS << "unsigned "
Chris Lattner96352e52010-09-06 21:08:38 +00002546 << Target.getName() << ClassName << "::\n"
2547 << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
2548 << " &Operands,\n";
Jim Grosbach14ce6fa2012-04-24 22:40:08 +00002549 OS << " MCInst &Inst, unsigned &ErrorInfo, ";
2550 OS << "unsigned VariantID) {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00002551
2552 // Emit code to get the available features.
2553 OS << " // Get the current feature set.\n";
2554 OS << " unsigned AvailableFeatures = getAvailableFeatures();\n\n";
2555
Chris Lattner674c1dc2010-10-30 17:36:36 +00002556 OS << " // Get the instruction mnemonic, which is the first token.\n";
2557 OS << " StringRef Mnemonic = ((" << Target.getName()
2558 << "Operand*)Operands[0])->getToken();\n\n";
2559
Chris Lattner7fd44892010-10-30 18:48:18 +00002560 if (HasMnemonicAliases) {
2561 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
Devang Patel40bced02012-01-17 18:30:45 +00002562 OS << " // FIXME : Add an entry in AsmParserVariant to check this.\n";
2563 OS << " if (!VariantID)\n";
2564 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
Chris Lattner7fd44892010-10-30 18:48:18 +00002565 }
Bob Wilson828295b2011-01-26 21:26:19 +00002566
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002567 // Emit code to compute the class list for this operand vector.
2568 OS << " // Eliminate obvious mismatches.\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00002569 OS << " if (Operands.size() > " << (MaxNumOperands+1) << ") {\n";
2570 OS << " ErrorInfo = " << (MaxNumOperands+1) << ";\n";
2571 OS << " return Match_InvalidOperand;\n";
2572 OS << " }\n\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002573
Chris Lattner9bb9fa12010-09-06 23:37:39 +00002574 OS << " // Some state to try to produce better error messages.\n";
Jim Grosbach19cb7f42011-08-15 23:03:29 +00002575 OS << " bool HadMatchOtherThanFeatures = false;\n";
Jim Grosbach578071a2011-08-16 20:12:35 +00002576 OS << " bool HadMatchOtherThanPredicate = false;\n";
Jim Grosbach19cb7f42011-08-15 23:03:29 +00002577 OS << " unsigned RetCode = Match_InvalidOperand;\n";
Jim Grosbach84cb0332011-02-11 21:31:55 +00002578 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00002579 OS << " // wrong for all instances of the instruction.\n";
2580 OS << " ErrorInfo = ~0U;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002581
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002582 // Emit code to search the table.
2583 OS << " // Search the table.\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002584 OS << " std::pair<const MatchEntry*, const MatchEntry*> MnemonicRange =\n";
2585 OS << " std::equal_range(MatchTable, MatchTable+"
Chris Lattner22bc5c42010-11-01 05:06:45 +00002586 << Info.Matchables.size() << ", Mnemonic, LessOpcode());\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002587
Chris Lattnera008e8a2010-09-06 21:54:15 +00002588 OS << " // Return a more specific error code if no mnemonics match.\n";
2589 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2590 OS << " return Match_MnemonicFail;\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002591
Chris Lattner2b1f9432010-09-06 21:22:45 +00002592 OS << " for (const MatchEntry *it = MnemonicRange.first, "
Chris Lattner80db4e52010-09-06 21:23:43 +00002593 << "*ie = MnemonicRange.second;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00002594 OS << " it != ie; ++it) {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00002595
Gabor Greife53ee3b2010-09-07 06:06:06 +00002596 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00002597 OS << " assert(Mnemonic == it->getMnemonic());\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002598
Daniel Dunbar54074b52010-07-19 05:44:09 +00002599 // Emit check that the subclasses match.
Devang Patel56315d32012-01-10 17:50:43 +00002600 OS << " if (VariantID != it->AsmVariantID) continue;\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00002601 OS << " bool OperandsValid = true;\n";
2602 OS << " for (unsigned i = 0; i != " << MaxNumOperands << "; ++i) {\n";
Jim Grosbachb9db0c52011-02-10 00:08:28 +00002603 OS << " if (i + 1 >= Operands.size()) {\n";
2604 OS << " OperandsValid = (it->Classes[i] == " <<"InvalidMatchClass);\n";
Jim Grosbachb9d5af02011-05-03 19:09:56 +00002605 OS << " break;\n";
Jim Grosbachb9db0c52011-02-10 00:08:28 +00002606 OS << " }\n";
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00002607 OS << " if (validateOperandClass(Operands[i+1], "
Benjamin Krameraf482cf2011-10-17 16:18:09 +00002608 "(MatchClassKind)it->Classes[i]))\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00002609 OS << " continue;\n";
Chris Lattner9bb9fa12010-09-06 23:37:39 +00002610 OS << " // If this operand is broken for all of the instances of this\n";
2611 OS << " // mnemonic, keep track of it so we can report loc info.\n";
Kevin Enderby79fcb6d2011-02-02 18:20:55 +00002612 OS << " if (it == MnemonicRange.first || ErrorInfo <= i+1)\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00002613 OS << " ErrorInfo = i+1;\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00002614 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
2615 OS << " OperandsValid = false;\n";
2616 OS << " break;\n";
2617 OS << " }\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002618
Chris Lattnerce4a3352010-09-06 22:11:18 +00002619 OS << " if (!OperandsValid) continue;\n";
Chris Lattnerec6789f2010-09-06 20:08:02 +00002620
2621 // Emit check that the required features are available.
2622 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2623 << "!= it->RequiredFeatures) {\n";
2624 OS << " HadMatchOtherThanFeatures = true;\n";
Jim Grosbach14ce6fa2012-04-24 22:40:08 +00002625 OS << " ErrorInfo = it->RequiredFeatures & ~AvailableFeatures;\n";
Chris Lattnerec6789f2010-09-06 20:08:02 +00002626 OS << " continue;\n";
2627 OS << " }\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002628 OS << "\n";
Daniel Dunbarb4129152011-02-04 17:12:23 +00002629 OS << " // We have selected a definite instruction, convert the parsed\n"
2630 << " // operands into the appropriate MCInst.\n";
2631 OS << " if (!ConvertToMCInst(it->ConvertFn, Inst,\n"
2632 << " it->Opcode, Operands))\n";
2633 OS << " return Match_ConversionFail;\n";
2634 OS << "\n";
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00002635
Jim Grosbach19cb7f42011-08-15 23:03:29 +00002636 // Verify the instruction with the target-specific match predicate function.
2637 OS << " // We have a potential match. Check the target predicate to\n"
2638 << " // handle any context sensitive constraints.\n"
2639 << " unsigned MatchResult;\n"
2640 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
2641 << " Match_Success) {\n"
2642 << " Inst.clear();\n"
2643 << " RetCode = MatchResult;\n"
Jim Grosbach578071a2011-08-16 20:12:35 +00002644 << " HadMatchOtherThanPredicate = true;\n"
Jim Grosbach19cb7f42011-08-15 23:03:29 +00002645 << " continue;\n"
2646 << " }\n\n";
2647
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00002648 // Call the post-processing function, if used.
2649 std::string InsnCleanupFn =
2650 AsmParser->getValueAsString("AsmParserInstCleanup");
2651 if (!InsnCleanupFn.empty())
2652 OS << " " << InsnCleanupFn << "(Inst);\n";
2653
Chris Lattner79ed3f72010-09-06 19:22:17 +00002654 OS << " return Match_Success;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002655 OS << " }\n\n";
2656
Chris Lattnerec6789f2010-09-06 20:08:02 +00002657 OS << " // Okay, we had no match. Try to return a useful error code.\n";
Jim Grosbach578071a2011-08-16 20:12:35 +00002658 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)";
2659 OS << " return RetCode;\n";
Jim Grosbach14ce6fa2012-04-24 22:40:08 +00002660 OS << " assert(ErrorInfo && \"missing feature(s) but what?!\");";
Jim Grosbach578071a2011-08-16 20:12:35 +00002661 OS << " return Match_MissingFeature;\n";
Daniel Dunbara027d222009-07-31 02:32:59 +00002662 OS << "}\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002663
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002664 if (Info.OperandMatchInfo.size())
Jim Grosbach8caecde2012-04-19 17:52:32 +00002665 emitCustomOperandParsing(OS, Target, Info, ClassName);
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002666
Chris Lattner0692ee62010-09-06 19:11:01 +00002667 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbard51ffcf2009-07-11 19:39:44 +00002668}
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +00002669
2670namespace llvm {
2671
2672void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
2673 emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
2674 AsmMatcherEmitter(RK).run(OS);
2675}
2676
2677} // End llvm namespace