blob: 508efa8bf5e4e7c96f9b9daefc30cb7c15604ecd [file] [log] [blame]
Daniel Dunbar3085b572009-07-11 19:39:44 +00001//===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Daniel Dunbar3085b572009-07-11 19:39:44 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This tablegen backend emits a target specifier matcher for converting parsed
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +000010// assembly operands in the MCInst structures. It also emits a matcher for
11// custom operand parsing.
12//
13// Converting assembly operands into MCInst structures
14// ---------------------------------------------------
Daniel Dunbar3085b572009-07-11 19:39:44 +000015//
Daniel Dunbare10787e2009-08-07 08:26:05 +000016// The input to the target specific matcher is a list of literal tokens and
17// operands. The target specific parser should generally eliminate any syntax
18// which is not relevant for matching; for example, comma tokens should have
19// already been consumed and eliminated by the parser. Most instructions will
20// end up with a single literal token (the instruction name) and some number of
21// operands.
22//
23// Some example inputs, for X86:
24// 'addl' (immediate ...) (register ...)
25// 'add' (immediate ...) (memory ...)
Jim Grosbach0eccfc22010-10-29 22:13:48 +000026// 'call' '*' %epc
Daniel Dunbare10787e2009-08-07 08:26:05 +000027//
28// The assembly matcher is responsible for converting this input into a precise
29// machine instruction (i.e., an instruction with a well defined encoding). This
30// mapping has several properties which complicate matching:
31//
32// - It may be ambiguous; many architectures can legally encode particular
33// variants of an instruction in different ways (for example, using a smaller
34// encoding for small immediates). Such ambiguities should never be
35// arbitrarily resolved by the assembler, the assembler is always responsible
36// for choosing the "best" available instruction.
37//
38// - It may depend on the subtarget or the assembler context. Instructions
39// which are invalid for the current mode, but otherwise unambiguous (e.g.,
40// an SSE instruction in a file being assembled for i486) should be accepted
41// and rejected by the assembler front end. However, if the proper encoding
42// for an instruction is dependent on the assembler context then the matcher
43// is responsible for selecting the correct machine instruction for the
44// current mode.
45//
46// The core matching algorithm attempts to exploit the regularity in most
47// instruction sets to quickly determine the set of possibly matching
48// instructions, and the simplify the generated code. Additionally, this helps
49// to ensure that the ambiguities are intentionally resolved by the user.
50//
51// The matching is divided into two distinct phases:
52//
53// 1. Classification: Each operand is mapped to the unique set which (a)
54// contains it, and (b) is the largest such subset for which a single
55// instruction could match all members.
56//
57// For register classes, we can generate these subgroups automatically. For
58// arbitrary operands, we expect the user to define the classes and their
59// relations to one another (for example, 8-bit signed immediates as a
60// subset of 32-bit immediates).
61//
62// By partitioning the operands in this way, we guarantee that for any
63// tuple of classes, any single instruction must match either all or none
64// of the sets of operands which could classify to that tuple.
65//
66// In addition, the subset relation amongst classes induces a partial order
67// on such tuples, which we use to resolve ambiguities.
68//
Daniel Dunbare10787e2009-08-07 08:26:05 +000069// 2. The input can now be treated as a tuple of classes (static tokens are
70// simple singleton sets). Each such tuple should generally map to a single
71// instruction (we currently ignore cases where this isn't true, whee!!!),
72// which we can emit a simple matcher for.
73//
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +000074// Custom Operand Parsing
75// ----------------------
76//
77// Some targets need a custom way to parse operands, some specific instructions
78// can contain arguments that can represent processor flags and other kinds of
Craig Topperaae8fb82012-09-18 01:13:36 +000079// identifiers that need to be mapped to specific values in the final encoded
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +000080// instructions. The target specific custom operand parsing works in the
81// following way:
82//
83// 1. A operand match table is built, each entry contains a mnemonic, an
84// operand class, a mask for all operand positions for that same
85// class/mnemonic and target features to be checked while trying to match.
86//
87// 2. The operand matcher will try every possible entry with the same
88// mnemonic and will check if the target feature for this mnemonic also
89// matches. After that, if the operand to be matched has its index
Chris Lattner0ab5e2c2011-04-15 05:18:47 +000090// present in the mask, a successful match occurs. Otherwise, fallback
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +000091// to the regular operand parsing.
92//
93// 3. For a match success, each operand class that has a 'ParserMethod'
94// becomes part of a switch from where the custom method is called.
95//
Daniel Dunbar3085b572009-07-11 19:39:44 +000096//===----------------------------------------------------------------------===//
97
Daniel Dunbar3085b572009-07-11 19:39:44 +000098#include "CodeGenTarget.h"
Daniel Sandersea6ef3d2016-11-15 09:51:02 +000099#include "SubtargetFeatureInfo.h"
Daniel Sandersca89f3a2016-11-19 12:21:34 +0000100#include "Types.h"
Justin Lebar5e83dfe2016-10-21 21:45:01 +0000101#include "llvm/ADT/CachedHashString.h"
Chris Lattner4efe13d2010-11-04 02:11:18 +0000102#include "llvm/ADT/PointerUnion.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +0000103#include "llvm/ADT/STLExtras.h"
Chris Lattnerf7a01e92010-11-01 01:47:07 +0000104#include "llvm/ADT/SmallPtrSet.h"
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000105#include "llvm/ADT/SmallVector.h"
Daniel Dunbare10787e2009-08-07 08:26:05 +0000106#include "llvm/ADT/StringExtras.h"
Nico Weber432a3882018-04-30 14:59:11 +0000107#include "llvm/Config/llvm-config.h"
Daniel Dunbare10787e2009-08-07 08:26:05 +0000108#include "llvm/Support/CommandLine.h"
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +0000109#include "llvm/Support/Debug.h"
Craig Topperc4965bc2012-02-05 07:21:30 +0000110#include "llvm/Support/ErrorHandling.h"
Peter Collingbourne84c287e2011-10-01 16:41:13 +0000111#include "llvm/TableGen/Error.h"
112#include "llvm/TableGen/Record.h"
Douglas Gregor12c1cd32012-05-02 17:32:48 +0000113#include "llvm/TableGen/StringMatcher.h"
Craig Topper3e1d5da2013-08-29 05:09:55 +0000114#include "llvm/TableGen/StringToOffsetTable.h"
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000115#include "llvm/TableGen/TableGenBackend.h"
116#include <cassert>
Will Dietz981af002013-10-12 00:55:57 +0000117#include <cctype>
Mehdi Aminib550cb12016-04-18 09:17:29 +0000118#include <forward_list>
Daniel Dunbar71330282009-08-08 05:24:34 +0000119#include <map>
120#include <set>
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000121
Daniel Dunbar3085b572009-07-11 19:39:44 +0000122using namespace llvm;
123
Chandler Carruthe96dd892014-04-21 22:55:11 +0000124#define DEBUG_TYPE "asm-matcher-emitter"
125
Daniel Sanders0848b232017-03-27 13:15:13 +0000126cl::OptionCategory AsmMatcherEmitterCat("Options for -gen-asm-matcher");
127
Daniel Dunbar15b80372009-08-07 20:33:39 +0000128static cl::opt<std::string>
Daniel Sanders0848b232017-03-27 13:15:13 +0000129 MatchPrefix("match-prefix", cl::init(""),
130 cl::desc("Only match instructions with the given prefix"),
131 cl::cat(AsmMatcherEmitterCat));
Daniel Dunbare10787e2009-08-07 08:26:05 +0000132
Daniel Dunbare10787e2009-08-07 08:26:05 +0000133namespace {
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000134class AsmMatcherInfo;
Daniel Dunbareefe8612010-07-19 05:44:09 +0000135
Tim Northoverc74e6912013-09-16 16:43:19 +0000136// Register sets are used as keys in some second-order sets TableGen creates
137// when generating its data structures. This means that the order of two
138// RegisterSets can be seen in the outputted AsmMatcher tables occasionally, and
139// can even affect compiler output (at least seen in diagnostics produced when
140// all matches fail). So we use a type that sorts them consistently.
141typedef std::set<Record*, LessRecordByID> RegisterSet;
142
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +0000143class AsmMatcherEmitter {
144 RecordKeeper &Records;
145public:
146 AsmMatcherEmitter(RecordKeeper &R) : Records(R) {}
147
148 void run(raw_ostream &o);
149};
150
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000151/// ClassInfo - Helper class for storing the information about a particular
152/// class of operands which can be matched.
153struct ClassInfo {
Daniel Dunbar3239f022009-08-09 04:00:06 +0000154 enum ClassInfoKind {
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000155 /// Invalid kind, for use as a sentinel value.
156 Invalid = 0,
157
158 /// The class for a particular token.
159 Token,
160
161 /// The (first) register class, subsequent register classes are
162 /// RegisterClass0+1, and so on.
163 RegisterClass0,
164
165 /// The (first) user defined class, subsequent user defined classes are
166 /// UserClass0+1, and so on.
167 UserClass0 = 1<<16
Daniel Dunbar3239f022009-08-09 04:00:06 +0000168 };
169
170 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
171 /// N) for the Nth user defined class.
172 unsigned Kind;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000173
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000174 /// SuperClasses - The super classes of this class. Note that for simplicities
175 /// sake user operands only record their immediate super class, while register
176 /// operands include all superclasses.
177 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000178
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000179 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000180 std::string Name;
181
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000182 /// ClassName - The unadorned generic name for this class (e.g., Token).
183 std::string ClassName;
184
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000185 /// ValueName - The name of the value this class represents; for a token this
186 /// is the literal token string, for an operand it is the TableGen class (or
187 /// empty if this is a derived class).
188 std::string ValueName;
189
190 /// PredicateMethod - The name of the operand method to test whether the
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000191 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000192 std::string PredicateMethod;
193
194 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000195 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000196 std::string RenderMethod;
Daniel Dunbar3239f022009-08-09 04:00:06 +0000197
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000198 /// ParserMethod - The name of the operand method to do a target specific
199 /// parsing on the operand.
200 std::string ParserMethod;
201
Eric Christopher650c8f22014-05-20 17:11:11 +0000202 /// For register classes: the records for all the registers in this class.
Tim Northoverc74e6912013-09-16 16:43:19 +0000203 RegisterSet Registers;
Daniel Dunbar34c87912009-08-11 20:10:07 +0000204
Eric Christopher650c8f22014-05-20 17:11:11 +0000205 /// For custom match classes: the diagnostic kind for when the predicate fails.
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +0000206 std::string DiagnosticType;
Tom Stellardb9f235e2016-02-05 19:59:33 +0000207
Oliver Stannard41dfac32017-10-03 14:34:57 +0000208 /// For custom match classes: the diagnostic string for when the predicate fails.
209 std::string DiagnosticString;
210
Tom Stellardb9f235e2016-02-05 19:59:33 +0000211 /// Is this operand optional and not always required.
212 bool IsOptional;
213
Sam Kolton5f10a132016-05-06 11:31:17 +0000214 /// DefaultMethod - The name of the method that returns the default operand
215 /// for optional operand
216 std::string DefaultMethod;
217
Daniel Dunbar34c87912009-08-11 20:10:07 +0000218public:
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000219 /// isRegisterClass() - Check if this is a register class.
220 bool isRegisterClass() const {
221 return Kind >= RegisterClass0 && Kind < UserClass0;
222 }
223
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000224 /// isUserClass() - Check if this is a user defined class.
225 bool isUserClass() const {
226 return Kind >= UserClass0;
227 }
228
Dmitri Gribenko8d302402012-09-15 20:22:05 +0000229 /// isRelatedTo - Check whether this class is "related" to \p RHS. Classes
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000230 /// are related if they are in the same class hierarchy.
231 bool isRelatedTo(const ClassInfo &RHS) const {
232 // Tokens are only related to tokens.
233 if (Kind == Token || RHS.Kind == Token)
234 return Kind == Token && RHS.Kind == Token;
235
Daniel Dunbar34c87912009-08-11 20:10:07 +0000236 // Registers classes are only related to registers classes, and only if
237 // their intersection is non-empty.
238 if (isRegisterClass() || RHS.isRegisterClass()) {
239 if (!isRegisterClass() || !RHS.isRegisterClass())
240 return false;
241
Tim Northoverc74e6912013-09-16 16:43:19 +0000242 RegisterSet Tmp;
243 std::insert_iterator<RegisterSet> II(Tmp, Tmp.begin());
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000244 std::set_intersection(Registers.begin(), Registers.end(),
Daniel Dunbar34c87912009-08-11 20:10:07 +0000245 RHS.Registers.begin(), RHS.Registers.end(),
Tim Northoverc74e6912013-09-16 16:43:19 +0000246 II, LessRecordByID());
Daniel Dunbar34c87912009-08-11 20:10:07 +0000247
248 return !Tmp.empty();
249 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000250
251 // Otherwise we have two users operands; they are related if they are in the
252 // same class hierarchy.
Daniel Dunbar34c87912009-08-11 20:10:07 +0000253 //
254 // FIXME: This is an oversimplification, they should only be related if they
255 // intersect, however we don't have that information.
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000256 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
257 const ClassInfo *Root = this;
258 while (!Root->SuperClasses.empty())
259 Root = Root->SuperClasses.front();
260
Daniel Dunbar34c87912009-08-11 20:10:07 +0000261 const ClassInfo *RHSRoot = &RHS;
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000262 while (!RHSRoot->SuperClasses.empty())
263 RHSRoot = RHSRoot->SuperClasses.front();
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000264
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000265 return Root == RHSRoot;
266 }
267
Dmitri Gribenko8d302402012-09-15 20:22:05 +0000268 /// isSubsetOf - Test whether this class is a subset of \p RHS.
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000269 bool isSubsetOf(const ClassInfo &RHS) const {
270 // This is a subset of RHS if it is the same class...
271 if (this == &RHS)
272 return true;
273
274 // ... or if any of its super classes are a subset of RHS.
Marcello Maggioni218b6a22018-07-13 16:36:14 +0000275 SmallVector<const ClassInfo *, 16> Worklist(SuperClasses.begin(),
276 SuperClasses.end());
277 SmallPtrSet<const ClassInfo *, 16> Visited;
278 while (!Worklist.empty()) {
279 auto *CI = Worklist.pop_back_val();
280 if (CI == &RHS)
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000281 return true;
Marcello Maggioni218b6a22018-07-13 16:36:14 +0000282 for (auto *Super : CI->SuperClasses)
283 if (Visited.insert(Super).second)
284 Worklist.push_back(Super);
285 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000286
287 return false;
Daniel Dunbar8e33cb22009-08-09 07:20:21 +0000288 }
289
Oliver Stannard7772f022016-01-25 10:20:19 +0000290 int getTreeDepth() const {
291 int Depth = 0;
292 const ClassInfo *Root = this;
293 while (!Root->SuperClasses.empty()) {
294 Depth++;
295 Root = Root->SuperClasses.front();
296 }
297 return Depth;
298 }
299
300 const ClassInfo *findRoot() const {
301 const ClassInfo *Root = this;
302 while (!Root->SuperClasses.empty())
303 Root = Root->SuperClasses.front();
304 return Root;
305 }
306
307 /// Compare two classes. This does not produce a total ordering, but does
308 /// guarantee that subclasses are sorted before their parents, and that the
309 /// ordering is transitive.
Daniel Dunbar3239f022009-08-09 04:00:06 +0000310 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar97ac3af2010-05-27 05:31:32 +0000311 if (this == &RHS)
312 return false;
313
Oliver Stannard7772f022016-01-25 10:20:19 +0000314 // First, enforce the ordering between the three different types of class.
315 // Tokens sort before registers, which sort before user classes.
316 if (Kind == Token) {
317 if (RHS.Kind != Token)
Duncan Sands41b4a6b2010-07-12 08:16:59 +0000318 return true;
Oliver Stannard7772f022016-01-25 10:20:19 +0000319 assert(RHS.Kind == Token);
320 } else if (isRegisterClass()) {
321 if (RHS.Kind == Token)
Duncan Sands41b4a6b2010-07-12 08:16:59 +0000322 return false;
Oliver Stannard7772f022016-01-25 10:20:19 +0000323 else if (RHS.isUserClass())
324 return true;
325 assert(RHS.isRegisterClass());
326 } else if (isUserClass()) {
327 if (!RHS.isUserClass())
328 return false;
329 assert(RHS.isUserClass());
330 } else {
331 llvm_unreachable("Unknown ClassInfoKind");
Daniel Dunbar3239f022009-08-09 04:00:06 +0000332 }
Oliver Stannard7772f022016-01-25 10:20:19 +0000333
334 if (Kind == Token || isUserClass()) {
335 // Related tokens and user classes get sorted by depth in the inheritence
336 // tree (so that subclasses are before their parents).
337 if (isRelatedTo(RHS)) {
338 if (getTreeDepth() > RHS.getTreeDepth())
339 return true;
340 if (getTreeDepth() < RHS.getTreeDepth())
341 return false;
342 } else {
343 // Unrelated tokens and user classes are ordered by the name of their
344 // root nodes, so that there is a consistent ordering between
345 // unconnected trees.
346 return findRoot()->ValueName < RHS.findRoot()->ValueName;
347 }
348 } else if (isRegisterClass()) {
349 // For register sets, sort by number of registers. This guarantees that
350 // a set will always sort before all of it's strict supersets.
351 if (Registers.size() != RHS.Registers.size())
352 return Registers.size() < RHS.Registers.size();
353 } else {
354 llvm_unreachable("Unknown ClassInfoKind");
355 }
356
357 // FIXME: We should be able to just return false here, as we only need a
358 // partial order (we use stable sorts, so this is deterministic) and the
359 // name of a class shouldn't be significant. However, some of the backends
360 // accidentally rely on this behaviour, so it will have to stay like this
361 // until they are fixed.
362 return ValueName < RHS.ValueName;
Daniel Dunbar3239f022009-08-09 04:00:06 +0000363 }
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000364};
365
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000366class AsmVariantInfo {
367public:
Craig Topperbcd3c372017-05-31 21:12:46 +0000368 StringRef RegisterPrefix;
369 StringRef TokenizingCharacters;
370 StringRef SeparatorCharacters;
371 StringRef BreakCharacters;
372 StringRef Name;
Craig Topperc8b5b252015-12-30 06:00:18 +0000373 int AsmVariantNo;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000374};
375
Chris Lattnerad776812010-11-01 05:06:45 +0000376/// MatchableInfo - Helper class for storing the necessary information for an
377/// instruction or alias which is capable of being matched.
378struct MatchableInfo {
Chris Lattner896cf042010-11-03 19:47:34 +0000379 struct AsmOperand {
Chris Lattner28ea9b12010-11-02 17:30:52 +0000380 /// Token - This is the token that the operand came from.
381 StringRef Token;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000382
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000383 /// The unique class instance this operand should match.
384 ClassInfo *Class;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000385
Chris Lattner7108dad2010-11-04 01:42:59 +0000386 /// The operand name this is, if anything.
387 StringRef SrcOpName;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000388
Sander de Smalen5b691a12018-02-04 16:24:17 +0000389 /// The operand name this is, before renaming for tied operands.
390 StringRef OrigSrcOpName;
391
Bob Wilsonb9b24222011-01-26 19:44:55 +0000392 /// The suboperand index within SrcOpName, or -1 for the entire operand.
393 int SubOpIdx;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000394
Ahmed Bougachaeb4dbd82015-05-29 01:03:37 +0000395 /// Whether the token is "isolated", i.e., it is preceded and followed
396 /// by separators.
397 bool IsIsolatedToken;
398
Devang Patel6d676e42012-01-07 01:33:34 +0000399 /// Register record if this token is singleton register.
400 Record *SingletonReg;
401
Ahmed Bougachaeb4dbd82015-05-29 01:03:37 +0000402 explicit AsmOperand(bool IsIsolatedToken, StringRef T)
403 : Token(T), Class(nullptr), SubOpIdx(-1),
404 IsIsolatedToken(IsIsolatedToken), SingletonReg(nullptr) {}
Daniel Dunbare10787e2009-08-07 08:26:05 +0000405 };
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000406
Chris Lattner743081d2010-11-04 00:43:46 +0000407 /// ResOperand - This represents a single operand in the result instruction
408 /// generated by the match. In cases (like addressing modes) where a single
409 /// assembler operand expands to multiple MCOperands, this represents the
410 /// single assembler operand, not the MCOperand.
411 struct ResOperand {
412 enum {
413 /// RenderAsmOperand - This represents an operand result that is
414 /// generated by calling the render method on the assembly operand. The
415 /// corresponding AsmOperand is specified by AsmOperandNum.
416 RenderAsmOperand,
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000417
Chris Lattner743081d2010-11-04 00:43:46 +0000418 /// TiedOperand - This represents a result operand that is a duplicate of
419 /// a previous result operand.
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000420 TiedOperand,
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000421
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000422 /// ImmOperand - This represents an immediate value that is dumped into
423 /// the operand.
Chris Lattner4869d342010-11-06 19:57:21 +0000424 ImmOperand,
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000425
Chris Lattner4869d342010-11-06 19:57:21 +0000426 /// RegOperand - This represents a fixed register that is dumped in.
427 RegOperand
Chris Lattner743081d2010-11-04 00:43:46 +0000428 } Kind;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000429
Sander de Smalen5b691a12018-02-04 16:24:17 +0000430 /// Tuple containing the index of the (earlier) result operand that should
431 /// be copied from, as well as the indices of the corresponding (parsed)
432 /// operands in the asm string.
433 struct TiedOperandsTuple {
434 unsigned ResOpnd;
435 unsigned SrcOpnd1Idx;
436 unsigned SrcOpnd2Idx;
437 };
438
Chris Lattner743081d2010-11-04 00:43:46 +0000439 union {
440 /// This is the operand # in the AsmOperands list that this should be
441 /// copied from.
442 unsigned AsmOperandNum;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000443
Sander de Smalen5b691a12018-02-04 16:24:17 +0000444 /// Description of tied operands.
445 TiedOperandsTuple TiedOperands;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000446
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000447 /// ImmVal - This is the immediate value added to the instruction.
448 int64_t ImmVal;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000449
Chris Lattner4869d342010-11-06 19:57:21 +0000450 /// Register - This is the register record.
451 Record *Register;
Chris Lattner743081d2010-11-04 00:43:46 +0000452 };
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000453
Bob Wilsonb9b24222011-01-26 19:44:55 +0000454 /// MINumOperands - The number of MCInst operands populated by this
455 /// operand.
456 unsigned MINumOperands;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000457
Bob Wilsonb9b24222011-01-26 19:44:55 +0000458 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
Chris Lattner743081d2010-11-04 00:43:46 +0000459 ResOperand X;
460 X.Kind = RenderAsmOperand;
461 X.AsmOperandNum = AsmOpNum;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000462 X.MINumOperands = NumOperands;
Chris Lattner743081d2010-11-04 00:43:46 +0000463 return X;
464 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000465
Sander de Smalen5b691a12018-02-04 16:24:17 +0000466 static ResOperand getTiedOp(unsigned TiedOperandNum, unsigned SrcOperand1,
467 unsigned SrcOperand2) {
Chris Lattner743081d2010-11-04 00:43:46 +0000468 ResOperand X;
469 X.Kind = TiedOperand;
Sander de Smalen5b691a12018-02-04 16:24:17 +0000470 X.TiedOperands = { TiedOperandNum, SrcOperand1, SrcOperand2 };
Bob Wilsonb9b24222011-01-26 19:44:55 +0000471 X.MINumOperands = 1;
Chris Lattner743081d2010-11-04 00:43:46 +0000472 return X;
473 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000474
Bob Wilsonb9b24222011-01-26 19:44:55 +0000475 static ResOperand getImmOp(int64_t Val) {
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000476 ResOperand X;
477 X.Kind = ImmOperand;
478 X.ImmVal = Val;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000479 X.MINumOperands = 1;
Chris Lattnerb6f8e822010-11-06 19:25:43 +0000480 return X;
481 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000482
Bob Wilsonb9b24222011-01-26 19:44:55 +0000483 static ResOperand getRegOp(Record *Reg) {
Chris Lattner4869d342010-11-06 19:57:21 +0000484 ResOperand X;
485 X.Kind = RegOperand;
486 X.Register = Reg;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000487 X.MINumOperands = 1;
Chris Lattner4869d342010-11-06 19:57:21 +0000488 return X;
489 }
Chris Lattner743081d2010-11-04 00:43:46 +0000490 };
Daniel Dunbare10787e2009-08-07 08:26:05 +0000491
Devang Patel9bdc5052012-01-10 17:50:43 +0000492 /// AsmVariantID - Target's assembly syntax variant no.
493 int AsmVariantID;
494
David Blaikieba4e00f2014-12-22 21:26:26 +0000495 /// AsmString - The assembly string for this instruction (with variants
496 /// removed), e.g. "movsx $src, $dst".
497 std::string AsmString;
498
Chris Lattnera7a903e2010-11-02 17:34:28 +0000499 /// TheDef - This is the definition of the instruction or InstAlias that this
500 /// matchable came from.
Chris Lattner39bc53b2010-11-01 04:34:44 +0000501 Record *const TheDef;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000502
Chris Lattner4efe13d2010-11-04 02:11:18 +0000503 /// DefRec - This is the definition that it came from.
504 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000505
Chris Lattnerfecdad62010-11-06 07:14:44 +0000506 const CodeGenInstruction *getResultInst() const {
507 if (DefRec.is<const CodeGenInstruction*>())
508 return DefRec.get<const CodeGenInstruction*>();
509 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
510 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000511
Chris Lattner743081d2010-11-04 00:43:46 +0000512 /// ResOperands - This is the operand list that should be built for the result
513 /// MCInst.
Jim Grosbacha37e2292012-04-19 17:52:34 +0000514 SmallVector<ResOperand, 8> ResOperands;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000515
Chris Lattner28ea9b12010-11-02 17:30:52 +0000516 /// Mnemonic - This is the first token of the matched instruction, its
517 /// mnemonic.
518 StringRef Mnemonic;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000519
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000520 /// AsmOperands - The textual operands that this instruction matches,
Chris Lattnera7a903e2010-11-02 17:34:28 +0000521 /// annotated with a class and where in the OperandList they were defined.
522 /// This directly corresponds to the tokenized AsmString after the mnemonic is
523 /// removed.
Jim Grosbacha37e2292012-04-19 17:52:34 +0000524 SmallVector<AsmOperand, 8> AsmOperands;
Daniel Dunbare10787e2009-08-07 08:26:05 +0000525
Daniel Dunbareefe8612010-07-19 05:44:09 +0000526 /// Predicates - The required subtarget features to match this instruction.
David Blaikie9a9da992014-11-28 22:15:06 +0000527 SmallVector<const SubtargetFeatureInfo *, 4> RequiredFeatures;
Daniel Dunbareefe8612010-07-19 05:44:09 +0000528
Daniel Dunbar71330282009-08-08 05:24:34 +0000529 /// ConversionFnKind - The enum value which is passed to the generated
Chad Rosierba284b92012-09-05 01:02:38 +0000530 /// convertToMCInst to convert parsed operands into an MCInst for this
Daniel Dunbar71330282009-08-08 05:24:34 +0000531 /// function.
532 std::string ConversionFnKind;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000533
Joey Gouly0e76fa72013-09-12 10:28:05 +0000534 /// If this instruction is deprecated in some form.
535 bool HasDeprecation;
536
Tom Stellard74c87c82015-05-26 15:55:50 +0000537 /// If this is an alias, this is use to determine whether or not to using
538 /// the conversion function defined by the instruction's AsmMatchConverter
539 /// or to use the function generated by the alias.
540 bool UseInstAsmMatchConverter;
541
Chris Lattnerad776812010-11-01 05:06:45 +0000542 MatchableInfo(const CodeGenInstruction &CGI)
Tom Stellard74c87c82015-05-26 15:55:50 +0000543 : AsmVariantID(0), AsmString(CGI.AsmString), TheDef(CGI.TheDef), DefRec(&CGI),
544 UseInstAsmMatchConverter(true) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000545 }
Chris Lattner39bc53b2010-11-01 04:34:44 +0000546
David Blaikieba4e00f2014-12-22 21:26:26 +0000547 MatchableInfo(std::unique_ptr<const CodeGenInstAlias> Alias)
Tom Stellard74c87c82015-05-26 15:55:50 +0000548 : AsmVariantID(0), AsmString(Alias->AsmString), TheDef(Alias->TheDef),
549 DefRec(Alias.release()),
550 UseInstAsmMatchConverter(
551 TheDef->getValueAsBit("UseInstAsmMatchConverter")) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000552 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000553
David Blaikie6e48a812015-08-01 01:08:30 +0000554 // Could remove this and the dtor if PointerUnion supported unique_ptr
555 // elements with a dynamic failure/assertion (like the one below) in the case
556 // where it was copied while being in an owning state.
557 MatchableInfo(const MatchableInfo &RHS)
558 : AsmVariantID(RHS.AsmVariantID), AsmString(RHS.AsmString),
559 TheDef(RHS.TheDef), DefRec(RHS.DefRec), ResOperands(RHS.ResOperands),
560 Mnemonic(RHS.Mnemonic), AsmOperands(RHS.AsmOperands),
561 RequiredFeatures(RHS.RequiredFeatures),
562 ConversionFnKind(RHS.ConversionFnKind),
563 HasDeprecation(RHS.HasDeprecation),
564 UseInstAsmMatchConverter(RHS.UseInstAsmMatchConverter) {
565 assert(!DefRec.is<const CodeGenInstAlias *>());
566 }
567
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000568 ~MatchableInfo() {
David Blaikieba4e00f2014-12-22 21:26:26 +0000569 delete DefRec.dyn_cast<const CodeGenInstAlias*>();
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000570 }
Craig Topperce274892014-11-28 05:01:21 +0000571
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000572 // Two-operand aliases clone from the main matchable, but mark the second
573 // operand as a tied operand of the first for purposes of the assembler.
574 void formTwoOperandAlias(StringRef Constraint);
575
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000576 void initialize(const AsmMatcherInfo &Info,
Craig Topper71b7b682014-08-21 05:55:13 +0000577 SmallPtrSetImpl<Record*> &SingletonRegisters,
Craig Topperfd2c6a32015-12-31 08:18:23 +0000578 AsmVariantInfo const &Variant,
579 bool HasMnemonicFirst);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000580
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000581 /// validate - Return true if this matchable is a valid thing to match against
Chris Lattnerad776812010-11-01 05:06:45 +0000582 /// and perform a bunch of validity checking.
Sander de Smalen5b691a12018-02-04 16:24:17 +0000583 bool validate(StringRef CommentDelimiter, bool IsAlias) const;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000584
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000585 /// findAsmOperand - Find the AsmOperand with the specified name and
Bob Wilsonb9b24222011-01-26 19:44:55 +0000586 /// suboperand index.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000587 int findAsmOperand(StringRef N, int SubOpIdx) const {
David Majnemer562e8292016-08-12 00:18:03 +0000588 auto I = find_if(AsmOperands, [&](const AsmOperand &Op) {
589 return Op.SrcOpName == N && Op.SubOpIdx == SubOpIdx;
590 });
Craig Topper58a0e7a2016-01-03 07:33:36 +0000591 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
Bob Wilsonb9b24222011-01-26 19:44:55 +0000592 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000593
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000594 /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
Bob Wilsonb9b24222011-01-26 19:44:55 +0000595 /// This does not check the suboperand index.
Sander de Smalen5b691a12018-02-04 16:24:17 +0000596 int findAsmOperandNamed(StringRef N, int LastIdx = -1) const {
597 auto I = std::find_if(AsmOperands.begin() + LastIdx + 1, AsmOperands.end(),
David Majnemer562e8292016-08-12 00:18:03 +0000598 [&](const AsmOperand &Op) { return Op.SrcOpName == N; });
Craig Topper58a0e7a2016-01-03 07:33:36 +0000599 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
Chris Lattner897a1402010-11-04 01:55:23 +0000600 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000601
Sander de Smalen5b691a12018-02-04 16:24:17 +0000602 int findAsmOperandOriginallyNamed(StringRef N) const {
603 auto I =
604 find_if(AsmOperands,
605 [&](const AsmOperand &Op) { return Op.OrigSrcOpName == N; });
606 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
607 }
608
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000609 void buildInstructionResultOperands();
Sander de Smalen5b691a12018-02-04 16:24:17 +0000610 void buildAliasResultOperands(bool AliasConstraintsAreChecked);
Chris Lattner743081d2010-11-04 00:43:46 +0000611
Chris Lattnerad776812010-11-01 05:06:45 +0000612 /// operator< - Compare two matchables.
613 bool operator<(const MatchableInfo &RHS) const {
Chris Lattner82d88ce2010-09-06 21:01:37 +0000614 // The primary comparator is the instruction mnemonic.
Ahmed Bougachaef3358d2016-06-23 17:09:49 +0000615 if (int Cmp = Mnemonic.compare(RHS.Mnemonic))
616 return Cmp == -1;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000617
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000618 if (AsmOperands.size() != RHS.AsmOperands.size())
619 return AsmOperands.size() < RHS.AsmOperands.size();
Daniel Dunbar3239f022009-08-09 04:00:06 +0000620
Daniel Dunbard9631912009-08-09 08:23:23 +0000621 // Compare lexicographically by operand. The matcher validates that other
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000622 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000623 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
624 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbar3239f022009-08-09 04:00:06 +0000625 return true;
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000626 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbard9631912009-08-09 08:23:23 +0000627 return false;
628 }
629
Andrew Trick818f5ac2012-08-29 03:52:57 +0000630 // Give matches that require more features higher precedence. This is useful
631 // because we cannot define AssemblerPredicates with the negation of
632 // processor features. For example, ARM v6 "nop" may be either a HINT or
633 // MOV. With v6, we want to match HINT. The assembler has no way to
634 // predicate MOV under "NoV6", but HINT will always match first because it
635 // requires V6 while MOV does not.
636 if (RequiredFeatures.size() != RHS.RequiredFeatures.size())
637 return RequiredFeatures.size() > RHS.RequiredFeatures.size();
638
Daniel Dunbar3239f022009-08-09 04:00:06 +0000639 return false;
640 }
641
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000642 /// couldMatchAmbiguouslyWith - Check whether this matchable could
Dmitri Gribenko8d302402012-09-15 20:22:05 +0000643 /// ambiguously match the same set of operands as \p RHS (without being a
Daniel Dunbarf573b562009-08-09 06:05:33 +0000644 /// strictly superior match).
Craig Topper42bd8192014-11-28 03:53:00 +0000645 bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) const {
Chris Lattnere3c48de2010-11-01 23:57:23 +0000646 // The primary comparator is the instruction mnemonic.
Chris Lattner28ea9b12010-11-02 17:30:52 +0000647 if (Mnemonic != RHS.Mnemonic)
Chris Lattnere3c48de2010-11-01 23:57:23 +0000648 return false;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000649
Craig Topperad895412018-01-06 19:20:32 +0000650 // Different variants can't conflict.
651 if (AsmVariantID != RHS.AsmVariantID)
652 return false;
653
Daniel Dunbarf573b562009-08-09 06:05:33 +0000654 // The number of operands is unambiguous.
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000655 if (AsmOperands.size() != RHS.AsmOperands.size())
Daniel Dunbarf573b562009-08-09 06:05:33 +0000656 return false;
657
Daniel Dunbare1974092010-01-23 00:26:16 +0000658 // Otherwise, make sure the ordering of the two instructions is unambiguous
659 // by checking that either (a) a token or operand kind discriminates them,
660 // or (b) the ordering among equivalent kinds is consistent.
661
Daniel Dunbarf573b562009-08-09 06:05:33 +0000662 // Tokens and operand kinds are unambiguous (assuming a correct target
663 // specific parser).
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000664 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
665 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
666 AsmOperands[i].Class->Kind == ClassInfo::Token)
667 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
668 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbarf573b562009-08-09 06:05:33 +0000669 return false;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000670
Daniel Dunbarf573b562009-08-09 06:05:33 +0000671 // Otherwise, this operand could commute if all operands are equivalent, or
672 // there is a pair of operands that compare less than and a pair that
673 // compare greater than.
674 bool HasLT = false, HasGT = false;
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000675 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
676 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbarf573b562009-08-09 06:05:33 +0000677 HasLT = true;
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000678 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbarf573b562009-08-09 06:05:33 +0000679 HasGT = true;
680 }
681
Craig Topper322b67f2016-01-03 07:33:39 +0000682 return HasLT == HasGT;
Daniel Dunbarf573b562009-08-09 06:05:33 +0000683 }
684
Craig Topper42bd8192014-11-28 03:53:00 +0000685 void dump() const;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000686
Chris Lattner28ea9b12010-11-02 17:30:52 +0000687private:
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000688 void tokenizeAsmString(AsmMatcherInfo const &Info,
689 AsmVariantInfo const &Variant);
Craig Topperbc22e262015-12-31 05:01:45 +0000690 void addAsmOperand(StringRef Token, bool IsIsolatedToken = false);
Daniel Dunbare10787e2009-08-07 08:26:05 +0000691};
692
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000693struct OperandMatchEntry {
694 unsigned OperandMask;
Craig Topper42bd8192014-11-28 03:53:00 +0000695 const MatchableInfo* MI;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000696 ClassInfo *CI;
697
Craig Topper42bd8192014-11-28 03:53:00 +0000698 static OperandMatchEntry create(const MatchableInfo *mi, ClassInfo *ci,
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000699 unsigned opMask) {
700 OperandMatchEntry X;
701 X.OperandMask = opMask;
702 X.CI = ci;
703 X.MI = mi;
704 return X;
705 }
706};
707
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000708class AsmMatcherInfo {
709public:
Chris Lattner77d369c2010-12-13 00:23:57 +0000710 /// Tracked Records
Chris Lattner89dcb682010-12-15 04:48:22 +0000711 RecordKeeper &Records;
Chris Lattner77d369c2010-12-13 00:23:57 +0000712
Daniel Dunbare4318712009-08-11 20:59:47 +0000713 /// The tablegen AsmParser record.
714 Record *AsmParser;
715
Chris Lattnerb80ab362010-11-01 01:37:30 +0000716 /// Target - The target information.
717 CodeGenTarget &Target;
718
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000719 /// The classes which are needed for matching.
David Blaikied749e342014-11-28 20:35:57 +0000720 std::forward_list<ClassInfo> Classes;
Jim Grosbach0eccfc22010-10-29 22:13:48 +0000721
Chris Lattnerad776812010-11-01 05:06:45 +0000722 /// The information on the matchables to match.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +0000723 std::vector<std::unique_ptr<MatchableInfo>> Matchables;
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000724
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000725 /// Info for custom matching operands by user defined methods.
726 std::vector<OperandMatchEntry> OperandMatchInfo;
727
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000728 /// Map of Register records to their class information.
Sean Silvac8f56572012-09-19 01:47:01 +0000729 typedef std::map<Record*, ClassInfo*, LessRecordByID> RegisterClassesTy;
730 RegisterClassesTy RegisterClasses;
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000731
Daniel Dunbareefe8612010-07-19 05:44:09 +0000732 /// Map of Predicate records to their subtarget information.
David Blaikie9a9da992014-11-28 22:15:06 +0000733 std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000734
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +0000735 /// Map of AsmOperandClass records to their class information.
736 std::map<Record*, ClassInfo*> AsmOperandClasses;
737
Oliver Stannard29ffd3f2017-10-10 11:00:40 +0000738 /// Map of RegisterClass records to their class information.
739 std::map<Record*, ClassInfo*> RegisterClassClasses;
740
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000741private:
742 /// Map of token to class information which has already been constructed.
743 std::map<std::string, ClassInfo*> TokenClasses;
744
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000745private:
746 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattner60db0a62010-02-09 00:34:28 +0000747 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000748
749 /// getOperandClass - Lookup or create the class for the given operand.
Bob Wilsonb9b24222011-01-26 19:44:55 +0000750 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
Jim Grosbachd1f1b792011-10-28 22:32:53 +0000751 int SubOpIdx);
752 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000753
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000754 /// buildRegisterClasses - Build the ClassInfo* instances for register
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000755 /// classes.
Craig Topper71b7b682014-08-21 05:55:13 +0000756 void buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters);
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000757
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000758 /// buildOperandClasses - Build the ClassInfo* instances for user defined
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000759 /// operand classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000760 void buildOperandClasses();
Daniel Dunbarbb98db22009-08-11 02:59:53 +0000761
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000762 void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
Bob Wilsonb9b24222011-01-26 19:44:55 +0000763 unsigned AsmOpIdx);
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000764 void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
Chris Lattner4efe13d2010-11-04 02:11:18 +0000765 MatchableInfo::AsmOperand &Op);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000766
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000767public:
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000768 AsmMatcherInfo(Record *AsmParser,
769 CodeGenTarget &Target,
Chris Lattner89dcb682010-12-15 04:48:22 +0000770 RecordKeeper &Records);
Daniel Dunbare4318712009-08-11 20:59:47 +0000771
Daniel Sandersea6ef3d2016-11-15 09:51:02 +0000772 /// Construct the various tables used during matching.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000773 void buildInfo();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000774
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000775 /// buildOperandMatchInfo - Build the necessary information to handle user
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000776 /// defined operand parsing methods.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000777 void buildOperandMatchInfo();
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +0000778
Chris Lattner43690072010-10-30 20:15:02 +0000779 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
780 /// given operand.
David Blaikie9a9da992014-11-28 22:15:06 +0000781 const SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
Chris Lattner43690072010-10-30 20:15:02 +0000782 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
Craig Topper42bd8192014-11-28 03:53:00 +0000783 const auto &I = SubtargetFeatures.find(Def);
David Blaikie9a9da992014-11-28 22:15:06 +0000784 return I == SubtargetFeatures.end() ? nullptr : &I->second;
Chris Lattner43690072010-10-30 20:15:02 +0000785 }
Chris Lattner77d369c2010-12-13 00:23:57 +0000786
Chris Lattner89dcb682010-12-15 04:48:22 +0000787 RecordKeeper &getRecords() const {
788 return Records;
Chris Lattner77d369c2010-12-13 00:23:57 +0000789 }
Sam Kolton5f10a132016-05-06 11:31:17 +0000790
791 bool hasOptionalOperands() const {
David Majnemer562e8292016-08-12 00:18:03 +0000792 return find_if(Classes, [](const ClassInfo &Class) {
793 return Class.IsOptional;
794 }) != Classes.end();
Sam Kolton5f10a132016-05-06 11:31:17 +0000795 }
Daniel Dunbar541efcc2009-08-08 07:50:56 +0000796};
797
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000798} // end anonymous namespace
Daniel Dunbare10787e2009-08-07 08:26:05 +0000799
Aaron Ballman615eb472017-10-15 14:32:27 +0000800#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Galina Kistanova98d4bd52017-05-17 02:20:05 +0000801LLVM_DUMP_METHOD void MatchableInfo::dump() const {
Chris Lattner9f093812010-11-06 06:43:11 +0000802 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +0000803
Craig Topperad895412018-01-06 19:20:32 +0000804 errs() << " variant: " << AsmVariantID << "\n";
805
Chris Lattnerd64b7c02010-11-02 01:03:43 +0000806 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
Craig Topper42bd8192014-11-28 03:53:00 +0000807 const AsmOperand &Op = AsmOperands[i];
Daniel Dunbarc32aa062009-08-09 05:18:30 +0000808 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Chris Lattner4779e3e92010-11-04 00:57:06 +0000809 errs() << '\"' << Op.Token << "\"\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +0000810 }
811}
Galina Kistanova98d4bd52017-05-17 02:20:05 +0000812#endif
Daniel Dunbare10787e2009-08-07 08:26:05 +0000813
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000814static std::pair<StringRef, StringRef>
Jakob Stoklund Olesend7b66962012-08-22 23:33:58 +0000815parseTwoOperandConstraint(StringRef S, ArrayRef<SMLoc> Loc) {
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000816 // Split via the '='.
817 std::pair<StringRef, StringRef> Ops = S.split('=');
818 if (Ops.second == "")
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000819 PrintFatalError(Loc, "missing '=' in two-operand alias constraint");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000820 // Trim whitespace and the leading '$' on the operand names.
821 size_t start = Ops.first.find_first_of('$');
822 if (start == std::string::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000823 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000824 Ops.first = Ops.first.slice(start + 1, std::string::npos);
825 size_t end = Ops.first.find_last_of(" \t");
826 Ops.first = Ops.first.slice(0, end);
827 // Now the second operand.
828 start = Ops.second.find_first_of('$');
829 if (start == std::string::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000830 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000831 Ops.second = Ops.second.slice(start + 1, std::string::npos);
832 end = Ops.second.find_last_of(" \t");
833 Ops.first = Ops.first.slice(0, end);
834 return Ops;
835}
836
837void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
838 // Figure out which operands are aliased and mark them as tied.
839 std::pair<StringRef, StringRef> Ops =
840 parseTwoOperandConstraint(Constraint, TheDef->getLoc());
841
842 // Find the AsmOperands that refer to the operands we're aliasing.
843 int SrcAsmOperand = findAsmOperandNamed(Ops.first);
844 int DstAsmOperand = findAsmOperandNamed(Ops.second);
845 if (SrcAsmOperand == -1)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000846 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +0000847 "unknown source two-operand alias operand '" + Ops.first +
848 "'.");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000849 if (DstAsmOperand == -1)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000850 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +0000851 "unknown destination two-operand alias operand '" +
852 Ops.second + "'.");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000853
854 // Find the ResOperand that refers to the operand we're aliasing away
855 // and update it to refer to the combined operand instead.
Craig Toppere4e74152015-12-29 07:03:23 +0000856 for (ResOperand &Op : ResOperands) {
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000857 if (Op.Kind == ResOperand::RenderAsmOperand &&
858 Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
859 Op.AsmOperandNum = DstAsmOperand;
860 break;
861 }
862 }
863 // Remove the AsmOperand for the alias operand.
864 AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
865 // Adjust the ResOperand references to any AsmOperands that followed
866 // the one we just deleted.
Craig Toppere4e74152015-12-29 07:03:23 +0000867 for (ResOperand &Op : ResOperands) {
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000868 switch(Op.Kind) {
869 default:
870 // Nothing to do for operands that don't reference AsmOperands.
871 break;
872 case ResOperand::RenderAsmOperand:
873 if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
874 --Op.AsmOperandNum;
875 break;
Jim Grosbach31c2d3f2012-04-19 23:59:23 +0000876 }
877 }
878}
879
Craig Topper22fa45f2015-09-13 18:01:25 +0000880/// extractSingletonRegisterForAsmOperand - Extract singleton register,
881/// if present, from specified token.
882static void
883extractSingletonRegisterForAsmOperand(MatchableInfo::AsmOperand &Op,
884 const AsmMatcherInfo &Info,
885 StringRef RegisterPrefix) {
886 StringRef Tok = Op.Token;
887
888 // If this token is not an isolated token, i.e., it isn't separated from
889 // other tokens (e.g. with whitespace), don't interpret it as a register name.
890 if (!Op.IsIsolatedToken)
891 return;
892
893 if (RegisterPrefix.empty()) {
894 std::string LoweredTok = Tok.lower();
895 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
896 Op.SingletonReg = Reg->TheDef;
897 return;
898 }
899
900 if (!Tok.startswith(RegisterPrefix))
901 return;
902
903 StringRef RegName = Tok.substr(RegisterPrefix.size());
904 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
905 Op.SingletonReg = Reg->TheDef;
906
907 // If there is no register prefix (i.e. "%" in "%eax"), then this may
908 // be some random non-register token, just ignore it.
Craig Topper22fa45f2015-09-13 18:01:25 +0000909}
910
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000911void MatchableInfo::initialize(const AsmMatcherInfo &Info,
Craig Topper71b7b682014-08-21 05:55:13 +0000912 SmallPtrSetImpl<Record*> &SingletonRegisters,
Craig Topperfd2c6a32015-12-31 08:18:23 +0000913 AsmVariantInfo const &Variant,
914 bool HasMnemonicFirst) {
Craig Topperc8b5b252015-12-30 06:00:18 +0000915 AsmVariantID = Variant.AsmVariantNo;
Jim Grosbach0bba00d2012-01-24 21:06:59 +0000916 AsmString =
Craig Topperc8b5b252015-12-30 06:00:18 +0000917 CodeGenInstruction::FlattenAsmStringVariants(AsmString,
918 Variant.AsmVariantNo);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000919
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000920 tokenizeAsmString(Info, Variant);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000921
Craig Topperfd2c6a32015-12-31 08:18:23 +0000922 // The first token of the instruction is the mnemonic, which must be a
923 // simple string, not a $foo variable or a singleton register.
924 if (AsmOperands.empty())
925 PrintFatalError(TheDef->getLoc(),
926 "Instruction '" + TheDef->getName() + "' has no tokens");
927
928 assert(!AsmOperands[0].Token.empty());
929 if (HasMnemonicFirst) {
930 Mnemonic = AsmOperands[0].Token;
931 if (Mnemonic[0] == '$')
932 PrintFatalError(TheDef->getLoc(),
933 "Invalid instruction mnemonic '" + Mnemonic + "'!");
934
935 // Remove the first operand, it is tracked in the mnemonic field.
936 AsmOperands.erase(AsmOperands.begin());
937 } else if (AsmOperands[0].Token[0] != '$')
938 Mnemonic = AsmOperands[0].Token;
939
Chris Lattnerba465f92010-11-01 04:53:48 +0000940 // Compute the require features.
Craig Topper22fa45f2015-09-13 18:01:25 +0000941 for (Record *Predicate : TheDef->getValueAsListOfDefs("Predicates"))
David Blaikie9a9da992014-11-28 22:15:06 +0000942 if (const SubtargetFeatureInfo *Feature =
Craig Topper22fa45f2015-09-13 18:01:25 +0000943 Info.getSubtargetFeature(Predicate))
Chris Lattnerba465f92010-11-01 04:53:48 +0000944 RequiredFeatures.push_back(Feature);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +0000945
Chris Lattnerba465f92010-11-01 04:53:48 +0000946 // Collect singleton registers, if used.
Craig Topper22fa45f2015-09-13 18:01:25 +0000947 for (MatchableInfo::AsmOperand &Op : AsmOperands) {
Craig Topperc8b5b252015-12-30 06:00:18 +0000948 extractSingletonRegisterForAsmOperand(Op, Info, Variant.RegisterPrefix);
Craig Topper22fa45f2015-09-13 18:01:25 +0000949 if (Record *Reg = Op.SingletonReg)
Chris Lattnerba465f92010-11-01 04:53:48 +0000950 SingletonRegisters.insert(Reg);
951 }
Joey Gouly0e76fa72013-09-12 10:28:05 +0000952
953 const RecordVal *DepMask = TheDef->getValue("DeprecatedFeatureMask");
954 if (!DepMask)
955 DepMask = TheDef->getValue("ComplexDeprecationPredicate");
956
957 HasDeprecation =
958 DepMask ? !DepMask->getValue()->getAsUnquotedString().empty() : false;
Chris Lattnerba465f92010-11-01 04:53:48 +0000959}
960
Ahmed Bougachad8dc2ac2015-05-29 00:55:55 +0000961/// Append an AsmOperand for the given substring of AsmString.
Craig Topperbc22e262015-12-31 05:01:45 +0000962void MatchableInfo::addAsmOperand(StringRef Token, bool IsIsolatedToken) {
963 AsmOperands.push_back(AsmOperand(IsIsolatedToken, Token));
Ahmed Bougachad8dc2ac2015-05-29 00:55:55 +0000964}
965
Jim Grosbach8c2beaa2012-04-19 17:52:32 +0000966/// tokenizeAsmString - Tokenize a simplified assembly string.
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000967void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info,
968 AsmVariantInfo const &Variant) {
Chris Lattner28ea9b12010-11-02 17:30:52 +0000969 StringRef String = AsmString;
Craig Topperba614322015-12-30 06:00:15 +0000970 size_t Prev = 0;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000971 bool InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +0000972 bool IsIsolatedToken = true;
Craig Topperba614322015-12-30 06:00:15 +0000973 for (size_t i = 0, e = String.size(); i != e; ++i) {
Craig Topperbc22e262015-12-31 05:01:45 +0000974 char Char = String[i];
975 if (Variant.BreakCharacters.find(Char) != std::string::npos) {
976 if (InTok) {
977 addAsmOperand(String.slice(Prev, i), false);
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000978 Prev = i;
Craig Topperbc22e262015-12-31 05:01:45 +0000979 IsIsolatedToken = false;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000980 }
981 InTok = true;
982 continue;
983 }
Craig Topperbc22e262015-12-31 05:01:45 +0000984 if (Variant.TokenizingCharacters.find(Char) != std::string::npos) {
985 if (InTok) {
986 addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000987 InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +0000988 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +0000989 }
Craig Topperbc22e262015-12-31 05:01:45 +0000990 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +0000991 Prev = i + 1;
Craig Topperbc22e262015-12-31 05:01:45 +0000992 IsIsolatedToken = true;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000993 continue;
994 }
Craig Topperbc22e262015-12-31 05:01:45 +0000995 if (Variant.SeparatorCharacters.find(Char) != std::string::npos) {
996 if (InTok) {
997 addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
Colin LeMahieu8a0453e2015-11-09 00:31:07 +0000998 InTok = false;
999 }
1000 Prev = i + 1;
Craig Topperbc22e262015-12-31 05:01:45 +00001001 IsIsolatedToken = true;
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001002 continue;
1003 }
Craig Topperbc22e262015-12-31 05:01:45 +00001004
1005 switch (Char) {
Chris Lattner28ea9b12010-11-02 17:30:52 +00001006 case '\\':
1007 if (InTok) {
Craig Topperbc22e262015-12-31 05:01:45 +00001008 addAsmOperand(String.slice(Prev, i), false);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001009 InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +00001010 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001011 }
1012 ++i;
1013 assert(i != String.size() && "Invalid quoted character");
Craig Topperbc22e262015-12-31 05:01:45 +00001014 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001015 Prev = i + 1;
Craig Topperbc22e262015-12-31 05:01:45 +00001016 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001017 break;
1018
1019 case '$': {
Craig Topperbc22e262015-12-31 05:01:45 +00001020 if (InTok) {
1021 addAsmOperand(String.slice(Prev, i), false);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001022 InTok = false;
Craig Topperbc22e262015-12-31 05:01:45 +00001023 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001024 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001025
Colin LeMahieu3d905742015-08-10 19:58:06 +00001026 // If this isn't "${", start new identifier looking like "$xxx"
Chris Lattnerd6746d52010-11-06 22:06:03 +00001027 if (i + 1 == String.size() || String[i + 1] != '{') {
1028 Prev = i;
1029 break;
1030 }
Chris Lattner28ea9b12010-11-02 17:30:52 +00001031
Craig Topperba614322015-12-30 06:00:15 +00001032 size_t EndPos = String.find('}', i);
1033 assert(EndPos != StringRef::npos &&
1034 "Missing brace in operand reference!");
Craig Topperbc22e262015-12-31 05:01:45 +00001035 addAsmOperand(String.slice(i, EndPos+1), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001036 Prev = EndPos + 1;
1037 i = EndPos;
Craig Topperbc22e262015-12-31 05:01:45 +00001038 IsIsolatedToken = false;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001039 break;
1040 }
Craig Topperbc22e262015-12-31 05:01:45 +00001041
Chris Lattner28ea9b12010-11-02 17:30:52 +00001042 default:
1043 InTok = true;
Craig Topperbc22e262015-12-31 05:01:45 +00001044 break;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001045 }
1046 }
1047 if (InTok && Prev != String.size())
Craig Topperbc22e262015-12-31 05:01:45 +00001048 addAsmOperand(String.substr(Prev), IsIsolatedToken);
Chris Lattner28ea9b12010-11-02 17:30:52 +00001049}
1050
Sander de Smalen5b691a12018-02-04 16:24:17 +00001051bool MatchableInfo::validate(StringRef CommentDelimiter, bool IsAlias) const {
Chris Lattnerad776812010-11-01 05:06:45 +00001052 // Reject matchables with no .s string.
Chris Lattner39bc53b2010-11-01 04:34:44 +00001053 if (AsmString.empty())
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001054 PrintFatalError(TheDef->getLoc(), "instruction with empty asm string");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001055
Chris Lattnerad776812010-11-01 05:06:45 +00001056 // Reject any matchables with a newline in them, they should be marked
Chris Lattner39bc53b2010-11-01 04:34:44 +00001057 // isCodeGenOnly if they are pseudo instructions.
1058 if (AsmString.find('\n') != std::string::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001059 PrintFatalError(TheDef->getLoc(),
Chris Lattner39bc53b2010-11-01 04:34:44 +00001060 "multiline instruction is not valid for the asmparser, "
1061 "mark it isCodeGenOnly");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001062
Chris Lattner178f4bb2010-11-01 04:44:29 +00001063 // Remove comments from the asm string. We know that the asmstring only
1064 // has one line.
1065 if (!CommentDelimiter.empty() &&
1066 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001067 PrintFatalError(TheDef->getLoc(),
Chris Lattner178f4bb2010-11-01 04:44:29 +00001068 "asmstring for instruction has comment character in it, "
1069 "mark it isCodeGenOnly");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001070
Chris Lattnerad776812010-11-01 05:06:45 +00001071 // Reject matchables with operand modifiers, these aren't something we can
Bob Wilson266d2ba2011-01-20 18:38:07 +00001072 // handle, the target should be refactored to use operands instead of
1073 // modifiers.
Chris Lattner39bc53b2010-11-01 04:34:44 +00001074 //
Sjoerd Meijerbb4839d2019-05-30 07:38:09 +00001075 // Also, check for instructions which reference the operand multiple times,
1076 // if they don't define a custom AsmMatcher: this implies a constraint that
1077 // the built-in matching code would not honor.
Chris Lattner39bc53b2010-11-01 04:34:44 +00001078 std::set<std::string> OperandNames;
Craig Topper77bd2b72015-12-30 06:00:20 +00001079 for (const AsmOperand &Op : AsmOperands) {
1080 StringRef Tok = Op.Token;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001081 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001082 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001083 "matchable with operand modifier '" + Tok +
1084 "' not supported by asm matcher. Mark isCodeGenOnly!");
Chris Lattnerad776812010-11-01 05:06:45 +00001085 // Verify that any operand is only mentioned once.
Chris Lattner4d23eb22010-11-02 23:18:43 +00001086 // We reject aliases and ignore instructions for now.
Sjoerd Meijerbb4839d2019-05-30 07:38:09 +00001087 if (!IsAlias && TheDef->getValueAsString("AsmMatchConverter").empty() &&
1088 Tok[0] == '$' && !OperandNames.insert(Tok).second) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001089 LLVM_DEBUG({
Chris Lattner9f093812010-11-06 06:43:11 +00001090 errs() << "warning: '" << TheDef->getName() << "': "
Chris Lattnerad776812010-11-01 05:06:45 +00001091 << "ignoring instruction with tied operand '"
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001092 << Tok << "'\n";
Chris Lattner39bc53b2010-11-01 04:34:44 +00001093 });
1094 return false;
1095 }
1096 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001097
Chris Lattner39bc53b2010-11-01 04:34:44 +00001098 return true;
1099}
1100
Chris Lattner60db0a62010-02-09 00:34:28 +00001101static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001102 std::string Res;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001103
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001104 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
1105 switch (*it) {
1106 case '*': Res += "_STAR_"; break;
1107 case '%': Res += "_PCT_"; break;
1108 case ':': Res += "_COLON_"; break;
Bill Wendling4a08e562010-11-18 23:36:54 +00001109 case '!': Res += "_EXCLAIM_"; break;
Bill Wendlinga01ea892011-01-22 09:44:32 +00001110 case '.': Res += "_DOT_"; break;
Tim Northoverb3cfb282013-01-10 16:47:31 +00001111 case '<': Res += "_LT_"; break;
1112 case '>': Res += "_GT_"; break;
Hal Finkelf9090722015-01-15 01:33:00 +00001113 case '-': Res += "_MINUS_"; break;
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001114 default:
Tim Northoverb3cfb282013-01-10 16:47:31 +00001115 if ((*it >= 'A' && *it <= 'Z') ||
1116 (*it >= 'a' && *it <= 'z') ||
1117 (*it >= '0' && *it <= '9'))
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001118 Res += *it;
Chris Lattner33fc3e02010-10-31 19:10:56 +00001119 else
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001120 Res += "_" + utostr((unsigned) *it) + "_";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001121 }
1122 }
1123
1124 return Res;
1125}
1126
Chris Lattner60db0a62010-02-09 00:34:28 +00001127ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001128 ClassInfo *&Entry = TokenClasses[Token];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001129
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001130 if (!Entry) {
David Blaikied749e342014-11-28 20:35:57 +00001131 Classes.emplace_front();
1132 Entry = &Classes.front();
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001133 Entry->Kind = ClassInfo::Token;
Daniel Dunbarc32aa062009-08-09 05:18:30 +00001134 Entry->ClassName = "Token";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001135 Entry->Name = "MCK_" + getEnumNameForToken(Token);
1136 Entry->ValueName = Token;
1137 Entry->PredicateMethod = "<invalid>";
1138 Entry->RenderMethod = "<invalid>";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001139 Entry->ParserMethod = "";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001140 Entry->DiagnosticType = "";
Tom Stellardb9f235e2016-02-05 19:59:33 +00001141 Entry->IsOptional = false;
Sam Kolton5f10a132016-05-06 11:31:17 +00001142 Entry->DefaultMethod = "<invalid>";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001143 }
1144
1145 return Entry;
1146}
1147
1148ClassInfo *
Bob Wilsonb9b24222011-01-26 19:44:55 +00001149AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
1150 int SubOpIdx) {
1151 Record *Rec = OI.Rec;
1152 if (SubOpIdx != -1)
Sean Silva88eb8dd2012-10-10 20:24:47 +00001153 Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001154 return getOperandClass(Rec, SubOpIdx);
1155}
Bob Wilsonb9b24222011-01-26 19:44:55 +00001156
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001157ClassInfo *
1158AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001159 if (Rec->isSubClassOf("RegisterOperand")) {
1160 // RegisterOperand may have an associated ParserMatchClass. If it does,
1161 // use it, else just fall back to the underlying register class.
1162 const RecordVal *R = Rec->getValue("ParserMatchClass");
Craig Topper24064772014-04-15 07:20:03 +00001163 if (!R || !R->getValue())
Daniel Sandersdff673b2019-02-12 17:36:57 +00001164 PrintFatalError(Rec->getLoc(),
1165 "Record `" + Rec->getName() +
1166 "' does not have a ParserMatchClass!\n");
Owen Andersona84be6c2011-06-27 21:06:21 +00001167
Sean Silvafb509ed2012-10-10 20:24:43 +00001168 if (DefInit *DI= dyn_cast<DefInit>(R->getValue())) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001169 Record *MatchClass = DI->getDef();
1170 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1171 return CI;
1172 }
1173
1174 // No custom match class. Just use the register class.
1175 Record *ClassRec = Rec->getValueAsDef("RegClass");
1176 if (!ClassRec)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001177 PrintFatalError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
Owen Andersona84be6c2011-06-27 21:06:21 +00001178 "' has no associated register class!\n");
1179 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
1180 return CI;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001181 PrintFatalError(Rec->getLoc(), "register class has no class info!");
Owen Andersona84be6c2011-06-27 21:06:21 +00001182 }
1183
Bob Wilsonb9b24222011-01-26 19:44:55 +00001184 if (Rec->isSubClassOf("RegisterClass")) {
1185 if (ClassInfo *CI = RegisterClassClasses[Rec])
Chris Lattner77d3ead2010-11-02 18:10:06 +00001186 return CI;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001187 PrintFatalError(Rec->getLoc(), "register class has no class info!");
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001188 }
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001189
Jim Grosbachf6cb1ee2012-09-12 17:40:25 +00001190 if (!Rec->isSubClassOf("Operand"))
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001191 PrintFatalError(Rec->getLoc(), "Operand `" + Rec->getName() +
Jim Grosbachf6cb1ee2012-09-12 17:40:25 +00001192 "' does not derive from class Operand!\n");
Bob Wilsonb9b24222011-01-26 19:44:55 +00001193 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
Chris Lattner77d3ead2010-11-02 18:10:06 +00001194 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1195 return CI;
Daniel Dunbar17410a42009-08-10 18:41:10 +00001196
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001197 PrintFatalError(Rec->getLoc(), "operand has no match class!");
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001198}
1199
Tim Northoverc74e6912013-09-16 16:43:19 +00001200struct LessRegisterSet {
Tim Northover9c30f7a2013-09-16 17:33:40 +00001201 bool operator() (const RegisterSet &LHS, const RegisterSet & RHS) const {
Tim Northoverc74e6912013-09-16 16:43:19 +00001202 // std::set<T> defines its own compariso "operator<", but it
1203 // performs a lexicographical comparison by T's innate comparison
1204 // for some reason. We don't want non-deterministic pointer
1205 // comparisons so use this instead.
1206 return std::lexicographical_compare(LHS.begin(), LHS.end(),
1207 RHS.begin(), RHS.end(),
1208 LessRecordByID());
1209 }
1210};
1211
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001212void AsmMatcherInfo::
Craig Topper71b7b682014-08-21 05:55:13 +00001213buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters) {
David Blaikie9b613db2014-11-29 18:13:39 +00001214 const auto &Registers = Target.getRegBank().getRegisters();
David Blaikiec0bb5ca2014-12-03 19:58:41 +00001215 auto &RegClassList = Target.getRegBank().getRegClasses();
Daniel Dunbar17410a42009-08-10 18:41:10 +00001216
Tim Northoverc74e6912013-09-16 16:43:19 +00001217 typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet;
1218
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001219 // The register sets used for matching.
Tim Northoverc74e6912013-09-16 16:43:19 +00001220 RegisterSetSet RegisterSets;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001221
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001222 // Gather the defined sets.
David Blaikiedacea4b2014-12-03 19:58:45 +00001223 for (const CodeGenRegisterClass &RC : RegClassList)
1224 RegisterSets.insert(
1225 RegisterSet(RC.getOrder().begin(), RC.getOrder().end()));
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001226
1227 // Add any required singleton sets.
Craig Topper03ec8012014-11-25 20:11:31 +00001228 for (Record *Rec : SingletonRegisters) {
Tim Northoverc74e6912013-09-16 16:43:19 +00001229 RegisterSets.insert(RegisterSet(&Rec, &Rec + 1));
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001230 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001231
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001232 // Introduce derived sets where necessary (when a register does not determine
1233 // a unique register set class), and build the mapping of registers to the set
1234 // they should classify to.
Tim Northoverc74e6912013-09-16 16:43:19 +00001235 std::map<Record*, RegisterSet> RegisterMap;
David Blaikie9b613db2014-11-29 18:13:39 +00001236 for (const CodeGenRegister &CGR : Registers) {
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001237 // Compute the intersection of all sets containing this register.
Tim Northoverc74e6912013-09-16 16:43:19 +00001238 RegisterSet ContainingSet;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001239
Craig Topper03ec8012014-11-25 20:11:31 +00001240 for (const RegisterSet &RS : RegisterSets) {
David Blaikie9b613db2014-11-29 18:13:39 +00001241 if (!RS.count(CGR.TheDef))
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001242 continue;
1243
1244 if (ContainingSet.empty()) {
Craig Topper03ec8012014-11-25 20:11:31 +00001245 ContainingSet = RS;
Chris Lattner77d3ead2010-11-02 18:10:06 +00001246 continue;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001247 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001248
Tim Northoverc74e6912013-09-16 16:43:19 +00001249 RegisterSet Tmp;
Chris Lattner77d3ead2010-11-02 18:10:06 +00001250 std::swap(Tmp, ContainingSet);
Tim Northoverc74e6912013-09-16 16:43:19 +00001251 std::insert_iterator<RegisterSet> II(ContainingSet,
1252 ContainingSet.begin());
Craig Topper03ec8012014-11-25 20:11:31 +00001253 std::set_intersection(Tmp.begin(), Tmp.end(), RS.begin(), RS.end(), II,
Tim Northoverc74e6912013-09-16 16:43:19 +00001254 LessRecordByID());
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001255 }
1256
1257 if (!ContainingSet.empty()) {
1258 RegisterSets.insert(ContainingSet);
David Blaikie9b613db2014-11-29 18:13:39 +00001259 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001260 }
1261 }
1262
1263 // Construct the register classes.
Tim Northoverc74e6912013-09-16 16:43:19 +00001264 std::map<RegisterSet, ClassInfo*, LessRegisterSet> RegisterSetClasses;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001265 unsigned Index = 0;
Craig Topper03ec8012014-11-25 20:11:31 +00001266 for (const RegisterSet &RS : RegisterSets) {
David Blaikied749e342014-11-28 20:35:57 +00001267 Classes.emplace_front();
1268 ClassInfo *CI = &Classes.front();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001269 CI->Kind = ClassInfo::RegisterClass0 + Index;
1270 CI->ClassName = "Reg" + utostr(Index);
1271 CI->Name = "MCK_Reg" + utostr(Index);
1272 CI->ValueName = "";
1273 CI->PredicateMethod = ""; // unused
1274 CI->RenderMethod = "addRegOperands";
Craig Topper03ec8012014-11-25 20:11:31 +00001275 CI->Registers = RS;
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001276 // FIXME: diagnostic type.
1277 CI->DiagnosticType = "";
Tom Stellardb9f235e2016-02-05 19:59:33 +00001278 CI->IsOptional = false;
Sam Kolton5f10a132016-05-06 11:31:17 +00001279 CI->DefaultMethod = ""; // unused
Craig Topper03ec8012014-11-25 20:11:31 +00001280 RegisterSetClasses.insert(std::make_pair(RS, CI));
1281 ++Index;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001282 }
1283
1284 // Find the superclasses; we could compute only the subgroup lattice edges,
1285 // but there isn't really a point.
Craig Topper03ec8012014-11-25 20:11:31 +00001286 for (const RegisterSet &RS : RegisterSets) {
1287 ClassInfo *CI = RegisterSetClasses[RS];
1288 for (const RegisterSet &RS2 : RegisterSets)
1289 if (RS != RS2 &&
1290 std::includes(RS2.begin(), RS2.end(), RS.begin(), RS.end(),
Tim Northoverc74e6912013-09-16 16:43:19 +00001291 LessRecordByID()))
Craig Topper03ec8012014-11-25 20:11:31 +00001292 CI->SuperClasses.push_back(RegisterSetClasses[RS2]);
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001293 }
1294
1295 // Name the register classes which correspond to a user defined RegisterClass.
David Blaikiedacea4b2014-12-03 19:58:45 +00001296 for (const CodeGenRegisterClass &RC : RegClassList) {
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001297 // Def will be NULL for non-user defined register classes.
David Blaikiedacea4b2014-12-03 19:58:45 +00001298 Record *Def = RC.getDef();
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001299 if (!Def)
1300 continue;
David Blaikiedacea4b2014-12-03 19:58:45 +00001301 ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(),
1302 RC.getOrder().end())];
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001303 if (CI->ValueName.empty()) {
David Blaikiedacea4b2014-12-03 19:58:45 +00001304 CI->ClassName = RC.getName();
1305 CI->Name = "MCK_" + RC.getName();
1306 CI->ValueName = RC.getName();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001307 } else
David Blaikiedacea4b2014-12-03 19:58:45 +00001308 CI->ValueName = CI->ValueName + "," + RC.getName();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001309
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00001310 Init *DiagnosticType = Def->getValueInit("DiagnosticType");
1311 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
1312 CI->DiagnosticType = SI->getValue();
1313
1314 Init *DiagnosticString = Def->getValueInit("DiagnosticString");
1315 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticString))
1316 CI->DiagnosticString = SI->getValue();
1317
1318 // If we have a diagnostic string but the diagnostic type is not specified
1319 // explicitly, create an anonymous diagnostic type.
1320 if (!CI->DiagnosticString.empty() && CI->DiagnosticType.empty())
1321 CI->DiagnosticType = RC.getName();
1322
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001323 RegisterClassClasses.insert(std::make_pair(Def, CI));
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001324 }
1325
1326 // Populate the map for individual registers.
Tim Northoverc74e6912013-09-16 16:43:19 +00001327 for (std::map<Record*, RegisterSet>::iterator it = RegisterMap.begin(),
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001328 ie = RegisterMap.end(); it != ie; ++it)
Chris Lattner77d3ead2010-11-02 18:10:06 +00001329 RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001330
1331 // Name the register classes which correspond to singleton registers.
Craig Topper03ec8012014-11-25 20:11:31 +00001332 for (Record *Rec : SingletonRegisters) {
Chris Lattner77d3ead2010-11-02 18:10:06 +00001333 ClassInfo *CI = RegisterClasses[Rec];
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001334 assert(CI && "Missing singleton register class info!");
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001335
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001336 if (CI->ValueName.empty()) {
1337 CI->ClassName = Rec->getName();
Matthias Braun4a86d452016-12-04 05:48:16 +00001338 CI->Name = "MCK_" + Rec->getName().str();
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001339 CI->ValueName = Rec->getName();
1340 } else
Matthias Braun4a86d452016-12-04 05:48:16 +00001341 CI->ValueName = CI->ValueName + "," + Rec->getName().str();
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001342 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001343}
1344
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001345void AsmMatcherInfo::buildOperandClasses() {
Chris Lattnere3c48de2010-11-01 23:57:23 +00001346 std::vector<Record*> AsmOperands =
1347 Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbarcf181532010-01-30 01:02:37 +00001348
1349 // Pre-populate AsmOperandClasses map.
David Blaikied749e342014-11-28 20:35:57 +00001350 for (Record *Rec : AsmOperands) {
1351 Classes.emplace_front();
1352 AsmOperandClasses[Rec] = &Classes.front();
1353 }
Daniel Dunbarcf181532010-01-30 01:02:37 +00001354
Daniel Dunbar17410a42009-08-10 18:41:10 +00001355 unsigned Index = 0;
Craig Topper03ec8012014-11-25 20:11:31 +00001356 for (Record *Rec : AsmOperands) {
1357 ClassInfo *CI = AsmOperandClasses[Rec];
Daniel Dunbar17410a42009-08-10 18:41:10 +00001358 CI->Kind = ClassInfo::UserClass0 + Index;
1359
Craig Topper03ec8012014-11-25 20:11:31 +00001360 ListInit *Supers = Rec->getValueAsListInit("SuperClasses");
Craig Topperef0578a2015-06-02 04:15:51 +00001361 for (Init *I : Supers->getValues()) {
1362 DefInit *DI = dyn_cast<DefInit>(I);
Daniel Dunbar346782c2010-05-22 21:02:29 +00001363 if (!DI) {
Craig Topper03ec8012014-11-25 20:11:31 +00001364 PrintError(Rec->getLoc(), "Invalid super class reference!");
Daniel Dunbar346782c2010-05-22 21:02:29 +00001365 continue;
1366 }
1367
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001368 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1369 if (!SC)
Craig Topper03ec8012014-11-25 20:11:31 +00001370 PrintError(Rec->getLoc(), "Invalid super class reference!");
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001371 else
1372 CI->SuperClasses.push_back(SC);
Daniel Dunbar17410a42009-08-10 18:41:10 +00001373 }
Craig Topper03ec8012014-11-25 20:11:31 +00001374 CI->ClassName = Rec->getValueAsString("Name");
Daniel Dunbar17410a42009-08-10 18:41:10 +00001375 CI->Name = "MCK_" + CI->ClassName;
Craig Topper03ec8012014-11-25 20:11:31 +00001376 CI->ValueName = Rec->getName();
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001377
1378 // Get or construct the predicate method name.
Craig Topper03ec8012014-11-25 20:11:31 +00001379 Init *PMName = Rec->getValueInit("PredicateMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001380 if (StringInit *SI = dyn_cast<StringInit>(PMName)) {
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001381 CI->PredicateMethod = SI->getValue();
1382 } else {
Sean Silva88eb8dd2012-10-10 20:24:47 +00001383 assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!");
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001384 CI->PredicateMethod = "is" + CI->ClassName;
1385 }
1386
1387 // Get or construct the render method name.
Craig Topper03ec8012014-11-25 20:11:31 +00001388 Init *RMName = Rec->getValueInit("RenderMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001389 if (StringInit *SI = dyn_cast<StringInit>(RMName)) {
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001390 CI->RenderMethod = SI->getValue();
1391 } else {
Sean Silva88eb8dd2012-10-10 20:24:47 +00001392 assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!");
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001393 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1394 }
1395
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001396 // Get the parse method name or leave it as empty.
Craig Topper03ec8012014-11-25 20:11:31 +00001397 Init *PRMName = Rec->getValueInit("ParserMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001398 if (StringInit *SI = dyn_cast<StringInit>(PRMName))
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001399 CI->ParserMethod = SI->getValue();
1400
Oliver Stannard41dfac32017-10-03 14:34:57 +00001401 // Get the diagnostic type and string or leave them as empty.
Craig Topper03ec8012014-11-25 20:11:31 +00001402 Init *DiagnosticType = Rec->getValueInit("DiagnosticType");
Sean Silvafb509ed2012-10-10 20:24:43 +00001403 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001404 CI->DiagnosticType = SI->getValue();
Oliver Stannard41dfac32017-10-03 14:34:57 +00001405 Init *DiagnosticString = Rec->getValueInit("DiagnosticString");
1406 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticString))
1407 CI->DiagnosticString = SI->getValue();
1408 // If we have a DiagnosticString, we need a DiagnosticType for use within
1409 // the matcher.
1410 if (!CI->DiagnosticString.empty() && CI->DiagnosticType.empty())
1411 CI->DiagnosticType = CI->ClassName;
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001412
Tom Stellardb9f235e2016-02-05 19:59:33 +00001413 Init *IsOptional = Rec->getValueInit("IsOptional");
1414 if (BitInit *BI = dyn_cast<BitInit>(IsOptional))
1415 CI->IsOptional = BI->getValue();
1416
Sam Kolton5f10a132016-05-06 11:31:17 +00001417 // Get or construct the default method name.
1418 Init *DMName = Rec->getValueInit("DefaultMethod");
1419 if (StringInit *SI = dyn_cast<StringInit>(DMName)) {
1420 CI->DefaultMethod = SI->getValue();
1421 } else {
1422 assert(isa<UnsetInit>(DMName) && "Unexpected DefaultMethod field!");
1423 CI->DefaultMethod = "default" + CI->ClassName + "Operands";
1424 }
1425
Craig Topper03ec8012014-11-25 20:11:31 +00001426 ++Index;
Daniel Dunbar17410a42009-08-10 18:41:10 +00001427 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001428}
1429
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001430AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1431 CodeGenTarget &target,
Chris Lattner89dcb682010-12-15 04:48:22 +00001432 RecordKeeper &records)
Devang Patel6d676e42012-01-07 01:33:34 +00001433 : Records(records), AsmParser(asmParser), Target(target) {
Daniel Dunbare4318712009-08-11 20:59:47 +00001434}
1435
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001436/// buildOperandMatchInfo - Build the necessary information to handle user
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001437/// defined operand parsing methods.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001438void AsmMatcherInfo::buildOperandMatchInfo() {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001439
Jim Grosbach925a6d02012-04-18 23:46:25 +00001440 /// Map containing a mask with all operands indices that can be found for
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001441 /// that class inside a instruction.
Benjamin Kramercd2bae32019-08-22 17:32:16 +00001442 typedef std::map<ClassInfo *, unsigned, deref<std::less<>>> OpClassMaskTy;
Sean Silva835139b2012-09-19 01:47:03 +00001443 OpClassMaskTy OpClassMask;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001444
Craig Topperf34dad92014-11-28 03:53:02 +00001445 for (const auto &MI : Matchables) {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001446 OpClassMask.clear();
1447
1448 // Keep track of all operands of this instructions which belong to the
1449 // same class.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001450 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
1451 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001452 if (Op.Class->ParserMethod.empty())
1453 continue;
1454 unsigned &OperandMask = OpClassMask[Op.Class];
1455 OperandMask |= (1 << i);
1456 }
1457
1458 // Generate operand match info for each mnemonic/operand class pair.
Craig Topper42bd8192014-11-28 03:53:00 +00001459 for (const auto &OCM : OpClassMask) {
1460 unsigned OpMask = OCM.second;
1461 ClassInfo *CI = OCM.first;
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001462 OperandMatchInfo.push_back(OperandMatchEntry::create(MI.get(), CI,
1463 OpMask));
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001464 }
1465 }
1466}
1467
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001468void AsmMatcherInfo::buildInfo() {
Chris Lattnera0e87192010-10-30 20:07:57 +00001469 // Build information about all of the AssemblerPredicates.
Daniel Sandersea6ef3d2016-11-15 09:51:02 +00001470 const std::vector<std::pair<Record *, SubtargetFeatureInfo>>
1471 &SubtargetFeaturePairs = SubtargetFeatureInfo::getAll(Records);
1472 SubtargetFeatures.insert(SubtargetFeaturePairs.begin(),
1473 SubtargetFeaturePairs.end());
Daniel Sandersa3e11252016-11-15 10:13:09 +00001474#ifndef NDEBUG
Daniel Sandersea6ef3d2016-11-15 09:51:02 +00001475 for (const auto &Pair : SubtargetFeatures)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001476 LLVM_DEBUG(Pair.second.dump());
Daniel Sandersa3e11252016-11-15 10:13:09 +00001477#endif // NDEBUG
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001478
Craig Topperfd2c6a32015-12-31 08:18:23 +00001479 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
Sander de Smalen5b691a12018-02-04 16:24:17 +00001480 bool ReportMultipleNearMisses =
1481 AsmParser->getValueAsBit("ReportMultipleNearMisses");
Craig Topperfd2c6a32015-12-31 08:18:23 +00001482
Chris Lattner33fc3e02010-10-31 19:10:56 +00001483 // Parse the instructions; we need to do this first so that we can gather the
1484 // singleton register classes.
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001485 SmallPtrSet<Record*, 16> SingletonRegisters;
Devang Patel85d684a2012-01-09 19:13:28 +00001486 unsigned VariantCount = Target.getAsmParserVariantCount();
1487 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1488 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topperbcd3c372017-05-31 21:12:46 +00001489 StringRef CommentDelimiter =
1490 AsmVariant->getValueAsString("CommentDelimiter");
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001491 AsmVariantInfo Variant;
Craig Topperc8b5b252015-12-30 06:00:18 +00001492 Variant.RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001493 Variant.TokenizingCharacters =
1494 AsmVariant->getValueAsString("TokenizingCharacters");
1495 Variant.SeparatorCharacters =
1496 AsmVariant->getValueAsString("SeparatorCharacters");
1497 Variant.BreakCharacters =
1498 AsmVariant->getValueAsString("BreakCharacters");
Sam Kolton1b746d12016-09-08 15:50:52 +00001499 Variant.Name = AsmVariant->getValueAsString("Name");
Craig Topperc8b5b252015-12-30 06:00:18 +00001500 Variant.AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001501
Craig Topper8cc904d2016-01-17 20:38:18 +00001502 for (const CodeGenInstruction *CGI : Target.getInstructionsByEnumValue()) {
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001503
Devang Patel85d684a2012-01-09 19:13:28 +00001504 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1505 // filter the set of instructions we consider.
Craig Topper03ec8012014-11-25 20:11:31 +00001506 if (!StringRef(CGI->TheDef->getName()).startswith(MatchPrefix))
Jim Grosbach3263a072012-04-11 21:02:33 +00001507 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001508
Devang Patel85d684a2012-01-09 19:13:28 +00001509 // Ignore "codegen only" instructions.
Craig Topper03ec8012014-11-25 20:11:31 +00001510 if (CGI->TheDef->getValueAsBit("isCodeGenOnly"))
Jim Grosbach3263a072012-04-11 21:02:33 +00001511 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001512
Sam Kolton1b746d12016-09-08 15:50:52 +00001513 // Ignore instructions for different instructions
Craig Topperbcd3c372017-05-31 21:12:46 +00001514 StringRef V = CGI->TheDef->getValueAsString("AsmVariantName");
Sam Kolton1b746d12016-09-08 15:50:52 +00001515 if (!V.empty() && V != Variant.Name)
1516 continue;
1517
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001518 auto II = std::make_unique<MatchableInfo>(*CGI);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001519
Craig Topperfd2c6a32015-12-31 08:18:23 +00001520 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001521
Devang Patel85d684a2012-01-09 19:13:28 +00001522 // Ignore instructions which shouldn't be matched and diagnose invalid
1523 // instruction definitions with an error.
Sander de Smalen5b691a12018-02-04 16:24:17 +00001524 if (!II->validate(CommentDelimiter, false))
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001525 continue;
1526
1527 Matchables.push_back(std::move(II));
Chris Lattner743081d2010-11-04 00:43:46 +00001528 }
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001529
Devang Patel85d684a2012-01-09 19:13:28 +00001530 // Parse all of the InstAlias definitions and stick them in the list of
1531 // matchables.
1532 std::vector<Record*> AllInstAliases =
1533 Records.getAllDerivedDefinitions("InstAlias");
1534 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001535 auto Alias = std::make_unique<CodeGenInstAlias>(AllInstAliases[i],
Craig Topperc8b5b252015-12-30 06:00:18 +00001536 Target);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001537
Devang Patel85d684a2012-01-09 19:13:28 +00001538 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1539 // filter the set of instruction aliases we consider, based on the target
1540 // instruction.
Jim Grosbach56e63262012-04-17 00:01:04 +00001541 if (!StringRef(Alias->ResultInst->TheDef->getName())
1542 .startswith( MatchPrefix))
Jim Grosbach3263a072012-04-11 21:02:33 +00001543 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001544
Craig Topperbcd3c372017-05-31 21:12:46 +00001545 StringRef V = Alias->TheDef->getValueAsString("AsmVariantName");
Sam Kolton1b746d12016-09-08 15:50:52 +00001546 if (!V.empty() && V != Variant.Name)
1547 continue;
1548
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001549 auto II = std::make_unique<MatchableInfo>(std::move(Alias));
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001550
Craig Topperfd2c6a32015-12-31 08:18:23 +00001551 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001552
Devang Patel85d684a2012-01-09 19:13:28 +00001553 // Validate the alias definitions.
Sander de Smalen5b691a12018-02-04 16:24:17 +00001554 II->validate(CommentDelimiter, true);
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001555
1556 Matchables.push_back(std::move(II));
Devang Patel85d684a2012-01-09 19:13:28 +00001557 }
Chris Lattner488c2012010-11-01 04:05:41 +00001558 }
Chris Lattnerd8adec72010-11-01 04:03:32 +00001559
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001560 // Build info for the register classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001561 buildRegisterClasses(SingletonRegisters);
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001562
1563 // Build info for the user defined assembly operand classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001564 buildOperandClasses();
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001565
Chris Lattner4779e3e92010-11-04 00:57:06 +00001566 // Build the information about matchables, now that we have fully formed
1567 // classes.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001568 std::vector<std::unique_ptr<MatchableInfo>> NewMatchables;
Craig Topperf34dad92014-11-28 03:53:02 +00001569 for (auto &II : Matchables) {
Chris Lattner82d88ce2010-09-06 21:01:37 +00001570 // Parse the tokens after the mnemonic.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001571 // Note: buildInstructionOperandReference may insert new AsmOperands, so
Bob Wilsonb9b24222011-01-26 19:44:55 +00001572 // don't precompute the loop bound.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001573 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1574 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
Chris Lattner28ea9b12010-11-02 17:30:52 +00001575 StringRef Token = Op.Token;
Daniel Dunbare10787e2009-08-07 08:26:05 +00001576
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001577 // Check for singleton registers.
Craig Toppere4e74152015-12-29 07:03:23 +00001578 if (Record *RegRecord = Op.SingletonReg) {
Chris Lattner28ea9b12010-11-02 17:30:52 +00001579 Op.Class = RegisterClasses[RegRecord];
Chris Lattnerb80ab362010-11-01 01:37:30 +00001580 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1581 "Unexpected class for singleton register");
Chris Lattnerb80ab362010-11-01 01:37:30 +00001582 continue;
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001583 }
1584
Daniel Dunbare10787e2009-08-07 08:26:05 +00001585 // Check for simple tokens.
1586 if (Token[0] != '$') {
Chris Lattner28ea9b12010-11-02 17:30:52 +00001587 Op.Class = getTokenClass(Token);
Daniel Dunbare10787e2009-08-07 08:26:05 +00001588 continue;
1589 }
1590
Chris Lattnerd6746d52010-11-06 22:06:03 +00001591 if (Token.size() > 1 && isdigit(Token[1])) {
1592 Op.Class = getTokenClass(Token);
1593 continue;
1594 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001595
Chris Lattner4efe13d2010-11-04 02:11:18 +00001596 // Otherwise this is an operand reference.
Chris Lattnerccde4632010-11-04 01:58:23 +00001597 StringRef OperandName;
1598 if (Token[1] == '{')
1599 OperandName = Token.substr(2, Token.size() - 3);
1600 else
1601 OperandName = Token.substr(1);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001602
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001603 if (II->DefRec.is<const CodeGenInstruction*>())
1604 buildInstructionOperandReference(II.get(), OperandName, i);
Chris Lattner4efe13d2010-11-04 02:11:18 +00001605 else
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001606 buildAliasOperandReference(II.get(), OperandName, Op);
Daniel Dunbare10787e2009-08-07 08:26:05 +00001607 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001608
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001609 if (II->DefRec.is<const CodeGenInstruction*>()) {
1610 II->buildInstructionResultOperands();
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001611 // If the instruction has a two-operand alias, build up the
1612 // matchable here. We'll add them in bulk at the end to avoid
1613 // confusing this loop.
Craig Topperbcd3c372017-05-31 21:12:46 +00001614 StringRef Constraint =
1615 II->TheDef->getValueAsString("TwoOperandAliasConstraint");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001616 if (Constraint != "") {
1617 // Start by making a copy of the original matchable.
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001618 auto AliasII = std::make_unique<MatchableInfo>(*II);
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001619
1620 // Adjust it to be a two-operand alias.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001621 AliasII->formTwoOperandAlias(Constraint);
1622
1623 // Add the alias to the matchables list.
1624 NewMatchables.push_back(std::move(AliasII));
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001625 }
1626 } else
Sander de Smalen5b691a12018-02-04 16:24:17 +00001627 // FIXME: The tied operands checking is not yet integrated with the
1628 // framework for reporting multiple near misses. To prevent invalid
1629 // formats from being matched with an alias if a tied-operands check
1630 // would otherwise have disallowed it, we just disallow such constructs
1631 // in TableGen completely.
1632 II->buildAliasResultOperands(!ReportMultipleNearMisses);
Daniel Dunbare10787e2009-08-07 08:26:05 +00001633 }
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001634 if (!NewMatchables.empty())
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001635 Matchables.insert(Matchables.end(),
1636 std::make_move_iterator(NewMatchables.begin()),
1637 std::make_move_iterator(NewMatchables.end()));
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001638
Jim Grosbachba395922011-12-06 23:43:54 +00001639 // Process token alias definitions and set up the associated superclass
1640 // information.
1641 std::vector<Record*> AllTokenAliases =
1642 Records.getAllDerivedDefinitions("TokenAlias");
Craig Toppere4e74152015-12-29 07:03:23 +00001643 for (Record *Rec : AllTokenAliases) {
Jim Grosbachba395922011-12-06 23:43:54 +00001644 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1645 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
Jim Grosbach37f6dcb32012-04-17 21:23:52 +00001646 if (FromClass == ToClass)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001647 PrintFatalError(Rec->getLoc(),
Jim Grosbach37f6dcb32012-04-17 21:23:52 +00001648 "error: Destination value identical to source value.");
Jim Grosbachba395922011-12-06 23:43:54 +00001649 FromClass->SuperClasses.push_back(ToClass);
1650 }
1651
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001652 // Reorder classes so that classes precede super classes.
David Blaikied749e342014-11-28 20:35:57 +00001653 Classes.sort();
Oliver Stannard7772f022016-01-25 10:20:19 +00001654
Matthias Brauna8eed312016-12-05 19:44:31 +00001655#ifdef EXPENSIVE_CHECKS
1656 // Verify that the table is sorted and operator < works transitively.
Oliver Stannard7772f022016-01-25 10:20:19 +00001657 for (auto I = Classes.begin(), E = Classes.end(); I != E; ++I) {
1658 for (auto J = I; J != E; ++J) {
1659 assert(!(*J < *I));
1660 assert(I == J || !J->isSubsetOf(*I));
1661 }
1662 }
Matthias Brauna8eed312016-12-05 19:44:31 +00001663#endif
Daniel Dunbare10787e2009-08-07 08:26:05 +00001664}
1665
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001666/// buildInstructionOperandReference - The specified operand is a reference to a
Chris Lattner4779e3e92010-11-04 00:57:06 +00001667/// named operand such as $src. Resolve the Class and OperandInfo pointers.
1668void AsmMatcherInfo::
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001669buildInstructionOperandReference(MatchableInfo *II,
Chris Lattnerccde4632010-11-04 01:58:23 +00001670 StringRef OperandName,
Bob Wilsonb9b24222011-01-26 19:44:55 +00001671 unsigned AsmOpIdx) {
Chris Lattner4efe13d2010-11-04 02:11:18 +00001672 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1673 const CGIOperandList &Operands = CGI.Operands;
Bob Wilsonb9b24222011-01-26 19:44:55 +00001674 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001675
Chris Lattnerfecdad62010-11-06 07:14:44 +00001676 // Map this token to an operand.
Chris Lattner4779e3e92010-11-04 00:57:06 +00001677 unsigned Idx;
1678 if (!Operands.hasOperandNamed(OperandName, Idx))
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001679 PrintFatalError(II->TheDef->getLoc(),
1680 "error: unable to find operand: '" + OperandName + "'");
Chris Lattner897a1402010-11-04 01:55:23 +00001681
Bob Wilsonb9b24222011-01-26 19:44:55 +00001682 // If the instruction operand has multiple suboperands, but the parser
1683 // match class for the asm operand is still the default "ImmAsmOperand",
1684 // then handle each suboperand separately.
1685 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1686 Record *Rec = Operands[Idx].Rec;
1687 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1688 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1689 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1690 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1691 StringRef Token = Op->Token; // save this in case Op gets moved
1692 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
Ahmed Bougachaeb4dbd82015-05-29 01:03:37 +00001693 MatchableInfo::AsmOperand NewAsmOp(/*IsIsolatedToken=*/true, Token);
Bob Wilsonb9b24222011-01-26 19:44:55 +00001694 NewAsmOp.SubOpIdx = SI;
1695 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1696 }
1697 // Replace Op with first suboperand.
1698 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1699 Op->SubOpIdx = 0;
1700 }
1701 }
1702
Chris Lattner897a1402010-11-04 01:55:23 +00001703 // Set up the operand class.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001704 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
Sander de Smalen5b691a12018-02-04 16:24:17 +00001705 Op->OrigSrcOpName = OperandName;
Chris Lattner897a1402010-11-04 01:55:23 +00001706
1707 // If the named operand is tied, canonicalize it to the untied operand.
1708 // For example, something like:
1709 // (outs GPR:$dst), (ins GPR:$src)
1710 // with an asmstring of
1711 // "inc $src"
1712 // we want to canonicalize to:
1713 // "inc $dst"
1714 // so that we know how to provide the $dst operand when filling in the result.
Ulrich Weigande037a492013-04-27 18:48:23 +00001715 int OITied = -1;
1716 if (Operands[Idx].MINumOperands == 1)
1717 OITied = Operands[Idx].getTiedRegister();
Chris Lattner4779e3e92010-11-04 00:57:06 +00001718 if (OITied != -1) {
1719 // The tied operand index is an MIOperand index, find the operand that
1720 // contains it.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001721 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1722 OperandName = Operands[Idx.first].Name;
1723 Op->SubOpIdx = Idx.second;
Chris Lattner4779e3e92010-11-04 00:57:06 +00001724 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001725
Bob Wilsonb9b24222011-01-26 19:44:55 +00001726 Op->SrcOpName = OperandName;
Chris Lattner4779e3e92010-11-04 00:57:06 +00001727}
1728
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001729/// buildAliasOperandReference - When parsing an operand reference out of the
Chris Lattnerb625dd22010-11-06 07:06:09 +00001730/// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1731/// operand reference is by looking it up in the result pattern definition.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001732void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
Chris Lattner4efe13d2010-11-04 02:11:18 +00001733 StringRef OperandName,
1734 MatchableInfo::AsmOperand &Op) {
1735 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001736
Chris Lattner4efe13d2010-11-04 02:11:18 +00001737 // Set up the operand class.
Chris Lattnerb625dd22010-11-06 07:06:09 +00001738 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
Chris Lattnerb6f8e822010-11-06 19:25:43 +00001739 if (CGA.ResultOperands[i].isRecord() &&
1740 CGA.ResultOperands[i].getName() == OperandName) {
Chris Lattnerfecdad62010-11-06 07:14:44 +00001741 // It's safe to go with the first one we find, because CodeGenInstAlias
1742 // validates that all operands with the same name have the same record.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001743 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001744 // Use the match class from the Alias definition, not the
1745 // destination instruction, as we may have an immediate that's
1746 // being munged by the match class.
1747 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
Bob Wilsonb9b24222011-01-26 19:44:55 +00001748 Op.SubOpIdx);
Chris Lattnerb625dd22010-11-06 07:06:09 +00001749 Op.SrcOpName = OperandName;
Sander de Smalen5b691a12018-02-04 16:24:17 +00001750 Op.OrigSrcOpName = OperandName;
Chris Lattnerb625dd22010-11-06 07:06:09 +00001751 return;
Chris Lattner4efe13d2010-11-04 02:11:18 +00001752 }
Chris Lattnerb625dd22010-11-06 07:06:09 +00001753
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001754 PrintFatalError(II->TheDef->getLoc(),
1755 "error: unable to find operand: '" + OperandName + "'");
Chris Lattner4efe13d2010-11-04 02:11:18 +00001756}
1757
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001758void MatchableInfo::buildInstructionResultOperands() {
Chris Lattnerfecdad62010-11-06 07:14:44 +00001759 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001760
Chris Lattnerfecdad62010-11-06 07:14:44 +00001761 // Loop over all operands of the result instruction, determining how to
1762 // populate them.
Craig Toppere4e74152015-12-29 07:03:23 +00001763 for (const CGIOperandList::OperandInfo &OpInfo : ResultInst->Operands) {
Chris Lattner7108dad2010-11-04 01:42:59 +00001764 // If this is a tied operand, just copy from the previously handled operand.
Ulrich Weigande037a492013-04-27 18:48:23 +00001765 int TiedOp = -1;
1766 if (OpInfo.MINumOperands == 1)
1767 TiedOp = OpInfo.getTiedRegister();
Chris Lattner7108dad2010-11-04 01:42:59 +00001768 if (TiedOp != -1) {
Sander de Smalen5b691a12018-02-04 16:24:17 +00001769 int TiedSrcOperand = findAsmOperandOriginallyNamed(OpInfo.Name);
1770 if (TiedSrcOperand != -1 &&
1771 ResOperands[TiedOp].Kind == ResOperand::RenderAsmOperand)
1772 ResOperands.push_back(ResOperand::getTiedOp(
1773 TiedOp, ResOperands[TiedOp].AsmOperandNum, TiedSrcOperand));
1774 else
1775 ResOperands.push_back(ResOperand::getTiedOp(TiedOp, 0, 0));
Chris Lattner7108dad2010-11-04 01:42:59 +00001776 continue;
1777 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001778
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001779 int SrcOperand = findAsmOperandNamed(OpInfo.Name);
Ulrich Weigande037a492013-04-27 18:48:23 +00001780 if (OpInfo.Name.empty() || SrcOperand == -1) {
1781 // This may happen for operands that are tied to a suboperand of a
1782 // complex operand. Simply use a dummy value here; nobody should
1783 // use this operand slot.
1784 // FIXME: The long term goal is for the MCOperand list to not contain
1785 // tied operands at all.
1786 ResOperands.push_back(ResOperand::getImmOp(0));
1787 continue;
1788 }
Chris Lattner7108dad2010-11-04 01:42:59 +00001789
Bob Wilsonb9b24222011-01-26 19:44:55 +00001790 // Check if the one AsmOperand populates the entire operand.
1791 unsigned NumOperands = OpInfo.MINumOperands;
1792 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1793 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
Chris Lattner743081d2010-11-04 00:43:46 +00001794 continue;
1795 }
Bob Wilsonb9b24222011-01-26 19:44:55 +00001796
1797 // Add a separate ResOperand for each suboperand.
1798 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1799 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1800 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1801 "unexpected AsmOperands for suboperands");
1802 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1803 }
Chris Lattner743081d2010-11-04 00:43:46 +00001804 }
1805}
1806
Sander de Smalen5b691a12018-02-04 16:24:17 +00001807void MatchableInfo::buildAliasResultOperands(bool AliasConstraintsAreChecked) {
Chris Lattner8188fb22010-11-06 07:31:43 +00001808 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1809 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001810
Sander de Smalen5b691a12018-02-04 16:24:17 +00001811 // Map of: $reg -> #lastref
1812 // where $reg is the name of the operand in the asm string
1813 // where #lastref is the last processed index where $reg was referenced in
1814 // the asm string.
1815 SmallDenseMap<StringRef, int> OperandRefs;
1816
Chris Lattner8188fb22010-11-06 07:31:43 +00001817 // Loop over all operands of the result instruction, determining how to
1818 // populate them.
1819 unsigned AliasOpNo = 0;
Bob Wilsonb9b24222011-01-26 19:44:55 +00001820 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
Chris Lattner8188fb22010-11-06 07:31:43 +00001821 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001822 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001823
Chris Lattner8188fb22010-11-06 07:31:43 +00001824 // If this is a tied operand, just copy from the previously handled operand.
Ulrich Weigande037a492013-04-27 18:48:23 +00001825 int TiedOp = -1;
1826 if (OpInfo->MINumOperands == 1)
1827 TiedOp = OpInfo->getTiedRegister();
Chris Lattner8188fb22010-11-06 07:31:43 +00001828 if (TiedOp != -1) {
Sander de Smalen5b691a12018-02-04 16:24:17 +00001829 unsigned SrcOp1 = 0;
1830 unsigned SrcOp2 = 0;
1831
1832 // If an operand has been specified twice in the asm string,
1833 // add the two source operand's indices to the TiedOp so that
1834 // at runtime the 'tied' constraint is checked.
1835 if (ResOperands[TiedOp].Kind == ResOperand::RenderAsmOperand) {
1836 SrcOp1 = ResOperands[TiedOp].AsmOperandNum;
1837
1838 // Find the next operand (similarly named operand) in the string.
1839 StringRef Name = AsmOperands[SrcOp1].SrcOpName;
1840 auto Insert = OperandRefs.try_emplace(Name, SrcOp1);
1841 SrcOp2 = findAsmOperandNamed(Name, Insert.first->second);
1842
1843 // Not updating the record in OperandRefs will cause TableGen
1844 // to fail with an error at the end of this function.
1845 if (AliasConstraintsAreChecked)
1846 Insert.first->second = SrcOp2;
1847
1848 // In case it only has one reference in the asm string,
1849 // it doesn't need to be checked for tied constraints.
1850 SrcOp2 = (SrcOp2 == (unsigned)-1) ? SrcOp1 : SrcOp2;
1851 }
1852
Sander de Smalen118099a2018-06-18 13:39:29 +00001853 // If the alias operand is of a different operand class, we only want
1854 // to benefit from the tied-operands check and just match the operand
1855 // as a normal, but not copy the original (TiedOp) to the result
1856 // instruction. We do this by passing -1 as the tied operand to copy.
1857 if (ResultInst->Operands[i].Rec->getName() !=
1858 ResultInst->Operands[TiedOp].Rec->getName()) {
1859 SrcOp1 = ResOperands[TiedOp].AsmOperandNum;
1860 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1861 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1862 SrcOp2 = findAsmOperand(Name, SubIdx);
1863 ResOperands.push_back(
1864 ResOperand::getTiedOp((unsigned)-1, SrcOp1, SrcOp2));
1865 } else {
1866 ResOperands.push_back(ResOperand::getTiedOp(TiedOp, SrcOp1, SrcOp2));
1867 continue;
1868 }
Chris Lattner4869d342010-11-06 19:57:21 +00001869 }
1870
Bob Wilsonb9b24222011-01-26 19:44:55 +00001871 // Handle all the suboperands for this operand.
1872 const std::string &OpName = OpInfo->Name;
1873 for ( ; AliasOpNo < LastOpNo &&
1874 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1875 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1876
1877 // Find out what operand from the asmparser that this MCInst operand
1878 // comes from.
1879 switch (CGA.ResultOperands[AliasOpNo].Kind) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001880 case CodeGenInstAlias::ResultOperand::K_Record: {
1881 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001882 int SrcOperand = findAsmOperand(Name, SubIdx);
Bob Wilsonb9b24222011-01-26 19:44:55 +00001883 if (SrcOperand == -1)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001884 PrintFatalError(TheDef->getLoc(), "Instruction '" +
Bob Wilsonb9b24222011-01-26 19:44:55 +00001885 TheDef->getName() + "' has operand '" + OpName +
1886 "' that doesn't appear in asm string!");
Sander de Smalen5b691a12018-02-04 16:24:17 +00001887
1888 // Add it to the operand references. If it is added a second time, the
1889 // record won't be updated and it will fail later on.
1890 OperandRefs.try_emplace(Name, SrcOperand);
1891
Bob Wilsonb9b24222011-01-26 19:44:55 +00001892 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1893 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1894 NumOperands));
1895 break;
1896 }
1897 case CodeGenInstAlias::ResultOperand::K_Imm: {
1898 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1899 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1900 break;
1901 }
1902 case CodeGenInstAlias::ResultOperand::K_Reg: {
1903 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1904 ResOperands.push_back(ResOperand::getRegOp(Reg));
1905 break;
1906 }
1907 }
Chris Lattner4869d342010-11-06 19:57:21 +00001908 }
Chris Lattner8188fb22010-11-06 07:31:43 +00001909 }
Sander de Smalen5b691a12018-02-04 16:24:17 +00001910
1911 // Check that operands are not repeated more times than is supported.
1912 for (auto &T : OperandRefs) {
1913 if (T.second != -1 && findAsmOperandNamed(T.first, T.second) != -1)
1914 PrintFatalError(TheDef->getLoc(),
1915 "Operand '" + T.first + "' can never be matched");
1916 }
Chris Lattner8188fb22010-11-06 07:31:43 +00001917}
Chris Lattner743081d2010-11-04 00:43:46 +00001918
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001919static unsigned
1920getConverterOperandID(const std::string &Name,
1921 SmallSetVector<CachedHashString, 16> &Table,
1922 bool &IsNew) {
1923 IsNew = Table.insert(CachedHashString(Name));
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001924
David Majnemer0d955d02016-08-11 22:21:41 +00001925 unsigned ID = IsNew ? Table.size() - 1 : find(Table, Name) - Table.begin();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001926
1927 assert(ID < Table.size());
1928
1929 return ID;
1930}
1931
Craig Topperb64f9152019-04-02 20:52:04 +00001932static unsigned
1933emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName,
1934 std::vector<std::unique_ptr<MatchableInfo>> &Infos,
1935 bool HasMnemonicFirst, bool HasOptionalOperands,
1936 raw_ostream &OS) {
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001937 SmallSetVector<CachedHashString, 16> OperandConversionKinds;
1938 SmallSetVector<CachedHashString, 16> InstructionConversionKinds;
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001939 std::vector<std::vector<uint8_t> > ConversionTable;
1940 size_t MaxRowLength = 2; // minimum is custom converter plus terminator.
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001941
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001942 // TargetOperandClass - This is the target's operand class, like X86Operand.
Matthias Braun4a86d452016-12-04 05:48:16 +00001943 std::string TargetOperandClass = Target.getName().str() + "Operand";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001944
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001945 // Write the convert function to a separate stream, so we can drop it after
1946 // the enum. We'll build up the conversion handlers for the individual
1947 // operand types opportunistically as we encounter them.
1948 std::string ConvertFnBody;
1949 raw_string_ostream CvtOS(ConvertFnBody);
1950 // Start the unified conversion function.
Sam Kolton5f10a132016-05-06 11:31:17 +00001951 if (HasOptionalOperands) {
1952 CvtOS << "void " << Target.getName() << ClassName << "::\n"
1953 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1954 << "unsigned Opcode,\n"
1955 << " const OperandVector &Operands,\n"
1956 << " const SmallBitVector &OptionalOperandsMask) {\n";
1957 } else {
1958 CvtOS << "void " << Target.getName() << ClassName << "::\n"
1959 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1960 << "unsigned Opcode,\n"
1961 << " const OperandVector &Operands) {\n";
1962 }
1963 CvtOS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
1964 CvtOS << " const uint8_t *Converter = ConversionTable[Kind];\n";
1965 if (HasOptionalOperands) {
Nirav Daveb2f3fad2017-08-07 13:55:27 +00001966 size_t MaxNumOperands = 0;
1967 for (const auto &MI : Infos) {
1968 MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
1969 }
1970 CvtOS << " unsigned DefaultsOffset[" << (MaxNumOperands + 1)
1971 << "] = { 0 };\n";
1972 CvtOS << " assert(OptionalOperandsMask.size() == " << (MaxNumOperands)
1973 << ");\n";
1974 CvtOS << " for (unsigned i = 0, NumDefaults = 0; i < " << (MaxNumOperands)
1975 << "; ++i) {\n";
1976 CvtOS << " DefaultsOffset[i + 1] = NumDefaults;\n";
1977 CvtOS << " NumDefaults += (OptionalOperandsMask[i] ? 1 : 0);\n";
1978 CvtOS << " }\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00001979 }
1980 CvtOS << " unsigned OpIdx;\n";
1981 CvtOS << " Inst.setOpcode(Opcode);\n";
1982 CvtOS << " for (const uint8_t *p = Converter; *p; p+= 2) {\n";
1983 if (HasOptionalOperands) {
Nirav Daveb2f3fad2017-08-07 13:55:27 +00001984 CvtOS << " OpIdx = *(p + 1) - DefaultsOffset[*(p + 1)];\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00001985 } else {
1986 CvtOS << " OpIdx = *(p + 1);\n";
1987 }
1988 CvtOS << " switch (*p) {\n";
1989 CvtOS << " default: llvm_unreachable(\"invalid conversion entry!\");\n";
1990 CvtOS << " case CVT_Reg:\n";
1991 CvtOS << " static_cast<" << TargetOperandClass
1992 << "&>(*Operands[OpIdx]).addRegOperands(Inst, 1);\n";
1993 CvtOS << " break;\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00001994 CvtOS << " case CVT_Tied: {\n";
Simon Pilgrime4d40f92018-02-17 12:29:47 +00001995 CvtOS << " assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
1996 CvtOS << " std::begin(TiedAsmOperandTable)) &&\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00001997 CvtOS << " \"Tied operand not found\");\n";
1998 CvtOS << " unsigned TiedResOpnd = TiedAsmOperandTable[OpIdx][0];\n";
Sander de Smalen118099a2018-06-18 13:39:29 +00001999 CvtOS << " if (TiedResOpnd != (uint8_t) -1)\n";
2000 CvtOS << " Inst.addOperand(Inst.getOperand(TiedResOpnd));\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00002001 CvtOS << " break;\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00002002 CvtOS << " }\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002003
Chad Rosier738ea252012-08-30 17:59:25 +00002004 std::string OperandFnBody;
2005 raw_string_ostream OpOS(OperandFnBody);
2006 // Start the operand number lookup function.
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002007 OpOS << "void " << Target.getName() << ClassName << "::\n"
2008 << "convertToMapAndConstraints(unsigned Kind,\n";
Chad Rosier380a74a2012-10-02 00:25:57 +00002009 OpOS.indent(27);
David Blaikie960ea3f2014-06-08 16:18:35 +00002010 OpOS << "const OperandVector &Operands) {\n"
Chad Rosier98cfa102012-08-31 00:03:31 +00002011 << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002012 << " unsigned NumMCOperands = 0;\n"
Craig Topper91506102012-09-18 01:41:49 +00002013 << " const uint8_t *Converter = ConversionTable[Kind];\n"
2014 << " for (const uint8_t *p = Converter; *p; p+= 2) {\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002015 << " switch (*p) {\n"
2016 << " default: llvm_unreachable(\"invalid conversion entry!\");\n"
2017 << " case CVT_Reg:\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002018 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
Chad Rosier72450332013-01-15 23:07:53 +00002019 << " Operands[*(p + 1)]->setConstraint(\"r\");\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002020 << " ++NumMCOperands;\n"
2021 << " break;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002022 << " case CVT_Tied:\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002023 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002024 << " break;\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002025
2026 // Pre-populate the operand conversion kinds with the standard always
2027 // available entries.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002028 OperandConversionKinds.insert(CachedHashString("CVT_Done"));
2029 OperandConversionKinds.insert(CachedHashString("CVT_Reg"));
2030 OperandConversionKinds.insert(CachedHashString("CVT_Tied"));
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002031 enum { CVT_Done, CVT_Reg, CVT_Tied };
2032
Sander de Smalen5b691a12018-02-04 16:24:17 +00002033 // Map of e.g. <0, 2, 3> -> "Tie_0_2_3" enum label.
Sander de Smalen118099a2018-06-18 13:39:29 +00002034 std::map<std::tuple<uint8_t, uint8_t, uint8_t>, std::string>
Sander de Smalen5b691a12018-02-04 16:24:17 +00002035 TiedOperandsEnumMap;
2036
Craig Topperf34dad92014-11-28 03:53:02 +00002037 for (auto &II : Infos) {
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00002038 // Check if we have a custom match function.
Craig Topperbcd3c372017-05-31 21:12:46 +00002039 StringRef AsmMatchConverter =
2040 II->getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
Tom Stellard74c87c82015-05-26 15:55:50 +00002041 if (!AsmMatchConverter.empty() && II->UseInstAsmMatchConverter) {
Craig Topperbcd3c372017-05-31 21:12:46 +00002042 std::string Signature = ("ConvertCustom_" + AsmMatchConverter).str();
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002043 II->ConversionFnKind = Signature;
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00002044
2045 // Check if we have already generated this signature.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002046 if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00002047 continue;
2048
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002049 // Remember this converter for the kind enum.
2050 unsigned KindID = OperandConversionKinds.size();
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002051 OperandConversionKinds.insert(
2052 CachedHashString("CVT_" + getEnumNameForToken(AsmMatchConverter)));
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00002053
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002054 // Add the converter row for this instruction.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002055 ConversionTable.emplace_back();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002056 ConversionTable.back().push_back(KindID);
2057 ConversionTable.back().push_back(CVT_Done);
2058
2059 // Add the handler to the conversion driver function.
Tim Northoverb3cfb282013-01-10 16:47:31 +00002060 CvtOS << " case CVT_"
2061 << getEnumNameForToken(AsmMatchConverter) << ":\n"
Chad Rosier451ef132012-08-31 22:12:31 +00002062 << " " << AsmMatchConverter << "(Inst, Operands);\n"
Chad Rosier98cfa102012-08-31 00:03:31 +00002063 << " break;\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002064
Chad Rosier738ea252012-08-30 17:59:25 +00002065 // FIXME: Handle the operand number lookup for custom match functions.
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00002066 continue;
2067 }
2068
Daniel Dunbare10787e2009-08-07 08:26:05 +00002069 // Build the conversion function signature.
2070 std::string Signature = "Convert";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002071
2072 std::vector<uint8_t> ConversionRow;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002073
Chris Lattner5cf8a4a2010-11-02 21:49:44 +00002074 // Compute the convert enum and the case body.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002075 MaxRowLength = std::max(MaxRowLength, II->ResOperands.size()*2 + 1 );
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002076
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002077 for (unsigned i = 0, e = II->ResOperands.size(); i != e; ++i) {
2078 const MatchableInfo::ResOperand &OpInfo = II->ResOperands[i];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002079
Chris Lattner743081d2010-11-04 00:43:46 +00002080 // Generate code to populate each result operand.
2081 switch (OpInfo.Kind) {
Chris Lattner743081d2010-11-04 00:43:46 +00002082 case MatchableInfo::ResOperand::RenderAsmOperand: {
2083 // This comes from something we parsed.
Craig Topper03ec8012014-11-25 20:11:31 +00002084 const MatchableInfo::AsmOperand &Op =
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002085 II->AsmOperands[OpInfo.AsmOperandNum];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002086
Chris Lattnere032dbf2010-11-02 22:55:03 +00002087 // Registers are always converted the same, don't duplicate the
2088 // conversion function based on them.
Chris Lattnere032dbf2010-11-02 22:55:03 +00002089 Signature += "__";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002090 std::string Class;
2091 Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName;
2092 Signature += Class;
Bob Wilsonb9b24222011-01-26 19:44:55 +00002093 Signature += utostr(OpInfo.MINumOperands);
Chris Lattner743081d2010-11-04 00:43:46 +00002094 Signature += "_" + itostr(OpInfo.AsmOperandNum);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002095
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002096 // Add the conversion kind, if necessary, and get the associated ID
2097 // the index of its entry in the vector).
2098 std::string Name = "CVT_" + (Op.Class->isRegisterClass() ? "Reg" :
2099 Op.Class->RenderMethod);
Sam Kolton5f10a132016-05-06 11:31:17 +00002100 if (Op.Class->IsOptional) {
2101 // For optional operands we must also care about DefaultMethod
2102 assert(HasOptionalOperands);
2103 Name += "_" + Op.Class->DefaultMethod;
2104 }
Tim Northoverb3cfb282013-01-10 16:47:31 +00002105 Name = getEnumNameForToken(Name);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002106
2107 bool IsNewConverter = false;
2108 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2109 IsNewConverter);
2110
2111 // Add the operand entry to the instruction kind conversion row.
2112 ConversionRow.push_back(ID);
Craig Topperfd2c6a32015-12-31 08:18:23 +00002113 ConversionRow.push_back(OpInfo.AsmOperandNum + HasMnemonicFirst);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002114
2115 if (!IsNewConverter)
2116 break;
2117
2118 // This is a new operand kind. Add a handler for it to the
2119 // converter driver.
Sam Kolton5f10a132016-05-06 11:31:17 +00002120 CvtOS << " case " << Name << ":\n";
2121 if (Op.Class->IsOptional) {
2122 // If optional operand is not present in actual instruction then we
2123 // should call its DefaultMethod before RenderMethod
2124 assert(HasOptionalOperands);
2125 CvtOS << " if (OptionalOperandsMask[*(p + 1) - 1]) {\n"
2126 << " " << Op.Class->DefaultMethod << "()"
2127 << "->" << Op.Class->RenderMethod << "(Inst, "
2128 << OpInfo.MINumOperands << ");\n"
Sam Kolton5f10a132016-05-06 11:31:17 +00002129 << " } else {\n"
2130 << " static_cast<" << TargetOperandClass
2131 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod
2132 << "(Inst, " << OpInfo.MINumOperands << ");\n"
2133 << " }\n";
2134 } else {
2135 CvtOS << " static_cast<" << TargetOperandClass
2136 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod
2137 << "(Inst, " << OpInfo.MINumOperands << ");\n";
2138 }
2139 CvtOS << " break;\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002140
2141 // Add a handler for the operand number lookup.
2142 OpOS << " case " << Name << ":\n"
Chad Rosier72450332013-01-15 23:07:53 +00002143 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n";
2144
2145 if (Op.Class->isRegisterClass())
2146 OpOS << " Operands[*(p + 1)]->setConstraint(\"r\");\n";
2147 else
2148 OpOS << " Operands[*(p + 1)]->setConstraint(\"m\");\n";
2149 OpOS << " NumMCOperands += " << OpInfo.MINumOperands << ";\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002150 << " break;\n";
Chris Lattner743081d2010-11-04 00:43:46 +00002151 break;
Daniel Dunbarf22553a2010-02-10 08:15:48 +00002152 }
Chris Lattner743081d2010-11-04 00:43:46 +00002153 case MatchableInfo::ResOperand::TiedOperand: {
2154 // If this operand is tied to a previous one, just copy the MCInst
2155 // operand from the earlier one.We can only tie single MCOperand values.
Ulrich Weigande037a492013-04-27 18:48:23 +00002156 assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
Sander de Smalen118099a2018-06-18 13:39:29 +00002157 uint8_t TiedOp = OpInfo.TiedOperands.ResOpnd;
2158 uint8_t SrcOp1 =
2159 OpInfo.TiedOperands.SrcOpnd1Idx + HasMnemonicFirst;
2160 uint8_t SrcOp2 =
2161 OpInfo.TiedOperands.SrcOpnd2Idx + HasMnemonicFirst;
2162 assert((i > TiedOp || TiedOp == (uint8_t)-1) &&
2163 "Tied operand precedes its target!");
Sander de Smalen5b691a12018-02-04 16:24:17 +00002164 auto TiedTupleName = std::string("Tie") + utostr(TiedOp) + '_' +
2165 utostr(SrcOp1) + '_' + utostr(SrcOp2);
2166 Signature += "__" + TiedTupleName;
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002167 ConversionRow.push_back(CVT_Tied);
2168 ConversionRow.push_back(TiedOp);
Sander de Smalen5b691a12018-02-04 16:24:17 +00002169 ConversionRow.push_back(SrcOp1);
2170 ConversionRow.push_back(SrcOp2);
2171
2172 // Also create an 'enum' for this combination of tied operands.
2173 auto Key = std::make_tuple(TiedOp, SrcOp1, SrcOp2);
2174 TiedOperandsEnumMap.emplace(Key, TiedTupleName);
Chris Lattner743081d2010-11-04 00:43:46 +00002175 break;
2176 }
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002177 case MatchableInfo::ResOperand::ImmOperand: {
2178 int64_t Val = OpInfo.ImmVal;
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002179 std::string Ty = "imm_" + itostr(Val);
Hal Finkelf9090722015-01-15 01:33:00 +00002180 Ty = getEnumNameForToken(Ty);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002181 Signature += "__" + Ty;
2182
2183 std::string Name = "CVT_" + Ty;
2184 bool IsNewConverter = false;
2185 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2186 IsNewConverter);
2187 // Add the operand entry to the instruction kind conversion row.
2188 ConversionRow.push_back(ID);
2189 ConversionRow.push_back(0);
2190
2191 if (!IsNewConverter)
2192 break;
2193
2194 CvtOS << " case " << Name << ":\n"
Jim Grosbache9119e42015-05-13 18:37:00 +00002195 << " Inst.addOperand(MCOperand::createImm(" << Val << "));\n"
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002196 << " break;\n";
2197
Chad Rosier738ea252012-08-30 17:59:25 +00002198 OpOS << " case " << Name << ":\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002199 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2200 << " Operands[*(p + 1)]->setConstraint(\"\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002201 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002202 << " break;\n";
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002203 break;
2204 }
Chris Lattner4869d342010-11-06 19:57:21 +00002205 case MatchableInfo::ResOperand::RegOperand: {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002206 std::string Reg, Name;
Craig Topper24064772014-04-15 07:20:03 +00002207 if (!OpInfo.Register) {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002208 Name = "reg0";
2209 Reg = "0";
Bob Wilson03912ab2011-01-14 22:58:09 +00002210 } else {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002211 Reg = getQualifiedName(OpInfo.Register);
Matthias Braun4a86d452016-12-04 05:48:16 +00002212 Name = "reg" + OpInfo.Register->getName().str();
Bob Wilson03912ab2011-01-14 22:58:09 +00002213 }
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002214 Signature += "__" + Name;
2215 Name = "CVT_" + Name;
2216 bool IsNewConverter = false;
2217 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2218 IsNewConverter);
2219 // Add the operand entry to the instruction kind conversion row.
2220 ConversionRow.push_back(ID);
2221 ConversionRow.push_back(0);
2222
2223 if (!IsNewConverter)
2224 break;
2225 CvtOS << " case " << Name << ":\n"
Jim Grosbache9119e42015-05-13 18:37:00 +00002226 << " Inst.addOperand(MCOperand::createReg(" << Reg << "));\n"
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002227 << " break;\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002228
2229 OpOS << " case " << Name << ":\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002230 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2231 << " Operands[*(p + 1)]->setConstraint(\"m\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002232 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002233 << " break;\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002234 }
Chris Lattner743081d2010-11-04 00:43:46 +00002235 }
Daniel Dunbare10787e2009-08-07 08:26:05 +00002236 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002237
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002238 // If there were no operands, add to the signature to that effect
2239 if (Signature == "Convert")
2240 Signature += "_NoOperands";
2241
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002242 II->ConversionFnKind = Signature;
Daniel Dunbare10787e2009-08-07 08:26:05 +00002243
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002244 // Save the signature. If we already have it, don't add a new row
2245 // to the table.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002246 if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
Daniel Dunbare10787e2009-08-07 08:26:05 +00002247 continue;
2248
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002249 // Add the row to the table.
Craig Topperc4de7ee2015-08-16 21:27:08 +00002250 ConversionTable.push_back(std::move(ConversionRow));
Daniel Dunbare10787e2009-08-07 08:26:05 +00002251 }
Daniel Dunbar71330282009-08-08 05:24:34 +00002252
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002253 // Finish up the converter driver function.
Chad Rosierc38826c2012-09-03 17:39:57 +00002254 CvtOS << " }\n }\n}\n\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002255
Chad Rosier738ea252012-08-30 17:59:25 +00002256 // Finish up the operand number lookup function.
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002257 OpOS << " }\n }\n}\n\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002258
Sander de Smalen5b691a12018-02-04 16:24:17 +00002259 // Output a static table for tied operands.
2260 if (TiedOperandsEnumMap.size()) {
2261 // The number of tied operand combinations will be small in practice,
2262 // but just add the assert to be sure.
Sander de Smalen118099a2018-06-18 13:39:29 +00002263 assert(TiedOperandsEnumMap.size() <= 254 &&
Sander de Smalen5b691a12018-02-04 16:24:17 +00002264 "Too many tied-operand combinations to reference with "
Sander de Smalen118099a2018-06-18 13:39:29 +00002265 "an 8bit offset from the conversion table, where index "
2266 "'255' is reserved as operand not to be copied.");
Sander de Smalen5b691a12018-02-04 16:24:17 +00002267
2268 OS << "enum {\n";
2269 for (auto &KV : TiedOperandsEnumMap) {
2270 OS << " " << KV.second << ",\n";
2271 }
2272 OS << "};\n\n";
2273
Craig Topper88c142b2018-06-18 16:17:46 +00002274 OS << "static const uint8_t TiedAsmOperandTable[][3] = {\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00002275 for (auto &KV : TiedOperandsEnumMap) {
Sander de Smalen118099a2018-06-18 13:39:29 +00002276 OS << " /* " << KV.second << " */ { "
2277 << utostr(std::get<0>(KV.first)) << ", "
2278 << utostr(std::get<1>(KV.first)) << ", "
2279 << utostr(std::get<2>(KV.first)) << " },\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00002280 }
2281 OS << "};\n\n";
2282 } else
Craig Topper88c142b2018-06-18 16:17:46 +00002283 OS << "static const uint8_t TiedAsmOperandTable[][3] = "
Sander de Smalen118099a2018-06-18 13:39:29 +00002284 "{ /* empty */ {0, 0, 0} };\n\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00002285
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002286 OS << "namespace {\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002287
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002288 // Output the operand conversion kind enum.
2289 OS << "enum OperatorConversionKind {\n";
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002290 for (const auto &Converter : OperandConversionKinds)
Craig Topper6e526f12016-01-03 07:33:30 +00002291 OS << " " << Converter << ",\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002292 OS << " CVT_NUM_CONVERTERS\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002293 OS << "};\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002294
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002295 // Output the instruction conversion kind enum.
2296 OS << "enum InstructionConversionKind {\n";
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002297 for (const auto &Signature : InstructionConversionKinds)
Craig Topper802d3d32015-08-16 21:27:10 +00002298 OS << " " << Signature << ",\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002299 OS << " CVT_NUM_SIGNATURES\n";
2300 OS << "};\n\n";
2301
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002302 OS << "} // end anonymous namespace\n\n";
2303
2304 // Output the conversion table.
Craig Topper91506102012-09-18 01:41:49 +00002305 OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES]["
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002306 << MaxRowLength << "] = {\n";
2307
2308 for (unsigned Row = 0, ERow = ConversionTable.size(); Row != ERow; ++Row) {
2309 assert(ConversionTable[Row].size() % 2 == 0 && "bad conversion row!");
2310 OS << " // " << InstructionConversionKinds[Row] << "\n";
2311 OS << " { ";
Sander de Smalen5b691a12018-02-04 16:24:17 +00002312 for (unsigned i = 0, e = ConversionTable[Row].size(); i != e; i += 2) {
2313 OS << OperandConversionKinds[ConversionTable[Row][i]] << ", ";
2314 if (OperandConversionKinds[ConversionTable[Row][i]] !=
2315 CachedHashString("CVT_Tied")) {
2316 OS << (unsigned)(ConversionTable[Row][i + 1]) << ", ";
2317 continue;
2318 }
2319
2320 // For a tied operand, emit a reference to the TiedAsmOperandTable
2321 // that contains the operand to copy, and the parsed operands to
2322 // check for their tied constraints.
Sander de Smalen118099a2018-06-18 13:39:29 +00002323 auto Key = std::make_tuple((uint8_t)ConversionTable[Row][i + 1],
2324 (uint8_t)ConversionTable[Row][i + 2],
2325 (uint8_t)ConversionTable[Row][i + 3]);
Sander de Smalen5b691a12018-02-04 16:24:17 +00002326 auto TiedOpndEnum = TiedOperandsEnumMap.find(Key);
2327 assert(TiedOpndEnum != TiedOperandsEnumMap.end() &&
2328 "No record for tied operand pair");
2329 OS << TiedOpndEnum->second << ", ";
2330 i += 2;
2331 }
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002332 OS << "CVT_Done },\n";
2333 }
2334
2335 OS << "};\n\n";
2336
2337 // Spit out the conversion driver function.
Daniel Dunbar71330282009-08-08 05:24:34 +00002338 OS << CvtOS.str();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002339
Chad Rosier738ea252012-08-30 17:59:25 +00002340 // Spit out the operand number lookup function.
2341 OS << OpOS.str();
Craig Topperb64f9152019-04-02 20:52:04 +00002342
2343 return ConversionTable.size();
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002344}
2345
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002346/// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
2347static void emitMatchClassEnumeration(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002348 std::forward_list<ClassInfo> &Infos,
2349 raw_ostream &OS) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002350 OS << "namespace {\n\n";
2351
2352 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
2353 << "/// instruction matching.\n";
2354 OS << "enum MatchClassKind {\n";
2355 OS << " InvalidMatchClass = 0,\n";
Tom Stellardb9f235e2016-02-05 19:59:33 +00002356 OS << " OptionalMatchClass = 1,\n";
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002357 ClassInfo::ClassInfoKind LastKind = ClassInfo::Token;
2358 StringRef LastName = "OptionalMatchClass";
Craig Topperf34dad92014-11-28 03:53:02 +00002359 for (const auto &CI : Infos) {
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002360 if (LastKind == ClassInfo::Token && CI.Kind != ClassInfo::Token) {
2361 OS << " MCK_LAST_TOKEN = " << LastName << ",\n";
2362 } else if (LastKind < ClassInfo::UserClass0 &&
2363 CI.Kind >= ClassInfo::UserClass0) {
2364 OS << " MCK_LAST_REGISTER = " << LastName << ",\n";
2365 }
2366 LastKind = (ClassInfo::ClassInfoKind)CI.Kind;
2367 LastName = CI.Name;
2368
David Blaikied749e342014-11-28 20:35:57 +00002369 OS << " " << CI.Name << ", // ";
2370 if (CI.Kind == ClassInfo::Token) {
2371 OS << "'" << CI.ValueName << "'\n";
2372 } else if (CI.isRegisterClass()) {
2373 if (!CI.ValueName.empty())
2374 OS << "register class '" << CI.ValueName << "'\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002375 else
2376 OS << "derived register class\n";
2377 } else {
David Blaikied749e342014-11-28 20:35:57 +00002378 OS << "user defined class '" << CI.ValueName << "'\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002379 }
2380 }
2381 OS << " NumMatchClassKinds\n";
2382 OS << "};\n\n";
2383
2384 OS << "}\n\n";
2385}
2386
Oliver Stannard41dfac32017-10-03 14:34:57 +00002387/// emitMatchClassDiagStrings - Emit a function to get the diagnostic text to be
2388/// used when an assembly operand does not match the expected operand class.
2389static void emitOperandMatchErrorDiagStrings(AsmMatcherInfo &Info, raw_ostream &OS) {
2390 // If the target does not use DiagnosticString for any operands, don't emit
2391 // an unused function.
2392 if (std::all_of(
2393 Info.Classes.begin(), Info.Classes.end(),
2394 [](const ClassInfo &CI) { return CI.DiagnosticString.empty(); }))
2395 return;
2396
2397 OS << "static const char *getMatchKindDiag(" << Info.Target.getName()
2398 << "AsmParser::" << Info.Target.getName()
2399 << "MatchResultTy MatchResult) {\n";
2400 OS << " switch (MatchResult) {\n";
2401
2402 for (const auto &CI: Info.Classes) {
2403 if (!CI.DiagnosticString.empty()) {
2404 assert(!CI.DiagnosticType.empty() &&
2405 "DiagnosticString set without DiagnosticType");
2406 OS << " case " << Info.Target.getName()
2407 << "AsmParser::Match_" << CI.DiagnosticType << ":\n";
2408 OS << " return \"" << CI.DiagnosticString << "\";\n";
2409 }
2410 }
2411
2412 OS << " default:\n";
2413 OS << " return nullptr;\n";
2414
2415 OS << " }\n";
2416 OS << "}\n\n";
2417}
2418
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002419static void emitRegisterMatchErrorFunc(AsmMatcherInfo &Info, raw_ostream &OS) {
2420 OS << "static unsigned getDiagKindFromRegisterClass(MatchClassKind "
2421 "RegisterClass) {\n";
Fangrui Song2e83b2e2018-10-19 06:12:02 +00002422 if (none_of(Info.Classes, [](const ClassInfo &CI) {
2423 return CI.isRegisterClass() && !CI.DiagnosticType.empty();
2424 })) {
Oliver Stannarddab52122017-10-12 09:28:23 +00002425 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2426 } else {
2427 OS << " switch (RegisterClass) {\n";
2428 for (const auto &CI: Info.Classes) {
2429 if (CI.isRegisterClass() && !CI.DiagnosticType.empty()) {
2430 OS << " case " << CI.Name << ":\n";
2431 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
2432 << CI.DiagnosticType << ";\n";
2433 }
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002434 }
Oliver Stannarddab52122017-10-12 09:28:23 +00002435
2436 OS << " default:\n";
2437 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2438
2439 OS << " }\n";
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002440 }
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002441 OS << "}\n\n";
2442}
2443
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002444/// emitValidateOperandClass - Emit the function to validate an operand class.
2445static void emitValidateOperandClass(AsmMatcherInfo &Info,
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002446 raw_ostream &OS) {
David Blaikie960ea3f2014-06-08 16:18:35 +00002447 OS << "static unsigned validateOperandClass(MCParsedAsmOperand &GOp, "
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002448 << "MatchClassKind Kind) {\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00002449 OS << " " << Info.Target.getName() << "Operand &Operand = ("
2450 << Info.Target.getName() << "Operand&)GOp;\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002451
Kevin Enderby1b87c802011-07-15 18:30:43 +00002452 // The InvalidMatchClass is not to match any operand.
2453 OS << " if (Kind == InvalidMatchClass)\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002454 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n\n";
Kevin Enderby1b87c802011-07-15 18:30:43 +00002455
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002456 // Check for Token operands first.
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002457 // FIXME: Use a more specific diagnostic type.
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002458 OS << " if (Operand.isToken() && Kind <= MCK_LAST_TOKEN)\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002459 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
2460 << " MCTargetAsmParser::Match_Success :\n"
2461 << " MCTargetAsmParser::Match_InvalidOperand;\n\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002462
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002463 // Check the user classes. We don't care what order since we're only
2464 // actually matching against one of them.
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002465 OS << " switch (Kind) {\n"
2466 " default: break;\n";
Craig Topperf34dad92014-11-28 03:53:02 +00002467 for (const auto &CI : Info.Classes) {
David Blaikied749e342014-11-28 20:35:57 +00002468 if (!CI.isUserClass())
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002469 continue;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002470
David Blaikied749e342014-11-28 20:35:57 +00002471 OS << " // '" << CI.ClassName << "' class\n";
Sander de Smalena2fb1d12018-04-26 09:24:45 +00002472 OS << " case " << CI.Name << ": {\n";
2473 OS << " DiagnosticPredicate DP(Operand." << CI.PredicateMethod
2474 << "());\n";
2475 OS << " if (DP.isMatch())\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002476 OS << " return MCTargetAsmParser::Match_Success;\n";
Sander de Smalena2fb1d12018-04-26 09:24:45 +00002477 if (!CI.DiagnosticType.empty()) {
2478 OS << " if (DP.isNearMatch())\n";
2479 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
David Blaikied749e342014-11-28 20:35:57 +00002480 << CI.DiagnosticType << ";\n";
Sander de Smalena2fb1d12018-04-26 09:24:45 +00002481 OS << " break;\n";
2482 }
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002483 else
2484 OS << " break;\n";
Sander de Smalena2fb1d12018-04-26 09:24:45 +00002485 OS << " }\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002486 }
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002487 OS << " } // end switch (Kind)\n\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002488
Owen Anderson8a503f22012-07-16 23:20:09 +00002489 // Check for register operands, including sub-classes.
2490 OS << " if (Operand.isReg()) {\n";
2491 OS << " MatchClassKind OpKind;\n";
2492 OS << " switch (Operand.getReg()) {\n";
2493 OS << " default: OpKind = InvalidMatchClass; break;\n";
Craig Topper03ec8012014-11-25 20:11:31 +00002494 for (const auto &RC : Info.RegisterClasses)
Craig Topper2b347eb2017-07-07 05:19:25 +00002495 OS << " case " << RC.first->getValueAsString("Namespace") << "::"
Craig Topper03ec8012014-11-25 20:11:31 +00002496 << RC.first->getName() << ": OpKind = " << RC.second->Name
Owen Anderson8a503f22012-07-16 23:20:09 +00002497 << "; break;\n";
2498 OS << " }\n";
2499 OS << " return isSubclass(OpKind, Kind) ? "
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002500 << "(unsigned)MCTargetAsmParser::Match_Success :\n "
2501 << " getDiagKindFromRegisterClass(Kind);\n }\n\n";
2502
2503 // Expected operand is a register, but actual is not.
2504 OS << " if (Kind > MCK_LAST_TOKEN && Kind <= MCK_LAST_REGISTER)\n";
2505 OS << " return getDiagKindFromRegisterClass(Kind);\n\n";
Owen Anderson8a503f22012-07-16 23:20:09 +00002506
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002507 // Generic fallthrough match failure case for operands that don't have
2508 // specialized diagnostic types.
2509 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002510 OS << "}\n\n";
2511}
2512
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002513/// emitIsSubclass - Emit the subclass predicate function.
2514static void emitIsSubclass(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002515 std::forward_list<ClassInfo> &Infos,
Daniel Dunbar2587b612009-08-10 16:05:47 +00002516 raw_ostream &OS) {
Dmitri Gribenko8d302402012-09-15 20:22:05 +00002517 OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n";
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002518 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
Daniel Dunbar2587b612009-08-10 16:05:47 +00002519 OS << " if (A == B)\n";
2520 OS << " return true;\n\n";
2521
Craig Topper39311c72015-12-30 06:00:22 +00002522 bool EmittedSwitch = false;
Craig Topperf34dad92014-11-28 03:53:02 +00002523 for (const auto &A : Infos) {
Jim Grosbachba395922011-12-06 23:43:54 +00002524 std::vector<StringRef> SuperClasses;
Tom Stellardb9f235e2016-02-05 19:59:33 +00002525 if (A.IsOptional)
2526 SuperClasses.push_back("OptionalMatchClass");
Craig Topperf34dad92014-11-28 03:53:02 +00002527 for (const auto &B : Infos) {
David Blaikied749e342014-11-28 20:35:57 +00002528 if (&A != &B && A.isSubsetOf(B))
2529 SuperClasses.push_back(B.Name);
Daniel Dunbar2587b612009-08-10 16:05:47 +00002530 }
Jim Grosbachba395922011-12-06 23:43:54 +00002531
2532 if (SuperClasses.empty())
2533 continue;
2534
Craig Topper39311c72015-12-30 06:00:22 +00002535 // If this is the first SuperClass, emit the switch header.
2536 if (!EmittedSwitch) {
Craig Topper13b2a4e2015-12-30 06:00:24 +00002537 OS << " switch (A) {\n";
Craig Topper39311c72015-12-30 06:00:22 +00002538 OS << " default:\n";
2539 OS << " return false;\n";
2540 EmittedSwitch = true;
2541 }
2542
2543 OS << "\n case " << A.Name << ":\n";
Jim Grosbachba395922011-12-06 23:43:54 +00002544
2545 if (SuperClasses.size() == 1) {
Craig Topper13b2a4e2015-12-30 06:00:24 +00002546 OS << " return B == " << SuperClasses.back() << ";\n";
Jim Grosbachba395922011-12-06 23:43:54 +00002547 continue;
2548 }
2549
Aaron Ballmane59e3582013-07-15 16:53:32 +00002550 if (!SuperClasses.empty()) {
Craig Topper39311c72015-12-30 06:00:22 +00002551 OS << " switch (B) {\n";
2552 OS << " default: return false;\n";
Craig Topper77bd2b72015-12-30 06:00:20 +00002553 for (StringRef SC : SuperClasses)
Craig Topper39311c72015-12-30 06:00:22 +00002554 OS << " case " << SC << ": return true;\n";
2555 OS << " }\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002556 } else {
2557 // No case statement to emit
Craig Topper39311c72015-12-30 06:00:22 +00002558 OS << " return false;\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002559 }
Daniel Dunbar2587b612009-08-10 16:05:47 +00002560 }
Aaron Ballmane59e3582013-07-15 16:53:32 +00002561
Craig Topper39311c72015-12-30 06:00:22 +00002562 // If there were case statements emitted into the string stream write the
2563 // default.
Craig Topperf58323e2016-01-03 07:33:34 +00002564 if (EmittedSwitch)
2565 OS << " }\n";
2566 else
Aaron Ballmane59e3582013-07-15 16:53:32 +00002567 OS << " return false;\n";
2568
Daniel Dunbar2587b612009-08-10 16:05:47 +00002569 OS << "}\n\n";
2570}
2571
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002572/// emitMatchTokenString - Emit the function to match a token string to the
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002573/// appropriate match class value.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002574static void emitMatchTokenString(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002575 std::forward_list<ClassInfo> &Infos,
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002576 raw_ostream &OS) {
2577 // Construct the match list.
Chris Lattnerca5a3552010-09-06 02:01:51 +00002578 std::vector<StringMatcher::StringPair> Matches;
Craig Topperf34dad92014-11-28 03:53:02 +00002579 for (const auto &CI : Infos) {
David Blaikied749e342014-11-28 20:35:57 +00002580 if (CI.Kind == ClassInfo::Token)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002581 Matches.emplace_back(CI.ValueName, "return " + CI.Name + ";");
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002582 }
2583
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002584 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002585
Chris Lattnerca5a3552010-09-06 02:01:51 +00002586 StringMatcher("Name", Matches, OS).Emit();
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002587
2588 OS << " return InvalidMatchClass;\n";
2589 OS << "}\n\n";
2590}
Chris Lattner00e2e742009-08-08 20:02:57 +00002591
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002592/// emitMatchRegisterName - Emit the function to match a string to the target
Daniel Dunbard0470d72009-08-07 21:01:44 +00002593/// specific register enum.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002594static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
Daniel Dunbard0470d72009-08-07 21:01:44 +00002595 raw_ostream &OS) {
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002596 // Construct the match list.
Chris Lattnerca5a3552010-09-06 02:01:51 +00002597 std::vector<StringMatcher::StringPair> Matches;
David Blaikie9b613db2014-11-29 18:13:39 +00002598 const auto &Regs = Target.getRegBank().getRegisters();
2599 for (const CodeGenRegister &Reg : Regs) {
2600 if (Reg.TheDef->getValueAsString("AsmName").empty())
Daniel Dunbare2eec052009-07-17 18:51:11 +00002601 continue;
2602
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002603 Matches.emplace_back(Reg.TheDef->getValueAsString("AsmName"),
2604 "return " + utostr(Reg.EnumValue) + ";");
Daniel Dunbare2eec052009-07-17 18:51:11 +00002605 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002606
Chris Lattner60db0a62010-02-09 00:34:28 +00002607 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002608
Alex Bradburyd590c8572017-12-07 09:51:55 +00002609 bool IgnoreDuplicates =
2610 AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
2611 StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002612
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002613 OS << " return 0;\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +00002614 OS << "}\n\n";
Daniel Dunbard0470d72009-08-07 21:01:44 +00002615}
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002616
Dylan McKaybff960a2016-02-03 10:30:16 +00002617/// Emit the function to match a string to the target
2618/// specific register enum.
2619static void emitMatchRegisterAltName(CodeGenTarget &Target, Record *AsmParser,
2620 raw_ostream &OS) {
2621 // Construct the match list.
2622 std::vector<StringMatcher::StringPair> Matches;
2623 const auto &Regs = Target.getRegBank().getRegisters();
2624 for (const CodeGenRegister &Reg : Regs) {
2625
2626 auto AltNames = Reg.TheDef->getValueAsListOfStrings("AltNames");
2627
2628 for (auto AltName : AltNames) {
2629 AltName = StringRef(AltName).trim();
2630
2631 // don't handle empty alternative names
2632 if (AltName.empty())
2633 continue;
2634
2635 Matches.emplace_back(AltName,
2636 "return " + utostr(Reg.EnumValue) + ";");
2637 }
2638 }
2639
2640 OS << "static unsigned MatchRegisterAltName(StringRef Name) {\n";
2641
Alex Bradburyd590c8572017-12-07 09:51:55 +00002642 bool IgnoreDuplicates =
2643 AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
2644 StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
Dylan McKaybff960a2016-02-03 10:30:16 +00002645
2646 OS << " return 0;\n";
2647 OS << "}\n\n";
2648}
2649
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002650/// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
2651static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) {
2652 // Get the set of diagnostic types from all of the operand classes.
2653 std::set<StringRef> Types;
Craig Topper6e526f12016-01-03 07:33:30 +00002654 for (const auto &OpClassEntry : Info.AsmOperandClasses) {
2655 if (!OpClassEntry.second->DiagnosticType.empty())
2656 Types.insert(OpClassEntry.second->DiagnosticType);
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002657 }
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002658 for (const auto &OpClassEntry : Info.RegisterClassClasses) {
2659 if (!OpClassEntry.second->DiagnosticType.empty())
2660 Types.insert(OpClassEntry.second->DiagnosticType);
2661 }
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002662
2663 if (Types.empty()) return;
2664
2665 // Now emit the enum entries.
Craig Topper6e526f12016-01-03 07:33:30 +00002666 for (StringRef Type : Types)
2667 OS << " Match_" << Type << ",\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002668 OS << " END_OPERAND_DIAGNOSTIC_TYPES\n";
2669}
2670
Jim Grosbach5117ef72012-04-24 22:40:08 +00002671/// emitGetSubtargetFeatureName - Emit the helper function to get the
2672/// user-level name for a subtarget feature.
2673static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
2674 OS << "// User-level names for subtarget features that participate in\n"
2675 << "// instruction matching.\n"
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002676 << "static const char *getSubtargetFeatureName(uint64_t Val) {\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002677 if (!Info.SubtargetFeatures.empty()) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002678 OS << " switch(Val) {\n";
Craig Topper42bd8192014-11-28 03:53:00 +00002679 for (const auto &SF : Info.SubtargetFeatures) {
David Blaikie9a9da992014-11-28 22:15:06 +00002680 const SubtargetFeatureInfo &SFI = SF.second;
Aaron Ballmane59e3582013-07-15 16:53:32 +00002681 // FIXME: Totally just a placeholder name to get the algorithm working.
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002682 OS << " case " << SFI.getEnumBitName() << ": return \""
Aaron Ballmane59e3582013-07-15 16:53:32 +00002683 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
2684 }
2685 OS << " default: return \"(unknown)\";\n";
2686 OS << " }\n";
2687 } else {
2688 // Nothing to emit, so skip the switch
2689 OS << " return \"(unknown)\";\n";
Jim Grosbach5117ef72012-04-24 22:40:08 +00002690 }
Aaron Ballmane59e3582013-07-15 16:53:32 +00002691 OS << "}\n\n";
Jim Grosbach5117ef72012-04-24 22:40:08 +00002692}
2693
Chris Lattner43690072010-10-30 20:15:02 +00002694static std::string GetAliasRequiredFeatures(Record *R,
2695 const AsmMatcherInfo &Info) {
Chris Lattner2cb092d2010-10-30 19:23:13 +00002696 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
Chris Lattner2cb092d2010-10-30 19:23:13 +00002697 std::string Result;
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002698
2699 if (ReqFeatures.empty())
2700 return Result;
2701
Chris Lattner2cb092d2010-10-30 19:23:13 +00002702 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
David Blaikie9a9da992014-11-28 22:15:06 +00002703 const SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002704
Craig Topper24064772014-04-15 07:20:03 +00002705 if (!F)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002706 PrintFatalError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
Chris Lattner517dc952010-11-01 02:09:21 +00002707 "' is not marked as an AssemblerPredicate!");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002708
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002709 if (i)
2710 Result += " && ";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002711
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002712 Result += "Features.test(" + F->getEnumBitName() + ')';
Chris Lattner2cb092d2010-10-30 19:23:13 +00002713 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002714
Chris Lattner2cb092d2010-10-30 19:23:13 +00002715 return Result;
2716}
2717
Chad Rosier9f7a2212013-04-18 22:35:36 +00002718static void emitMnemonicAliasVariant(raw_ostream &OS,const AsmMatcherInfo &Info,
2719 std::vector<Record*> &Aliases,
2720 unsigned Indent = 0,
2721 StringRef AsmParserVariantName = StringRef()){
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002722 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
2723 // iteration order of the map is stable.
2724 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002725
Craig Topper6e526f12016-01-03 07:33:30 +00002726 for (Record *R : Aliases) {
Chad Rosier9f7a2212013-04-18 22:35:36 +00002727 // FIXME: Allow AssemblerVariantName to be a comma separated list.
Craig Topperbcd3c372017-05-31 21:12:46 +00002728 StringRef AsmVariantName = R->getValueAsString("AsmVariantName");
Chad Rosier9f7a2212013-04-18 22:35:36 +00002729 if (AsmVariantName != AsmParserVariantName)
2730 continue;
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002731 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00002732 }
Chad Rosier9f7a2212013-04-18 22:35:36 +00002733 if (AliasesFromMnemonic.empty())
2734 return;
Vladimir Medic75429ad2013-07-16 09:22:38 +00002735
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002736 // Process each alias a "from" mnemonic at a time, building the code executed
2737 // by the string remapper.
2738 std::vector<StringMatcher::StringPair> Cases;
Craig Topper6e526f12016-01-03 07:33:30 +00002739 for (const auto &AliasEntry : AliasesFromMnemonic) {
2740 const std::vector<Record*> &ToVec = AliasEntry.second;
Chris Lattner2cb092d2010-10-30 19:23:13 +00002741
2742 // Loop through each alias and emit code that handles each case. If there
2743 // are two instructions without predicates, emit an error. If there is one,
2744 // emit it last.
2745 std::string MatchCode;
2746 int AliasWithNoPredicate = -1;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002747
Chris Lattner2cb092d2010-10-30 19:23:13 +00002748 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
2749 Record *R = ToVec[i];
Chris Lattner43690072010-10-30 20:15:02 +00002750 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002751
Chris Lattner2cb092d2010-10-30 19:23:13 +00002752 // If this unconditionally matches, remember it for later and diagnose
2753 // duplicates.
2754 if (FeatureMask.empty()) {
2755 if (AliasWithNoPredicate != -1) {
2756 // We can't have two aliases from the same mnemonic with no predicate.
2757 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
2758 "two MnemonicAliases with the same 'from' mnemonic!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002759 PrintFatalError(R->getLoc(), "this is the other MnemonicAlias.");
Chris Lattner2cb092d2010-10-30 19:23:13 +00002760 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002761
Chris Lattner2cb092d2010-10-30 19:23:13 +00002762 AliasWithNoPredicate = i;
2763 continue;
2764 }
Craig Topper6e526f12016-01-03 07:33:30 +00002765 if (R->getValueAsString("ToMnemonic") == AliasEntry.first)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002766 PrintFatalError(R->getLoc(), "MnemonicAlias to the same string");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002767
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00002768 if (!MatchCode.empty())
2769 MatchCode += "else ";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002770 MatchCode += "if (" + FeatureMask + ")\n";
Craig Topper2b8419a2017-05-31 19:01:11 +00002771 MatchCode += " Mnemonic = \"";
2772 MatchCode += R->getValueAsString("ToMnemonic");
2773 MatchCode += "\";\n";
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002774 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002775
Chris Lattner2cb092d2010-10-30 19:23:13 +00002776 if (AliasWithNoPredicate != -1) {
2777 Record *R = ToVec[AliasWithNoPredicate];
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00002778 if (!MatchCode.empty())
2779 MatchCode += "else\n ";
Craig Topper2b8419a2017-05-31 19:01:11 +00002780 MatchCode += "Mnemonic = \"";
2781 MatchCode += R->getValueAsString("ToMnemonic");
2782 MatchCode += "\";\n";
Chris Lattner2cb092d2010-10-30 19:23:13 +00002783 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002784
Chris Lattner2cb092d2010-10-30 19:23:13 +00002785 MatchCode += "return;";
2786
Craig Topper6e526f12016-01-03 07:33:30 +00002787 Cases.push_back(std::make_pair(AliasEntry.first, MatchCode));
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002788 }
Chad Rosier9f7a2212013-04-18 22:35:36 +00002789 StringMatcher("Mnemonic", Cases, OS).Emit(Indent);
2790}
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002791
Chad Rosier9f7a2212013-04-18 22:35:36 +00002792/// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
2793/// emit a function for them and return true, otherwise return false.
2794static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info,
2795 CodeGenTarget &Target) {
2796 // Ignore aliases when match-prefix is set.
2797 if (!MatchPrefix.empty())
2798 return false;
2799
2800 std::vector<Record*> Aliases =
2801 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
2802 if (Aliases.empty()) return false;
2803
2804 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002805 "const FeatureBitset &Features, unsigned VariantID) {\n";
Chad Rosier9f7a2212013-04-18 22:35:36 +00002806 OS << " switch (VariantID) {\n";
2807 unsigned VariantCount = Target.getAsmParserVariantCount();
2808 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2809 Record *AsmVariant = Target.getAsmParserVariant(VC);
2810 int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant");
Craig Topperbcd3c372017-05-31 21:12:46 +00002811 StringRef AsmParserVariantName = AsmVariant->getValueAsString("Name");
Chad Rosier9f7a2212013-04-18 22:35:36 +00002812 OS << " case " << AsmParserVariantNo << ":\n";
2813 emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2,
2814 AsmParserVariantName);
2815 OS << " break;\n";
2816 }
2817 OS << " }\n";
2818
2819 // Emit aliases that apply to all variants.
2820 emitMnemonicAliasVariant(OS, Info, Aliases);
2821
Daniel Dunbare46bc4c2011-01-18 01:59:30 +00002822 OS << "}\n\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002823
Chris Lattner477fba4f2010-10-30 18:48:18 +00002824 return true;
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00002825}
2826
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002827static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002828 const AsmMatcherInfo &Info, StringRef ClassName,
2829 StringToOffsetTable &StringTable,
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002830 unsigned MaxMnemonicIndex,
2831 unsigned MaxFeaturesIndex,
2832 bool HasMnemonicFirst) {
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002833 unsigned MaxMask = 0;
Craig Topper869cd5f2015-12-31 08:18:20 +00002834 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
2835 MaxMask |= OMI.OperandMask;
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002836 }
2837
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002838 // Emit the static custom operand parsing table;
2839 OS << "namespace {\n";
2840 OS << " struct OperandMatchEntry {\n";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002841 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
2842 << " Mnemonic;\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002843 OS << " " << getMinimalTypeForRange(MaxMask)
2844 << " OperandMask;\n";
David Blaikied749e342014-11-28 20:35:57 +00002845 OS << " " << getMinimalTypeForRange(std::distance(
2846 Info.Classes.begin(), Info.Classes.end())) << " Class;\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002847 OS << " " << getMinimalTypeForRange(MaxFeaturesIndex)
2848 << " RequiredFeaturesIdx;\n\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002849 OS << " StringRef getMnemonic() const {\n";
2850 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2851 OS << " MnemonicTable[Mnemonic]);\n";
2852 OS << " }\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002853 OS << " };\n\n";
2854
2855 OS << " // Predicate for searching for an opcode.\n";
2856 OS << " struct LessOpcodeOperand {\n";
2857 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002858 OS << " return LHS.getMnemonic() < RHS;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002859 OS << " }\n";
2860 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002861 OS << " return LHS < RHS.getMnemonic();\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002862 OS << " }\n";
2863 OS << " bool operator()(const OperandMatchEntry &LHS,";
2864 OS << " const OperandMatchEntry &RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002865 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002866 OS << " }\n";
2867 OS << " };\n";
2868
2869 OS << "} // end anonymous namespace.\n\n";
2870
2871 OS << "static const OperandMatchEntry OperandMatchTable["
2872 << Info.OperandMatchInfo.size() << "] = {\n";
2873
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002874 OS << " /* Operand List Mnemonic, Mask, Operand Class, Features */\n";
Craig Topper869cd5f2015-12-31 08:18:20 +00002875 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002876 const MatchableInfo &II = *OMI.MI;
2877
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002878 OS << " { ";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002879
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002880 // Store a pascal-style length byte in the mnemonic.
2881 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002882 OS << StringTable.GetOrAddStringOffset(LenMnemonic, false)
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002883 << " /* " << II.Mnemonic << " */, ";
2884
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002885 OS << OMI.OperandMask;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002886 OS << " /* ";
2887 bool printComma = false;
2888 for (int i = 0, e = 31; i !=e; ++i)
2889 if (OMI.OperandMask & (1 << i)) {
2890 if (printComma)
2891 OS << ", ";
2892 OS << i;
2893 printComma = true;
2894 }
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002895 OS << " */, ";
2896
2897 OS << OMI.CI->Name;
2898
2899 // Write the required features mask.
2900 OS << ", AMFBS";
2901 if (II.RequiredFeatures.empty())
2902 OS << "_None";
2903 else
2904 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i)
2905 OS << '_' << II.RequiredFeatures[i]->TheDef->getName();
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002906
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002907 OS << " },\n";
2908 }
2909 OS << "};\n\n";
2910
2911 // Emit the operand class switch to call the correct custom parser for
2912 // the found operand class.
Alex Bradbury58eba092016-11-01 16:32:05 +00002913 OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
David Blaikie960ea3f2014-06-08 16:18:35 +00002914 << "tryCustomParseOperand(OperandVector"
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002915 << " &Operands,\n unsigned MCK) {\n\n"
2916 << " switch(MCK) {\n";
2917
Craig Topperf34dad92014-11-28 03:53:02 +00002918 for (const auto &CI : Info.Classes) {
David Blaikied749e342014-11-28 20:35:57 +00002919 if (CI.ParserMethod.empty())
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002920 continue;
David Blaikied749e342014-11-28 20:35:57 +00002921 OS << " case " << CI.Name << ":\n"
2922 << " return " << CI.ParserMethod << "(Operands);\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002923 }
2924
2925 OS << " default:\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002926 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002927 OS << " }\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002928 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002929 OS << "}\n\n";
2930
2931 // Emit the static custom operand parser. This code is very similar with
2932 // the other matcher. Also use MatchResultTy here just in case we go for
2933 // a better error handling.
Alex Bradbury58eba092016-11-01 16:32:05 +00002934 OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
David Blaikie960ea3f2014-06-08 16:18:35 +00002935 << "MatchOperandParserImpl(OperandVector"
Sander de Smalencd6be962017-12-20 11:02:42 +00002936 << " &Operands,\n StringRef Mnemonic,\n"
2937 << " bool ParseForAllFeatures) {\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002938
2939 // Emit code to get the available features.
2940 OS << " // Get the current feature set.\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002941 OS << " const FeatureBitset &AvailableFeatures = getAvailableFeatures();\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002942
2943 OS << " // Get the next operand index.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00002944 OS << " unsigned NextOpNum = Operands.size()"
2945 << (HasMnemonicFirst ? " - 1" : "") << ";\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002946
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002947 // Emit code to search the table.
2948 OS << " // Search the table.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00002949 if (HasMnemonicFirst) {
2950 OS << " auto MnemonicRange =\n";
2951 OS << " std::equal_range(std::begin(OperandMatchTable), "
2952 "std::end(OperandMatchTable),\n";
2953 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2954 } else {
2955 OS << " auto MnemonicRange = std::make_pair(std::begin(OperandMatchTable),"
2956 " std::end(OperandMatchTable));\n";
2957 OS << " if (!Mnemonic.empty())\n";
2958 OS << " MnemonicRange =\n";
2959 OS << " std::equal_range(std::begin(OperandMatchTable), "
2960 "std::end(OperandMatchTable),\n";
2961 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2962 }
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002963
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002964 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002965 OS << " return MatchOperand_NoMatch;\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002966
2967 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2968 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2969
2970 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002971 OS << " assert(Mnemonic == it->getMnemonic());\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002972
2973 // Emit check that the required features are available.
2974 OS << " // check if the available features match\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002975 OS << " const FeatureBitset &RequiredFeatures = "
2976 "FeatureBitsets[it->RequiredFeaturesIdx];\n";
Sander de Smalencd6be962017-12-20 11:02:42 +00002977 OS << " if (!ParseForAllFeatures && (AvailableFeatures & "
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002978 "RequiredFeatures) != RequiredFeatures)\n";
Sander de Smalencd6be962017-12-20 11:02:42 +00002979 OS << " continue;\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002980
2981 // Emit check to ensure the operand number matches.
2982 OS << " // check if the operand in question has a custom parser.\n";
2983 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2984 OS << " continue;\n\n";
2985
2986 // Emit call to the custom parser method
2987 OS << " // call custom parse method to handle the operand\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002988 OS << " OperandMatchResultTy Result = ";
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002989 OS << "tryCustomParseOperand(Operands, it->Class);\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002990 OS << " if (Result != MatchOperand_NoMatch)\n";
2991 OS << " return Result;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002992 OS << " }\n\n";
2993
Jim Grosbach861e49c2011-02-12 01:34:40 +00002994 OS << " // Okay, we had no match.\n";
2995 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002996 OS << "}\n\n";
2997}
2998
Sander de Smalen886510f2018-01-10 10:10:56 +00002999static void emitAsmTiedOperandConstraints(CodeGenTarget &Target,
3000 AsmMatcherInfo &Info,
3001 raw_ostream &OS) {
Sander de Smalen118099a2018-06-18 13:39:29 +00003002 std::string AsmParserName =
3003 Info.AsmParser->getValueAsString("AsmParserClassName");
Sander de Smalen886510f2018-01-10 10:10:56 +00003004 OS << "static bool ";
Sander de Smalen118099a2018-06-18 13:39:29 +00003005 OS << "checkAsmTiedOperandConstraints(const " << Target.getName()
3006 << AsmParserName << "&AsmParser,\n";
3007 OS << " unsigned Kind,\n";
Sander de Smalen886510f2018-01-10 10:10:56 +00003008 OS << " const OperandVector &Operands,\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00003009 OS << " uint64_t &ErrorInfo) {\n";
3010 OS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
3011 OS << " const uint8_t *Converter = ConversionTable[Kind];\n";
3012 OS << " for (const uint8_t *p = Converter; *p; p+= 2) {\n";
3013 OS << " switch (*p) {\n";
3014 OS << " case CVT_Tied: {\n";
3015 OS << " unsigned OpIdx = *(p+1);\n";
Simon Pilgrime4d40f92018-02-17 12:29:47 +00003016 OS << " assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
3017 OS << " std::begin(TiedAsmOperandTable)) &&\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00003018 OS << " \"Tied operand not found\");\n";
3019 OS << " unsigned OpndNum1 = TiedAsmOperandTable[OpIdx][1];\n";
3020 OS << " unsigned OpndNum2 = TiedAsmOperandTable[OpIdx][2];\n";
3021 OS << " if (OpndNum1 != OpndNum2) {\n";
3022 OS << " auto &SrcOp1 = Operands[OpndNum1];\n";
3023 OS << " auto &SrcOp2 = Operands[OpndNum2];\n";
Sander de Smalen118099a2018-06-18 13:39:29 +00003024 OS << " if (SrcOp1->isReg() && SrcOp2->isReg()) {\n";
3025 OS << " if (!AsmParser.regsEqual(*SrcOp1, *SrcOp2)) {\n";
3026 OS << " ErrorInfo = OpndNum2;\n";
3027 OS << " return false;\n";
3028 OS << " }\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00003029 OS << " }\n";
3030 OS << " }\n";
3031 OS << " break;\n";
3032 OS << " }\n";
3033 OS << " default:\n";
3034 OS << " break;\n";
Sander de Smalen886510f2018-01-10 10:10:56 +00003035 OS << " }\n";
3036 OS << " }\n";
3037 OS << " return true;\n";
3038 OS << "}\n\n";
3039}
3040
Sjoerd Meijer6d14fdf2017-07-05 12:39:13 +00003041static void emitMnemonicSpellChecker(raw_ostream &OS, CodeGenTarget &Target,
3042 unsigned VariantCount) {
Craig Topper2a060282017-10-26 06:46:40 +00003043 OS << "static std::string " << Target.getName()
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003044 << "MnemonicSpellCheck(StringRef S, const FeatureBitset &FBS,"
3045 << " unsigned VariantID) {\n";
Sjoerd Meijer6d14fdf2017-07-05 12:39:13 +00003046 if (!VariantCount)
3047 OS << " return \"\";";
3048 else {
3049 OS << " const unsigned MaxEditDist = 2;\n";
3050 OS << " std::vector<StringRef> Candidates;\n";
Craig Topper05515562017-10-26 06:46:41 +00003051 OS << " StringRef Prev = \"\";\n\n";
3052
3053 OS << " // Find the appropriate table for this asm variant.\n";
3054 OS << " const MatchEntry *Start, *End;\n";
3055 OS << " switch (VariantID) {\n";
3056 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
3057 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3058 Record *AsmVariant = Target.getAsmParserVariant(VC);
3059 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3060 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3061 << "); End = std::end(MatchTable" << VC << "); break;\n";
3062 }
3063 OS << " }\n\n";
3064 OS << " for (auto I = Start; I < End; I++) {\n";
Sjoerd Meijer6d14fdf2017-07-05 12:39:13 +00003065 OS << " // Ignore unsupported instructions.\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003066 OS << " const FeatureBitset &RequiredFeatures = "
3067 "FeatureBitsets[I->RequiredFeaturesIdx];\n";
3068 OS << " if ((FBS & RequiredFeatures) != RequiredFeatures)\n";
Sjoerd Meijer6d14fdf2017-07-05 12:39:13 +00003069 OS << " continue;\n";
3070 OS << "\n";
3071 OS << " StringRef T = I->getMnemonic();\n";
3072 OS << " // Avoid recomputing the edit distance for the same string.\n";
3073 OS << " if (T.equals(Prev))\n";
3074 OS << " continue;\n";
3075 OS << "\n";
3076 OS << " Prev = T;\n";
3077 OS << " unsigned Dist = S.edit_distance(T, false, MaxEditDist);\n";
3078 OS << " if (Dist <= MaxEditDist)\n";
3079 OS << " Candidates.push_back(T);\n";
3080 OS << " }\n";
3081 OS << "\n";
3082 OS << " if (Candidates.empty())\n";
3083 OS << " return \"\";\n";
3084 OS << "\n";
3085 OS << " std::string Res = \", did you mean: \";\n";
3086 OS << " unsigned i = 0;\n";
3087 OS << " for( ; i < Candidates.size() - 1; i++)\n";
3088 OS << " Res += Candidates[i].str() + \", \";\n";
3089 OS << " return Res + Candidates[i].str() + \"?\";\n";
3090 }
3091 OS << "}\n";
3092 OS << "\n";
3093}
3094
3095
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003096// Emit a function mapping match classes to strings, for debugging.
3097static void emitMatchClassKindNames(std::forward_list<ClassInfo> &Infos,
3098 raw_ostream &OS) {
3099 OS << "#ifndef NDEBUG\n";
3100 OS << "const char *getMatchClassName(MatchClassKind Kind) {\n";
3101 OS << " switch (Kind) {\n";
3102
3103 OS << " case InvalidMatchClass: return \"InvalidMatchClass\";\n";
3104 OS << " case OptionalMatchClass: return \"OptionalMatchClass\";\n";
3105 for (const auto &CI : Infos) {
3106 OS << " case " << CI.Name << ": return \"" << CI.Name << "\";\n";
3107 }
3108 OS << " case NumMatchClassKinds: return \"NumMatchClassKinds\";\n";
3109
3110 OS << " }\n";
3111 OS << " llvm_unreachable(\"unhandled MatchClassKind!\");\n";
3112 OS << "}\n\n";
3113 OS << "#endif // NDEBUG\n";
3114}
3115
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003116static std::string
3117getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
3118 std::string Name = "AMFBS";
3119 for (const auto &Feature : FeatureBitset)
3120 Name += ("_" + Feature->getName()).str();
3121 return Name;
3122}
3123
Daniel Dunbard0470d72009-08-07 21:01:44 +00003124void AsmMatcherEmitter::run(raw_ostream &OS) {
Chris Lattner77d369c2010-12-13 00:23:57 +00003125 CodeGenTarget Target(Records);
Daniel Dunbard0470d72009-08-07 21:01:44 +00003126 Record *AsmParser = Target.getAsmParser();
Craig Topperbcd3c372017-05-31 21:12:46 +00003127 StringRef ClassName = AsmParser->getValueAsString("AsmParserClassName");
Daniel Dunbard0470d72009-08-07 21:01:44 +00003128
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003129 // Compute the information on the instructions to match.
Chris Lattner77d369c2010-12-13 00:23:57 +00003130 AsmMatcherInfo Info(AsmParser, Target, Records);
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003131 Info.buildInfo();
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003132
Daniel Dunbar3b8a4662010-02-02 23:46:36 +00003133 // Sort the instruction table using the partial order on classes. We use
3134 // stable_sort to ensure that ambiguous instructions are still
3135 // deterministically ordered.
Fangrui Songefd94c52019-04-23 14:51:27 +00003136 llvm::stable_sort(
3137 Info.Matchables,
3138 [](const std::unique_ptr<MatchableInfo> &a,
3139 const std::unique_ptr<MatchableInfo> &b) { return *a < *b; });
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003140
Matthias Brauna8eed312016-12-05 19:44:31 +00003141#ifdef EXPENSIVE_CHECKS
3142 // Verify that the table is sorted and operator < works transitively.
3143 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
3144 ++I) {
3145 for (auto J = I; J != E; ++J) {
3146 assert(!(**J < **I));
3147 }
3148 }
3149#endif
3150
Daniel Dunbar71330282009-08-08 05:24:34 +00003151 DEBUG_WITH_TYPE("instruction_info", {
Craig Topperf34dad92014-11-28 03:53:02 +00003152 for (const auto &MI : Info.Matchables)
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003153 MI->dump();
Daniel Dunbare10787e2009-08-07 08:26:05 +00003154 });
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003155
Chris Lattnerad776812010-11-01 05:06:45 +00003156 // Check for ambiguous matchables.
Chris Lattnerc0658cb2010-09-06 21:28:52 +00003157 DEBUG_WITH_TYPE("ambiguous_instrs", {
3158 unsigned NumAmbiguous = 0;
David Blaikie9a6f2832014-12-22 21:26:38 +00003159 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
3160 ++I) {
3161 for (auto J = std::next(I); J != E; ++J) {
3162 const MatchableInfo &A = **I;
3163 const MatchableInfo &B = **J;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003164
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003165 if (A.couldMatchAmbiguouslyWith(B)) {
Chris Lattnerad776812010-11-01 05:06:45 +00003166 errs() << "warning: ambiguous matchables:\n";
Chris Lattnerc0658cb2010-09-06 21:28:52 +00003167 A.dump();
3168 errs() << "\nis incomparable with:\n";
3169 B.dump();
3170 errs() << "\n\n";
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00003171 ++NumAmbiguous;
3172 }
Daniel Dunbarf573b562009-08-09 06:05:33 +00003173 }
Daniel Dunbar3239f022009-08-09 04:00:06 +00003174 }
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00003175 if (NumAmbiguous)
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003176 errs() << "warning: " << NumAmbiguous
Chris Lattnerad776812010-11-01 05:06:45 +00003177 << " ambiguous matchables!\n";
Chris Lattnerc0658cb2010-09-06 21:28:52 +00003178 });
Daniel Dunbar3239f022009-08-09 04:00:06 +00003179
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003180 // Compute the information on the custom operand parsing.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003181 Info.buildOperandMatchInfo();
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003182
Craig Topperfd2c6a32015-12-31 08:18:23 +00003183 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
Sam Kolton5f10a132016-05-06 11:31:17 +00003184 bool HasOptionalOperands = Info.hasOptionalOperands();
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003185 bool ReportMultipleNearMisses =
3186 AsmParser->getValueAsBit("ReportMultipleNearMisses");
Craig Topperfd2c6a32015-12-31 08:18:23 +00003187
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00003188 // Write the output.
3189
Chris Lattner3e4582a2010-09-06 19:11:01 +00003190 // Information for the class declaration.
3191 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
3192 OS << "#undef GET_ASSEMBLER_HEADER\n";
Jim Grosbach860a84d2011-02-11 21:31:55 +00003193 OS << " // This should be included into the middle of the declaration of\n";
Evan Cheng11424442011-07-26 00:24:13 +00003194 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003195 OS << " FeatureBitset ComputeAvailableFeatures(const FeatureBitset& FB) const;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003196 if (HasOptionalOperands) {
3197 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
3198 << "unsigned Opcode,\n"
3199 << " const OperandVector &Operands,\n"
3200 << " const SmallBitVector &OptionalOperandsMask);\n";
3201 } else {
3202 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
3203 << "unsigned Opcode,\n"
3204 << " const OperandVector &Operands);\n";
3205 }
Chad Rosier380a74a2012-10-02 00:25:57 +00003206 OS << " void convertToMapAndConstraints(unsigned Kind,\n ";
Peter Collingbourne0da86302016-10-10 22:49:37 +00003207 OS << " const OperandVector &Operands) override;\n";
Craig Toppera5754e62015-01-03 08:16:29 +00003208 OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003209 << " MCInst &Inst,\n";
3210 if (ReportMultipleNearMisses)
3211 OS << " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
3212 else
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003213 OS << " uint64_t &ErrorInfo,\n"
3214 << " FeatureBitset &MissingFeatures,\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003215 OS << " bool matchingInlineAsm,\n"
Chad Rosier380a74a2012-10-02 00:25:57 +00003216 << " unsigned VariantID = 0);\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003217 if (!ReportMultipleNearMisses)
3218 OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
3219 << " MCInst &Inst,\n"
3220 << " uint64_t &ErrorInfo,\n"
3221 << " bool matchingInlineAsm,\n"
3222 << " unsigned VariantID = 0) {\n"
3223 << " FeatureBitset MissingFeatures;\n"
3224 << " return MatchInstructionImpl(Operands, Inst, ErrorInfo, MissingFeatures,\n"
3225 << " matchingInlineAsm, VariantID);\n"
3226 << " }\n\n";
3227
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003228
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003229 if (!Info.OperandMatchInfo.empty()) {
Jim Grosbach861e49c2011-02-12 01:34:40 +00003230 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00003231 OS << " OperandVector &Operands,\n";
Sander de Smalencd6be962017-12-20 11:02:42 +00003232 OS << " StringRef Mnemonic,\n";
3233 OS << " bool ParseForAllFeatures = false);\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003234
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00003235 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00003236 OS << " OperandVector &Operands,\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003237 OS << " unsigned MCK);\n\n";
3238 }
3239
Chris Lattner3e4582a2010-09-06 19:11:01 +00003240 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
3241
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00003242 // Emit the operand match diagnostic enum names.
3243 OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
3244 OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3245 emitOperandDiagnosticTypes(Info, OS);
3246 OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3247
Chris Lattner3e4582a2010-09-06 19:11:01 +00003248 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
3249 OS << "#undef GET_REGISTER_MATCHER\n\n";
3250
Daniel Dunbareefe8612010-07-19 05:44:09 +00003251 // Emit the subtarget feature enumeration.
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003252 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(
Daniel Sanders72db2a32016-11-19 13:05:44 +00003253 Info.SubtargetFeatures, OS);
Daniel Dunbareefe8612010-07-19 05:44:09 +00003254
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00003255 // Emit the function to match a register name to number.
Akira Hatanaka7605630c2012-08-17 20:16:42 +00003256 // This should be omitted for Mips target
3257 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName"))
3258 emitMatchRegisterName(Target, AsmParser, OS);
Chris Lattner3e4582a2010-09-06 19:11:01 +00003259
Dylan McKaybff960a2016-02-03 10:30:16 +00003260 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterAltName"))
3261 emitMatchRegisterAltName(Target, AsmParser, OS);
3262
Chris Lattner3e4582a2010-09-06 19:11:01 +00003263 OS << "#endif // GET_REGISTER_MATCHER\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003264
Craig Topper3ec7c2a2012-04-25 06:56:34 +00003265 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
3266 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00003267
Jim Grosbach5117ef72012-04-24 22:40:08 +00003268 // Generate the helper function to get the names for subtarget features.
3269 emitGetSubtargetFeatureName(Info, OS);
3270
Craig Topper3ec7c2a2012-04-25 06:56:34 +00003271 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
3272
3273 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
3274 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
3275
Chris Lattner477fba4f2010-10-30 18:48:18 +00003276 // Generate the function that remaps for mnemonic aliases.
Chad Rosier9f7a2212013-04-18 22:35:36 +00003277 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00003278
Chad Rosierf4e35dc2012-10-01 23:45:51 +00003279 // Generate the convertToMCInst function to convert operands into an MCInst.
3280 // Also, generate the convertToMapAndConstraints function for MS-style inline
3281 // assembly. The latter doesn't actually generate a MCInst.
Craig Topperb64f9152019-04-02 20:52:04 +00003282 unsigned NumConverters = emitConvertFuncs(Target, ClassName, Info.Matchables,
3283 HasMnemonicFirst,
3284 HasOptionalOperands, OS);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003285
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003286 // Emit the enumeration for classes which participate in matching.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003287 emitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003288
Oliver Stannard41dfac32017-10-03 14:34:57 +00003289 // Emit a function to get the user-visible string to describe an operand
3290 // match failure in diagnostics.
3291 emitOperandMatchErrorDiagStrings(Info, OS);
3292
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00003293 // Emit a function to map register classes to operand match failure codes.
3294 emitRegisterMatchErrorFunc(Info, OS);
3295
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003296 // Emit the routine to match token strings to their match class.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003297 emitMatchTokenString(Target, Info.Classes, OS);
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003298
Daniel Dunbar2587b612009-08-10 16:05:47 +00003299 // Emit the subclass predicate routine.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003300 emitIsSubclass(Target, Info.Classes, OS);
Daniel Dunbar2587b612009-08-10 16:05:47 +00003301
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00003302 // Emit the routine to validate an operand against a match class.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003303 emitValidateOperandClass(Info, OS);
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00003304
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003305 emitMatchClassKindNames(Info.Classes, OS);
3306
Daniel Dunbareefe8612010-07-19 05:44:09 +00003307 // Emit the available features compute function.
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003308 SubtargetFeatureInfo::emitComputeAssemblerAvailableFeatures(
Daniel Sanders72db2a32016-11-19 13:05:44 +00003309 Info.Target.getName(), ClassName, "ComputeAvailableFeatures",
3310 Info.SubtargetFeatures, OS);
Daniel Dunbareefe8612010-07-19 05:44:09 +00003311
Sander de Smalen886510f2018-01-10 10:10:56 +00003312 if (!ReportMultipleNearMisses)
3313 emitAsmTiedOperandConstraints(Target, Info, OS);
3314
Craig Toppere2cfeb32012-09-18 06:10:45 +00003315 StringToOffsetTable StringTable;
3316
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003317 size_t MaxNumOperands = 0;
Craig Toppere2cfeb32012-09-18 06:10:45 +00003318 unsigned MaxMnemonicIndex = 0;
Joey Gouly0e76fa72013-09-12 10:28:05 +00003319 bool HasDeprecation = false;
Craig Topperf34dad92014-11-28 03:53:02 +00003320 for (const auto &MI : Info.Matchables) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003321 MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
3322 HasDeprecation |= MI->HasDeprecation;
Craig Toppere2cfeb32012-09-18 06:10:45 +00003323
3324 // Store a pascal-style length byte in the mnemonic.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003325 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
Craig Toppere2cfeb32012-09-18 06:10:45 +00003326 MaxMnemonicIndex = std::max(MaxMnemonicIndex,
3327 StringTable.GetOrAddStringOffset(LenMnemonic, false));
3328 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003329
Craig Topper7ecfa6d2012-09-18 07:02:21 +00003330 OS << "static const char *const MnemonicTable =\n";
3331 StringTable.EmitString(OS);
3332 OS << ";\n\n";
3333
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003334 std::vector<std::vector<Record *>> FeatureBitsets;
3335 for (const auto &MI : Info.Matchables) {
3336 if (MI->RequiredFeatures.empty())
3337 continue;
3338 FeatureBitsets.emplace_back();
3339 for (unsigned I = 0, E = MI->RequiredFeatures.size(); I != E; ++I)
3340 FeatureBitsets.back().push_back(MI->RequiredFeatures[I]->TheDef);
3341 }
3342
3343 llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
3344 const std::vector<Record *> &B) {
3345 if (A.size() < B.size())
3346 return true;
3347 if (A.size() > B.size())
3348 return false;
3349 for (const auto &Pair : zip(A, B)) {
3350 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
3351 return true;
3352 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
3353 return false;
3354 }
3355 return false;
3356 });
3357 FeatureBitsets.erase(
3358 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
3359 FeatureBitsets.end());
3360 OS << "// Feature bitsets.\n"
3361 << "enum : " << getMinimalTypeForRange(FeatureBitsets.size()) << " {\n"
3362 << " AMFBS_None,\n";
3363 for (const auto &FeatureBitset : FeatureBitsets) {
3364 if (FeatureBitset.empty())
3365 continue;
3366 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
3367 }
3368 OS << "};\n\n"
Benjamin Kramer16b32292019-08-24 15:02:44 +00003369 << "static constexpr FeatureBitset FeatureBitsets[] = {\n"
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003370 << " {}, // AMFBS_None\n";
3371 for (const auto &FeatureBitset : FeatureBitsets) {
3372 if (FeatureBitset.empty())
3373 continue;
3374 OS << " {";
3375 for (const auto &Feature : FeatureBitset) {
3376 const auto &I = Info.SubtargetFeatures.find(Feature);
3377 assert(I != Info.SubtargetFeatures.end() && "Didn't import predicate?");
3378 OS << I->second.getEnumBitName() << ", ";
3379 }
3380 OS << "},\n";
3381 }
3382 OS << "};\n\n";
3383
Simon Pilgrim6bdc7552017-03-31 10:59:37 +00003384 // Emit the static match table; unused classes get initialized to 0 which is
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003385 // guaranteed to be InvalidMatchClass.
3386 //
3387 // FIXME: We can reduce the size of this table very easily. First, we change
3388 // it so that store the kinds in separate bit-fields for each index, which
3389 // only needs to be the max width used for classes at that index (we also need
3390 // to reject based on this during classification). If we then make sure to
3391 // order the match kinds appropriately (putting mnemonics last), then we
3392 // should only end up using a few bits for each class, especially the ones
3393 // following the mnemonic.
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003394 OS << "namespace {\n";
3395 OS << " struct MatchEntry {\n";
Craig Toppere2cfeb32012-09-18 06:10:45 +00003396 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
3397 << " Mnemonic;\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003398 OS << " uint16_t Opcode;\n";
Craig Topperb64f9152019-04-02 20:52:04 +00003399 OS << " " << getMinimalTypeForRange(NumConverters)
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003400 << " ConvertFn;\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003401 OS << " " << getMinimalTypeForRange(FeatureBitsets.size())
3402 << " RequiredFeaturesIdx;\n";
David Blaikied749e342014-11-28 20:35:57 +00003403 OS << " " << getMinimalTypeForRange(
3404 std::distance(Info.Classes.begin(), Info.Classes.end()))
3405 << " Classes[" << MaxNumOperands << "];\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003406 OS << " StringRef getMnemonic() const {\n";
3407 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
3408 OS << " MnemonicTable[Mnemonic]);\n";
3409 OS << " }\n";
Chris Lattner81301972010-09-06 21:22:45 +00003410 OS << " };\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003411
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003412 OS << " // Predicate for searching for an opcode.\n";
Chris Lattner81301972010-09-06 21:22:45 +00003413 OS << " struct LessOpcode {\n";
3414 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003415 OS << " return LHS.getMnemonic() < RHS;\n";
Chris Lattner81301972010-09-06 21:22:45 +00003416 OS << " }\n";
3417 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003418 OS << " return LHS < RHS.getMnemonic();\n";
Chris Lattner81301972010-09-06 21:22:45 +00003419 OS << " }\n";
Chris Lattner62823362010-09-07 06:10:48 +00003420 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003421 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Chris Lattner62823362010-09-07 06:10:48 +00003422 OS << " }\n";
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003423 OS << " };\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003424
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003425 OS << "} // end anonymous namespace.\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003426
Craig Topper690d8ea2013-07-24 07:33:14 +00003427 unsigned VariantCount = Target.getAsmParserVariantCount();
3428 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3429 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topper690d8ea2013-07-24 07:33:14 +00003430 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003431
Craig Topper690d8ea2013-07-24 07:33:14 +00003432 OS << "static const MatchEntry MatchTable" << VC << "[] = {\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003433
Craig Topperf34dad92014-11-28 03:53:02 +00003434 for (const auto &MI : Info.Matchables) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003435 if (MI->AsmVariantID != AsmVariantNo)
Craig Topper690d8ea2013-07-24 07:33:14 +00003436 continue;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003437
Craig Topper690d8ea2013-07-24 07:33:14 +00003438 // Store a pascal-style length byte in the mnemonic.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003439 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
Craig Topper690d8ea2013-07-24 07:33:14 +00003440 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003441 << " /* " << MI->Mnemonic << " */, "
Craig Topper2b347eb2017-07-07 05:19:25 +00003442 << Target.getInstNamespace() << "::"
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003443 << MI->getResultInst()->TheDef->getName() << ", "
3444 << MI->ConversionFnKind << ", ";
Craig Topper690d8ea2013-07-24 07:33:14 +00003445
3446 // Write the required features mask.
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003447 OS << "AMFBS";
3448 if (MI->RequiredFeatures.empty())
3449 OS << "_None";
3450 else
3451 for (unsigned i = 0, e = MI->RequiredFeatures.size(); i != e; ++i)
3452 OS << '_' << MI->RequiredFeatures[i]->TheDef->getName();
Craig Topper690d8ea2013-07-24 07:33:14 +00003453
3454 OS << ", { ";
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003455 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
3456 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
Craig Topper690d8ea2013-07-24 07:33:14 +00003457
3458 if (i) OS << ", ";
3459 OS << Op.Class->Name;
Daniel Dunbareefe8612010-07-19 05:44:09 +00003460 }
Craig Topper690d8ea2013-07-24 07:33:14 +00003461 OS << " }, },\n";
Craig Topper4de73732012-04-02 07:48:39 +00003462 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003463
Craig Topper690d8ea2013-07-24 07:33:14 +00003464 OS << "};\n\n";
3465 }
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003466
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003467 OS << "#include \"llvm/Support/Debug.h\"\n";
3468 OS << "#include \"llvm/Support/Format.h\"\n\n";
3469
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003470 // Finally, build the match function.
David Blaikie960ea3f2014-06-08 16:18:35 +00003471 OS << "unsigned " << Target.getName() << ClassName << "::\n"
Craig Toppera5754e62015-01-03 08:16:29 +00003472 << "MatchInstructionImpl(const OperandVector &Operands,\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003473 OS << " MCInst &Inst,\n";
3474 if (ReportMultipleNearMisses)
3475 OS << " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
3476 else
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003477 OS << " uint64_t &ErrorInfo,\n"
3478 << " FeatureBitset &MissingFeatures,\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003479 OS << " bool matchingInlineAsm, unsigned VariantID) {\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00003480
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003481 if (!ReportMultipleNearMisses) {
3482 OS << " // Eliminate obvious mismatches.\n";
3483 OS << " if (Operands.size() > "
3484 << (MaxNumOperands + HasMnemonicFirst) << ") {\n";
3485 OS << " ErrorInfo = "
3486 << (MaxNumOperands + HasMnemonicFirst) << ";\n";
3487 OS << " return Match_InvalidOperand;\n";
3488 OS << " }\n\n";
3489 }
Chad Rosiereac13a32012-08-30 21:43:05 +00003490
Daniel Dunbareefe8612010-07-19 05:44:09 +00003491 // Emit code to get the available features.
3492 OS << " // Get the current feature set.\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003493 OS << " const FeatureBitset &AvailableFeatures = getAvailableFeatures();\n\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00003494
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00003495 OS << " // Get the instruction mnemonic, which is the first token.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003496 if (HasMnemonicFirst) {
3497 OS << " StringRef Mnemonic = ((" << Target.getName()
3498 << "Operand&)*Operands[0]).getToken();\n\n";
3499 } else {
3500 OS << " StringRef Mnemonic;\n";
3501 OS << " if (Operands[0]->isToken())\n";
3502 OS << " Mnemonic = ((" << Target.getName()
3503 << "Operand&)*Operands[0]).getToken();\n\n";
3504 }
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00003505
Chris Lattner477fba4f2010-10-30 18:48:18 +00003506 if (HasMnemonicAliases) {
3507 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
Chad Rosier9f7a2212013-04-18 22:35:36 +00003508 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n";
Chris Lattner477fba4f2010-10-30 18:48:18 +00003509 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00003510
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003511 // Emit code to compute the class list for this operand vector.
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003512 if (!ReportMultipleNearMisses) {
3513 OS << " // Some state to try to produce better error messages.\n";
3514 OS << " bool HadMatchOtherThanFeatures = false;\n";
3515 OS << " bool HadMatchOtherThanPredicate = false;\n";
3516 OS << " unsigned RetCode = Match_InvalidOperand;\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003517 OS << " MissingFeatures.set();\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003518 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
3519 OS << " // wrong for all instances of the instruction.\n";
3520 OS << " ErrorInfo = ~0ULL;\n";
3521 }
3522
Sam Kolton5f10a132016-05-06 11:31:17 +00003523 if (HasOptionalOperands) {
3524 OS << " SmallBitVector OptionalOperandsMask(" << MaxNumOperands << ");\n";
3525 }
Chris Lattner81301972010-09-06 21:22:45 +00003526
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003527 // Emit code to search the table.
Craig Topper690d8ea2013-07-24 07:33:14 +00003528 OS << " // Find the appropriate table for this asm variant.\n";
3529 OS << " const MatchEntry *Start, *End;\n";
3530 OS << " switch (VariantID) {\n";
Craig Topper8c714d12015-01-03 08:16:14 +00003531 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
Craig Topper690d8ea2013-07-24 07:33:14 +00003532 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3533 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topper690d8ea2013-07-24 07:33:14 +00003534 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Benjamin Kramer502b9e12014-04-12 16:15:53 +00003535 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3536 << "); End = std::end(MatchTable" << VC << "); break;\n";
Craig Topper690d8ea2013-07-24 07:33:14 +00003537 }
3538 OS << " }\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003539
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003540 OS << " // Search the table.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003541 if (HasMnemonicFirst) {
3542 OS << " auto MnemonicRange = "
3543 "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
3544 } else {
3545 OS << " auto MnemonicRange = std::make_pair(Start, End);\n";
3546 OS << " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
3547 OS << " if (!Mnemonic.empty())\n";
3548 OS << " MnemonicRange = "
3549 "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
3550 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003551
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003552 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"AsmMatcher: found \" <<\n"
3553 << " std::distance(MnemonicRange.first, MnemonicRange.second) << \n"
3554 << " \" encodings with mnemonic '\" << Mnemonic << \"'\\n\");\n\n";
3555
Chris Lattner628fbec2010-09-06 21:54:15 +00003556 OS << " // Return a more specific error code if no mnemonics match.\n";
3557 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
3558 OS << " return Match_MnemonicFail;\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003559
Chris Lattner81301972010-09-06 21:22:45 +00003560 OS << " for (const MatchEntry *it = MnemonicRange.first, "
Chris Lattner9026ac02010-09-06 21:23:43 +00003561 << "*ie = MnemonicRange.second;\n";
Chris Lattner81301972010-09-06 21:22:45 +00003562 OS << " it != ie; ++it) {\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003563 OS << " const FeatureBitset &RequiredFeatures = "
3564 "FeatureBitsets[it->RequiredFeaturesIdx];\n";
Sander de Smalencd6be962017-12-20 11:02:42 +00003565 OS << " bool HasRequiredFeatures =\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003566 OS << " (AvailableFeatures & RequiredFeatures) == RequiredFeatures;\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003567 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Trying to match opcode \"\n";
3568 OS << " << MII.getName(it->Opcode) << \"\\n\");\n";
3569
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003570 if (ReportMultipleNearMisses) {
3571 OS << " // Some state to record ways in which this instruction did not match.\n";
3572 OS << " NearMissInfo OperandNearMiss = NearMissInfo::getSuccess();\n";
3573 OS << " NearMissInfo FeaturesNearMiss = NearMissInfo::getSuccess();\n";
3574 OS << " NearMissInfo EarlyPredicateNearMiss = NearMissInfo::getSuccess();\n";
3575 OS << " NearMissInfo LatePredicateNearMiss = NearMissInfo::getSuccess();\n";
Oliver Stannard7ab60602017-12-04 13:42:22 +00003576 OS << " bool MultipleInvalidOperands = false;\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003577 }
3578
Craig Topperfd2c6a32015-12-31 08:18:23 +00003579 if (HasMnemonicFirst) {
3580 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
3581 OS << " assert(Mnemonic == it->getMnemonic());\n";
3582 }
3583
Daniel Dunbareefe8612010-07-19 05:44:09 +00003584 // Emit check that the subclasses match.
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003585 if (!ReportMultipleNearMisses)
3586 OS << " bool OperandsValid = true;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003587 if (HasOptionalOperands) {
3588 OS << " OptionalOperandsMask.reset(0, " << MaxNumOperands << ");\n";
3589 }
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003590 OS << " for (unsigned FormalIdx = " << (HasMnemonicFirst ? "0" : "SIndex")
3591 << ", ActualIdx = " << (HasMnemonicFirst ? "1" : "SIndex")
3592 << "; FormalIdx != " << MaxNumOperands << "; ++FormalIdx) {\n";
3593 OS << " auto Formal = "
3594 << "static_cast<MatchClassKind>(it->Classes[FormalIdx]);\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003595 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3596 OS << " dbgs() << \" Matching formal operand class \" << getMatchClassName(Formal)\n";
3597 OS << " << \" against actual operand at index \" << ActualIdx);\n";
3598 OS << " if (ActualIdx < Operands.size())\n";
3599 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \" (\";\n";
3600 OS << " Operands[ActualIdx]->print(dbgs()); dbgs() << \"): \");\n";
3601 OS << " else\n";
3602 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \": \");\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003603 OS << " if (ActualIdx >= Operands.size()) {\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003604 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"actual operand index out of range \");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003605 if (ReportMultipleNearMisses) {
3606 OS << " bool ThisOperandValid = (Formal == " <<"InvalidMatchClass) || "
3607 "isSubclass(Formal, OptionalMatchClass);\n";
3608 OS << " if (!ThisOperandValid) {\n";
3609 OS << " if (!OperandNearMiss) {\n";
3610 OS << " // Record info about match failure for later use.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003611 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"recording too-few-operands near miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003612 OS << " OperandNearMiss =\n";
3613 OS << " NearMissInfo::getTooFewOperands(Formal, it->Opcode);\n";
Oliver Stannard1e73e952017-11-21 15:16:50 +00003614 OS << " } else if (OperandNearMiss.getKind() != NearMissInfo::NearMissTooFewOperands) {\n";
Oliver Stannard7ab60602017-12-04 13:42:22 +00003615 OS << " // If more than one operand is invalid, give up on this match entry.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003616 OS << " DEBUG_WITH_TYPE(\n";
3617 OS << " \"asm-matcher\",\n";
3618 OS << " dbgs() << \"second invalid operand, giving up on this opcode\\n\");\n";
Oliver Stannard7ab60602017-12-04 13:42:22 +00003619 OS << " MultipleInvalidOperands = true;\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003620 OS << " break;\n";
3621 OS << " }\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003622 OS << " } else {\n";
3623 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"but formal operand not required\\n\");\n";
Oliver Stannard6e943312017-11-21 15:12:05 +00003624 OS << " break;\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003625 OS << " }\n";
3626 OS << " continue;\n";
3627 } else {
3628 OS << " OperandsValid = (Formal == InvalidMatchClass) || isSubclass(Formal, OptionalMatchClass);\n";
3629 OS << " if (!OperandsValid) ErrorInfo = ActualIdx;\n";
3630 if (HasOptionalOperands) {
3631 OS << " OptionalOperandsMask.set(FormalIdx, " << MaxNumOperands
3632 << ");\n";
3633 }
3634 OS << " break;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003635 }
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00003636 OS << " }\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003637 OS << " MCParsedAsmOperand &Actual = *Operands[ActualIdx];\n";
Colin LeMahieu23403c22015-11-09 00:46:46 +00003638 OS << " unsigned Diag = validateOperandClass(Actual, Formal);\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003639 OS << " if (Diag == Match_Success) {\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003640 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3641 OS << " dbgs() << \"match success using generic matcher\\n\");\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003642 OS << " ++ActualIdx;\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00003643 OS << " continue;\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003644 OS << " }\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003645 OS << " // If the generic handler indicates an invalid operand\n";
3646 OS << " // failure, check for a special case.\n";
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00003647 OS << " if (Diag != Match_Success) {\n";
3648 OS << " unsigned TargetDiag = validateTargetOperandClass(Actual, Formal);\n";
3649 OS << " if (TargetDiag == Match_Success) {\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003650 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3651 OS << " dbgs() << \"match success using target matcher\\n\");\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003652 OS << " ++ActualIdx;\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003653 OS << " continue;\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003654 OS << " }\n";
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00003655 OS << " // If the target matcher returned a specific error code use\n";
3656 OS << " // that, else use the one from the generic matcher.\n";
Sander de Smalencd6be962017-12-20 11:02:42 +00003657 OS << " if (TargetDiag != Match_InvalidOperand && "
3658 "HasRequiredFeatures)\n";
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00003659 OS << " Diag = TargetDiag;\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003660 OS << " }\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003661 OS << " // If current formal operand wasn't matched and it is optional\n"
3662 << " // then try to match next formal operand\n";
3663 OS << " if (Diag == Match_InvalidOperand "
Sam Kolton5f10a132016-05-06 11:31:17 +00003664 << "&& isSubclass(Formal, OptionalMatchClass)) {\n";
3665 if (HasOptionalOperands) {
3666 OS << " OptionalOperandsMask.set(FormalIdx);\n";
3667 }
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003668 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"ignoring optional operand\\n\");\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003669 OS << " continue;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003670 OS << " }\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003671
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003672 if (ReportMultipleNearMisses) {
3673 OS << " if (!OperandNearMiss) {\n";
3674 OS << " // If this is the first invalid operand we have seen, record some\n";
3675 OS << " // information about it.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003676 OS << " DEBUG_WITH_TYPE(\n";
3677 OS << " \"asm-matcher\",\n";
3678 OS << " dbgs()\n";
3679 OS << " << \"operand match failed, recording near-miss with diag code \"\n";
3680 OS << " << Diag << \"\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003681 OS << " OperandNearMiss =\n";
3682 OS << " NearMissInfo::getMissedOperand(Diag, Formal, it->Opcode, ActualIdx);\n";
3683 OS << " ++ActualIdx;\n";
3684 OS << " } else {\n";
3685 OS << " // If more than one operand is invalid, give up on this match entry.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003686 OS << " DEBUG_WITH_TYPE(\n";
3687 OS << " \"asm-matcher\",\n";
3688 OS << " dbgs() << \"second operand mismatch, skipping this opcode\\n\");\n";
Oliver Stannard7ab60602017-12-04 13:42:22 +00003689 OS << " MultipleInvalidOperands = true;\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003690 OS << " break;\n";
3691 OS << " }\n";
3692 OS << " }\n\n";
3693 } else {
3694 OS << " // If this operand is broken for all of the instances of this\n";
3695 OS << " // mnemonic, keep track of it so we can report loc info.\n";
3696 OS << " // If we already had a match that only failed due to a\n";
3697 OS << " // target predicate, that diagnostic is preferred.\n";
3698 OS << " if (!HadMatchOtherThanPredicate &&\n";
3699 OS << " (it == MnemonicRange.first || ErrorInfo <= ActualIdx)) {\n";
Sander de Smalencd6be962017-12-20 11:02:42 +00003700 OS << " if (HasRequiredFeatures && (ErrorInfo != ActualIdx || Diag "
3701 "!= Match_InvalidOperand))\n";
Sander de Smalen4acd57e2017-11-21 15:07:43 +00003702 OS << " RetCode = Diag;\n";
Sander de Smalen14e36ee2017-12-14 16:09:48 +00003703 OS << " ErrorInfo = ActualIdx;\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003704 OS << " }\n";
3705 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
3706 OS << " OperandsValid = false;\n";
3707 OS << " break;\n";
3708 OS << " }\n\n";
3709 }
3710
Oliver Stannard7ab60602017-12-04 13:42:22 +00003711 if (ReportMultipleNearMisses)
3712 OS << " if (MultipleInvalidOperands) {\n";
3713 else
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003714 OS << " if (!OperandsValid) {\n";
Oliver Stannard7ab60602017-12-04 13:42:22 +00003715 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3716 OS << " \"operand mismatches, ignoring \"\n";
3717 OS << " \"this opcode\\n\");\n";
3718 OS << " continue;\n";
3719 OS << " }\n";
Chris Lattnerb4be28f2010-09-06 20:08:02 +00003720
3721 // Emit check that the required features are available.
Sander de Smalencd6be962017-12-20 11:02:42 +00003722 OS << " if (!HasRequiredFeatures) {\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003723 if (!ReportMultipleNearMisses)
3724 OS << " HadMatchOtherThanFeatures = true;\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003725 OS << " FeatureBitset NewMissingFeatures = RequiredFeatures & "
Jim Grosbach9ec06a152012-06-18 19:45:46 +00003726 "~AvailableFeatures;\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003727 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Missing target features:\";\n";
3728 OS << " for (unsigned I = 0, E = NewMissingFeatures.size(); I != E; ++I)\n";
3729 OS << " if (NewMissingFeatures[I])\n";
3730 OS << " dbgs() << ' ' << I;\n";
3731 OS << " dbgs() << \"\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003732 if (ReportMultipleNearMisses) {
3733 OS << " FeaturesNearMiss = NearMissInfo::getMissedFeature(NewMissingFeatures);\n";
3734 } else {
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003735 OS << " if (NewMissingFeatures.count() <=\n"
3736 " MissingFeatures.count())\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003737 OS << " MissingFeatures = NewMissingFeatures;\n";
3738 OS << " continue;\n";
3739 }
Chris Lattnerb4be28f2010-09-06 20:08:02 +00003740 OS << " }\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003741 OS << "\n";
Ahmed Bougacha0dc19792014-12-16 18:05:28 +00003742 OS << " Inst.clear();\n\n";
Daniel Sandersc5537422016-07-27 13:49:44 +00003743 OS << " Inst.setOpcode(it->Opcode);\n";
3744 // Verify the instruction with the target-specific match predicate function.
3745 OS << " // We have a potential match but have not rendered the operands.\n"
3746 << " // Check the target predicate to handle any context sensitive\n"
3747 " // constraints.\n"
3748 << " // For example, Ties that are referenced multiple times must be\n"
3749 " // checked here to ensure the input is the same for each match\n"
3750 " // constraints. If we leave it any later the ties will have been\n"
3751 " // canonicalized\n"
3752 << " unsigned MatchResult;\n"
3753 << " if ((MatchResult = checkEarlyTargetMatchPredicate(Inst, "
3754 "Operands)) != Match_Success) {\n"
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003755 << " Inst.clear();\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003756 OS << " DEBUG_WITH_TYPE(\n";
3757 OS << " \"asm-matcher\",\n";
3758 OS << " dbgs() << \"Early target match predicate failed with diag code \"\n";
3759 OS << " << MatchResult << \"\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003760 if (ReportMultipleNearMisses) {
3761 OS << " EarlyPredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
3762 } else {
3763 OS << " RetCode = MatchResult;\n"
3764 << " HadMatchOtherThanPredicate = true;\n"
3765 << " continue;\n";
3766 }
3767 OS << " }\n\n";
3768
3769 if (ReportMultipleNearMisses) {
3770 OS << " // If we did not successfully match the operands, then we can't convert to\n";
3771 OS << " // an MCInst, so bail out on this instruction variant now.\n";
3772 OS << " if (OperandNearMiss) {\n";
3773 OS << " // If the operand mismatch was the only problem, reprrt it as a near-miss.\n";
3774 OS << " if (NearMisses && !FeaturesNearMiss && !EarlyPredicateNearMiss) {\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003775 OS << " DEBUG_WITH_TYPE(\n";
3776 OS << " \"asm-matcher\",\n";
3777 OS << " dbgs()\n";
3778 OS << " << \"Opcode result: one mismatched operand, adding near-miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003779 OS << " NearMisses->push_back(OperandNearMiss);\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003780 OS << " } else {\n";
3781 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3782 OS << " \"types of mismatch, so not \"\n";
3783 OS << " \"reporting near-miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003784 OS << " }\n";
3785 OS << " continue;\n";
3786 OS << " }\n\n";
3787 }
3788
Chad Rosierf4e35dc2012-10-01 23:45:51 +00003789 OS << " if (matchingInlineAsm) {\n";
Chad Rosier2f480a82012-10-12 22:53:36 +00003790 OS << " convertToMapAndConstraints(it->ConvertFn, Operands);\n";
Sander de Smalen886510f2018-01-10 10:10:56 +00003791 if (!ReportMultipleNearMisses) {
Sander de Smalen118099a2018-06-18 13:39:29 +00003792 OS << " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
3793 "Operands, ErrorInfo))\n";
Sander de Smalen886510f2018-01-10 10:10:56 +00003794 OS << " return Match_InvalidTiedOperand;\n";
Sander de Smalen886510f2018-01-10 10:10:56 +00003795 OS << "\n";
3796 }
Chad Rosierf4e35dc2012-10-01 23:45:51 +00003797 OS << " return Match_Success;\n";
3798 OS << " }\n\n";
Daniel Dunbar66193402011-02-04 17:12:23 +00003799 OS << " // We have selected a definite instruction, convert the parsed\n"
3800 << " // operands into the appropriate MCInst.\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003801 if (HasOptionalOperands) {
3802 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands,\n"
3803 << " OptionalOperandsMask);\n";
3804 } else {
3805 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
3806 }
Daniel Dunbar66193402011-02-04 17:12:23 +00003807 OS << "\n";
Daniel Dunbar451a4352010-03-18 20:05:56 +00003808
Jim Grosbach120a96a2011-08-15 23:03:29 +00003809 // Verify the instruction with the target-specific match predicate function.
3810 OS << " // We have a potential match. Check the target predicate to\n"
3811 << " // handle any context sensitive constraints.\n"
Jim Grosbach120a96a2011-08-15 23:03:29 +00003812 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
3813 << " Match_Success) {\n"
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003814 << " DEBUG_WITH_TYPE(\"asm-matcher\",\n"
3815 << " dbgs() << \"Target match predicate failed with diag code \"\n"
3816 << " << MatchResult << \"\\n\");\n"
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003817 << " Inst.clear();\n";
3818 if (ReportMultipleNearMisses) {
3819 OS << " LatePredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
3820 } else {
3821 OS << " RetCode = MatchResult;\n"
3822 << " HadMatchOtherThanPredicate = true;\n"
3823 << " continue;\n";
3824 }
3825 OS << " }\n\n";
3826
3827 if (ReportMultipleNearMisses) {
3828 OS << " int NumNearMisses = ((int)(bool)OperandNearMiss +\n";
3829 OS << " (int)(bool)FeaturesNearMiss +\n";
3830 OS << " (int)(bool)EarlyPredicateNearMiss +\n";
3831 OS << " (int)(bool)LatePredicateNearMiss);\n";
3832 OS << " if (NumNearMisses == 1) {\n";
3833 OS << " // We had exactly one type of near-miss, so add that to the list.\n";
3834 OS << " assert(!OperandNearMiss && \"OperandNearMiss was handled earlier\");\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003835 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: found one type of \"\n";
3836 OS << " \"mismatch, so reporting a \"\n";
3837 OS << " \"near-miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003838 OS << " if (NearMisses && FeaturesNearMiss)\n";
3839 OS << " NearMisses->push_back(FeaturesNearMiss);\n";
3840 OS << " else if (NearMisses && EarlyPredicateNearMiss)\n";
3841 OS << " NearMisses->push_back(EarlyPredicateNearMiss);\n";
3842 OS << " else if (NearMisses && LatePredicateNearMiss)\n";
3843 OS << " NearMisses->push_back(LatePredicateNearMiss);\n";
3844 OS << "\n";
3845 OS << " continue;\n";
3846 OS << " } else if (NumNearMisses > 1) {\n";
3847 OS << " // This instruction missed in more than one way, so ignore it.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003848 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3849 OS << " \"types of mismatch, so not \"\n";
3850 OS << " \"reporting near-miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003851 OS << " continue;\n";
3852 OS << " }\n";
3853 }
Jim Grosbach120a96a2011-08-15 23:03:29 +00003854
Daniel Dunbar451a4352010-03-18 20:05:56 +00003855 // Call the post-processing function, if used.
Craig Topperbcd3c372017-05-31 21:12:46 +00003856 StringRef InsnCleanupFn = AsmParser->getValueAsString("AsmParserInstCleanup");
Daniel Dunbar451a4352010-03-18 20:05:56 +00003857 if (!InsnCleanupFn.empty())
3858 OS << " " << InsnCleanupFn << "(Inst);\n";
3859
Joey Gouly0e76fa72013-09-12 10:28:05 +00003860 if (HasDeprecation) {
3861 OS << " std::string Info;\n";
Weiming Zhaob38cfce2016-12-05 23:55:13 +00003862 OS << " if (!getParser().getTargetParser().\n";
3863 OS << " getTargetOptions().MCNoDeprecatedWarn &&\n";
3864 OS << " MII.get(Inst.getOpcode()).getDeprecatedInfo(Inst, getSTI(), Info)) {\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00003865 OS << " SMLoc Loc = ((" << Target.getName()
3866 << "Operand&)*Operands[0]).getStartLoc();\n";
Rafael Espindola961d4692014-11-11 05:18:41 +00003867 OS << " getParser().Warning(Loc, Info, None);\n";
Joey Gouly0e76fa72013-09-12 10:28:05 +00003868 OS << " }\n";
3869 }
3870
Sander de Smalen886510f2018-01-10 10:10:56 +00003871 if (!ReportMultipleNearMisses) {
Sander de Smalen118099a2018-06-18 13:39:29 +00003872 OS << " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
3873 "Operands, ErrorInfo))\n";
Craig Topper773ead22018-04-25 06:24:51 +00003874 OS << " return Match_InvalidTiedOperand;\n";
Sander de Smalen886510f2018-01-10 10:10:56 +00003875 OS << "\n";
3876 }
3877
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003878 OS << " DEBUG_WITH_TYPE(\n";
3879 OS << " \"asm-matcher\",\n";
3880 OS << " dbgs() << \"Opcode result: complete match, selecting this opcode\\n\");\n";
Chris Lattnera22a3682010-09-06 19:22:17 +00003881 OS << " return Match_Success;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003882 OS << " }\n\n";
3883
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003884 if (ReportMultipleNearMisses) {
3885 OS << " // No instruction variants matched exactly.\n";
3886 OS << " return Match_NearMisses;\n";
3887 } else {
3888 OS << " // Okay, we had no match. Try to return a useful error code.\n";
3889 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n";
3890 OS << " return RetCode;\n\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003891 OS << " ErrorInfo = 0;\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003892 OS << " return Match_MissingFeature;\n";
3893 }
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003894 OS << "}\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003895
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003896 if (!Info.OperandMatchInfo.empty())
Craig Topper7ecfa6d2012-09-18 07:02:21 +00003897 emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable,
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003898 MaxMnemonicIndex, FeatureBitsets.size(),
3899 HasMnemonicFirst);
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003900
Chris Lattner3e4582a2010-09-06 19:11:01 +00003901 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
Craig Topper2a060282017-10-26 06:46:40 +00003902
3903 OS << "\n#ifdef GET_MNEMONIC_SPELL_CHECKER\n";
3904 OS << "#undef GET_MNEMONIC_SPELL_CHECKER\n\n";
3905
3906 emitMnemonicSpellChecker(OS, Target, VariantCount);
3907
3908 OS << "#endif // GET_MNEMONIC_SPELL_CHECKER\n\n";
Daniel Dunbar3085b572009-07-11 19:39:44 +00003909}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00003910
3911namespace llvm {
3912
3913void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
3914 emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
3915 AsmMatcherEmitter(RK).run(OS);
3916}
3917
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +00003918} // end namespace llvm