blob: fb715364b7143dec586249f65d3c8859c2f861b6 [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;
Sam Kolton1b746d12016-09-08 15:50:52 +0000356 std::string Name;
Craig Topperc8b5b252015-12-30 06:00:18 +0000357 int AsmVariantNo;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000358};
359
Chris Lattnerad776812010-11-01 05:06:45 +0000360/// MatchableInfo - Helper class for storing the necessary information for an
361/// instruction or alias which is capable of being matched.
362struct MatchableInfo {
Chris Lattner896cf042010-11-03 19:47:34 +0000363 struct AsmOperand {
Chris Lattner28ea9b12010-11-02 17:30:52 +0000364 /// Token - This is the token that the operand came from.
365 StringRef Token;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000366
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000367 /// The unique class instance this operand should match.
368 ClassInfo *Class;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000369
Chris Lattner7108dad2010-11-04 01:42:59 +0000370 /// The operand name this is, if anything.
371 StringRef SrcOpName;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000372
373 /// The suboperand index within SrcOpName, or -1 for the entire operand.
374 int SubOpIdx;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000375
Ahmed Bougachaeb4dbd82015-05-29 01:03:37 +0000376 /// Whether the token is "isolated", i.e., it is preceded and followed
377 /// by separators.
378 bool IsIsolatedToken;
379
Devang Patel6d676e42012-01-07 01:33:34 +0000380 /// Register record if this token is singleton register.
381 Record *SingletonReg;
382
Ahmed Bougachaeb4dbd82015-05-29 01:03:37 +0000383 explicit AsmOperand(bool IsIsolatedToken, StringRef T)
384 : Token(T), Class(nullptr), SubOpIdx(-1),
385 IsIsolatedToken(IsIsolatedToken), SingletonReg(nullptr) {}
Daniel Dunbare10787e2009-08-07 08:26:05 +0000386 };
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000387
Chris Lattner743081d2010-11-04 00:43:46 +0000388 /// ResOperand - This represents a single operand in the result instruction
389 /// generated by the match. In cases (like addressing modes) where a single
390 /// assembler operand expands to multiple MCOperands, this represents the
391 /// single assembler operand, not the MCOperand.
392 struct ResOperand {
393 enum {
394 /// RenderAsmOperand - This represents an operand result that is
395 /// generated by calling the render method on the assembly operand. The
396 /// corresponding AsmOperand is specified by AsmOperandNum.
397 RenderAsmOperand,
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000398
Chris Lattner743081d2010-11-04 00:43:46 +0000399 /// TiedOperand - This represents a result operand that is a duplicate of
400 /// a previous result operand.
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000401 TiedOperand,
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000402
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000403 /// ImmOperand - This represents an immediate value that is dumped into
404 /// the operand.
Chris Lattner4869d342010-11-06 19:57:21 +0000405 ImmOperand,
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000406
Chris Lattner4869d342010-11-06 19:57:21 +0000407 /// RegOperand - This represents a fixed register that is dumped in.
408 RegOperand
Chris Lattner743081d2010-11-04 00:43:46 +0000409 } Kind;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000410
Chris Lattner743081d2010-11-04 00:43:46 +0000411 union {
412 /// This is the operand # in the AsmOperands list that this should be
413 /// copied from.
414 unsigned AsmOperandNum;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000415
Chris Lattner743081d2010-11-04 00:43:46 +0000416 /// TiedOperandNum - This is the (earlier) result operand that should be
417 /// copied from.
418 unsigned TiedOperandNum;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000419
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000420 /// ImmVal - This is the immediate value added to the instruction.
421 int64_t ImmVal;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000422
Chris Lattner4869d342010-11-06 19:57:21 +0000423 /// Register - This is the register record.
424 Record *Register;
Chris Lattner743081d2010-11-04 00:43:46 +0000425 };
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000426
Bob Wilsonb9b24222011-01-26 19:44:55 +0000427 /// MINumOperands - The number of MCInst operands populated by this
428 /// operand.
429 unsigned MINumOperands;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000430
Bob Wilsonb9b24222011-01-26 19:44:55 +0000431 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
Chris Lattner743081d2010-11-04 00:43:46 +0000432 ResOperand X;
433 X.Kind = RenderAsmOperand;
434 X.AsmOperandNum = AsmOpNum;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000435 X.MINumOperands = NumOperands;
Chris Lattner743081d2010-11-04 00:43:46 +0000436 return X;
437 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000438
Bob Wilsonb9b24222011-01-26 19:44:55 +0000439 static ResOperand getTiedOp(unsigned TiedOperandNum) {
Chris Lattner743081d2010-11-04 00:43:46 +0000440 ResOperand X;
441 X.Kind = TiedOperand;
442 X.TiedOperandNum = TiedOperandNum;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000443 X.MINumOperands = 1;
Chris Lattner743081d2010-11-04 00:43:46 +0000444 return X;
445 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000446
Bob Wilsonb9b24222011-01-26 19:44:55 +0000447 static ResOperand getImmOp(int64_t Val) {
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000448 ResOperand X;
449 X.Kind = ImmOperand;
450 X.ImmVal = Val;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000451 X.MINumOperands = 1;
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000452 return X;
453 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000454
Bob Wilsonb9b24222011-01-26 19:44:55 +0000455 static ResOperand getRegOp(Record *Reg) {
Chris Lattner4869d342010-11-06 19:57:21 +0000456 ResOperand X;
457 X.Kind = RegOperand;
458 X.Register = Reg;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000459 X.MINumOperands = 1;
Chris Lattner4869d342010-11-06 19:57:21 +0000460 return X;
461 }
Chris Lattner743081d2010-11-04 00:43:46 +0000462 };
Daniel Dunbare10787e2009-08-07 08:26:05 +0000463
Devang Patel9bdc5052012-01-10 17:50:43 +0000464 /// AsmVariantID - Target's assembly syntax variant no.
465 int AsmVariantID;
466
David Blaikieba4e00f2014-12-22 21:26:26 +0000467 /// AsmString - The assembly string for this instruction (with variants
468 /// removed), e.g. "movsx $src, $dst".
469 std::string AsmString;
470
Chris Lattnera7a903e2010-11-02 17:34:28 +0000471 /// TheDef - This is the definition of the instruction or InstAlias that this
472 /// matchable came from.
Chris Lattner39bc53b2010-11-01 04:34:44 +0000473 Record *const TheDef;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000474
Chris Lattner4efe13d2010-11-04 02:11:18 +0000475 /// DefRec - This is the definition that it came from.
476 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000477
Chris Lattnerfecdad62010-11-06 07:14:44 +0000478 const CodeGenInstruction *getResultInst() const {
479 if (DefRec.is<const CodeGenInstruction*>())
480 return DefRec.get<const CodeGenInstruction*>();
481 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
482 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000483
Chris Lattner743081d2010-11-04 00:43:46 +0000484 /// ResOperands - This is the operand list that should be built for the result
485 /// MCInst.
Jim Grosbacha37e2292012-04-19 17:52:34 +0000486 SmallVector<ResOperand, 8> ResOperands;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000487
Chris Lattner28ea9b12010-11-02 17:30:52 +0000488 /// Mnemonic - This is the first token of the matched instruction, its
489 /// mnemonic.
490 StringRef Mnemonic;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000491
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000492 /// AsmOperands - The textual operands that this instruction matches,
Chris Lattnera7a903e2010-11-02 17:34:28 +0000493 /// annotated with a class and where in the OperandList they were defined.
494 /// This directly corresponds to the tokenized AsmString after the mnemonic is
495 /// removed.
Jim Grosbacha37e2292012-04-19 17:52:34 +0000496 SmallVector<AsmOperand, 8> AsmOperands;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000497
Daniel Dunbareefe8612010-07-19 05:44:09 +0000498 /// Predicates - The required subtarget features to match this instruction.
David Blaikie9a9da992014-11-28 22:15:06 +0000499 SmallVector<const SubtargetFeatureInfo *, 4> RequiredFeatures;
Daniel Dunbareefe8612010-07-19 05:44:09 +0000500
Daniel Dunbar71330282009-08-08 05:24:34 +0000501 /// ConversionFnKind - The enum value which is passed to the generated
Chad Rosierba284b92012-09-05 01:02:38 +0000502 /// convertToMCInst to convert parsed operands into an MCInst for this
Daniel Dunbar71330282009-08-08 05:24:34 +0000503 /// function.
504 std::string ConversionFnKind;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000505
Joey Gouly0e76fa72013-09-12 10:28:05 +0000506 /// If this instruction is deprecated in some form.
507 bool HasDeprecation;
508
Tom Stellard74c87c82015-05-26 15:55:50 +0000509 /// If this is an alias, this is use to determine whether or not to using
510 /// the conversion function defined by the instruction's AsmMatchConverter
511 /// or to use the function generated by the alias.
512 bool UseInstAsmMatchConverter;
513
Chris Lattnerad776812010-11-01 05:06:45 +0000514 MatchableInfo(const CodeGenInstruction &CGI)
Tom Stellard74c87c82015-05-26 15:55:50 +0000515 : AsmVariantID(0), AsmString(CGI.AsmString), TheDef(CGI.TheDef), DefRec(&CGI),
516 UseInstAsmMatchConverter(true) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000517 }
Chris Lattner39bc53b2010-11-01 04:34:44 +0000518
David Blaikieba4e00f2014-12-22 21:26:26 +0000519 MatchableInfo(std::unique_ptr<const CodeGenInstAlias> Alias)
Tom Stellard74c87c82015-05-26 15:55:50 +0000520 : AsmVariantID(0), AsmString(Alias->AsmString), TheDef(Alias->TheDef),
521 DefRec(Alias.release()),
522 UseInstAsmMatchConverter(
523 TheDef->getValueAsBit("UseInstAsmMatchConverter")) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000524 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000525
David Blaikie6e48a812015-08-01 01:08:30 +0000526 // Could remove this and the dtor if PointerUnion supported unique_ptr
527 // elements with a dynamic failure/assertion (like the one below) in the case
528 // where it was copied while being in an owning state.
529 MatchableInfo(const MatchableInfo &RHS)
530 : AsmVariantID(RHS.AsmVariantID), AsmString(RHS.AsmString),
531 TheDef(RHS.TheDef), DefRec(RHS.DefRec), ResOperands(RHS.ResOperands),
532 Mnemonic(RHS.Mnemonic), AsmOperands(RHS.AsmOperands),
533 RequiredFeatures(RHS.RequiredFeatures),
534 ConversionFnKind(RHS.ConversionFnKind),
535 HasDeprecation(RHS.HasDeprecation),
536 UseInstAsmMatchConverter(RHS.UseInstAsmMatchConverter) {
537 assert(!DefRec.is<const CodeGenInstAlias *>());
538 }
539
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000540 ~MatchableInfo() {
David Blaikieba4e00f2014-12-22 21:26:26 +0000541 delete DefRec.dyn_cast<const CodeGenInstAlias*>();
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000542 }
Craig Topperce274892014-11-28 05:01:21 +0000543
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000544 // Two-operand aliases clone from the main matchable, but mark the second
545 // operand as a tied operand of the first for purposes of the assembler.
546 void formTwoOperandAlias(StringRef Constraint);
547
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000548 void initialize(const AsmMatcherInfo &Info,
Craig Topper71b7b682014-08-21 05:55:13 +0000549 SmallPtrSetImpl<Record*> &SingletonRegisters,
Craig Topperfd2c6a32015-12-31 08:18:23 +0000550 AsmVariantInfo const &Variant,
551 bool HasMnemonicFirst);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000552
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000553 /// validate - Return true if this matchable is a valid thing to match against
Chris Lattnerad776812010-11-01 05:06:45 +0000554 /// and perform a bunch of validity checking.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000555 bool validate(StringRef CommentDelimiter, bool Hack) const;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000556
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000557 /// findAsmOperand - Find the AsmOperand with the specified name and
Bob Wilsonb9b24222011-01-26 19:44:55 +0000558 /// suboperand index.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000559 int findAsmOperand(StringRef N, int SubOpIdx) const {
David Majnemer562e8292016-08-12 00:18:03 +0000560 auto I = find_if(AsmOperands, [&](const AsmOperand &Op) {
561 return Op.SrcOpName == N && Op.SubOpIdx == SubOpIdx;
562 });
Craig Topper58a0e7a2016-01-03 07:33:36 +0000563 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000564 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000565
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000566 /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
Bob Wilsonb9b24222011-01-26 19:44:55 +0000567 /// This does not check the suboperand index.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000568 int findAsmOperandNamed(StringRef N) const {
David Majnemer562e8292016-08-12 00:18:03 +0000569 auto I = find_if(AsmOperands,
570 [&](const AsmOperand &Op) { return Op.SrcOpName == N; });
Craig Topper58a0e7a2016-01-03 07:33:36 +0000571 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
Chris Lattner897a1402010-11-04 01:55:23 +0000572 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000573
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000574 void buildInstructionResultOperands();
575 void buildAliasResultOperands();
Chris Lattner743081d2010-11-04 00:43:46 +0000576
Chris Lattnerad776812010-11-01 05:06:45 +0000577 /// operator< - Compare two matchables.
578 bool operator<(const MatchableInfo &RHS) const {
Chris Lattner82d88ce2010-09-06 21:01:37 +0000579 // The primary comparator is the instruction mnemonic.
Ahmed Bougachaef3358d2016-06-23 17:09:49 +0000580 if (int Cmp = Mnemonic.compare(RHS.Mnemonic))
581 return Cmp == -1;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000582
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000583 if (AsmOperands.size() != RHS.AsmOperands.size())
584 return AsmOperands.size() < RHS.AsmOperands.size();
Daniel Dunbar3239f022009-08-09 04:00:06 +0000585
Daniel Dunbard9631912009-08-09 08:23:23 +0000586 // Compare lexicographically by operand. The matcher validates that other
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000587 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000588 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
589 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbar3239f022009-08-09 04:00:06 +0000590 return true;
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000591 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbard9631912009-08-09 08:23:23 +0000592 return false;
593 }
594
Andrew Trick818f5ac2012-08-29 03:52:57 +0000595 // Give matches that require more features higher precedence. This is useful
596 // because we cannot define AssemblerPredicates with the negation of
597 // processor features. For example, ARM v6 "nop" may be either a HINT or
598 // MOV. With v6, we want to match HINT. The assembler has no way to
599 // predicate MOV under "NoV6", but HINT will always match first because it
600 // requires V6 while MOV does not.
601 if (RequiredFeatures.size() != RHS.RequiredFeatures.size())
602 return RequiredFeatures.size() > RHS.RequiredFeatures.size();
603
Daniel Dunbar3239f022009-08-09 04:00:06 +0000604 return false;
605 }
606
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000607 /// couldMatchAmbiguouslyWith - Check whether this matchable could
Dmitri Gribenko8d302402012-09-15 20:22:05 +0000608 /// ambiguously match the same set of operands as \p RHS (without being a
Daniel Dunbarf573b562009-08-09 06:05:33 +0000609 /// strictly superior match).
Craig Topper42bd8192014-11-28 03:53:00 +0000610 bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) const {
Chris Lattnere3c48de2010-11-01 23:57:23 +0000611 // The primary comparator is the instruction mnemonic.
Chris Lattner28ea9b12010-11-02 17:30:52 +0000612 if (Mnemonic != RHS.Mnemonic)
Chris Lattnere3c48de2010-11-01 23:57:23 +0000613 return false;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000614
Daniel Dunbarf573b562009-08-09 06:05:33 +0000615 // The number of operands is unambiguous.
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000616 if (AsmOperands.size() != RHS.AsmOperands.size())
Daniel Dunbarf573b562009-08-09 06:05:33 +0000617 return false;
618
Daniel Dunbare1974092010-01-23 00:26:16 +0000619 // Otherwise, make sure the ordering of the two instructions is unambiguous
620 // by checking that either (a) a token or operand kind discriminates them,
621 // or (b) the ordering among equivalent kinds is consistent.
622
Daniel Dunbarf573b562009-08-09 06:05:33 +0000623 // Tokens and operand kinds are unambiguous (assuming a correct target
624 // specific parser).
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000625 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
626 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
627 AsmOperands[i].Class->Kind == ClassInfo::Token)
628 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
629 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbarf573b562009-08-09 06:05:33 +0000630 return false;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000631
Daniel Dunbarf573b562009-08-09 06:05:33 +0000632 // Otherwise, this operand could commute if all operands are equivalent, or
633 // there is a pair of operands that compare less than and a pair that
634 // compare greater than.
635 bool HasLT = false, HasGT = false;
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000636 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
637 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbarf573b562009-08-09 06:05:33 +0000638 HasLT = true;
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000639 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbarf573b562009-08-09 06:05:33 +0000640 HasGT = true;
641 }
642
Craig Topper322b67f2016-01-03 07:33:39 +0000643 return HasLT == HasGT;
Daniel Dunbarf573b562009-08-09 06:05:33 +0000644 }
645
Craig Topper42bd8192014-11-28 03:53:00 +0000646 void dump() const;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000647
Chris Lattner28ea9b12010-11-02 17:30:52 +0000648private:
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000649 void tokenizeAsmString(AsmMatcherInfo const &Info,
650 AsmVariantInfo const &Variant);
Craig Topperbc22e262015-12-31 05:01:45 +0000651 void addAsmOperand(StringRef Token, bool IsIsolatedToken = false);
Daniel Dunbare10787e2009-08-07 08:26:05 +0000652};
653
Daniel Dunbareefe8612010-07-19 05:44:09 +0000654/// SubtargetFeatureInfo - Helper class for storing information on a subtarget
655/// feature which participates in instruction matching.
656struct SubtargetFeatureInfo {
657 /// \brief The predicate record for this feature.
658 Record *TheDef;
659
660 /// \brief An unique index assigned to represent this feature.
Tim Northover26bb14e2014-08-18 11:49:42 +0000661 uint64_t Index;
Daniel Dunbareefe8612010-07-19 05:44:09 +0000662
Tim Northover26bb14e2014-08-18 11:49:42 +0000663 SubtargetFeatureInfo(Record *D, uint64_t Idx) : TheDef(D), Index(Idx) {}
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000664
Daniel Dunbareefe8612010-07-19 05:44:09 +0000665 /// \brief The name of the enumerated constant identifying this feature.
Chris Lattnera0e87192010-10-30 20:07:57 +0000666 std::string getEnumName() const {
667 return "Feature_" + TheDef->getName();
668 }
Daniel Sanders3ea92742014-05-21 10:11:24 +0000669
Craig Topper42bd8192014-11-28 03:53:00 +0000670 void dump() const {
Daniel Sanders3ea92742014-05-21 10:11:24 +0000671 errs() << getEnumName() << " " << Index << "\n";
672 TheDef->dump();
673 }
Daniel Dunbareefe8612010-07-19 05:44:09 +0000674};
675
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000676struct OperandMatchEntry {
677 unsigned OperandMask;
Craig Topper42bd8192014-11-28 03:53:00 +0000678 const MatchableInfo* MI;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000679 ClassInfo *CI;
680
Craig Topper42bd8192014-11-28 03:53:00 +0000681 static OperandMatchEntry create(const MatchableInfo *mi, ClassInfo *ci,
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000682 unsigned opMask) {
683 OperandMatchEntry X;
684 X.OperandMask = opMask;
685 X.CI = ci;
686 X.MI = mi;
687 return X;
688 }
689};
690
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000691class AsmMatcherInfo {
692public:
Chris Lattner77d369c2010-12-13 00:23:57 +0000693 /// Tracked Records
Chris Lattner89dcb682010-12-15 04:48:22 +0000694 RecordKeeper &Records;
Chris Lattner77d369c2010-12-13 00:23:57 +0000695
Daniel Dunbare4318712009-08-11 20:59:47 +0000696 /// The tablegen AsmParser record.
697 Record *AsmParser;
698
Chris Lattnerb80ab362010-11-01 01:37:30 +0000699 /// Target - The target information.
700 CodeGenTarget &Target;
701
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000702 /// The classes which are needed for matching.
David Blaikied749e342014-11-28 20:35:57 +0000703 std::forward_list<ClassInfo> Classes;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000704
Chris Lattnerad776812010-11-01 05:06:45 +0000705 /// The information on the matchables to match.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000706 std::vector<std::unique_ptr<MatchableInfo>> Matchables;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000707
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000708 /// Info for custom matching operands by user defined methods.
709 std::vector<OperandMatchEntry> OperandMatchInfo;
710
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000711 /// Map of Register records to their class information.
Sean Silvac8f56572012-09-19 01:47:01 +0000712 typedef std::map<Record*, ClassInfo*, LessRecordByID> RegisterClassesTy;
713 RegisterClassesTy RegisterClasses;
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000714
Daniel Dunbareefe8612010-07-19 05:44:09 +0000715 /// Map of Predicate records to their subtarget information.
David Blaikie9a9da992014-11-28 22:15:06 +0000716 std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000717
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +0000718 /// Map of AsmOperandClass records to their class information.
719 std::map<Record*, ClassInfo*> AsmOperandClasses;
720
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000721private:
722 /// Map of token to class information which has already been constructed.
723 std::map<std::string, ClassInfo*> TokenClasses;
724
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000725 /// Map of RegisterClass records to their class information.
726 std::map<Record*, ClassInfo*> RegisterClassClasses;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000727
728private:
729 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattner60db0a62010-02-09 00:34:28 +0000730 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000731
732 /// getOperandClass - Lookup or create the class for the given operand.
Bob Wilsonb9b24222011-01-26 19:44:55 +0000733 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
Jim Grosbachd1f1b792011-10-28 22:32:53 +0000734 int SubOpIdx);
735 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000736
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000737 /// buildRegisterClasses - Build the ClassInfo* instances for register
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000738 /// classes.
Craig Topper71b7b682014-08-21 05:55:13 +0000739 void buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters);
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000740
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000741 /// buildOperandClasses - Build the ClassInfo* instances for user defined
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000742 /// operand classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000743 void buildOperandClasses();
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000744
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000745 void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
Bob Wilsonb9b24222011-01-26 19:44:55 +0000746 unsigned AsmOpIdx);
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000747 void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
Chris Lattner4efe13d2010-11-04 02:11:18 +0000748 MatchableInfo::AsmOperand &Op);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000749
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000750public:
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000751 AsmMatcherInfo(Record *AsmParser,
752 CodeGenTarget &Target,
Chris Lattner89dcb682010-12-15 04:48:22 +0000753 RecordKeeper &Records);
Daniel Dunbare4318712009-08-11 20:59:47 +0000754
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000755 /// buildInfo - Construct the various tables used during matching.
756 void buildInfo();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000757
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000758 /// buildOperandMatchInfo - Build the necessary information to handle user
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000759 /// defined operand parsing methods.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000760 void buildOperandMatchInfo();
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000761
Chris Lattner43690072010-10-30 20:15:02 +0000762 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
763 /// given operand.
David Blaikie9a9da992014-11-28 22:15:06 +0000764 const SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
Chris Lattner43690072010-10-30 20:15:02 +0000765 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
Craig Topper42bd8192014-11-28 03:53:00 +0000766 const auto &I = SubtargetFeatures.find(Def);
David Blaikie9a9da992014-11-28 22:15:06 +0000767 return I == SubtargetFeatures.end() ? nullptr : &I->second;
Chris Lattner43690072010-10-30 20:15:02 +0000768 }
Chris Lattner77d369c2010-12-13 00:23:57 +0000769
Chris Lattner89dcb682010-12-15 04:48:22 +0000770 RecordKeeper &getRecords() const {
771 return Records;
Chris Lattner77d369c2010-12-13 00:23:57 +0000772 }
Sam Kolton5f10a132016-05-06 11:31:17 +0000773
774 bool hasOptionalOperands() const {
David Majnemer562e8292016-08-12 00:18:03 +0000775 return find_if(Classes, [](const ClassInfo &Class) {
776 return Class.IsOptional;
777 }) != Classes.end();
Sam Kolton5f10a132016-05-06 11:31:17 +0000778 }
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000779};
780
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000781} // end anonymous namespace
Daniel Dunbare10787e2009-08-07 08:26:05 +0000782
Craig Topper42bd8192014-11-28 03:53:00 +0000783void MatchableInfo::dump() const {
Chris Lattner9f093812010-11-06 06:43:11 +0000784 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +0000785
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000786 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
Craig Topper42bd8192014-11-28 03:53:00 +0000787 const AsmOperand &Op = AsmOperands[i];
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000788 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Chris Lattner4779e3e92010-11-04 00:57:06 +0000789 errs() << '\"' << Op.Token << "\"\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +0000790 }
791}
792
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000793static std::pair<StringRef, StringRef>
Jakob Stoklund Olesend7b66962012-08-22 23:33:58 +0000794parseTwoOperandConstraint(StringRef S, ArrayRef<SMLoc> Loc) {
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000795 // Split via the '='.
796 std::pair<StringRef, StringRef> Ops = S.split('=');
797 if (Ops.second == "")
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000798 PrintFatalError(Loc, "missing '=' in two-operand alias constraint");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000799 // Trim whitespace and the leading '$' on the operand names.
800 size_t start = Ops.first.find_first_of('$');
801 if (start == std::string::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000802 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000803 Ops.first = Ops.first.slice(start + 1, std::string::npos);
804 size_t end = Ops.first.find_last_of(" \t");
805 Ops.first = Ops.first.slice(0, end);
806 // Now the second operand.
807 start = Ops.second.find_first_of('$');
808 if (start == std::string::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000809 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000810 Ops.second = Ops.second.slice(start + 1, std::string::npos);
811 end = Ops.second.find_last_of(" \t");
812 Ops.first = Ops.first.slice(0, end);
813 return Ops;
814}
815
816void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
817 // Figure out which operands are aliased and mark them as tied.
818 std::pair<StringRef, StringRef> Ops =
819 parseTwoOperandConstraint(Constraint, TheDef->getLoc());
820
821 // Find the AsmOperands that refer to the operands we're aliasing.
822 int SrcAsmOperand = findAsmOperandNamed(Ops.first);
823 int DstAsmOperand = findAsmOperandNamed(Ops.second);
824 if (SrcAsmOperand == -1)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000825 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +0000826 "unknown source two-operand alias operand '" + Ops.first +
827 "'.");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000828 if (DstAsmOperand == -1)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000829 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +0000830 "unknown destination two-operand alias operand '" +
831 Ops.second + "'.");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000832
833 // Find the ResOperand that refers to the operand we're aliasing away
834 // and update it to refer to the combined operand instead.
Craig Toppere4e74152015-12-29 07:03:23 +0000835 for (ResOperand &Op : ResOperands) {
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000836 if (Op.Kind == ResOperand::RenderAsmOperand &&
837 Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
838 Op.AsmOperandNum = DstAsmOperand;
839 break;
840 }
841 }
842 // Remove the AsmOperand for the alias operand.
843 AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
844 // Adjust the ResOperand references to any AsmOperands that followed
845 // the one we just deleted.
Craig Toppere4e74152015-12-29 07:03:23 +0000846 for (ResOperand &Op : ResOperands) {
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000847 switch(Op.Kind) {
848 default:
849 // Nothing to do for operands that don't reference AsmOperands.
850 break;
851 case ResOperand::RenderAsmOperand:
852 if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
853 --Op.AsmOperandNum;
854 break;
855 case ResOperand::TiedOperand:
856 if (Op.TiedOperandNum > (unsigned)SrcAsmOperand)
857 --Op.TiedOperandNum;
858 break;
859 }
860 }
861}
862
Craig Topper22fa45f2015-09-13 18:01:25 +0000863/// extractSingletonRegisterForAsmOperand - Extract singleton register,
864/// if present, from specified token.
865static void
866extractSingletonRegisterForAsmOperand(MatchableInfo::AsmOperand &Op,
867 const AsmMatcherInfo &Info,
868 StringRef RegisterPrefix) {
869 StringRef Tok = Op.Token;
870
871 // If this token is not an isolated token, i.e., it isn't separated from
872 // other tokens (e.g. with whitespace), don't interpret it as a register name.
873 if (!Op.IsIsolatedToken)
874 return;
875
876 if (RegisterPrefix.empty()) {
877 std::string LoweredTok = Tok.lower();
878 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
879 Op.SingletonReg = Reg->TheDef;
880 return;
881 }
882
883 if (!Tok.startswith(RegisterPrefix))
884 return;
885
886 StringRef RegName = Tok.substr(RegisterPrefix.size());
887 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
888 Op.SingletonReg = Reg->TheDef;
889
890 // If there is no register prefix (i.e. "%" in "%eax"), then this may
891 // be some random non-register token, just ignore it.
Craig Topper22fa45f2015-09-13 18:01:25 +0000892}
893
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000894void MatchableInfo::initialize(const AsmMatcherInfo &Info,
Craig Topper71b7b682014-08-21 05:55:13 +0000895 SmallPtrSetImpl<Record*> &SingletonRegisters,
Craig Topperfd2c6a32015-12-31 08:18:23 +0000896 AsmVariantInfo const &Variant,
897 bool HasMnemonicFirst) {
Craig Topperc8b5b252015-12-30 06:00:18 +0000898 AsmVariantID = Variant.AsmVariantNo;
Jim Grosbach0bba00d2012-01-24 21:06:59 +0000899 AsmString =
Craig Topperc8b5b252015-12-30 06:00:18 +0000900 CodeGenInstruction::FlattenAsmStringVariants(AsmString,
901 Variant.AsmVariantNo);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000902
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000903 tokenizeAsmString(Info, Variant);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000904
Craig Topperfd2c6a32015-12-31 08:18:23 +0000905 // The first token of the instruction is the mnemonic, which must be a
906 // simple string, not a $foo variable or a singleton register.
907 if (AsmOperands.empty())
908 PrintFatalError(TheDef->getLoc(),
909 "Instruction '" + TheDef->getName() + "' has no tokens");
910
911 assert(!AsmOperands[0].Token.empty());
912 if (HasMnemonicFirst) {
913 Mnemonic = AsmOperands[0].Token;
914 if (Mnemonic[0] == '$')
915 PrintFatalError(TheDef->getLoc(),
916 "Invalid instruction mnemonic '" + Mnemonic + "'!");
917
918 // Remove the first operand, it is tracked in the mnemonic field.
919 AsmOperands.erase(AsmOperands.begin());
920 } else if (AsmOperands[0].Token[0] != '$')
921 Mnemonic = AsmOperands[0].Token;
922
Chris Lattnerba465f92010-11-01 04:53:48 +0000923 // Compute the require features.
Craig Topper22fa45f2015-09-13 18:01:25 +0000924 for (Record *Predicate : TheDef->getValueAsListOfDefs("Predicates"))
David Blaikie9a9da992014-11-28 22:15:06 +0000925 if (const SubtargetFeatureInfo *Feature =
Craig Topper22fa45f2015-09-13 18:01:25 +0000926 Info.getSubtargetFeature(Predicate))
Chris Lattnerba465f92010-11-01 04:53:48 +0000927 RequiredFeatures.push_back(Feature);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000928
Chris Lattnerba465f92010-11-01 04:53:48 +0000929 // Collect singleton registers, if used.
Craig Topper22fa45f2015-09-13 18:01:25 +0000930 for (MatchableInfo::AsmOperand &Op : AsmOperands) {
Craig Topperc8b5b252015-12-30 06:00:18 +0000931 extractSingletonRegisterForAsmOperand(Op, Info, Variant.RegisterPrefix);
Craig Topper22fa45f2015-09-13 18:01:25 +0000932 if (Record *Reg = Op.SingletonReg)
Chris Lattnerba465f92010-11-01 04:53:48 +0000933 SingletonRegisters.insert(Reg);
934 }
Joey Gouly0e76fa72013-09-12 10:28:05 +0000935
936 const RecordVal *DepMask = TheDef->getValue("DeprecatedFeatureMask");
937 if (!DepMask)
938 DepMask = TheDef->getValue("ComplexDeprecationPredicate");
939
940 HasDeprecation =
941 DepMask ? !DepMask->getValue()->getAsUnquotedString().empty() : false;
Chris Lattnerba465f92010-11-01 04:53:48 +0000942}
943
Ahmed Bougachad8dc2ac2015-05-29 00:55:55 +0000944/// Append an AsmOperand for the given substring of AsmString.
Craig Topperbc22e262015-12-31 05:01:45 +0000945void MatchableInfo::addAsmOperand(StringRef Token, bool IsIsolatedToken) {
946 AsmOperands.push_back(AsmOperand(IsIsolatedToken, Token));
Ahmed Bougachad8dc2ac2015-05-29 00:55:55 +0000947}
948
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000949/// tokenizeAsmString - Tokenize a simplified assembly string.
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000950void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info,
951 AsmVariantInfo const &Variant) {
Chris Lattner28ea9b12010-11-02 17:30:52 +0000952 StringRef String = AsmString;
Craig Topperba614322015-12-30 06:00:15 +0000953 size_t Prev = 0;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000954 bool InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +0000955 bool IsIsolatedToken = true;
Craig Topperba614322015-12-30 06:00:15 +0000956 for (size_t i = 0, e = String.size(); i != e; ++i) {
Craig Topperbc22e262015-12-31 05:01:45 +0000957 char Char = String[i];
958 if (Variant.BreakCharacters.find(Char) != std::string::npos) {
959 if (InTok) {
960 addAsmOperand(String.slice(Prev, i), false);
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000961 Prev = i;
Craig Topperbc22e262015-12-31 05:01:45 +0000962 IsIsolatedToken = false;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000963 }
964 InTok = true;
965 continue;
966 }
Craig Topperbc22e262015-12-31 05:01:45 +0000967 if (Variant.TokenizingCharacters.find(Char) != std::string::npos) {
968 if (InTok) {
969 addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000970 InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +0000971 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +0000972 }
Craig Topperbc22e262015-12-31 05:01:45 +0000973 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000974 Prev = i + 1;
Craig Topperbc22e262015-12-31 05:01:45 +0000975 IsIsolatedToken = true;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000976 continue;
977 }
Craig Topperbc22e262015-12-31 05:01:45 +0000978 if (Variant.SeparatorCharacters.find(Char) != std::string::npos) {
979 if (InTok) {
980 addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000981 InTok = false;
982 }
983 Prev = i + 1;
Craig Topperbc22e262015-12-31 05:01:45 +0000984 IsIsolatedToken = true;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000985 continue;
986 }
Craig Topperbc22e262015-12-31 05:01:45 +0000987
988 switch (Char) {
Chris Lattner28ea9b12010-11-02 17:30:52 +0000989 case '\\':
990 if (InTok) {
Craig Topperbc22e262015-12-31 05:01:45 +0000991 addAsmOperand(String.slice(Prev, i), false);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000992 InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +0000993 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +0000994 }
995 ++i;
996 assert(i != String.size() && "Invalid quoted character");
Craig Topperbc22e262015-12-31 05:01:45 +0000997 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000998 Prev = i + 1;
Craig Topperbc22e262015-12-31 05:01:45 +0000999 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001000 break;
1001
1002 case '$': {
Craig Topperbc22e262015-12-31 05:01:45 +00001003 if (InTok) {
1004 addAsmOperand(String.slice(Prev, i), false);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001005 InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +00001006 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001007 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001008
Colin LeMahieu3d905742015-08-10 19:58:06 +00001009 // If this isn't "${", start new identifier looking like "$xxx"
Chris Lattnerd6746d52010-11-06 22:06:03 +00001010 if (i + 1 == String.size() || String[i + 1] != '{') {
1011 Prev = i;
1012 break;
1013 }
Chris Lattner28ea9b12010-11-02 17:30:52 +00001014
Craig Topperba614322015-12-30 06:00:15 +00001015 size_t EndPos = String.find('}', i);
1016 assert(EndPos != StringRef::npos &&
1017 "Missing brace in operand reference!");
Craig Topperbc22e262015-12-31 05:01:45 +00001018 addAsmOperand(String.slice(i, EndPos+1), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001019 Prev = EndPos + 1;
1020 i = EndPos;
Craig Topperbc22e262015-12-31 05:01:45 +00001021 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001022 break;
1023 }
Craig Topperbc22e262015-12-31 05:01:45 +00001024
Chris Lattner28ea9b12010-11-02 17:30:52 +00001025 default:
1026 InTok = true;
Craig Topperbc22e262015-12-31 05:01:45 +00001027 break;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001028 }
1029 }
1030 if (InTok && Prev != String.size())
Craig Topperbc22e262015-12-31 05:01:45 +00001031 addAsmOperand(String.substr(Prev), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001032}
1033
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001034bool MatchableInfo::validate(StringRef CommentDelimiter, bool Hack) const {
Chris Lattnerad776812010-11-01 05:06:45 +00001035 // Reject matchables with no .s string.
Chris Lattner39bc53b2010-11-01 04:34:44 +00001036 if (AsmString.empty())
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001037 PrintFatalError(TheDef->getLoc(), "instruction with empty asm string");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001038
Chris Lattnerad776812010-11-01 05:06:45 +00001039 // Reject any matchables with a newline in them, they should be marked
Chris Lattner39bc53b2010-11-01 04:34:44 +00001040 // isCodeGenOnly if they are pseudo instructions.
1041 if (AsmString.find('\n') != std::string::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001042 PrintFatalError(TheDef->getLoc(),
Chris Lattner39bc53b2010-11-01 04:34:44 +00001043 "multiline instruction is not valid for the asmparser, "
1044 "mark it isCodeGenOnly");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001045
Chris Lattner178f4bb2010-11-01 04:44:29 +00001046 // Remove comments from the asm string. We know that the asmstring only
1047 // has one line.
1048 if (!CommentDelimiter.empty() &&
1049 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001050 PrintFatalError(TheDef->getLoc(),
Chris Lattner178f4bb2010-11-01 04:44:29 +00001051 "asmstring for instruction has comment character in it, "
1052 "mark it isCodeGenOnly");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001053
Chris Lattnerad776812010-11-01 05:06:45 +00001054 // Reject matchables with operand modifiers, these aren't something we can
Bob Wilson266d2ba2011-01-20 18:38:07 +00001055 // handle, the target should be refactored to use operands instead of
1056 // modifiers.
Chris Lattner39bc53b2010-11-01 04:34:44 +00001057 //
1058 // Also, check for instructions which reference the operand multiple times;
1059 // this implies a constraint we would not honor.
1060 std::set<std::string> OperandNames;
Craig Topper77bd2b72015-12-30 06:00:20 +00001061 for (const AsmOperand &Op : AsmOperands) {
1062 StringRef Tok = Op.Token;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001063 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001064 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001065 "matchable with operand modifier '" + Tok +
1066 "' not supported by asm matcher. Mark isCodeGenOnly!");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001067
Chris Lattnerad776812010-11-01 05:06:45 +00001068 // Verify that any operand is only mentioned once.
Chris Lattner4d23eb22010-11-02 23:18:43 +00001069 // We reject aliases and ignore instructions for now.
Chris Lattner28ea9b12010-11-02 17:30:52 +00001070 if (Tok[0] == '$' && !OperandNames.insert(Tok).second) {
Chris Lattnerad776812010-11-01 05:06:45 +00001071 if (!Hack)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001072 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001073 "ERROR: matchable with tied operand '" + Tok +
1074 "' can never be matched!");
Chris Lattnerad776812010-11-01 05:06:45 +00001075 // FIXME: Should reject these. The ARM backend hits this with $lane in a
1076 // bunch of instructions. It is unclear what the right answer is.
Chris Lattner39bc53b2010-11-01 04:34:44 +00001077 DEBUG({
Chris Lattner9f093812010-11-06 06:43:11 +00001078 errs() << "warning: '" << TheDef->getName() << "': "
Chris Lattnerad776812010-11-01 05:06:45 +00001079 << "ignoring instruction with tied operand '"
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001080 << Tok << "'\n";
Chris Lattner39bc53b2010-11-01 04:34:44 +00001081 });
1082 return false;
1083 }
1084 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001085
Chris Lattner39bc53b2010-11-01 04:34:44 +00001086 return true;
1087}
1088
Chris Lattner60db0a62010-02-09 00:34:28 +00001089static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001090 std::string Res;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001091
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001092 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
1093 switch (*it) {
1094 case '*': Res += "_STAR_"; break;
1095 case '%': Res += "_PCT_"; break;
1096 case ':': Res += "_COLON_"; break;
Bill Wendling4a08e562010-11-18 23:36:54 +00001097 case '!': Res += "_EXCLAIM_"; break;
Bill Wendlinga01ea892011-01-22 09:44:32 +00001098 case '.': Res += "_DOT_"; break;
Tim Northoverb3cfb282013-01-10 16:47:31 +00001099 case '<': Res += "_LT_"; break;
1100 case '>': Res += "_GT_"; break;
Hal Finkelf9090722015-01-15 01:33:00 +00001101 case '-': Res += "_MINUS_"; break;
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001102 default:
Tim Northoverb3cfb282013-01-10 16:47:31 +00001103 if ((*it >= 'A' && *it <= 'Z') ||
1104 (*it >= 'a' && *it <= 'z') ||
1105 (*it >= '0' && *it <= '9'))
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001106 Res += *it;
Chris Lattner33fc3e02010-10-31 19:10:56 +00001107 else
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001108 Res += "_" + utostr((unsigned) *it) + "_";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001109 }
1110 }
1111
1112 return Res;
1113}
1114
Chris Lattner60db0a62010-02-09 00:34:28 +00001115ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001116 ClassInfo *&Entry = TokenClasses[Token];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001117
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001118 if (!Entry) {
David Blaikied749e342014-11-28 20:35:57 +00001119 Classes.emplace_front();
1120 Entry = &Classes.front();
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001121 Entry->Kind = ClassInfo::Token;
Daniel Dunbarc32aa062009-08-09 05:18:30 +00001122 Entry->ClassName = "Token";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001123 Entry->Name = "MCK_" + getEnumNameForToken(Token);
1124 Entry->ValueName = Token;
1125 Entry->PredicateMethod = "<invalid>";
1126 Entry->RenderMethod = "<invalid>";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001127 Entry->ParserMethod = "";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001128 Entry->DiagnosticType = "";
Tom Stellardb9f235e2016-02-05 19:59:33 +00001129 Entry->IsOptional = false;
Sam Kolton5f10a132016-05-06 11:31:17 +00001130 Entry->DefaultMethod = "<invalid>";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001131 }
1132
1133 return Entry;
1134}
1135
1136ClassInfo *
Bob Wilsonb9b24222011-01-26 19:44:55 +00001137AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
1138 int SubOpIdx) {
1139 Record *Rec = OI.Rec;
1140 if (SubOpIdx != -1)
Sean Silva88eb8dd2012-10-10 20:24:47 +00001141 Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001142 return getOperandClass(Rec, SubOpIdx);
1143}
Bob Wilsonb9b24222011-01-26 19:44:55 +00001144
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001145ClassInfo *
1146AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001147 if (Rec->isSubClassOf("RegisterOperand")) {
1148 // RegisterOperand may have an associated ParserMatchClass. If it does,
1149 // use it, else just fall back to the underlying register class.
1150 const RecordVal *R = Rec->getValue("ParserMatchClass");
Craig Topper24064772014-04-15 07:20:03 +00001151 if (!R || !R->getValue())
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001152 PrintFatalError("Record `" + Rec->getName() +
1153 "' does not have a ParserMatchClass!\n");
Owen Andersona84be6c2011-06-27 21:06:21 +00001154
Sean Silvafb509ed2012-10-10 20:24:43 +00001155 if (DefInit *DI= dyn_cast<DefInit>(R->getValue())) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001156 Record *MatchClass = DI->getDef();
1157 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1158 return CI;
1159 }
1160
1161 // No custom match class. Just use the register class.
1162 Record *ClassRec = Rec->getValueAsDef("RegClass");
1163 if (!ClassRec)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001164 PrintFatalError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
Owen Andersona84be6c2011-06-27 21:06:21 +00001165 "' has no associated register class!\n");
1166 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
1167 return CI;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001168 PrintFatalError(Rec->getLoc(), "register class has no class info!");
Owen Andersona84be6c2011-06-27 21:06:21 +00001169 }
1170
Bob Wilsonb9b24222011-01-26 19:44:55 +00001171 if (Rec->isSubClassOf("RegisterClass")) {
1172 if (ClassInfo *CI = RegisterClassClasses[Rec])
Chris Lattner77d3ead2010-11-02 18:10:06 +00001173 return CI;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001174 PrintFatalError(Rec->getLoc(), "register class has no class info!");
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001175 }
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001176
Jim Grosbachf6cb1ee2012-09-12 17:40:25 +00001177 if (!Rec->isSubClassOf("Operand"))
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001178 PrintFatalError(Rec->getLoc(), "Operand `" + Rec->getName() +
Jim Grosbachf6cb1ee2012-09-12 17:40:25 +00001179 "' does not derive from class Operand!\n");
Bob Wilsonb9b24222011-01-26 19:44:55 +00001180 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
Chris Lattner77d3ead2010-11-02 18:10:06 +00001181 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1182 return CI;
Daniel Dunbar17410a42009-08-10 18:41:10 +00001183
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001184 PrintFatalError(Rec->getLoc(), "operand has no match class!");
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001185}
1186
Tim Northoverc74e6912013-09-16 16:43:19 +00001187struct LessRegisterSet {
Tim Northover9c30f7a2013-09-16 17:33:40 +00001188 bool operator() (const RegisterSet &LHS, const RegisterSet & RHS) const {
Tim Northoverc74e6912013-09-16 16:43:19 +00001189 // std::set<T> defines its own compariso "operator<", but it
1190 // performs a lexicographical comparison by T's innate comparison
1191 // for some reason. We don't want non-deterministic pointer
1192 // comparisons so use this instead.
1193 return std::lexicographical_compare(LHS.begin(), LHS.end(),
1194 RHS.begin(), RHS.end(),
1195 LessRecordByID());
1196 }
1197};
1198
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001199void AsmMatcherInfo::
Craig Topper71b7b682014-08-21 05:55:13 +00001200buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters) {
David Blaikie9b613db2014-11-29 18:13:39 +00001201 const auto &Registers = Target.getRegBank().getRegisters();
David Blaikiec0bb5ca2014-12-03 19:58:41 +00001202 auto &RegClassList = Target.getRegBank().getRegClasses();
Daniel Dunbar17410a42009-08-10 18:41:10 +00001203
Tim Northoverc74e6912013-09-16 16:43:19 +00001204 typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet;
1205
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001206 // The register sets used for matching.
Tim Northoverc74e6912013-09-16 16:43:19 +00001207 RegisterSetSet RegisterSets;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001208
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001209 // Gather the defined sets.
David Blaikiedacea4b2014-12-03 19:58:45 +00001210 for (const CodeGenRegisterClass &RC : RegClassList)
1211 RegisterSets.insert(
1212 RegisterSet(RC.getOrder().begin(), RC.getOrder().end()));
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001213
1214 // Add any required singleton sets.
Craig Topper03ec8012014-11-25 20:11:31 +00001215 for (Record *Rec : SingletonRegisters) {
Tim Northoverc74e6912013-09-16 16:43:19 +00001216 RegisterSets.insert(RegisterSet(&Rec, &Rec + 1));
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001217 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001218
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001219 // Introduce derived sets where necessary (when a register does not determine
1220 // a unique register set class), and build the mapping of registers to the set
1221 // they should classify to.
Tim Northoverc74e6912013-09-16 16:43:19 +00001222 std::map<Record*, RegisterSet> RegisterMap;
David Blaikie9b613db2014-11-29 18:13:39 +00001223 for (const CodeGenRegister &CGR : Registers) {
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001224 // Compute the intersection of all sets containing this register.
Tim Northoverc74e6912013-09-16 16:43:19 +00001225 RegisterSet ContainingSet;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001226
Craig Topper03ec8012014-11-25 20:11:31 +00001227 for (const RegisterSet &RS : RegisterSets) {
David Blaikie9b613db2014-11-29 18:13:39 +00001228 if (!RS.count(CGR.TheDef))
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001229 continue;
1230
1231 if (ContainingSet.empty()) {
Craig Topper03ec8012014-11-25 20:11:31 +00001232 ContainingSet = RS;
Chris Lattner77d3ead2010-11-02 18:10:06 +00001233 continue;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001234 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001235
Tim Northoverc74e6912013-09-16 16:43:19 +00001236 RegisterSet Tmp;
Chris Lattner77d3ead2010-11-02 18:10:06 +00001237 std::swap(Tmp, ContainingSet);
Tim Northoverc74e6912013-09-16 16:43:19 +00001238 std::insert_iterator<RegisterSet> II(ContainingSet,
1239 ContainingSet.begin());
Craig Topper03ec8012014-11-25 20:11:31 +00001240 std::set_intersection(Tmp.begin(), Tmp.end(), RS.begin(), RS.end(), II,
Tim Northoverc74e6912013-09-16 16:43:19 +00001241 LessRecordByID());
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001242 }
1243
1244 if (!ContainingSet.empty()) {
1245 RegisterSets.insert(ContainingSet);
David Blaikie9b613db2014-11-29 18:13:39 +00001246 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001247 }
1248 }
1249
1250 // Construct the register classes.
Tim Northoverc74e6912013-09-16 16:43:19 +00001251 std::map<RegisterSet, ClassInfo*, LessRegisterSet> RegisterSetClasses;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001252 unsigned Index = 0;
Craig Topper03ec8012014-11-25 20:11:31 +00001253 for (const RegisterSet &RS : RegisterSets) {
David Blaikied749e342014-11-28 20:35:57 +00001254 Classes.emplace_front();
1255 ClassInfo *CI = &Classes.front();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001256 CI->Kind = ClassInfo::RegisterClass0 + Index;
1257 CI->ClassName = "Reg" + utostr(Index);
1258 CI->Name = "MCK_Reg" + utostr(Index);
1259 CI->ValueName = "";
1260 CI->PredicateMethod = ""; // unused
1261 CI->RenderMethod = "addRegOperands";
Craig Topper03ec8012014-11-25 20:11:31 +00001262 CI->Registers = RS;
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001263 // FIXME: diagnostic type.
1264 CI->DiagnosticType = "";
Tom Stellardb9f235e2016-02-05 19:59:33 +00001265 CI->IsOptional = false;
Sam Kolton5f10a132016-05-06 11:31:17 +00001266 CI->DefaultMethod = ""; // unused
Craig Topper03ec8012014-11-25 20:11:31 +00001267 RegisterSetClasses.insert(std::make_pair(RS, CI));
1268 ++Index;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001269 }
1270
1271 // Find the superclasses; we could compute only the subgroup lattice edges,
1272 // but there isn't really a point.
Craig Topper03ec8012014-11-25 20:11:31 +00001273 for (const RegisterSet &RS : RegisterSets) {
1274 ClassInfo *CI = RegisterSetClasses[RS];
1275 for (const RegisterSet &RS2 : RegisterSets)
1276 if (RS != RS2 &&
1277 std::includes(RS2.begin(), RS2.end(), RS.begin(), RS.end(),
Tim Northoverc74e6912013-09-16 16:43:19 +00001278 LessRecordByID()))
Craig Topper03ec8012014-11-25 20:11:31 +00001279 CI->SuperClasses.push_back(RegisterSetClasses[RS2]);
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001280 }
1281
1282 // Name the register classes which correspond to a user defined RegisterClass.
David Blaikiedacea4b2014-12-03 19:58:45 +00001283 for (const CodeGenRegisterClass &RC : RegClassList) {
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001284 // Def will be NULL for non-user defined register classes.
David Blaikiedacea4b2014-12-03 19:58:45 +00001285 Record *Def = RC.getDef();
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001286 if (!Def)
1287 continue;
David Blaikiedacea4b2014-12-03 19:58:45 +00001288 ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(),
1289 RC.getOrder().end())];
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001290 if (CI->ValueName.empty()) {
David Blaikiedacea4b2014-12-03 19:58:45 +00001291 CI->ClassName = RC.getName();
1292 CI->Name = "MCK_" + RC.getName();
1293 CI->ValueName = RC.getName();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001294 } else
David Blaikiedacea4b2014-12-03 19:58:45 +00001295 CI->ValueName = CI->ValueName + "," + RC.getName();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001296
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001297 RegisterClassClasses.insert(std::make_pair(Def, CI));
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001298 }
1299
1300 // Populate the map for individual registers.
Tim Northoverc74e6912013-09-16 16:43:19 +00001301 for (std::map<Record*, RegisterSet>::iterator it = RegisterMap.begin(),
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001302 ie = RegisterMap.end(); it != ie; ++it)
Chris Lattner77d3ead2010-11-02 18:10:06 +00001303 RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001304
1305 // Name the register classes which correspond to singleton registers.
Craig Topper03ec8012014-11-25 20:11:31 +00001306 for (Record *Rec : SingletonRegisters) {
Chris Lattner77d3ead2010-11-02 18:10:06 +00001307 ClassInfo *CI = RegisterClasses[Rec];
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001308 assert(CI && "Missing singleton register class info!");
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001309
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001310 if (CI->ValueName.empty()) {
1311 CI->ClassName = Rec->getName();
1312 CI->Name = "MCK_" + Rec->getName();
1313 CI->ValueName = Rec->getName();
1314 } else
1315 CI->ValueName = CI->ValueName + "," + Rec->getName();
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001316 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001317}
1318
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001319void AsmMatcherInfo::buildOperandClasses() {
Chris Lattnere3c48de2010-11-01 23:57:23 +00001320 std::vector<Record*> AsmOperands =
1321 Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbarcf181532010-01-30 01:02:37 +00001322
1323 // Pre-populate AsmOperandClasses map.
David Blaikied749e342014-11-28 20:35:57 +00001324 for (Record *Rec : AsmOperands) {
1325 Classes.emplace_front();
1326 AsmOperandClasses[Rec] = &Classes.front();
1327 }
Daniel Dunbarcf181532010-01-30 01:02:37 +00001328
Daniel Dunbar17410a42009-08-10 18:41:10 +00001329 unsigned Index = 0;
Craig Topper03ec8012014-11-25 20:11:31 +00001330 for (Record *Rec : AsmOperands) {
1331 ClassInfo *CI = AsmOperandClasses[Rec];
Daniel Dunbar17410a42009-08-10 18:41:10 +00001332 CI->Kind = ClassInfo::UserClass0 + Index;
1333
Craig Topper03ec8012014-11-25 20:11:31 +00001334 ListInit *Supers = Rec->getValueAsListInit("SuperClasses");
Craig Topperef0578a2015-06-02 04:15:51 +00001335 for (Init *I : Supers->getValues()) {
1336 DefInit *DI = dyn_cast<DefInit>(I);
Daniel Dunbar346782c2010-05-22 21:02:29 +00001337 if (!DI) {
Craig Topper03ec8012014-11-25 20:11:31 +00001338 PrintError(Rec->getLoc(), "Invalid super class reference!");
Daniel Dunbar346782c2010-05-22 21:02:29 +00001339 continue;
1340 }
1341
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001342 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1343 if (!SC)
Craig Topper03ec8012014-11-25 20:11:31 +00001344 PrintError(Rec->getLoc(), "Invalid super class reference!");
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001345 else
1346 CI->SuperClasses.push_back(SC);
Daniel Dunbar17410a42009-08-10 18:41:10 +00001347 }
Craig Topper03ec8012014-11-25 20:11:31 +00001348 CI->ClassName = Rec->getValueAsString("Name");
Daniel Dunbar17410a42009-08-10 18:41:10 +00001349 CI->Name = "MCK_" + CI->ClassName;
Craig Topper03ec8012014-11-25 20:11:31 +00001350 CI->ValueName = Rec->getName();
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001351
1352 // Get or construct the predicate method name.
Craig Topper03ec8012014-11-25 20:11:31 +00001353 Init *PMName = Rec->getValueInit("PredicateMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001354 if (StringInit *SI = dyn_cast<StringInit>(PMName)) {
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001355 CI->PredicateMethod = SI->getValue();
1356 } else {
Sean Silva88eb8dd2012-10-10 20:24:47 +00001357 assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!");
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001358 CI->PredicateMethod = "is" + CI->ClassName;
1359 }
1360
1361 // Get or construct the render method name.
Craig Topper03ec8012014-11-25 20:11:31 +00001362 Init *RMName = Rec->getValueInit("RenderMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001363 if (StringInit *SI = dyn_cast<StringInit>(RMName)) {
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001364 CI->RenderMethod = SI->getValue();
1365 } else {
Sean Silva88eb8dd2012-10-10 20:24:47 +00001366 assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!");
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001367 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1368 }
1369
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001370 // Get the parse method name or leave it as empty.
Craig Topper03ec8012014-11-25 20:11:31 +00001371 Init *PRMName = Rec->getValueInit("ParserMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001372 if (StringInit *SI = dyn_cast<StringInit>(PRMName))
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001373 CI->ParserMethod = SI->getValue();
1374
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001375 // Get the diagnostic type or leave it as empty.
1376 // Get the parse method name or leave it as empty.
Craig Topper03ec8012014-11-25 20:11:31 +00001377 Init *DiagnosticType = Rec->getValueInit("DiagnosticType");
Sean Silvafb509ed2012-10-10 20:24:43 +00001378 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001379 CI->DiagnosticType = SI->getValue();
1380
Tom Stellardb9f235e2016-02-05 19:59:33 +00001381 Init *IsOptional = Rec->getValueInit("IsOptional");
1382 if (BitInit *BI = dyn_cast<BitInit>(IsOptional))
1383 CI->IsOptional = BI->getValue();
1384
Sam Kolton5f10a132016-05-06 11:31:17 +00001385 // Get or construct the default method name.
1386 Init *DMName = Rec->getValueInit("DefaultMethod");
1387 if (StringInit *SI = dyn_cast<StringInit>(DMName)) {
1388 CI->DefaultMethod = SI->getValue();
1389 } else {
1390 assert(isa<UnsetInit>(DMName) && "Unexpected DefaultMethod field!");
1391 CI->DefaultMethod = "default" + CI->ClassName + "Operands";
1392 }
1393
Craig Topper03ec8012014-11-25 20:11:31 +00001394 ++Index;
Daniel Dunbar17410a42009-08-10 18:41:10 +00001395 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001396}
1397
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001398AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1399 CodeGenTarget &target,
Chris Lattner89dcb682010-12-15 04:48:22 +00001400 RecordKeeper &records)
Devang Patel6d676e42012-01-07 01:33:34 +00001401 : Records(records), AsmParser(asmParser), Target(target) {
Daniel Dunbare4318712009-08-11 20:59:47 +00001402}
1403
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001404/// buildOperandMatchInfo - Build the necessary information to handle user
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001405/// defined operand parsing methods.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001406void AsmMatcherInfo::buildOperandMatchInfo() {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001407
Jim Grosbach925a6d02012-04-18 23:46:25 +00001408 /// Map containing a mask with all operands indices that can be found for
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001409 /// that class inside a instruction.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00001410 typedef std::map<ClassInfo *, unsigned, less_ptr<ClassInfo>> OpClassMaskTy;
Sean Silva835139b2012-09-19 01:47:03 +00001411 OpClassMaskTy OpClassMask;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001412
Craig Topperf34dad92014-11-28 03:53:02 +00001413 for (const auto &MI : Matchables) {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001414 OpClassMask.clear();
1415
1416 // Keep track of all operands of this instructions which belong to the
1417 // same class.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001418 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
1419 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001420 if (Op.Class->ParserMethod.empty())
1421 continue;
1422 unsigned &OperandMask = OpClassMask[Op.Class];
1423 OperandMask |= (1 << i);
1424 }
1425
1426 // Generate operand match info for each mnemonic/operand class pair.
Craig Topper42bd8192014-11-28 03:53:00 +00001427 for (const auto &OCM : OpClassMask) {
1428 unsigned OpMask = OCM.second;
1429 ClassInfo *CI = OCM.first;
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001430 OperandMatchInfo.push_back(OperandMatchEntry::create(MI.get(), CI,
1431 OpMask));
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001432 }
1433 }
1434}
1435
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001436void AsmMatcherInfo::buildInfo() {
Chris Lattnera0e87192010-10-30 20:07:57 +00001437 // Build information about all of the AssemblerPredicates.
1438 std::vector<Record*> AllPredicates =
1439 Records.getAllDerivedDefinitions("Predicate");
Craig Topper6e526f12016-01-03 07:33:30 +00001440 for (Record *Pred : AllPredicates) {
Chris Lattnera0e87192010-10-30 20:07:57 +00001441 // Ignore predicates that are not intended for the assembler.
1442 if (!Pred->getValueAsBit("AssemblerMatcherPredicate"))
1443 continue;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001444
Chris Lattner178f4bb2010-11-01 04:44:29 +00001445 if (Pred->getName().empty())
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001446 PrintFatalError(Pred->getLoc(), "Predicate has no name!");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001447
David Blaikie9a9da992014-11-28 22:15:06 +00001448 SubtargetFeatures.insert(std::make_pair(
1449 Pred, SubtargetFeatureInfo(Pred, SubtargetFeatures.size())));
1450 DEBUG(SubtargetFeatures.find(Pred)->second.dump());
1451 assert(SubtargetFeatures.size() <= 64 && "Too many subtarget features!");
Chris Lattnera0e87192010-10-30 20:07:57 +00001452 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001453
Craig Topperfd2c6a32015-12-31 08:18:23 +00001454 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
1455
Chris Lattner33fc3e02010-10-31 19:10:56 +00001456 // Parse the instructions; we need to do this first so that we can gather the
1457 // singleton register classes.
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001458 SmallPtrSet<Record*, 16> SingletonRegisters;
Devang Patel85d684a2012-01-09 19:13:28 +00001459 unsigned VariantCount = Target.getAsmParserVariantCount();
1460 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1461 Record *AsmVariant = Target.getAsmParserVariant(VC);
Jim Grosbach56e63262012-04-17 00:01:04 +00001462 std::string CommentDelimiter =
1463 AsmVariant->getValueAsString("CommentDelimiter");
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001464 AsmVariantInfo Variant;
Craig Topperc8b5b252015-12-30 06:00:18 +00001465 Variant.RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001466 Variant.TokenizingCharacters =
1467 AsmVariant->getValueAsString("TokenizingCharacters");
1468 Variant.SeparatorCharacters =
1469 AsmVariant->getValueAsString("SeparatorCharacters");
1470 Variant.BreakCharacters =
1471 AsmVariant->getValueAsString("BreakCharacters");
Sam Kolton1b746d12016-09-08 15:50:52 +00001472 Variant.Name = AsmVariant->getValueAsString("Name");
Craig Topperc8b5b252015-12-30 06:00:18 +00001473 Variant.AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001474
Craig Topper8cc904d2016-01-17 20:38:18 +00001475 for (const CodeGenInstruction *CGI : Target.getInstructionsByEnumValue()) {
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001476
Devang Patel85d684a2012-01-09 19:13:28 +00001477 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1478 // filter the set of instructions we consider.
Craig Topper03ec8012014-11-25 20:11:31 +00001479 if (!StringRef(CGI->TheDef->getName()).startswith(MatchPrefix))
Jim Grosbach3263a072012-04-11 21:02:33 +00001480 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001481
Devang Patel85d684a2012-01-09 19:13:28 +00001482 // Ignore "codegen only" instructions.
Craig Topper03ec8012014-11-25 20:11:31 +00001483 if (CGI->TheDef->getValueAsBit("isCodeGenOnly"))
Jim Grosbach3263a072012-04-11 21:02:33 +00001484 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001485
Sam Kolton1b746d12016-09-08 15:50:52 +00001486 // Ignore instructions for different instructions
1487 const std::string V = CGI->TheDef->getValueAsString("AsmVariantName");
1488 if (!V.empty() && V != Variant.Name)
1489 continue;
1490
Craig Topper1c8fbd22015-09-06 03:44:50 +00001491 auto II = llvm::make_unique<MatchableInfo>(*CGI);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001492
Craig Topperfd2c6a32015-12-31 08:18:23 +00001493 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001494
Devang Patel85d684a2012-01-09 19:13:28 +00001495 // Ignore instructions which shouldn't be matched and diagnose invalid
1496 // instruction definitions with an error.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001497 if (!II->validate(CommentDelimiter, true))
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001498 continue;
1499
1500 Matchables.push_back(std::move(II));
Chris Lattner743081d2010-11-04 00:43:46 +00001501 }
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001502
Devang Patel85d684a2012-01-09 19:13:28 +00001503 // Parse all of the InstAlias definitions and stick them in the list of
1504 // matchables.
1505 std::vector<Record*> AllInstAliases =
1506 Records.getAllDerivedDefinitions("InstAlias");
1507 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
David Blaikieba4e00f2014-12-22 21:26:26 +00001508 auto Alias = llvm::make_unique<CodeGenInstAlias>(AllInstAliases[i],
Craig Topperc8b5b252015-12-30 06:00:18 +00001509 Variant.AsmVariantNo,
1510 Target);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001511
Devang Patel85d684a2012-01-09 19:13:28 +00001512 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1513 // filter the set of instruction aliases we consider, based on the target
1514 // instruction.
Jim Grosbach56e63262012-04-17 00:01:04 +00001515 if (!StringRef(Alias->ResultInst->TheDef->getName())
1516 .startswith( MatchPrefix))
Jim Grosbach3263a072012-04-11 21:02:33 +00001517 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001518
Sam Kolton1b746d12016-09-08 15:50:52 +00001519 const std::string V = Alias->TheDef->getValueAsString("AsmVariantName");
1520 if (!V.empty() && V != Variant.Name)
1521 continue;
1522
Craig Topper1c8fbd22015-09-06 03:44:50 +00001523 auto II = llvm::make_unique<MatchableInfo>(std::move(Alias));
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001524
Craig Topperfd2c6a32015-12-31 08:18:23 +00001525 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001526
Devang Patel85d684a2012-01-09 19:13:28 +00001527 // Validate the alias definitions.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001528 II->validate(CommentDelimiter, false);
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001529
1530 Matchables.push_back(std::move(II));
Devang Patel85d684a2012-01-09 19:13:28 +00001531 }
Chris Lattner488c2012010-11-01 04:05:41 +00001532 }
Chris Lattnerd8adec72010-11-01 04:03:32 +00001533
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001534 // Build info for the register classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001535 buildRegisterClasses(SingletonRegisters);
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001536
1537 // Build info for the user defined assembly operand classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001538 buildOperandClasses();
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001539
Chris Lattner4779e3e92010-11-04 00:57:06 +00001540 // Build the information about matchables, now that we have fully formed
1541 // classes.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001542 std::vector<std::unique_ptr<MatchableInfo>> NewMatchables;
Craig Topperf34dad92014-11-28 03:53:02 +00001543 for (auto &II : Matchables) {
Chris Lattner82d88ce2010-09-06 21:01:37 +00001544 // Parse the tokens after the mnemonic.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001545 // Note: buildInstructionOperandReference may insert new AsmOperands, so
Bob Wilsonb9b24222011-01-26 19:44:55 +00001546 // don't precompute the loop bound.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001547 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1548 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
Chris Lattner28ea9b12010-11-02 17:30:52 +00001549 StringRef Token = Op.Token;
Daniel Dunbare10787e2009-08-07 08:26:05 +00001550
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001551 // Check for singleton registers.
Craig Toppere4e74152015-12-29 07:03:23 +00001552 if (Record *RegRecord = Op.SingletonReg) {
Chris Lattner28ea9b12010-11-02 17:30:52 +00001553 Op.Class = RegisterClasses[RegRecord];
Chris Lattnerb80ab362010-11-01 01:37:30 +00001554 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1555 "Unexpected class for singleton register");
Chris Lattnerb80ab362010-11-01 01:37:30 +00001556 continue;
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001557 }
1558
Daniel Dunbare10787e2009-08-07 08:26:05 +00001559 // Check for simple tokens.
1560 if (Token[0] != '$') {
Chris Lattner28ea9b12010-11-02 17:30:52 +00001561 Op.Class = getTokenClass(Token);
Daniel Dunbare10787e2009-08-07 08:26:05 +00001562 continue;
1563 }
1564
Chris Lattnerd6746d52010-11-06 22:06:03 +00001565 if (Token.size() > 1 && isdigit(Token[1])) {
1566 Op.Class = getTokenClass(Token);
1567 continue;
1568 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001569
Chris Lattner4efe13d2010-11-04 02:11:18 +00001570 // Otherwise this is an operand reference.
Chris Lattnerccde4632010-11-04 01:58:23 +00001571 StringRef OperandName;
1572 if (Token[1] == '{')
1573 OperandName = Token.substr(2, Token.size() - 3);
1574 else
1575 OperandName = Token.substr(1);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001576
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001577 if (II->DefRec.is<const CodeGenInstruction*>())
1578 buildInstructionOperandReference(II.get(), OperandName, i);
Chris Lattner4efe13d2010-11-04 02:11:18 +00001579 else
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001580 buildAliasOperandReference(II.get(), OperandName, Op);
Daniel Dunbare10787e2009-08-07 08:26:05 +00001581 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001582
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001583 if (II->DefRec.is<const CodeGenInstruction*>()) {
1584 II->buildInstructionResultOperands();
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001585 // If the instruction has a two-operand alias, build up the
1586 // matchable here. We'll add them in bulk at the end to avoid
1587 // confusing this loop.
1588 std::string Constraint =
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001589 II->TheDef->getValueAsString("TwoOperandAliasConstraint");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001590 if (Constraint != "") {
1591 // Start by making a copy of the original matchable.
Craig Topper1c8fbd22015-09-06 03:44:50 +00001592 auto AliasII = llvm::make_unique<MatchableInfo>(*II);
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001593
1594 // Adjust it to be a two-operand alias.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001595 AliasII->formTwoOperandAlias(Constraint);
1596
1597 // Add the alias to the matchables list.
1598 NewMatchables.push_back(std::move(AliasII));
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001599 }
1600 } else
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001601 II->buildAliasResultOperands();
Daniel Dunbare10787e2009-08-07 08:26:05 +00001602 }
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001603 if (!NewMatchables.empty())
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001604 Matchables.insert(Matchables.end(),
1605 std::make_move_iterator(NewMatchables.begin()),
1606 std::make_move_iterator(NewMatchables.end()));
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001607
Jim Grosbachba395922011-12-06 23:43:54 +00001608 // Process token alias definitions and set up the associated superclass
1609 // information.
1610 std::vector<Record*> AllTokenAliases =
1611 Records.getAllDerivedDefinitions("TokenAlias");
Craig Toppere4e74152015-12-29 07:03:23 +00001612 for (Record *Rec : AllTokenAliases) {
Jim Grosbachba395922011-12-06 23:43:54 +00001613 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1614 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
Jim Grosbach37f6dcb32012-04-17 21:23:52 +00001615 if (FromClass == ToClass)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001616 PrintFatalError(Rec->getLoc(),
Jim Grosbach37f6dcb32012-04-17 21:23:52 +00001617 "error: Destination value identical to source value.");
Jim Grosbachba395922011-12-06 23:43:54 +00001618 FromClass->SuperClasses.push_back(ToClass);
1619 }
1620
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001621 // Reorder classes so that classes precede super classes.
David Blaikied749e342014-11-28 20:35:57 +00001622 Classes.sort();
Oliver Stannard7772f022016-01-25 10:20:19 +00001623
1624#ifndef NDEBUG
1625 // Verify that the table is now sorted
1626 for (auto I = Classes.begin(), E = Classes.end(); I != E; ++I) {
1627 for (auto J = I; J != E; ++J) {
1628 assert(!(*J < *I));
1629 assert(I == J || !J->isSubsetOf(*I));
1630 }
1631 }
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +00001632#endif // NDEBUG
Daniel Dunbare10787e2009-08-07 08:26:05 +00001633}
1634
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001635/// buildInstructionOperandReference - The specified operand is a reference to a
Chris Lattner4779e3e92010-11-04 00:57:06 +00001636/// named operand such as $src. Resolve the Class and OperandInfo pointers.
1637void AsmMatcherInfo::
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001638buildInstructionOperandReference(MatchableInfo *II,
Chris Lattnerccde4632010-11-04 01:58:23 +00001639 StringRef OperandName,
Bob Wilsonb9b24222011-01-26 19:44:55 +00001640 unsigned AsmOpIdx) {
Chris Lattner4efe13d2010-11-04 02:11:18 +00001641 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1642 const CGIOperandList &Operands = CGI.Operands;
Bob Wilsonb9b24222011-01-26 19:44:55 +00001643 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001644
Chris Lattnerfecdad62010-11-06 07:14:44 +00001645 // Map this token to an operand.
Chris Lattner4779e3e92010-11-04 00:57:06 +00001646 unsigned Idx;
1647 if (!Operands.hasOperandNamed(OperandName, Idx))
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001648 PrintFatalError(II->TheDef->getLoc(),
1649 "error: unable to find operand: '" + OperandName + "'");
Chris Lattner897a1402010-11-04 01:55:23 +00001650
Bob Wilsonb9b24222011-01-26 19:44:55 +00001651 // If the instruction operand has multiple suboperands, but the parser
1652 // match class for the asm operand is still the default "ImmAsmOperand",
1653 // then handle each suboperand separately.
1654 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1655 Record *Rec = Operands[Idx].Rec;
1656 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1657 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1658 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1659 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1660 StringRef Token = Op->Token; // save this in case Op gets moved
1661 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
Ahmed Bougachaeb4dbd82015-05-29 01:03:37 +00001662 MatchableInfo::AsmOperand NewAsmOp(/*IsIsolatedToken=*/true, Token);
Bob Wilsonb9b24222011-01-26 19:44:55 +00001663 NewAsmOp.SubOpIdx = SI;
1664 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1665 }
1666 // Replace Op with first suboperand.
1667 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1668 Op->SubOpIdx = 0;
1669 }
1670 }
1671
Chris Lattner897a1402010-11-04 01:55:23 +00001672 // Set up the operand class.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001673 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
Chris Lattner897a1402010-11-04 01:55:23 +00001674
1675 // If the named operand is tied, canonicalize it to the untied operand.
1676 // For example, something like:
1677 // (outs GPR:$dst), (ins GPR:$src)
1678 // with an asmstring of
1679 // "inc $src"
1680 // we want to canonicalize to:
1681 // "inc $dst"
1682 // so that we know how to provide the $dst operand when filling in the result.
Ulrich Weigande037a492013-04-27 18:48:23 +00001683 int OITied = -1;
1684 if (Operands[Idx].MINumOperands == 1)
1685 OITied = Operands[Idx].getTiedRegister();
Chris Lattner4779e3e92010-11-04 00:57:06 +00001686 if (OITied != -1) {
1687 // The tied operand index is an MIOperand index, find the operand that
1688 // contains it.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001689 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1690 OperandName = Operands[Idx.first].Name;
1691 Op->SubOpIdx = Idx.second;
Chris Lattner4779e3e92010-11-04 00:57:06 +00001692 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001693
Bob Wilsonb9b24222011-01-26 19:44:55 +00001694 Op->SrcOpName = OperandName;
Chris Lattner4779e3e92010-11-04 00:57:06 +00001695}
1696
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001697/// buildAliasOperandReference - When parsing an operand reference out of the
Chris Lattnerb625dd22010-11-06 07:06:09 +00001698/// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1699/// operand reference is by looking it up in the result pattern definition.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001700void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
Chris Lattner4efe13d2010-11-04 02:11:18 +00001701 StringRef OperandName,
1702 MatchableInfo::AsmOperand &Op) {
1703 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001704
Chris Lattner4efe13d2010-11-04 02:11:18 +00001705 // Set up the operand class.
Chris Lattnerb625dd22010-11-06 07:06:09 +00001706 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
Chris Lattnerb6f8e822010-11-06 19:25:43 +00001707 if (CGA.ResultOperands[i].isRecord() &&
1708 CGA.ResultOperands[i].getName() == OperandName) {
Chris Lattnerfecdad62010-11-06 07:14:44 +00001709 // It's safe to go with the first one we find, because CodeGenInstAlias
1710 // validates that all operands with the same name have the same record.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001711 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001712 // Use the match class from the Alias definition, not the
1713 // destination instruction, as we may have an immediate that's
1714 // being munged by the match class.
1715 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
Bob Wilsonb9b24222011-01-26 19:44:55 +00001716 Op.SubOpIdx);
Chris Lattnerb625dd22010-11-06 07:06:09 +00001717 Op.SrcOpName = OperandName;
1718 return;
Chris Lattner4efe13d2010-11-04 02:11:18 +00001719 }
Chris Lattnerb625dd22010-11-06 07:06:09 +00001720
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001721 PrintFatalError(II->TheDef->getLoc(),
1722 "error: unable to find operand: '" + OperandName + "'");
Chris Lattner4efe13d2010-11-04 02:11:18 +00001723}
1724
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001725void MatchableInfo::buildInstructionResultOperands() {
Chris Lattnerfecdad62010-11-06 07:14:44 +00001726 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001727
Chris Lattnerfecdad62010-11-06 07:14:44 +00001728 // Loop over all operands of the result instruction, determining how to
1729 // populate them.
Craig Toppere4e74152015-12-29 07:03:23 +00001730 for (const CGIOperandList::OperandInfo &OpInfo : ResultInst->Operands) {
Chris Lattner7108dad2010-11-04 01:42:59 +00001731 // If this is a tied operand, just copy from the previously handled operand.
Ulrich Weigande037a492013-04-27 18:48:23 +00001732 int TiedOp = -1;
1733 if (OpInfo.MINumOperands == 1)
1734 TiedOp = OpInfo.getTiedRegister();
Chris Lattner7108dad2010-11-04 01:42:59 +00001735 if (TiedOp != -1) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001736 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
Chris Lattner7108dad2010-11-04 01:42:59 +00001737 continue;
1738 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001739
Bob Wilsonb9b24222011-01-26 19:44:55 +00001740 // Find out what operand from the asmparser this MCInst operand comes from.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001741 int SrcOperand = findAsmOperandNamed(OpInfo.Name);
Ulrich Weigande037a492013-04-27 18:48:23 +00001742 if (OpInfo.Name.empty() || SrcOperand == -1) {
1743 // This may happen for operands that are tied to a suboperand of a
1744 // complex operand. Simply use a dummy value here; nobody should
1745 // use this operand slot.
1746 // FIXME: The long term goal is for the MCOperand list to not contain
1747 // tied operands at all.
1748 ResOperands.push_back(ResOperand::getImmOp(0));
1749 continue;
1750 }
Chris Lattner7108dad2010-11-04 01:42:59 +00001751
Bob Wilsonb9b24222011-01-26 19:44:55 +00001752 // Check if the one AsmOperand populates the entire operand.
1753 unsigned NumOperands = OpInfo.MINumOperands;
1754 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1755 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
Chris Lattner743081d2010-11-04 00:43:46 +00001756 continue;
1757 }
Bob Wilsonb9b24222011-01-26 19:44:55 +00001758
1759 // Add a separate ResOperand for each suboperand.
1760 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1761 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1762 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1763 "unexpected AsmOperands for suboperands");
1764 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1765 }
Chris Lattner743081d2010-11-04 00:43:46 +00001766 }
1767}
1768
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001769void MatchableInfo::buildAliasResultOperands() {
Chris Lattner8188fb22010-11-06 07:31:43 +00001770 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1771 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001772
Chris Lattner8188fb22010-11-06 07:31:43 +00001773 // Loop over all operands of the result instruction, determining how to
1774 // populate them.
1775 unsigned AliasOpNo = 0;
Bob Wilsonb9b24222011-01-26 19:44:55 +00001776 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
Chris Lattner8188fb22010-11-06 07:31:43 +00001777 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001778 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001779
Chris Lattner8188fb22010-11-06 07:31:43 +00001780 // If this is a tied operand, just copy from the previously handled operand.
Ulrich Weigande037a492013-04-27 18:48:23 +00001781 int TiedOp = -1;
1782 if (OpInfo->MINumOperands == 1)
1783 TiedOp = OpInfo->getTiedRegister();
Chris Lattner8188fb22010-11-06 07:31:43 +00001784 if (TiedOp != -1) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001785 ResOperands.push_back(ResOperand::getTiedOp(TiedOp));
Chris Lattner4869d342010-11-06 19:57:21 +00001786 continue;
1787 }
1788
Bob Wilsonb9b24222011-01-26 19:44:55 +00001789 // Handle all the suboperands for this operand.
1790 const std::string &OpName = OpInfo->Name;
1791 for ( ; AliasOpNo < LastOpNo &&
1792 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1793 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1794
1795 // Find out what operand from the asmparser that this MCInst operand
1796 // comes from.
1797 switch (CGA.ResultOperands[AliasOpNo].Kind) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001798 case CodeGenInstAlias::ResultOperand::K_Record: {
1799 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001800 int SrcOperand = findAsmOperand(Name, SubIdx);
Bob Wilsonb9b24222011-01-26 19:44:55 +00001801 if (SrcOperand == -1)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001802 PrintFatalError(TheDef->getLoc(), "Instruction '" +
Bob Wilsonb9b24222011-01-26 19:44:55 +00001803 TheDef->getName() + "' has operand '" + OpName +
1804 "' that doesn't appear in asm string!");
1805 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1806 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1807 NumOperands));
1808 break;
1809 }
1810 case CodeGenInstAlias::ResultOperand::K_Imm: {
1811 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1812 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1813 break;
1814 }
1815 case CodeGenInstAlias::ResultOperand::K_Reg: {
1816 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1817 ResOperands.push_back(ResOperand::getRegOp(Reg));
1818 break;
1819 }
1820 }
Chris Lattner4869d342010-11-06 19:57:21 +00001821 }
Chris Lattner8188fb22010-11-06 07:31:43 +00001822 }
1823}
Chris Lattner743081d2010-11-04 00:43:46 +00001824
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001825static unsigned getConverterOperandID(const std::string &Name,
Rafael Espindola55512f92015-11-18 06:52:18 +00001826 SmallSetVector<std::string, 16> &Table,
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001827 bool &IsNew) {
1828 IsNew = Table.insert(Name);
1829
David Majnemer0d955d02016-08-11 22:21:41 +00001830 unsigned ID = IsNew ? Table.size() - 1 : find(Table, Name) - Table.begin();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001831
1832 assert(ID < Table.size());
1833
1834 return ID;
1835}
1836
Chad Rosierf4e35dc2012-10-01 23:45:51 +00001837static void emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName,
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001838 std::vector<std::unique_ptr<MatchableInfo>> &Infos,
Sam Kolton5f10a132016-05-06 11:31:17 +00001839 bool HasMnemonicFirst, bool HasOptionalOperands,
1840 raw_ostream &OS) {
Rafael Espindola55512f92015-11-18 06:52:18 +00001841 SmallSetVector<std::string, 16> OperandConversionKinds;
1842 SmallSetVector<std::string, 16> InstructionConversionKinds;
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001843 std::vector<std::vector<uint8_t> > ConversionTable;
1844 size_t MaxRowLength = 2; // minimum is custom converter plus terminator.
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001845
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001846 // TargetOperandClass - This is the target's operand class, like X86Operand.
1847 std::string TargetOperandClass = Target.getName() + "Operand";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001848
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001849 // Write the convert function to a separate stream, so we can drop it after
1850 // the enum. We'll build up the conversion handlers for the individual
1851 // operand types opportunistically as we encounter them.
1852 std::string ConvertFnBody;
1853 raw_string_ostream CvtOS(ConvertFnBody);
1854 // Start the unified conversion function.
Sam Kolton5f10a132016-05-06 11:31:17 +00001855 if (HasOptionalOperands) {
1856 CvtOS << "void " << Target.getName() << ClassName << "::\n"
1857 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1858 << "unsigned Opcode,\n"
1859 << " const OperandVector &Operands,\n"
1860 << " const SmallBitVector &OptionalOperandsMask) {\n";
1861 } else {
1862 CvtOS << "void " << Target.getName() << ClassName << "::\n"
1863 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1864 << "unsigned Opcode,\n"
1865 << " const OperandVector &Operands) {\n";
1866 }
1867 CvtOS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
1868 CvtOS << " const uint8_t *Converter = ConversionTable[Kind];\n";
1869 if (HasOptionalOperands) {
1870 CvtOS << " unsigned NumDefaults = 0;\n";
1871 }
1872 CvtOS << " unsigned OpIdx;\n";
1873 CvtOS << " Inst.setOpcode(Opcode);\n";
1874 CvtOS << " for (const uint8_t *p = Converter; *p; p+= 2) {\n";
1875 if (HasOptionalOperands) {
1876 CvtOS << " OpIdx = *(p + 1) - NumDefaults;\n";
1877 } else {
1878 CvtOS << " OpIdx = *(p + 1);\n";
1879 }
1880 CvtOS << " switch (*p) {\n";
1881 CvtOS << " default: llvm_unreachable(\"invalid conversion entry!\");\n";
1882 CvtOS << " case CVT_Reg:\n";
1883 CvtOS << " static_cast<" << TargetOperandClass
1884 << "&>(*Operands[OpIdx]).addRegOperands(Inst, 1);\n";
1885 CvtOS << " break;\n";
1886 CvtOS << " case CVT_Tied:\n";
1887 CvtOS << " Inst.addOperand(Inst.getOperand(OpIdx));\n";
1888 CvtOS << " break;\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001889
Chad Rosier738ea252012-08-30 17:59:25 +00001890 std::string OperandFnBody;
1891 raw_string_ostream OpOS(OperandFnBody);
1892 // Start the operand number lookup function.
Chad Rosierf4e35dc2012-10-01 23:45:51 +00001893 OpOS << "void " << Target.getName() << ClassName << "::\n"
1894 << "convertToMapAndConstraints(unsigned Kind,\n";
Chad Rosier380a74a2012-10-02 00:25:57 +00001895 OpOS.indent(27);
David Blaikie960ea3f2014-06-08 16:18:35 +00001896 OpOS << "const OperandVector &Operands) {\n"
Chad Rosier98cfa102012-08-31 00:03:31 +00001897 << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00001898 << " unsigned NumMCOperands = 0;\n"
Craig Topper91506102012-09-18 01:41:49 +00001899 << " const uint8_t *Converter = ConversionTable[Kind];\n"
1900 << " for (const uint8_t *p = Converter; *p; p+= 2) {\n"
Chad Rosier738ea252012-08-30 17:59:25 +00001901 << " switch (*p) {\n"
1902 << " default: llvm_unreachable(\"invalid conversion entry!\");\n"
1903 << " case CVT_Reg:\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00001904 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
Chad Rosier72450332013-01-15 23:07:53 +00001905 << " Operands[*(p + 1)]->setConstraint(\"r\");\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00001906 << " ++NumMCOperands;\n"
1907 << " break;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00001908 << " case CVT_Tied:\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00001909 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00001910 << " break;\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001911
1912 // Pre-populate the operand conversion kinds with the standard always
1913 // available entries.
1914 OperandConversionKinds.insert("CVT_Done");
1915 OperandConversionKinds.insert("CVT_Reg");
1916 OperandConversionKinds.insert("CVT_Tied");
1917 enum { CVT_Done, CVT_Reg, CVT_Tied };
1918
Craig Topperf34dad92014-11-28 03:53:02 +00001919 for (auto &II : Infos) {
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001920 // Check if we have a custom match function.
Daniel Dunbar5f74b392011-04-01 20:23:52 +00001921 std::string AsmMatchConverter =
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001922 II->getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
Tom Stellard74c87c82015-05-26 15:55:50 +00001923 if (!AsmMatchConverter.empty() && II->UseInstAsmMatchConverter) {
Daniel Dunbar5f74b392011-04-01 20:23:52 +00001924 std::string Signature = "ConvertCustom_" + AsmMatchConverter;
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001925 II->ConversionFnKind = Signature;
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001926
1927 // Check if we have already generated this signature.
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001928 if (!InstructionConversionKinds.insert(Signature))
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001929 continue;
1930
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001931 // Remember this converter for the kind enum.
1932 unsigned KindID = OperandConversionKinds.size();
Tim Northoverb3cfb282013-01-10 16:47:31 +00001933 OperandConversionKinds.insert("CVT_" +
1934 getEnumNameForToken(AsmMatchConverter));
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001935
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001936 // Add the converter row for this instruction.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001937 ConversionTable.emplace_back();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001938 ConversionTable.back().push_back(KindID);
1939 ConversionTable.back().push_back(CVT_Done);
1940
1941 // Add the handler to the conversion driver function.
Tim Northoverb3cfb282013-01-10 16:47:31 +00001942 CvtOS << " case CVT_"
1943 << getEnumNameForToken(AsmMatchConverter) << ":\n"
Chad Rosier451ef132012-08-31 22:12:31 +00001944 << " " << AsmMatchConverter << "(Inst, Operands);\n"
Chad Rosier98cfa102012-08-31 00:03:31 +00001945 << " break;\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001946
Chad Rosier738ea252012-08-30 17:59:25 +00001947 // FIXME: Handle the operand number lookup for custom match functions.
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00001948 continue;
1949 }
1950
Daniel Dunbare10787e2009-08-07 08:26:05 +00001951 // Build the conversion function signature.
1952 std::string Signature = "Convert";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001953
1954 std::vector<uint8_t> ConversionRow;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001955
Chris Lattner5cf8a4a2010-11-02 21:49:44 +00001956 // Compute the convert enum and the case body.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001957 MaxRowLength = std::max(MaxRowLength, II->ResOperands.size()*2 + 1 );
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001958
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001959 for (unsigned i = 0, e = II->ResOperands.size(); i != e; ++i) {
1960 const MatchableInfo::ResOperand &OpInfo = II->ResOperands[i];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001961
Chris Lattner743081d2010-11-04 00:43:46 +00001962 // Generate code to populate each result operand.
1963 switch (OpInfo.Kind) {
Chris Lattner743081d2010-11-04 00:43:46 +00001964 case MatchableInfo::ResOperand::RenderAsmOperand: {
1965 // This comes from something we parsed.
Craig Topper03ec8012014-11-25 20:11:31 +00001966 const MatchableInfo::AsmOperand &Op =
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001967 II->AsmOperands[OpInfo.AsmOperandNum];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001968
Chris Lattnere032dbf2010-11-02 22:55:03 +00001969 // Registers are always converted the same, don't duplicate the
1970 // conversion function based on them.
Chris Lattnere032dbf2010-11-02 22:55:03 +00001971 Signature += "__";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001972 std::string Class;
1973 Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName;
1974 Signature += Class;
Bob Wilsonb9b24222011-01-26 19:44:55 +00001975 Signature += utostr(OpInfo.MINumOperands);
Chris Lattner743081d2010-11-04 00:43:46 +00001976 Signature += "_" + itostr(OpInfo.AsmOperandNum);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001977
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001978 // Add the conversion kind, if necessary, and get the associated ID
1979 // the index of its entry in the vector).
1980 std::string Name = "CVT_" + (Op.Class->isRegisterClass() ? "Reg" :
1981 Op.Class->RenderMethod);
Sam Kolton5f10a132016-05-06 11:31:17 +00001982 if (Op.Class->IsOptional) {
1983 // For optional operands we must also care about DefaultMethod
1984 assert(HasOptionalOperands);
1985 Name += "_" + Op.Class->DefaultMethod;
1986 }
Tim Northoverb3cfb282013-01-10 16:47:31 +00001987 Name = getEnumNameForToken(Name);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001988
1989 bool IsNewConverter = false;
1990 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
1991 IsNewConverter);
1992
1993 // Add the operand entry to the instruction kind conversion row.
1994 ConversionRow.push_back(ID);
Craig Topperfd2c6a32015-12-31 08:18:23 +00001995 ConversionRow.push_back(OpInfo.AsmOperandNum + HasMnemonicFirst);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001996
1997 if (!IsNewConverter)
1998 break;
1999
2000 // This is a new operand kind. Add a handler for it to the
2001 // converter driver.
Sam Kolton5f10a132016-05-06 11:31:17 +00002002 CvtOS << " case " << Name << ":\n";
2003 if (Op.Class->IsOptional) {
2004 // If optional operand is not present in actual instruction then we
2005 // should call its DefaultMethod before RenderMethod
2006 assert(HasOptionalOperands);
2007 CvtOS << " if (OptionalOperandsMask[*(p + 1) - 1]) {\n"
2008 << " " << Op.Class->DefaultMethod << "()"
2009 << "->" << Op.Class->RenderMethod << "(Inst, "
2010 << OpInfo.MINumOperands << ");\n"
2011 << " ++NumDefaults;\n"
2012 << " } else {\n"
2013 << " static_cast<" << TargetOperandClass
2014 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod
2015 << "(Inst, " << OpInfo.MINumOperands << ");\n"
2016 << " }\n";
2017 } else {
2018 CvtOS << " static_cast<" << TargetOperandClass
2019 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod
2020 << "(Inst, " << OpInfo.MINumOperands << ");\n";
2021 }
2022 CvtOS << " break;\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002023
2024 // Add a handler for the operand number lookup.
2025 OpOS << " case " << Name << ":\n"
Chad Rosier72450332013-01-15 23:07:53 +00002026 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n";
2027
2028 if (Op.Class->isRegisterClass())
2029 OpOS << " Operands[*(p + 1)]->setConstraint(\"r\");\n";
2030 else
2031 OpOS << " Operands[*(p + 1)]->setConstraint(\"m\");\n";
2032 OpOS << " NumMCOperands += " << OpInfo.MINumOperands << ";\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002033 << " break;\n";
Chris Lattner743081d2010-11-04 00:43:46 +00002034 break;
Daniel Dunbarf22553a2010-02-10 08:15:48 +00002035 }
Chris Lattner743081d2010-11-04 00:43:46 +00002036 case MatchableInfo::ResOperand::TiedOperand: {
2037 // If this operand is tied to a previous one, just copy the MCInst
2038 // operand from the earlier one.We can only tie single MCOperand values.
Ulrich Weigande037a492013-04-27 18:48:23 +00002039 assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
Chris Lattner743081d2010-11-04 00:43:46 +00002040 unsigned TiedOp = OpInfo.TiedOperandNum;
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002041 assert(i > TiedOp && "Tied operand precedes its target!");
Chris Lattner743081d2010-11-04 00:43:46 +00002042 Signature += "__Tie" + utostr(TiedOp);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002043 ConversionRow.push_back(CVT_Tied);
2044 ConversionRow.push_back(TiedOp);
Chris Lattner743081d2010-11-04 00:43:46 +00002045 break;
2046 }
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002047 case MatchableInfo::ResOperand::ImmOperand: {
2048 int64_t Val = OpInfo.ImmVal;
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002049 std::string Ty = "imm_" + itostr(Val);
Hal Finkelf9090722015-01-15 01:33:00 +00002050 Ty = getEnumNameForToken(Ty);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002051 Signature += "__" + Ty;
2052
2053 std::string Name = "CVT_" + Ty;
2054 bool IsNewConverter = false;
2055 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2056 IsNewConverter);
2057 // Add the operand entry to the instruction kind conversion row.
2058 ConversionRow.push_back(ID);
2059 ConversionRow.push_back(0);
2060
2061 if (!IsNewConverter)
2062 break;
2063
2064 CvtOS << " case " << Name << ":\n"
Jim Grosbache9119e42015-05-13 18:37:00 +00002065 << " Inst.addOperand(MCOperand::createImm(" << Val << "));\n"
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002066 << " break;\n";
2067
Chad Rosier738ea252012-08-30 17:59:25 +00002068 OpOS << " case " << Name << ":\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002069 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2070 << " Operands[*(p + 1)]->setConstraint(\"\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002071 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002072 << " break;\n";
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002073 break;
2074 }
Chris Lattner4869d342010-11-06 19:57:21 +00002075 case MatchableInfo::ResOperand::RegOperand: {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002076 std::string Reg, Name;
Craig Topper24064772014-04-15 07:20:03 +00002077 if (!OpInfo.Register) {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002078 Name = "reg0";
2079 Reg = "0";
Bob Wilson03912ab2011-01-14 22:58:09 +00002080 } else {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002081 Reg = getQualifiedName(OpInfo.Register);
2082 Name = "reg" + OpInfo.Register->getName();
Bob Wilson03912ab2011-01-14 22:58:09 +00002083 }
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002084 Signature += "__" + Name;
2085 Name = "CVT_" + Name;
2086 bool IsNewConverter = false;
2087 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2088 IsNewConverter);
2089 // Add the operand entry to the instruction kind conversion row.
2090 ConversionRow.push_back(ID);
2091 ConversionRow.push_back(0);
2092
2093 if (!IsNewConverter)
2094 break;
2095 CvtOS << " case " << Name << ":\n"
Jim Grosbache9119e42015-05-13 18:37:00 +00002096 << " Inst.addOperand(MCOperand::createReg(" << Reg << "));\n"
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002097 << " break;\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002098
2099 OpOS << " case " << Name << ":\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002100 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2101 << " Operands[*(p + 1)]->setConstraint(\"m\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002102 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002103 << " break;\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002104 }
Chris Lattner743081d2010-11-04 00:43:46 +00002105 }
Daniel Dunbare10787e2009-08-07 08:26:05 +00002106 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002107
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002108 // If there were no operands, add to the signature to that effect
2109 if (Signature == "Convert")
2110 Signature += "_NoOperands";
2111
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002112 II->ConversionFnKind = Signature;
Daniel Dunbare10787e2009-08-07 08:26:05 +00002113
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002114 // Save the signature. If we already have it, don't add a new row
2115 // to the table.
2116 if (!InstructionConversionKinds.insert(Signature))
Daniel Dunbare10787e2009-08-07 08:26:05 +00002117 continue;
2118
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002119 // Add the row to the table.
Craig Topperc4de7ee2015-08-16 21:27:08 +00002120 ConversionTable.push_back(std::move(ConversionRow));
Daniel Dunbare10787e2009-08-07 08:26:05 +00002121 }
Daniel Dunbar71330282009-08-08 05:24:34 +00002122
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002123 // Finish up the converter driver function.
Chad Rosierc38826c2012-09-03 17:39:57 +00002124 CvtOS << " }\n }\n}\n\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002125
Chad Rosier738ea252012-08-30 17:59:25 +00002126 // Finish up the operand number lookup function.
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002127 OpOS << " }\n }\n}\n\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002128
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002129 OS << "namespace {\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002130
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002131 // Output the operand conversion kind enum.
2132 OS << "enum OperatorConversionKind {\n";
Craig Topper6e526f12016-01-03 07:33:30 +00002133 for (const std::string &Converter : OperandConversionKinds)
2134 OS << " " << Converter << ",\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002135 OS << " CVT_NUM_CONVERTERS\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002136 OS << "};\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002137
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002138 // Output the instruction conversion kind enum.
2139 OS << "enum InstructionConversionKind {\n";
Craig Topper802d3d32015-08-16 21:27:10 +00002140 for (const std::string &Signature : InstructionConversionKinds)
2141 OS << " " << Signature << ",\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002142 OS << " CVT_NUM_SIGNATURES\n";
2143 OS << "};\n\n";
2144
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002145 OS << "} // end anonymous namespace\n\n";
2146
2147 // Output the conversion table.
Craig Topper91506102012-09-18 01:41:49 +00002148 OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES]["
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002149 << MaxRowLength << "] = {\n";
2150
2151 for (unsigned Row = 0, ERow = ConversionTable.size(); Row != ERow; ++Row) {
2152 assert(ConversionTable[Row].size() % 2 == 0 && "bad conversion row!");
2153 OS << " // " << InstructionConversionKinds[Row] << "\n";
2154 OS << " { ";
2155 for (unsigned i = 0, e = ConversionTable[Row].size(); i != e; i += 2)
2156 OS << OperandConversionKinds[ConversionTable[Row][i]] << ", "
2157 << (unsigned)(ConversionTable[Row][i + 1]) << ", ";
2158 OS << "CVT_Done },\n";
2159 }
2160
2161 OS << "};\n\n";
2162
2163 // Spit out the conversion driver function.
Daniel Dunbar71330282009-08-08 05:24:34 +00002164 OS << CvtOS.str();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002165
Chad Rosier738ea252012-08-30 17:59:25 +00002166 // Spit out the operand number lookup function.
2167 OS << OpOS.str();
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002168}
2169
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002170/// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
2171static void emitMatchClassEnumeration(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002172 std::forward_list<ClassInfo> &Infos,
2173 raw_ostream &OS) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002174 OS << "namespace {\n\n";
2175
2176 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
2177 << "/// instruction matching.\n";
2178 OS << "enum MatchClassKind {\n";
2179 OS << " InvalidMatchClass = 0,\n";
Tom Stellardb9f235e2016-02-05 19:59:33 +00002180 OS << " OptionalMatchClass = 1,\n";
Craig Topperf34dad92014-11-28 03:53:02 +00002181 for (const auto &CI : Infos) {
David Blaikied749e342014-11-28 20:35:57 +00002182 OS << " " << CI.Name << ", // ";
2183 if (CI.Kind == ClassInfo::Token) {
2184 OS << "'" << CI.ValueName << "'\n";
2185 } else if (CI.isRegisterClass()) {
2186 if (!CI.ValueName.empty())
2187 OS << "register class '" << CI.ValueName << "'\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002188 else
2189 OS << "derived register class\n";
2190 } else {
David Blaikied749e342014-11-28 20:35:57 +00002191 OS << "user defined class '" << CI.ValueName << "'\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002192 }
2193 }
2194 OS << " NumMatchClassKinds\n";
2195 OS << "};\n\n";
2196
2197 OS << "}\n\n";
2198}
2199
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002200/// emitValidateOperandClass - Emit the function to validate an operand class.
2201static void emitValidateOperandClass(AsmMatcherInfo &Info,
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002202 raw_ostream &OS) {
David Blaikie960ea3f2014-06-08 16:18:35 +00002203 OS << "static unsigned validateOperandClass(MCParsedAsmOperand &GOp, "
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002204 << "MatchClassKind Kind) {\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00002205 OS << " " << Info.Target.getName() << "Operand &Operand = ("
2206 << Info.Target.getName() << "Operand&)GOp;\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002207
Kevin Enderby1b87c802011-07-15 18:30:43 +00002208 // The InvalidMatchClass is not to match any operand.
2209 OS << " if (Kind == InvalidMatchClass)\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002210 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n\n";
Kevin Enderby1b87c802011-07-15 18:30:43 +00002211
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002212 // Check for Token operands first.
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002213 // FIXME: Use a more specific diagnostic type.
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002214 OS << " if (Operand.isToken())\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002215 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
2216 << " MCTargetAsmParser::Match_Success :\n"
2217 << " MCTargetAsmParser::Match_InvalidOperand;\n\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002218
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002219 // Check the user classes. We don't care what order since we're only
2220 // actually matching against one of them.
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002221 OS << " switch (Kind) {\n"
2222 " default: break;\n";
Craig Topperf34dad92014-11-28 03:53:02 +00002223 for (const auto &CI : Info.Classes) {
David Blaikied749e342014-11-28 20:35:57 +00002224 if (!CI.isUserClass())
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002225 continue;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002226
David Blaikied749e342014-11-28 20:35:57 +00002227 OS << " // '" << CI.ClassName << "' class\n";
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002228 OS << " case " << CI.Name << ":\n";
David Blaikied749e342014-11-28 20:35:57 +00002229 OS << " if (Operand." << CI.PredicateMethod << "())\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002230 OS << " return MCTargetAsmParser::Match_Success;\n";
David Blaikied749e342014-11-28 20:35:57 +00002231 if (!CI.DiagnosticType.empty())
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002232 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
David Blaikied749e342014-11-28 20:35:57 +00002233 << CI.DiagnosticType << ";\n";
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002234 else
2235 OS << " break;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002236 }
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002237 OS << " } // end switch (Kind)\n\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002238
Owen Anderson8a503f22012-07-16 23:20:09 +00002239 // Check for register operands, including sub-classes.
2240 OS << " if (Operand.isReg()) {\n";
2241 OS << " MatchClassKind OpKind;\n";
2242 OS << " switch (Operand.getReg()) {\n";
2243 OS << " default: OpKind = InvalidMatchClass; break;\n";
Craig Topper03ec8012014-11-25 20:11:31 +00002244 for (const auto &RC : Info.RegisterClasses)
Owen Anderson8a503f22012-07-16 23:20:09 +00002245 OS << " case " << Info.Target.getName() << "::"
Craig Topper03ec8012014-11-25 20:11:31 +00002246 << RC.first->getName() << ": OpKind = " << RC.second->Name
Owen Anderson8a503f22012-07-16 23:20:09 +00002247 << "; break;\n";
2248 OS << " }\n";
2249 OS << " return isSubclass(OpKind, Kind) ? "
2250 << "MCTargetAsmParser::Match_Success :\n "
2251 << " MCTargetAsmParser::Match_InvalidOperand;\n }\n\n";
2252
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002253 // Generic fallthrough match failure case for operands that don't have
2254 // specialized diagnostic types.
2255 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002256 OS << "}\n\n";
2257}
2258
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002259/// emitIsSubclass - Emit the subclass predicate function.
2260static void emitIsSubclass(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002261 std::forward_list<ClassInfo> &Infos,
Daniel Dunbar2587b612009-08-10 16:05:47 +00002262 raw_ostream &OS) {
Dmitri Gribenko8d302402012-09-15 20:22:05 +00002263 OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n";
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002264 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
Daniel Dunbar2587b612009-08-10 16:05:47 +00002265 OS << " if (A == B)\n";
2266 OS << " return true;\n\n";
2267
Craig Topper39311c72015-12-30 06:00:22 +00002268 bool EmittedSwitch = false;
Craig Topperf34dad92014-11-28 03:53:02 +00002269 for (const auto &A : Infos) {
Jim Grosbachba395922011-12-06 23:43:54 +00002270 std::vector<StringRef> SuperClasses;
Tom Stellardb9f235e2016-02-05 19:59:33 +00002271 if (A.IsOptional)
2272 SuperClasses.push_back("OptionalMatchClass");
Craig Topperf34dad92014-11-28 03:53:02 +00002273 for (const auto &B : Infos) {
David Blaikied749e342014-11-28 20:35:57 +00002274 if (&A != &B && A.isSubsetOf(B))
2275 SuperClasses.push_back(B.Name);
Daniel Dunbar2587b612009-08-10 16:05:47 +00002276 }
Jim Grosbachba395922011-12-06 23:43:54 +00002277
2278 if (SuperClasses.empty())
2279 continue;
2280
Craig Topper39311c72015-12-30 06:00:22 +00002281 // If this is the first SuperClass, emit the switch header.
2282 if (!EmittedSwitch) {
Craig Topper13b2a4e2015-12-30 06:00:24 +00002283 OS << " switch (A) {\n";
Craig Topper39311c72015-12-30 06:00:22 +00002284 OS << " default:\n";
2285 OS << " return false;\n";
2286 EmittedSwitch = true;
2287 }
2288
2289 OS << "\n case " << A.Name << ":\n";
Jim Grosbachba395922011-12-06 23:43:54 +00002290
2291 if (SuperClasses.size() == 1) {
Craig Topper13b2a4e2015-12-30 06:00:24 +00002292 OS << " return B == " << SuperClasses.back() << ";\n";
Jim Grosbachba395922011-12-06 23:43:54 +00002293 continue;
2294 }
2295
Aaron Ballmane59e3582013-07-15 16:53:32 +00002296 if (!SuperClasses.empty()) {
Craig Topper39311c72015-12-30 06:00:22 +00002297 OS << " switch (B) {\n";
2298 OS << " default: return false;\n";
Craig Topper77bd2b72015-12-30 06:00:20 +00002299 for (StringRef SC : SuperClasses)
Craig Topper39311c72015-12-30 06:00:22 +00002300 OS << " case " << SC << ": return true;\n";
2301 OS << " }\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002302 } else {
2303 // No case statement to emit
Craig Topper39311c72015-12-30 06:00:22 +00002304 OS << " return false;\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002305 }
Daniel Dunbar2587b612009-08-10 16:05:47 +00002306 }
Aaron Ballmane59e3582013-07-15 16:53:32 +00002307
Craig Topper39311c72015-12-30 06:00:22 +00002308 // If there were case statements emitted into the string stream write the
2309 // default.
Craig Topperf58323e2016-01-03 07:33:34 +00002310 if (EmittedSwitch)
2311 OS << " }\n";
2312 else
Aaron Ballmane59e3582013-07-15 16:53:32 +00002313 OS << " return false;\n";
2314
Daniel Dunbar2587b612009-08-10 16:05:47 +00002315 OS << "}\n\n";
2316}
2317
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002318/// emitMatchTokenString - Emit the function to match a token string to the
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002319/// appropriate match class value.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002320static void emitMatchTokenString(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002321 std::forward_list<ClassInfo> &Infos,
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002322 raw_ostream &OS) {
2323 // Construct the match list.
Chris Lattnerca5a3552010-09-06 02:01:51 +00002324 std::vector<StringMatcher::StringPair> Matches;
Craig Topperf34dad92014-11-28 03:53:02 +00002325 for (const auto &CI : Infos) {
David Blaikied749e342014-11-28 20:35:57 +00002326 if (CI.Kind == ClassInfo::Token)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002327 Matches.emplace_back(CI.ValueName, "return " + CI.Name + ";");
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002328 }
2329
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002330 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002331
Chris Lattnerca5a3552010-09-06 02:01:51 +00002332 StringMatcher("Name", Matches, OS).Emit();
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002333
2334 OS << " return InvalidMatchClass;\n";
2335 OS << "}\n\n";
2336}
Chris Lattner00e2e742009-08-08 20:02:57 +00002337
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002338/// emitMatchRegisterName - Emit the function to match a string to the target
Daniel Dunbard0470d72009-08-07 21:01:44 +00002339/// specific register enum.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002340static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
Daniel Dunbard0470d72009-08-07 21:01:44 +00002341 raw_ostream &OS) {
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002342 // Construct the match list.
Chris Lattnerca5a3552010-09-06 02:01:51 +00002343 std::vector<StringMatcher::StringPair> Matches;
David Blaikie9b613db2014-11-29 18:13:39 +00002344 const auto &Regs = Target.getRegBank().getRegisters();
2345 for (const CodeGenRegister &Reg : Regs) {
2346 if (Reg.TheDef->getValueAsString("AsmName").empty())
Daniel Dunbare2eec052009-07-17 18:51:11 +00002347 continue;
2348
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002349 Matches.emplace_back(Reg.TheDef->getValueAsString("AsmName"),
2350 "return " + utostr(Reg.EnumValue) + ";");
Daniel Dunbare2eec052009-07-17 18:51:11 +00002351 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002352
Chris Lattner60db0a62010-02-09 00:34:28 +00002353 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002354
Chris Lattnerca5a3552010-09-06 02:01:51 +00002355 StringMatcher("Name", Matches, OS).Emit();
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002356
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002357 OS << " return 0;\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +00002358 OS << "}\n\n";
Daniel Dunbard0470d72009-08-07 21:01:44 +00002359}
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002360
Dylan McKaybff960a2016-02-03 10:30:16 +00002361/// Emit the function to match a string to the target
2362/// specific register enum.
2363static void emitMatchRegisterAltName(CodeGenTarget &Target, Record *AsmParser,
2364 raw_ostream &OS) {
2365 // Construct the match list.
2366 std::vector<StringMatcher::StringPair> Matches;
2367 const auto &Regs = Target.getRegBank().getRegisters();
2368 for (const CodeGenRegister &Reg : Regs) {
2369
2370 auto AltNames = Reg.TheDef->getValueAsListOfStrings("AltNames");
2371
2372 for (auto AltName : AltNames) {
2373 AltName = StringRef(AltName).trim();
2374
2375 // don't handle empty alternative names
2376 if (AltName.empty())
2377 continue;
2378
2379 Matches.emplace_back(AltName,
2380 "return " + utostr(Reg.EnumValue) + ";");
2381 }
2382 }
2383
2384 OS << "static unsigned MatchRegisterAltName(StringRef Name) {\n";
2385
2386 StringMatcher("Name", Matches, OS).Emit();
2387
2388 OS << " return 0;\n";
2389 OS << "}\n\n";
2390}
2391
Daniel Sanders3ea92742014-05-21 10:11:24 +00002392static const char *getMinimalTypeForRange(uint64_t Range) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002393 assert(Range <= 0xFFFFFFFFFFFFFFFFULL && "Enum too large");
2394 if (Range > 0xFFFFFFFFULL)
2395 return "uint64_t";
Daniel Sanders3ea92742014-05-21 10:11:24 +00002396 if (Range > 0xFFFF)
2397 return "uint32_t";
2398 if (Range > 0xFF)
2399 return "uint16_t";
2400 return "uint8_t";
2401}
2402
2403static const char *getMinimalRequiredFeaturesType(const AsmMatcherInfo &Info) {
2404 uint64_t MaxIndex = Info.SubtargetFeatures.size();
2405 if (MaxIndex > 0)
2406 MaxIndex--;
2407 return getMinimalTypeForRange(1ULL << MaxIndex);
2408}
2409
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002410/// emitSubtargetFeatureFlagEnumeration - Emit the subtarget feature flag
Daniel Dunbareefe8612010-07-19 05:44:09 +00002411/// definitions.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002412static void emitSubtargetFeatureFlagEnumeration(AsmMatcherInfo &Info,
Daniel Dunbareefe8612010-07-19 05:44:09 +00002413 raw_ostream &OS) {
2414 OS << "// Flags for subtarget features that participate in "
2415 << "instruction matching.\n";
Daniel Sanders3ea92742014-05-21 10:11:24 +00002416 OS << "enum SubtargetFeatureFlag : " << getMinimalRequiredFeaturesType(Info)
2417 << " {\n";
Craig Topper42bd8192014-11-28 03:53:00 +00002418 for (const auto &SF : Info.SubtargetFeatures) {
David Blaikie9a9da992014-11-28 22:15:06 +00002419 const SubtargetFeatureInfo &SFI = SF.second;
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002420 OS << " " << SFI.getEnumName() << " = (1ULL << " << SFI.Index << "),\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00002421 }
2422 OS << " Feature_None = 0\n";
2423 OS << "};\n\n";
2424}
2425
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002426/// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
2427static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) {
2428 // Get the set of diagnostic types from all of the operand classes.
2429 std::set<StringRef> Types;
Craig Topper6e526f12016-01-03 07:33:30 +00002430 for (const auto &OpClassEntry : Info.AsmOperandClasses) {
2431 if (!OpClassEntry.second->DiagnosticType.empty())
2432 Types.insert(OpClassEntry.second->DiagnosticType);
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002433 }
2434
2435 if (Types.empty()) return;
2436
2437 // Now emit the enum entries.
Craig Topper6e526f12016-01-03 07:33:30 +00002438 for (StringRef Type : Types)
2439 OS << " Match_" << Type << ",\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002440 OS << " END_OPERAND_DIAGNOSTIC_TYPES\n";
2441}
2442
Jim Grosbach5117ef72012-04-24 22:40:08 +00002443/// emitGetSubtargetFeatureName - Emit the helper function to get the
2444/// user-level name for a subtarget feature.
2445static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
2446 OS << "// User-level names for subtarget features that participate in\n"
2447 << "// instruction matching.\n"
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002448 << "static const char *getSubtargetFeatureName(uint64_t Val) {\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002449 if (!Info.SubtargetFeatures.empty()) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002450 OS << " switch(Val) {\n";
Craig Topper42bd8192014-11-28 03:53:00 +00002451 for (const auto &SF : Info.SubtargetFeatures) {
David Blaikie9a9da992014-11-28 22:15:06 +00002452 const SubtargetFeatureInfo &SFI = SF.second;
Aaron Ballmane59e3582013-07-15 16:53:32 +00002453 // FIXME: Totally just a placeholder name to get the algorithm working.
2454 OS << " case " << SFI.getEnumName() << ": return \""
2455 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
2456 }
2457 OS << " default: return \"(unknown)\";\n";
2458 OS << " }\n";
2459 } else {
2460 // Nothing to emit, so skip the switch
2461 OS << " return \"(unknown)\";\n";
Jim Grosbach5117ef72012-04-24 22:40:08 +00002462 }
Aaron Ballmane59e3582013-07-15 16:53:32 +00002463 OS << "}\n\n";
Jim Grosbach5117ef72012-04-24 22:40:08 +00002464}
2465
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002466/// emitComputeAvailableFeatures - Emit the function to compute the list of
Daniel Dunbareefe8612010-07-19 05:44:09 +00002467/// available features given a subtarget.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002468static void emitComputeAvailableFeatures(AsmMatcherInfo &Info,
Daniel Dunbareefe8612010-07-19 05:44:09 +00002469 raw_ostream &OS) {
2470 std::string ClassName =
2471 Info.AsmParser->getValueAsString("AsmParserClassName");
2472
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002473 OS << "uint64_t " << Info.Target.getName() << ClassName << "::\n"
Michael Kupersteindb0712f2015-05-26 10:47:10 +00002474 << "ComputeAvailableFeatures(const FeatureBitset& FB) const {\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002475 OS << " uint64_t Features = 0;\n";
Craig Topper42bd8192014-11-28 03:53:00 +00002476 for (const auto &SF : Info.SubtargetFeatures) {
David Blaikie9a9da992014-11-28 22:15:06 +00002477 const SubtargetFeatureInfo &SFI = SF.second;
Evan Cheng4d1ca962011-07-08 01:53:10 +00002478
2479 OS << " if (";
Jim Grosbach56e63262012-04-17 00:01:04 +00002480 std::string CondStorage =
2481 SFI.TheDef->getValueAsString("AssemblerCondString");
Evan Cheng1a6d5512011-07-08 18:04:22 +00002482 StringRef Conds = CondStorage;
Evan Cheng4d1ca962011-07-08 01:53:10 +00002483 std::pair<StringRef,StringRef> Comma = Conds.split(',');
2484 bool First = true;
2485 do {
2486 if (!First)
2487 OS << " && ";
2488
2489 bool Neg = false;
2490 StringRef Cond = Comma.first;
2491 if (Cond[0] == '!') {
2492 Neg = true;
2493 Cond = Cond.substr(1);
2494 }
2495
Michael Kupersteindb0712f2015-05-26 10:47:10 +00002496 OS << "(";
Evan Cheng4d1ca962011-07-08 01:53:10 +00002497 if (Neg)
Michael Kupersteindb0712f2015-05-26 10:47:10 +00002498 OS << "!";
2499 OS << "FB[" << Info.Target.getName() << "::" << Cond << "])";
Evan Cheng4d1ca962011-07-08 01:53:10 +00002500
2501 if (Comma.second.empty())
2502 break;
2503
2504 First = false;
2505 Comma = Comma.second.split(',');
2506 } while (true);
2507
2508 OS << ")\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002509 OS << " Features |= " << SFI.getEnumName() << ";\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00002510 }
2511 OS << " return Features;\n";
2512 OS << "}\n\n";
2513}
2514
Chris Lattner43690072010-10-30 20:15:02 +00002515static std::string GetAliasRequiredFeatures(Record *R,
2516 const AsmMatcherInfo &Info) {
Chris Lattner2cb092d2010-10-30 19:23:13 +00002517 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
Chris Lattner2cb092d2010-10-30 19:23:13 +00002518 std::string Result;
2519 unsigned NumFeatures = 0;
2520 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
David Blaikie9a9da992014-11-28 22:15:06 +00002521 const SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002522
Craig Topper24064772014-04-15 07:20:03 +00002523 if (!F)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002524 PrintFatalError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
Chris Lattner517dc952010-11-01 02:09:21 +00002525 "' is not marked as an AssemblerPredicate!");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002526
Chris Lattner517dc952010-11-01 02:09:21 +00002527 if (NumFeatures)
2528 Result += '|';
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002529
Chris Lattner517dc952010-11-01 02:09:21 +00002530 Result += F->getEnumName();
2531 ++NumFeatures;
Chris Lattner2cb092d2010-10-30 19:23:13 +00002532 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002533
Chris Lattner2cb092d2010-10-30 19:23:13 +00002534 if (NumFeatures > 1)
2535 Result = '(' + Result + ')';
2536 return Result;
2537}
2538
Chad Rosier9f7a2212013-04-18 22:35:36 +00002539static void emitMnemonicAliasVariant(raw_ostream &OS,const AsmMatcherInfo &Info,
2540 std::vector<Record*> &Aliases,
2541 unsigned Indent = 0,
2542 StringRef AsmParserVariantName = StringRef()){
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002543 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
2544 // iteration order of the map is stable.
2545 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002546
Craig Topper6e526f12016-01-03 07:33:30 +00002547 for (Record *R : Aliases) {
Chad Rosier9f7a2212013-04-18 22:35:36 +00002548 // FIXME: Allow AssemblerVariantName to be a comma separated list.
2549 std::string AsmVariantName = R->getValueAsString("AsmVariantName");
2550 if (AsmVariantName != AsmParserVariantName)
2551 continue;
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002552 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00002553 }
Chad Rosier9f7a2212013-04-18 22:35:36 +00002554 if (AliasesFromMnemonic.empty())
2555 return;
Vladimir Medic75429ad2013-07-16 09:22:38 +00002556
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002557 // Process each alias a "from" mnemonic at a time, building the code executed
2558 // by the string remapper.
2559 std::vector<StringMatcher::StringPair> Cases;
Craig Topper6e526f12016-01-03 07:33:30 +00002560 for (const auto &AliasEntry : AliasesFromMnemonic) {
2561 const std::vector<Record*> &ToVec = AliasEntry.second;
Chris Lattner2cb092d2010-10-30 19:23:13 +00002562
2563 // Loop through each alias and emit code that handles each case. If there
2564 // are two instructions without predicates, emit an error. If there is one,
2565 // emit it last.
2566 std::string MatchCode;
2567 int AliasWithNoPredicate = -1;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002568
Chris Lattner2cb092d2010-10-30 19:23:13 +00002569 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
2570 Record *R = ToVec[i];
Chris Lattner43690072010-10-30 20:15:02 +00002571 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002572
Chris Lattner2cb092d2010-10-30 19:23:13 +00002573 // If this unconditionally matches, remember it for later and diagnose
2574 // duplicates.
2575 if (FeatureMask.empty()) {
2576 if (AliasWithNoPredicate != -1) {
2577 // We can't have two aliases from the same mnemonic with no predicate.
2578 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
2579 "two MnemonicAliases with the same 'from' mnemonic!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002580 PrintFatalError(R->getLoc(), "this is the other MnemonicAlias.");
Chris Lattner2cb092d2010-10-30 19:23:13 +00002581 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002582
Chris Lattner2cb092d2010-10-30 19:23:13 +00002583 AliasWithNoPredicate = i;
2584 continue;
2585 }
Craig Topper6e526f12016-01-03 07:33:30 +00002586 if (R->getValueAsString("ToMnemonic") == AliasEntry.first)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002587 PrintFatalError(R->getLoc(), "MnemonicAlias to the same string");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002588
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00002589 if (!MatchCode.empty())
2590 MatchCode += "else ";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002591 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
Chris Lattner2cb092d2010-10-30 19:23:13 +00002592 MatchCode += " Mnemonic = \"" +R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002593 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002594
Chris Lattner2cb092d2010-10-30 19:23:13 +00002595 if (AliasWithNoPredicate != -1) {
2596 Record *R = ToVec[AliasWithNoPredicate];
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00002597 if (!MatchCode.empty())
2598 MatchCode += "else\n ";
2599 MatchCode += "Mnemonic = \"" + R->getValueAsString("ToMnemonic")+"\";\n";
Chris Lattner2cb092d2010-10-30 19:23:13 +00002600 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002601
Chris Lattner2cb092d2010-10-30 19:23:13 +00002602 MatchCode += "return;";
2603
Craig Topper6e526f12016-01-03 07:33:30 +00002604 Cases.push_back(std::make_pair(AliasEntry.first, MatchCode));
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002605 }
Chad Rosier9f7a2212013-04-18 22:35:36 +00002606 StringMatcher("Mnemonic", Cases, OS).Emit(Indent);
2607}
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002608
Chad Rosier9f7a2212013-04-18 22:35:36 +00002609/// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
2610/// emit a function for them and return true, otherwise return false.
2611static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info,
2612 CodeGenTarget &Target) {
2613 // Ignore aliases when match-prefix is set.
2614 if (!MatchPrefix.empty())
2615 return false;
2616
2617 std::vector<Record*> Aliases =
2618 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
2619 if (Aliases.empty()) return false;
2620
2621 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002622 "uint64_t Features, unsigned VariantID) {\n";
Chad Rosier9f7a2212013-04-18 22:35:36 +00002623 OS << " switch (VariantID) {\n";
2624 unsigned VariantCount = Target.getAsmParserVariantCount();
2625 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2626 Record *AsmVariant = Target.getAsmParserVariant(VC);
2627 int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant");
2628 std::string AsmParserVariantName = AsmVariant->getValueAsString("Name");
2629 OS << " case " << AsmParserVariantNo << ":\n";
2630 emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2,
2631 AsmParserVariantName);
2632 OS << " break;\n";
2633 }
2634 OS << " }\n";
2635
2636 // Emit aliases that apply to all variants.
2637 emitMnemonicAliasVariant(OS, Info, Aliases);
2638
Daniel Dunbare46bc4c2011-01-18 01:59:30 +00002639 OS << "}\n\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002640
Chris Lattner477fba4f2010-10-30 18:48:18 +00002641 return true;
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00002642}
2643
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002644static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002645 const AsmMatcherInfo &Info, StringRef ClassName,
2646 StringToOffsetTable &StringTable,
Craig Topperfd2c6a32015-12-31 08:18:23 +00002647 unsigned MaxMnemonicIndex, bool HasMnemonicFirst) {
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002648 unsigned MaxMask = 0;
Craig Topper869cd5f2015-12-31 08:18:20 +00002649 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
2650 MaxMask |= OMI.OperandMask;
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002651 }
2652
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002653 // Emit the static custom operand parsing table;
2654 OS << "namespace {\n";
2655 OS << " struct OperandMatchEntry {\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002656 OS << " " << getMinimalRequiredFeaturesType(Info)
2657 << " RequiredFeatures;\n";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002658 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
2659 << " Mnemonic;\n";
David Blaikied749e342014-11-28 20:35:57 +00002660 OS << " " << getMinimalTypeForRange(std::distance(
2661 Info.Classes.begin(), Info.Classes.end())) << " Class;\n";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002662 OS << " " << getMinimalTypeForRange(MaxMask)
2663 << " OperandMask;\n\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002664 OS << " StringRef getMnemonic() const {\n";
2665 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2666 OS << " MnemonicTable[Mnemonic]);\n";
2667 OS << " }\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002668 OS << " };\n\n";
2669
2670 OS << " // Predicate for searching for an opcode.\n";
2671 OS << " struct LessOpcodeOperand {\n";
2672 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002673 OS << " return LHS.getMnemonic() < RHS;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002674 OS << " }\n";
2675 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002676 OS << " return LHS < RHS.getMnemonic();\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002677 OS << " }\n";
2678 OS << " bool operator()(const OperandMatchEntry &LHS,";
2679 OS << " const OperandMatchEntry &RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002680 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002681 OS << " }\n";
2682 OS << " };\n";
2683
2684 OS << "} // end anonymous namespace.\n\n";
2685
2686 OS << "static const OperandMatchEntry OperandMatchTable["
2687 << Info.OperandMatchInfo.size() << "] = {\n";
2688
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002689 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
Craig Topper869cd5f2015-12-31 08:18:20 +00002690 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002691 const MatchableInfo &II = *OMI.MI;
2692
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002693 OS << " { ";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002694
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002695 // Write the required features mask.
2696 if (!II.RequiredFeatures.empty()) {
2697 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002698 if (i) OS << "|";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002699 OS << II.RequiredFeatures[i]->getEnumName();
2700 }
2701 } else
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002702 OS << "0";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002703
2704 // Store a pascal-style length byte in the mnemonic.
2705 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2706 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2707 << " /* " << II.Mnemonic << " */, ";
2708
2709 OS << OMI.CI->Name;
2710
2711 OS << ", " << OMI.OperandMask;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002712 OS << " /* ";
2713 bool printComma = false;
2714 for (int i = 0, e = 31; i !=e; ++i)
2715 if (OMI.OperandMask & (1 << i)) {
2716 if (printComma)
2717 OS << ", ";
2718 OS << i;
2719 printComma = true;
2720 }
2721 OS << " */";
2722
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002723 OS << " },\n";
2724 }
2725 OS << "};\n\n";
2726
2727 // Emit the operand class switch to call the correct custom parser for
2728 // the found operand class.
Jim Grosbach861e49c2011-02-12 01:34:40 +00002729 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
2730 << Target.getName() << ClassName << "::\n"
David Blaikie960ea3f2014-06-08 16:18:35 +00002731 << "tryCustomParseOperand(OperandVector"
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002732 << " &Operands,\n unsigned MCK) {\n\n"
2733 << " switch(MCK) {\n";
2734
Craig Topperf34dad92014-11-28 03:53:02 +00002735 for (const auto &CI : Info.Classes) {
David Blaikied749e342014-11-28 20:35:57 +00002736 if (CI.ParserMethod.empty())
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002737 continue;
David Blaikied749e342014-11-28 20:35:57 +00002738 OS << " case " << CI.Name << ":\n"
2739 << " return " << CI.ParserMethod << "(Operands);\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002740 }
2741
2742 OS << " default:\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002743 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002744 OS << " }\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002745 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002746 OS << "}\n\n";
2747
2748 // Emit the static custom operand parser. This code is very similar with
2749 // the other matcher. Also use MatchResultTy here just in case we go for
2750 // a better error handling.
Jim Grosbach861e49c2011-02-12 01:34:40 +00002751 OS << Target.getName() << ClassName << "::OperandMatchResultTy "
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002752 << Target.getName() << ClassName << "::\n"
David Blaikie960ea3f2014-06-08 16:18:35 +00002753 << "MatchOperandParserImpl(OperandVector"
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002754 << " &Operands,\n StringRef Mnemonic) {\n";
2755
2756 // Emit code to get the available features.
2757 OS << " // Get the current feature set.\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002758 OS << " uint64_t AvailableFeatures = getAvailableFeatures();\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002759
2760 OS << " // Get the next operand index.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00002761 OS << " unsigned NextOpNum = Operands.size()"
2762 << (HasMnemonicFirst ? " - 1" : "") << ";\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002763
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002764 // Emit code to search the table.
2765 OS << " // Search the table.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00002766 if (HasMnemonicFirst) {
2767 OS << " auto MnemonicRange =\n";
2768 OS << " std::equal_range(std::begin(OperandMatchTable), "
2769 "std::end(OperandMatchTable),\n";
2770 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2771 } else {
2772 OS << " auto MnemonicRange = std::make_pair(std::begin(OperandMatchTable),"
2773 " std::end(OperandMatchTable));\n";
2774 OS << " if (!Mnemonic.empty())\n";
2775 OS << " MnemonicRange =\n";
2776 OS << " std::equal_range(std::begin(OperandMatchTable), "
2777 "std::end(OperandMatchTable),\n";
2778 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2779 }
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002780
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002781 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002782 OS << " return MatchOperand_NoMatch;\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002783
2784 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2785 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2786
2787 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002788 OS << " assert(Mnemonic == it->getMnemonic());\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002789
2790 // Emit check that the required features are available.
2791 OS << " // check if the available features match\n";
2792 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
2793 << "!= it->RequiredFeatures) {\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002794 OS << " continue;\n";
2795 OS << " }\n\n";
2796
2797 // Emit check to ensure the operand number matches.
2798 OS << " // check if the operand in question has a custom parser.\n";
2799 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2800 OS << " continue;\n\n";
2801
2802 // Emit call to the custom parser method
2803 OS << " // call custom parse method to handle the operand\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002804 OS << " OperandMatchResultTy Result = ";
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002805 OS << "tryCustomParseOperand(Operands, it->Class);\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002806 OS << " if (Result != MatchOperand_NoMatch)\n";
2807 OS << " return Result;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002808 OS << " }\n\n";
2809
Jim Grosbach861e49c2011-02-12 01:34:40 +00002810 OS << " // Okay, we had no match.\n";
2811 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002812 OS << "}\n\n";
2813}
2814
Daniel Dunbard0470d72009-08-07 21:01:44 +00002815void AsmMatcherEmitter::run(raw_ostream &OS) {
Chris Lattner77d369c2010-12-13 00:23:57 +00002816 CodeGenTarget Target(Records);
Daniel Dunbard0470d72009-08-07 21:01:44 +00002817 Record *AsmParser = Target.getAsmParser();
2818 std::string ClassName = AsmParser->getValueAsString("AsmParserClassName");
2819
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002820 // Compute the information on the instructions to match.
Chris Lattner77d369c2010-12-13 00:23:57 +00002821 AsmMatcherInfo Info(AsmParser, Target, Records);
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002822 Info.buildInfo();
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002823
Daniel Dunbar3b8a4662010-02-02 23:46:36 +00002824 // Sort the instruction table using the partial order on classes. We use
2825 // stable_sort to ensure that ambiguous instructions are still
2826 // deterministically ordered.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002827 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
2828 [](const std::unique_ptr<MatchableInfo> &a,
2829 const std::unique_ptr<MatchableInfo> &b){
2830 return *a < *b;});
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002831
Oliver Stannard7772f022016-01-25 10:20:19 +00002832#ifndef NDEBUG
2833 // Verify that the table is now sorted
2834 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
2835 ++I) {
2836 for (auto J = I; J != E; ++J) {
2837 assert(!(**J < **I));
2838 }
2839 }
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +00002840#endif // NDEBUG
Oliver Stannard7772f022016-01-25 10:20:19 +00002841
Daniel Dunbar71330282009-08-08 05:24:34 +00002842 DEBUG_WITH_TYPE("instruction_info", {
Craig Topperf34dad92014-11-28 03:53:02 +00002843 for (const auto &MI : Info.Matchables)
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002844 MI->dump();
Daniel Dunbare10787e2009-08-07 08:26:05 +00002845 });
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002846
Chris Lattnerad776812010-11-01 05:06:45 +00002847 // Check for ambiguous matchables.
Chris Lattnerc0658cb2010-09-06 21:28:52 +00002848 DEBUG_WITH_TYPE("ambiguous_instrs", {
2849 unsigned NumAmbiguous = 0;
David Blaikie9a6f2832014-12-22 21:26:38 +00002850 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
2851 ++I) {
2852 for (auto J = std::next(I); J != E; ++J) {
2853 const MatchableInfo &A = **I;
2854 const MatchableInfo &B = **J;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002855
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002856 if (A.couldMatchAmbiguouslyWith(B)) {
Chris Lattnerad776812010-11-01 05:06:45 +00002857 errs() << "warning: ambiguous matchables:\n";
Chris Lattnerc0658cb2010-09-06 21:28:52 +00002858 A.dump();
2859 errs() << "\nis incomparable with:\n";
2860 B.dump();
2861 errs() << "\n\n";
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00002862 ++NumAmbiguous;
2863 }
Daniel Dunbarf573b562009-08-09 06:05:33 +00002864 }
Daniel Dunbar3239f022009-08-09 04:00:06 +00002865 }
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00002866 if (NumAmbiguous)
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002867 errs() << "warning: " << NumAmbiguous
Chris Lattnerad776812010-11-01 05:06:45 +00002868 << " ambiguous matchables!\n";
Chris Lattnerc0658cb2010-09-06 21:28:52 +00002869 });
Daniel Dunbar3239f022009-08-09 04:00:06 +00002870
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002871 // Compute the information on the custom operand parsing.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002872 Info.buildOperandMatchInfo();
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002873
Craig Topperfd2c6a32015-12-31 08:18:23 +00002874 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
Sam Kolton5f10a132016-05-06 11:31:17 +00002875 bool HasOptionalOperands = Info.hasOptionalOperands();
Craig Topperfd2c6a32015-12-31 08:18:23 +00002876
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00002877 // Write the output.
2878
Chris Lattner3e4582a2010-09-06 19:11:01 +00002879 // Information for the class declaration.
2880 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
2881 OS << "#undef GET_ASSEMBLER_HEADER\n";
Jim Grosbach860a84d2011-02-11 21:31:55 +00002882 OS << " // This should be included into the middle of the declaration of\n";
Evan Cheng11424442011-07-26 00:24:13 +00002883 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002884 OS << " uint64_t ComputeAvailableFeatures(const FeatureBitset& FB) const;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00002885 if (HasOptionalOperands) {
2886 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
2887 << "unsigned Opcode,\n"
2888 << " const OperandVector &Operands,\n"
2889 << " const SmallBitVector &OptionalOperandsMask);\n";
2890 } else {
2891 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
2892 << "unsigned Opcode,\n"
2893 << " const OperandVector &Operands);\n";
2894 }
Chad Rosier380a74a2012-10-02 00:25:57 +00002895 OS << " void convertToMapAndConstraints(unsigned Kind,\n ";
Peter Collingbourne0da86302016-10-10 22:49:37 +00002896 OS << " const OperandVector &Operands) override;\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00002897 if (HasMnemonicFirst)
2898 OS << " bool mnemonicIsValid(StringRef Mnemonic, unsigned VariantID);\n";
Craig Toppera5754e62015-01-03 08:16:29 +00002899 OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002900 << " MCInst &Inst,\n"
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002901 << " uint64_t &ErrorInfo,"
2902 << " bool matchingInlineAsm,\n"
Chad Rosier380a74a2012-10-02 00:25:57 +00002903 << " unsigned VariantID = 0);\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002904
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00002905 if (!Info.OperandMatchInfo.empty()) {
Jim Grosbach861e49c2011-02-12 01:34:40 +00002906 OS << "\n enum OperandMatchResultTy {\n";
2907 OS << " MatchOperand_Success, // operand matched successfully\n";
2908 OS << " MatchOperand_NoMatch, // operand did not match\n";
2909 OS << " MatchOperand_ParseFail // operand matched but had errors\n";
2910 OS << " };\n";
2911 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00002912 OS << " OperandVector &Operands,\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002913 OS << " StringRef Mnemonic);\n";
2914
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002915 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00002916 OS << " OperandVector &Operands,\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002917 OS << " unsigned MCK);\n\n";
2918 }
2919
Chris Lattner3e4582a2010-09-06 19:11:01 +00002920 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
2921
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002922 // Emit the operand match diagnostic enum names.
2923 OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
2924 OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
2925 emitOperandDiagnosticTypes(Info, OS);
2926 OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
2927
Chris Lattner3e4582a2010-09-06 19:11:01 +00002928 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
2929 OS << "#undef GET_REGISTER_MATCHER\n\n";
2930
Daniel Dunbareefe8612010-07-19 05:44:09 +00002931 // Emit the subtarget feature enumeration.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002932 emitSubtargetFeatureFlagEnumeration(Info, OS);
Daniel Dunbareefe8612010-07-19 05:44:09 +00002933
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00002934 // Emit the function to match a register name to number.
Akira Hatanaka7605630c2012-08-17 20:16:42 +00002935 // This should be omitted for Mips target
2936 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName"))
2937 emitMatchRegisterName(Target, AsmParser, OS);
Chris Lattner3e4582a2010-09-06 19:11:01 +00002938
Dylan McKaybff960a2016-02-03 10:30:16 +00002939 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterAltName"))
2940 emitMatchRegisterAltName(Target, AsmParser, OS);
2941
Chris Lattner3e4582a2010-09-06 19:11:01 +00002942 OS << "#endif // GET_REGISTER_MATCHER\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002943
Craig Topper3ec7c2a2012-04-25 06:56:34 +00002944 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
2945 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00002946
Jim Grosbach5117ef72012-04-24 22:40:08 +00002947 // Generate the helper function to get the names for subtarget features.
2948 emitGetSubtargetFeatureName(Info, OS);
2949
Craig Topper3ec7c2a2012-04-25 06:56:34 +00002950 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
2951
2952 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
2953 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
2954
Chris Lattner477fba4f2010-10-30 18:48:18 +00002955 // Generate the function that remaps for mnemonic aliases.
Chad Rosier9f7a2212013-04-18 22:35:36 +00002956 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002957
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002958 // Generate the convertToMCInst function to convert operands into an MCInst.
2959 // Also, generate the convertToMapAndConstraints function for MS-style inline
2960 // assembly. The latter doesn't actually generate a MCInst.
Sam Kolton5f10a132016-05-06 11:31:17 +00002961 emitConvertFuncs(Target, ClassName, Info.Matchables, HasMnemonicFirst,
2962 HasOptionalOperands, OS);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002963
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002964 // Emit the enumeration for classes which participate in matching.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002965 emitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002966
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002967 // Emit the routine to match token strings to their match class.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002968 emitMatchTokenString(Target, Info.Classes, OS);
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002969
Daniel Dunbar2587b612009-08-10 16:05:47 +00002970 // Emit the subclass predicate routine.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002971 emitIsSubclass(Target, Info.Classes, OS);
Daniel Dunbar2587b612009-08-10 16:05:47 +00002972
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002973 // Emit the routine to validate an operand against a match class.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002974 emitValidateOperandClass(Info, OS);
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002975
Daniel Dunbareefe8612010-07-19 05:44:09 +00002976 // Emit the available features compute function.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002977 emitComputeAvailableFeatures(Info, OS);
Daniel Dunbareefe8612010-07-19 05:44:09 +00002978
Craig Toppere2cfeb32012-09-18 06:10:45 +00002979 StringToOffsetTable StringTable;
2980
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002981 size_t MaxNumOperands = 0;
Craig Toppere2cfeb32012-09-18 06:10:45 +00002982 unsigned MaxMnemonicIndex = 0;
Joey Gouly0e76fa72013-09-12 10:28:05 +00002983 bool HasDeprecation = false;
Craig Topperf34dad92014-11-28 03:53:02 +00002984 for (const auto &MI : Info.Matchables) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002985 MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
2986 HasDeprecation |= MI->HasDeprecation;
Craig Toppere2cfeb32012-09-18 06:10:45 +00002987
2988 // Store a pascal-style length byte in the mnemonic.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002989 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
Craig Toppere2cfeb32012-09-18 06:10:45 +00002990 MaxMnemonicIndex = std::max(MaxMnemonicIndex,
2991 StringTable.GetOrAddStringOffset(LenMnemonic, false));
2992 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002993
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002994 OS << "static const char *const MnemonicTable =\n";
2995 StringTable.EmitString(OS);
2996 OS << ";\n\n";
2997
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002998 // Emit the static match table; unused classes get initalized to 0 which is
2999 // guaranteed to be InvalidMatchClass.
3000 //
3001 // FIXME: We can reduce the size of this table very easily. First, we change
3002 // it so that store the kinds in separate bit-fields for each index, which
3003 // only needs to be the max width used for classes at that index (we also need
3004 // to reject based on this during classification). If we then make sure to
3005 // order the match kinds appropriately (putting mnemonics last), then we
3006 // should only end up using a few bits for each class, especially the ones
3007 // following the mnemonic.
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003008 OS << "namespace {\n";
3009 OS << " struct MatchEntry {\n";
Craig Toppere2cfeb32012-09-18 06:10:45 +00003010 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
3011 << " Mnemonic;\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003012 OS << " uint16_t Opcode;\n";
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003013 OS << " " << getMinimalTypeForRange(Info.Matchables.size())
3014 << " ConvertFn;\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003015 OS << " " << getMinimalRequiredFeaturesType(Info)
3016 << " RequiredFeatures;\n";
David Blaikied749e342014-11-28 20:35:57 +00003017 OS << " " << getMinimalTypeForRange(
3018 std::distance(Info.Classes.begin(), Info.Classes.end()))
3019 << " Classes[" << MaxNumOperands << "];\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003020 OS << " StringRef getMnemonic() const {\n";
3021 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
3022 OS << " MnemonicTable[Mnemonic]);\n";
3023 OS << " }\n";
Chris Lattner81301972010-09-06 21:22:45 +00003024 OS << " };\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003025
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003026 OS << " // Predicate for searching for an opcode.\n";
Chris Lattner81301972010-09-06 21:22:45 +00003027 OS << " struct LessOpcode {\n";
3028 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003029 OS << " return LHS.getMnemonic() < RHS;\n";
Chris Lattner81301972010-09-06 21:22:45 +00003030 OS << " }\n";
3031 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003032 OS << " return LHS < RHS.getMnemonic();\n";
Chris Lattner81301972010-09-06 21:22:45 +00003033 OS << " }\n";
Chris Lattner62823362010-09-07 06:10:48 +00003034 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003035 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Chris Lattner62823362010-09-07 06:10:48 +00003036 OS << " }\n";
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003037 OS << " };\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003038
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003039 OS << "} // end anonymous namespace.\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003040
Craig Topper690d8ea2013-07-24 07:33:14 +00003041 unsigned VariantCount = Target.getAsmParserVariantCount();
3042 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3043 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topper690d8ea2013-07-24 07:33:14 +00003044 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003045
Craig Topper690d8ea2013-07-24 07:33:14 +00003046 OS << "static const MatchEntry MatchTable" << VC << "[] = {\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003047
Craig Topperf34dad92014-11-28 03:53:02 +00003048 for (const auto &MI : Info.Matchables) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003049 if (MI->AsmVariantID != AsmVariantNo)
Craig Topper690d8ea2013-07-24 07:33:14 +00003050 continue;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003051
Craig Topper690d8ea2013-07-24 07:33:14 +00003052 // Store a pascal-style length byte in the mnemonic.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003053 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
Craig Topper690d8ea2013-07-24 07:33:14 +00003054 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003055 << " /* " << MI->Mnemonic << " */, "
3056 << Target.getName() << "::"
3057 << MI->getResultInst()->TheDef->getName() << ", "
3058 << MI->ConversionFnKind << ", ";
Craig Topper690d8ea2013-07-24 07:33:14 +00003059
3060 // Write the required features mask.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003061 if (!MI->RequiredFeatures.empty()) {
3062 for (unsigned i = 0, e = MI->RequiredFeatures.size(); i != e; ++i) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003063 if (i) OS << "|";
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003064 OS << MI->RequiredFeatures[i]->getEnumName();
Craig Topper690d8ea2013-07-24 07:33:14 +00003065 }
3066 } else
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003067 OS << "0";
Craig Topper690d8ea2013-07-24 07:33:14 +00003068
3069 OS << ", { ";
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003070 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
3071 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
Craig Topper690d8ea2013-07-24 07:33:14 +00003072
3073 if (i) OS << ", ";
3074 OS << Op.Class->Name;
Daniel Dunbareefe8612010-07-19 05:44:09 +00003075 }
Craig Topper690d8ea2013-07-24 07:33:14 +00003076 OS << " }, },\n";
Craig Topper4de73732012-04-02 07:48:39 +00003077 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003078
Craig Topper690d8ea2013-07-24 07:33:14 +00003079 OS << "};\n\n";
3080 }
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003081
Bob Wilson770681d72011-01-26 21:43:46 +00003082 // A method to determine if a mnemonic is in the list.
Craig Topperfd2c6a32015-12-31 08:18:23 +00003083 if (HasMnemonicFirst) {
3084 OS << "bool " << Target.getName() << ClassName << "::\n"
3085 << "mnemonicIsValid(StringRef Mnemonic, unsigned VariantID) {\n";
3086 OS << " // Find the appropriate table for this asm variant.\n";
3087 OS << " const MatchEntry *Start, *End;\n";
3088 OS << " switch (VariantID) {\n";
3089 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
3090 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3091 Record *AsmVariant = Target.getAsmParserVariant(VC);
3092 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3093 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3094 << "); End = std::end(MatchTable" << VC << "); break;\n";
3095 }
3096 OS << " }\n";
3097 OS << " // Search the table.\n";
3098 OS << " auto MnemonicRange = ";
3099 OS << "std::equal_range(Start, End, Mnemonic, LessOpcode());\n";
3100 OS << " return MnemonicRange.first != MnemonicRange.second;\n";
3101 OS << "}\n\n";
Craig Topper690d8ea2013-07-24 07:33:14 +00003102 }
Bob Wilson770681d72011-01-26 21:43:46 +00003103
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003104 // Finally, build the match function.
David Blaikie960ea3f2014-06-08 16:18:35 +00003105 OS << "unsigned " << Target.getName() << ClassName << "::\n"
Craig Toppera5754e62015-01-03 08:16:29 +00003106 << "MatchInstructionImpl(const OperandVector &Operands,\n";
3107 OS << " MCInst &Inst, uint64_t &ErrorInfo,\n"
3108 << " bool matchingInlineAsm, unsigned VariantID) {\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00003109
Chad Rosiereac13a32012-08-30 21:43:05 +00003110 OS << " // Eliminate obvious mismatches.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003111 OS << " if (Operands.size() > "
3112 << (MaxNumOperands + HasMnemonicFirst) << ") {\n";
3113 OS << " ErrorInfo = "
3114 << (MaxNumOperands + HasMnemonicFirst) << ";\n";
Chad Rosiereac13a32012-08-30 21:43:05 +00003115 OS << " return Match_InvalidOperand;\n";
3116 OS << " }\n\n";
3117
Daniel Dunbareefe8612010-07-19 05:44:09 +00003118 // Emit code to get the available features.
3119 OS << " // Get the current feature set.\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003120 OS << " uint64_t AvailableFeatures = getAvailableFeatures();\n\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00003121
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00003122 OS << " // Get the instruction mnemonic, which is the first token.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003123 if (HasMnemonicFirst) {
3124 OS << " StringRef Mnemonic = ((" << Target.getName()
3125 << "Operand&)*Operands[0]).getToken();\n\n";
3126 } else {
3127 OS << " StringRef Mnemonic;\n";
3128 OS << " if (Operands[0]->isToken())\n";
3129 OS << " Mnemonic = ((" << Target.getName()
3130 << "Operand&)*Operands[0]).getToken();\n\n";
3131 }
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00003132
Chris Lattner477fba4f2010-10-30 18:48:18 +00003133 if (HasMnemonicAliases) {
3134 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
Chad Rosier9f7a2212013-04-18 22:35:36 +00003135 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n";
Chris Lattner477fba4f2010-10-30 18:48:18 +00003136 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00003137
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003138 // Emit code to compute the class list for this operand vector.
Chris Lattnerabfe4222010-09-06 23:37:39 +00003139 OS << " // Some state to try to produce better error messages.\n";
Jim Grosbach120a96a2011-08-15 23:03:29 +00003140 OS << " bool HadMatchOtherThanFeatures = false;\n";
Jim Grosbachd152e2c2011-08-16 20:12:35 +00003141 OS << " bool HadMatchOtherThanPredicate = false;\n";
Jim Grosbach120a96a2011-08-15 23:03:29 +00003142 OS << " unsigned RetCode = Match_InvalidOperand;\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003143 OS << " uint64_t MissingFeatures = ~0ULL;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003144 if (HasOptionalOperands) {
3145 OS << " SmallBitVector OptionalOperandsMask(" << MaxNumOperands << ");\n";
3146 }
Jim Grosbach860a84d2011-02-11 21:31:55 +00003147 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
Chris Lattnerabfe4222010-09-06 23:37:39 +00003148 OS << " // wrong for all instances of the instruction.\n";
Tom Stellard5698d632015-03-05 19:46:55 +00003149 OS << " ErrorInfo = ~0ULL;\n";
Chris Lattner81301972010-09-06 21:22:45 +00003150
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003151 // Emit code to search the table.
Craig Topper690d8ea2013-07-24 07:33:14 +00003152 OS << " // Find the appropriate table for this asm variant.\n";
3153 OS << " const MatchEntry *Start, *End;\n";
3154 OS << " switch (VariantID) {\n";
Craig Topper8c714d12015-01-03 08:16:14 +00003155 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
Craig Topper690d8ea2013-07-24 07:33:14 +00003156 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3157 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topper690d8ea2013-07-24 07:33:14 +00003158 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Benjamin Kramer502b9e12014-04-12 16:15:53 +00003159 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3160 << "); End = std::end(MatchTable" << VC << "); break;\n";
Craig Topper690d8ea2013-07-24 07:33:14 +00003161 }
3162 OS << " }\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003163
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003164 OS << " // Search the table.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003165 if (HasMnemonicFirst) {
3166 OS << " auto MnemonicRange = "
3167 "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
3168 } else {
3169 OS << " auto MnemonicRange = std::make_pair(Start, End);\n";
3170 OS << " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
3171 OS << " if (!Mnemonic.empty())\n";
3172 OS << " MnemonicRange = "
3173 "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
3174 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003175
Chris Lattner628fbec2010-09-06 21:54:15 +00003176 OS << " // Return a more specific error code if no mnemonics match.\n";
3177 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
3178 OS << " return Match_MnemonicFail;\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003179
Chris Lattner81301972010-09-06 21:22:45 +00003180 OS << " for (const MatchEntry *it = MnemonicRange.first, "
Chris Lattner9026ac02010-09-06 21:23:43 +00003181 << "*ie = MnemonicRange.second;\n";
Chris Lattner81301972010-09-06 21:22:45 +00003182 OS << " it != ie; ++it) {\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00003183
Craig Topperfd2c6a32015-12-31 08:18:23 +00003184 if (HasMnemonicFirst) {
3185 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
3186 OS << " assert(Mnemonic == it->getMnemonic());\n";
3187 }
3188
Daniel Dunbareefe8612010-07-19 05:44:09 +00003189 // Emit check that the subclasses match.
Chris Lattner339cc7b2010-09-06 22:11:18 +00003190 OS << " bool OperandsValid = true;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003191 if (HasOptionalOperands) {
3192 OS << " OptionalOperandsMask.reset(0, " << MaxNumOperands << ");\n";
3193 }
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003194 OS << " for (unsigned FormalIdx = " << (HasMnemonicFirst ? "0" : "SIndex")
3195 << ", ActualIdx = " << (HasMnemonicFirst ? "1" : "SIndex")
3196 << "; FormalIdx != " << MaxNumOperands << "; ++FormalIdx) {\n";
3197 OS << " auto Formal = "
3198 << "static_cast<MatchClassKind>(it->Classes[FormalIdx]);\n";
3199 OS << " if (ActualIdx >= Operands.size()) {\n";
Tom Stellardb9f235e2016-02-05 19:59:33 +00003200 OS << " OperandsValid = (Formal == " <<"InvalidMatchClass) || "
3201 "isSubclass(Formal, OptionalMatchClass);\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003202 OS << " if (!OperandsValid) ErrorInfo = ActualIdx;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003203 if (HasOptionalOperands) {
3204 OS << " OptionalOperandsMask.set(FormalIdx, " << MaxNumOperands
3205 << ");\n";
3206 }
Jim Grosbache6ce2052011-05-03 19:09:56 +00003207 OS << " break;\n";
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00003208 OS << " }\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003209 OS << " MCParsedAsmOperand &Actual = *Operands[ActualIdx];\n";
Colin LeMahieu23403c22015-11-09 00:46:46 +00003210 OS << " unsigned Diag = validateOperandClass(Actual, Formal);\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003211 OS << " if (Diag == Match_Success) {\n";
3212 OS << " ++ActualIdx;\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00003213 OS << " continue;\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003214 OS << " }\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003215 OS << " // If the generic handler indicates an invalid operand\n";
3216 OS << " // failure, check for a special case.\n";
3217 OS << " if (Diag == Match_InvalidOperand) {\n";
Colin LeMahieu23403c22015-11-09 00:46:46 +00003218 OS << " Diag = validateTargetOperandClass(Actual, Formal);\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003219 OS << " if (Diag == Match_Success) {\n";
3220 OS << " ++ActualIdx;\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003221 OS << " continue;\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003222 OS << " }\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003223 OS << " }\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003224 OS << " // If current formal operand wasn't matched and it is optional\n"
3225 << " // then try to match next formal operand\n";
3226 OS << " if (Diag == Match_InvalidOperand "
Sam Kolton5f10a132016-05-06 11:31:17 +00003227 << "&& isSubclass(Formal, OptionalMatchClass)) {\n";
3228 if (HasOptionalOperands) {
3229 OS << " OptionalOperandsMask.set(FormalIdx);\n";
3230 }
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003231 OS << " continue;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003232 OS << " }\n";
Chris Lattnerabfe4222010-09-06 23:37:39 +00003233 OS << " // If this operand is broken for all of the instances of this\n";
3234 OS << " // mnemonic, keep track of it so we can report loc info.\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00003235 OS << " // If we already had a match that only failed due to a\n";
3236 OS << " // target predicate, that diagnostic is preferred.\n";
3237 OS << " if (!HadMatchOtherThanPredicate &&\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003238 OS << " (it == MnemonicRange.first || ErrorInfo <= ActualIdx)) {\n";
3239 OS << " ErrorInfo = ActualIdx;\n";
Jim Grosbach8ccdbd12012-06-26 22:58:01 +00003240 OS << " // InvalidOperand is the default. Prefer specificity.\n";
3241 OS << " if (Diag != Match_InvalidOperand)\n";
3242 OS << " RetCode = Diag;\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00003243 OS << " }\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00003244 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
3245 OS << " OperandsValid = false;\n";
3246 OS << " break;\n";
3247 OS << " }\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003248
Chris Lattner339cc7b2010-09-06 22:11:18 +00003249 OS << " if (!OperandsValid) continue;\n";
Chris Lattnerb4be28f2010-09-06 20:08:02 +00003250
3251 // Emit check that the required features are available.
3252 OS << " if ((AvailableFeatures & it->RequiredFeatures) "
3253 << "!= it->RequiredFeatures) {\n";
3254 OS << " HadMatchOtherThanFeatures = true;\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003255 OS << " uint64_t NewMissingFeatures = it->RequiredFeatures & "
Jim Grosbach9ec06a152012-06-18 19:45:46 +00003256 "~AvailableFeatures;\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003257 OS << " if (countPopulation(NewMissingFeatures) <=\n"
3258 " countPopulation(MissingFeatures))\n";
Jim Grosbach9ec06a152012-06-18 19:45:46 +00003259 OS << " MissingFeatures = NewMissingFeatures;\n";
Chris Lattnerb4be28f2010-09-06 20:08:02 +00003260 OS << " continue;\n";
3261 OS << " }\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003262 OS << "\n";
Ahmed Bougacha0dc19792014-12-16 18:05:28 +00003263 OS << " Inst.clear();\n\n";
Daniel Sandersc5537422016-07-27 13:49:44 +00003264 OS << " Inst.setOpcode(it->Opcode);\n";
3265 // Verify the instruction with the target-specific match predicate function.
3266 OS << " // We have a potential match but have not rendered the operands.\n"
3267 << " // Check the target predicate to handle any context sensitive\n"
3268 " // constraints.\n"
3269 << " // For example, Ties that are referenced multiple times must be\n"
3270 " // checked here to ensure the input is the same for each match\n"
3271 " // constraints. If we leave it any later the ties will have been\n"
3272 " // canonicalized\n"
3273 << " unsigned MatchResult;\n"
3274 << " if ((MatchResult = checkEarlyTargetMatchPredicate(Inst, "
3275 "Operands)) != Match_Success) {\n"
3276 << " Inst.clear();\n"
3277 << " RetCode = MatchResult;\n"
3278 << " HadMatchOtherThanPredicate = true;\n"
3279 << " continue;\n"
3280 << " }\n\n";
Chad Rosierf4e35dc2012-10-01 23:45:51 +00003281 OS << " if (matchingInlineAsm) {\n";
Chad Rosier2f480a82012-10-12 22:53:36 +00003282 OS << " convertToMapAndConstraints(it->ConvertFn, Operands);\n";
Chad Rosierf4e35dc2012-10-01 23:45:51 +00003283 OS << " return Match_Success;\n";
3284 OS << " }\n\n";
Daniel Dunbar66193402011-02-04 17:12:23 +00003285 OS << " // We have selected a definite instruction, convert the parsed\n"
3286 << " // operands into the appropriate MCInst.\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003287 if (HasOptionalOperands) {
3288 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands,\n"
3289 << " OptionalOperandsMask);\n";
3290 } else {
3291 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
3292 }
Daniel Dunbar66193402011-02-04 17:12:23 +00003293 OS << "\n";
Daniel Dunbar451a4352010-03-18 20:05:56 +00003294
Jim Grosbach120a96a2011-08-15 23:03:29 +00003295 // Verify the instruction with the target-specific match predicate function.
3296 OS << " // We have a potential match. Check the target predicate to\n"
3297 << " // handle any context sensitive constraints.\n"
Jim Grosbach120a96a2011-08-15 23:03:29 +00003298 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
3299 << " Match_Success) {\n"
3300 << " Inst.clear();\n"
3301 << " RetCode = MatchResult;\n"
Jim Grosbachd152e2c2011-08-16 20:12:35 +00003302 << " HadMatchOtherThanPredicate = true;\n"
Jim Grosbach120a96a2011-08-15 23:03:29 +00003303 << " continue;\n"
3304 << " }\n\n";
3305
Daniel Dunbar451a4352010-03-18 20:05:56 +00003306 // Call the post-processing function, if used.
3307 std::string InsnCleanupFn =
3308 AsmParser->getValueAsString("AsmParserInstCleanup");
3309 if (!InsnCleanupFn.empty())
3310 OS << " " << InsnCleanupFn << "(Inst);\n";
3311
Joey Gouly0e76fa72013-09-12 10:28:05 +00003312 if (HasDeprecation) {
3313 OS << " std::string Info;\n";
Akira Hatanakabd9fc282015-11-14 05:20:05 +00003314 OS << " if (MII.get(Inst.getOpcode()).getDeprecatedInfo(Inst, getSTI(), Info)) {\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00003315 OS << " SMLoc Loc = ((" << Target.getName()
3316 << "Operand&)*Operands[0]).getStartLoc();\n";
Rafael Espindola961d4692014-11-11 05:18:41 +00003317 OS << " getParser().Warning(Loc, Info, None);\n";
Joey Gouly0e76fa72013-09-12 10:28:05 +00003318 OS << " }\n";
3319 }
3320
Chris Lattnera22a3682010-09-06 19:22:17 +00003321 OS << " return Match_Success;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003322 OS << " }\n\n";
3323
Chris Lattnerb4be28f2010-09-06 20:08:02 +00003324 OS << " // Okay, we had no match. Try to return a useful error code.\n";
Chad Rosier4ee03842012-08-21 17:22:47 +00003325 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n";
3326 OS << " return RetCode;\n\n";
Jim Grosbach9ec06a152012-06-18 19:45:46 +00003327 OS << " // Missing feature matches return which features were missing\n";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003328 OS << " ErrorInfo = MissingFeatures;\n";
Jim Grosbachd152e2c2011-08-16 20:12:35 +00003329 OS << " return Match_MissingFeature;\n";
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003330 OS << "}\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003331
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003332 if (!Info.OperandMatchInfo.empty())
Craig Topper7ecfa6d2012-09-18 07:02:21 +00003333 emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable,
Craig Topperfd2c6a32015-12-31 08:18:23 +00003334 MaxMnemonicIndex, HasMnemonicFirst);
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003335
Chris Lattner3e4582a2010-09-06 19:11:01 +00003336 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
Daniel Dunbar3085b572009-07-11 19:39:44 +00003337}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00003338
3339namespace llvm {
3340
3341void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
3342 emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
3343 AsmMatcherEmitter(RK).run(OS);
3344}
3345
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +00003346} // end namespace llvm