blob: 6f7fd2bca857f383a74cf7cef3e571418f672222 [file] [log] [blame]
Daniel Dunbar3085b572009-07-11 19:39:44 +00001//===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a target specifier matcher for converting parsed
Bruno Cardoso Lopes2315beb2011-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 Dunbar3085b572009-07-11 19:39:44 +000016//
Daniel Dunbare10787e2009-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 Grosbach0eccfc22010-10-29 22:13:48 +000027// 'call' '*' %epc
Daniel Dunbare10787e2009-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 Dunbare10787e2009-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 Lopes2315beb2011-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
Craig Topperaae8fb82012-09-18 01:13:36 +000080// identifiers that need to be mapped to specific values in the final encoded
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +000081// 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 Lattner0ab5e2c2011-04-15 05:18:47 +000091// present in the mask, a successful match occurs. Otherwise, fallback
Bruno Cardoso Lopes2315beb2011-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 Dunbar3085b572009-07-11 19:39:44 +000097//===----------------------------------------------------------------------===//
98
Daniel Dunbar3085b572009-07-11 19:39:44 +000099#include "CodeGenTarget.h"
Chris Lattner4efe13d2010-11-04 02:11:18 +0000100#include "llvm/ADT/PointerUnion.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +0000101#include "llvm/ADT/STLExtras.h"
Chris Lattnerf7a01e92010-11-01 01:47:07 +0000102#include "llvm/ADT/SmallPtrSet.h"
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000103#include "llvm/ADT/SmallVector.h"
Daniel Dunbare10787e2009-08-07 08:26:05 +0000104#include "llvm/ADT/StringExtras.h"
105#include "llvm/Support/CommandLine.h"
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000106#include "llvm/Support/Debug.h"
Craig Topperc4965bc2012-02-05 07:21:30 +0000107#include "llvm/Support/ErrorHandling.h"
Peter Collingbourne84c287e2011-10-01 16:41:13 +0000108#include "llvm/TableGen/Error.h"
109#include "llvm/TableGen/Record.h"
Douglas Gregor12c1cd32012-05-02 17:32:48 +0000110#include "llvm/TableGen/StringMatcher.h"
Craig Topper3e1d5da2013-08-29 05:09:55 +0000111#include "llvm/TableGen/StringToOffsetTable.h"
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000112#include "llvm/TableGen/TableGenBackend.h"
113#include <cassert>
Will Dietz981af002013-10-12 00:55:57 +0000114#include <cctype>
Mehdi Aminib550cb12016-04-18 09:17:29 +0000115#include <forward_list>
Daniel Dunbar71330282009-08-08 05:24:34 +0000116#include <map>
117#include <set>
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000118
Daniel Dunbar3085b572009-07-11 19:39:44 +0000119using namespace llvm;
120
Chandler Carruthe96dd892014-04-21 22:55:11 +0000121#define DEBUG_TYPE "asm-matcher-emitter"
122
Daniel Dunbar15b80372009-08-07 20:33:39 +0000123static cl::opt<std::string>
Daniel Dunbar3239f022009-08-09 04:00:06 +0000124MatchPrefix("match-prefix", cl::init(""),
125 cl::desc("Only match instructions with the given prefix"));
Daniel Dunbare10787e2009-08-07 08:26:05 +0000126
Daniel Dunbare10787e2009-08-07 08:26:05 +0000127namespace {
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000128class AsmMatcherInfo;
Daniel Dunbareefe8612010-07-19 05:44:09 +0000129struct SubtargetFeatureInfo;
130
Tim Northoverc74e6912013-09-16 16:43:19 +0000131// Register sets are used as keys in some second-order sets TableGen creates
132// when generating its data structures. This means that the order of two
133// RegisterSets can be seen in the outputted AsmMatcher tables occasionally, and
134// can even affect compiler output (at least seen in diagnostics produced when
135// all matches fail). So we use a type that sorts them consistently.
136typedef std::set<Record*, LessRecordByID> RegisterSet;
137
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000138class AsmMatcherEmitter {
139 RecordKeeper &Records;
140public:
141 AsmMatcherEmitter(RecordKeeper &R) : Records(R) {}
142
143 void run(raw_ostream &o);
144};
145
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000146/// ClassInfo - Helper class for storing the information about a particular
147/// class of operands which can be matched.
148struct ClassInfo {
Daniel Dunbar3239f022009-08-09 04:00:06 +0000149 enum ClassInfoKind {
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000150 /// Invalid kind, for use as a sentinel value.
151 Invalid = 0,
152
153 /// The class for a particular token.
154 Token,
155
156 /// The (first) register class, subsequent register classes are
157 /// RegisterClass0+1, and so on.
158 RegisterClass0,
159
160 /// The (first) user defined class, subsequent user defined classes are
161 /// UserClass0+1, and so on.
162 UserClass0 = 1<<16
Daniel Dunbar3239f022009-08-09 04:00:06 +0000163 };
164
165 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
166 /// N) for the Nth user defined class.
167 unsigned Kind;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000168
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000169 /// SuperClasses - The super classes of this class. Note that for simplicities
170 /// sake user operands only record their immediate super class, while register
171 /// operands include all superclasses.
172 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000173
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000174 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000175 std::string Name;
176
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000177 /// ClassName - The unadorned generic name for this class (e.g., Token).
178 std::string ClassName;
179
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000180 /// ValueName - The name of the value this class represents; for a token this
181 /// is the literal token string, for an operand it is the TableGen class (or
182 /// empty if this is a derived class).
183 std::string ValueName;
184
185 /// PredicateMethod - The name of the operand method to test whether the
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000186 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000187 std::string PredicateMethod;
188
189 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000190 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000191 std::string RenderMethod;
Daniel Dunbar3239f022009-08-09 04:00:06 +0000192
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000193 /// ParserMethod - The name of the operand method to do a target specific
194 /// parsing on the operand.
195 std::string ParserMethod;
196
Eric Christopher650c8f22014-05-20 17:11:11 +0000197 /// For register classes: the records for all the registers in this class.
Tim Northoverc74e6912013-09-16 16:43:19 +0000198 RegisterSet Registers;
Daniel Dunbar34c87912009-08-11 20:10:07 +0000199
Eric Christopher650c8f22014-05-20 17:11:11 +0000200 /// For custom match classes: the diagnostic kind for when the predicate fails.
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +0000201 std::string DiagnosticType;
Tom Stellardb9f235e2016-02-05 19:59:33 +0000202
203 /// Is this operand optional and not always required.
204 bool IsOptional;
205
Sam Kolton5f10a132016-05-06 11:31:17 +0000206 /// DefaultMethod - The name of the method that returns the default operand
207 /// for optional operand
208 std::string DefaultMethod;
209
Daniel Dunbar34c87912009-08-11 20:10:07 +0000210public:
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000211 /// isRegisterClass() - Check if this is a register class.
212 bool isRegisterClass() const {
213 return Kind >= RegisterClass0 && Kind < UserClass0;
214 }
215
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000216 /// isUserClass() - Check if this is a user defined class.
217 bool isUserClass() const {
218 return Kind >= UserClass0;
219 }
220
Dmitri Gribenko8d302402012-09-15 20:22:05 +0000221 /// isRelatedTo - Check whether this class is "related" to \p RHS. Classes
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000222 /// are related if they are in the same class hierarchy.
223 bool isRelatedTo(const ClassInfo &RHS) const {
224 // Tokens are only related to tokens.
225 if (Kind == Token || RHS.Kind == Token)
226 return Kind == Token && RHS.Kind == Token;
227
Daniel Dunbar34c87912009-08-11 20:10:07 +0000228 // Registers classes are only related to registers classes, and only if
229 // their intersection is non-empty.
230 if (isRegisterClass() || RHS.isRegisterClass()) {
231 if (!isRegisterClass() || !RHS.isRegisterClass())
232 return false;
233
Tim Northoverc74e6912013-09-16 16:43:19 +0000234 RegisterSet Tmp;
235 std::insert_iterator<RegisterSet> II(Tmp, Tmp.begin());
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000236 std::set_intersection(Registers.begin(), Registers.end(),
Daniel Dunbar34c87912009-08-11 20:10:07 +0000237 RHS.Registers.begin(), RHS.Registers.end(),
Tim Northoverc74e6912013-09-16 16:43:19 +0000238 II, LessRecordByID());
Daniel Dunbar34c87912009-08-11 20:10:07 +0000239
240 return !Tmp.empty();
241 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000242
243 // Otherwise we have two users operands; they are related if they are in the
244 // same class hierarchy.
Daniel Dunbar34c87912009-08-11 20:10:07 +0000245 //
246 // FIXME: This is an oversimplification, they should only be related if they
247 // intersect, however we don't have that information.
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000248 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
249 const ClassInfo *Root = this;
250 while (!Root->SuperClasses.empty())
251 Root = Root->SuperClasses.front();
252
Daniel Dunbar34c87912009-08-11 20:10:07 +0000253 const ClassInfo *RHSRoot = &RHS;
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000254 while (!RHSRoot->SuperClasses.empty())
255 RHSRoot = RHSRoot->SuperClasses.front();
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000256
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000257 return Root == RHSRoot;
258 }
259
Dmitri Gribenko8d302402012-09-15 20:22:05 +0000260 /// isSubsetOf - Test whether this class is a subset of \p RHS.
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000261 bool isSubsetOf(const ClassInfo &RHS) const {
262 // This is a subset of RHS if it is the same class...
263 if (this == &RHS)
264 return true;
265
266 // ... or if any of its super classes are a subset of RHS.
Craig Topper03ec8012014-11-25 20:11:31 +0000267 for (const ClassInfo *CI : SuperClasses)
268 if (CI->isSubsetOf(RHS))
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000269 return true;
270
271 return false;
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000272 }
273
Oliver Stannard7772f022016-01-25 10:20:19 +0000274 int getTreeDepth() const {
275 int Depth = 0;
276 const ClassInfo *Root = this;
277 while (!Root->SuperClasses.empty()) {
278 Depth++;
279 Root = Root->SuperClasses.front();
280 }
281 return Depth;
282 }
283
284 const ClassInfo *findRoot() const {
285 const ClassInfo *Root = this;
286 while (!Root->SuperClasses.empty())
287 Root = Root->SuperClasses.front();
288 return Root;
289 }
290
291 /// Compare two classes. This does not produce a total ordering, but does
292 /// guarantee that subclasses are sorted before their parents, and that the
293 /// ordering is transitive.
Daniel Dunbar3239f022009-08-09 04:00:06 +0000294 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar97ac3af2010-05-27 05:31:32 +0000295 if (this == &RHS)
296 return false;
297
Oliver Stannard7772f022016-01-25 10:20:19 +0000298 // First, enforce the ordering between the three different types of class.
299 // Tokens sort before registers, which sort before user classes.
300 if (Kind == Token) {
301 if (RHS.Kind != Token)
Duncan Sands41b4a6b2010-07-12 08:16:59 +0000302 return true;
Oliver Stannard7772f022016-01-25 10:20:19 +0000303 assert(RHS.Kind == Token);
304 } else if (isRegisterClass()) {
305 if (RHS.Kind == Token)
Duncan Sands41b4a6b2010-07-12 08:16:59 +0000306 return false;
Oliver Stannard7772f022016-01-25 10:20:19 +0000307 else if (RHS.isUserClass())
308 return true;
309 assert(RHS.isRegisterClass());
310 } else if (isUserClass()) {
311 if (!RHS.isUserClass())
312 return false;
313 assert(RHS.isUserClass());
314 } else {
315 llvm_unreachable("Unknown ClassInfoKind");
Daniel Dunbar3239f022009-08-09 04:00:06 +0000316 }
Oliver Stannard7772f022016-01-25 10:20:19 +0000317
318 if (Kind == Token || isUserClass()) {
319 // Related tokens and user classes get sorted by depth in the inheritence
320 // tree (so that subclasses are before their parents).
321 if (isRelatedTo(RHS)) {
322 if (getTreeDepth() > RHS.getTreeDepth())
323 return true;
324 if (getTreeDepth() < RHS.getTreeDepth())
325 return false;
326 } else {
327 // Unrelated tokens and user classes are ordered by the name of their
328 // root nodes, so that there is a consistent ordering between
329 // unconnected trees.
330 return findRoot()->ValueName < RHS.findRoot()->ValueName;
331 }
332 } else if (isRegisterClass()) {
333 // For register sets, sort by number of registers. This guarantees that
334 // a set will always sort before all of it's strict supersets.
335 if (Registers.size() != RHS.Registers.size())
336 return Registers.size() < RHS.Registers.size();
337 } else {
338 llvm_unreachable("Unknown ClassInfoKind");
339 }
340
341 // FIXME: We should be able to just return false here, as we only need a
342 // partial order (we use stable sorts, so this is deterministic) and the
343 // name of a class shouldn't be significant. However, some of the backends
344 // accidentally rely on this behaviour, so it will have to stay like this
345 // until they are fixed.
346 return ValueName < RHS.ValueName;
Daniel Dunbar3239f022009-08-09 04:00:06 +0000347 }
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000348};
349
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000350class AsmVariantInfo {
351public:
Craig Topperc8b5b252015-12-30 06:00:18 +0000352 std::string RegisterPrefix;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000353 std::string TokenizingCharacters;
354 std::string SeparatorCharacters;
355 std::string BreakCharacters;
Craig Topperc8b5b252015-12-30 06:00:18 +0000356 int AsmVariantNo;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000357};
358
Chris Lattnerad776812010-11-01 05:06:45 +0000359/// MatchableInfo - Helper class for storing the necessary information for an
360/// instruction or alias which is capable of being matched.
361struct MatchableInfo {
Chris Lattner896cf042010-11-03 19:47:34 +0000362 struct AsmOperand {
Chris Lattner28ea9b12010-11-02 17:30:52 +0000363 /// Token - This is the token that the operand came from.
364 StringRef Token;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000365
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000366 /// The unique class instance this operand should match.
367 ClassInfo *Class;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000368
Chris Lattner7108dad2010-11-04 01:42:59 +0000369 /// The operand name this is, if anything.
370 StringRef SrcOpName;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000371
372 /// The suboperand index within SrcOpName, or -1 for the entire operand.
373 int SubOpIdx;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000374
Ahmed Bougachaeb4dbd82015-05-29 01:03:37 +0000375 /// Whether the token is "isolated", i.e., it is preceded and followed
376 /// by separators.
377 bool IsIsolatedToken;
378
Devang Patel6d676e42012-01-07 01:33:34 +0000379 /// Register record if this token is singleton register.
380 Record *SingletonReg;
381
Ahmed Bougachaeb4dbd82015-05-29 01:03:37 +0000382 explicit AsmOperand(bool IsIsolatedToken, StringRef T)
383 : Token(T), Class(nullptr), SubOpIdx(-1),
384 IsIsolatedToken(IsIsolatedToken), SingletonReg(nullptr) {}
Daniel Dunbare10787e2009-08-07 08:26:05 +0000385 };
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000386
Chris Lattner743081d2010-11-04 00:43:46 +0000387 /// ResOperand - This represents a single operand in the result instruction
388 /// generated by the match. In cases (like addressing modes) where a single
389 /// assembler operand expands to multiple MCOperands, this represents the
390 /// single assembler operand, not the MCOperand.
391 struct ResOperand {
392 enum {
393 /// RenderAsmOperand - This represents an operand result that is
394 /// generated by calling the render method on the assembly operand. The
395 /// corresponding AsmOperand is specified by AsmOperandNum.
396 RenderAsmOperand,
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000397
Chris Lattner743081d2010-11-04 00:43:46 +0000398 /// TiedOperand - This represents a result operand that is a duplicate of
399 /// a previous result operand.
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000400 TiedOperand,
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000401
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000402 /// ImmOperand - This represents an immediate value that is dumped into
403 /// the operand.
Chris Lattner4869d342010-11-06 19:57:21 +0000404 ImmOperand,
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000405
Chris Lattner4869d342010-11-06 19:57:21 +0000406 /// RegOperand - This represents a fixed register that is dumped in.
407 RegOperand
Chris Lattner743081d2010-11-04 00:43:46 +0000408 } Kind;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000409
Chris Lattner743081d2010-11-04 00:43:46 +0000410 union {
411 /// This is the operand # in the AsmOperands list that this should be
412 /// copied from.
413 unsigned AsmOperandNum;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000414
Chris Lattner743081d2010-11-04 00:43:46 +0000415 /// TiedOperandNum - This is the (earlier) result operand that should be
416 /// copied from.
417 unsigned TiedOperandNum;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000418
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000419 /// ImmVal - This is the immediate value added to the instruction.
420 int64_t ImmVal;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000421
Chris Lattner4869d342010-11-06 19:57:21 +0000422 /// Register - This is the register record.
423 Record *Register;
Chris Lattner743081d2010-11-04 00:43:46 +0000424 };
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000425
Bob Wilsonb9b24222011-01-26 19:44:55 +0000426 /// MINumOperands - The number of MCInst operands populated by this
427 /// operand.
428 unsigned MINumOperands;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000429
Bob Wilsonb9b24222011-01-26 19:44:55 +0000430 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
Chris Lattner743081d2010-11-04 00:43:46 +0000431 ResOperand X;
432 X.Kind = RenderAsmOperand;
433 X.AsmOperandNum = AsmOpNum;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000434 X.MINumOperands = NumOperands;
Chris Lattner743081d2010-11-04 00:43:46 +0000435 return X;
436 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000437
Bob Wilsonb9b24222011-01-26 19:44:55 +0000438 static ResOperand getTiedOp(unsigned TiedOperandNum) {
Chris Lattner743081d2010-11-04 00:43:46 +0000439 ResOperand X;
440 X.Kind = TiedOperand;
441 X.TiedOperandNum = TiedOperandNum;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000442 X.MINumOperands = 1;
Chris Lattner743081d2010-11-04 00:43:46 +0000443 return X;
444 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000445
Bob Wilsonb9b24222011-01-26 19:44:55 +0000446 static ResOperand getImmOp(int64_t Val) {
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000447 ResOperand X;
448 X.Kind = ImmOperand;
449 X.ImmVal = Val;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000450 X.MINumOperands = 1;
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000451 return X;
452 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000453
Bob Wilsonb9b24222011-01-26 19:44:55 +0000454 static ResOperand getRegOp(Record *Reg) {
Chris Lattner4869d342010-11-06 19:57:21 +0000455 ResOperand X;
456 X.Kind = RegOperand;
457 X.Register = Reg;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000458 X.MINumOperands = 1;
Chris Lattner4869d342010-11-06 19:57:21 +0000459 return X;
460 }
Chris Lattner743081d2010-11-04 00:43:46 +0000461 };
Daniel Dunbare10787e2009-08-07 08:26:05 +0000462
Devang Patel9bdc5052012-01-10 17:50:43 +0000463 /// AsmVariantID - Target's assembly syntax variant no.
464 int AsmVariantID;
465
David Blaikieba4e00f2014-12-22 21:26:26 +0000466 /// AsmString - The assembly string for this instruction (with variants
467 /// removed), e.g. "movsx $src, $dst".
468 std::string AsmString;
469
Chris Lattnera7a903e2010-11-02 17:34:28 +0000470 /// TheDef - This is the definition of the instruction or InstAlias that this
471 /// matchable came from.
Chris Lattner39bc53b2010-11-01 04:34:44 +0000472 Record *const TheDef;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000473
Chris Lattner4efe13d2010-11-04 02:11:18 +0000474 /// DefRec - This is the definition that it came from.
475 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000476
Chris Lattnerfecdad62010-11-06 07:14:44 +0000477 const CodeGenInstruction *getResultInst() const {
478 if (DefRec.is<const CodeGenInstruction*>())
479 return DefRec.get<const CodeGenInstruction*>();
480 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
481 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000482
Chris Lattner743081d2010-11-04 00:43:46 +0000483 /// ResOperands - This is the operand list that should be built for the result
484 /// MCInst.
Jim Grosbacha37e2292012-04-19 17:52:34 +0000485 SmallVector<ResOperand, 8> ResOperands;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000486
Chris Lattner28ea9b12010-11-02 17:30:52 +0000487 /// Mnemonic - This is the first token of the matched instruction, its
488 /// mnemonic.
489 StringRef Mnemonic;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000490
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000491 /// AsmOperands - The textual operands that this instruction matches,
Chris Lattnera7a903e2010-11-02 17:34:28 +0000492 /// annotated with a class and where in the OperandList they were defined.
493 /// This directly corresponds to the tokenized AsmString after the mnemonic is
494 /// removed.
Jim Grosbacha37e2292012-04-19 17:52:34 +0000495 SmallVector<AsmOperand, 8> AsmOperands;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000496
Daniel Dunbareefe8612010-07-19 05:44:09 +0000497 /// Predicates - The required subtarget features to match this instruction.
David Blaikie9a9da992014-11-28 22:15:06 +0000498 SmallVector<const SubtargetFeatureInfo *, 4> RequiredFeatures;
Daniel Dunbareefe8612010-07-19 05:44:09 +0000499
Daniel Dunbar71330282009-08-08 05:24:34 +0000500 /// ConversionFnKind - The enum value which is passed to the generated
Chad Rosierba284b92012-09-05 01:02:38 +0000501 /// convertToMCInst to convert parsed operands into an MCInst for this
Daniel Dunbar71330282009-08-08 05:24:34 +0000502 /// function.
503 std::string ConversionFnKind;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000504
Joey Gouly0e76fa72013-09-12 10:28:05 +0000505 /// If this instruction is deprecated in some form.
506 bool HasDeprecation;
507
Tom Stellard74c87c82015-05-26 15:55:50 +0000508 /// If this is an alias, this is use to determine whether or not to using
509 /// the conversion function defined by the instruction's AsmMatchConverter
510 /// or to use the function generated by the alias.
511 bool UseInstAsmMatchConverter;
512
Chris Lattnerad776812010-11-01 05:06:45 +0000513 MatchableInfo(const CodeGenInstruction &CGI)
Tom Stellard74c87c82015-05-26 15:55:50 +0000514 : AsmVariantID(0), AsmString(CGI.AsmString), TheDef(CGI.TheDef), DefRec(&CGI),
515 UseInstAsmMatchConverter(true) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000516 }
Chris Lattner39bc53b2010-11-01 04:34:44 +0000517
David Blaikieba4e00f2014-12-22 21:26:26 +0000518 MatchableInfo(std::unique_ptr<const CodeGenInstAlias> Alias)
Tom Stellard74c87c82015-05-26 15:55:50 +0000519 : AsmVariantID(0), AsmString(Alias->AsmString), TheDef(Alias->TheDef),
520 DefRec(Alias.release()),
521 UseInstAsmMatchConverter(
522 TheDef->getValueAsBit("UseInstAsmMatchConverter")) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000523 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000524
David Blaikie6e48a812015-08-01 01:08:30 +0000525 // Could remove this and the dtor if PointerUnion supported unique_ptr
526 // elements with a dynamic failure/assertion (like the one below) in the case
527 // where it was copied while being in an owning state.
528 MatchableInfo(const MatchableInfo &RHS)
529 : AsmVariantID(RHS.AsmVariantID), AsmString(RHS.AsmString),
530 TheDef(RHS.TheDef), DefRec(RHS.DefRec), ResOperands(RHS.ResOperands),
531 Mnemonic(RHS.Mnemonic), AsmOperands(RHS.AsmOperands),
532 RequiredFeatures(RHS.RequiredFeatures),
533 ConversionFnKind(RHS.ConversionFnKind),
534 HasDeprecation(RHS.HasDeprecation),
535 UseInstAsmMatchConverter(RHS.UseInstAsmMatchConverter) {
536 assert(!DefRec.is<const CodeGenInstAlias *>());
537 }
538
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000539 ~MatchableInfo() {
David Blaikieba4e00f2014-12-22 21:26:26 +0000540 delete DefRec.dyn_cast<const CodeGenInstAlias*>();
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000541 }
Craig Topperce274892014-11-28 05:01:21 +0000542
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000543 // Two-operand aliases clone from the main matchable, but mark the second
544 // operand as a tied operand of the first for purposes of the assembler.
545 void formTwoOperandAlias(StringRef Constraint);
546
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000547 void initialize(const AsmMatcherInfo &Info,
Craig Topper71b7b682014-08-21 05:55:13 +0000548 SmallPtrSetImpl<Record*> &SingletonRegisters,
Craig Topperfd2c6a32015-12-31 08:18:23 +0000549 AsmVariantInfo const &Variant,
550 bool HasMnemonicFirst);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000551
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000552 /// validate - Return true if this matchable is a valid thing to match against
Chris Lattnerad776812010-11-01 05:06:45 +0000553 /// and perform a bunch of validity checking.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000554 bool validate(StringRef CommentDelimiter, bool Hack) const;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000555
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000556 /// findAsmOperand - Find the AsmOperand with the specified name and
Bob Wilsonb9b24222011-01-26 19:44:55 +0000557 /// suboperand index.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000558 int findAsmOperand(StringRef N, int SubOpIdx) const {
David Majnemer562e8292016-08-12 00:18:03 +0000559 auto I = find_if(AsmOperands, [&](const AsmOperand &Op) {
560 return Op.SrcOpName == N && Op.SubOpIdx == SubOpIdx;
561 });
Craig Topper58a0e7a2016-01-03 07:33:36 +0000562 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000563 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000564
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000565 /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
Bob Wilsonb9b24222011-01-26 19:44:55 +0000566 /// This does not check the suboperand index.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000567 int findAsmOperandNamed(StringRef N) const {
David Majnemer562e8292016-08-12 00:18:03 +0000568 auto I = find_if(AsmOperands,
569 [&](const AsmOperand &Op) { return Op.SrcOpName == N; });
Craig Topper58a0e7a2016-01-03 07:33:36 +0000570 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
Chris Lattner897a1402010-11-04 01:55:23 +0000571 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000572
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000573 void buildInstructionResultOperands();
574 void buildAliasResultOperands();
Chris Lattner743081d2010-11-04 00:43:46 +0000575
Chris Lattnerad776812010-11-01 05:06:45 +0000576 /// operator< - Compare two matchables.
577 bool operator<(const MatchableInfo &RHS) const {
Chris Lattner82d88ce2010-09-06 21:01:37 +0000578 // The primary comparator is the instruction mnemonic.
Ahmed Bougachaef3358d2016-06-23 17:09:49 +0000579 if (int Cmp = Mnemonic.compare(RHS.Mnemonic))
580 return Cmp == -1;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000581
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000582 if (AsmOperands.size() != RHS.AsmOperands.size())
583 return AsmOperands.size() < RHS.AsmOperands.size();
Daniel Dunbar3239f022009-08-09 04:00:06 +0000584
Daniel Dunbard9631912009-08-09 08:23:23 +0000585 // Compare lexicographically by operand. The matcher validates that other
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000586 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000587 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
588 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbar3239f022009-08-09 04:00:06 +0000589 return true;
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000590 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbard9631912009-08-09 08:23:23 +0000591 return false;
592 }
593
Andrew Trick818f5ac2012-08-29 03:52:57 +0000594 // Give matches that require more features higher precedence. This is useful
595 // because we cannot define AssemblerPredicates with the negation of
596 // processor features. For example, ARM v6 "nop" may be either a HINT or
597 // MOV. With v6, we want to match HINT. The assembler has no way to
598 // predicate MOV under "NoV6", but HINT will always match first because it
599 // requires V6 while MOV does not.
600 if (RequiredFeatures.size() != RHS.RequiredFeatures.size())
601 return RequiredFeatures.size() > RHS.RequiredFeatures.size();
602
Daniel Dunbar3239f022009-08-09 04:00:06 +0000603 return false;
604 }
605
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000606 /// couldMatchAmbiguouslyWith - Check whether this matchable could
Dmitri Gribenko8d302402012-09-15 20:22:05 +0000607 /// ambiguously match the same set of operands as \p RHS (without being a
Daniel Dunbarf573b562009-08-09 06:05:33 +0000608 /// strictly superior match).
Craig Topper42bd8192014-11-28 03:53:00 +0000609 bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) const {
Chris Lattnere3c48de2010-11-01 23:57:23 +0000610 // The primary comparator is the instruction mnemonic.
Chris Lattner28ea9b12010-11-02 17:30:52 +0000611 if (Mnemonic != RHS.Mnemonic)
Chris Lattnere3c48de2010-11-01 23:57:23 +0000612 return false;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000613
Daniel Dunbarf573b562009-08-09 06:05:33 +0000614 // The number of operands is unambiguous.
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000615 if (AsmOperands.size() != RHS.AsmOperands.size())
Daniel Dunbarf573b562009-08-09 06:05:33 +0000616 return false;
617
Daniel Dunbare1974092010-01-23 00:26:16 +0000618 // Otherwise, make sure the ordering of the two instructions is unambiguous
619 // by checking that either (a) a token or operand kind discriminates them,
620 // or (b) the ordering among equivalent kinds is consistent.
621
Daniel Dunbarf573b562009-08-09 06:05:33 +0000622 // Tokens and operand kinds are unambiguous (assuming a correct target
623 // specific parser).
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000624 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
625 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
626 AsmOperands[i].Class->Kind == ClassInfo::Token)
627 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
628 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbarf573b562009-08-09 06:05:33 +0000629 return false;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000630
Daniel Dunbarf573b562009-08-09 06:05:33 +0000631 // Otherwise, this operand could commute if all operands are equivalent, or
632 // there is a pair of operands that compare less than and a pair that
633 // compare greater than.
634 bool HasLT = false, HasGT = false;
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000635 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
636 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbarf573b562009-08-09 06:05:33 +0000637 HasLT = true;
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000638 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbarf573b562009-08-09 06:05:33 +0000639 HasGT = true;
640 }
641
Craig Topper322b67f2016-01-03 07:33:39 +0000642 return HasLT == HasGT;
Daniel Dunbarf573b562009-08-09 06:05:33 +0000643 }
644
Craig Topper42bd8192014-11-28 03:53:00 +0000645 void dump() const;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000646
Chris Lattner28ea9b12010-11-02 17:30:52 +0000647private:
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000648 void tokenizeAsmString(AsmMatcherInfo const &Info,
649 AsmVariantInfo const &Variant);
Craig Topperbc22e262015-12-31 05:01:45 +0000650 void addAsmOperand(StringRef Token, bool IsIsolatedToken = false);
Daniel Dunbare10787e2009-08-07 08:26:05 +0000651};
652
Daniel Dunbareefe8612010-07-19 05:44:09 +0000653/// SubtargetFeatureInfo - Helper class for storing information on a subtarget
654/// feature which participates in instruction matching.
655struct SubtargetFeatureInfo {
656 /// \brief The predicate record for this feature.
657 Record *TheDef;
658
659 /// \brief An unique index assigned to represent this feature.
Tim Northover26bb14e2014-08-18 11:49:42 +0000660 uint64_t Index;
Daniel Dunbareefe8612010-07-19 05:44:09 +0000661
Tim Northover26bb14e2014-08-18 11:49:42 +0000662 SubtargetFeatureInfo(Record *D, uint64_t Idx) : TheDef(D), Index(Idx) {}
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000663
Daniel Dunbareefe8612010-07-19 05:44:09 +0000664 /// \brief The name of the enumerated constant identifying this feature.
Chris Lattnera0e87192010-10-30 20:07:57 +0000665 std::string getEnumName() const {
666 return "Feature_" + TheDef->getName();
667 }
Daniel Sanders3ea92742014-05-21 10:11:24 +0000668
Craig Topper42bd8192014-11-28 03:53:00 +0000669 void dump() const {
Daniel Sanders3ea92742014-05-21 10:11:24 +0000670 errs() << getEnumName() << " " << Index << "\n";
671 TheDef->dump();
672 }
Daniel Dunbareefe8612010-07-19 05:44:09 +0000673};
674
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000675struct OperandMatchEntry {
676 unsigned OperandMask;
Craig Topper42bd8192014-11-28 03:53:00 +0000677 const MatchableInfo* MI;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000678 ClassInfo *CI;
679
Craig Topper42bd8192014-11-28 03:53:00 +0000680 static OperandMatchEntry create(const MatchableInfo *mi, ClassInfo *ci,
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000681 unsigned opMask) {
682 OperandMatchEntry X;
683 X.OperandMask = opMask;
684 X.CI = ci;
685 X.MI = mi;
686 return X;
687 }
688};
689
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000690class AsmMatcherInfo {
691public:
Chris Lattner77d369c2010-12-13 00:23:57 +0000692 /// Tracked Records
Chris Lattner89dcb682010-12-15 04:48:22 +0000693 RecordKeeper &Records;
Chris Lattner77d369c2010-12-13 00:23:57 +0000694
Daniel Dunbare4318712009-08-11 20:59:47 +0000695 /// The tablegen AsmParser record.
696 Record *AsmParser;
697
Chris Lattnerb80ab362010-11-01 01:37:30 +0000698 /// Target - The target information.
699 CodeGenTarget &Target;
700
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000701 /// The classes which are needed for matching.
David Blaikied749e342014-11-28 20:35:57 +0000702 std::forward_list<ClassInfo> Classes;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000703
Chris Lattnerad776812010-11-01 05:06:45 +0000704 /// The information on the matchables to match.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000705 std::vector<std::unique_ptr<MatchableInfo>> Matchables;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000706
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000707 /// Info for custom matching operands by user defined methods.
708 std::vector<OperandMatchEntry> OperandMatchInfo;
709
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000710 /// Map of Register records to their class information.
Sean Silvac8f56572012-09-19 01:47:01 +0000711 typedef std::map<Record*, ClassInfo*, LessRecordByID> RegisterClassesTy;
712 RegisterClassesTy RegisterClasses;
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000713
Daniel Dunbareefe8612010-07-19 05:44:09 +0000714 /// Map of Predicate records to their subtarget information.
David Blaikie9a9da992014-11-28 22:15:06 +0000715 std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000716
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +0000717 /// Map of AsmOperandClass records to their class information.
718 std::map<Record*, ClassInfo*> AsmOperandClasses;
719
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000720private:
721 /// Map of token to class information which has already been constructed.
722 std::map<std::string, ClassInfo*> TokenClasses;
723
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000724 /// Map of RegisterClass records to their class information.
725 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000726
727private:
728 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattner60db0a62010-02-09 00:34:28 +0000729 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000730
731 /// getOperandClass - Lookup or create the class for the given operand.
Bob Wilsonb9b24222011-01-26 19:44:55 +0000732 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
Jim Grosbachd1f1b792011-10-28 22:32:53 +0000733 int SubOpIdx);
734 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000735
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000736 /// buildRegisterClasses - Build the ClassInfo* instances for register
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000737 /// classes.
Craig Topper71b7b682014-08-21 05:55:13 +0000738 void buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters);
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000739
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000740 /// buildOperandClasses - Build the ClassInfo* instances for user defined
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000741 /// operand classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000742 void buildOperandClasses();
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000743
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000744 void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
Bob Wilsonb9b24222011-01-26 19:44:55 +0000745 unsigned AsmOpIdx);
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000746 void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
Chris Lattner4efe13d2010-11-04 02:11:18 +0000747 MatchableInfo::AsmOperand &Op);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000748
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000749public:
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000750 AsmMatcherInfo(Record *AsmParser,
751 CodeGenTarget &Target,
Chris Lattner89dcb682010-12-15 04:48:22 +0000752 RecordKeeper &Records);
Daniel Dunbare4318712009-08-11 20:59:47 +0000753
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000754 /// buildInfo - Construct the various tables used during matching.
755 void buildInfo();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000756
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000757 /// buildOperandMatchInfo - Build the necessary information to handle user
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000758 /// defined operand parsing methods.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000759 void buildOperandMatchInfo();
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000760
Chris Lattner43690072010-10-30 20:15:02 +0000761 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
762 /// given operand.
David Blaikie9a9da992014-11-28 22:15:06 +0000763 const SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
Chris Lattner43690072010-10-30 20:15:02 +0000764 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
Craig Topper42bd8192014-11-28 03:53:00 +0000765 const auto &I = SubtargetFeatures.find(Def);
David Blaikie9a9da992014-11-28 22:15:06 +0000766 return I == SubtargetFeatures.end() ? nullptr : &I->second;
Chris Lattner43690072010-10-30 20:15:02 +0000767 }
Chris Lattner77d369c2010-12-13 00:23:57 +0000768
Chris Lattner89dcb682010-12-15 04:48:22 +0000769 RecordKeeper &getRecords() const {
770 return Records;
Chris Lattner77d369c2010-12-13 00:23:57 +0000771 }
Sam Kolton5f10a132016-05-06 11:31:17 +0000772
773 bool hasOptionalOperands() const {
David Majnemer562e8292016-08-12 00:18:03 +0000774 return find_if(Classes, [](const ClassInfo &Class) {
775 return Class.IsOptional;
776 }) != Classes.end();
Sam Kolton5f10a132016-05-06 11:31:17 +0000777 }
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000778};
779
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000780} // end anonymous namespace
Daniel Dunbare10787e2009-08-07 08:26:05 +0000781
Craig Topper42bd8192014-11-28 03:53:00 +0000782void MatchableInfo::dump() const {
Chris Lattner9f093812010-11-06 06:43:11 +0000783 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +0000784
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000785 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
Craig Topper42bd8192014-11-28 03:53:00 +0000786 const AsmOperand &Op = AsmOperands[i];
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000787 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Chris Lattner4779e3e92010-11-04 00:57:06 +0000788 errs() << '\"' << Op.Token << "\"\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +0000789 }
790}
791
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000792static std::pair<StringRef, StringRef>
Jakob Stoklund Olesend7b66962012-08-22 23:33:58 +0000793parseTwoOperandConstraint(StringRef S, ArrayRef<SMLoc> Loc) {
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000794 // Split via the '='.
795 std::pair<StringRef, StringRef> Ops = S.split('=');
796 if (Ops.second == "")
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000797 PrintFatalError(Loc, "missing '=' in two-operand alias constraint");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000798 // Trim whitespace and the leading '$' on the operand names.
799 size_t start = Ops.first.find_first_of('$');
800 if (start == std::string::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000801 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000802 Ops.first = Ops.first.slice(start + 1, std::string::npos);
803 size_t end = Ops.first.find_last_of(" \t");
804 Ops.first = Ops.first.slice(0, end);
805 // Now the second operand.
806 start = Ops.second.find_first_of('$');
807 if (start == std::string::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000808 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000809 Ops.second = Ops.second.slice(start + 1, std::string::npos);
810 end = Ops.second.find_last_of(" \t");
811 Ops.first = Ops.first.slice(0, end);
812 return Ops;
813}
814
815void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
816 // Figure out which operands are aliased and mark them as tied.
817 std::pair<StringRef, StringRef> Ops =
818 parseTwoOperandConstraint(Constraint, TheDef->getLoc());
819
820 // Find the AsmOperands that refer to the operands we're aliasing.
821 int SrcAsmOperand = findAsmOperandNamed(Ops.first);
822 int DstAsmOperand = findAsmOperandNamed(Ops.second);
823 if (SrcAsmOperand == -1)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000824 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +0000825 "unknown source two-operand alias operand '" + Ops.first +
826 "'.");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000827 if (DstAsmOperand == -1)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000828 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +0000829 "unknown destination two-operand alias operand '" +
830 Ops.second + "'.");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000831
832 // Find the ResOperand that refers to the operand we're aliasing away
833 // and update it to refer to the combined operand instead.
Craig Toppere4e74152015-12-29 07:03:23 +0000834 for (ResOperand &Op : ResOperands) {
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000835 if (Op.Kind == ResOperand::RenderAsmOperand &&
836 Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
837 Op.AsmOperandNum = DstAsmOperand;
838 break;
839 }
840 }
841 // Remove the AsmOperand for the alias operand.
842 AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
843 // Adjust the ResOperand references to any AsmOperands that followed
844 // the one we just deleted.
Craig Toppere4e74152015-12-29 07:03:23 +0000845 for (ResOperand &Op : ResOperands) {
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000846 switch(Op.Kind) {
847 default:
848 // Nothing to do for operands that don't reference AsmOperands.
849 break;
850 case ResOperand::RenderAsmOperand:
851 if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
852 --Op.AsmOperandNum;
853 break;
854 case ResOperand::TiedOperand:
855 if (Op.TiedOperandNum > (unsigned)SrcAsmOperand)
856 --Op.TiedOperandNum;
857 break;
858 }
859 }
860}
861
Craig Topper22fa45f2015-09-13 18:01:25 +0000862/// extractSingletonRegisterForAsmOperand - Extract singleton register,
863/// if present, from specified token.
864static void
865extractSingletonRegisterForAsmOperand(MatchableInfo::AsmOperand &Op,
866 const AsmMatcherInfo &Info,
867 StringRef RegisterPrefix) {
868 StringRef Tok = Op.Token;
869
870 // If this token is not an isolated token, i.e., it isn't separated from
871 // other tokens (e.g. with whitespace), don't interpret it as a register name.
872 if (!Op.IsIsolatedToken)
873 return;
874
875 if (RegisterPrefix.empty()) {
876 std::string LoweredTok = Tok.lower();
877 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
878 Op.SingletonReg = Reg->TheDef;
879 return;
880 }
881
882 if (!Tok.startswith(RegisterPrefix))
883 return;
884
885 StringRef RegName = Tok.substr(RegisterPrefix.size());
886 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
887 Op.SingletonReg = Reg->TheDef;
888
889 // If there is no register prefix (i.e. "%" in "%eax"), then this may
890 // be some random non-register token, just ignore it.
Craig Topper22fa45f2015-09-13 18:01:25 +0000891}
892
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000893void MatchableInfo::initialize(const AsmMatcherInfo &Info,
Craig Topper71b7b682014-08-21 05:55:13 +0000894 SmallPtrSetImpl<Record*> &SingletonRegisters,
Craig Topperfd2c6a32015-12-31 08:18:23 +0000895 AsmVariantInfo const &Variant,
896 bool HasMnemonicFirst) {
Craig Topperc8b5b252015-12-30 06:00:18 +0000897 AsmVariantID = Variant.AsmVariantNo;
Jim Grosbach0bba00d2012-01-24 21:06:59 +0000898 AsmString =
Craig Topperc8b5b252015-12-30 06:00:18 +0000899 CodeGenInstruction::FlattenAsmStringVariants(AsmString,
900 Variant.AsmVariantNo);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000901
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000902 tokenizeAsmString(Info, Variant);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000903
Craig Topperfd2c6a32015-12-31 08:18:23 +0000904 // The first token of the instruction is the mnemonic, which must be a
905 // simple string, not a $foo variable or a singleton register.
906 if (AsmOperands.empty())
907 PrintFatalError(TheDef->getLoc(),
908 "Instruction '" + TheDef->getName() + "' has no tokens");
909
910 assert(!AsmOperands[0].Token.empty());
911 if (HasMnemonicFirst) {
912 Mnemonic = AsmOperands[0].Token;
913 if (Mnemonic[0] == '$')
914 PrintFatalError(TheDef->getLoc(),
915 "Invalid instruction mnemonic '" + Mnemonic + "'!");
916
917 // Remove the first operand, it is tracked in the mnemonic field.
918 AsmOperands.erase(AsmOperands.begin());
919 } else if (AsmOperands[0].Token[0] != '$')
920 Mnemonic = AsmOperands[0].Token;
921
Chris Lattnerba465f92010-11-01 04:53:48 +0000922 // Compute the require features.
Craig Topper22fa45f2015-09-13 18:01:25 +0000923 for (Record *Predicate : TheDef->getValueAsListOfDefs("Predicates"))
David Blaikie9a9da992014-11-28 22:15:06 +0000924 if (const SubtargetFeatureInfo *Feature =
Craig Topper22fa45f2015-09-13 18:01:25 +0000925 Info.getSubtargetFeature(Predicate))
Chris Lattnerba465f92010-11-01 04:53:48 +0000926 RequiredFeatures.push_back(Feature);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000927
Chris Lattnerba465f92010-11-01 04:53:48 +0000928 // Collect singleton registers, if used.
Craig Topper22fa45f2015-09-13 18:01:25 +0000929 for (MatchableInfo::AsmOperand &Op : AsmOperands) {
Craig Topperc8b5b252015-12-30 06:00:18 +0000930 extractSingletonRegisterForAsmOperand(Op, Info, Variant.RegisterPrefix);
Craig Topper22fa45f2015-09-13 18:01:25 +0000931 if (Record *Reg = Op.SingletonReg)
Chris Lattnerba465f92010-11-01 04:53:48 +0000932 SingletonRegisters.insert(Reg);
933 }
Joey Gouly0e76fa72013-09-12 10:28:05 +0000934
935 const RecordVal *DepMask = TheDef->getValue("DeprecatedFeatureMask");
936 if (!DepMask)
937 DepMask = TheDef->getValue("ComplexDeprecationPredicate");
938
939 HasDeprecation =
940 DepMask ? !DepMask->getValue()->getAsUnquotedString().empty() : false;
Chris Lattnerba465f92010-11-01 04:53:48 +0000941}
942
Ahmed Bougachad8dc2ac2015-05-29 00:55:55 +0000943/// Append an AsmOperand for the given substring of AsmString.
Craig Topperbc22e262015-12-31 05:01:45 +0000944void MatchableInfo::addAsmOperand(StringRef Token, bool IsIsolatedToken) {
945 AsmOperands.push_back(AsmOperand(IsIsolatedToken, Token));
Ahmed Bougachad8dc2ac2015-05-29 00:55:55 +0000946}
947
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000948/// tokenizeAsmString - Tokenize a simplified assembly string.
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000949void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info,
950 AsmVariantInfo const &Variant) {
Chris Lattner28ea9b12010-11-02 17:30:52 +0000951 StringRef String = AsmString;
Craig Topperba614322015-12-30 06:00:15 +0000952 size_t Prev = 0;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000953 bool InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +0000954 bool IsIsolatedToken = true;
Craig Topperba614322015-12-30 06:00:15 +0000955 for (size_t i = 0, e = String.size(); i != e; ++i) {
Craig Topperbc22e262015-12-31 05:01:45 +0000956 char Char = String[i];
957 if (Variant.BreakCharacters.find(Char) != std::string::npos) {
958 if (InTok) {
959 addAsmOperand(String.slice(Prev, i), false);
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000960 Prev = i;
Craig Topperbc22e262015-12-31 05:01:45 +0000961 IsIsolatedToken = false;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000962 }
963 InTok = true;
964 continue;
965 }
Craig Topperbc22e262015-12-31 05:01:45 +0000966 if (Variant.TokenizingCharacters.find(Char) != std::string::npos) {
967 if (InTok) {
968 addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000969 InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +0000970 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +0000971 }
Craig Topperbc22e262015-12-31 05:01:45 +0000972 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000973 Prev = i + 1;
Craig Topperbc22e262015-12-31 05:01:45 +0000974 IsIsolatedToken = true;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000975 continue;
976 }
Craig Topperbc22e262015-12-31 05:01:45 +0000977 if (Variant.SeparatorCharacters.find(Char) != std::string::npos) {
978 if (InTok) {
979 addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000980 InTok = false;
981 }
982 Prev = i + 1;
Craig Topperbc22e262015-12-31 05:01:45 +0000983 IsIsolatedToken = true;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000984 continue;
985 }
Craig Topperbc22e262015-12-31 05:01:45 +0000986
987 switch (Char) {
Chris Lattner28ea9b12010-11-02 17:30:52 +0000988 case '\\':
989 if (InTok) {
Craig Topperbc22e262015-12-31 05:01:45 +0000990 addAsmOperand(String.slice(Prev, i), false);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000991 InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +0000992 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +0000993 }
994 ++i;
995 assert(i != String.size() && "Invalid quoted character");
Craig Topperbc22e262015-12-31 05:01:45 +0000996 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000997 Prev = i + 1;
Craig Topperbc22e262015-12-31 05:01:45 +0000998 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +0000999 break;
1000
1001 case '$': {
Craig Topperbc22e262015-12-31 05:01:45 +00001002 if (InTok) {
1003 addAsmOperand(String.slice(Prev, i), false);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001004 InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +00001005 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001006 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001007
Colin LeMahieu3d905742015-08-10 19:58:06 +00001008 // If this isn't "${", start new identifier looking like "$xxx"
Chris Lattnerd6746d52010-11-06 22:06:03 +00001009 if (i + 1 == String.size() || String[i + 1] != '{') {
1010 Prev = i;
1011 break;
1012 }
Chris Lattner28ea9b12010-11-02 17:30:52 +00001013
Craig Topperba614322015-12-30 06:00:15 +00001014 size_t EndPos = String.find('}', i);
1015 assert(EndPos != StringRef::npos &&
1016 "Missing brace in operand reference!");
Craig Topperbc22e262015-12-31 05:01:45 +00001017 addAsmOperand(String.slice(i, EndPos+1), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001018 Prev = EndPos + 1;
1019 i = EndPos;
Craig Topperbc22e262015-12-31 05:01:45 +00001020 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001021 break;
1022 }
Craig Topperbc22e262015-12-31 05:01:45 +00001023
Chris Lattner28ea9b12010-11-02 17:30:52 +00001024 default:
1025 InTok = true;
Craig Topperbc22e262015-12-31 05:01:45 +00001026 break;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001027 }
1028 }
1029 if (InTok && Prev != String.size())
Craig Topperbc22e262015-12-31 05:01:45 +00001030 addAsmOperand(String.substr(Prev), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001031}
1032
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001033bool MatchableInfo::validate(StringRef CommentDelimiter, bool Hack) const {
Chris Lattnerad776812010-11-01 05:06:45 +00001034 // Reject matchables with no .s string.
Chris Lattner39bc53b2010-11-01 04:34:44 +00001035 if (AsmString.empty())
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001036 PrintFatalError(TheDef->getLoc(), "instruction with empty asm string");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001037
Chris Lattnerad776812010-11-01 05:06:45 +00001038 // Reject any matchables with a newline in them, they should be marked
Chris Lattner39bc53b2010-11-01 04:34:44 +00001039 // isCodeGenOnly if they are pseudo instructions.
1040 if (AsmString.find('\n') != std::string::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001041 PrintFatalError(TheDef->getLoc(),
Chris Lattner39bc53b2010-11-01 04:34:44 +00001042 "multiline instruction is not valid for the asmparser, "
1043 "mark it isCodeGenOnly");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001044
Chris Lattner178f4bb2010-11-01 04:44:29 +00001045 // Remove comments from the asm string. We know that the asmstring only
1046 // has one line.
1047 if (!CommentDelimiter.empty() &&
1048 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001049 PrintFatalError(TheDef->getLoc(),
Chris Lattner178f4bb2010-11-01 04:44:29 +00001050 "asmstring for instruction has comment character in it, "
1051 "mark it isCodeGenOnly");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001052
Chris Lattnerad776812010-11-01 05:06:45 +00001053 // Reject matchables with operand modifiers, these aren't something we can
Bob Wilson266d2ba2011-01-20 18:38:07 +00001054 // handle, the target should be refactored to use operands instead of
1055 // modifiers.
Chris Lattner39bc53b2010-11-01 04:34:44 +00001056 //
1057 // Also, check for instructions which reference the operand multiple times;
1058 // this implies a constraint we would not honor.
1059 std::set<std::string> OperandNames;
Craig Topper77bd2b72015-12-30 06:00:20 +00001060 for (const AsmOperand &Op : AsmOperands) {
1061 StringRef Tok = Op.Token;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001062 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001063 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001064 "matchable with operand modifier '" + Tok +
1065 "' not supported by asm matcher. Mark isCodeGenOnly!");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001066
Chris Lattnerad776812010-11-01 05:06:45 +00001067 // Verify that any operand is only mentioned once.
Chris Lattner4d23eb22010-11-02 23:18:43 +00001068 // We reject aliases and ignore instructions for now.
Chris Lattner28ea9b12010-11-02 17:30:52 +00001069 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
Chris Lattnerad776812010-11-01 05:06:45 +00001070 if (!Hack)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001071 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001072 "ERROR: matchable with tied operand '" + Tok +
1073 "' can never be matched!");
Chris Lattnerad776812010-11-01 05:06:45 +00001074 // FIXME: Should reject these. The ARM backend hits this with $lane in a
1075 // bunch of instructions. It is unclear what the right answer is.
Chris Lattner39bc53b2010-11-01 04:34:44 +00001076 DEBUG({
Chris Lattner9f093812010-11-06 06:43:11 +00001077 errs() << "warning: '" << TheDef->getName() << "': "
Chris Lattnerad776812010-11-01 05:06:45 +00001078 << "ignoring instruction with tied operand '"
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001079 << Tok << "'\n";
Chris Lattner39bc53b2010-11-01 04:34:44 +00001080 });
1081 return false;
1082 }
1083 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001084
Chris Lattner39bc53b2010-11-01 04:34:44 +00001085 return true;
1086}
1087
Chris Lattner60db0a62010-02-09 00:34:28 +00001088static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001089 std::string Res;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001090
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001091 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
1092 switch (*it) {
1093 case '*': Res += "_STAR_"; break;
1094 case '%': Res += "_PCT_"; break;
1095 case ':': Res += "_COLON_"; break;
Bill Wendling4a08e562010-11-18 23:36:54 +00001096 case '!': Res += "_EXCLAIM_"; break;
Bill Wendlinga01ea892011-01-22 09:44:32 +00001097 case '.': Res += "_DOT_"; break;
Tim Northoverb3cfb282013-01-10 16:47:31 +00001098 case '<': Res += "_LT_"; break;
1099 case '>': Res += "_GT_"; break;
Hal Finkelf9090722015-01-15 01:33:00 +00001100 case '-': Res += "_MINUS_"; break;
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001101 default:
Tim Northoverb3cfb282013-01-10 16:47:31 +00001102 if ((*it >= 'A' && *it <= 'Z') ||
1103 (*it >= 'a' && *it <= 'z') ||
1104 (*it >= '0' && *it <= '9'))
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001105 Res += *it;
Chris Lattner33fc3e02010-10-31 19:10:56 +00001106 else
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001107 Res += "_" + utostr((unsigned) *it) + "_";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001108 }
1109 }
1110
1111 return Res;
1112}
1113
Chris Lattner60db0a62010-02-09 00:34:28 +00001114ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001115 ClassInfo *&Entry = TokenClasses[Token];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001116
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001117 if (!Entry) {
David Blaikied749e342014-11-28 20:35:57 +00001118 Classes.emplace_front();
1119 Entry = &Classes.front();
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001120 Entry->Kind = ClassInfo::Token;
Daniel Dunbarc32aa062009-08-09 05:18:30 +00001121 Entry->ClassName = "Token";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001122 Entry->Name = "MCK_" + getEnumNameForToken(Token);
1123 Entry->ValueName = Token;
1124 Entry->PredicateMethod = "<invalid>";
1125 Entry->RenderMethod = "<invalid>";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001126 Entry->ParserMethod = "";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001127 Entry->DiagnosticType = "";
Tom Stellardb9f235e2016-02-05 19:59:33 +00001128 Entry->IsOptional = false;
Sam Kolton5f10a132016-05-06 11:31:17 +00001129 Entry->DefaultMethod = "<invalid>";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001130 }
1131
1132 return Entry;
1133}
1134
1135ClassInfo *
Bob Wilsonb9b24222011-01-26 19:44:55 +00001136AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
1137 int SubOpIdx) {
1138 Record *Rec = OI.Rec;
1139 if (SubOpIdx != -1)
Sean Silva88eb8dd2012-10-10 20:24:47 +00001140 Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001141 return getOperandClass(Rec, SubOpIdx);
1142}
Bob Wilsonb9b24222011-01-26 19:44:55 +00001143
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001144ClassInfo *
1145AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001146 if (Rec->isSubClassOf("RegisterOperand")) {
1147 // RegisterOperand may have an associated ParserMatchClass. If it does,
1148 // use it, else just fall back to the underlying register class.
1149 const RecordVal *R = Rec->getValue("ParserMatchClass");
Craig Topper24064772014-04-15 07:20:03 +00001150 if (!R || !R->getValue())
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001151 PrintFatalError("Record `" + Rec->getName() +
1152 "' does not have a ParserMatchClass!\n");
Owen Andersona84be6c2011-06-27 21:06:21 +00001153
Sean Silvafb509ed2012-10-10 20:24:43 +00001154 if (DefInit *DI= dyn_cast<DefInit>(R->getValue())) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001155 Record *MatchClass = DI->getDef();
1156 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1157 return CI;
1158 }
1159
1160 // No custom match class. Just use the register class.
1161 Record *ClassRec = Rec->getValueAsDef("RegClass");
1162 if (!ClassRec)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001163 PrintFatalError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
Owen Andersona84be6c2011-06-27 21:06:21 +00001164 "' has no associated register class!\n");
1165 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
1166 return CI;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001167 PrintFatalError(Rec->getLoc(), "register class has no class info!");
Owen Andersona84be6c2011-06-27 21:06:21 +00001168 }
1169
Bob Wilsonb9b24222011-01-26 19:44:55 +00001170 if (Rec->isSubClassOf("RegisterClass")) {
1171 if (ClassInfo *CI = RegisterClassClasses[Rec])
Chris Lattner77d3ead2010-11-02 18:10:06 +00001172 return CI;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001173 PrintFatalError(Rec->getLoc(), "register class has no class info!");
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001174 }
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001175
Jim Grosbachf6cb1ee2012-09-12 17:40:25 +00001176 if (!Rec->isSubClassOf("Operand"))
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001177 PrintFatalError(Rec->getLoc(), "Operand `" + Rec->getName() +
Jim Grosbachf6cb1ee2012-09-12 17:40:25 +00001178 "' does not derive from class Operand!\n");
Bob Wilsonb9b24222011-01-26 19:44:55 +00001179 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
Chris Lattner77d3ead2010-11-02 18:10:06 +00001180 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1181 return CI;
Daniel Dunbar17410a42009-08-10 18:41:10 +00001182
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001183 PrintFatalError(Rec->getLoc(), "operand has no match class!");
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001184}
1185
Tim Northoverc74e6912013-09-16 16:43:19 +00001186struct LessRegisterSet {
Tim Northover9c30f7a2013-09-16 17:33:40 +00001187 bool operator() (const RegisterSet &LHS, const RegisterSet & RHS) const {
Tim Northoverc74e6912013-09-16 16:43:19 +00001188 // std::set<T> defines its own compariso "operator<", but it
1189 // performs a lexicographical comparison by T's innate comparison
1190 // for some reason. We don't want non-deterministic pointer
1191 // comparisons so use this instead.
1192 return std::lexicographical_compare(LHS.begin(), LHS.end(),
1193 RHS.begin(), RHS.end(),
1194 LessRecordByID());
1195 }
1196};
1197
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001198void AsmMatcherInfo::
Craig Topper71b7b682014-08-21 05:55:13 +00001199buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters) {
David Blaikie9b613db2014-11-29 18:13:39 +00001200 const auto &Registers = Target.getRegBank().getRegisters();
David Blaikiec0bb5ca2014-12-03 19:58:41 +00001201 auto &RegClassList = Target.getRegBank().getRegClasses();
Daniel Dunbar17410a42009-08-10 18:41:10 +00001202
Tim Northoverc74e6912013-09-16 16:43:19 +00001203 typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet;
1204
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001205 // The register sets used for matching.
Tim Northoverc74e6912013-09-16 16:43:19 +00001206 RegisterSetSet RegisterSets;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001207
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001208 // Gather the defined sets.
David Blaikiedacea4b2014-12-03 19:58:45 +00001209 for (const CodeGenRegisterClass &RC : RegClassList)
1210 RegisterSets.insert(
1211 RegisterSet(RC.getOrder().begin(), RC.getOrder().end()));
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001212
1213 // Add any required singleton sets.
Craig Topper03ec8012014-11-25 20:11:31 +00001214 for (Record *Rec : SingletonRegisters) {
Tim Northoverc74e6912013-09-16 16:43:19 +00001215 RegisterSets.insert(RegisterSet(&Rec, &Rec + 1));
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001216 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001217
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001218 // Introduce derived sets where necessary (when a register does not determine
1219 // a unique register set class), and build the mapping of registers to the set
1220 // they should classify to.
Tim Northoverc74e6912013-09-16 16:43:19 +00001221 std::map<Record*, RegisterSet> RegisterMap;
David Blaikie9b613db2014-11-29 18:13:39 +00001222 for (const CodeGenRegister &CGR : Registers) {
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001223 // Compute the intersection of all sets containing this register.
Tim Northoverc74e6912013-09-16 16:43:19 +00001224 RegisterSet ContainingSet;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001225
Craig Topper03ec8012014-11-25 20:11:31 +00001226 for (const RegisterSet &RS : RegisterSets) {
David Blaikie9b613db2014-11-29 18:13:39 +00001227 if (!RS.count(CGR.TheDef))
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001228 continue;
1229
1230 if (ContainingSet.empty()) {
Craig Topper03ec8012014-11-25 20:11:31 +00001231 ContainingSet = RS;
Chris Lattner77d3ead2010-11-02 18:10:06 +00001232 continue;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001233 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001234
Tim Northoverc74e6912013-09-16 16:43:19 +00001235 RegisterSet Tmp;
Chris Lattner77d3ead2010-11-02 18:10:06 +00001236 std::swap(Tmp, ContainingSet);
Tim Northoverc74e6912013-09-16 16:43:19 +00001237 std::insert_iterator<RegisterSet> II(ContainingSet,
1238 ContainingSet.begin());
Craig Topper03ec8012014-11-25 20:11:31 +00001239 std::set_intersection(Tmp.begin(), Tmp.end(), RS.begin(), RS.end(), II,
Tim Northoverc74e6912013-09-16 16:43:19 +00001240 LessRecordByID());
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001241 }
1242
1243 if (!ContainingSet.empty()) {
1244 RegisterSets.insert(ContainingSet);
David Blaikie9b613db2014-11-29 18:13:39 +00001245 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001246 }
1247 }
1248
1249 // Construct the register classes.
Tim Northoverc74e6912013-09-16 16:43:19 +00001250 std::map<RegisterSet, ClassInfo*, LessRegisterSet> RegisterSetClasses;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001251 unsigned Index = 0;
Craig Topper03ec8012014-11-25 20:11:31 +00001252 for (const RegisterSet &RS : RegisterSets) {
David Blaikied749e342014-11-28 20:35:57 +00001253 Classes.emplace_front();
1254 ClassInfo *CI = &Classes.front();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001255 CI->Kind = ClassInfo::RegisterClass0 + Index;
1256 CI->ClassName = "Reg" + utostr(Index);
1257 CI->Name = "MCK_Reg" + utostr(Index);
1258 CI->ValueName = "";
1259 CI->PredicateMethod = ""; // unused
1260 CI->RenderMethod = "addRegOperands";
Craig Topper03ec8012014-11-25 20:11:31 +00001261 CI->Registers = RS;
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001262 // FIXME: diagnostic type.
1263 CI->DiagnosticType = "";
Tom Stellardb9f235e2016-02-05 19:59:33 +00001264 CI->IsOptional = false;
Sam Kolton5f10a132016-05-06 11:31:17 +00001265 CI->DefaultMethod = ""; // unused
Craig Topper03ec8012014-11-25 20:11:31 +00001266 RegisterSetClasses.insert(std::make_pair(RS, CI));
1267 ++Index;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001268 }
1269
1270 // Find the superclasses; we could compute only the subgroup lattice edges,
1271 // but there isn't really a point.
Craig Topper03ec8012014-11-25 20:11:31 +00001272 for (const RegisterSet &RS : RegisterSets) {
1273 ClassInfo *CI = RegisterSetClasses[RS];
1274 for (const RegisterSet &RS2 : RegisterSets)
1275 if (RS != RS2 &&
1276 std::includes(RS2.begin(), RS2.end(), RS.begin(), RS.end(),
Tim Northoverc74e6912013-09-16 16:43:19 +00001277 LessRecordByID()))
Craig Topper03ec8012014-11-25 20:11:31 +00001278 CI->SuperClasses.push_back(RegisterSetClasses[RS2]);
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001279 }
1280
1281 // Name the register classes which correspond to a user defined RegisterClass.
David Blaikiedacea4b2014-12-03 19:58:45 +00001282 for (const CodeGenRegisterClass &RC : RegClassList) {
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001283 // Def will be NULL for non-user defined register classes.
David Blaikiedacea4b2014-12-03 19:58:45 +00001284 Record *Def = RC.getDef();
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001285 if (!Def)
1286 continue;
David Blaikiedacea4b2014-12-03 19:58:45 +00001287 ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(),
1288 RC.getOrder().end())];
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001289 if (CI->ValueName.empty()) {
David Blaikiedacea4b2014-12-03 19:58:45 +00001290 CI->ClassName = RC.getName();
1291 CI->Name = "MCK_" + RC.getName();
1292 CI->ValueName = RC.getName();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001293 } else
David Blaikiedacea4b2014-12-03 19:58:45 +00001294 CI->ValueName = CI->ValueName + "," + RC.getName();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001295
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001296 RegisterClassClasses.insert(std::make_pair(Def, CI));
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001297 }
1298
1299 // Populate the map for individual registers.
Tim Northoverc74e6912013-09-16 16:43:19 +00001300 for (std::map<Record*, RegisterSet>::iterator it = RegisterMap.begin(),
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001301 ie = RegisterMap.end(); it != ie; ++it)
Chris Lattner77d3ead2010-11-02 18:10:06 +00001302 RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001303
1304 // Name the register classes which correspond to singleton registers.
Craig Topper03ec8012014-11-25 20:11:31 +00001305 for (Record *Rec : SingletonRegisters) {
Chris Lattner77d3ead2010-11-02 18:10:06 +00001306 ClassInfo *CI = RegisterClasses[Rec];
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001307 assert(CI && "Missing singleton register class info!");
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001308
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001309 if (CI->ValueName.empty()) {
1310 CI->ClassName = Rec->getName();
1311 CI->Name = "MCK_" + Rec->getName();
1312 CI->ValueName = Rec->getName();
1313 } else
1314 CI->ValueName = CI->ValueName + "," + Rec->getName();
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001315 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001316}
1317
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001318void AsmMatcherInfo::buildOperandClasses() {
Chris Lattnere3c48de2010-11-01 23:57:23 +00001319 std::vector<Record*> AsmOperands =
1320 Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbarcf181532010-01-30 01:02:37 +00001321
1322 // Pre-populate AsmOperandClasses map.
David Blaikied749e342014-11-28 20:35:57 +00001323 for (Record *Rec : AsmOperands) {
1324 Classes.emplace_front();
1325 AsmOperandClasses[Rec] = &Classes.front();
1326 }
Daniel Dunbarcf181532010-01-30 01:02:37 +00001327
Daniel Dunbar17410a42009-08-10 18:41:10 +00001328 unsigned Index = 0;
Craig Topper03ec8012014-11-25 20:11:31 +00001329 for (Record *Rec : AsmOperands) {
1330 ClassInfo *CI = AsmOperandClasses[Rec];
Daniel Dunbar17410a42009-08-10 18:41:10 +00001331 CI->Kind = ClassInfo::UserClass0 + Index;
1332
Craig Topper03ec8012014-11-25 20:11:31 +00001333 ListInit *Supers = Rec->getValueAsListInit("SuperClasses");
Craig Topperef0578a2015-06-02 04:15:51 +00001334 for (Init *I : Supers->getValues()) {
1335 DefInit *DI = dyn_cast<DefInit>(I);
Daniel Dunbar346782c2010-05-22 21:02:29 +00001336 if (!DI) {
Craig Topper03ec8012014-11-25 20:11:31 +00001337 PrintError(Rec->getLoc(), "Invalid super class reference!");
Daniel Dunbar346782c2010-05-22 21:02:29 +00001338 continue;
1339 }
1340
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001341 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1342 if (!SC)
Craig Topper03ec8012014-11-25 20:11:31 +00001343 PrintError(Rec->getLoc(), "Invalid super class reference!");
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001344 else
1345 CI->SuperClasses.push_back(SC);
Daniel Dunbar17410a42009-08-10 18:41:10 +00001346 }
Craig Topper03ec8012014-11-25 20:11:31 +00001347 CI->ClassName = Rec->getValueAsString("Name");
Daniel Dunbar17410a42009-08-10 18:41:10 +00001348 CI->Name = "MCK_" + CI->ClassName;
Craig Topper03ec8012014-11-25 20:11:31 +00001349 CI->ValueName = Rec->getName();
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001350
1351 // Get or construct the predicate method name.
Craig Topper03ec8012014-11-25 20:11:31 +00001352 Init *PMName = Rec->getValueInit("PredicateMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001353 if (StringInit *SI = dyn_cast<StringInit>(PMName)) {
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001354 CI->PredicateMethod = SI->getValue();
1355 } else {
Sean Silva88eb8dd2012-10-10 20:24:47 +00001356 assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!");
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001357 CI->PredicateMethod = "is" + CI->ClassName;
1358 }
1359
1360 // Get or construct the render method name.
Craig Topper03ec8012014-11-25 20:11:31 +00001361 Init *RMName = Rec->getValueInit("RenderMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001362 if (StringInit *SI = dyn_cast<StringInit>(RMName)) {
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001363 CI->RenderMethod = SI->getValue();
1364 } else {
Sean Silva88eb8dd2012-10-10 20:24:47 +00001365 assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!");
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001366 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1367 }
1368
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001369 // Get the parse method name or leave it as empty.
Craig Topper03ec8012014-11-25 20:11:31 +00001370 Init *PRMName = Rec->getValueInit("ParserMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001371 if (StringInit *SI = dyn_cast<StringInit>(PRMName))
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001372 CI->ParserMethod = SI->getValue();
1373
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001374 // Get the diagnostic type or leave it as empty.
1375 // Get the parse method name or leave it as empty.
Craig Topper03ec8012014-11-25 20:11:31 +00001376 Init *DiagnosticType = Rec->getValueInit("DiagnosticType");
Sean Silvafb509ed2012-10-10 20:24:43 +00001377 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001378 CI->DiagnosticType = SI->getValue();
1379
Tom Stellardb9f235e2016-02-05 19:59:33 +00001380 Init *IsOptional = Rec->getValueInit("IsOptional");
1381 if (BitInit *BI = dyn_cast<BitInit>(IsOptional))
1382 CI->IsOptional = BI->getValue();
1383
Sam Kolton5f10a132016-05-06 11:31:17 +00001384 // Get or construct the default method name.
1385 Init *DMName = Rec->getValueInit("DefaultMethod");
1386 if (StringInit *SI = dyn_cast<StringInit>(DMName)) {
1387 CI->DefaultMethod = SI->getValue();
1388 } else {
1389 assert(isa<UnsetInit>(DMName) && "Unexpected DefaultMethod field!");
1390 CI->DefaultMethod = "default" + CI->ClassName + "Operands";
1391 }
1392
Craig Topper03ec8012014-11-25 20:11:31 +00001393 ++Index;
Daniel Dunbar17410a42009-08-10 18:41:10 +00001394 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001395}
1396
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001397AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1398 CodeGenTarget &target,
Chris Lattner89dcb682010-12-15 04:48:22 +00001399 RecordKeeper &records)
Devang Patel6d676e42012-01-07 01:33:34 +00001400 : Records(records), AsmParser(asmParser), Target(target) {
Daniel Dunbare4318712009-08-11 20:59:47 +00001401}
1402
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001403/// buildOperandMatchInfo - Build the necessary information to handle user
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001404/// defined operand parsing methods.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001405void AsmMatcherInfo::buildOperandMatchInfo() {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001406
Jim Grosbach925a6d02012-04-18 23:46:25 +00001407 /// Map containing a mask with all operands indices that can be found for
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001408 /// that class inside a instruction.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00001409 typedef std::map<ClassInfo *, unsigned, less_ptr<ClassInfo>> OpClassMaskTy;
Sean Silva835139b2012-09-19 01:47:03 +00001410 OpClassMaskTy OpClassMask;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001411
Craig Topperf34dad92014-11-28 03:53:02 +00001412 for (const auto &MI : Matchables) {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001413 OpClassMask.clear();
1414
1415 // Keep track of all operands of this instructions which belong to the
1416 // same class.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001417 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
1418 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001419 if (Op.Class->ParserMethod.empty())
1420 continue;
1421 unsigned &OperandMask = OpClassMask[Op.Class];
1422 OperandMask |= (1 << i);
1423 }
1424
1425 // Generate operand match info for each mnemonic/operand class pair.
Craig Topper42bd8192014-11-28 03:53:00 +00001426 for (const auto &OCM : OpClassMask) {
1427 unsigned OpMask = OCM.second;
1428 ClassInfo *CI = OCM.first;
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001429 OperandMatchInfo.push_back(OperandMatchEntry::create(MI.get(), CI,
1430 OpMask));
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001431 }
1432 }
1433}
1434
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001435void AsmMatcherInfo::buildInfo() {
Chris Lattnera0e87192010-10-30 20:07:57 +00001436 // Build information about all of the AssemblerPredicates.
1437 std::vector<Record*> AllPredicates =
1438 Records.getAllDerivedDefinitions("Predicate");
Craig Topper6e526f12016-01-03 07:33:30 +00001439 for (Record *Pred : AllPredicates) {
Chris Lattnera0e87192010-10-30 20:07:57 +00001440 // Ignore predicates that are not intended for the assembler.
1441 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
1442 continue;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001443
Chris Lattner178f4bb2010-11-01 04:44:29 +00001444 if (Pred->getName().empty())
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001445 PrintFatalError(Pred->getLoc(), "Predicate has no name!");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001446
David Blaikie9a9da992014-11-28 22:15:06 +00001447 SubtargetFeatures.insert(std::make_pair(
1448 Pred, SubtargetFeatureInfo(Pred, SubtargetFeatures.size())));
1449 DEBUG(SubtargetFeatures.find(Pred)->second.dump());
1450 assert(SubtargetFeatures.size() <= 64 && "Too many subtarget features!");
Chris Lattnera0e87192010-10-30 20:07:57 +00001451 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001452
Craig Topperfd2c6a32015-12-31 08:18:23 +00001453 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
1454
Chris Lattner33fc3e02010-10-31 19:10:56 +00001455 // Parse the instructions; we need to do this first so that we can gather the
1456 // singleton register classes.
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001457 SmallPtrSet<Record*, 16> SingletonRegisters;
Devang Patel85d684a2012-01-09 19:13:28 +00001458 unsigned VariantCount = Target.getAsmParserVariantCount();
1459 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1460 Record *AsmVariant = Target.getAsmParserVariant(VC);
Jim Grosbach56e63262012-04-17 00:01:04 +00001461 std::string CommentDelimiter =
1462 AsmVariant->getValueAsString("CommentDelimiter");
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001463 AsmVariantInfo Variant;
Craig Topperc8b5b252015-12-30 06:00:18 +00001464 Variant.RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001465 Variant.TokenizingCharacters =
1466 AsmVariant->getValueAsString("TokenizingCharacters");
1467 Variant.SeparatorCharacters =
1468 AsmVariant->getValueAsString("SeparatorCharacters");
1469 Variant.BreakCharacters =
1470 AsmVariant->getValueAsString("BreakCharacters");
Craig Topperc8b5b252015-12-30 06:00:18 +00001471 Variant.AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001472
Craig Topper8cc904d2016-01-17 20:38:18 +00001473 for (const CodeGenInstruction *CGI : Target.getInstructionsByEnumValue()) {
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001474
Devang Patel85d684a2012-01-09 19:13:28 +00001475 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1476 // filter the set of instructions we consider.
Craig Topper03ec8012014-11-25 20:11:31 +00001477 if (!StringRef(CGI->TheDef->getName()).startswith(MatchPrefix))
Jim Grosbach3263a072012-04-11 21:02:33 +00001478 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001479
Devang Patel85d684a2012-01-09 19:13:28 +00001480 // Ignore "codegen only" instructions.
Craig Topper03ec8012014-11-25 20:11:31 +00001481 if (CGI->TheDef->getValueAsBit("isCodeGenOnly"))
Jim Grosbach3263a072012-04-11 21:02:33 +00001482 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001483
Craig Topper1c8fbd22015-09-06 03:44:50 +00001484 auto II = llvm::make_unique<MatchableInfo>(*CGI);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001485
Craig Topperfd2c6a32015-12-31 08:18:23 +00001486 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001487
Devang Patel85d684a2012-01-09 19:13:28 +00001488 // Ignore instructions which shouldn't be matched and diagnose invalid
1489 // instruction definitions with an error.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001490 if (!II->validate(CommentDelimiter, true))
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001491 continue;
1492
1493 Matchables.push_back(std::move(II));
Chris Lattner743081d2010-11-04 00:43:46 +00001494 }
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001495
Devang Patel85d684a2012-01-09 19:13:28 +00001496 // Parse all of the InstAlias definitions and stick them in the list of
1497 // matchables.
1498 std::vector<Record*> AllInstAliases =
1499 Records.getAllDerivedDefinitions("InstAlias");
1500 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
David Blaikieba4e00f2014-12-22 21:26:26 +00001501 auto Alias = llvm::make_unique<CodeGenInstAlias>(AllInstAliases[i],
Craig Topperc8b5b252015-12-30 06:00:18 +00001502 Variant.AsmVariantNo,
1503 Target);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001504
Devang Patel85d684a2012-01-09 19:13:28 +00001505 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1506 // filter the set of instruction aliases we consider, based on the target
1507 // instruction.
Jim Grosbach56e63262012-04-17 00:01:04 +00001508 if (!StringRef(Alias->ResultInst->TheDef->getName())
1509 .startswith( MatchPrefix))
Jim Grosbach3263a072012-04-11 21:02:33 +00001510 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001511
Craig Topper1c8fbd22015-09-06 03:44:50 +00001512 auto II = llvm::make_unique<MatchableInfo>(std::move(Alias));
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001513
Craig Topperfd2c6a32015-12-31 08:18:23 +00001514 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001515
Devang Patel85d684a2012-01-09 19:13:28 +00001516 // Validate the alias definitions.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001517 II->validate(CommentDelimiter, false);
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001518
1519 Matchables.push_back(std::move(II));
Devang Patel85d684a2012-01-09 19:13:28 +00001520 }
Chris Lattner488c2012010-11-01 04:05:41 +00001521 }
Chris Lattnerd8adec72010-11-01 04:03:32 +00001522
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001523 // Build info for the register classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001524 buildRegisterClasses(SingletonRegisters);
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001525
1526 // Build info for the user defined assembly operand classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001527 buildOperandClasses();
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001528
Chris Lattner4779e3e92010-11-04 00:57:06 +00001529 // Build the information about matchables, now that we have fully formed
1530 // classes.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001531 std::vector<std::unique_ptr<MatchableInfo>> NewMatchables;
Craig Topperf34dad92014-11-28 03:53:02 +00001532 for (auto &II : Matchables) {
Chris Lattner82d88ce2010-09-06 21:01:37 +00001533 // Parse the tokens after the mnemonic.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001534 // Note: buildInstructionOperandReference may insert new AsmOperands, so
Bob Wilsonb9b24222011-01-26 19:44:55 +00001535 // don't precompute the loop bound.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001536 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1537 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
Chris Lattner28ea9b12010-11-02 17:30:52 +00001538 StringRef Token = Op.Token;
Daniel Dunbare10787e2009-08-07 08:26:05 +00001539
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001540 // Check for singleton registers.
Craig Toppere4e74152015-12-29 07:03:23 +00001541 if (Record *RegRecord = Op.SingletonReg) {
Chris Lattner28ea9b12010-11-02 17:30:52 +00001542 Op.Class = RegisterClasses[RegRecord];
Chris Lattnerb80ab362010-11-01 01:37:30 +00001543 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1544 "Unexpected class for singleton register");
Chris Lattnerb80ab362010-11-01 01:37:30 +00001545 continue;
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001546 }
1547
Daniel Dunbare10787e2009-08-07 08:26:05 +00001548 // Check for simple tokens.
1549 if (Token[0] != '$') {
Chris Lattner28ea9b12010-11-02 17:30:52 +00001550 Op.Class = getTokenClass(Token);
Daniel Dunbare10787e2009-08-07 08:26:05 +00001551 continue;
1552 }
1553
Chris Lattnerd6746d52010-11-06 22:06:03 +00001554 if (Token.size() > 1 && isdigit(Token[1])) {
1555 Op.Class = getTokenClass(Token);
1556 continue;
1557 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001558
Chris Lattner4efe13d2010-11-04 02:11:18 +00001559 // Otherwise this is an operand reference.
Chris Lattnerccde4632010-11-04 01:58:23 +00001560 StringRef OperandName;
1561 if (Token[1] == '{')
1562 OperandName = Token.substr(2, Token.size() - 3);
1563 else
1564 OperandName = Token.substr(1);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001565
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001566 if (II->DefRec.is<const CodeGenInstruction*>())
1567 buildInstructionOperandReference(II.get(), OperandName, i);
Chris Lattner4efe13d2010-11-04 02:11:18 +00001568 else
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001569 buildAliasOperandReference(II.get(), OperandName, Op);
Daniel Dunbare10787e2009-08-07 08:26:05 +00001570 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001571
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001572 if (II->DefRec.is<const CodeGenInstruction*>()) {
1573 II->buildInstructionResultOperands();
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001574 // If the instruction has a two-operand alias, build up the
1575 // matchable here. We'll add them in bulk at the end to avoid
1576 // confusing this loop.
1577 std::string Constraint =
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001578 II->TheDef->getValueAsString("TwoOperandAliasConstraint");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001579 if (Constraint != "") {
1580 // Start by making a copy of the original matchable.
Craig Topper1c8fbd22015-09-06 03:44:50 +00001581 auto AliasII = llvm::make_unique<MatchableInfo>(*II);
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001582
1583 // Adjust it to be a two-operand alias.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001584 AliasII->formTwoOperandAlias(Constraint);
1585
1586 // Add the alias to the matchables list.
1587 NewMatchables.push_back(std::move(AliasII));
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001588 }
1589 } else
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001590 II->buildAliasResultOperands();
Daniel Dunbare10787e2009-08-07 08:26:05 +00001591 }
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001592 if (!NewMatchables.empty())
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001593 Matchables.insert(Matchables.end(),
1594 std::make_move_iterator(NewMatchables.begin()),
1595 std::make_move_iterator(NewMatchables.end()));
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001596
Jim Grosbachba395922011-12-06 23:43:54 +00001597 // Process token alias definitions and set up the associated superclass
1598 // information.
1599 std::vector<Record*> AllTokenAliases =
1600 Records.getAllDerivedDefinitions("TokenAlias");
Craig Toppere4e74152015-12-29 07:03:23 +00001601 for (Record *Rec : AllTokenAliases) {
Jim Grosbachba395922011-12-06 23:43:54 +00001602 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1603 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
Jim Grosbach37f6dcb32012-04-17 21:23:52 +00001604 if (FromClass == ToClass)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001605 PrintFatalError(Rec->getLoc(),
Jim Grosbach37f6dcb32012-04-17 21:23:52 +00001606 "error: Destination value identical to source value.");
Jim Grosbachba395922011-12-06 23:43:54 +00001607 FromClass->SuperClasses.push_back(ToClass);
1608 }
1609
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001610 // Reorder classes so that classes precede super classes.
David Blaikied749e342014-11-28 20:35:57 +00001611 Classes.sort();
Oliver Stannard7772f022016-01-25 10:20:19 +00001612
1613#ifndef NDEBUG
1614 // Verify that the table is now sorted
1615 for (auto I = Classes.begin(), E = Classes.end(); I != E; ++I) {
1616 for (auto J = I; J != E; ++J) {
1617 assert(!(*J < *I));
1618 assert(I == J || !J->isSubsetOf(*I));
1619 }
1620 }
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +00001621#endif // NDEBUG
Daniel Dunbare10787e2009-08-07 08:26:05 +00001622}
1623
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001624/// buildInstructionOperandReference - The specified operand is a reference to a
Chris Lattner4779e3e92010-11-04 00:57:06 +00001625/// named operand such as $src. Resolve the Class and OperandInfo pointers.
1626void AsmMatcherInfo::
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001627buildInstructionOperandReference(MatchableInfo *II,
Chris Lattnerccde4632010-11-04 01:58:23 +00001628 StringRef OperandName,
Bob Wilsonb9b24222011-01-26 19:44:55 +00001629 unsigned AsmOpIdx) {
Chris Lattner4efe13d2010-11-04 02:11:18 +00001630 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1631 const CGIOperandList &Operands = CGI.Operands;
Bob Wilsonb9b24222011-01-26 19:44:55 +00001632 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001633
Chris Lattnerfecdad62010-11-06 07:14:44 +00001634 // Map this token to an operand.
Chris Lattner4779e3e92010-11-04 00:57:06 +00001635 unsigned Idx;
1636 if (!Operands.hasOperandNamed(OperandName, Idx))
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001637 PrintFatalError(II->TheDef->getLoc(),
1638 "error: unable to find operand: '" + OperandName + "'");
Chris Lattner897a1402010-11-04 01:55:23 +00001639
Bob Wilsonb9b24222011-01-26 19:44:55 +00001640 // If the instruction operand has multiple suboperands, but the parser
1641 // match class for the asm operand is still the default "ImmAsmOperand",
1642 // then handle each suboperand separately.
1643 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1644 Record *Rec = Operands[Idx].Rec;
1645 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1646 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1647 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1648 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1649 StringRef Token = Op->Token; // save this in case Op gets moved
1650 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
Ahmed Bougachaeb4dbd82015-05-29 01:03:37 +00001651 MatchableInfo::AsmOperand NewAsmOp(/*IsIsolatedToken=*/true, Token);
Bob Wilsonb9b24222011-01-26 19:44:55 +00001652 NewAsmOp.SubOpIdx = SI;
1653 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1654 }
1655 // Replace Op with first suboperand.
1656 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1657 Op->SubOpIdx = 0;
1658 }
1659 }
1660
Chris Lattner897a1402010-11-04 01:55:23 +00001661 // Set up the operand class.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001662 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
Chris Lattner897a1402010-11-04 01:55:23 +00001663
1664 // If the named operand is tied, canonicalize it to the untied operand.
1665 // For example, something like:
1666 // (outs GPR:$dst), (ins GPR:$src)
1667 // with an asmstring of
1668 // "inc $src"
1669 // we want to canonicalize to:
1670 // "inc $dst"
1671 // so that we know how to provide the $dst operand when filling in the result.
Ulrich Weigande037a492013-04-27 18:48:23 +00001672 int OITied = -1;
1673 if (Operands[Idx].MINumOperands == 1)
1674 OITied = Operands[Idx].getTiedRegister();
Chris Lattner4779e3e92010-11-04 00:57:06 +00001675 if (OITied != -1) {
1676 // The tied operand index is an MIOperand index, find the operand that
1677 // contains it.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001678 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1679 OperandName = Operands[Idx.first].Name;
1680 Op->SubOpIdx = Idx.second;
Chris Lattner4779e3e92010-11-04 00:57:06 +00001681 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001682
Bob Wilsonb9b24222011-01-26 19:44:55 +00001683 Op->SrcOpName = OperandName;
Chris Lattner4779e3e92010-11-04 00:57:06 +00001684}
1685
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001686/// buildAliasOperandReference - When parsing an operand reference out of the
Chris Lattnerb625dd22010-11-06 07:06:09 +00001687/// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1688/// operand reference is by looking it up in the result pattern definition.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001689void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
Chris Lattner4efe13d2010-11-04 02:11:18 +00001690 StringRef OperandName,
1691 MatchableInfo::AsmOperand &Op) {
1692 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001693
Chris Lattner4efe13d2010-11-04 02:11:18 +00001694 // Set up the operand class.
Chris Lattnerb625dd22010-11-06 07:06:09 +00001695 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
Chris Lattnerb6f8e822010-11-06 19:25:43 +00001696 if (CGA.ResultOperands[i].isRecord() &&
1697 CGA.ResultOperands[i].getName() == OperandName) {
Chris Lattnerfecdad62010-11-06 07:14:44 +00001698 // It's safe to go with the first one we find, because CodeGenInstAlias
1699 // validates that all operands with the same name have the same record.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001700 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001701 // Use the match class from the Alias definition, not the
1702 // destination instruction, as we may have an immediate that's
1703 // being munged by the match class.
1704 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
Bob Wilsonb9b24222011-01-26 19:44:55 +00001705 Op.SubOpIdx);
Chris Lattnerb625dd22010-11-06 07:06:09 +00001706 Op.SrcOpName = OperandName;
1707 return;
Chris Lattner4efe13d2010-11-04 02:11:18 +00001708 }
Chris Lattnerb625dd22010-11-06 07:06:09 +00001709
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001710 PrintFatalError(II->TheDef->getLoc(),
1711 "error: unable to find operand: '" + OperandName + "'");
Chris Lattner4efe13d2010-11-04 02:11:18 +00001712}
1713
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001714void MatchableInfo::buildInstructionResultOperands() {
Chris Lattnerfecdad62010-11-06 07:14:44 +00001715 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001716
Chris Lattnerfecdad62010-11-06 07:14:44 +00001717 // Loop over all operands of the result instruction, determining how to
1718 // populate them.
Craig Toppere4e74152015-12-29 07:03:23 +00001719 for (const CGIOperandList::OperandInfo &OpInfo : ResultInst->Operands) {
Chris Lattner7108dad2010-11-04 01:42:59 +00001720 // If this is a tied operand, just copy from the previously handled operand.
Ulrich Weigande037a492013-04-27 18:48:23 +00001721 int TiedOp = -1;
1722 if (OpInfo.MINumOperands == 1)
1723 TiedOp = OpInfo.getTiedRegister();
Chris Lattner7108dad2010-11-04 01:42:59 +00001724 if (TiedOp != -1) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001725 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
Chris Lattner7108dad2010-11-04 01:42:59 +00001726 continue;
1727 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001728
Bob Wilsonb9b24222011-01-26 19:44:55 +00001729 // Find out what operand from the asmparser this MCInst operand comes from.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001730 int SrcOperand = findAsmOperandNamed(OpInfo.Name);
Ulrich Weigande037a492013-04-27 18:48:23 +00001731 if (OpInfo.Name.empty() || SrcOperand == -1) {
1732 // This may happen for operands that are tied to a suboperand of a
1733 // complex operand. Simply use a dummy value here; nobody should
1734 // use this operand slot.
1735 // FIXME: The long term goal is for the MCOperand list to not contain
1736 // tied operands at all.
1737 ResOperands.push_back(ResOperand::getImmOp(0));
1738 continue;
1739 }
Chris Lattner7108dad2010-11-04 01:42:59 +00001740
Bob Wilsonb9b24222011-01-26 19:44:55 +00001741 // Check if the one AsmOperand populates the entire operand.
1742 unsigned NumOperands = OpInfo.MINumOperands;
1743 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1744 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
Chris Lattner743081d2010-11-04 00:43:46 +00001745 continue;
1746 }
Bob Wilsonb9b24222011-01-26 19:44:55 +00001747
1748 // Add a separate ResOperand for each suboperand.
1749 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1750 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1751 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1752 "unexpected AsmOperands for suboperands");
1753 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1754 }
Chris Lattner743081d2010-11-04 00:43:46 +00001755 }
1756}
1757
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001758void MatchableInfo::buildAliasResultOperands() {
Chris Lattner8188fb22010-11-06 07:31:43 +00001759 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1760 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001761
Chris Lattner8188fb22010-11-06 07:31:43 +00001762 // Loop over all operands of the result instruction, determining how to
1763 // populate them.
1764 unsigned AliasOpNo = 0;
Bob Wilsonb9b24222011-01-26 19:44:55 +00001765 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
Chris Lattner8188fb22010-11-06 07:31:43 +00001766 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001767 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001768
Chris Lattner8188fb22010-11-06 07:31:43 +00001769 // If this is a tied operand, just copy from the previously handled operand.
Ulrich Weigande037a492013-04-27 18:48:23 +00001770 int TiedOp = -1;
1771 if (OpInfo->MINumOperands == 1)
1772 TiedOp = OpInfo->getTiedRegister();
Chris Lattner8188fb22010-11-06 07:31:43 +00001773 if (TiedOp != -1) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001774 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
Chris Lattner4869d342010-11-06 19:57:21 +00001775 continue;
1776 }
1777
Bob Wilsonb9b24222011-01-26 19:44:55 +00001778 // Handle all the suboperands for this operand.
1779 const std::string &OpName = OpInfo->Name;
1780 for ( ; AliasOpNo < LastOpNo &&
1781 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1782 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1783
1784 // Find out what operand from the asmparser that this MCInst operand
1785 // comes from.
1786 switch (CGA.ResultOperands[AliasOpNo].Kind) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001787 case CodeGenInstAlias::ResultOperand::K_Record: {
1788 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001789 int SrcOperand = findAsmOperand(Name, SubIdx);
Bob Wilsonb9b24222011-01-26 19:44:55 +00001790 if (SrcOperand == -1)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001791 PrintFatalError(TheDef->getLoc(), "Instruction '" +
Bob Wilsonb9b24222011-01-26 19:44:55 +00001792 TheDef->getName() + "' has operand '" + OpName +
1793 "' that doesn't appear in asm string!");
1794 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1795 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1796 NumOperands));
1797 break;
1798 }
1799 case CodeGenInstAlias::ResultOperand::K_Imm: {
1800 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1801 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1802 break;
1803 }
1804 case CodeGenInstAlias::ResultOperand::K_Reg: {
1805 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1806 ResOperands.push_back(ResOperand::getRegOp(Reg));
1807 break;
1808 }
1809 }
Chris Lattner4869d342010-11-06 19:57:21 +00001810 }
Chris Lattner8188fb22010-11-06 07:31:43 +00001811 }
1812}
Chris Lattner743081d2010-11-04 00:43:46 +00001813
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001814static unsigned getConverterOperandID(const std::string &Name,
Rafael Espindola55512f92015-11-18 06:52:18 +00001815 SmallSetVector<std::string, 16> &Table,
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001816 bool &IsNew) {
1817 IsNew = Table.insert(Name);
1818
David Majnemer0d955d02016-08-11 22:21:41 +00001819 unsigned ID = IsNew ? Table.size() - 1 : find(Table, Name) - Table.begin();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001820
1821 assert(ID < Table.size());
1822
1823 return ID;
1824}
1825
Chad Rosierf4e35dc2012-10-01 23:45:51 +00001826static void emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName,
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001827 std::vector<std::unique_ptr<MatchableInfo>> &Infos,
Sam Kolton5f10a132016-05-06 11:31:17 +00001828 bool HasMnemonicFirst, bool HasOptionalOperands,
1829 raw_ostream &OS) {
Rafael Espindola55512f92015-11-18 06:52:18 +00001830 SmallSetVector<std::string, 16> OperandConversionKinds;
1831 SmallSetVector<std::string, 16> InstructionConversionKinds;
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001832 std::vector<std::vector<uint8_t> > ConversionTable;
1833 size_t MaxRowLength = 2; // minimum is custom converter plus terminator.
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001834
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001835 // TargetOperandClass - This is the target's operand class, like X86Operand.
1836 std::string TargetOperandClass = Target.getName() + "Operand";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001837
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001838 // Write the convert function to a separate stream, so we can drop it after
1839 // the enum. We'll build up the conversion handlers for the individual
1840 // operand types opportunistically as we encounter them.
1841 std::string ConvertFnBody;
1842 raw_string_ostream CvtOS(ConvertFnBody);
1843 // Start the unified conversion function.
Sam Kolton5f10a132016-05-06 11:31:17 +00001844 if (HasOptionalOperands) {
1845 CvtOS << "void " << Target.getName() << ClassName << "::\n"
1846 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1847 << "unsigned Opcode,\n"
1848 << " const OperandVector &Operands,\n"
1849 << " const SmallBitVector &OptionalOperandsMask) {\n";
1850 } else {
1851 CvtOS << "void " << Target.getName() << ClassName << "::\n"
1852 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1853 << "unsigned Opcode,\n"
1854 << " const OperandVector &Operands) {\n";
1855 }
1856 CvtOS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
1857 CvtOS << " const uint8_t *Converter = ConversionTable[Kind];\n";
1858 if (HasOptionalOperands) {
1859 CvtOS << " unsigned NumDefaults = 0;\n";
1860 }
1861 CvtOS << " unsigned OpIdx;\n";
1862 CvtOS << " Inst.setOpcode(Opcode);\n";
1863 CvtOS << " for (const uint8_t *p = Converter; *p; p+= 2) {\n";
1864 if (HasOptionalOperands) {
1865 CvtOS << " OpIdx = *(p + 1) - NumDefaults;\n";
1866 } else {
1867 CvtOS << " OpIdx = *(p + 1);\n";
1868 }
1869 CvtOS << " switch (*p) {\n";
1870 CvtOS << " default: llvm_unreachable(\"invalid conversion entry!\");\n";
1871 CvtOS << " case CVT_Reg:\n";
1872 CvtOS << " static_cast<" << TargetOperandClass
1873 << "&>(*Operands[OpIdx]).addRegOperands(Inst, 1);\n";
1874 CvtOS << " break;\n";
1875 CvtOS << " case CVT_Tied:\n";
1876 CvtOS << " Inst.addOperand(Inst.getOperand(OpIdx));\n";
1877 CvtOS << " break;\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001878
Chad Rosier738ea252012-08-30 17:59:25 +00001879 std::string OperandFnBody;
1880 raw_string_ostream OpOS(OperandFnBody);
1881 // Start the operand number lookup function.
Chad Rosierf4e35dc2012-10-01 23:45:51 +00001882 OpOS << "void " << Target.getName() << ClassName << "::\n"
1883 << "convertToMapAndConstraints(unsigned Kind,\n";
Chad Rosier380a74a2012-10-02 00:25:57 +00001884 OpOS.indent(27);
David Blaikie960ea3f2014-06-08 16:18:35 +00001885 OpOS << "const OperandVector &Operands) {\n"
Chad Rosier98cfa102012-08-31 00:03:31 +00001886 << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00001887 << " unsigned NumMCOperands = 0;\n"
Craig Topper91506102012-09-18 01:41:49 +00001888 << " const uint8_t *Converter = ConversionTable[Kind];\n"
1889 << " for (const uint8_t *p = Converter; *p; p+= 2) {\n"
Chad Rosier738ea252012-08-30 17:59:25 +00001890 << " switch (*p) {\n"
1891 << " default: llvm_unreachable(\"invalid conversion entry!\");\n"
1892 << " case CVT_Reg:\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00001893 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
Chad Rosier72450332013-01-15 23:07:53 +00001894 << " Operands[*(p + 1)]->setConstraint(\"r\");\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00001895 << " ++NumMCOperands;\n"
1896 << " break;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00001897 << " case CVT_Tied:\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00001898 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00001899 << " break;\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001900
1901 // Pre-populate the operand conversion kinds with the standard always
1902 // available entries.
1903 OperandConversionKinds.insert("CVT_Done");
1904 OperandConversionKinds.insert("CVT_Reg");
1905 OperandConversionKinds.insert("CVT_Tied");
1906 enum { CVT_Done, CVT_Reg, CVT_Tied };
1907
Craig Topperf34dad92014-11-28 03:53:02 +00001908 for (auto &II : Infos) {
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001909 // Check if we have a custom match function.
Daniel Dunbar5f74b392011-04-01 20:23:52 +00001910 std::string AsmMatchConverter =
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001911 II->getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
Tom Stellard74c87c82015-05-26 15:55:50 +00001912 if (!AsmMatchConverter.empty() && II->UseInstAsmMatchConverter) {
Daniel Dunbar5f74b392011-04-01 20:23:52 +00001913 std::string Signature = "ConvertCustom_" + AsmMatchConverter;
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001914 II->ConversionFnKind = Signature;
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001915
1916 // Check if we have already generated this signature.
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001917 if (!InstructionConversionKinds.insert(Signature))
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001918 continue;
1919
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001920 // Remember this converter for the kind enum.
1921 unsigned KindID = OperandConversionKinds.size();
Tim Northoverb3cfb282013-01-10 16:47:31 +00001922 OperandConversionKinds.insert("CVT_" +
1923 getEnumNameForToken(AsmMatchConverter));
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001924
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001925 // Add the converter row for this instruction.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001926 ConversionTable.emplace_back();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001927 ConversionTable.back().push_back(KindID);
1928 ConversionTable.back().push_back(CVT_Done);
1929
1930 // Add the handler to the conversion driver function.
Tim Northoverb3cfb282013-01-10 16:47:31 +00001931 CvtOS << " case CVT_"
1932 << getEnumNameForToken(AsmMatchConverter) << ":\n"
Chad Rosier451ef132012-08-31 22:12:31 +00001933 << " " << AsmMatchConverter << "(Inst, Operands);\n"
Chad Rosier98cfa102012-08-31 00:03:31 +00001934 << " break;\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001935
Chad Rosier738ea252012-08-30 17:59:25 +00001936 // FIXME: Handle the operand number lookup for custom match functions.
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001937 continue;
1938 }
1939
Daniel Dunbare10787e2009-08-07 08:26:05 +00001940 // Build the conversion function signature.
1941 std::string Signature = "Convert";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001942
1943 std::vector<uint8_t> ConversionRow;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001944
Chris Lattner5cf8a4a2010-11-02 21:49:44 +00001945 // Compute the convert enum and the case body.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001946 MaxRowLength = std::max(MaxRowLength, II->ResOperands.size()*2 + 1 );
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001947
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001948 for (unsigned i = 0, e = II->ResOperands.size(); i != e; ++i) {
1949 const MatchableInfo::ResOperand &OpInfo = II->ResOperands[i];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001950
Chris Lattner743081d2010-11-04 00:43:46 +00001951 // Generate code to populate each result operand.
1952 switch (OpInfo.Kind) {
Chris Lattner743081d2010-11-04 00:43:46 +00001953 case MatchableInfo::ResOperand::RenderAsmOperand: {
1954 // This comes from something we parsed.
Craig Topper03ec8012014-11-25 20:11:31 +00001955 const MatchableInfo::AsmOperand &Op =
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001956 II->AsmOperands[OpInfo.AsmOperandNum];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001957
Chris Lattnere032dbf2010-11-02 22:55:03 +00001958 // Registers are always converted the same, don't duplicate the
1959 // conversion function based on them.
Chris Lattnere032dbf2010-11-02 22:55:03 +00001960 Signature += "__";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001961 std::string Class;
1962 Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName;
1963 Signature += Class;
Bob Wilsonb9b24222011-01-26 19:44:55 +00001964 Signature += utostr(OpInfo.MINumOperands);
Chris Lattner743081d2010-11-04 00:43:46 +00001965 Signature += "_" + itostr(OpInfo.AsmOperandNum);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001966
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001967 // Add the conversion kind, if necessary, and get the associated ID
1968 // the index of its entry in the vector).
1969 std::string Name = "CVT_" + (Op.Class->isRegisterClass() ? "Reg" :
1970 Op.Class->RenderMethod);
Sam Kolton5f10a132016-05-06 11:31:17 +00001971 if (Op.Class->IsOptional) {
1972 // For optional operands we must also care about DefaultMethod
1973 assert(HasOptionalOperands);
1974 Name += "_" + Op.Class->DefaultMethod;
1975 }
Tim Northoverb3cfb282013-01-10 16:47:31 +00001976 Name = getEnumNameForToken(Name);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001977
1978 bool IsNewConverter = false;
1979 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
1980 IsNewConverter);
1981
1982 // Add the operand entry to the instruction kind conversion row.
1983 ConversionRow.push_back(ID);
Craig Topperfd2c6a32015-12-31 08:18:23 +00001984 ConversionRow.push_back(OpInfo.AsmOperandNum + HasMnemonicFirst);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001985
1986 if (!IsNewConverter)
1987 break;
1988
1989 // This is a new operand kind. Add a handler for it to the
1990 // converter driver.
Sam Kolton5f10a132016-05-06 11:31:17 +00001991 CvtOS << " case " << Name << ":\n";
1992 if (Op.Class->IsOptional) {
1993 // If optional operand is not present in actual instruction then we
1994 // should call its DefaultMethod before RenderMethod
1995 assert(HasOptionalOperands);
1996 CvtOS << " if (OptionalOperandsMask[*(p + 1) - 1]) {\n"
1997 << " " << Op.Class->DefaultMethod << "()"
1998 << "->" << Op.Class->RenderMethod << "(Inst, "
1999 << OpInfo.MINumOperands << ");\n"
2000 << " ++NumDefaults;\n"
2001 << " } else {\n"
2002 << " static_cast<" << TargetOperandClass
2003 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod
2004 << "(Inst, " << OpInfo.MINumOperands << ");\n"
2005 << " }\n";
2006 } else {
2007 CvtOS << " static_cast<" << TargetOperandClass
2008 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod
2009 << "(Inst, " << OpInfo.MINumOperands << ");\n";
2010 }
2011 CvtOS << " break;\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002012
2013 // Add a handler for the operand number lookup.
2014 OpOS << " case " << Name << ":\n"
Chad Rosier72450332013-01-15 23:07:53 +00002015 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n";
2016
2017 if (Op.Class->isRegisterClass())
2018 OpOS << " Operands[*(p + 1)]->setConstraint(\"r\");\n";
2019 else
2020 OpOS << " Operands[*(p + 1)]->setConstraint(\"m\");\n";
2021 OpOS << " NumMCOperands += " << OpInfo.MINumOperands << ";\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002022 << " break;\n";
Chris Lattner743081d2010-11-04 00:43:46 +00002023 break;
Daniel Dunbarf22553a2010-02-10 08:15:48 +00002024 }
Chris Lattner743081d2010-11-04 00:43:46 +00002025 case MatchableInfo::ResOperand::TiedOperand: {
2026 // If this operand is tied to a previous one, just copy the MCInst
2027 // operand from the earlier one.We can only tie single MCOperand values.
Ulrich Weigande037a492013-04-27 18:48:23 +00002028 assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
Chris Lattner743081d2010-11-04 00:43:46 +00002029 unsigned TiedOp = OpInfo.TiedOperandNum;
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002030 assert(i > TiedOp && "Tied operand precedes its target!");
Chris Lattner743081d2010-11-04 00:43:46 +00002031 Signature += "__Tie" + utostr(TiedOp);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002032 ConversionRow.push_back(CVT_Tied);
2033 ConversionRow.push_back(TiedOp);
Chris Lattner743081d2010-11-04 00:43:46 +00002034 break;
2035 }
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002036 case MatchableInfo::ResOperand::ImmOperand: {
2037 int64_t Val = OpInfo.ImmVal;
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002038 std::string Ty = "imm_" + itostr(Val);
Hal Finkelf9090722015-01-15 01:33:00 +00002039 Ty = getEnumNameForToken(Ty);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002040 Signature += "__" + Ty;
2041
2042 std::string Name = "CVT_" + Ty;
2043 bool IsNewConverter = false;
2044 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2045 IsNewConverter);
2046 // Add the operand entry to the instruction kind conversion row.
2047 ConversionRow.push_back(ID);
2048 ConversionRow.push_back(0);
2049
2050 if (!IsNewConverter)
2051 break;
2052
2053 CvtOS << " case " << Name << ":\n"
Jim Grosbache9119e42015-05-13 18:37:00 +00002054 << " Inst.addOperand(MCOperand::createImm(" << Val << "));\n"
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002055 << " break;\n";
2056
Chad Rosier738ea252012-08-30 17:59:25 +00002057 OpOS << " case " << Name << ":\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002058 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2059 << " Operands[*(p + 1)]->setConstraint(\"\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002060 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002061 << " break;\n";
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002062 break;
2063 }
Chris Lattner4869d342010-11-06 19:57:21 +00002064 case MatchableInfo::ResOperand::RegOperand: {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002065 std::string Reg, Name;
Craig Topper24064772014-04-15 07:20:03 +00002066 if (!OpInfo.Register) {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002067 Name = "reg0";
2068 Reg = "0";
Bob Wilson03912ab2011-01-14 22:58:09 +00002069 } else {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002070 Reg = getQualifiedName(OpInfo.Register);
2071 Name = "reg" + OpInfo.Register->getName();
Bob Wilson03912ab2011-01-14 22:58:09 +00002072 }
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002073 Signature += "__" + Name;
2074 Name = "CVT_" + Name;
2075 bool IsNewConverter = false;
2076 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2077 IsNewConverter);
2078 // Add the operand entry to the instruction kind conversion row.
2079 ConversionRow.push_back(ID);
2080 ConversionRow.push_back(0);
2081
2082 if (!IsNewConverter)
2083 break;
2084 CvtOS << " case " << Name << ":\n"
Jim Grosbache9119e42015-05-13 18:37:00 +00002085 << " Inst.addOperand(MCOperand::createReg(" << Reg << "));\n"
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002086 << " break;\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002087
2088 OpOS << " case " << Name << ":\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002089 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2090 << " Operands[*(p + 1)]->setConstraint(\"m\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002091 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002092 << " break;\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002093 }
Chris Lattner743081d2010-11-04 00:43:46 +00002094 }
Daniel Dunbare10787e2009-08-07 08:26:05 +00002095 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002096
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002097 // If there were no operands, add to the signature to that effect
2098 if (Signature == "Convert")
2099 Signature += "_NoOperands";
2100
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002101 II->ConversionFnKind = Signature;
Daniel Dunbare10787e2009-08-07 08:26:05 +00002102
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002103 // Save the signature. If we already have it, don't add a new row
2104 // to the table.
2105 if (!InstructionConversionKinds.insert(Signature))
Daniel Dunbare10787e2009-08-07 08:26:05 +00002106 continue;
2107
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002108 // Add the row to the table.
Craig Topperc4de7ee2015-08-16 21:27:08 +00002109 ConversionTable.push_back(std::move(ConversionRow));
Daniel Dunbare10787e2009-08-07 08:26:05 +00002110 }
Daniel Dunbar71330282009-08-08 05:24:34 +00002111
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002112 // Finish up the converter driver function.
Chad Rosierc38826c2012-09-03 17:39:57 +00002113 CvtOS << " }\n }\n}\n\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002114
Chad Rosier738ea252012-08-30 17:59:25 +00002115 // Finish up the operand number lookup function.
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002116 OpOS << " }\n }\n}\n\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002117
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002118 OS << "namespace {\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002119
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002120 // Output the operand conversion kind enum.
2121 OS << "enum OperatorConversionKind {\n";
Craig Topper6e526f12016-01-03 07:33:30 +00002122 for (const std::string &Converter : OperandConversionKinds)
2123 OS << " " << Converter << ",\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002124 OS << " CVT_NUM_CONVERTERS\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002125 OS << "};\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002126
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002127 // Output the instruction conversion kind enum.
2128 OS << "enum InstructionConversionKind {\n";
Craig Topper802d3d32015-08-16 21:27:10 +00002129 for (const std::string &Signature : InstructionConversionKinds)
2130 OS << " " << Signature << ",\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002131 OS << " CVT_NUM_SIGNATURES\n";
2132 OS << "};\n\n";
2133
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002134 OS << "} // end anonymous namespace\n\n";
2135
2136 // Output the conversion table.
Craig Topper91506102012-09-18 01:41:49 +00002137 OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES]["
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002138 << MaxRowLength << "] = {\n";
2139
2140 for (unsigned Row = 0, ERow = ConversionTable.size(); Row != ERow; ++Row) {
2141 assert(ConversionTable[Row].size() % 2 == 0 && "bad conversion row!");
2142 OS << " // " << InstructionConversionKinds[Row] << "\n";
2143 OS << " { ";
2144 for (unsigned i = 0, e = ConversionTable[Row].size(); i != e; i += 2)
2145 OS << OperandConversionKinds[ConversionTable[Row][i]] << ", "
2146 << (unsigned)(ConversionTable[Row][i + 1]) << ", ";
2147 OS << "CVT_Done },\n";
2148 }
2149
2150 OS << "};\n\n";
2151
2152 // Spit out the conversion driver function.
Daniel Dunbar71330282009-08-08 05:24:34 +00002153 OS << CvtOS.str();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002154
Chad Rosier738ea252012-08-30 17:59:25 +00002155 // Spit out the operand number lookup function.
2156 OS << OpOS.str();
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002157}
2158
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002159/// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
2160static void emitMatchClassEnumeration(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002161 std::forward_list<ClassInfo> &Infos,
2162 raw_ostream &OS) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002163 OS << "namespace {\n\n";
2164
2165 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
2166 << "/// instruction matching.\n";
2167 OS << "enum MatchClassKind {\n";
2168 OS << " InvalidMatchClass = 0,\n";
Tom Stellardb9f235e2016-02-05 19:59:33 +00002169 OS << " OptionalMatchClass = 1,\n";
Craig Topperf34dad92014-11-28 03:53:02 +00002170 for (const auto &CI : Infos) {
David Blaikied749e342014-11-28 20:35:57 +00002171 OS << " " << CI.Name << ", // ";
2172 if (CI.Kind == ClassInfo::Token) {
2173 OS << "'" << CI.ValueName << "'\n";
2174 } else if (CI.isRegisterClass()) {
2175 if (!CI.ValueName.empty())
2176 OS << "register class '" << CI.ValueName << "'\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002177 else
2178 OS << "derived register class\n";
2179 } else {
David Blaikied749e342014-11-28 20:35:57 +00002180 OS << "user defined class '" << CI.ValueName << "'\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002181 }
2182 }
2183 OS << " NumMatchClassKinds\n";
2184 OS << "};\n\n";
2185
2186 OS << "}\n\n";
2187}
2188
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002189/// emitValidateOperandClass - Emit the function to validate an operand class.
2190static void emitValidateOperandClass(AsmMatcherInfo &Info,
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002191 raw_ostream &OS) {
David Blaikie960ea3f2014-06-08 16:18:35 +00002192 OS << "static unsigned validateOperandClass(MCParsedAsmOperand &GOp, "
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002193 << "MatchClassKind Kind) {\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00002194 OS << " " << Info.Target.getName() << "Operand &Operand = ("
2195 << Info.Target.getName() << "Operand&)GOp;\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002196
Kevin Enderby1b87c802011-07-15 18:30:43 +00002197 // The InvalidMatchClass is not to match any operand.
2198 OS << " if (Kind == InvalidMatchClass)\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002199 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n\n";
Kevin Enderby1b87c802011-07-15 18:30:43 +00002200
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002201 // Check for Token operands first.
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002202 // FIXME: Use a more specific diagnostic type.
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002203 OS << " if (Operand.isToken())\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002204 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
2205 << " MCTargetAsmParser::Match_Success :\n"
2206 << " MCTargetAsmParser::Match_InvalidOperand;\n\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002207
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002208 // Check the user classes. We don't care what order since we're only
2209 // actually matching against one of them.
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002210 OS << " switch (Kind) {\n"
2211 " default: break;\n";
Craig Topperf34dad92014-11-28 03:53:02 +00002212 for (const auto &CI : Info.Classes) {
David Blaikied749e342014-11-28 20:35:57 +00002213 if (!CI.isUserClass())
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002214 continue;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002215
David Blaikied749e342014-11-28 20:35:57 +00002216 OS << " // '" << CI.ClassName << "' class\n";
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002217 OS << " case " << CI.Name << ":\n";
David Blaikied749e342014-11-28 20:35:57 +00002218 OS << " if (Operand." << CI.PredicateMethod << "())\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002219 OS << " return MCTargetAsmParser::Match_Success;\n";
David Blaikied749e342014-11-28 20:35:57 +00002220 if (!CI.DiagnosticType.empty())
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002221 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
David Blaikied749e342014-11-28 20:35:57 +00002222 << CI.DiagnosticType << ";\n";
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002223 else
2224 OS << " break;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002225 }
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002226 OS << " } // end switch (Kind)\n\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002227
Owen Anderson8a503f22012-07-16 23:20:09 +00002228 // Check for register operands, including sub-classes.
2229 OS << " if (Operand.isReg()) {\n";
2230 OS << " MatchClassKind OpKind;\n";
2231 OS << " switch (Operand.getReg()) {\n";
2232 OS << " default: OpKind = InvalidMatchClass; break;\n";
Craig Topper03ec8012014-11-25 20:11:31 +00002233 for (const auto &RC : Info.RegisterClasses)
Owen Anderson8a503f22012-07-16 23:20:09 +00002234 OS << " case " << Info.Target.getName() << "::"
Craig Topper03ec8012014-11-25 20:11:31 +00002235 << RC.first->getName() << ": OpKind = " << RC.second->Name
Owen Anderson8a503f22012-07-16 23:20:09 +00002236 << "; break;\n";
2237 OS << " }\n";
2238 OS << " return isSubclass(OpKind, Kind) ? "
2239 << "MCTargetAsmParser::Match_Success :\n "
2240 << " MCTargetAsmParser::Match_InvalidOperand;\n }\n\n";
2241
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002242 // Generic fallthrough match failure case for operands that don't have
2243 // specialized diagnostic types.
2244 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002245 OS << "}\n\n";
2246}
2247
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002248/// emitIsSubclass - Emit the subclass predicate function.
2249static void emitIsSubclass(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002250 std::forward_list<ClassInfo> &Infos,
Daniel Dunbar2587b612009-08-10 16:05:47 +00002251 raw_ostream &OS) {
Dmitri Gribenko8d302402012-09-15 20:22:05 +00002252 OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n";
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002253 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
Daniel Dunbar2587b612009-08-10 16:05:47 +00002254 OS << " if (A == B)\n";
2255 OS << " return true;\n\n";
2256
Craig Topper39311c72015-12-30 06:00:22 +00002257 bool EmittedSwitch = false;
Craig Topperf34dad92014-11-28 03:53:02 +00002258 for (const auto &A : Infos) {
Jim Grosbachba395922011-12-06 23:43:54 +00002259 std::vector<StringRef> SuperClasses;
Tom Stellardb9f235e2016-02-05 19:59:33 +00002260 if (A.IsOptional)
2261 SuperClasses.push_back("OptionalMatchClass");
Craig Topperf34dad92014-11-28 03:53:02 +00002262 for (const auto &B : Infos) {
David Blaikied749e342014-11-28 20:35:57 +00002263 if (&A != &B && A.isSubsetOf(B))
2264 SuperClasses.push_back(B.Name);
Daniel Dunbar2587b612009-08-10 16:05:47 +00002265 }
Jim Grosbachba395922011-12-06 23:43:54 +00002266
2267 if (SuperClasses.empty())
2268 continue;
2269
Craig Topper39311c72015-12-30 06:00:22 +00002270 // If this is the first SuperClass, emit the switch header.
2271 if (!EmittedSwitch) {
Craig Topper13b2a4e2015-12-30 06:00:24 +00002272 OS << " switch (A) {\n";
Craig Topper39311c72015-12-30 06:00:22 +00002273 OS << " default:\n";
2274 OS << " return false;\n";
2275 EmittedSwitch = true;
2276 }
2277
2278 OS << "\n case " << A.Name << ":\n";
Jim Grosbachba395922011-12-06 23:43:54 +00002279
2280 if (SuperClasses.size() == 1) {
Craig Topper13b2a4e2015-12-30 06:00:24 +00002281 OS << " return B == " << SuperClasses.back() << ";\n";
Jim Grosbachba395922011-12-06 23:43:54 +00002282 continue;
2283 }
2284
Aaron Ballmane59e3582013-07-15 16:53:32 +00002285 if (!SuperClasses.empty()) {
Craig Topper39311c72015-12-30 06:00:22 +00002286 OS << " switch (B) {\n";
2287 OS << " default: return false;\n";
Craig Topper77bd2b72015-12-30 06:00:20 +00002288 for (StringRef SC : SuperClasses)
Craig Topper39311c72015-12-30 06:00:22 +00002289 OS << " case " << SC << ": return true;\n";
2290 OS << " }\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002291 } else {
2292 // No case statement to emit
Craig Topper39311c72015-12-30 06:00:22 +00002293 OS << " return false;\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002294 }
Daniel Dunbar2587b612009-08-10 16:05:47 +00002295 }
Aaron Ballmane59e3582013-07-15 16:53:32 +00002296
Craig Topper39311c72015-12-30 06:00:22 +00002297 // If there were case statements emitted into the string stream write the
2298 // default.
Craig Topperf58323e2016-01-03 07:33:34 +00002299 if (EmittedSwitch)
2300 OS << " }\n";
2301 else
Aaron Ballmane59e3582013-07-15 16:53:32 +00002302 OS << " return false;\n";
2303
Daniel Dunbar2587b612009-08-10 16:05:47 +00002304 OS << "}\n\n";
2305}
2306
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002307/// emitMatchTokenString - Emit the function to match a token string to the
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002308/// appropriate match class value.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002309static void emitMatchTokenString(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002310 std::forward_list<ClassInfo> &Infos,
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002311 raw_ostream &OS) {
2312 // Construct the match list.
Chris Lattnerca5a3552010-09-06 02:01:51 +00002313 std::vector<StringMatcher::StringPair> Matches;
Craig Topperf34dad92014-11-28 03:53:02 +00002314 for (const auto &CI : Infos) {
David Blaikied749e342014-11-28 20:35:57 +00002315 if (CI.Kind == ClassInfo::Token)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002316 Matches.emplace_back(CI.ValueName, "return " + CI.Name + ";");
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002317 }
2318
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002319 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002320
Chris Lattnerca5a3552010-09-06 02:01:51 +00002321 StringMatcher("Name", Matches, OS).Emit();
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002322
2323 OS << " return InvalidMatchClass;\n";
2324 OS << "}\n\n";
2325}
Chris Lattner00e2e742009-08-08 20:02:57 +00002326
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002327/// emitMatchRegisterName - Emit the function to match a string to the target
Daniel Dunbard0470d72009-08-07 21:01:44 +00002328/// specific register enum.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002329static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
Daniel Dunbard0470d72009-08-07 21:01:44 +00002330 raw_ostream &OS) {
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002331 // Construct the match list.
Chris Lattnerca5a3552010-09-06 02:01:51 +00002332 std::vector<StringMatcher::StringPair> Matches;
David Blaikie9b613db2014-11-29 18:13:39 +00002333 const auto &Regs = Target.getRegBank().getRegisters();
2334 for (const CodeGenRegister &Reg : Regs) {
2335 if (Reg.TheDef->getValueAsString("AsmName").empty())
Daniel Dunbare2eec052009-07-17 18:51:11 +00002336 continue;
2337
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002338 Matches.emplace_back(Reg.TheDef->getValueAsString("AsmName"),
2339 "return " + utostr(Reg.EnumValue) + ";");
Daniel Dunbare2eec052009-07-17 18:51:11 +00002340 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002341
Chris Lattner60db0a62010-02-09 00:34:28 +00002342 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002343
Chris Lattnerca5a3552010-09-06 02:01:51 +00002344 StringMatcher("Name", Matches, OS).Emit();
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002345
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002346 OS << " return 0;\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +00002347 OS << "}\n\n";
Daniel Dunbard0470d72009-08-07 21:01:44 +00002348}
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002349
Dylan McKaybff960a2016-02-03 10:30:16 +00002350/// Emit the function to match a string to the target
2351/// specific register enum.
2352static void emitMatchRegisterAltName(CodeGenTarget &Target, Record *AsmParser,
2353 raw_ostream &OS) {
2354 // Construct the match list.
2355 std::vector<StringMatcher::StringPair> Matches;
2356 const auto &Regs = Target.getRegBank().getRegisters();
2357 for (const CodeGenRegister &Reg : Regs) {
2358
2359 auto AltNames = Reg.TheDef->getValueAsListOfStrings("AltNames");
2360
2361 for (auto AltName : AltNames) {
2362 AltName = StringRef(AltName).trim();
2363
2364 // don't handle empty alternative names
2365 if (AltName.empty())
2366 continue;
2367
2368 Matches.emplace_back(AltName,
2369 "return " + utostr(Reg.EnumValue) + ";");
2370 }
2371 }
2372
2373 OS << "static unsigned MatchRegisterAltName(StringRef Name) {\n";
2374
2375 StringMatcher("Name", Matches, OS).Emit();
2376
2377 OS << " return 0;\n";
2378 OS << "}\n\n";
2379}
2380
Daniel Sanders3ea92742014-05-21 10:11:24 +00002381static const char *getMinimalTypeForRange(uint64_t Range) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002382 assert(Range <= 0xFFFFFFFFFFFFFFFFULL && "Enum too large");
2383 if (Range > 0xFFFFFFFFULL)
2384 return "uint64_t";
Daniel Sanders3ea92742014-05-21 10:11:24 +00002385 if (Range > 0xFFFF)
2386 return "uint32_t";
2387 if (Range > 0xFF)
2388 return "uint16_t";
2389 return "uint8_t";
2390}
2391
2392static const char *getMinimalRequiredFeaturesType(const AsmMatcherInfo &Info) {
2393 uint64_t MaxIndex = Info.SubtargetFeatures.size();
2394 if (MaxIndex > 0)
2395 MaxIndex--;
2396 return getMinimalTypeForRange(1ULL << MaxIndex);
2397}
2398
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002399/// emitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
Daniel Dunbareefe8612010-07-19 05:44:09 +00002400/// definitions.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002401static void emitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
Daniel Dunbareefe8612010-07-19 05:44:09 +00002402 raw_ostream &OS) {
2403 OS << "// Flags for subtarget features that participate in "
2404 << "instruction matching.\n";
Daniel Sanders3ea92742014-05-21 10:11:24 +00002405 OS << "enum SubtargetFeatureFlag : " << getMinimalRequiredFeaturesType(Info)
2406 << " {\n";
Craig Topper42bd8192014-11-28 03:53:00 +00002407 for (const auto &SF : Info.SubtargetFeatures) {
David Blaikie9a9da992014-11-28 22:15:06 +00002408 const SubtargetFeatureInfo &SFI = SF.second;
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002409 OS << " " << SFI.getEnumName() << " = (1ULL << " << SFI.Index << "),\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00002410 }
2411 OS << " Feature_None = 0\n";
2412 OS << "};\n\n";
2413}
2414
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002415/// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
2416static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) {
2417 // Get the set of diagnostic types from all of the operand classes.
2418 std::set<StringRef> Types;
Craig Topper6e526f12016-01-03 07:33:30 +00002419 for (const auto &OpClassEntry : Info.AsmOperandClasses) {
2420 if (!OpClassEntry.second->DiagnosticType.empty())
2421 Types.insert(OpClassEntry.second->DiagnosticType);
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002422 }
2423
2424 if (Types.empty()) return;
2425
2426 // Now emit the enum entries.
Craig Topper6e526f12016-01-03 07:33:30 +00002427 for (StringRef Type : Types)
2428 OS << " Match_" << Type << ",\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002429 OS << " END_OPERAND_DIAGNOSTIC_TYPES\n";
2430}
2431
Jim Grosbach5117ef72012-04-24 22:40:08 +00002432/// emitGetSubtargetFeatureName - Emit the helper function to get the
2433/// user-level name for a subtarget feature.
2434static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
2435 OS << "// User-level names for subtarget features that participate in\n"
2436 << "// instruction matching.\n"
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002437 << "static const char *getSubtargetFeatureName(uint64_t Val) {\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002438 if (!Info.SubtargetFeatures.empty()) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002439 OS << " switch(Val) {\n";
Craig Topper42bd8192014-11-28 03:53:00 +00002440 for (const auto &SF : Info.SubtargetFeatures) {
David Blaikie9a9da992014-11-28 22:15:06 +00002441 const SubtargetFeatureInfo &SFI = SF.second;
Aaron Ballmane59e3582013-07-15 16:53:32 +00002442 // FIXME: Totally just a placeholder name to get the algorithm working.
2443 OS << " case " << SFI.getEnumName() << ": return \""
2444 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
2445 }
2446 OS << " default: return \"(unknown)\";\n";
2447 OS << " }\n";
2448 } else {
2449 // Nothing to emit, so skip the switch
2450 OS << " return \"(unknown)\";\n";
Jim Grosbach5117ef72012-04-24 22:40:08 +00002451 }
Aaron Ballmane59e3582013-07-15 16:53:32 +00002452 OS << "}\n\n";
Jim Grosbach5117ef72012-04-24 22:40:08 +00002453}
2454
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002455/// emitComputeAvailableFeatures - Emit the function to compute the list of
Daniel Dunbareefe8612010-07-19 05:44:09 +00002456/// available features given a subtarget.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002457static void emitComputeAvailableFeatures(AsmMatcherInfo &Info,
Daniel Dunbareefe8612010-07-19 05:44:09 +00002458 raw_ostream &OS) {
2459 std::string ClassName =
2460 Info.AsmParser->getValueAsString("AsmParserClassName");
2461
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002462 OS << "uint64_t " << Info.Target.getName() << ClassName << "::\n"
Michael Kupersteindb0712f2015-05-26 10:47:10 +00002463 << "ComputeAvailableFeatures(const FeatureBitset& FB) const {\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002464 OS << " uint64_t Features = 0;\n";
Craig Topper42bd8192014-11-28 03:53:00 +00002465 for (const auto &SF : Info.SubtargetFeatures) {
David Blaikie9a9da992014-11-28 22:15:06 +00002466 const SubtargetFeatureInfo &SFI = SF.second;
Evan Cheng4d1ca962011-07-08 01:53:10 +00002467
2468 OS << " if (";
Jim Grosbach56e63262012-04-17 00:01:04 +00002469 std::string CondStorage =
2470 SFI.TheDef->getValueAsString("AssemblerCondString");
Evan Cheng1a6d5512011-07-08 18:04:22 +00002471 StringRef Conds = CondStorage;
Evan Cheng4d1ca962011-07-08 01:53:10 +00002472 std::pair<StringRef,StringRef> Comma = Conds.split(',');
2473 bool First = true;
2474 do {
2475 if (!First)
2476 OS << " && ";
2477
2478 bool Neg = false;
2479 StringRef Cond = Comma.first;
2480 if (Cond[0] == '!') {
2481 Neg = true;
2482 Cond = Cond.substr(1);
2483 }
2484
Michael Kupersteindb0712f2015-05-26 10:47:10 +00002485 OS << "(";
Evan Cheng4d1ca962011-07-08 01:53:10 +00002486 if (Neg)
Michael Kupersteindb0712f2015-05-26 10:47:10 +00002487 OS << "!";
2488 OS << "FB[" << Info.Target.getName() << "::" << Cond << "])";
Evan Cheng4d1ca962011-07-08 01:53:10 +00002489
2490 if (Comma.second.empty())
2491 break;
2492
2493 First = false;
2494 Comma = Comma.second.split(',');
2495 } while (true);
2496
2497 OS << ")\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002498 OS << " Features |= " << SFI.getEnumName() << ";\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00002499 }
2500 OS << " return Features;\n";
2501 OS << "}\n\n";
2502}
2503
Chris Lattner43690072010-10-30 20:15:02 +00002504static std::string GetAliasRequiredFeatures(Record *R,
2505 const AsmMatcherInfo &Info) {
Chris Lattner2cb092d2010-10-30 19:23:13 +00002506 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
Chris Lattner2cb092d2010-10-30 19:23:13 +00002507 std::string Result;
2508 unsigned NumFeatures = 0;
2509 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
David Blaikie9a9da992014-11-28 22:15:06 +00002510 const SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002511
Craig Topper24064772014-04-15 07:20:03 +00002512 if (!F)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002513 PrintFatalError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
Chris Lattner517dc952010-11-01 02:09:21 +00002514 "' is not marked as an AssemblerPredicate!");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002515
Chris Lattner517dc952010-11-01 02:09:21 +00002516 if (NumFeatures)
2517 Result += '|';
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002518
Chris Lattner517dc952010-11-01 02:09:21 +00002519 Result += F->getEnumName();
2520 ++NumFeatures;
Chris Lattner2cb092d2010-10-30 19:23:13 +00002521 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002522
Chris Lattner2cb092d2010-10-30 19:23:13 +00002523 if (NumFeatures > 1)
2524 Result = '(' + Result + ')';
2525 return Result;
2526}
2527
Chad Rosier9f7a2212013-04-18 22:35:36 +00002528static void emitMnemonicAliasVariant(raw_ostream &OS,const AsmMatcherInfo &Info,
2529 std::vector<Record*> &Aliases,
2530 unsigned Indent = 0,
2531 StringRef AsmParserVariantName = StringRef()){
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002532 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
2533 // iteration order of the map is stable.
2534 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002535
Craig Topper6e526f12016-01-03 07:33:30 +00002536 for (Record *R : Aliases) {
Chad Rosier9f7a2212013-04-18 22:35:36 +00002537 // FIXME: Allow AssemblerVariantName to be a comma separated list.
2538 std::string AsmVariantName = R->getValueAsString("AsmVariantName");
2539 if (AsmVariantName != AsmParserVariantName)
2540 continue;
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002541 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00002542 }
Chad Rosier9f7a2212013-04-18 22:35:36 +00002543 if (AliasesFromMnemonic.empty())
2544 return;
Vladimir Medic75429ad2013-07-16 09:22:38 +00002545
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002546 // Process each alias a "from" mnemonic at a time, building the code executed
2547 // by the string remapper.
2548 std::vector<StringMatcher::StringPair> Cases;
Craig Topper6e526f12016-01-03 07:33:30 +00002549 for (const auto &AliasEntry : AliasesFromMnemonic) {
2550 const std::vector<Record*> &ToVec = AliasEntry.second;
Chris Lattner2cb092d2010-10-30 19:23:13 +00002551
2552 // Loop through each alias and emit code that handles each case. If there
2553 // are two instructions without predicates, emit an error. If there is one,
2554 // emit it last.
2555 std::string MatchCode;
2556 int AliasWithNoPredicate = -1;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002557
Chris Lattner2cb092d2010-10-30 19:23:13 +00002558 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
2559 Record *R = ToVec[i];
Chris Lattner43690072010-10-30 20:15:02 +00002560 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002561
Chris Lattner2cb092d2010-10-30 19:23:13 +00002562 // If this unconditionally matches, remember it for later and diagnose
2563 // duplicates.
2564 if (FeatureMask.empty()) {
2565 if (AliasWithNoPredicate != -1) {
2566 // We can't have two aliases from the same mnemonic with no predicate.
2567 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
2568 "two MnemonicAliases with the same 'from' mnemonic!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002569 PrintFatalError(R->getLoc(), "this is the other MnemonicAlias.");
Chris Lattner2cb092d2010-10-30 19:23:13 +00002570 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002571
Chris Lattner2cb092d2010-10-30 19:23:13 +00002572 AliasWithNoPredicate = i;
2573 continue;
2574 }
Craig Topper6e526f12016-01-03 07:33:30 +00002575 if (R->getValueAsString("ToMnemonic") == AliasEntry.first)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002576 PrintFatalError(R->getLoc(), "MnemonicAlias to the same string");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002577
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00002578 if (!MatchCode.empty())
2579 MatchCode += "else ";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002580 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
Chris Lattner2cb092d2010-10-30 19:23:13 +00002581 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002582 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002583
Chris Lattner2cb092d2010-10-30 19:23:13 +00002584 if (AliasWithNoPredicate != -1) {
2585 Record *R = ToVec[AliasWithNoPredicate];
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00002586 if (!MatchCode.empty())
2587 MatchCode += "else\n ";
2588 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattner2cb092d2010-10-30 19:23:13 +00002589 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002590
Chris Lattner2cb092d2010-10-30 19:23:13 +00002591 MatchCode += "return;";
2592
Craig Topper6e526f12016-01-03 07:33:30 +00002593 Cases.push_back(std::make_pair(AliasEntry.first, MatchCode));
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002594 }
Chad Rosier9f7a2212013-04-18 22:35:36 +00002595 StringMatcher("Mnemonic", Cases, OS).Emit(Indent);
2596}
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002597
Chad Rosier9f7a2212013-04-18 22:35:36 +00002598/// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
2599/// emit a function for them and return true, otherwise return false.
2600static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info,
2601 CodeGenTarget &Target) {
2602 // Ignore aliases when match-prefix is set.
2603 if (!MatchPrefix.empty())
2604 return false;
2605
2606 std::vector<Record*> Aliases =
2607 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
2608 if (Aliases.empty()) return false;
2609
2610 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002611 "uint64_t Features, unsigned VariantID) {\n";
Chad Rosier9f7a2212013-04-18 22:35:36 +00002612 OS << " switch (VariantID) {\n";
2613 unsigned VariantCount = Target.getAsmParserVariantCount();
2614 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2615 Record *AsmVariant = Target.getAsmParserVariant(VC);
2616 int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant");
2617 std::string AsmParserVariantName = AsmVariant->getValueAsString("Name");
2618 OS << " case " << AsmParserVariantNo << ":\n";
2619 emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2,
2620 AsmParserVariantName);
2621 OS << " break;\n";
2622 }
2623 OS << " }\n";
2624
2625 // Emit aliases that apply to all variants.
2626 emitMnemonicAliasVariant(OS, Info, Aliases);
2627
Daniel Dunbare46bc4c2011-01-18 01:59:30 +00002628 OS << "}\n\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002629
Chris Lattner477fba4f2010-10-30 18:48:18 +00002630 return true;
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00002631}
2632
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002633static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002634 const AsmMatcherInfo &Info, StringRef ClassName,
2635 StringToOffsetTable &StringTable,
Craig Topperfd2c6a32015-12-31 08:18:23 +00002636 unsigned MaxMnemonicIndex, bool HasMnemonicFirst) {
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002637 unsigned MaxMask = 0;
Craig Topper869cd5f2015-12-31 08:18:20 +00002638 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
2639 MaxMask |= OMI.OperandMask;
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002640 }
2641
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002642 // Emit the static custom operand parsing table;
2643 OS << "namespace {\n";
2644 OS << " struct OperandMatchEntry {\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002645 OS << " " << getMinimalRequiredFeaturesType(Info)
2646 << " RequiredFeatures;\n";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002647 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
2648 << " Mnemonic;\n";
David Blaikied749e342014-11-28 20:35:57 +00002649 OS << " " << getMinimalTypeForRange(std::distance(
2650 Info.Classes.begin(), Info.Classes.end())) << " Class;\n";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002651 OS << " " << getMinimalTypeForRange(MaxMask)
2652 << " OperandMask;\n\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002653 OS << " StringRef getMnemonic() const {\n";
2654 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2655 OS << " MnemonicTable[Mnemonic]);\n";
2656 OS << " }\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002657 OS << " };\n\n";
2658
2659 OS << " // Predicate for searching for an opcode.\n";
2660 OS << " struct LessOpcodeOperand {\n";
2661 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002662 OS << " return LHS.getMnemonic() < RHS;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002663 OS << " }\n";
2664 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002665 OS << " return LHS < RHS.getMnemonic();\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002666 OS << " }\n";
2667 OS << " bool operator()(const OperandMatchEntry &LHS,";
2668 OS << " const OperandMatchEntry &RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002669 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002670 OS << " }\n";
2671 OS << " };\n";
2672
2673 OS << "} // end anonymous namespace.\n\n";
2674
2675 OS << "static const OperandMatchEntry OperandMatchTable["
2676 << Info.OperandMatchInfo.size() << "] = {\n";
2677
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002678 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
Craig Topper869cd5f2015-12-31 08:18:20 +00002679 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002680 const MatchableInfo &II = *OMI.MI;
2681
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002682 OS << " { ";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002683
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002684 // Write the required features mask.
2685 if (!II.RequiredFeatures.empty()) {
2686 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002687 if (i) OS << "|";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002688 OS << II.RequiredFeatures[i]->getEnumName();
2689 }
2690 } else
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002691 OS << "0";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002692
2693 // Store a pascal-style length byte in the mnemonic.
2694 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2695 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2696 << " /* " << II.Mnemonic << " */, ";
2697
2698 OS << OMI.CI->Name;
2699
2700 OS << ", " << OMI.OperandMask;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002701 OS << " /* ";
2702 bool printComma = false;
2703 for (int i = 0, e = 31; i !=e; ++i)
2704 if (OMI.OperandMask & (1 << i)) {
2705 if (printComma)
2706 OS << ", ";
2707 OS << i;
2708 printComma = true;
2709 }
2710 OS << " */";
2711
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002712 OS << " },\n";
2713 }
2714 OS << "};\n\n";
2715
2716 // Emit the operand class switch to call the correct custom parser for
2717 // the found operand class.
Jim Grosbach861e49c2011-02-12 01:34:40 +00002718 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2719 << Target.getName() << ClassName << "::\n"
David Blaikie960ea3f2014-06-08 16:18:35 +00002720 << "tryCustomParseOperand(OperandVector"
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002721 << " &Operands,\n unsigned MCK) {\n\n"
2722 << " switch(MCK) {\n";
2723
Craig Topperf34dad92014-11-28 03:53:02 +00002724 for (const auto &CI : Info.Classes) {
David Blaikied749e342014-11-28 20:35:57 +00002725 if (CI.ParserMethod.empty())
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002726 continue;
David Blaikied749e342014-11-28 20:35:57 +00002727 OS << " case " << CI.Name << ":\n"
2728 << " return " << CI.ParserMethod << "(Operands);\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002729 }
2730
2731 OS << " default:\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002732 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002733 OS << " }\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002734 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002735 OS << "}\n\n";
2736
2737 // Emit the static custom operand parser. This code is very similar with
2738 // the other matcher. Also use MatchResultTy here just in case we go for
2739 // a better error handling.
Jim Grosbach861e49c2011-02-12 01:34:40 +00002740 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002741 << Target.getName() << ClassName << "::\n"
David Blaikie960ea3f2014-06-08 16:18:35 +00002742 << "MatchOperandParserImpl(OperandVector"
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002743 << " &Operands,\n StringRef Mnemonic) {\n";
2744
2745 // Emit code to get the available features.
2746 OS << " // Get the current feature set.\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002747 OS << " uint64_t AvailableFeatures = getAvailableFeatures();\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002748
2749 OS << " // Get the next operand index.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00002750 OS << " unsigned NextOpNum = Operands.size()"
2751 << (HasMnemonicFirst ? " - 1" : "") << ";\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002752
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002753 // Emit code to search the table.
2754 OS << " // Search the table.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00002755 if (HasMnemonicFirst) {
2756 OS << " auto MnemonicRange =\n";
2757 OS << " std::equal_range(std::begin(OperandMatchTable), "
2758 "std::end(OperandMatchTable),\n";
2759 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2760 } else {
2761 OS << " auto MnemonicRange = std::make_pair(std::begin(OperandMatchTable),"
2762 " std::end(OperandMatchTable));\n";
2763 OS << " if (!Mnemonic.empty())\n";
2764 OS << " MnemonicRange =\n";
2765 OS << " std::equal_range(std::begin(OperandMatchTable), "
2766 "std::end(OperandMatchTable),\n";
2767 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2768 }
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002769
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002770 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002771 OS << " return MatchOperand_NoMatch;\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002772
2773 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2774 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2775
2776 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002777 OS << " assert(Mnemonic == it->getMnemonic());\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002778
2779 // Emit check that the required features are available.
2780 OS << " // check if the available features match\n";
2781 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2782 << "!= it->RequiredFeatures) {\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002783 OS << " continue;\n";
2784 OS << " }\n\n";
2785
2786 // Emit check to ensure the operand number matches.
2787 OS << " // check if the operand in question has a custom parser.\n";
2788 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2789 OS << " continue;\n\n";
2790
2791 // Emit call to the custom parser method
2792 OS << " // call custom parse method to handle the operand\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002793 OS << " OperandMatchResultTy Result = ";
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002794 OS << "tryCustomParseOperand(Operands, it->Class);\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002795 OS << " if (Result != MatchOperand_NoMatch)\n";
2796 OS << " return Result;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002797 OS << " }\n\n";
2798
Jim Grosbach861e49c2011-02-12 01:34:40 +00002799 OS << " // Okay, we had no match.\n";
2800 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002801 OS << "}\n\n";
2802}
2803
Daniel Dunbard0470d72009-08-07 21:01:44 +00002804void AsmMatcherEmitter::run(raw_ostream &OS) {
Chris Lattner77d369c2010-12-13 00:23:57 +00002805 CodeGenTarget Target(Records);
Daniel Dunbard0470d72009-08-07 21:01:44 +00002806 Record *AsmParser = Target.getAsmParser();
2807 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2808
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002809 // Compute the information on the instructions to match.
Chris Lattner77d369c2010-12-13 00:23:57 +00002810 AsmMatcherInfo Info(AsmParser, Target, Records);
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002811 Info.buildInfo();
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002812
Daniel Dunbar3b8a4662010-02-02 23:46:36 +00002813 // Sort the instruction table using the partial order on classes. We use
2814 // stable_sort to ensure that ambiguous instructions are still
2815 // deterministically ordered.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002816 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2817 [](const std::unique_ptr<MatchableInfo> &a,
2818 const std::unique_ptr<MatchableInfo> &b){
2819 return *a < *b;});
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002820
Oliver Stannard7772f022016-01-25 10:20:19 +00002821#ifndef NDEBUG
2822 // Verify that the table is now sorted
2823 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
2824 ++I) {
2825 for (auto J = I; J != E; ++J) {
2826 assert(!(**J < **I));
2827 }
2828 }
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +00002829#endif // NDEBUG
Oliver Stannard7772f022016-01-25 10:20:19 +00002830
Daniel Dunbar71330282009-08-08 05:24:34 +00002831 DEBUG_WITH_TYPE("instruction_info", {
Craig Topperf34dad92014-11-28 03:53:02 +00002832 for (const auto &MI : Info.Matchables)
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002833 MI->dump();
Daniel Dunbare10787e2009-08-07 08:26:05 +00002834 });
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002835
Chris Lattnerad776812010-11-01 05:06:45 +00002836 // Check for ambiguous matchables.
Chris Lattnerc0658cb2010-09-06 21:28:52 +00002837 DEBUG_WITH_TYPE("ambiguous_instrs", {
2838 unsigned NumAmbiguous = 0;
David Blaikie9a6f2832014-12-22 21:26:38 +00002839 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
2840 ++I) {
2841 for (auto J = std::next(I); J != E; ++J) {
2842 const MatchableInfo &A = **I;
2843 const MatchableInfo &B = **J;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002844
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002845 if (A.couldMatchAmbiguouslyWith(B)) {
Chris Lattnerad776812010-11-01 05:06:45 +00002846 errs() << "warning: ambiguous matchables:\n";
Chris Lattnerc0658cb2010-09-06 21:28:52 +00002847 A.dump();
2848 errs() << "\nis incomparable with:\n";
2849 B.dump();
2850 errs() << "\n\n";
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00002851 ++NumAmbiguous;
2852 }
Daniel Dunbarf573b562009-08-09 06:05:33 +00002853 }
Daniel Dunbar3239f022009-08-09 04:00:06 +00002854 }
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00002855 if (NumAmbiguous)
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002856 errs() << "warning: " << NumAmbiguous
Chris Lattnerad776812010-11-01 05:06:45 +00002857 << " ambiguous matchables!\n";
Chris Lattnerc0658cb2010-09-06 21:28:52 +00002858 });
Daniel Dunbar3239f022009-08-09 04:00:06 +00002859
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002860 // Compute the information on the custom operand parsing.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002861 Info.buildOperandMatchInfo();
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002862
Craig Topperfd2c6a32015-12-31 08:18:23 +00002863 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
Sam Kolton5f10a132016-05-06 11:31:17 +00002864 bool HasOptionalOperands = Info.hasOptionalOperands();
Craig Topperfd2c6a32015-12-31 08:18:23 +00002865
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00002866 // Write the output.
2867
Chris Lattner3e4582a2010-09-06 19:11:01 +00002868 // Information for the class declaration.
2869 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2870 OS << "#undef GET_ASSEMBLER_HEADER\n";
Jim Grosbach860a84d2011-02-11 21:31:55 +00002871 OS << " // This should be included into the middle of the declaration of\n";
Evan Cheng11424442011-07-26 00:24:13 +00002872 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002873 OS << " uint64_t ComputeAvailableFeatures(const FeatureBitset& FB) const;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00002874 if (HasOptionalOperands) {
2875 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
2876 << "unsigned Opcode,\n"
2877 << " const OperandVector &Operands,\n"
2878 << " const SmallBitVector &OptionalOperandsMask);\n";
2879 } else {
2880 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
2881 << "unsigned Opcode,\n"
2882 << " const OperandVector &Operands);\n";
2883 }
Chad Rosier380a74a2012-10-02 00:25:57 +00002884 OS << " void convertToMapAndConstraints(unsigned Kind,\n ";
David Blaikie960ea3f2014-06-08 16:18:35 +00002885 OS << " const OperandVector &Operands) override;\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00002886 if (HasMnemonicFirst)
2887 OS << " bool mnemonicIsValid(StringRef Mnemonic, unsigned VariantID);\n";
Craig Toppera5754e62015-01-03 08:16:29 +00002888 OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002889 << " MCInst &Inst,\n"
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002890 << " uint64_t &ErrorInfo,"
2891 << " bool matchingInlineAsm,\n"
Chad Rosier380a74a2012-10-02 00:25:57 +00002892 << " unsigned VariantID = 0);\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002893
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00002894 if (!Info.OperandMatchInfo.empty()) {
Jim Grosbach861e49c2011-02-12 01:34:40 +00002895 OS << "\n enum OperandMatchResultTy {\n";
2896 OS << " MatchOperand_Success, // operand matched successfully\n";
2897 OS << " MatchOperand_NoMatch, // operand did not match\n";
2898 OS << " MatchOperand_ParseFail // operand matched but had errors\n";
2899 OS << " };\n";
2900 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00002901 OS << " OperandVector &Operands,\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002902 OS << " StringRef Mnemonic);\n";
2903
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002904 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00002905 OS << " OperandVector &Operands,\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002906 OS << " unsigned MCK);\n\n";
2907 }
2908
Chris Lattner3e4582a2010-09-06 19:11:01 +00002909 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2910
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002911 // Emit the operand match diagnostic enum names.
2912 OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
2913 OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
2914 emitOperandDiagnosticTypes(Info, OS);
2915 OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
2916
Chris Lattner3e4582a2010-09-06 19:11:01 +00002917 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2918 OS << "#undef GET_REGISTER_MATCHER\n\n";
2919
Daniel Dunbareefe8612010-07-19 05:44:09 +00002920 // Emit the subtarget feature enumeration.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002921 emitSubtargetFeatureFlagEnumeration(Info, OS);
Daniel Dunbareefe8612010-07-19 05:44:09 +00002922
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00002923 // Emit the function to match a register name to number.
Akira Hatanaka7605630c2012-08-17 20:16:42 +00002924 // This should be omitted for Mips target
2925 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName"))
2926 emitMatchRegisterName(Target, AsmParser, OS);
Chris Lattner3e4582a2010-09-06 19:11:01 +00002927
Dylan McKaybff960a2016-02-03 10:30:16 +00002928 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterAltName"))
2929 emitMatchRegisterAltName(Target, AsmParser, OS);
2930
Chris Lattner3e4582a2010-09-06 19:11:01 +00002931 OS << "#endif // GET_REGISTER_MATCHER\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002932
Craig Topper3ec7c2a2012-04-25 06:56:34 +00002933 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
2934 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00002935
Jim Grosbach5117ef72012-04-24 22:40:08 +00002936 // Generate the helper function to get the names for subtarget features.
2937 emitGetSubtargetFeatureName(Info, OS);
2938
Craig Topper3ec7c2a2012-04-25 06:56:34 +00002939 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
2940
2941 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2942 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
2943
Chris Lattner477fba4f2010-10-30 18:48:18 +00002944 // Generate the function that remaps for mnemonic aliases.
Chad Rosier9f7a2212013-04-18 22:35:36 +00002945 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002946
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002947 // Generate the convertToMCInst function to convert operands into an MCInst.
2948 // Also, generate the convertToMapAndConstraints function for MS-style inline
2949 // assembly. The latter doesn't actually generate a MCInst.
Sam Kolton5f10a132016-05-06 11:31:17 +00002950 emitConvertFuncs(Target, ClassName, Info.Matchables, HasMnemonicFirst,
2951 HasOptionalOperands, OS);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002952
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002953 // Emit the enumeration for classes which participate in matching.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002954 emitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002955
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002956 // Emit the routine to match token strings to their match class.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002957 emitMatchTokenString(Target, Info.Classes, OS);
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002958
Daniel Dunbar2587b612009-08-10 16:05:47 +00002959 // Emit the subclass predicate routine.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002960 emitIsSubclass(Target, Info.Classes, OS);
Daniel Dunbar2587b612009-08-10 16:05:47 +00002961
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002962 // Emit the routine to validate an operand against a match class.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002963 emitValidateOperandClass(Info, OS);
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002964
Daniel Dunbareefe8612010-07-19 05:44:09 +00002965 // Emit the available features compute function.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002966 emitComputeAvailableFeatures(Info, OS);
Daniel Dunbareefe8612010-07-19 05:44:09 +00002967
Craig Toppere2cfeb32012-09-18 06:10:45 +00002968 StringToOffsetTable StringTable;
2969
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002970 size_t MaxNumOperands = 0;
Craig Toppere2cfeb32012-09-18 06:10:45 +00002971 unsigned MaxMnemonicIndex = 0;
Joey Gouly0e76fa72013-09-12 10:28:05 +00002972 bool HasDeprecation = false;
Craig Topperf34dad92014-11-28 03:53:02 +00002973 for (const auto &MI : Info.Matchables) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002974 MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
2975 HasDeprecation |= MI->HasDeprecation;
Craig Toppere2cfeb32012-09-18 06:10:45 +00002976
2977 // Store a pascal-style length byte in the mnemonic.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002978 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
Craig Toppere2cfeb32012-09-18 06:10:45 +00002979 MaxMnemonicIndex = std::max(MaxMnemonicIndex,
2980 StringTable.GetOrAddStringOffset(LenMnemonic, false));
2981 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002982
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002983 OS << "static const char *const MnemonicTable =\n";
2984 StringTable.EmitString(OS);
2985 OS << ";\n\n";
2986
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002987 // Emit the static match table; unused classes get initalized to 0 which is
2988 // guaranteed to be InvalidMatchClass.
2989 //
2990 // FIXME: We can reduce the size of this table very easily. First, we change
2991 // it so that store the kinds in separate bit-fields for each index, which
2992 // only needs to be the max width used for classes at that index (we also need
2993 // to reject based on this during classification). If we then make sure to
2994 // order the match kinds appropriately (putting mnemonics last), then we
2995 // should only end up using a few bits for each class, especially the ones
2996 // following the mnemonic.
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00002997 OS << "namespace {\n";
2998 OS << " struct MatchEntry {\n";
Craig Toppere2cfeb32012-09-18 06:10:45 +00002999 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
3000 << " Mnemonic;\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003001 OS << " uint16_t Opcode;\n";
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003002 OS << " " << getMinimalTypeForRange(Info.Matchables.size())
3003 << " ConvertFn;\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003004 OS << " " << getMinimalRequiredFeaturesType(Info)
3005 << " RequiredFeatures;\n";
David Blaikied749e342014-11-28 20:35:57 +00003006 OS << " " << getMinimalTypeForRange(
3007 std::distance(Info.Classes.begin(), Info.Classes.end()))
3008 << " Classes[" << MaxNumOperands << "];\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003009 OS << " StringRef getMnemonic() const {\n";
3010 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
3011 OS << " MnemonicTable[Mnemonic]);\n";
3012 OS << " }\n";
Chris Lattner81301972010-09-06 21:22:45 +00003013 OS << " };\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003014
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003015 OS << " // Predicate for searching for an opcode.\n";
Chris Lattner81301972010-09-06 21:22:45 +00003016 OS << " struct LessOpcode {\n";
3017 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003018 OS << " return LHS.getMnemonic() < RHS;\n";
Chris Lattner81301972010-09-06 21:22:45 +00003019 OS << " }\n";
3020 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003021 OS << " return LHS < RHS.getMnemonic();\n";
Chris Lattner81301972010-09-06 21:22:45 +00003022 OS << " }\n";
Chris Lattner62823362010-09-07 06:10:48 +00003023 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003024 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Chris Lattner62823362010-09-07 06:10:48 +00003025 OS << " }\n";
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003026 OS << " };\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003027
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003028 OS << "} // end anonymous namespace.\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003029
Craig Topper690d8ea2013-07-24 07:33:14 +00003030 unsigned VariantCount = Target.getAsmParserVariantCount();
3031 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3032 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topper690d8ea2013-07-24 07:33:14 +00003033 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003034
Craig Topper690d8ea2013-07-24 07:33:14 +00003035 OS << "static const MatchEntry MatchTable" << VC << "[] = {\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003036
Craig Topperf34dad92014-11-28 03:53:02 +00003037 for (const auto &MI : Info.Matchables) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003038 if (MI->AsmVariantID != AsmVariantNo)
Craig Topper690d8ea2013-07-24 07:33:14 +00003039 continue;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003040
Craig Topper690d8ea2013-07-24 07:33:14 +00003041 // Store a pascal-style length byte in the mnemonic.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003042 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
Craig Topper690d8ea2013-07-24 07:33:14 +00003043 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003044 << " /* " << MI->Mnemonic << " */, "
3045 << Target.getName() << "::"
3046 << MI->getResultInst()->TheDef->getName() << ", "
3047 << MI->ConversionFnKind << ", ";
Craig Topper690d8ea2013-07-24 07:33:14 +00003048
3049 // Write the required features mask.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003050 if (!MI->RequiredFeatures.empty()) {
3051 for (unsigned i = 0, e = MI->RequiredFeatures.size(); i != e; ++i) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003052 if (i) OS << "|";
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003053 OS << MI->RequiredFeatures[i]->getEnumName();
Craig Topper690d8ea2013-07-24 07:33:14 +00003054 }
3055 } else
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003056 OS << "0";
Craig Topper690d8ea2013-07-24 07:33:14 +00003057
3058 OS << ", { ";
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003059 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
3060 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
Craig Topper690d8ea2013-07-24 07:33:14 +00003061
3062 if (i) OS << ", ";
3063 OS << Op.Class->Name;
Daniel Dunbareefe8612010-07-19 05:44:09 +00003064 }
Craig Topper690d8ea2013-07-24 07:33:14 +00003065 OS << " }, },\n";
Craig Topper4de73732012-04-02 07:48:39 +00003066 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003067
Craig Topper690d8ea2013-07-24 07:33:14 +00003068 OS << "};\n\n";
3069 }
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003070
Bob Wilson770681d72011-01-26 21:43:46 +00003071 // A method to determine if a mnemonic is in the list.
Craig Topperfd2c6a32015-12-31 08:18:23 +00003072 if (HasMnemonicFirst) {
3073 OS << "bool " << Target.getName() << ClassName << "::\n"
3074 << "mnemonicIsValid(StringRef Mnemonic, unsigned VariantID) {\n";
3075 OS << " // Find the appropriate table for this asm variant.\n";
3076 OS << " const MatchEntry *Start, *End;\n";
3077 OS << " switch (VariantID) {\n";
3078 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
3079 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3080 Record *AsmVariant = Target.getAsmParserVariant(VC);
3081 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3082 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3083 << "); End = std::end(MatchTable" << VC << "); break;\n";
3084 }
3085 OS << " }\n";
3086 OS << " // Search the table.\n";
3087 OS << " auto MnemonicRange = ";
3088 OS << "std::equal_range(Start, End, Mnemonic, LessOpcode());\n";
3089 OS << " return MnemonicRange.first != MnemonicRange.second;\n";
3090 OS << "}\n\n";
Craig Topper690d8ea2013-07-24 07:33:14 +00003091 }
Bob Wilson770681d72011-01-26 21:43:46 +00003092
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003093 // Finally, build the match function.
David Blaikie960ea3f2014-06-08 16:18:35 +00003094 OS << "unsigned " << Target.getName() << ClassName << "::\n"
Craig Toppera5754e62015-01-03 08:16:29 +00003095 << "MatchInstructionImpl(const OperandVector &Operands,\n";
3096 OS << " MCInst &Inst, uint64_t &ErrorInfo,\n"
3097 << " bool matchingInlineAsm, unsigned VariantID) {\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00003098
Chad Rosiereac13a32012-08-30 21:43:05 +00003099 OS << " // Eliminate obvious mismatches.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003100 OS << " if (Operands.size() > "
3101 << (MaxNumOperands + HasMnemonicFirst) << ") {\n";
3102 OS << " ErrorInfo = "
3103 << (MaxNumOperands + HasMnemonicFirst) << ";\n";
Chad Rosiereac13a32012-08-30 21:43:05 +00003104 OS << " return Match_InvalidOperand;\n";
3105 OS << " }\n\n";
3106
Daniel Dunbareefe8612010-07-19 05:44:09 +00003107 // Emit code to get the available features.
3108 OS << " // Get the current feature set.\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003109 OS << " uint64_t AvailableFeatures = getAvailableFeatures();\n\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00003110
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00003111 OS << " // Get the instruction mnemonic, which is the first token.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003112 if (HasMnemonicFirst) {
3113 OS << " StringRef Mnemonic = ((" << Target.getName()
3114 << "Operand&)*Operands[0]).getToken();\n\n";
3115 } else {
3116 OS << " StringRef Mnemonic;\n";
3117 OS << " if (Operands[0]->isToken())\n";
3118 OS << " Mnemonic = ((" << Target.getName()
3119 << "Operand&)*Operands[0]).getToken();\n\n";
3120 }
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00003121
Chris Lattner477fba4f2010-10-30 18:48:18 +00003122 if (HasMnemonicAliases) {
3123 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
Chad Rosier9f7a2212013-04-18 22:35:36 +00003124 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n";
Chris Lattner477fba4f2010-10-30 18:48:18 +00003125 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00003126
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003127 // Emit code to compute the class list for this operand vector.
Chris Lattnerabfe4222010-09-06 23:37:39 +00003128 OS << " // Some state to try to produce better error messages.\n";
Jim Grosbach120a96a2011-08-15 23:03:29 +00003129 OS << " bool HadMatchOtherThanFeatures = false;\n";
Jim Grosbachd152e2c2011-08-16 20:12:35 +00003130 OS << " bool HadMatchOtherThanPredicate = false;\n";
Jim Grosbach120a96a2011-08-15 23:03:29 +00003131 OS << " unsigned RetCode = Match_InvalidOperand;\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003132 OS << " uint64_t MissingFeatures = ~0ULL;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003133 if (HasOptionalOperands) {
3134 OS << " SmallBitVector OptionalOperandsMask(" << MaxNumOperands << ");\n";
3135 }
Jim Grosbach860a84d2011-02-11 21:31:55 +00003136 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
Chris Lattnerabfe4222010-09-06 23:37:39 +00003137 OS << " // wrong for all instances of the instruction.\n";
Tom Stellard5698d632015-03-05 19:46:55 +00003138 OS << " ErrorInfo = ~0ULL;\n";
Chris Lattner81301972010-09-06 21:22:45 +00003139
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003140 // Emit code to search the table.
Craig Topper690d8ea2013-07-24 07:33:14 +00003141 OS << " // Find the appropriate table for this asm variant.\n";
3142 OS << " const MatchEntry *Start, *End;\n";
3143 OS << " switch (VariantID) {\n";
Craig Topper8c714d12015-01-03 08:16:14 +00003144 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
Craig Topper690d8ea2013-07-24 07:33:14 +00003145 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3146 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topper690d8ea2013-07-24 07:33:14 +00003147 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Benjamin Kramer502b9e12014-04-12 16:15:53 +00003148 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3149 << "); End = std::end(MatchTable" << VC << "); break;\n";
Craig Topper690d8ea2013-07-24 07:33:14 +00003150 }
3151 OS << " }\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003152
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003153 OS << " // Search the table.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003154 if (HasMnemonicFirst) {
3155 OS << " auto MnemonicRange = "
3156 "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
3157 } else {
3158 OS << " auto MnemonicRange = std::make_pair(Start, End);\n";
3159 OS << " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
3160 OS << " if (!Mnemonic.empty())\n";
3161 OS << " MnemonicRange = "
3162 "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
3163 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003164
Chris Lattner628fbec2010-09-06 21:54:15 +00003165 OS << " // Return a more specific error code if no mnemonics match.\n";
3166 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
3167 OS << " return Match_MnemonicFail;\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003168
Chris Lattner81301972010-09-06 21:22:45 +00003169 OS << " for (const MatchEntry *it = MnemonicRange.first, "
Chris Lattner9026ac02010-09-06 21:23:43 +00003170 << "*ie = MnemonicRange.second;\n";
Chris Lattner81301972010-09-06 21:22:45 +00003171 OS << " it != ie; ++it) {\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00003172
Craig Topperfd2c6a32015-12-31 08:18:23 +00003173 if (HasMnemonicFirst) {
3174 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
3175 OS << " assert(Mnemonic == it->getMnemonic());\n";
3176 }
3177
Daniel Dunbareefe8612010-07-19 05:44:09 +00003178 // Emit check that the subclasses match.
Chris Lattner339cc7b2010-09-06 22:11:18 +00003179 OS << " bool OperandsValid = true;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003180 if (HasOptionalOperands) {
3181 OS << " OptionalOperandsMask.reset(0, " << MaxNumOperands << ");\n";
3182 }
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003183 OS << " for (unsigned FormalIdx = " << (HasMnemonicFirst ? "0" : "SIndex")
3184 << ", ActualIdx = " << (HasMnemonicFirst ? "1" : "SIndex")
3185 << "; FormalIdx != " << MaxNumOperands << "; ++FormalIdx) {\n";
3186 OS << " auto Formal = "
3187 << "static_cast<MatchClassKind>(it->Classes[FormalIdx]);\n";
3188 OS << " if (ActualIdx >= Operands.size()) {\n";
Tom Stellardb9f235e2016-02-05 19:59:33 +00003189 OS << " OperandsValid = (Formal == " <<"InvalidMatchClass) || "
3190 "isSubclass(Formal, OptionalMatchClass);\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003191 OS << " if (!OperandsValid) ErrorInfo = ActualIdx;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003192 if (HasOptionalOperands) {
3193 OS << " OptionalOperandsMask.set(FormalIdx, " << MaxNumOperands
3194 << ");\n";
3195 }
Jim Grosbache6ce2052011-05-03 19:09:56 +00003196 OS << " break;\n";
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00003197 OS << " }\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003198 OS << " MCParsedAsmOperand &Actual = *Operands[ActualIdx];\n";
Colin LeMahieu23403c22015-11-09 00:46:46 +00003199 OS << " unsigned Diag = validateOperandClass(Actual, Formal);\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003200 OS << " if (Diag == Match_Success) {\n";
3201 OS << " ++ActualIdx;\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00003202 OS << " continue;\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003203 OS << " }\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003204 OS << " // If the generic handler indicates an invalid operand\n";
3205 OS << " // failure, check for a special case.\n";
3206 OS << " if (Diag == Match_InvalidOperand) {\n";
Colin LeMahieu23403c22015-11-09 00:46:46 +00003207 OS << " Diag = validateTargetOperandClass(Actual, Formal);\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003208 OS << " if (Diag == Match_Success) {\n";
3209 OS << " ++ActualIdx;\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003210 OS << " continue;\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003211 OS << " }\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003212 OS << " }\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003213 OS << " // If current formal operand wasn't matched and it is optional\n"
3214 << " // then try to match next formal operand\n";
3215 OS << " if (Diag == Match_InvalidOperand "
Sam Kolton5f10a132016-05-06 11:31:17 +00003216 << "&& isSubclass(Formal, OptionalMatchClass)) {\n";
3217 if (HasOptionalOperands) {
3218 OS << " OptionalOperandsMask.set(FormalIdx);\n";
3219 }
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003220 OS << " continue;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003221 OS << " }\n";
Chris Lattnerabfe4222010-09-06 23:37:39 +00003222 OS << " // If this operand is broken for all of the instances of this\n";
3223 OS << " // mnemonic, keep track of it so we can report loc info.\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00003224 OS << " // If we already had a match that only failed due to a\n";
3225 OS << " // target predicate, that diagnostic is preferred.\n";
3226 OS << " if (!HadMatchOtherThanPredicate &&\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003227 OS << " (it == MnemonicRange.first || ErrorInfo <= ActualIdx)) {\n";
3228 OS << " ErrorInfo = ActualIdx;\n";
Jim Grosbach8ccdbd12012-06-26 22:58:01 +00003229 OS << " // InvalidOperand is the default. Prefer specificity.\n";
3230 OS << " if (Diag != Match_InvalidOperand)\n";
3231 OS << " RetCode = Diag;\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00003232 OS << " }\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00003233 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
3234 OS << " OperandsValid = false;\n";
3235 OS << " break;\n";
3236 OS << " }\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003237
Chris Lattner339cc7b2010-09-06 22:11:18 +00003238 OS << " if (!OperandsValid) continue;\n";
Chris Lattnerb4be28f2010-09-06 20:08:02 +00003239
3240 // Emit check that the required features are available.
3241 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
3242 << "!= it->RequiredFeatures) {\n";
3243 OS << " HadMatchOtherThanFeatures = true;\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003244 OS << " uint64_t NewMissingFeatures = it->RequiredFeatures & "
Jim Grosbach9ec06a152012-06-18 19:45:46 +00003245 "~AvailableFeatures;\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003246 OS << " if (countPopulation(NewMissingFeatures) <=\n"
3247 " countPopulation(MissingFeatures))\n";
Jim Grosbach9ec06a152012-06-18 19:45:46 +00003248 OS << " MissingFeatures = NewMissingFeatures;\n";
Chris Lattnerb4be28f2010-09-06 20:08:02 +00003249 OS << " continue;\n";
3250 OS << " }\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003251 OS << "\n";
Ahmed Bougacha0dc19792014-12-16 18:05:28 +00003252 OS << " Inst.clear();\n\n";
Daniel Sandersc5537422016-07-27 13:49:44 +00003253 OS << " Inst.setOpcode(it->Opcode);\n";
3254 // Verify the instruction with the target-specific match predicate function.
3255 OS << " // We have a potential match but have not rendered the operands.\n"
3256 << " // Check the target predicate to handle any context sensitive\n"
3257 " // constraints.\n"
3258 << " // For example, Ties that are referenced multiple times must be\n"
3259 " // checked here to ensure the input is the same for each match\n"
3260 " // constraints. If we leave it any later the ties will have been\n"
3261 " // canonicalized\n"
3262 << " unsigned MatchResult;\n"
3263 << " if ((MatchResult = checkEarlyTargetMatchPredicate(Inst, "
3264 "Operands)) != Match_Success) {\n"
3265 << " Inst.clear();\n"
3266 << " RetCode = MatchResult;\n"
3267 << " HadMatchOtherThanPredicate = true;\n"
3268 << " continue;\n"
3269 << " }\n\n";
Chad Rosierf4e35dc2012-10-01 23:45:51 +00003270 OS << " if (matchingInlineAsm) {\n";
Chad Rosier2f480a82012-10-12 22:53:36 +00003271 OS << " convertToMapAndConstraints(it->ConvertFn, Operands);\n";
Chad Rosierf4e35dc2012-10-01 23:45:51 +00003272 OS << " return Match_Success;\n";
3273 OS << " }\n\n";
Daniel Dunbar66193402011-02-04 17:12:23 +00003274 OS << " // We have selected a definite instruction, convert the parsed\n"
3275 << " // operands into the appropriate MCInst.\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003276 if (HasOptionalOperands) {
3277 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands,\n"
3278 << " OptionalOperandsMask);\n";
3279 } else {
3280 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
3281 }
Daniel Dunbar66193402011-02-04 17:12:23 +00003282 OS << "\n";
Daniel Dunbar451a4352010-03-18 20:05:56 +00003283
Jim Grosbach120a96a2011-08-15 23:03:29 +00003284 // Verify the instruction with the target-specific match predicate function.
3285 OS << " // We have a potential match. Check the target predicate to\n"
3286 << " // handle any context sensitive constraints.\n"
Jim Grosbach120a96a2011-08-15 23:03:29 +00003287 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
3288 << " Match_Success) {\n"
3289 << " Inst.clear();\n"
3290 << " RetCode = MatchResult;\n"
Jim Grosbachd152e2c2011-08-16 20:12:35 +00003291 << " HadMatchOtherThanPredicate = true;\n"
Jim Grosbach120a96a2011-08-15 23:03:29 +00003292 << " continue;\n"
3293 << " }\n\n";
3294
Daniel Dunbar451a4352010-03-18 20:05:56 +00003295 // Call the post-processing function, if used.
3296 std::string InsnCleanupFn =
3297 AsmParser->getValueAsString("AsmParserInstCleanup");
3298 if (!InsnCleanupFn.empty())
3299 OS << " " << InsnCleanupFn << "(Inst);\n";
3300
Joey Gouly0e76fa72013-09-12 10:28:05 +00003301 if (HasDeprecation) {
3302 OS << " std::string Info;\n";
Akira Hatanakabd9fc282015-11-14 05:20:05 +00003303 OS << " if (MII.get(Inst.getOpcode()).getDeprecatedInfo(Inst, getSTI(), Info)) {\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00003304 OS << " SMLoc Loc = ((" << Target.getName()
3305 << "Operand&)*Operands[0]).getStartLoc();\n";
Rafael Espindola961d4692014-11-11 05:18:41 +00003306 OS << " getParser().Warning(Loc, Info, None);\n";
Joey Gouly0e76fa72013-09-12 10:28:05 +00003307 OS << " }\n";
3308 }
3309
Chris Lattnera22a3682010-09-06 19:22:17 +00003310 OS << " return Match_Success;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003311 OS << " }\n\n";
3312
Chris Lattnerb4be28f2010-09-06 20:08:02 +00003313 OS << " // Okay, we had no match. Try to return a useful error code.\n";
Chad Rosier4ee03842012-08-21 17:22:47 +00003314 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n";
3315 OS << " return RetCode;\n\n";
Jim Grosbach9ec06a152012-06-18 19:45:46 +00003316 OS << " // Missing feature matches return which features were missing\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003317 OS << " ErrorInfo = MissingFeatures;\n";
Jim Grosbachd152e2c2011-08-16 20:12:35 +00003318 OS << " return Match_MissingFeature;\n";
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003319 OS << "}\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003320
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003321 if (!Info.OperandMatchInfo.empty())
Craig Topper7ecfa6d2012-09-18 07:02:21 +00003322 emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable,
Craig Topperfd2c6a32015-12-31 08:18:23 +00003323 MaxMnemonicIndex, HasMnemonicFirst);
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003324
Chris Lattner3e4582a2010-09-06 19:11:01 +00003325 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbar3085b572009-07-11 19:39:44 +00003326}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00003327
3328namespace llvm {
3329
3330void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
3331 emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
3332 AsmMatcherEmitter(RK).run(OS);
3333}
3334
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +00003335} // end namespace llvm