blob: df089cbf0ea09bc1d3372a02b0505cff510ac83f [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 //
1075 // Also, check for instructions which reference the operand multiple times;
1076 // this implies a constraint we would not honor.
1077 std::set<std::string> OperandNames;
Craig Topper77bd2b72015-12-30 06:00:20 +00001078 for (const AsmOperand &Op : AsmOperands) {
1079 StringRef Tok = Op.Token;
Chris Lattner28ea9b12010-11-02 17:30:52 +00001080 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001081 PrintFatalError(TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001082 "matchable with operand modifier '" + Tok +
1083 "' not supported by asm matcher. Mark isCodeGenOnly!");
Chris Lattnerad776812010-11-01 05:06:45 +00001084 // Verify that any operand is only mentioned once.
Chris Lattner4d23eb22010-11-02 23:18:43 +00001085 // We reject aliases and ignore instructions for now.
Sander de Smalen5b691a12018-02-04 16:24:17 +00001086 if (!IsAlias && Tok[0] == '$' && !OperandNames.insert(Tok).second) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001087 LLVM_DEBUG({
Chris Lattner9f093812010-11-06 06:43:11 +00001088 errs() << "warning: '" << TheDef->getName() << "': "
Chris Lattnerad776812010-11-01 05:06:45 +00001089 << "ignoring instruction with tied operand '"
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001090 << Tok << "'\n";
Chris Lattner39bc53b2010-11-01 04:34:44 +00001091 });
1092 return false;
1093 }
1094 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001095
Chris Lattner39bc53b2010-11-01 04:34:44 +00001096 return true;
1097}
1098
Chris Lattner60db0a62010-02-09 00:34:28 +00001099static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001100 std::string Res;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001101
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001102 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
1103 switch (*it) {
1104 case '*': Res += "_STAR_"; break;
1105 case '%': Res += "_PCT_"; break;
1106 case ':': Res += "_COLON_"; break;
Bill Wendling4a08e562010-11-18 23:36:54 +00001107 case '!': Res += "_EXCLAIM_"; break;
Bill Wendlinga01ea892011-01-22 09:44:32 +00001108 case '.': Res += "_DOT_"; break;
Tim Northoverb3cfb282013-01-10 16:47:31 +00001109 case '<': Res += "_LT_"; break;
1110 case '>': Res += "_GT_"; break;
Hal Finkelf9090722015-01-15 01:33:00 +00001111 case '-': Res += "_MINUS_"; break;
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001112 default:
Tim Northoverb3cfb282013-01-10 16:47:31 +00001113 if ((*it >= 'A' && *it <= 'Z') ||
1114 (*it >= 'a' && *it <= 'z') ||
1115 (*it >= '0' && *it <= '9'))
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001116 Res += *it;
Chris Lattner33fc3e02010-10-31 19:10:56 +00001117 else
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001118 Res += "_" + utostr((unsigned) *it) + "_";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001119 }
1120 }
1121
1122 return Res;
1123}
1124
Chris Lattner60db0a62010-02-09 00:34:28 +00001125ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001126 ClassInfo *&Entry = TokenClasses[Token];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001127
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001128 if (!Entry) {
David Blaikied749e342014-11-28 20:35:57 +00001129 Classes.emplace_front();
1130 Entry = &Classes.front();
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001131 Entry->Kind = ClassInfo::Token;
Daniel Dunbarc32aa062009-08-09 05:18:30 +00001132 Entry->ClassName = "Token";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001133 Entry->Name = "MCK_" + getEnumNameForToken(Token);
1134 Entry->ValueName = Token;
1135 Entry->PredicateMethod = "<invalid>";
1136 Entry->RenderMethod = "<invalid>";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001137 Entry->ParserMethod = "";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001138 Entry->DiagnosticType = "";
Tom Stellardb9f235e2016-02-05 19:59:33 +00001139 Entry->IsOptional = false;
Sam Kolton5f10a132016-05-06 11:31:17 +00001140 Entry->DefaultMethod = "<invalid>";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001141 }
1142
1143 return Entry;
1144}
1145
1146ClassInfo *
Bob Wilsonb9b24222011-01-26 19:44:55 +00001147AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
1148 int SubOpIdx) {
1149 Record *Rec = OI.Rec;
1150 if (SubOpIdx != -1)
Sean Silva88eb8dd2012-10-10 20:24:47 +00001151 Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001152 return getOperandClass(Rec, SubOpIdx);
1153}
Bob Wilsonb9b24222011-01-26 19:44:55 +00001154
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001155ClassInfo *
1156AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001157 if (Rec->isSubClassOf("RegisterOperand")) {
1158 // RegisterOperand may have an associated ParserMatchClass. If it does,
1159 // use it, else just fall back to the underlying register class.
1160 const RecordVal *R = Rec->getValue("ParserMatchClass");
Craig Topper24064772014-04-15 07:20:03 +00001161 if (!R || !R->getValue())
Daniel Sandersdff673b2019-02-12 17:36:57 +00001162 PrintFatalError(Rec->getLoc(),
1163 "Record `" + Rec->getName() +
1164 "' does not have a ParserMatchClass!\n");
Owen Andersona84be6c2011-06-27 21:06:21 +00001165
Sean Silvafb509ed2012-10-10 20:24:43 +00001166 if (DefInit *DI= dyn_cast<DefInit>(R->getValue())) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001167 Record *MatchClass = DI->getDef();
1168 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1169 return CI;
1170 }
1171
1172 // No custom match class. Just use the register class.
1173 Record *ClassRec = Rec->getValueAsDef("RegClass");
1174 if (!ClassRec)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001175 PrintFatalError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
Owen Andersona84be6c2011-06-27 21:06:21 +00001176 "' has no associated register class!\n");
1177 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
1178 return CI;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001179 PrintFatalError(Rec->getLoc(), "register class has no class info!");
Owen Andersona84be6c2011-06-27 21:06:21 +00001180 }
1181
Bob Wilsonb9b24222011-01-26 19:44:55 +00001182 if (Rec->isSubClassOf("RegisterClass")) {
1183 if (ClassInfo *CI = RegisterClassClasses[Rec])
Chris Lattner77d3ead2010-11-02 18:10:06 +00001184 return CI;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001185 PrintFatalError(Rec->getLoc(), "register class has no class info!");
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001186 }
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001187
Jim Grosbachf6cb1ee2012-09-12 17:40:25 +00001188 if (!Rec->isSubClassOf("Operand"))
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001189 PrintFatalError(Rec->getLoc(), "Operand `" + Rec->getName() +
Jim Grosbachf6cb1ee2012-09-12 17:40:25 +00001190 "' does not derive from class Operand!\n");
Bob Wilsonb9b24222011-01-26 19:44:55 +00001191 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
Chris Lattner77d3ead2010-11-02 18:10:06 +00001192 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1193 return CI;
Daniel Dunbar17410a42009-08-10 18:41:10 +00001194
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001195 PrintFatalError(Rec->getLoc(), "operand has no match class!");
Daniel Dunbar541efcc2009-08-08 07:50:56 +00001196}
1197
Tim Northoverc74e6912013-09-16 16:43:19 +00001198struct LessRegisterSet {
Tim Northover9c30f7a2013-09-16 17:33:40 +00001199 bool operator() (const RegisterSet &LHS, const RegisterSet & RHS) const {
Tim Northoverc74e6912013-09-16 16:43:19 +00001200 // std::set<T> defines its own compariso "operator<", but it
1201 // performs a lexicographical comparison by T's innate comparison
1202 // for some reason. We don't want non-deterministic pointer
1203 // comparisons so use this instead.
1204 return std::lexicographical_compare(LHS.begin(), LHS.end(),
1205 RHS.begin(), RHS.end(),
1206 LessRecordByID());
1207 }
1208};
1209
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001210void AsmMatcherInfo::
Craig Topper71b7b682014-08-21 05:55:13 +00001211buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters) {
David Blaikie9b613db2014-11-29 18:13:39 +00001212 const auto &Registers = Target.getRegBank().getRegisters();
David Blaikiec0bb5ca2014-12-03 19:58:41 +00001213 auto &RegClassList = Target.getRegBank().getRegClasses();
Daniel Dunbar17410a42009-08-10 18:41:10 +00001214
Tim Northoverc74e6912013-09-16 16:43:19 +00001215 typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet;
1216
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001217 // The register sets used for matching.
Tim Northoverc74e6912013-09-16 16:43:19 +00001218 RegisterSetSet RegisterSets;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001219
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001220 // Gather the defined sets.
David Blaikiedacea4b2014-12-03 19:58:45 +00001221 for (const CodeGenRegisterClass &RC : RegClassList)
1222 RegisterSets.insert(
1223 RegisterSet(RC.getOrder().begin(), RC.getOrder().end()));
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001224
1225 // Add any required singleton sets.
Craig Topper03ec8012014-11-25 20:11:31 +00001226 for (Record *Rec : SingletonRegisters) {
Tim Northoverc74e6912013-09-16 16:43:19 +00001227 RegisterSets.insert(RegisterSet(&Rec, &Rec + 1));
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001228 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001229
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001230 // Introduce derived sets where necessary (when a register does not determine
1231 // a unique register set class), and build the mapping of registers to the set
1232 // they should classify to.
Tim Northoverc74e6912013-09-16 16:43:19 +00001233 std::map<Record*, RegisterSet> RegisterMap;
David Blaikie9b613db2014-11-29 18:13:39 +00001234 for (const CodeGenRegister &CGR : Registers) {
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001235 // Compute the intersection of all sets containing this register.
Tim Northoverc74e6912013-09-16 16:43:19 +00001236 RegisterSet ContainingSet;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001237
Craig Topper03ec8012014-11-25 20:11:31 +00001238 for (const RegisterSet &RS : RegisterSets) {
David Blaikie9b613db2014-11-29 18:13:39 +00001239 if (!RS.count(CGR.TheDef))
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001240 continue;
1241
1242 if (ContainingSet.empty()) {
Craig Topper03ec8012014-11-25 20:11:31 +00001243 ContainingSet = RS;
Chris Lattner77d3ead2010-11-02 18:10:06 +00001244 continue;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001245 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001246
Tim Northoverc74e6912013-09-16 16:43:19 +00001247 RegisterSet Tmp;
Chris Lattner77d3ead2010-11-02 18:10:06 +00001248 std::swap(Tmp, ContainingSet);
Tim Northoverc74e6912013-09-16 16:43:19 +00001249 std::insert_iterator<RegisterSet> II(ContainingSet,
1250 ContainingSet.begin());
Craig Topper03ec8012014-11-25 20:11:31 +00001251 std::set_intersection(Tmp.begin(), Tmp.end(), RS.begin(), RS.end(), II,
Tim Northoverc74e6912013-09-16 16:43:19 +00001252 LessRecordByID());
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001253 }
1254
1255 if (!ContainingSet.empty()) {
1256 RegisterSets.insert(ContainingSet);
David Blaikie9b613db2014-11-29 18:13:39 +00001257 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001258 }
1259 }
1260
1261 // Construct the register classes.
Tim Northoverc74e6912013-09-16 16:43:19 +00001262 std::map<RegisterSet, ClassInfo*, LessRegisterSet> RegisterSetClasses;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001263 unsigned Index = 0;
Craig Topper03ec8012014-11-25 20:11:31 +00001264 for (const RegisterSet &RS : RegisterSets) {
David Blaikied749e342014-11-28 20:35:57 +00001265 Classes.emplace_front();
1266 ClassInfo *CI = &Classes.front();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001267 CI->Kind = ClassInfo::RegisterClass0 + Index;
1268 CI->ClassName = "Reg" + utostr(Index);
1269 CI->Name = "MCK_Reg" + utostr(Index);
1270 CI->ValueName = "";
1271 CI->PredicateMethod = ""; // unused
1272 CI->RenderMethod = "addRegOperands";
Craig Topper03ec8012014-11-25 20:11:31 +00001273 CI->Registers = RS;
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001274 // FIXME: diagnostic type.
1275 CI->DiagnosticType = "";
Tom Stellardb9f235e2016-02-05 19:59:33 +00001276 CI->IsOptional = false;
Sam Kolton5f10a132016-05-06 11:31:17 +00001277 CI->DefaultMethod = ""; // unused
Craig Topper03ec8012014-11-25 20:11:31 +00001278 RegisterSetClasses.insert(std::make_pair(RS, CI));
1279 ++Index;
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001280 }
1281
1282 // Find the superclasses; we could compute only the subgroup lattice edges,
1283 // but there isn't really a point.
Craig Topper03ec8012014-11-25 20:11:31 +00001284 for (const RegisterSet &RS : RegisterSets) {
1285 ClassInfo *CI = RegisterSetClasses[RS];
1286 for (const RegisterSet &RS2 : RegisterSets)
1287 if (RS != RS2 &&
1288 std::includes(RS2.begin(), RS2.end(), RS.begin(), RS.end(),
Tim Northoverc74e6912013-09-16 16:43:19 +00001289 LessRecordByID()))
Craig Topper03ec8012014-11-25 20:11:31 +00001290 CI->SuperClasses.push_back(RegisterSetClasses[RS2]);
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001291 }
1292
1293 // Name the register classes which correspond to a user defined RegisterClass.
David Blaikiedacea4b2014-12-03 19:58:45 +00001294 for (const CodeGenRegisterClass &RC : RegClassList) {
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001295 // Def will be NULL for non-user defined register classes.
David Blaikiedacea4b2014-12-03 19:58:45 +00001296 Record *Def = RC.getDef();
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001297 if (!Def)
1298 continue;
David Blaikiedacea4b2014-12-03 19:58:45 +00001299 ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(),
1300 RC.getOrder().end())];
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001301 if (CI->ValueName.empty()) {
David Blaikiedacea4b2014-12-03 19:58:45 +00001302 CI->ClassName = RC.getName();
1303 CI->Name = "MCK_" + RC.getName();
1304 CI->ValueName = RC.getName();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001305 } else
David Blaikiedacea4b2014-12-03 19:58:45 +00001306 CI->ValueName = CI->ValueName + "," + RC.getName();
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001307
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00001308 Init *DiagnosticType = Def->getValueInit("DiagnosticType");
1309 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
1310 CI->DiagnosticType = SI->getValue();
1311
1312 Init *DiagnosticString = Def->getValueInit("DiagnosticString");
1313 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticString))
1314 CI->DiagnosticString = SI->getValue();
1315
1316 // If we have a diagnostic string but the diagnostic type is not specified
1317 // explicitly, create an anonymous diagnostic type.
1318 if (!CI->DiagnosticString.empty() && CI->DiagnosticType.empty())
1319 CI->DiagnosticType = RC.getName();
1320
Jakob Stoklund Olesenbd92dc62011-10-04 15:28:08 +00001321 RegisterClassClasses.insert(std::make_pair(Def, CI));
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001322 }
1323
1324 // Populate the map for individual registers.
Tim Northoverc74e6912013-09-16 16:43:19 +00001325 for (std::map<Record*, RegisterSet>::iterator it = RegisterMap.begin(),
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001326 ie = RegisterMap.end(); it != ie; ++it)
Chris Lattner77d3ead2010-11-02 18:10:06 +00001327 RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001328
1329 // Name the register classes which correspond to singleton registers.
Craig Topper03ec8012014-11-25 20:11:31 +00001330 for (Record *Rec : SingletonRegisters) {
Chris Lattner77d3ead2010-11-02 18:10:06 +00001331 ClassInfo *CI = RegisterClasses[Rec];
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001332 assert(CI && "Missing singleton register class info!");
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001333
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001334 if (CI->ValueName.empty()) {
1335 CI->ClassName = Rec->getName();
Matthias Braun4a86d452016-12-04 05:48:16 +00001336 CI->Name = "MCK_" + Rec->getName().str();
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001337 CI->ValueName = Rec->getName();
1338 } else
Matthias Braun4a86d452016-12-04 05:48:16 +00001339 CI->ValueName = CI->ValueName + "," + Rec->getName().str();
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001340 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001341}
1342
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001343void AsmMatcherInfo::buildOperandClasses() {
Chris Lattnere3c48de2010-11-01 23:57:23 +00001344 std::vector<Record*> AsmOperands =
1345 Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbarcf181532010-01-30 01:02:37 +00001346
1347 // Pre-populate AsmOperandClasses map.
David Blaikied749e342014-11-28 20:35:57 +00001348 for (Record *Rec : AsmOperands) {
1349 Classes.emplace_front();
1350 AsmOperandClasses[Rec] = &Classes.front();
1351 }
Daniel Dunbarcf181532010-01-30 01:02:37 +00001352
Daniel Dunbar17410a42009-08-10 18:41:10 +00001353 unsigned Index = 0;
Craig Topper03ec8012014-11-25 20:11:31 +00001354 for (Record *Rec : AsmOperands) {
1355 ClassInfo *CI = AsmOperandClasses[Rec];
Daniel Dunbar17410a42009-08-10 18:41:10 +00001356 CI->Kind = ClassInfo::UserClass0 + Index;
1357
Craig Topper03ec8012014-11-25 20:11:31 +00001358 ListInit *Supers = Rec->getValueAsListInit("SuperClasses");
Craig Topperef0578a2015-06-02 04:15:51 +00001359 for (Init *I : Supers->getValues()) {
1360 DefInit *DI = dyn_cast<DefInit>(I);
Daniel Dunbar346782c2010-05-22 21:02:29 +00001361 if (!DI) {
Craig Topper03ec8012014-11-25 20:11:31 +00001362 PrintError(Rec->getLoc(), "Invalid super class reference!");
Daniel Dunbar346782c2010-05-22 21:02:29 +00001363 continue;
1364 }
1365
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001366 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1367 if (!SC)
Craig Topper03ec8012014-11-25 20:11:31 +00001368 PrintError(Rec->getLoc(), "Invalid super class reference!");
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001369 else
1370 CI->SuperClasses.push_back(SC);
Daniel Dunbar17410a42009-08-10 18:41:10 +00001371 }
Craig Topper03ec8012014-11-25 20:11:31 +00001372 CI->ClassName = Rec->getValueAsString("Name");
Daniel Dunbar17410a42009-08-10 18:41:10 +00001373 CI->Name = "MCK_" + CI->ClassName;
Craig Topper03ec8012014-11-25 20:11:31 +00001374 CI->ValueName = Rec->getName();
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001375
1376 // Get or construct the predicate method name.
Craig Topper03ec8012014-11-25 20:11:31 +00001377 Init *PMName = Rec->getValueInit("PredicateMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001378 if (StringInit *SI = dyn_cast<StringInit>(PMName)) {
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001379 CI->PredicateMethod = SI->getValue();
1380 } else {
Sean Silva88eb8dd2012-10-10 20:24:47 +00001381 assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!");
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001382 CI->PredicateMethod = "is" + CI->ClassName;
1383 }
1384
1385 // Get or construct the render method name.
Craig Topper03ec8012014-11-25 20:11:31 +00001386 Init *RMName = Rec->getValueInit("RenderMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001387 if (StringInit *SI = dyn_cast<StringInit>(RMName)) {
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001388 CI->RenderMethod = SI->getValue();
1389 } else {
Sean Silva88eb8dd2012-10-10 20:24:47 +00001390 assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!");
Daniel Dunbaraeb1feb2009-08-10 21:00:45 +00001391 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1392 }
1393
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001394 // Get the parse method name or leave it as empty.
Craig Topper03ec8012014-11-25 20:11:31 +00001395 Init *PRMName = Rec->getValueInit("ParserMethod");
Sean Silvafb509ed2012-10-10 20:24:43 +00001396 if (StringInit *SI = dyn_cast<StringInit>(PRMName))
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001397 CI->ParserMethod = SI->getValue();
1398
Oliver Stannard41dfac32017-10-03 14:34:57 +00001399 // Get the diagnostic type and string or leave them as empty.
Craig Topper03ec8012014-11-25 20:11:31 +00001400 Init *DiagnosticType = Rec->getValueInit("DiagnosticType");
Sean Silvafb509ed2012-10-10 20:24:43 +00001401 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001402 CI->DiagnosticType = SI->getValue();
Oliver Stannard41dfac32017-10-03 14:34:57 +00001403 Init *DiagnosticString = Rec->getValueInit("DiagnosticString");
1404 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticString))
1405 CI->DiagnosticString = SI->getValue();
1406 // If we have a DiagnosticString, we need a DiagnosticType for use within
1407 // the matcher.
1408 if (!CI->DiagnosticString.empty() && CI->DiagnosticType.empty())
1409 CI->DiagnosticType = CI->ClassName;
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00001410
Tom Stellardb9f235e2016-02-05 19:59:33 +00001411 Init *IsOptional = Rec->getValueInit("IsOptional");
1412 if (BitInit *BI = dyn_cast<BitInit>(IsOptional))
1413 CI->IsOptional = BI->getValue();
1414
Sam Kolton5f10a132016-05-06 11:31:17 +00001415 // Get or construct the default method name.
1416 Init *DMName = Rec->getValueInit("DefaultMethod");
1417 if (StringInit *SI = dyn_cast<StringInit>(DMName)) {
1418 CI->DefaultMethod = SI->getValue();
1419 } else {
1420 assert(isa<UnsetInit>(DMName) && "Unexpected DefaultMethod field!");
1421 CI->DefaultMethod = "default" + CI->ClassName + "Operands";
1422 }
1423
Craig Topper03ec8012014-11-25 20:11:31 +00001424 ++Index;
Daniel Dunbar17410a42009-08-10 18:41:10 +00001425 }
Daniel Dunbarbb98db22009-08-11 02:59:53 +00001426}
1427
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001428AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1429 CodeGenTarget &target,
Chris Lattner89dcb682010-12-15 04:48:22 +00001430 RecordKeeper &records)
Devang Patel6d676e42012-01-07 01:33:34 +00001431 : Records(records), AsmParser(asmParser), Target(target) {
Daniel Dunbare4318712009-08-11 20:59:47 +00001432}
1433
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001434/// buildOperandMatchInfo - Build the necessary information to handle user
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001435/// defined operand parsing methods.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001436void AsmMatcherInfo::buildOperandMatchInfo() {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001437
Jim Grosbach925a6d02012-04-18 23:46:25 +00001438 /// Map containing a mask with all operands indices that can be found for
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001439 /// that class inside a instruction.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00001440 typedef std::map<ClassInfo *, unsigned, less_ptr<ClassInfo>> OpClassMaskTy;
Sean Silva835139b2012-09-19 01:47:03 +00001441 OpClassMaskTy OpClassMask;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001442
Craig Topperf34dad92014-11-28 03:53:02 +00001443 for (const auto &MI : Matchables) {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001444 OpClassMask.clear();
1445
1446 // Keep track of all operands of this instructions which belong to the
1447 // same class.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001448 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
1449 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001450 if (Op.Class->ParserMethod.empty())
1451 continue;
1452 unsigned &OperandMask = OpClassMask[Op.Class];
1453 OperandMask |= (1 << i);
1454 }
1455
1456 // Generate operand match info for each mnemonic/operand class pair.
Craig Topper42bd8192014-11-28 03:53:00 +00001457 for (const auto &OCM : OpClassMask) {
1458 unsigned OpMask = OCM.second;
1459 ClassInfo *CI = OCM.first;
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001460 OperandMatchInfo.push_back(OperandMatchEntry::create(MI.get(), CI,
1461 OpMask));
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00001462 }
1463 }
1464}
1465
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001466void AsmMatcherInfo::buildInfo() {
Chris Lattnera0e87192010-10-30 20:07:57 +00001467 // Build information about all of the AssemblerPredicates.
Daniel Sandersea6ef3d2016-11-15 09:51:02 +00001468 const std::vector<std::pair<Record *, SubtargetFeatureInfo>>
1469 &SubtargetFeaturePairs = SubtargetFeatureInfo::getAll(Records);
1470 SubtargetFeatures.insert(SubtargetFeaturePairs.begin(),
1471 SubtargetFeaturePairs.end());
Daniel Sandersa3e11252016-11-15 10:13:09 +00001472#ifndef NDEBUG
Daniel Sandersea6ef3d2016-11-15 09:51:02 +00001473 for (const auto &Pair : SubtargetFeatures)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001474 LLVM_DEBUG(Pair.second.dump());
Daniel Sandersa3e11252016-11-15 10:13:09 +00001475#endif // NDEBUG
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001476
Craig Topperfd2c6a32015-12-31 08:18:23 +00001477 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
Sander de Smalen5b691a12018-02-04 16:24:17 +00001478 bool ReportMultipleNearMisses =
1479 AsmParser->getValueAsBit("ReportMultipleNearMisses");
Craig Topperfd2c6a32015-12-31 08:18:23 +00001480
Chris Lattner33fc3e02010-10-31 19:10:56 +00001481 // Parse the instructions; we need to do this first so that we can gather the
1482 // singleton register classes.
Chris Lattnerf7a01e92010-11-01 01:47:07 +00001483 SmallPtrSet<Record*, 16> SingletonRegisters;
Devang Patel85d684a2012-01-09 19:13:28 +00001484 unsigned VariantCount = Target.getAsmParserVariantCount();
1485 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1486 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topperbcd3c372017-05-31 21:12:46 +00001487 StringRef CommentDelimiter =
1488 AsmVariant->getValueAsString("CommentDelimiter");
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001489 AsmVariantInfo Variant;
Craig Topperc8b5b252015-12-30 06:00:18 +00001490 Variant.RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001491 Variant.TokenizingCharacters =
1492 AsmVariant->getValueAsString("TokenizingCharacters");
1493 Variant.SeparatorCharacters =
1494 AsmVariant->getValueAsString("SeparatorCharacters");
1495 Variant.BreakCharacters =
1496 AsmVariant->getValueAsString("BreakCharacters");
Sam Kolton1b746d12016-09-08 15:50:52 +00001497 Variant.Name = AsmVariant->getValueAsString("Name");
Craig Topperc8b5b252015-12-30 06:00:18 +00001498 Variant.AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001499
Craig Topper8cc904d2016-01-17 20:38:18 +00001500 for (const CodeGenInstruction *CGI : Target.getInstructionsByEnumValue()) {
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001501
Devang Patel85d684a2012-01-09 19:13:28 +00001502 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1503 // filter the set of instructions we consider.
Craig Topper03ec8012014-11-25 20:11:31 +00001504 if (!StringRef(CGI->TheDef->getName()).startswith(MatchPrefix))
Jim Grosbach3263a072012-04-11 21:02:33 +00001505 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001506
Devang Patel85d684a2012-01-09 19:13:28 +00001507 // Ignore "codegen only" instructions.
Craig Topper03ec8012014-11-25 20:11:31 +00001508 if (CGI->TheDef->getValueAsBit("isCodeGenOnly"))
Jim Grosbach3263a072012-04-11 21:02:33 +00001509 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001510
Sam Kolton1b746d12016-09-08 15:50:52 +00001511 // Ignore instructions for different instructions
Craig Topperbcd3c372017-05-31 21:12:46 +00001512 StringRef V = CGI->TheDef->getValueAsString("AsmVariantName");
Sam Kolton1b746d12016-09-08 15:50:52 +00001513 if (!V.empty() && V != Variant.Name)
1514 continue;
1515
Craig Topper1c8fbd22015-09-06 03:44:50 +00001516 auto II = llvm::make_unique<MatchableInfo>(*CGI);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001517
Craig Topperfd2c6a32015-12-31 08:18:23 +00001518 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001519
Devang Patel85d684a2012-01-09 19:13:28 +00001520 // Ignore instructions which shouldn't be matched and diagnose invalid
1521 // instruction definitions with an error.
Sander de Smalen5b691a12018-02-04 16:24:17 +00001522 if (!II->validate(CommentDelimiter, false))
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001523 continue;
1524
1525 Matchables.push_back(std::move(II));
Chris Lattner743081d2010-11-04 00:43:46 +00001526 }
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001527
Devang Patel85d684a2012-01-09 19:13:28 +00001528 // Parse all of the InstAlias definitions and stick them in the list of
1529 // matchables.
1530 std::vector<Record*> AllInstAliases =
1531 Records.getAllDerivedDefinitions("InstAlias");
1532 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
David Blaikieba4e00f2014-12-22 21:26:26 +00001533 auto Alias = llvm::make_unique<CodeGenInstAlias>(AllInstAliases[i],
Craig Topperc8b5b252015-12-30 06:00:18 +00001534 Target);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001535
Devang Patel85d684a2012-01-09 19:13:28 +00001536 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1537 // filter the set of instruction aliases we consider, based on the target
1538 // instruction.
Jim Grosbach56e63262012-04-17 00:01:04 +00001539 if (!StringRef(Alias->ResultInst->TheDef->getName())
1540 .startswith( MatchPrefix))
Jim Grosbach3263a072012-04-11 21:02:33 +00001541 continue;
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001542
Craig Topperbcd3c372017-05-31 21:12:46 +00001543 StringRef V = Alias->TheDef->getValueAsString("AsmVariantName");
Sam Kolton1b746d12016-09-08 15:50:52 +00001544 if (!V.empty() && V != Variant.Name)
1545 continue;
1546
Craig Topper1c8fbd22015-09-06 03:44:50 +00001547 auto II = llvm::make_unique<MatchableInfo>(std::move(Alias));
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001548
Craig Topperfd2c6a32015-12-31 08:18:23 +00001549 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
Jim Grosbach0bba00d2012-01-24 21:06:59 +00001550
Devang Patel85d684a2012-01-09 19:13:28 +00001551 // Validate the alias definitions.
Sander de Smalen5b691a12018-02-04 16:24:17 +00001552 II->validate(CommentDelimiter, true);
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001553
1554 Matchables.push_back(std::move(II));
Devang Patel85d684a2012-01-09 19:13:28 +00001555 }
Chris Lattner488c2012010-11-01 04:05:41 +00001556 }
Chris Lattnerd8adec72010-11-01 04:03:32 +00001557
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001558 // Build info for the register classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001559 buildRegisterClasses(SingletonRegisters);
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001560
1561 // Build info for the user defined assembly operand classes.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001562 buildOperandClasses();
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001563
Chris Lattner4779e3e92010-11-04 00:57:06 +00001564 // Build the information about matchables, now that we have fully formed
1565 // classes.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001566 std::vector<std::unique_ptr<MatchableInfo>> NewMatchables;
Craig Topperf34dad92014-11-28 03:53:02 +00001567 for (auto &II : Matchables) {
Chris Lattner82d88ce2010-09-06 21:01:37 +00001568 // Parse the tokens after the mnemonic.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001569 // Note: buildInstructionOperandReference may insert new AsmOperands, so
Bob Wilsonb9b24222011-01-26 19:44:55 +00001570 // don't precompute the loop bound.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001571 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1572 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
Chris Lattner28ea9b12010-11-02 17:30:52 +00001573 StringRef Token = Op.Token;
Daniel Dunbare10787e2009-08-07 08:26:05 +00001574
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001575 // Check for singleton registers.
Craig Toppere4e74152015-12-29 07:03:23 +00001576 if (Record *RegRecord = Op.SingletonReg) {
Chris Lattner28ea9b12010-11-02 17:30:52 +00001577 Op.Class = RegisterClasses[RegRecord];
Chris Lattnerb80ab362010-11-01 01:37:30 +00001578 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1579 "Unexpected class for singleton register");
Chris Lattnerb80ab362010-11-01 01:37:30 +00001580 continue;
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00001581 }
1582
Daniel Dunbare10787e2009-08-07 08:26:05 +00001583 // Check for simple tokens.
1584 if (Token[0] != '$') {
Chris Lattner28ea9b12010-11-02 17:30:52 +00001585 Op.Class = getTokenClass(Token);
Daniel Dunbare10787e2009-08-07 08:26:05 +00001586 continue;
1587 }
1588
Chris Lattnerd6746d52010-11-06 22:06:03 +00001589 if (Token.size() > 1 && isdigit(Token[1])) {
1590 Op.Class = getTokenClass(Token);
1591 continue;
1592 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001593
Chris Lattner4efe13d2010-11-04 02:11:18 +00001594 // Otherwise this is an operand reference.
Chris Lattnerccde4632010-11-04 01:58:23 +00001595 StringRef OperandName;
1596 if (Token[1] == '{')
1597 OperandName = Token.substr(2, Token.size() - 3);
1598 else
1599 OperandName = Token.substr(1);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001600
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001601 if (II->DefRec.is<const CodeGenInstruction*>())
1602 buildInstructionOperandReference(II.get(), OperandName, i);
Chris Lattner4efe13d2010-11-04 02:11:18 +00001603 else
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001604 buildAliasOperandReference(II.get(), OperandName, Op);
Daniel Dunbare10787e2009-08-07 08:26:05 +00001605 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001606
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001607 if (II->DefRec.is<const CodeGenInstruction*>()) {
1608 II->buildInstructionResultOperands();
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001609 // If the instruction has a two-operand alias, build up the
1610 // matchable here. We'll add them in bulk at the end to avoid
1611 // confusing this loop.
Craig Topperbcd3c372017-05-31 21:12:46 +00001612 StringRef Constraint =
1613 II->TheDef->getValueAsString("TwoOperandAliasConstraint");
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001614 if (Constraint != "") {
1615 // Start by making a copy of the original matchable.
Craig Topper1c8fbd22015-09-06 03:44:50 +00001616 auto AliasII = llvm::make_unique<MatchableInfo>(*II);
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001617
1618 // Adjust it to be a two-operand alias.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001619 AliasII->formTwoOperandAlias(Constraint);
1620
1621 // Add the alias to the matchables list.
1622 NewMatchables.push_back(std::move(AliasII));
Jim Grosbach31c2d3f2012-04-19 23:59:23 +00001623 }
1624 } else
Sander de Smalen5b691a12018-02-04 16:24:17 +00001625 // FIXME: The tied operands checking is not yet integrated with the
1626 // framework for reporting multiple near misses. To prevent invalid
1627 // formats from being matched with an alias if a tied-operands check
1628 // would otherwise have disallowed it, we just disallow such constructs
1629 // in TableGen completely.
1630 II->buildAliasResultOperands(!ReportMultipleNearMisses);
Daniel Dunbare10787e2009-08-07 08:26:05 +00001631 }
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00001632 if (!NewMatchables.empty())
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001633 Matchables.insert(Matchables.end(),
1634 std::make_move_iterator(NewMatchables.begin()),
1635 std::make_move_iterator(NewMatchables.end()));
Daniel Dunbar8e33cb22009-08-09 07:20:21 +00001636
Jim Grosbachba395922011-12-06 23:43:54 +00001637 // Process token alias definitions and set up the associated superclass
1638 // information.
1639 std::vector<Record*> AllTokenAliases =
1640 Records.getAllDerivedDefinitions("TokenAlias");
Craig Toppere4e74152015-12-29 07:03:23 +00001641 for (Record *Rec : AllTokenAliases) {
Jim Grosbachba395922011-12-06 23:43:54 +00001642 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1643 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
Jim Grosbach37f6dcb32012-04-17 21:23:52 +00001644 if (FromClass == ToClass)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001645 PrintFatalError(Rec->getLoc(),
Jim Grosbach37f6dcb32012-04-17 21:23:52 +00001646 "error: Destination value identical to source value.");
Jim Grosbachba395922011-12-06 23:43:54 +00001647 FromClass->SuperClasses.push_back(ToClass);
1648 }
1649
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001650 // Reorder classes so that classes precede super classes.
David Blaikied749e342014-11-28 20:35:57 +00001651 Classes.sort();
Oliver Stannard7772f022016-01-25 10:20:19 +00001652
Matthias Brauna8eed312016-12-05 19:44:31 +00001653#ifdef EXPENSIVE_CHECKS
1654 // Verify that the table is sorted and operator < works transitively.
Oliver Stannard7772f022016-01-25 10:20:19 +00001655 for (auto I = Classes.begin(), E = Classes.end(); I != E; ++I) {
1656 for (auto J = I; J != E; ++J) {
1657 assert(!(*J < *I));
1658 assert(I == J || !J->isSubsetOf(*I));
1659 }
1660 }
Matthias Brauna8eed312016-12-05 19:44:31 +00001661#endif
Daniel Dunbare10787e2009-08-07 08:26:05 +00001662}
1663
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001664/// buildInstructionOperandReference - The specified operand is a reference to a
Chris Lattner4779e3e92010-11-04 00:57:06 +00001665/// named operand such as $src. Resolve the Class and OperandInfo pointers.
1666void AsmMatcherInfo::
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001667buildInstructionOperandReference(MatchableInfo *II,
Chris Lattnerccde4632010-11-04 01:58:23 +00001668 StringRef OperandName,
Bob Wilsonb9b24222011-01-26 19:44:55 +00001669 unsigned AsmOpIdx) {
Chris Lattner4efe13d2010-11-04 02:11:18 +00001670 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1671 const CGIOperandList &Operands = CGI.Operands;
Bob Wilsonb9b24222011-01-26 19:44:55 +00001672 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001673
Chris Lattnerfecdad62010-11-06 07:14:44 +00001674 // Map this token to an operand.
Chris Lattner4779e3e92010-11-04 00:57:06 +00001675 unsigned Idx;
1676 if (!Operands.hasOperandNamed(OperandName, Idx))
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001677 PrintFatalError(II->TheDef->getLoc(),
1678 "error: unable to find operand: '" + OperandName + "'");
Chris Lattner897a1402010-11-04 01:55:23 +00001679
Bob Wilsonb9b24222011-01-26 19:44:55 +00001680 // If the instruction operand has multiple suboperands, but the parser
1681 // match class for the asm operand is still the default "ImmAsmOperand",
1682 // then handle each suboperand separately.
1683 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1684 Record *Rec = Operands[Idx].Rec;
1685 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1686 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1687 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1688 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1689 StringRef Token = Op->Token; // save this in case Op gets moved
1690 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
Ahmed Bougachaeb4dbd82015-05-29 01:03:37 +00001691 MatchableInfo::AsmOperand NewAsmOp(/*IsIsolatedToken=*/true, Token);
Bob Wilsonb9b24222011-01-26 19:44:55 +00001692 NewAsmOp.SubOpIdx = SI;
1693 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1694 }
1695 // Replace Op with first suboperand.
1696 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1697 Op->SubOpIdx = 0;
1698 }
1699 }
1700
Chris Lattner897a1402010-11-04 01:55:23 +00001701 // Set up the operand class.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001702 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
Sander de Smalen5b691a12018-02-04 16:24:17 +00001703 Op->OrigSrcOpName = OperandName;
Chris Lattner897a1402010-11-04 01:55:23 +00001704
1705 // If the named operand is tied, canonicalize it to the untied operand.
1706 // For example, something like:
1707 // (outs GPR:$dst), (ins GPR:$src)
1708 // with an asmstring of
1709 // "inc $src"
1710 // we want to canonicalize to:
1711 // "inc $dst"
1712 // so that we know how to provide the $dst operand when filling in the result.
Ulrich Weigande037a492013-04-27 18:48:23 +00001713 int OITied = -1;
1714 if (Operands[Idx].MINumOperands == 1)
1715 OITied = Operands[Idx].getTiedRegister();
Chris Lattner4779e3e92010-11-04 00:57:06 +00001716 if (OITied != -1) {
1717 // The tied operand index is an MIOperand index, find the operand that
1718 // contains it.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001719 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1720 OperandName = Operands[Idx.first].Name;
1721 Op->SubOpIdx = Idx.second;
Chris Lattner4779e3e92010-11-04 00:57:06 +00001722 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001723
Bob Wilsonb9b24222011-01-26 19:44:55 +00001724 Op->SrcOpName = OperandName;
Chris Lattner4779e3e92010-11-04 00:57:06 +00001725}
1726
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001727/// buildAliasOperandReference - When parsing an operand reference out of the
Chris Lattnerb625dd22010-11-06 07:06:09 +00001728/// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1729/// operand reference is by looking it up in the result pattern definition.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001730void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
Chris Lattner4efe13d2010-11-04 02:11:18 +00001731 StringRef OperandName,
1732 MatchableInfo::AsmOperand &Op) {
1733 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001734
Chris Lattner4efe13d2010-11-04 02:11:18 +00001735 // Set up the operand class.
Chris Lattnerb625dd22010-11-06 07:06:09 +00001736 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
Chris Lattnerb6f8e822010-11-06 19:25:43 +00001737 if (CGA.ResultOperands[i].isRecord() &&
1738 CGA.ResultOperands[i].getName() == OperandName) {
Chris Lattnerfecdad62010-11-06 07:14:44 +00001739 // It's safe to go with the first one we find, because CodeGenInstAlias
1740 // validates that all operands with the same name have the same record.
Bob Wilsonb9b24222011-01-26 19:44:55 +00001741 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
Jim Grosbachd1f1b792011-10-28 22:32:53 +00001742 // Use the match class from the Alias definition, not the
1743 // destination instruction, as we may have an immediate that's
1744 // being munged by the match class.
1745 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
Bob Wilsonb9b24222011-01-26 19:44:55 +00001746 Op.SubOpIdx);
Chris Lattnerb625dd22010-11-06 07:06:09 +00001747 Op.SrcOpName = OperandName;
Sander de Smalen5b691a12018-02-04 16:24:17 +00001748 Op.OrigSrcOpName = OperandName;
Chris Lattnerb625dd22010-11-06 07:06:09 +00001749 return;
Chris Lattner4efe13d2010-11-04 02:11:18 +00001750 }
Chris Lattnerb625dd22010-11-06 07:06:09 +00001751
Benjamin Kramer48e7e852014-03-29 17:17:15 +00001752 PrintFatalError(II->TheDef->getLoc(),
1753 "error: unable to find operand: '" + OperandName + "'");
Chris Lattner4efe13d2010-11-04 02:11:18 +00001754}
1755
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001756void MatchableInfo::buildInstructionResultOperands() {
Chris Lattnerfecdad62010-11-06 07:14:44 +00001757 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001758
Chris Lattnerfecdad62010-11-06 07:14:44 +00001759 // Loop over all operands of the result instruction, determining how to
1760 // populate them.
Craig Toppere4e74152015-12-29 07:03:23 +00001761 for (const CGIOperandList::OperandInfo &OpInfo : ResultInst->Operands) {
Chris Lattner7108dad2010-11-04 01:42:59 +00001762 // If this is a tied operand, just copy from the previously handled operand.
Ulrich Weigande037a492013-04-27 18:48:23 +00001763 int TiedOp = -1;
1764 if (OpInfo.MINumOperands == 1)
1765 TiedOp = OpInfo.getTiedRegister();
Chris Lattner7108dad2010-11-04 01:42:59 +00001766 if (TiedOp != -1) {
Sander de Smalen5b691a12018-02-04 16:24:17 +00001767 int TiedSrcOperand = findAsmOperandOriginallyNamed(OpInfo.Name);
1768 if (TiedSrcOperand != -1 &&
1769 ResOperands[TiedOp].Kind == ResOperand::RenderAsmOperand)
1770 ResOperands.push_back(ResOperand::getTiedOp(
1771 TiedOp, ResOperands[TiedOp].AsmOperandNum, TiedSrcOperand));
1772 else
1773 ResOperands.push_back(ResOperand::getTiedOp(TiedOp, 0, 0));
Chris Lattner7108dad2010-11-04 01:42:59 +00001774 continue;
1775 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001776
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001777 int SrcOperand = findAsmOperandNamed(OpInfo.Name);
Ulrich Weigande037a492013-04-27 18:48:23 +00001778 if (OpInfo.Name.empty() || SrcOperand == -1) {
1779 // This may happen for operands that are tied to a suboperand of a
1780 // complex operand. Simply use a dummy value here; nobody should
1781 // use this operand slot.
1782 // FIXME: The long term goal is for the MCOperand list to not contain
1783 // tied operands at all.
1784 ResOperands.push_back(ResOperand::getImmOp(0));
1785 continue;
1786 }
Chris Lattner7108dad2010-11-04 01:42:59 +00001787
Bob Wilsonb9b24222011-01-26 19:44:55 +00001788 // Check if the one AsmOperand populates the entire operand.
1789 unsigned NumOperands = OpInfo.MINumOperands;
1790 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1791 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
Chris Lattner743081d2010-11-04 00:43:46 +00001792 continue;
1793 }
Bob Wilsonb9b24222011-01-26 19:44:55 +00001794
1795 // Add a separate ResOperand for each suboperand.
1796 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1797 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1798 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1799 "unexpected AsmOperands for suboperands");
1800 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1801 }
Chris Lattner743081d2010-11-04 00:43:46 +00001802 }
1803}
1804
Sander de Smalen5b691a12018-02-04 16:24:17 +00001805void MatchableInfo::buildAliasResultOperands(bool AliasConstraintsAreChecked) {
Chris Lattner8188fb22010-11-06 07:31:43 +00001806 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1807 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001808
Sander de Smalen5b691a12018-02-04 16:24:17 +00001809 // Map of: $reg -> #lastref
1810 // where $reg is the name of the operand in the asm string
1811 // where #lastref is the last processed index where $reg was referenced in
1812 // the asm string.
1813 SmallDenseMap<StringRef, int> OperandRefs;
1814
Chris Lattner8188fb22010-11-06 07:31:43 +00001815 // Loop over all operands of the result instruction, determining how to
1816 // populate them.
1817 unsigned AliasOpNo = 0;
Bob Wilsonb9b24222011-01-26 19:44:55 +00001818 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
Chris Lattner8188fb22010-11-06 07:31:43 +00001819 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001820 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00001821
Chris Lattner8188fb22010-11-06 07:31:43 +00001822 // If this is a tied operand, just copy from the previously handled operand.
Ulrich Weigande037a492013-04-27 18:48:23 +00001823 int TiedOp = -1;
1824 if (OpInfo->MINumOperands == 1)
1825 TiedOp = OpInfo->getTiedRegister();
Chris Lattner8188fb22010-11-06 07:31:43 +00001826 if (TiedOp != -1) {
Sander de Smalen5b691a12018-02-04 16:24:17 +00001827 unsigned SrcOp1 = 0;
1828 unsigned SrcOp2 = 0;
1829
1830 // If an operand has been specified twice in the asm string,
1831 // add the two source operand's indices to the TiedOp so that
1832 // at runtime the 'tied' constraint is checked.
1833 if (ResOperands[TiedOp].Kind == ResOperand::RenderAsmOperand) {
1834 SrcOp1 = ResOperands[TiedOp].AsmOperandNum;
1835
1836 // Find the next operand (similarly named operand) in the string.
1837 StringRef Name = AsmOperands[SrcOp1].SrcOpName;
1838 auto Insert = OperandRefs.try_emplace(Name, SrcOp1);
1839 SrcOp2 = findAsmOperandNamed(Name, Insert.first->second);
1840
1841 // Not updating the record in OperandRefs will cause TableGen
1842 // to fail with an error at the end of this function.
1843 if (AliasConstraintsAreChecked)
1844 Insert.first->second = SrcOp2;
1845
1846 // In case it only has one reference in the asm string,
1847 // it doesn't need to be checked for tied constraints.
1848 SrcOp2 = (SrcOp2 == (unsigned)-1) ? SrcOp1 : SrcOp2;
1849 }
1850
Sander de Smalen118099a2018-06-18 13:39:29 +00001851 // If the alias operand is of a different operand class, we only want
1852 // to benefit from the tied-operands check and just match the operand
1853 // as a normal, but not copy the original (TiedOp) to the result
1854 // instruction. We do this by passing -1 as the tied operand to copy.
1855 if (ResultInst->Operands[i].Rec->getName() !=
1856 ResultInst->Operands[TiedOp].Rec->getName()) {
1857 SrcOp1 = ResOperands[TiedOp].AsmOperandNum;
1858 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1859 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1860 SrcOp2 = findAsmOperand(Name, SubIdx);
1861 ResOperands.push_back(
1862 ResOperand::getTiedOp((unsigned)-1, SrcOp1, SrcOp2));
1863 } else {
1864 ResOperands.push_back(ResOperand::getTiedOp(TiedOp, SrcOp1, SrcOp2));
1865 continue;
1866 }
Chris Lattner4869d342010-11-06 19:57:21 +00001867 }
1868
Bob Wilsonb9b24222011-01-26 19:44:55 +00001869 // Handle all the suboperands for this operand.
1870 const std::string &OpName = OpInfo->Name;
1871 for ( ; AliasOpNo < LastOpNo &&
1872 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1873 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1874
1875 // Find out what operand from the asmparser that this MCInst operand
1876 // comes from.
1877 switch (CGA.ResultOperands[AliasOpNo].Kind) {
Bob Wilsonb9b24222011-01-26 19:44:55 +00001878 case CodeGenInstAlias::ResultOperand::K_Record: {
1879 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00001880 int SrcOperand = findAsmOperand(Name, SubIdx);
Bob Wilsonb9b24222011-01-26 19:44:55 +00001881 if (SrcOperand == -1)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001882 PrintFatalError(TheDef->getLoc(), "Instruction '" +
Bob Wilsonb9b24222011-01-26 19:44:55 +00001883 TheDef->getName() + "' has operand '" + OpName +
1884 "' that doesn't appear in asm string!");
Sander de Smalen5b691a12018-02-04 16:24:17 +00001885
1886 // Add it to the operand references. If it is added a second time, the
1887 // record won't be updated and it will fail later on.
1888 OperandRefs.try_emplace(Name, SrcOperand);
1889
Bob Wilsonb9b24222011-01-26 19:44:55 +00001890 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1891 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1892 NumOperands));
1893 break;
1894 }
1895 case CodeGenInstAlias::ResultOperand::K_Imm: {
1896 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1897 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1898 break;
1899 }
1900 case CodeGenInstAlias::ResultOperand::K_Reg: {
1901 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1902 ResOperands.push_back(ResOperand::getRegOp(Reg));
1903 break;
1904 }
1905 }
Chris Lattner4869d342010-11-06 19:57:21 +00001906 }
Chris Lattner8188fb22010-11-06 07:31:43 +00001907 }
Sander de Smalen5b691a12018-02-04 16:24:17 +00001908
1909 // Check that operands are not repeated more times than is supported.
1910 for (auto &T : OperandRefs) {
1911 if (T.second != -1 && findAsmOperandNamed(T.first, T.second) != -1)
1912 PrintFatalError(TheDef->getLoc(),
1913 "Operand '" + T.first + "' can never be matched");
1914 }
Chris Lattner8188fb22010-11-06 07:31:43 +00001915}
Chris Lattner743081d2010-11-04 00:43:46 +00001916
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001917static unsigned
1918getConverterOperandID(const std::string &Name,
1919 SmallSetVector<CachedHashString, 16> &Table,
1920 bool &IsNew) {
1921 IsNew = Table.insert(CachedHashString(Name));
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001922
David Majnemer0d955d02016-08-11 22:21:41 +00001923 unsigned ID = IsNew ? Table.size() - 1 : find(Table, Name) - Table.begin();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001924
1925 assert(ID < Table.size());
1926
1927 return ID;
1928}
1929
Craig Topperb64f9152019-04-02 20:52:04 +00001930static unsigned
1931emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName,
1932 std::vector<std::unique_ptr<MatchableInfo>> &Infos,
1933 bool HasMnemonicFirst, bool HasOptionalOperands,
1934 raw_ostream &OS) {
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001935 SmallSetVector<CachedHashString, 16> OperandConversionKinds;
1936 SmallSetVector<CachedHashString, 16> InstructionConversionKinds;
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001937 std::vector<std::vector<uint8_t> > ConversionTable;
1938 size_t MaxRowLength = 2; // minimum is custom converter plus terminator.
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001939
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001940 // TargetOperandClass - This is the target's operand class, like X86Operand.
Matthias Braun4a86d452016-12-04 05:48:16 +00001941 std::string TargetOperandClass = Target.getName().str() + "Operand";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00001942
Jim Grosbachc93f6c72012-08-22 01:06:23 +00001943 // Write the convert function to a separate stream, so we can drop it after
1944 // the enum. We'll build up the conversion handlers for the individual
1945 // operand types opportunistically as we encounter them.
1946 std::string ConvertFnBody;
1947 raw_string_ostream CvtOS(ConvertFnBody);
1948 // Start the unified conversion function.
Sam Kolton5f10a132016-05-06 11:31:17 +00001949 if (HasOptionalOperands) {
1950 CvtOS << "void " << Target.getName() << ClassName << "::\n"
1951 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1952 << "unsigned Opcode,\n"
1953 << " const OperandVector &Operands,\n"
1954 << " const SmallBitVector &OptionalOperandsMask) {\n";
1955 } else {
1956 CvtOS << "void " << Target.getName() << ClassName << "::\n"
1957 << "convertToMCInst(unsigned Kind, MCInst &Inst, "
1958 << "unsigned Opcode,\n"
1959 << " const OperandVector &Operands) {\n";
1960 }
1961 CvtOS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
1962 CvtOS << " const uint8_t *Converter = ConversionTable[Kind];\n";
1963 if (HasOptionalOperands) {
Nirav Daveb2f3fad2017-08-07 13:55:27 +00001964 size_t MaxNumOperands = 0;
1965 for (const auto &MI : Infos) {
1966 MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
1967 }
1968 CvtOS << " unsigned DefaultsOffset[" << (MaxNumOperands + 1)
1969 << "] = { 0 };\n";
1970 CvtOS << " assert(OptionalOperandsMask.size() == " << (MaxNumOperands)
1971 << ");\n";
1972 CvtOS << " for (unsigned i = 0, NumDefaults = 0; i < " << (MaxNumOperands)
1973 << "; ++i) {\n";
1974 CvtOS << " DefaultsOffset[i + 1] = NumDefaults;\n";
1975 CvtOS << " NumDefaults += (OptionalOperandsMask[i] ? 1 : 0);\n";
1976 CvtOS << " }\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00001977 }
1978 CvtOS << " unsigned OpIdx;\n";
1979 CvtOS << " Inst.setOpcode(Opcode);\n";
1980 CvtOS << " for (const uint8_t *p = Converter; *p; p+= 2) {\n";
1981 if (HasOptionalOperands) {
Nirav Daveb2f3fad2017-08-07 13:55:27 +00001982 CvtOS << " OpIdx = *(p + 1) - DefaultsOffset[*(p + 1)];\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00001983 } else {
1984 CvtOS << " OpIdx = *(p + 1);\n";
1985 }
1986 CvtOS << " switch (*p) {\n";
1987 CvtOS << " default: llvm_unreachable(\"invalid conversion entry!\");\n";
1988 CvtOS << " case CVT_Reg:\n";
1989 CvtOS << " static_cast<" << TargetOperandClass
1990 << "&>(*Operands[OpIdx]).addRegOperands(Inst, 1);\n";
1991 CvtOS << " break;\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00001992 CvtOS << " case CVT_Tied: {\n";
Simon Pilgrime4d40f92018-02-17 12:29:47 +00001993 CvtOS << " assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
1994 CvtOS << " std::begin(TiedAsmOperandTable)) &&\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00001995 CvtOS << " \"Tied operand not found\");\n";
1996 CvtOS << " unsigned TiedResOpnd = TiedAsmOperandTable[OpIdx][0];\n";
Sander de Smalen118099a2018-06-18 13:39:29 +00001997 CvtOS << " if (TiedResOpnd != (uint8_t) -1)\n";
1998 CvtOS << " Inst.addOperand(Inst.getOperand(TiedResOpnd));\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00001999 CvtOS << " break;\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00002000 CvtOS << " }\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002001
Chad Rosier738ea252012-08-30 17:59:25 +00002002 std::string OperandFnBody;
2003 raw_string_ostream OpOS(OperandFnBody);
2004 // Start the operand number lookup function.
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002005 OpOS << "void " << Target.getName() << ClassName << "::\n"
2006 << "convertToMapAndConstraints(unsigned Kind,\n";
Chad Rosier380a74a2012-10-02 00:25:57 +00002007 OpOS.indent(27);
David Blaikie960ea3f2014-06-08 16:18:35 +00002008 OpOS << "const OperandVector &Operands) {\n"
Chad Rosier98cfa102012-08-31 00:03:31 +00002009 << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002010 << " unsigned NumMCOperands = 0;\n"
Craig Topper91506102012-09-18 01:41:49 +00002011 << " const uint8_t *Converter = ConversionTable[Kind];\n"
2012 << " for (const uint8_t *p = Converter; *p; p+= 2) {\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002013 << " switch (*p) {\n"
2014 << " default: llvm_unreachable(\"invalid conversion entry!\");\n"
2015 << " case CVT_Reg:\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002016 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
Chad Rosier72450332013-01-15 23:07:53 +00002017 << " Operands[*(p + 1)]->setConstraint(\"r\");\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002018 << " ++NumMCOperands;\n"
2019 << " break;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002020 << " case CVT_Tied:\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002021 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002022 << " break;\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002023
2024 // Pre-populate the operand conversion kinds with the standard always
2025 // available entries.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002026 OperandConversionKinds.insert(CachedHashString("CVT_Done"));
2027 OperandConversionKinds.insert(CachedHashString("CVT_Reg"));
2028 OperandConversionKinds.insert(CachedHashString("CVT_Tied"));
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002029 enum { CVT_Done, CVT_Reg, CVT_Tied };
2030
Sander de Smalen5b691a12018-02-04 16:24:17 +00002031 // Map of e.g. <0, 2, 3> -> "Tie_0_2_3" enum label.
Sander de Smalen118099a2018-06-18 13:39:29 +00002032 std::map<std::tuple<uint8_t, uint8_t, uint8_t>, std::string>
Sander de Smalen5b691a12018-02-04 16:24:17 +00002033 TiedOperandsEnumMap;
2034
Craig Topperf34dad92014-11-28 03:53:02 +00002035 for (auto &II : Infos) {
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00002036 // Check if we have a custom match function.
Craig Topperbcd3c372017-05-31 21:12:46 +00002037 StringRef AsmMatchConverter =
2038 II->getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
Tom Stellard74c87c82015-05-26 15:55:50 +00002039 if (!AsmMatchConverter.empty() && II->UseInstAsmMatchConverter) {
Craig Topperbcd3c372017-05-31 21:12:46 +00002040 std::string Signature = ("ConvertCustom_" + AsmMatchConverter).str();
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002041 II->ConversionFnKind = Signature;
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00002042
2043 // Check if we have already generated this signature.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002044 if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00002045 continue;
2046
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002047 // Remember this converter for the kind enum.
2048 unsigned KindID = OperandConversionKinds.size();
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002049 OperandConversionKinds.insert(
2050 CachedHashString("CVT_" + getEnumNameForToken(AsmMatchConverter)));
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00002051
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002052 // Add the converter row for this instruction.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002053 ConversionTable.emplace_back();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002054 ConversionTable.back().push_back(KindID);
2055 ConversionTable.back().push_back(CVT_Done);
2056
2057 // Add the handler to the conversion driver function.
Tim Northoverb3cfb282013-01-10 16:47:31 +00002058 CvtOS << " case CVT_"
2059 << getEnumNameForToken(AsmMatchConverter) << ":\n"
Chad Rosier451ef132012-08-31 22:12:31 +00002060 << " " << AsmMatchConverter << "(Inst, Operands);\n"
Chad Rosier98cfa102012-08-31 00:03:31 +00002061 << " break;\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002062
Chad Rosier738ea252012-08-30 17:59:25 +00002063 // FIXME: Handle the operand number lookup for custom match functions.
Daniel Dunbar77b7c3f2011-02-04 17:12:15 +00002064 continue;
2065 }
2066
Daniel Dunbare10787e2009-08-07 08:26:05 +00002067 // Build the conversion function signature.
2068 std::string Signature = "Convert";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002069
2070 std::vector<uint8_t> ConversionRow;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002071
Chris Lattner5cf8a4a2010-11-02 21:49:44 +00002072 // Compute the convert enum and the case body.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002073 MaxRowLength = std::max(MaxRowLength, II->ResOperands.size()*2 + 1 );
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002074
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002075 for (unsigned i = 0, e = II->ResOperands.size(); i != e; ++i) {
2076 const MatchableInfo::ResOperand &OpInfo = II->ResOperands[i];
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002077
Chris Lattner743081d2010-11-04 00:43:46 +00002078 // Generate code to populate each result operand.
2079 switch (OpInfo.Kind) {
Chris Lattner743081d2010-11-04 00:43:46 +00002080 case MatchableInfo::ResOperand::RenderAsmOperand: {
2081 // This comes from something we parsed.
Craig Topper03ec8012014-11-25 20:11:31 +00002082 const MatchableInfo::AsmOperand &Op =
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002083 II->AsmOperands[OpInfo.AsmOperandNum];
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002084
Chris Lattnere032dbf2010-11-02 22:55:03 +00002085 // Registers are always converted the same, don't duplicate the
2086 // conversion function based on them.
Chris Lattnere032dbf2010-11-02 22:55:03 +00002087 Signature += "__";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002088 std::string Class;
2089 Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName;
2090 Signature += Class;
Bob Wilsonb9b24222011-01-26 19:44:55 +00002091 Signature += utostr(OpInfo.MINumOperands);
Chris Lattner743081d2010-11-04 00:43:46 +00002092 Signature += "_" + itostr(OpInfo.AsmOperandNum);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002093
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002094 // Add the conversion kind, if necessary, and get the associated ID
2095 // the index of its entry in the vector).
2096 std::string Name = "CVT_" + (Op.Class->isRegisterClass() ? "Reg" :
2097 Op.Class->RenderMethod);
Sam Kolton5f10a132016-05-06 11:31:17 +00002098 if (Op.Class->IsOptional) {
2099 // For optional operands we must also care about DefaultMethod
2100 assert(HasOptionalOperands);
2101 Name += "_" + Op.Class->DefaultMethod;
2102 }
Tim Northoverb3cfb282013-01-10 16:47:31 +00002103 Name = getEnumNameForToken(Name);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002104
2105 bool IsNewConverter = false;
2106 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2107 IsNewConverter);
2108
2109 // Add the operand entry to the instruction kind conversion row.
2110 ConversionRow.push_back(ID);
Craig Topperfd2c6a32015-12-31 08:18:23 +00002111 ConversionRow.push_back(OpInfo.AsmOperandNum + HasMnemonicFirst);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002112
2113 if (!IsNewConverter)
2114 break;
2115
2116 // This is a new operand kind. Add a handler for it to the
2117 // converter driver.
Sam Kolton5f10a132016-05-06 11:31:17 +00002118 CvtOS << " case " << Name << ":\n";
2119 if (Op.Class->IsOptional) {
2120 // If optional operand is not present in actual instruction then we
2121 // should call its DefaultMethod before RenderMethod
2122 assert(HasOptionalOperands);
2123 CvtOS << " if (OptionalOperandsMask[*(p + 1) - 1]) {\n"
2124 << " " << Op.Class->DefaultMethod << "()"
2125 << "->" << Op.Class->RenderMethod << "(Inst, "
2126 << OpInfo.MINumOperands << ");\n"
Sam Kolton5f10a132016-05-06 11:31:17 +00002127 << " } else {\n"
2128 << " static_cast<" << TargetOperandClass
2129 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod
2130 << "(Inst, " << OpInfo.MINumOperands << ");\n"
2131 << " }\n";
2132 } else {
2133 CvtOS << " static_cast<" << TargetOperandClass
2134 << "&>(*Operands[OpIdx])." << Op.Class->RenderMethod
2135 << "(Inst, " << OpInfo.MINumOperands << ");\n";
2136 }
2137 CvtOS << " break;\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002138
2139 // Add a handler for the operand number lookup.
2140 OpOS << " case " << Name << ":\n"
Chad Rosier72450332013-01-15 23:07:53 +00002141 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n";
2142
2143 if (Op.Class->isRegisterClass())
2144 OpOS << " Operands[*(p + 1)]->setConstraint(\"r\");\n";
2145 else
2146 OpOS << " Operands[*(p + 1)]->setConstraint(\"m\");\n";
2147 OpOS << " NumMCOperands += " << OpInfo.MINumOperands << ";\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002148 << " break;\n";
Chris Lattner743081d2010-11-04 00:43:46 +00002149 break;
Daniel Dunbarf22553a2010-02-10 08:15:48 +00002150 }
Chris Lattner743081d2010-11-04 00:43:46 +00002151 case MatchableInfo::ResOperand::TiedOperand: {
2152 // If this operand is tied to a previous one, just copy the MCInst
2153 // operand from the earlier one.We can only tie single MCOperand values.
Ulrich Weigande037a492013-04-27 18:48:23 +00002154 assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
Sander de Smalen118099a2018-06-18 13:39:29 +00002155 uint8_t TiedOp = OpInfo.TiedOperands.ResOpnd;
2156 uint8_t SrcOp1 =
2157 OpInfo.TiedOperands.SrcOpnd1Idx + HasMnemonicFirst;
2158 uint8_t SrcOp2 =
2159 OpInfo.TiedOperands.SrcOpnd2Idx + HasMnemonicFirst;
2160 assert((i > TiedOp || TiedOp == (uint8_t)-1) &&
2161 "Tied operand precedes its target!");
Sander de Smalen5b691a12018-02-04 16:24:17 +00002162 auto TiedTupleName = std::string("Tie") + utostr(TiedOp) + '_' +
2163 utostr(SrcOp1) + '_' + utostr(SrcOp2);
2164 Signature += "__" + TiedTupleName;
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002165 ConversionRow.push_back(CVT_Tied);
2166 ConversionRow.push_back(TiedOp);
Sander de Smalen5b691a12018-02-04 16:24:17 +00002167 ConversionRow.push_back(SrcOp1);
2168 ConversionRow.push_back(SrcOp2);
2169
2170 // Also create an 'enum' for this combination of tied operands.
2171 auto Key = std::make_tuple(TiedOp, SrcOp1, SrcOp2);
2172 TiedOperandsEnumMap.emplace(Key, TiedTupleName);
Chris Lattner743081d2010-11-04 00:43:46 +00002173 break;
2174 }
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002175 case MatchableInfo::ResOperand::ImmOperand: {
2176 int64_t Val = OpInfo.ImmVal;
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002177 std::string Ty = "imm_" + itostr(Val);
Hal Finkelf9090722015-01-15 01:33:00 +00002178 Ty = getEnumNameForToken(Ty);
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002179 Signature += "__" + Ty;
2180
2181 std::string Name = "CVT_" + Ty;
2182 bool IsNewConverter = false;
2183 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2184 IsNewConverter);
2185 // Add the operand entry to the instruction kind conversion row.
2186 ConversionRow.push_back(ID);
2187 ConversionRow.push_back(0);
2188
2189 if (!IsNewConverter)
2190 break;
2191
2192 CvtOS << " case " << Name << ":\n"
Jim Grosbache9119e42015-05-13 18:37:00 +00002193 << " Inst.addOperand(MCOperand::createImm(" << Val << "));\n"
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002194 << " break;\n";
2195
Chad Rosier738ea252012-08-30 17:59:25 +00002196 OpOS << " case " << Name << ":\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002197 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2198 << " Operands[*(p + 1)]->setConstraint(\"\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002199 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002200 << " break;\n";
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002201 break;
2202 }
Chris Lattner4869d342010-11-06 19:57:21 +00002203 case MatchableInfo::ResOperand::RegOperand: {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002204 std::string Reg, Name;
Craig Topper24064772014-04-15 07:20:03 +00002205 if (!OpInfo.Register) {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002206 Name = "reg0";
2207 Reg = "0";
Bob Wilson03912ab2011-01-14 22:58:09 +00002208 } else {
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002209 Reg = getQualifiedName(OpInfo.Register);
Matthias Braun4a86d452016-12-04 05:48:16 +00002210 Name = "reg" + OpInfo.Register->getName().str();
Bob Wilson03912ab2011-01-14 22:58:09 +00002211 }
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002212 Signature += "__" + Name;
2213 Name = "CVT_" + Name;
2214 bool IsNewConverter = false;
2215 unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
2216 IsNewConverter);
2217 // Add the operand entry to the instruction kind conversion row.
2218 ConversionRow.push_back(ID);
2219 ConversionRow.push_back(0);
2220
2221 if (!IsNewConverter)
2222 break;
2223 CvtOS << " case " << Name << ":\n"
Jim Grosbache9119e42015-05-13 18:37:00 +00002224 << " Inst.addOperand(MCOperand::createReg(" << Reg << "));\n"
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002225 << " break;\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002226
2227 OpOS << " case " << Name << ":\n"
Chad Rosier2f480a82012-10-12 22:53:36 +00002228 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2229 << " Operands[*(p + 1)]->setConstraint(\"m\");\n"
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002230 << " ++NumMCOperands;\n"
Chad Rosier738ea252012-08-30 17:59:25 +00002231 << " break;\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002232 }
Chris Lattner743081d2010-11-04 00:43:46 +00002233 }
Daniel Dunbare10787e2009-08-07 08:26:05 +00002234 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002235
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002236 // If there were no operands, add to the signature to that effect
2237 if (Signature == "Convert")
2238 Signature += "_NoOperands";
2239
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00002240 II->ConversionFnKind = Signature;
Daniel Dunbare10787e2009-08-07 08:26:05 +00002241
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002242 // Save the signature. If we already have it, don't add a new row
2243 // to the table.
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002244 if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
Daniel Dunbare10787e2009-08-07 08:26:05 +00002245 continue;
2246
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002247 // Add the row to the table.
Craig Topperc4de7ee2015-08-16 21:27:08 +00002248 ConversionTable.push_back(std::move(ConversionRow));
Daniel Dunbare10787e2009-08-07 08:26:05 +00002249 }
Daniel Dunbar71330282009-08-08 05:24:34 +00002250
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002251 // Finish up the converter driver function.
Chad Rosierc38826c2012-09-03 17:39:57 +00002252 CvtOS << " }\n }\n}\n\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002253
Chad Rosier738ea252012-08-30 17:59:25 +00002254 // Finish up the operand number lookup function.
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002255 OpOS << " }\n }\n}\n\n";
Chad Rosier738ea252012-08-30 17:59:25 +00002256
Sander de Smalen5b691a12018-02-04 16:24:17 +00002257 // Output a static table for tied operands.
2258 if (TiedOperandsEnumMap.size()) {
2259 // The number of tied operand combinations will be small in practice,
2260 // but just add the assert to be sure.
Sander de Smalen118099a2018-06-18 13:39:29 +00002261 assert(TiedOperandsEnumMap.size() <= 254 &&
Sander de Smalen5b691a12018-02-04 16:24:17 +00002262 "Too many tied-operand combinations to reference with "
Sander de Smalen118099a2018-06-18 13:39:29 +00002263 "an 8bit offset from the conversion table, where index "
2264 "'255' is reserved as operand not to be copied.");
Sander de Smalen5b691a12018-02-04 16:24:17 +00002265
2266 OS << "enum {\n";
2267 for (auto &KV : TiedOperandsEnumMap) {
2268 OS << " " << KV.second << ",\n";
2269 }
2270 OS << "};\n\n";
2271
Craig Topper88c142b2018-06-18 16:17:46 +00002272 OS << "static const uint8_t TiedAsmOperandTable[][3] = {\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00002273 for (auto &KV : TiedOperandsEnumMap) {
Sander de Smalen118099a2018-06-18 13:39:29 +00002274 OS << " /* " << KV.second << " */ { "
2275 << utostr(std::get<0>(KV.first)) << ", "
2276 << utostr(std::get<1>(KV.first)) << ", "
2277 << utostr(std::get<2>(KV.first)) << " },\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00002278 }
2279 OS << "};\n\n";
2280 } else
Craig Topper88c142b2018-06-18 16:17:46 +00002281 OS << "static const uint8_t TiedAsmOperandTable[][3] = "
Sander de Smalen118099a2018-06-18 13:39:29 +00002282 "{ /* empty */ {0, 0, 0} };\n\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00002283
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002284 OS << "namespace {\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002285
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002286 // Output the operand conversion kind enum.
2287 OS << "enum OperatorConversionKind {\n";
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002288 for (const auto &Converter : OperandConversionKinds)
Craig Topper6e526f12016-01-03 07:33:30 +00002289 OS << " " << Converter << ",\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002290 OS << " CVT_NUM_CONVERTERS\n";
Daniel Dunbar71330282009-08-08 05:24:34 +00002291 OS << "};\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002292
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002293 // Output the instruction conversion kind enum.
2294 OS << "enum InstructionConversionKind {\n";
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002295 for (const auto &Signature : InstructionConversionKinds)
Craig Topper802d3d32015-08-16 21:27:10 +00002296 OS << " " << Signature << ",\n";
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002297 OS << " CVT_NUM_SIGNATURES\n";
2298 OS << "};\n\n";
2299
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002300 OS << "} // end anonymous namespace\n\n";
2301
2302 // Output the conversion table.
Craig Topper91506102012-09-18 01:41:49 +00002303 OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES]["
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002304 << MaxRowLength << "] = {\n";
2305
2306 for (unsigned Row = 0, ERow = ConversionTable.size(); Row != ERow; ++Row) {
2307 assert(ConversionTable[Row].size() % 2 == 0 && "bad conversion row!");
2308 OS << " // " << InstructionConversionKinds[Row] << "\n";
2309 OS << " { ";
Sander de Smalen5b691a12018-02-04 16:24:17 +00002310 for (unsigned i = 0, e = ConversionTable[Row].size(); i != e; i += 2) {
2311 OS << OperandConversionKinds[ConversionTable[Row][i]] << ", ";
2312 if (OperandConversionKinds[ConversionTable[Row][i]] !=
2313 CachedHashString("CVT_Tied")) {
2314 OS << (unsigned)(ConversionTable[Row][i + 1]) << ", ";
2315 continue;
2316 }
2317
2318 // For a tied operand, emit a reference to the TiedAsmOperandTable
2319 // that contains the operand to copy, and the parsed operands to
2320 // check for their tied constraints.
Sander de Smalen118099a2018-06-18 13:39:29 +00002321 auto Key = std::make_tuple((uint8_t)ConversionTable[Row][i + 1],
2322 (uint8_t)ConversionTable[Row][i + 2],
2323 (uint8_t)ConversionTable[Row][i + 3]);
Sander de Smalen5b691a12018-02-04 16:24:17 +00002324 auto TiedOpndEnum = TiedOperandsEnumMap.find(Key);
2325 assert(TiedOpndEnum != TiedOperandsEnumMap.end() &&
2326 "No record for tied operand pair");
2327 OS << TiedOpndEnum->second << ", ";
2328 i += 2;
2329 }
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002330 OS << "CVT_Done },\n";
2331 }
2332
2333 OS << "};\n\n";
2334
2335 // Spit out the conversion driver function.
Daniel Dunbar71330282009-08-08 05:24:34 +00002336 OS << CvtOS.str();
Jim Grosbachc93f6c72012-08-22 01:06:23 +00002337
Chad Rosier738ea252012-08-30 17:59:25 +00002338 // Spit out the operand number lookup function.
2339 OS << OpOS.str();
Craig Topperb64f9152019-04-02 20:52:04 +00002340
2341 return ConversionTable.size();
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002342}
2343
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002344/// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
2345static void emitMatchClassEnumeration(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002346 std::forward_list<ClassInfo> &Infos,
2347 raw_ostream &OS) {
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002348 OS << "namespace {\n\n";
2349
2350 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
2351 << "/// instruction matching.\n";
2352 OS << "enum MatchClassKind {\n";
2353 OS << " InvalidMatchClass = 0,\n";
Tom Stellardb9f235e2016-02-05 19:59:33 +00002354 OS << " OptionalMatchClass = 1,\n";
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002355 ClassInfo::ClassInfoKind LastKind = ClassInfo::Token;
2356 StringRef LastName = "OptionalMatchClass";
Craig Topperf34dad92014-11-28 03:53:02 +00002357 for (const auto &CI : Infos) {
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002358 if (LastKind == ClassInfo::Token && CI.Kind != ClassInfo::Token) {
2359 OS << " MCK_LAST_TOKEN = " << LastName << ",\n";
2360 } else if (LastKind < ClassInfo::UserClass0 &&
2361 CI.Kind >= ClassInfo::UserClass0) {
2362 OS << " MCK_LAST_REGISTER = " << LastName << ",\n";
2363 }
2364 LastKind = (ClassInfo::ClassInfoKind)CI.Kind;
2365 LastName = CI.Name;
2366
David Blaikied749e342014-11-28 20:35:57 +00002367 OS << " " << CI.Name << ", // ";
2368 if (CI.Kind == ClassInfo::Token) {
2369 OS << "'" << CI.ValueName << "'\n";
2370 } else if (CI.isRegisterClass()) {
2371 if (!CI.ValueName.empty())
2372 OS << "register class '" << CI.ValueName << "'\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002373 else
2374 OS << "derived register class\n";
2375 } else {
David Blaikied749e342014-11-28 20:35:57 +00002376 OS << "user defined class '" << CI.ValueName << "'\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002377 }
2378 }
2379 OS << " NumMatchClassKinds\n";
2380 OS << "};\n\n";
2381
2382 OS << "}\n\n";
2383}
2384
Oliver Stannard41dfac32017-10-03 14:34:57 +00002385/// emitMatchClassDiagStrings - Emit a function to get the diagnostic text to be
2386/// used when an assembly operand does not match the expected operand class.
2387static void emitOperandMatchErrorDiagStrings(AsmMatcherInfo &Info, raw_ostream &OS) {
2388 // If the target does not use DiagnosticString for any operands, don't emit
2389 // an unused function.
2390 if (std::all_of(
2391 Info.Classes.begin(), Info.Classes.end(),
2392 [](const ClassInfo &CI) { return CI.DiagnosticString.empty(); }))
2393 return;
2394
2395 OS << "static const char *getMatchKindDiag(" << Info.Target.getName()
2396 << "AsmParser::" << Info.Target.getName()
2397 << "MatchResultTy MatchResult) {\n";
2398 OS << " switch (MatchResult) {\n";
2399
2400 for (const auto &CI: Info.Classes) {
2401 if (!CI.DiagnosticString.empty()) {
2402 assert(!CI.DiagnosticType.empty() &&
2403 "DiagnosticString set without DiagnosticType");
2404 OS << " case " << Info.Target.getName()
2405 << "AsmParser::Match_" << CI.DiagnosticType << ":\n";
2406 OS << " return \"" << CI.DiagnosticString << "\";\n";
2407 }
2408 }
2409
2410 OS << " default:\n";
2411 OS << " return nullptr;\n";
2412
2413 OS << " }\n";
2414 OS << "}\n\n";
2415}
2416
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002417static void emitRegisterMatchErrorFunc(AsmMatcherInfo &Info, raw_ostream &OS) {
2418 OS << "static unsigned getDiagKindFromRegisterClass(MatchClassKind "
2419 "RegisterClass) {\n";
Fangrui Song2e83b2e2018-10-19 06:12:02 +00002420 if (none_of(Info.Classes, [](const ClassInfo &CI) {
2421 return CI.isRegisterClass() && !CI.DiagnosticType.empty();
2422 })) {
Oliver Stannarddab52122017-10-12 09:28:23 +00002423 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2424 } else {
2425 OS << " switch (RegisterClass) {\n";
2426 for (const auto &CI: Info.Classes) {
2427 if (CI.isRegisterClass() && !CI.DiagnosticType.empty()) {
2428 OS << " case " << CI.Name << ":\n";
2429 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
2430 << CI.DiagnosticType << ";\n";
2431 }
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002432 }
Oliver Stannarddab52122017-10-12 09:28:23 +00002433
2434 OS << " default:\n";
2435 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2436
2437 OS << " }\n";
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002438 }
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002439 OS << "}\n\n";
2440}
2441
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002442/// emitValidateOperandClass - Emit the function to validate an operand class.
2443static void emitValidateOperandClass(AsmMatcherInfo &Info,
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002444 raw_ostream &OS) {
David Blaikie960ea3f2014-06-08 16:18:35 +00002445 OS << "static unsigned validateOperandClass(MCParsedAsmOperand &GOp, "
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002446 << "MatchClassKind Kind) {\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00002447 OS << " " << Info.Target.getName() << "Operand &Operand = ("
2448 << Info.Target.getName() << "Operand&)GOp;\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002449
Kevin Enderby1b87c802011-07-15 18:30:43 +00002450 // The InvalidMatchClass is not to match any operand.
2451 OS << " if (Kind == InvalidMatchClass)\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002452 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n\n";
Kevin Enderby1b87c802011-07-15 18:30:43 +00002453
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002454 // Check for Token operands first.
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002455 // FIXME: Use a more specific diagnostic type.
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002456 OS << " if (Operand.isToken() && Kind <= MCK_LAST_TOKEN)\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002457 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
2458 << " MCTargetAsmParser::Match_Success :\n"
2459 << " MCTargetAsmParser::Match_InvalidOperand;\n\n";
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002460
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00002461 // Check the user classes. We don't care what order since we're only
2462 // actually matching against one of them.
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002463 OS << " switch (Kind) {\n"
2464 " default: break;\n";
Craig Topperf34dad92014-11-28 03:53:02 +00002465 for (const auto &CI : Info.Classes) {
David Blaikied749e342014-11-28 20:35:57 +00002466 if (!CI.isUserClass())
Daniel Dunbarbb98db22009-08-11 02:59:53 +00002467 continue;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002468
David Blaikied749e342014-11-28 20:35:57 +00002469 OS << " // '" << CI.ClassName << "' class\n";
Sander de Smalena2fb1d12018-04-26 09:24:45 +00002470 OS << " case " << CI.Name << ": {\n";
2471 OS << " DiagnosticPredicate DP(Operand." << CI.PredicateMethod
2472 << "());\n";
2473 OS << " if (DP.isMatch())\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002474 OS << " return MCTargetAsmParser::Match_Success;\n";
Sander de Smalena2fb1d12018-04-26 09:24:45 +00002475 if (!CI.DiagnosticType.empty()) {
2476 OS << " if (DP.isNearMatch())\n";
2477 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
David Blaikied749e342014-11-28 20:35:57 +00002478 << CI.DiagnosticType << ";\n";
Sander de Smalena2fb1d12018-04-26 09:24:45 +00002479 OS << " break;\n";
2480 }
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002481 else
2482 OS << " break;\n";
Sander de Smalena2fb1d12018-04-26 09:24:45 +00002483 OS << " }\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002484 }
Valery Pykhtin020c29e2016-04-05 16:18:16 +00002485 OS << " } // end switch (Kind)\n\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002486
Owen Anderson8a503f22012-07-16 23:20:09 +00002487 // Check for register operands, including sub-classes.
2488 OS << " if (Operand.isReg()) {\n";
2489 OS << " MatchClassKind OpKind;\n";
2490 OS << " switch (Operand.getReg()) {\n";
2491 OS << " default: OpKind = InvalidMatchClass; break;\n";
Craig Topper03ec8012014-11-25 20:11:31 +00002492 for (const auto &RC : Info.RegisterClasses)
Craig Topper2b347eb2017-07-07 05:19:25 +00002493 OS << " case " << RC.first->getValueAsString("Namespace") << "::"
Craig Topper03ec8012014-11-25 20:11:31 +00002494 << RC.first->getName() << ": OpKind = " << RC.second->Name
Owen Anderson8a503f22012-07-16 23:20:09 +00002495 << "; break;\n";
2496 OS << " }\n";
2497 OS << " return isSubclass(OpKind, Kind) ? "
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002498 << "(unsigned)MCTargetAsmParser::Match_Success :\n "
2499 << " getDiagKindFromRegisterClass(Kind);\n }\n\n";
2500
2501 // Expected operand is a register, but actual is not.
2502 OS << " if (Kind > MCK_LAST_TOKEN && Kind <= MCK_LAST_REGISTER)\n";
2503 OS << " return getDiagKindFromRegisterClass(Kind);\n\n";
Owen Anderson8a503f22012-07-16 23:20:09 +00002504
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002505 // Generic fallthrough match failure case for operands that don't have
2506 // specialized diagnostic types.
2507 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00002508 OS << "}\n\n";
2509}
2510
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002511/// emitIsSubclass - Emit the subclass predicate function.
2512static void emitIsSubclass(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002513 std::forward_list<ClassInfo> &Infos,
Daniel Dunbar2587b612009-08-10 16:05:47 +00002514 raw_ostream &OS) {
Dmitri Gribenko8d302402012-09-15 20:22:05 +00002515 OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n";
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002516 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
Daniel Dunbar2587b612009-08-10 16:05:47 +00002517 OS << " if (A == B)\n";
2518 OS << " return true;\n\n";
2519
Craig Topper39311c72015-12-30 06:00:22 +00002520 bool EmittedSwitch = false;
Craig Topperf34dad92014-11-28 03:53:02 +00002521 for (const auto &A : Infos) {
Jim Grosbachba395922011-12-06 23:43:54 +00002522 std::vector<StringRef> SuperClasses;
Tom Stellardb9f235e2016-02-05 19:59:33 +00002523 if (A.IsOptional)
2524 SuperClasses.push_back("OptionalMatchClass");
Craig Topperf34dad92014-11-28 03:53:02 +00002525 for (const auto &B : Infos) {
David Blaikied749e342014-11-28 20:35:57 +00002526 if (&A != &B && A.isSubsetOf(B))
2527 SuperClasses.push_back(B.Name);
Daniel Dunbar2587b612009-08-10 16:05:47 +00002528 }
Jim Grosbachba395922011-12-06 23:43:54 +00002529
2530 if (SuperClasses.empty())
2531 continue;
2532
Craig Topper39311c72015-12-30 06:00:22 +00002533 // If this is the first SuperClass, emit the switch header.
2534 if (!EmittedSwitch) {
Craig Topper13b2a4e2015-12-30 06:00:24 +00002535 OS << " switch (A) {\n";
Craig Topper39311c72015-12-30 06:00:22 +00002536 OS << " default:\n";
2537 OS << " return false;\n";
2538 EmittedSwitch = true;
2539 }
2540
2541 OS << "\n case " << A.Name << ":\n";
Jim Grosbachba395922011-12-06 23:43:54 +00002542
2543 if (SuperClasses.size() == 1) {
Craig Topper13b2a4e2015-12-30 06:00:24 +00002544 OS << " return B == " << SuperClasses.back() << ";\n";
Jim Grosbachba395922011-12-06 23:43:54 +00002545 continue;
2546 }
2547
Aaron Ballmane59e3582013-07-15 16:53:32 +00002548 if (!SuperClasses.empty()) {
Craig Topper39311c72015-12-30 06:00:22 +00002549 OS << " switch (B) {\n";
2550 OS << " default: return false;\n";
Craig Topper77bd2b72015-12-30 06:00:20 +00002551 for (StringRef SC : SuperClasses)
Craig Topper39311c72015-12-30 06:00:22 +00002552 OS << " case " << SC << ": return true;\n";
2553 OS << " }\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002554 } else {
2555 // No case statement to emit
Craig Topper39311c72015-12-30 06:00:22 +00002556 OS << " return false;\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002557 }
Daniel Dunbar2587b612009-08-10 16:05:47 +00002558 }
Aaron Ballmane59e3582013-07-15 16:53:32 +00002559
Craig Topper39311c72015-12-30 06:00:22 +00002560 // If there were case statements emitted into the string stream write the
2561 // default.
Craig Topperf58323e2016-01-03 07:33:34 +00002562 if (EmittedSwitch)
2563 OS << " }\n";
2564 else
Aaron Ballmane59e3582013-07-15 16:53:32 +00002565 OS << " return false;\n";
2566
Daniel Dunbar2587b612009-08-10 16:05:47 +00002567 OS << "}\n\n";
2568}
2569
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002570/// emitMatchTokenString - Emit the function to match a token string to the
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002571/// appropriate match class value.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002572static void emitMatchTokenString(CodeGenTarget &Target,
David Blaikied749e342014-11-28 20:35:57 +00002573 std::forward_list<ClassInfo> &Infos,
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002574 raw_ostream &OS) {
2575 // Construct the match list.
Chris Lattnerca5a3552010-09-06 02:01:51 +00002576 std::vector<StringMatcher::StringPair> Matches;
Craig Topperf34dad92014-11-28 03:53:02 +00002577 for (const auto &CI : Infos) {
David Blaikied749e342014-11-28 20:35:57 +00002578 if (CI.Kind == ClassInfo::Token)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002579 Matches.emplace_back(CI.ValueName, "return " + CI.Name + ";");
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002580 }
2581
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002582 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002583
Chris Lattnerca5a3552010-09-06 02:01:51 +00002584 StringMatcher("Name", Matches, OS).Emit();
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002585
2586 OS << " return InvalidMatchClass;\n";
2587 OS << "}\n\n";
2588}
Chris Lattner00e2e742009-08-08 20:02:57 +00002589
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002590/// emitMatchRegisterName - Emit the function to match a string to the target
Daniel Dunbard0470d72009-08-07 21:01:44 +00002591/// specific register enum.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002592static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
Daniel Dunbard0470d72009-08-07 21:01:44 +00002593 raw_ostream &OS) {
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002594 // Construct the match list.
Chris Lattnerca5a3552010-09-06 02:01:51 +00002595 std::vector<StringMatcher::StringPair> Matches;
David Blaikie9b613db2014-11-29 18:13:39 +00002596 const auto &Regs = Target.getRegBank().getRegisters();
2597 for (const CodeGenRegister &Reg : Regs) {
2598 if (Reg.TheDef->getValueAsString("AsmName").empty())
Daniel Dunbare2eec052009-07-17 18:51:11 +00002599 continue;
2600
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002601 Matches.emplace_back(Reg.TheDef->getValueAsString("AsmName"),
2602 "return " + utostr(Reg.EnumValue) + ";");
Daniel Dunbare2eec052009-07-17 18:51:11 +00002603 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002604
Chris Lattner60db0a62010-02-09 00:34:28 +00002605 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002606
Alex Bradburyd590c8572017-12-07 09:51:55 +00002607 bool IgnoreDuplicates =
2608 AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
2609 StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
Jim Grosbach0eccfc22010-10-29 22:13:48 +00002610
Daniel Dunbar66f4f542009-08-08 21:22:41 +00002611 OS << " return 0;\n";
Daniel Dunbare10787e2009-08-07 08:26:05 +00002612 OS << "}\n\n";
Daniel Dunbard0470d72009-08-07 21:01:44 +00002613}
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00002614
Dylan McKaybff960a2016-02-03 10:30:16 +00002615/// Emit the function to match a string to the target
2616/// specific register enum.
2617static void emitMatchRegisterAltName(CodeGenTarget &Target, Record *AsmParser,
2618 raw_ostream &OS) {
2619 // Construct the match list.
2620 std::vector<StringMatcher::StringPair> Matches;
2621 const auto &Regs = Target.getRegBank().getRegisters();
2622 for (const CodeGenRegister &Reg : Regs) {
2623
2624 auto AltNames = Reg.TheDef->getValueAsListOfStrings("AltNames");
2625
2626 for (auto AltName : AltNames) {
2627 AltName = StringRef(AltName).trim();
2628
2629 // don't handle empty alternative names
2630 if (AltName.empty())
2631 continue;
2632
2633 Matches.emplace_back(AltName,
2634 "return " + utostr(Reg.EnumValue) + ";");
2635 }
2636 }
2637
2638 OS << "static unsigned MatchRegisterAltName(StringRef Name) {\n";
2639
Alex Bradburyd590c8572017-12-07 09:51:55 +00002640 bool IgnoreDuplicates =
2641 AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
2642 StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
Dylan McKaybff960a2016-02-03 10:30:16 +00002643
2644 OS << " return 0;\n";
2645 OS << "}\n\n";
2646}
2647
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002648/// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
2649static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) {
2650 // Get the set of diagnostic types from all of the operand classes.
2651 std::set<StringRef> Types;
Craig Topper6e526f12016-01-03 07:33:30 +00002652 for (const auto &OpClassEntry : Info.AsmOperandClasses) {
2653 if (!OpClassEntry.second->DiagnosticType.empty())
2654 Types.insert(OpClassEntry.second->DiagnosticType);
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002655 }
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00002656 for (const auto &OpClassEntry : Info.RegisterClassClasses) {
2657 if (!OpClassEntry.second->DiagnosticType.empty())
2658 Types.insert(OpClassEntry.second->DiagnosticType);
2659 }
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002660
2661 if (Types.empty()) return;
2662
2663 // Now emit the enum entries.
Craig Topper6e526f12016-01-03 07:33:30 +00002664 for (StringRef Type : Types)
2665 OS << " Match_" << Type << ",\n";
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00002666 OS << " END_OPERAND_DIAGNOSTIC_TYPES\n";
2667}
2668
Jim Grosbach5117ef72012-04-24 22:40:08 +00002669/// emitGetSubtargetFeatureName - Emit the helper function to get the
2670/// user-level name for a subtarget feature.
2671static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
2672 OS << "// User-level names for subtarget features that participate in\n"
2673 << "// instruction matching.\n"
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002674 << "static const char *getSubtargetFeatureName(uint64_t Val) {\n";
Aaron Ballmane59e3582013-07-15 16:53:32 +00002675 if (!Info.SubtargetFeatures.empty()) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002676 OS << " switch(Val) {\n";
Craig Topper42bd8192014-11-28 03:53:00 +00002677 for (const auto &SF : Info.SubtargetFeatures) {
David Blaikie9a9da992014-11-28 22:15:06 +00002678 const SubtargetFeatureInfo &SFI = SF.second;
Aaron Ballmane59e3582013-07-15 16:53:32 +00002679 // FIXME: Totally just a placeholder name to get the algorithm working.
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002680 OS << " case " << SFI.getEnumBitName() << ": return \""
Aaron Ballmane59e3582013-07-15 16:53:32 +00002681 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
2682 }
2683 OS << " default: return \"(unknown)\";\n";
2684 OS << " }\n";
2685 } else {
2686 // Nothing to emit, so skip the switch
2687 OS << " return \"(unknown)\";\n";
Jim Grosbach5117ef72012-04-24 22:40:08 +00002688 }
Aaron Ballmane59e3582013-07-15 16:53:32 +00002689 OS << "}\n\n";
Jim Grosbach5117ef72012-04-24 22:40:08 +00002690}
2691
Chris Lattner43690072010-10-30 20:15:02 +00002692static std::string GetAliasRequiredFeatures(Record *R,
2693 const AsmMatcherInfo &Info) {
Chris Lattner2cb092d2010-10-30 19:23:13 +00002694 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
Chris Lattner2cb092d2010-10-30 19:23:13 +00002695 std::string Result;
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002696
2697 if (ReqFeatures.empty())
2698 return Result;
2699
Chris Lattner2cb092d2010-10-30 19:23:13 +00002700 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
David Blaikie9a9da992014-11-28 22:15:06 +00002701 const SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002702
Craig Topper24064772014-04-15 07:20:03 +00002703 if (!F)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002704 PrintFatalError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
Chris Lattner517dc952010-11-01 02:09:21 +00002705 "' is not marked as an AssemblerPredicate!");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002706
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002707 if (i)
2708 Result += " && ";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002709
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002710 Result += "Features.test(" + F->getEnumBitName() + ')';
Chris Lattner2cb092d2010-10-30 19:23:13 +00002711 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002712
Chris Lattner2cb092d2010-10-30 19:23:13 +00002713 return Result;
2714}
2715
Chad Rosier9f7a2212013-04-18 22:35:36 +00002716static void emitMnemonicAliasVariant(raw_ostream &OS,const AsmMatcherInfo &Info,
2717 std::vector<Record*> &Aliases,
2718 unsigned Indent = 0,
2719 StringRef AsmParserVariantName = StringRef()){
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002720 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
2721 // iteration order of the map is stable.
2722 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002723
Craig Topper6e526f12016-01-03 07:33:30 +00002724 for (Record *R : Aliases) {
Chad Rosier9f7a2212013-04-18 22:35:36 +00002725 // FIXME: Allow AssemblerVariantName to be a comma separated list.
Craig Topperbcd3c372017-05-31 21:12:46 +00002726 StringRef AsmVariantName = R->getValueAsString("AsmVariantName");
Chad Rosier9f7a2212013-04-18 22:35:36 +00002727 if (AsmVariantName != AsmParserVariantName)
2728 continue;
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002729 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00002730 }
Chad Rosier9f7a2212013-04-18 22:35:36 +00002731 if (AliasesFromMnemonic.empty())
2732 return;
Vladimir Medic75429ad2013-07-16 09:22:38 +00002733
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002734 // Process each alias a "from" mnemonic at a time, building the code executed
2735 // by the string remapper.
2736 std::vector<StringMatcher::StringPair> Cases;
Craig Topper6e526f12016-01-03 07:33:30 +00002737 for (const auto &AliasEntry : AliasesFromMnemonic) {
2738 const std::vector<Record*> &ToVec = AliasEntry.second;
Chris Lattner2cb092d2010-10-30 19:23:13 +00002739
2740 // Loop through each alias and emit code that handles each case. If there
2741 // are two instructions without predicates, emit an error. If there is one,
2742 // emit it last.
2743 std::string MatchCode;
2744 int AliasWithNoPredicate = -1;
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002745
Chris Lattner2cb092d2010-10-30 19:23:13 +00002746 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
2747 Record *R = ToVec[i];
Chris Lattner43690072010-10-30 20:15:02 +00002748 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002749
Chris Lattner2cb092d2010-10-30 19:23:13 +00002750 // If this unconditionally matches, remember it for later and diagnose
2751 // duplicates.
2752 if (FeatureMask.empty()) {
2753 if (AliasWithNoPredicate != -1) {
2754 // We can't have two aliases from the same mnemonic with no predicate.
2755 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
2756 "two MnemonicAliases with the same 'from' mnemonic!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002757 PrintFatalError(R->getLoc(), "this is the other MnemonicAlias.");
Chris Lattner2cb092d2010-10-30 19:23:13 +00002758 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002759
Chris Lattner2cb092d2010-10-30 19:23:13 +00002760 AliasWithNoPredicate = i;
2761 continue;
2762 }
Craig Topper6e526f12016-01-03 07:33:30 +00002763 if (R->getValueAsString("ToMnemonic") == AliasEntry.first)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002764 PrintFatalError(R->getLoc(), "MnemonicAlias to the same string");
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002765
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00002766 if (!MatchCode.empty())
2767 MatchCode += "else ";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002768 MatchCode += "if (" + FeatureMask + ")\n";
Craig Topper2b8419a2017-05-31 19:01:11 +00002769 MatchCode += " Mnemonic = \"";
2770 MatchCode += R->getValueAsString("ToMnemonic");
2771 MatchCode += "\";\n";
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002772 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002773
Chris Lattner2cb092d2010-10-30 19:23:13 +00002774 if (AliasWithNoPredicate != -1) {
2775 Record *R = ToVec[AliasWithNoPredicate];
Chris Lattnerf9ec2fb2010-10-30 19:47:49 +00002776 if (!MatchCode.empty())
2777 MatchCode += "else\n ";
Craig Topper2b8419a2017-05-31 19:01:11 +00002778 MatchCode += "Mnemonic = \"";
2779 MatchCode += R->getValueAsString("ToMnemonic");
2780 MatchCode += "\";\n";
Chris Lattner2cb092d2010-10-30 19:23:13 +00002781 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002782
Chris Lattner2cb092d2010-10-30 19:23:13 +00002783 MatchCode += "return;";
2784
Craig Topper6e526f12016-01-03 07:33:30 +00002785 Cases.push_back(std::make_pair(AliasEntry.first, MatchCode));
Chris Lattnercf9b6e32010-10-30 18:56:12 +00002786 }
Chad Rosier9f7a2212013-04-18 22:35:36 +00002787 StringMatcher("Mnemonic", Cases, OS).Emit(Indent);
2788}
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002789
Chad Rosier9f7a2212013-04-18 22:35:36 +00002790/// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
2791/// emit a function for them and return true, otherwise return false.
2792static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info,
2793 CodeGenTarget &Target) {
2794 // Ignore aliases when match-prefix is set.
2795 if (!MatchPrefix.empty())
2796 return false;
2797
2798 std::vector<Record*> Aliases =
2799 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
2800 if (Aliases.empty()) return false;
2801
2802 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002803 "const FeatureBitset &Features, unsigned VariantID) {\n";
Chad Rosier9f7a2212013-04-18 22:35:36 +00002804 OS << " switch (VariantID) {\n";
2805 unsigned VariantCount = Target.getAsmParserVariantCount();
2806 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2807 Record *AsmVariant = Target.getAsmParserVariant(VC);
2808 int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant");
Craig Topperbcd3c372017-05-31 21:12:46 +00002809 StringRef AsmParserVariantName = AsmVariant->getValueAsString("Name");
Chad Rosier9f7a2212013-04-18 22:35:36 +00002810 OS << " case " << AsmParserVariantNo << ":\n";
2811 emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2,
2812 AsmParserVariantName);
2813 OS << " break;\n";
2814 }
2815 OS << " }\n";
2816
2817 // Emit aliases that apply to all variants.
2818 emitMnemonicAliasVariant(OS, Info, Aliases);
2819
Daniel Dunbare46bc4c2011-01-18 01:59:30 +00002820 OS << "}\n\n";
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00002821
Chris Lattner477fba4f2010-10-30 18:48:18 +00002822 return true;
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00002823}
2824
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00002825static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002826 const AsmMatcherInfo &Info, StringRef ClassName,
2827 StringToOffsetTable &StringTable,
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002828 unsigned MaxMnemonicIndex,
2829 unsigned MaxFeaturesIndex,
2830 bool HasMnemonicFirst) {
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002831 unsigned MaxMask = 0;
Craig Topper869cd5f2015-12-31 08:18:20 +00002832 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
2833 MaxMask |= OMI.OperandMask;
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002834 }
2835
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002836 // Emit the static custom operand parsing table;
2837 OS << "namespace {\n";
2838 OS << " struct OperandMatchEntry {\n";
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002839 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
2840 << " Mnemonic;\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002841 OS << " " << getMinimalTypeForRange(MaxMask)
2842 << " OperandMask;\n";
David Blaikied749e342014-11-28 20:35:57 +00002843 OS << " " << getMinimalTypeForRange(std::distance(
2844 Info.Classes.begin(), Info.Classes.end())) << " Class;\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002845 OS << " " << getMinimalTypeForRange(MaxFeaturesIndex)
2846 << " RequiredFeaturesIdx;\n\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002847 OS << " StringRef getMnemonic() const {\n";
2848 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2849 OS << " MnemonicTable[Mnemonic]);\n";
2850 OS << " }\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002851 OS << " };\n\n";
2852
2853 OS << " // Predicate for searching for an opcode.\n";
2854 OS << " struct LessOpcodeOperand {\n";
2855 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002856 OS << " return LHS.getMnemonic() < RHS;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002857 OS << " }\n";
2858 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002859 OS << " return LHS < RHS.getMnemonic();\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002860 OS << " }\n";
2861 OS << " bool operator()(const OperandMatchEntry &LHS,";
2862 OS << " const OperandMatchEntry &RHS) {\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002863 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002864 OS << " }\n";
2865 OS << " };\n";
2866
2867 OS << "} // end anonymous namespace.\n\n";
2868
2869 OS << "static const OperandMatchEntry OperandMatchTable["
2870 << Info.OperandMatchInfo.size() << "] = {\n";
2871
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002872 OS << " /* Operand List Mnemonic, Mask, Operand Class, Features */\n";
Craig Topper869cd5f2015-12-31 08:18:20 +00002873 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002874 const MatchableInfo &II = *OMI.MI;
2875
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002876 OS << " { ";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002877
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002878 // Store a pascal-style length byte in the mnemonic.
2879 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002880 OS << StringTable.GetOrAddStringOffset(LenMnemonic, false)
Craig Topper7ecfa6d2012-09-18 07:02:21 +00002881 << " /* " << II.Mnemonic << " */, ";
2882
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002883 OS << OMI.OperandMask;
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002884 OS << " /* ";
2885 bool printComma = false;
2886 for (int i = 0, e = 31; i !=e; ++i)
2887 if (OMI.OperandMask & (1 << i)) {
2888 if (printComma)
2889 OS << ", ";
2890 OS << i;
2891 printComma = true;
2892 }
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002893 OS << " */, ";
2894
2895 OS << OMI.CI->Name;
2896
2897 // Write the required features mask.
2898 OS << ", AMFBS";
2899 if (II.RequiredFeatures.empty())
2900 OS << "_None";
2901 else
2902 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i)
2903 OS << '_' << II.RequiredFeatures[i]->TheDef->getName();
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002904
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002905 OS << " },\n";
2906 }
2907 OS << "};\n\n";
2908
2909 // Emit the operand class switch to call the correct custom parser for
2910 // the found operand class.
Alex Bradbury58eba092016-11-01 16:32:05 +00002911 OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
David Blaikie960ea3f2014-06-08 16:18:35 +00002912 << "tryCustomParseOperand(OperandVector"
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002913 << " &Operands,\n unsigned MCK) {\n\n"
2914 << " switch(MCK) {\n";
2915
Craig Topperf34dad92014-11-28 03:53:02 +00002916 for (const auto &CI : Info.Classes) {
David Blaikied749e342014-11-28 20:35:57 +00002917 if (CI.ParserMethod.empty())
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002918 continue;
David Blaikied749e342014-11-28 20:35:57 +00002919 OS << " case " << CI.Name << ":\n"
2920 << " return " << CI.ParserMethod << "(Operands);\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002921 }
2922
2923 OS << " default:\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002924 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002925 OS << " }\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\n";
2928
2929 // Emit the static custom operand parser. This code is very similar with
2930 // the other matcher. Also use MatchResultTy here just in case we go for
2931 // a better error handling.
Alex Bradbury58eba092016-11-01 16:32:05 +00002932 OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
David Blaikie960ea3f2014-06-08 16:18:35 +00002933 << "MatchOperandParserImpl(OperandVector"
Sander de Smalencd6be962017-12-20 11:02:42 +00002934 << " &Operands,\n StringRef Mnemonic,\n"
2935 << " bool ParseForAllFeatures) {\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002936
2937 // Emit code to get the available features.
2938 OS << " // Get the current feature set.\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002939 OS << " const FeatureBitset &AvailableFeatures = getAvailableFeatures();\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002940
2941 OS << " // Get the next operand index.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00002942 OS << " unsigned NextOpNum = Operands.size()"
2943 << (HasMnemonicFirst ? " - 1" : "") << ";\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002944
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002945 // Emit code to search the table.
2946 OS << " // Search the table.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00002947 if (HasMnemonicFirst) {
2948 OS << " auto MnemonicRange =\n";
2949 OS << " std::equal_range(std::begin(OperandMatchTable), "
2950 "std::end(OperandMatchTable),\n";
2951 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2952 } else {
2953 OS << " auto MnemonicRange = std::make_pair(std::begin(OperandMatchTable),"
2954 " std::end(OperandMatchTable));\n";
2955 OS << " if (!Mnemonic.empty())\n";
2956 OS << " MnemonicRange =\n";
2957 OS << " std::equal_range(std::begin(OperandMatchTable), "
2958 "std::end(OperandMatchTable),\n";
2959 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2960 }
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002961
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002962 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002963 OS << " return MatchOperand_NoMatch;\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002964
2965 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2966 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2967
2968 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Benjamin Kramer0764a3f2012-03-03 20:44:43 +00002969 OS << " assert(Mnemonic == it->getMnemonic());\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002970
2971 // Emit check that the required features are available.
2972 OS << " // check if the available features match\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002973 OS << " const FeatureBitset &RequiredFeatures = "
2974 "FeatureBitsets[it->RequiredFeaturesIdx];\n";
Sander de Smalencd6be962017-12-20 11:02:42 +00002975 OS << " if (!ParseForAllFeatures && (AvailableFeatures & "
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00002976 "RequiredFeatures) != RequiredFeatures)\n";
Sander de Smalencd6be962017-12-20 11:02:42 +00002977 OS << " continue;\n\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002978
2979 // Emit check to ensure the operand number matches.
2980 OS << " // check if the operand in question has a custom parser.\n";
2981 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2982 OS << " continue;\n\n";
2983
2984 // Emit call to the custom parser method
2985 OS << " // call custom parse method to handle the operand\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002986 OS << " OperandMatchResultTy Result = ";
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00002987 OS << "tryCustomParseOperand(Operands, it->Class);\n";
Jim Grosbach861e49c2011-02-12 01:34:40 +00002988 OS << " if (Result != MatchOperand_NoMatch)\n";
2989 OS << " return Result;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002990 OS << " }\n\n";
2991
Jim Grosbach861e49c2011-02-12 01:34:40 +00002992 OS << " // Okay, we had no match.\n";
2993 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00002994 OS << "}\n\n";
2995}
2996
Sander de Smalen886510f2018-01-10 10:10:56 +00002997static void emitAsmTiedOperandConstraints(CodeGenTarget &Target,
2998 AsmMatcherInfo &Info,
2999 raw_ostream &OS) {
Sander de Smalen118099a2018-06-18 13:39:29 +00003000 std::string AsmParserName =
3001 Info.AsmParser->getValueAsString("AsmParserClassName");
Sander de Smalen886510f2018-01-10 10:10:56 +00003002 OS << "static bool ";
Sander de Smalen118099a2018-06-18 13:39:29 +00003003 OS << "checkAsmTiedOperandConstraints(const " << Target.getName()
3004 << AsmParserName << "&AsmParser,\n";
3005 OS << " unsigned Kind,\n";
Sander de Smalen886510f2018-01-10 10:10:56 +00003006 OS << " const OperandVector &Operands,\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00003007 OS << " uint64_t &ErrorInfo) {\n";
3008 OS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
3009 OS << " const uint8_t *Converter = ConversionTable[Kind];\n";
3010 OS << " for (const uint8_t *p = Converter; *p; p+= 2) {\n";
3011 OS << " switch (*p) {\n";
3012 OS << " case CVT_Tied: {\n";
3013 OS << " unsigned OpIdx = *(p+1);\n";
Simon Pilgrime4d40f92018-02-17 12:29:47 +00003014 OS << " assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
3015 OS << " std::begin(TiedAsmOperandTable)) &&\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00003016 OS << " \"Tied operand not found\");\n";
3017 OS << " unsigned OpndNum1 = TiedAsmOperandTable[OpIdx][1];\n";
3018 OS << " unsigned OpndNum2 = TiedAsmOperandTable[OpIdx][2];\n";
3019 OS << " if (OpndNum1 != OpndNum2) {\n";
3020 OS << " auto &SrcOp1 = Operands[OpndNum1];\n";
3021 OS << " auto &SrcOp2 = Operands[OpndNum2];\n";
Sander de Smalen118099a2018-06-18 13:39:29 +00003022 OS << " if (SrcOp1->isReg() && SrcOp2->isReg()) {\n";
3023 OS << " if (!AsmParser.regsEqual(*SrcOp1, *SrcOp2)) {\n";
3024 OS << " ErrorInfo = OpndNum2;\n";
3025 OS << " return false;\n";
3026 OS << " }\n";
Sander de Smalen5b691a12018-02-04 16:24:17 +00003027 OS << " }\n";
3028 OS << " }\n";
3029 OS << " break;\n";
3030 OS << " }\n";
3031 OS << " default:\n";
3032 OS << " break;\n";
Sander de Smalen886510f2018-01-10 10:10:56 +00003033 OS << " }\n";
3034 OS << " }\n";
3035 OS << " return true;\n";
3036 OS << "}\n\n";
3037}
3038
Sjoerd Meijer6d14fdf2017-07-05 12:39:13 +00003039static void emitMnemonicSpellChecker(raw_ostream &OS, CodeGenTarget &Target,
3040 unsigned VariantCount) {
Craig Topper2a060282017-10-26 06:46:40 +00003041 OS << "static std::string " << Target.getName()
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003042 << "MnemonicSpellCheck(StringRef S, const FeatureBitset &FBS,"
3043 << " unsigned VariantID) {\n";
Sjoerd Meijer6d14fdf2017-07-05 12:39:13 +00003044 if (!VariantCount)
3045 OS << " return \"\";";
3046 else {
3047 OS << " const unsigned MaxEditDist = 2;\n";
3048 OS << " std::vector<StringRef> Candidates;\n";
Craig Topper05515562017-10-26 06:46:41 +00003049 OS << " StringRef Prev = \"\";\n\n";
3050
3051 OS << " // Find the appropriate table for this asm variant.\n";
3052 OS << " const MatchEntry *Start, *End;\n";
3053 OS << " switch (VariantID) {\n";
3054 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
3055 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3056 Record *AsmVariant = Target.getAsmParserVariant(VC);
3057 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3058 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3059 << "); End = std::end(MatchTable" << VC << "); break;\n";
3060 }
3061 OS << " }\n\n";
3062 OS << " for (auto I = Start; I < End; I++) {\n";
Sjoerd Meijer6d14fdf2017-07-05 12:39:13 +00003063 OS << " // Ignore unsupported instructions.\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003064 OS << " const FeatureBitset &RequiredFeatures = "
3065 "FeatureBitsets[I->RequiredFeaturesIdx];\n";
3066 OS << " if ((FBS & RequiredFeatures) != RequiredFeatures)\n";
Sjoerd Meijer6d14fdf2017-07-05 12:39:13 +00003067 OS << " continue;\n";
3068 OS << "\n";
3069 OS << " StringRef T = I->getMnemonic();\n";
3070 OS << " // Avoid recomputing the edit distance for the same string.\n";
3071 OS << " if (T.equals(Prev))\n";
3072 OS << " continue;\n";
3073 OS << "\n";
3074 OS << " Prev = T;\n";
3075 OS << " unsigned Dist = S.edit_distance(T, false, MaxEditDist);\n";
3076 OS << " if (Dist <= MaxEditDist)\n";
3077 OS << " Candidates.push_back(T);\n";
3078 OS << " }\n";
3079 OS << "\n";
3080 OS << " if (Candidates.empty())\n";
3081 OS << " return \"\";\n";
3082 OS << "\n";
3083 OS << " std::string Res = \", did you mean: \";\n";
3084 OS << " unsigned i = 0;\n";
3085 OS << " for( ; i < Candidates.size() - 1; i++)\n";
3086 OS << " Res += Candidates[i].str() + \", \";\n";
3087 OS << " return Res + Candidates[i].str() + \"?\";\n";
3088 }
3089 OS << "}\n";
3090 OS << "\n";
3091}
3092
3093
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003094// Emit a function mapping match classes to strings, for debugging.
3095static void emitMatchClassKindNames(std::forward_list<ClassInfo> &Infos,
3096 raw_ostream &OS) {
3097 OS << "#ifndef NDEBUG\n";
3098 OS << "const char *getMatchClassName(MatchClassKind Kind) {\n";
3099 OS << " switch (Kind) {\n";
3100
3101 OS << " case InvalidMatchClass: return \"InvalidMatchClass\";\n";
3102 OS << " case OptionalMatchClass: return \"OptionalMatchClass\";\n";
3103 for (const auto &CI : Infos) {
3104 OS << " case " << CI.Name << ": return \"" << CI.Name << "\";\n";
3105 }
3106 OS << " case NumMatchClassKinds: return \"NumMatchClassKinds\";\n";
3107
3108 OS << " }\n";
3109 OS << " llvm_unreachable(\"unhandled MatchClassKind!\");\n";
3110 OS << "}\n\n";
3111 OS << "#endif // NDEBUG\n";
3112}
3113
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003114static std::string
3115getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
3116 std::string Name = "AMFBS";
3117 for (const auto &Feature : FeatureBitset)
3118 Name += ("_" + Feature->getName()).str();
3119 return Name;
3120}
3121
Daniel Dunbard0470d72009-08-07 21:01:44 +00003122void AsmMatcherEmitter::run(raw_ostream &OS) {
Chris Lattner77d369c2010-12-13 00:23:57 +00003123 CodeGenTarget Target(Records);
Daniel Dunbard0470d72009-08-07 21:01:44 +00003124 Record *AsmParser = Target.getAsmParser();
Craig Topperbcd3c372017-05-31 21:12:46 +00003125 StringRef ClassName = AsmParser->getValueAsString("AsmParserClassName");
Daniel Dunbard0470d72009-08-07 21:01:44 +00003126
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003127 // Compute the information on the instructions to match.
Chris Lattner77d369c2010-12-13 00:23:57 +00003128 AsmMatcherInfo Info(AsmParser, Target, Records);
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003129 Info.buildInfo();
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003130
Daniel Dunbar3b8a4662010-02-02 23:46:36 +00003131 // Sort the instruction table using the partial order on classes. We use
3132 // stable_sort to ensure that ambiguous instructions are still
3133 // deterministically ordered.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003134 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
3135 [](const std::unique_ptr<MatchableInfo> &a,
3136 const std::unique_ptr<MatchableInfo> &b){
3137 return *a < *b;});
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003138
Matthias Brauna8eed312016-12-05 19:44:31 +00003139#ifdef EXPENSIVE_CHECKS
3140 // Verify that the table is sorted and operator < works transitively.
3141 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
3142 ++I) {
3143 for (auto J = I; J != E; ++J) {
3144 assert(!(**J < **I));
3145 }
3146 }
3147#endif
3148
Daniel Dunbar71330282009-08-08 05:24:34 +00003149 DEBUG_WITH_TYPE("instruction_info", {
Craig Topperf34dad92014-11-28 03:53:02 +00003150 for (const auto &MI : Info.Matchables)
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003151 MI->dump();
Daniel Dunbare10787e2009-08-07 08:26:05 +00003152 });
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003153
Chris Lattnerad776812010-11-01 05:06:45 +00003154 // Check for ambiguous matchables.
Chris Lattnerc0658cb2010-09-06 21:28:52 +00003155 DEBUG_WITH_TYPE("ambiguous_instrs", {
3156 unsigned NumAmbiguous = 0;
David Blaikie9a6f2832014-12-22 21:26:38 +00003157 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
3158 ++I) {
3159 for (auto J = std::next(I); J != E; ++J) {
3160 const MatchableInfo &A = **I;
3161 const MatchableInfo &B = **J;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003162
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003163 if (A.couldMatchAmbiguouslyWith(B)) {
Chris Lattnerad776812010-11-01 05:06:45 +00003164 errs() << "warning: ambiguous matchables:\n";
Chris Lattnerc0658cb2010-09-06 21:28:52 +00003165 A.dump();
3166 errs() << "\nis incomparable with:\n";
3167 B.dump();
3168 errs() << "\n\n";
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00003169 ++NumAmbiguous;
3170 }
Daniel Dunbarf573b562009-08-09 06:05:33 +00003171 }
Daniel Dunbar3239f022009-08-09 04:00:06 +00003172 }
Chris Lattnerfdb7dec2010-09-06 20:21:47 +00003173 if (NumAmbiguous)
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003174 errs() << "warning: " << NumAmbiguous
Chris Lattnerad776812010-11-01 05:06:45 +00003175 << " ambiguous matchables!\n";
Chris Lattnerc0658cb2010-09-06 21:28:52 +00003176 });
Daniel Dunbar3239f022009-08-09 04:00:06 +00003177
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003178 // Compute the information on the custom operand parsing.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003179 Info.buildOperandMatchInfo();
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003180
Craig Topperfd2c6a32015-12-31 08:18:23 +00003181 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
Sam Kolton5f10a132016-05-06 11:31:17 +00003182 bool HasOptionalOperands = Info.hasOptionalOperands();
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003183 bool ReportMultipleNearMisses =
3184 AsmParser->getValueAsBit("ReportMultipleNearMisses");
Craig Topperfd2c6a32015-12-31 08:18:23 +00003185
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00003186 // Write the output.
3187
Chris Lattner3e4582a2010-09-06 19:11:01 +00003188 // Information for the class declaration.
3189 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
3190 OS << "#undef GET_ASSEMBLER_HEADER\n";
Jim Grosbach860a84d2011-02-11 21:31:55 +00003191 OS << " // This should be included into the middle of the declaration of\n";
Evan Cheng11424442011-07-26 00:24:13 +00003192 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003193 OS << " FeatureBitset ComputeAvailableFeatures(const FeatureBitset& FB) const;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003194 if (HasOptionalOperands) {
3195 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
3196 << "unsigned Opcode,\n"
3197 << " const OperandVector &Operands,\n"
3198 << " const SmallBitVector &OptionalOperandsMask);\n";
3199 } else {
3200 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
3201 << "unsigned Opcode,\n"
3202 << " const OperandVector &Operands);\n";
3203 }
Chad Rosier380a74a2012-10-02 00:25:57 +00003204 OS << " void convertToMapAndConstraints(unsigned Kind,\n ";
Peter Collingbourne0da86302016-10-10 22:49:37 +00003205 OS << " const OperandVector &Operands) override;\n";
Craig Toppera5754e62015-01-03 08:16:29 +00003206 OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003207 << " MCInst &Inst,\n";
3208 if (ReportMultipleNearMisses)
3209 OS << " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
3210 else
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003211 OS << " uint64_t &ErrorInfo,\n"
3212 << " FeatureBitset &MissingFeatures,\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003213 OS << " bool matchingInlineAsm,\n"
Chad Rosier380a74a2012-10-02 00:25:57 +00003214 << " unsigned VariantID = 0);\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003215 if (!ReportMultipleNearMisses)
3216 OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
3217 << " MCInst &Inst,\n"
3218 << " uint64_t &ErrorInfo,\n"
3219 << " bool matchingInlineAsm,\n"
3220 << " unsigned VariantID = 0) {\n"
3221 << " FeatureBitset MissingFeatures;\n"
3222 << " return MatchInstructionImpl(Operands, Inst, ErrorInfo, MissingFeatures,\n"
3223 << " matchingInlineAsm, VariantID);\n"
3224 << " }\n\n";
3225
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003226
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003227 if (!Info.OperandMatchInfo.empty()) {
Jim Grosbach861e49c2011-02-12 01:34:40 +00003228 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00003229 OS << " OperandVector &Operands,\n";
Sander de Smalencd6be962017-12-20 11:02:42 +00003230 OS << " StringRef Mnemonic,\n";
3231 OS << " bool ParseForAllFeatures = false);\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003232
Jim Grosbach1f5c5aa2011-12-06 22:07:02 +00003233 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00003234 OS << " OperandVector &Operands,\n";
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003235 OS << " unsigned MCK);\n\n";
3236 }
3237
Chris Lattner3e4582a2010-09-06 19:11:01 +00003238 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
3239
Jim Grosbach3a8a0fa2012-06-22 23:56:44 +00003240 // Emit the operand match diagnostic enum names.
3241 OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
3242 OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3243 emitOperandDiagnosticTypes(Info, OS);
3244 OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3245
Chris Lattner3e4582a2010-09-06 19:11:01 +00003246 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
3247 OS << "#undef GET_REGISTER_MATCHER\n\n";
3248
Daniel Dunbareefe8612010-07-19 05:44:09 +00003249 // Emit the subtarget feature enumeration.
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003250 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(
Daniel Sanders72db2a32016-11-19 13:05:44 +00003251 Info.SubtargetFeatures, OS);
Daniel Dunbareefe8612010-07-19 05:44:09 +00003252
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00003253 // Emit the function to match a register name to number.
Akira Hatanaka7605630c2012-08-17 20:16:42 +00003254 // This should be omitted for Mips target
3255 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName"))
3256 emitMatchRegisterName(Target, AsmParser, OS);
Chris Lattner3e4582a2010-09-06 19:11:01 +00003257
Dylan McKaybff960a2016-02-03 10:30:16 +00003258 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterAltName"))
3259 emitMatchRegisterAltName(Target, AsmParser, OS);
3260
Chris Lattner3e4582a2010-09-06 19:11:01 +00003261 OS << "#endif // GET_REGISTER_MATCHER\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003262
Craig Topper3ec7c2a2012-04-25 06:56:34 +00003263 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
3264 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
Daniel Dunbar3fb754a2009-08-11 23:23:44 +00003265
Jim Grosbach5117ef72012-04-24 22:40:08 +00003266 // Generate the helper function to get the names for subtarget features.
3267 emitGetSubtargetFeatureName(Info, OS);
3268
Craig Topper3ec7c2a2012-04-25 06:56:34 +00003269 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
3270
3271 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
3272 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
3273
Chris Lattner477fba4f2010-10-30 18:48:18 +00003274 // Generate the function that remaps for mnemonic aliases.
Chad Rosier9f7a2212013-04-18 22:35:36 +00003275 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target);
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00003276
Chad Rosierf4e35dc2012-10-01 23:45:51 +00003277 // Generate the convertToMCInst function to convert operands into an MCInst.
3278 // Also, generate the convertToMapAndConstraints function for MS-style inline
3279 // assembly. The latter doesn't actually generate a MCInst.
Craig Topperb64f9152019-04-02 20:52:04 +00003280 unsigned NumConverters = emitConvertFuncs(Target, ClassName, Info.Matchables,
3281 HasMnemonicFirst,
3282 HasOptionalOperands, OS);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003283
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003284 // Emit the enumeration for classes which participate in matching.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003285 emitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003286
Oliver Stannard41dfac32017-10-03 14:34:57 +00003287 // Emit a function to get the user-visible string to describe an operand
3288 // match failure in diagnostics.
3289 emitOperandMatchErrorDiagStrings(Info, OS);
3290
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00003291 // Emit a function to map register classes to operand match failure codes.
3292 emitRegisterMatchErrorFunc(Info, OS);
3293
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003294 // Emit the routine to match token strings to their match class.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003295 emitMatchTokenString(Target, Info.Classes, OS);
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003296
Daniel Dunbar2587b612009-08-10 16:05:47 +00003297 // Emit the subclass predicate routine.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003298 emitIsSubclass(Target, Info.Classes, OS);
Daniel Dunbar2587b612009-08-10 16:05:47 +00003299
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00003300 // Emit the routine to validate an operand against a match class.
Jim Grosbach8c2beaa2012-04-19 17:52:32 +00003301 emitValidateOperandClass(Info, OS);
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00003302
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003303 emitMatchClassKindNames(Info.Classes, OS);
3304
Daniel Dunbareefe8612010-07-19 05:44:09 +00003305 // Emit the available features compute function.
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003306 SubtargetFeatureInfo::emitComputeAssemblerAvailableFeatures(
Daniel Sanders72db2a32016-11-19 13:05:44 +00003307 Info.Target.getName(), ClassName, "ComputeAvailableFeatures",
3308 Info.SubtargetFeatures, OS);
Daniel Dunbareefe8612010-07-19 05:44:09 +00003309
Sander de Smalen886510f2018-01-10 10:10:56 +00003310 if (!ReportMultipleNearMisses)
3311 emitAsmTiedOperandConstraints(Target, Info, OS);
3312
Craig Toppere2cfeb32012-09-18 06:10:45 +00003313 StringToOffsetTable StringTable;
3314
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003315 size_t MaxNumOperands = 0;
Craig Toppere2cfeb32012-09-18 06:10:45 +00003316 unsigned MaxMnemonicIndex = 0;
Joey Gouly0e76fa72013-09-12 10:28:05 +00003317 bool HasDeprecation = false;
Craig Topperf34dad92014-11-28 03:53:02 +00003318 for (const auto &MI : Info.Matchables) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003319 MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
3320 HasDeprecation |= MI->HasDeprecation;
Craig Toppere2cfeb32012-09-18 06:10:45 +00003321
3322 // Store a pascal-style length byte in the mnemonic.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003323 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
Craig Toppere2cfeb32012-09-18 06:10:45 +00003324 MaxMnemonicIndex = std::max(MaxMnemonicIndex,
3325 StringTable.GetOrAddStringOffset(LenMnemonic, false));
3326 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003327
Craig Topper7ecfa6d2012-09-18 07:02:21 +00003328 OS << "static const char *const MnemonicTable =\n";
3329 StringTable.EmitString(OS);
3330 OS << ";\n\n";
3331
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003332 std::vector<std::vector<Record *>> FeatureBitsets;
3333 for (const auto &MI : Info.Matchables) {
3334 if (MI->RequiredFeatures.empty())
3335 continue;
3336 FeatureBitsets.emplace_back();
3337 for (unsigned I = 0, E = MI->RequiredFeatures.size(); I != E; ++I)
3338 FeatureBitsets.back().push_back(MI->RequiredFeatures[I]->TheDef);
3339 }
3340
3341 llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
3342 const std::vector<Record *> &B) {
3343 if (A.size() < B.size())
3344 return true;
3345 if (A.size() > B.size())
3346 return false;
3347 for (const auto &Pair : zip(A, B)) {
3348 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
3349 return true;
3350 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
3351 return false;
3352 }
3353 return false;
3354 });
3355 FeatureBitsets.erase(
3356 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
3357 FeatureBitsets.end());
3358 OS << "// Feature bitsets.\n"
3359 << "enum : " << getMinimalTypeForRange(FeatureBitsets.size()) << " {\n"
3360 << " AMFBS_None,\n";
3361 for (const auto &FeatureBitset : FeatureBitsets) {
3362 if (FeatureBitset.empty())
3363 continue;
3364 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
3365 }
3366 OS << "};\n\n"
3367 << "const static FeatureBitset FeatureBitsets[] {\n"
3368 << " {}, // AMFBS_None\n";
3369 for (const auto &FeatureBitset : FeatureBitsets) {
3370 if (FeatureBitset.empty())
3371 continue;
3372 OS << " {";
3373 for (const auto &Feature : FeatureBitset) {
3374 const auto &I = Info.SubtargetFeatures.find(Feature);
3375 assert(I != Info.SubtargetFeatures.end() && "Didn't import predicate?");
3376 OS << I->second.getEnumBitName() << ", ";
3377 }
3378 OS << "},\n";
3379 }
3380 OS << "};\n\n";
3381
Simon Pilgrim6bdc7552017-03-31 10:59:37 +00003382 // Emit the static match table; unused classes get initialized to 0 which is
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003383 // guaranteed to be InvalidMatchClass.
3384 //
3385 // FIXME: We can reduce the size of this table very easily. First, we change
3386 // it so that store the kinds in separate bit-fields for each index, which
3387 // only needs to be the max width used for classes at that index (we also need
3388 // to reject based on this during classification). If we then make sure to
3389 // order the match kinds appropriately (putting mnemonics last), then we
3390 // should only end up using a few bits for each class, especially the ones
3391 // following the mnemonic.
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003392 OS << "namespace {\n";
3393 OS << " struct MatchEntry {\n";
Craig Toppere2cfeb32012-09-18 06:10:45 +00003394 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
3395 << " Mnemonic;\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003396 OS << " uint16_t Opcode;\n";
Craig Topperb64f9152019-04-02 20:52:04 +00003397 OS << " " << getMinimalTypeForRange(NumConverters)
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003398 << " ConvertFn;\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003399 OS << " " << getMinimalTypeForRange(FeatureBitsets.size())
3400 << " RequiredFeaturesIdx;\n";
David Blaikied749e342014-11-28 20:35:57 +00003401 OS << " " << getMinimalTypeForRange(
3402 std::distance(Info.Classes.begin(), Info.Classes.end()))
3403 << " Classes[" << MaxNumOperands << "];\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003404 OS << " StringRef getMnemonic() const {\n";
3405 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
3406 OS << " MnemonicTable[Mnemonic]);\n";
3407 OS << " }\n";
Chris Lattner81301972010-09-06 21:22:45 +00003408 OS << " };\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003409
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003410 OS << " // Predicate for searching for an opcode.\n";
Chris Lattner81301972010-09-06 21:22:45 +00003411 OS << " struct LessOpcode {\n";
3412 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003413 OS << " return LHS.getMnemonic() < RHS;\n";
Chris Lattner81301972010-09-06 21:22:45 +00003414 OS << " }\n";
3415 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003416 OS << " return LHS < RHS.getMnemonic();\n";
Chris Lattner81301972010-09-06 21:22:45 +00003417 OS << " }\n";
Chris Lattner62823362010-09-07 06:10:48 +00003418 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
Benjamin Kramer5aeee5f2012-03-03 19:13:26 +00003419 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Chris Lattner62823362010-09-07 06:10:48 +00003420 OS << " }\n";
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003421 OS << " };\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003422
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003423 OS << "} // end anonymous namespace.\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003424
Craig Topper690d8ea2013-07-24 07:33:14 +00003425 unsigned VariantCount = Target.getAsmParserVariantCount();
3426 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3427 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topper690d8ea2013-07-24 07:33:14 +00003428 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003429
Craig Topper690d8ea2013-07-24 07:33:14 +00003430 OS << "static const MatchEntry MatchTable" << VC << "[] = {\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003431
Craig Topperf34dad92014-11-28 03:53:02 +00003432 for (const auto &MI : Info.Matchables) {
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003433 if (MI->AsmVariantID != AsmVariantNo)
Craig Topper690d8ea2013-07-24 07:33:14 +00003434 continue;
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003435
Craig Topper690d8ea2013-07-24 07:33:14 +00003436 // Store a pascal-style length byte in the mnemonic.
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003437 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
Craig Topper690d8ea2013-07-24 07:33:14 +00003438 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003439 << " /* " << MI->Mnemonic << " */, "
Craig Topper2b347eb2017-07-07 05:19:25 +00003440 << Target.getInstNamespace() << "::"
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003441 << MI->getResultInst()->TheDef->getName() << ", "
3442 << MI->ConversionFnKind << ", ";
Craig Topper690d8ea2013-07-24 07:33:14 +00003443
3444 // Write the required features mask.
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003445 OS << "AMFBS";
3446 if (MI->RequiredFeatures.empty())
3447 OS << "_None";
3448 else
3449 for (unsigned i = 0, e = MI->RequiredFeatures.size(); i != e; ++i)
3450 OS << '_' << MI->RequiredFeatures[i]->TheDef->getName();
Craig Topper690d8ea2013-07-24 07:33:14 +00003451
3452 OS << ", { ";
Duncan P. N. Exon Smith5a48cafb2014-11-28 23:00:22 +00003453 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
3454 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
Craig Topper690d8ea2013-07-24 07:33:14 +00003455
3456 if (i) OS << ", ";
3457 OS << Op.Class->Name;
Daniel Dunbareefe8612010-07-19 05:44:09 +00003458 }
Craig Topper690d8ea2013-07-24 07:33:14 +00003459 OS << " }, },\n";
Craig Topper4de73732012-04-02 07:48:39 +00003460 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003461
Craig Topper690d8ea2013-07-24 07:33:14 +00003462 OS << "};\n\n";
3463 }
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003464
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003465 OS << "#include \"llvm/Support/Debug.h\"\n";
3466 OS << "#include \"llvm/Support/Format.h\"\n\n";
3467
Chris Lattner6b6f3dd2010-09-06 21:08:38 +00003468 // Finally, build the match function.
David Blaikie960ea3f2014-06-08 16:18:35 +00003469 OS << "unsigned " << Target.getName() << ClassName << "::\n"
Craig Toppera5754e62015-01-03 08:16:29 +00003470 << "MatchInstructionImpl(const OperandVector &Operands,\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003471 OS << " MCInst &Inst,\n";
3472 if (ReportMultipleNearMisses)
3473 OS << " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
3474 else
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003475 OS << " uint64_t &ErrorInfo,\n"
3476 << " FeatureBitset &MissingFeatures,\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003477 OS << " bool matchingInlineAsm, unsigned VariantID) {\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00003478
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003479 if (!ReportMultipleNearMisses) {
3480 OS << " // Eliminate obvious mismatches.\n";
3481 OS << " if (Operands.size() > "
3482 << (MaxNumOperands + HasMnemonicFirst) << ") {\n";
3483 OS << " ErrorInfo = "
3484 << (MaxNumOperands + HasMnemonicFirst) << ";\n";
3485 OS << " return Match_InvalidOperand;\n";
3486 OS << " }\n\n";
3487 }
Chad Rosiereac13a32012-08-30 21:43:05 +00003488
Daniel Dunbareefe8612010-07-19 05:44:09 +00003489 // Emit code to get the available features.
3490 OS << " // Get the current feature set.\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003491 OS << " const FeatureBitset &AvailableFeatures = getAvailableFeatures();\n\n";
Daniel Dunbareefe8612010-07-19 05:44:09 +00003492
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00003493 OS << " // Get the instruction mnemonic, which is the first token.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003494 if (HasMnemonicFirst) {
3495 OS << " StringRef Mnemonic = ((" << Target.getName()
3496 << "Operand&)*Operands[0]).getToken();\n\n";
3497 } else {
3498 OS << " StringRef Mnemonic;\n";
3499 OS << " if (Operands[0]->isToken())\n";
3500 OS << " Mnemonic = ((" << Target.getName()
3501 << "Operand&)*Operands[0]).getToken();\n\n";
3502 }
Chris Lattnerba7b4fe2010-10-30 17:36:36 +00003503
Chris Lattner477fba4f2010-10-30 18:48:18 +00003504 if (HasMnemonicAliases) {
3505 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
Chad Rosier9f7a2212013-04-18 22:35:36 +00003506 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n";
Chris Lattner477fba4f2010-10-30 18:48:18 +00003507 }
Bob Wilsonf4ee9e52011-01-26 21:26:19 +00003508
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003509 // Emit code to compute the class list for this operand vector.
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003510 if (!ReportMultipleNearMisses) {
3511 OS << " // Some state to try to produce better error messages.\n";
3512 OS << " bool HadMatchOtherThanFeatures = false;\n";
3513 OS << " bool HadMatchOtherThanPredicate = false;\n";
3514 OS << " unsigned RetCode = Match_InvalidOperand;\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003515 OS << " MissingFeatures.set();\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003516 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
3517 OS << " // wrong for all instances of the instruction.\n";
3518 OS << " ErrorInfo = ~0ULL;\n";
3519 }
3520
Sam Kolton5f10a132016-05-06 11:31:17 +00003521 if (HasOptionalOperands) {
3522 OS << " SmallBitVector OptionalOperandsMask(" << MaxNumOperands << ");\n";
3523 }
Chris Lattner81301972010-09-06 21:22:45 +00003524
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003525 // Emit code to search the table.
Craig Topper690d8ea2013-07-24 07:33:14 +00003526 OS << " // Find the appropriate table for this asm variant.\n";
3527 OS << " const MatchEntry *Start, *End;\n";
3528 OS << " switch (VariantID) {\n";
Craig Topper8c714d12015-01-03 08:16:14 +00003529 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
Craig Topper690d8ea2013-07-24 07:33:14 +00003530 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3531 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topper690d8ea2013-07-24 07:33:14 +00003532 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Benjamin Kramer502b9e12014-04-12 16:15:53 +00003533 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3534 << "); End = std::end(MatchTable" << VC << "); break;\n";
Craig Topper690d8ea2013-07-24 07:33:14 +00003535 }
3536 OS << " }\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003537
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003538 OS << " // Search the table.\n";
Craig Topperfd2c6a32015-12-31 08:18:23 +00003539 if (HasMnemonicFirst) {
3540 OS << " auto MnemonicRange = "
3541 "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
3542 } else {
3543 OS << " auto MnemonicRange = std::make_pair(Start, End);\n";
3544 OS << " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
3545 OS << " if (!Mnemonic.empty())\n";
3546 OS << " MnemonicRange = "
3547 "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
3548 }
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003549
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003550 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"AsmMatcher: found \" <<\n"
3551 << " std::distance(MnemonicRange.first, MnemonicRange.second) << \n"
3552 << " \" encodings with mnemonic '\" << Mnemonic << \"'\\n\");\n\n";
3553
Chris Lattner628fbec2010-09-06 21:54:15 +00003554 OS << " // Return a more specific error code if no mnemonics match.\n";
3555 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
3556 OS << " return Match_MnemonicFail;\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003557
Chris Lattner81301972010-09-06 21:22:45 +00003558 OS << " for (const MatchEntry *it = MnemonicRange.first, "
Chris Lattner9026ac02010-09-06 21:23:43 +00003559 << "*ie = MnemonicRange.second;\n";
Chris Lattner81301972010-09-06 21:22:45 +00003560 OS << " it != ie; ++it) {\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003561 OS << " const FeatureBitset &RequiredFeatures = "
3562 "FeatureBitsets[it->RequiredFeaturesIdx];\n";
Sander de Smalencd6be962017-12-20 11:02:42 +00003563 OS << " bool HasRequiredFeatures =\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003564 OS << " (AvailableFeatures & RequiredFeatures) == RequiredFeatures;\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003565 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Trying to match opcode \"\n";
3566 OS << " << MII.getName(it->Opcode) << \"\\n\");\n";
3567
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003568 if (ReportMultipleNearMisses) {
3569 OS << " // Some state to record ways in which this instruction did not match.\n";
3570 OS << " NearMissInfo OperandNearMiss = NearMissInfo::getSuccess();\n";
3571 OS << " NearMissInfo FeaturesNearMiss = NearMissInfo::getSuccess();\n";
3572 OS << " NearMissInfo EarlyPredicateNearMiss = NearMissInfo::getSuccess();\n";
3573 OS << " NearMissInfo LatePredicateNearMiss = NearMissInfo::getSuccess();\n";
Oliver Stannard7ab60602017-12-04 13:42:22 +00003574 OS << " bool MultipleInvalidOperands = false;\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003575 }
3576
Craig Topperfd2c6a32015-12-31 08:18:23 +00003577 if (HasMnemonicFirst) {
3578 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
3579 OS << " assert(Mnemonic == it->getMnemonic());\n";
3580 }
3581
Daniel Dunbareefe8612010-07-19 05:44:09 +00003582 // Emit check that the subclasses match.
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003583 if (!ReportMultipleNearMisses)
3584 OS << " bool OperandsValid = true;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003585 if (HasOptionalOperands) {
3586 OS << " OptionalOperandsMask.reset(0, " << MaxNumOperands << ");\n";
3587 }
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003588 OS << " for (unsigned FormalIdx = " << (HasMnemonicFirst ? "0" : "SIndex")
3589 << ", ActualIdx = " << (HasMnemonicFirst ? "1" : "SIndex")
3590 << "; FormalIdx != " << MaxNumOperands << "; ++FormalIdx) {\n";
3591 OS << " auto Formal = "
3592 << "static_cast<MatchClassKind>(it->Classes[FormalIdx]);\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003593 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3594 OS << " dbgs() << \" Matching formal operand class \" << getMatchClassName(Formal)\n";
3595 OS << " << \" against actual operand at index \" << ActualIdx);\n";
3596 OS << " if (ActualIdx < Operands.size())\n";
3597 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \" (\";\n";
3598 OS << " Operands[ActualIdx]->print(dbgs()); dbgs() << \"): \");\n";
3599 OS << " else\n";
3600 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \": \");\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003601 OS << " if (ActualIdx >= Operands.size()) {\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003602 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"actual operand index out of range \");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003603 if (ReportMultipleNearMisses) {
3604 OS << " bool ThisOperandValid = (Formal == " <<"InvalidMatchClass) || "
3605 "isSubclass(Formal, OptionalMatchClass);\n";
3606 OS << " if (!ThisOperandValid) {\n";
3607 OS << " if (!OperandNearMiss) {\n";
3608 OS << " // Record info about match failure for later use.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003609 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"recording too-few-operands near miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003610 OS << " OperandNearMiss =\n";
3611 OS << " NearMissInfo::getTooFewOperands(Formal, it->Opcode);\n";
Oliver Stannard1e73e952017-11-21 15:16:50 +00003612 OS << " } else if (OperandNearMiss.getKind() != NearMissInfo::NearMissTooFewOperands) {\n";
Oliver Stannard7ab60602017-12-04 13:42:22 +00003613 OS << " // If more than one operand is invalid, give up on this match entry.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003614 OS << " DEBUG_WITH_TYPE(\n";
3615 OS << " \"asm-matcher\",\n";
3616 OS << " dbgs() << \"second invalid operand, giving up on this opcode\\n\");\n";
Oliver Stannard7ab60602017-12-04 13:42:22 +00003617 OS << " MultipleInvalidOperands = true;\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003618 OS << " break;\n";
3619 OS << " }\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003620 OS << " } else {\n";
3621 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"but formal operand not required\\n\");\n";
Oliver Stannard6e943312017-11-21 15:12:05 +00003622 OS << " break;\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003623 OS << " }\n";
3624 OS << " continue;\n";
3625 } else {
3626 OS << " OperandsValid = (Formal == InvalidMatchClass) || isSubclass(Formal, OptionalMatchClass);\n";
3627 OS << " if (!OperandsValid) ErrorInfo = ActualIdx;\n";
3628 if (HasOptionalOperands) {
3629 OS << " OptionalOperandsMask.set(FormalIdx, " << MaxNumOperands
3630 << ");\n";
3631 }
3632 OS << " break;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003633 }
Jim Grosbach6e2e29b2011-02-10 00:08:28 +00003634 OS << " }\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003635 OS << " MCParsedAsmOperand &Actual = *Operands[ActualIdx];\n";
Colin LeMahieu23403c22015-11-09 00:46:46 +00003636 OS << " unsigned Diag = validateOperandClass(Actual, Formal);\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003637 OS << " if (Diag == Match_Success) {\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003638 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3639 OS << " dbgs() << \"match success using generic matcher\\n\");\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003640 OS << " ++ActualIdx;\n";
Chris Lattner339cc7b2010-09-06 22:11:18 +00003641 OS << " continue;\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003642 OS << " }\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003643 OS << " // If the generic handler indicates an invalid operand\n";
3644 OS << " // failure, check for a special case.\n";
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00003645 OS << " if (Diag != Match_Success) {\n";
3646 OS << " unsigned TargetDiag = validateTargetOperandClass(Actual, Formal);\n";
3647 OS << " if (TargetDiag == Match_Success) {\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003648 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3649 OS << " dbgs() << \"match success using target matcher\\n\");\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003650 OS << " ++ActualIdx;\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003651 OS << " continue;\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003652 OS << " }\n";
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00003653 OS << " // If the target matcher returned a specific error code use\n";
3654 OS << " // that, else use the one from the generic matcher.\n";
Sander de Smalencd6be962017-12-20 11:02:42 +00003655 OS << " if (TargetDiag != Match_InvalidOperand && "
3656 "HasRequiredFeatures)\n";
Oliver Stannard29ffd3f2017-10-10 11:00:40 +00003657 OS << " Diag = TargetDiag;\n";
Jim Grosbach86c652a2013-02-06 06:00:06 +00003658 OS << " }\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003659 OS << " // If current formal operand wasn't matched and it is optional\n"
3660 << " // then try to match next formal operand\n";
3661 OS << " if (Diag == Match_InvalidOperand "
Sam Kolton5f10a132016-05-06 11:31:17 +00003662 << "&& isSubclass(Formal, OptionalMatchClass)) {\n";
3663 if (HasOptionalOperands) {
3664 OS << " OptionalOperandsMask.set(FormalIdx);\n";
3665 }
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003666 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"ignoring optional operand\\n\");\n";
Nikolay Haustovea8febd2016-03-01 08:34:43 +00003667 OS << " continue;\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003668 OS << " }\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003669
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003670 if (ReportMultipleNearMisses) {
3671 OS << " if (!OperandNearMiss) {\n";
3672 OS << " // If this is the first invalid operand we have seen, record some\n";
3673 OS << " // information about it.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003674 OS << " DEBUG_WITH_TYPE(\n";
3675 OS << " \"asm-matcher\",\n";
3676 OS << " dbgs()\n";
3677 OS << " << \"operand match failed, recording near-miss with diag code \"\n";
3678 OS << " << Diag << \"\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003679 OS << " OperandNearMiss =\n";
3680 OS << " NearMissInfo::getMissedOperand(Diag, Formal, it->Opcode, ActualIdx);\n";
3681 OS << " ++ActualIdx;\n";
3682 OS << " } else {\n";
3683 OS << " // If more than one operand is invalid, give up on this match entry.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003684 OS << " DEBUG_WITH_TYPE(\n";
3685 OS << " \"asm-matcher\",\n";
3686 OS << " dbgs() << \"second operand mismatch, skipping this opcode\\n\");\n";
Oliver Stannard7ab60602017-12-04 13:42:22 +00003687 OS << " MultipleInvalidOperands = true;\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003688 OS << " break;\n";
3689 OS << " }\n";
3690 OS << " }\n\n";
3691 } else {
3692 OS << " // If this operand is broken for all of the instances of this\n";
3693 OS << " // mnemonic, keep track of it so we can report loc info.\n";
3694 OS << " // If we already had a match that only failed due to a\n";
3695 OS << " // target predicate, that diagnostic is preferred.\n";
3696 OS << " if (!HadMatchOtherThanPredicate &&\n";
3697 OS << " (it == MnemonicRange.first || ErrorInfo <= ActualIdx)) {\n";
Sander de Smalencd6be962017-12-20 11:02:42 +00003698 OS << " if (HasRequiredFeatures && (ErrorInfo != ActualIdx || Diag "
3699 "!= Match_InvalidOperand))\n";
Sander de Smalen4acd57e2017-11-21 15:07:43 +00003700 OS << " RetCode = Diag;\n";
Sander de Smalen14e36ee2017-12-14 16:09:48 +00003701 OS << " ErrorInfo = ActualIdx;\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003702 OS << " }\n";
3703 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
3704 OS << " OperandsValid = false;\n";
3705 OS << " break;\n";
3706 OS << " }\n\n";
3707 }
3708
Oliver Stannard7ab60602017-12-04 13:42:22 +00003709 if (ReportMultipleNearMisses)
3710 OS << " if (MultipleInvalidOperands) {\n";
3711 else
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003712 OS << " if (!OperandsValid) {\n";
Oliver Stannard7ab60602017-12-04 13:42:22 +00003713 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3714 OS << " \"operand mismatches, ignoring \"\n";
3715 OS << " \"this opcode\\n\");\n";
3716 OS << " continue;\n";
3717 OS << " }\n";
Chris Lattnerb4be28f2010-09-06 20:08:02 +00003718
3719 // Emit check that the required features are available.
Sander de Smalencd6be962017-12-20 11:02:42 +00003720 OS << " if (!HasRequiredFeatures) {\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003721 if (!ReportMultipleNearMisses)
3722 OS << " HadMatchOtherThanFeatures = true;\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003723 OS << " FeatureBitset NewMissingFeatures = RequiredFeatures & "
Jim Grosbach9ec06a152012-06-18 19:45:46 +00003724 "~AvailableFeatures;\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003725 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Missing target features:\";\n";
3726 OS << " for (unsigned I = 0, E = NewMissingFeatures.size(); I != E; ++I)\n";
3727 OS << " if (NewMissingFeatures[I])\n";
3728 OS << " dbgs() << ' ' << I;\n";
3729 OS << " dbgs() << \"\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003730 if (ReportMultipleNearMisses) {
3731 OS << " FeaturesNearMiss = NearMissInfo::getMissedFeature(NewMissingFeatures);\n";
3732 } else {
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003733 OS << " if (NewMissingFeatures.count() <=\n"
3734 " MissingFeatures.count())\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003735 OS << " MissingFeatures = NewMissingFeatures;\n";
3736 OS << " continue;\n";
3737 }
Chris Lattnerb4be28f2010-09-06 20:08:02 +00003738 OS << " }\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003739 OS << "\n";
Ahmed Bougacha0dc19792014-12-16 18:05:28 +00003740 OS << " Inst.clear();\n\n";
Daniel Sandersc5537422016-07-27 13:49:44 +00003741 OS << " Inst.setOpcode(it->Opcode);\n";
3742 // Verify the instruction with the target-specific match predicate function.
3743 OS << " // We have a potential match but have not rendered the operands.\n"
3744 << " // Check the target predicate to handle any context sensitive\n"
3745 " // constraints.\n"
3746 << " // For example, Ties that are referenced multiple times must be\n"
3747 " // checked here to ensure the input is the same for each match\n"
3748 " // constraints. If we leave it any later the ties will have been\n"
3749 " // canonicalized\n"
3750 << " unsigned MatchResult;\n"
3751 << " if ((MatchResult = checkEarlyTargetMatchPredicate(Inst, "
3752 "Operands)) != Match_Success) {\n"
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003753 << " Inst.clear();\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003754 OS << " DEBUG_WITH_TYPE(\n";
3755 OS << " \"asm-matcher\",\n";
3756 OS << " dbgs() << \"Early target match predicate failed with diag code \"\n";
3757 OS << " << MatchResult << \"\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003758 if (ReportMultipleNearMisses) {
3759 OS << " EarlyPredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
3760 } else {
3761 OS << " RetCode = MatchResult;\n"
3762 << " HadMatchOtherThanPredicate = true;\n"
3763 << " continue;\n";
3764 }
3765 OS << " }\n\n";
3766
3767 if (ReportMultipleNearMisses) {
3768 OS << " // If we did not successfully match the operands, then we can't convert to\n";
3769 OS << " // an MCInst, so bail out on this instruction variant now.\n";
3770 OS << " if (OperandNearMiss) {\n";
3771 OS << " // If the operand mismatch was the only problem, reprrt it as a near-miss.\n";
3772 OS << " if (NearMisses && !FeaturesNearMiss && !EarlyPredicateNearMiss) {\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003773 OS << " DEBUG_WITH_TYPE(\n";
3774 OS << " \"asm-matcher\",\n";
3775 OS << " dbgs()\n";
3776 OS << " << \"Opcode result: one mismatched operand, adding near-miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003777 OS << " NearMisses->push_back(OperandNearMiss);\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003778 OS << " } else {\n";
3779 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3780 OS << " \"types of mismatch, so not \"\n";
3781 OS << " \"reporting near-miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003782 OS << " }\n";
3783 OS << " continue;\n";
3784 OS << " }\n\n";
3785 }
3786
Chad Rosierf4e35dc2012-10-01 23:45:51 +00003787 OS << " if (matchingInlineAsm) {\n";
Chad Rosier2f480a82012-10-12 22:53:36 +00003788 OS << " convertToMapAndConstraints(it->ConvertFn, Operands);\n";
Sander de Smalen886510f2018-01-10 10:10:56 +00003789 if (!ReportMultipleNearMisses) {
Sander de Smalen118099a2018-06-18 13:39:29 +00003790 OS << " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
3791 "Operands, ErrorInfo))\n";
Sander de Smalen886510f2018-01-10 10:10:56 +00003792 OS << " return Match_InvalidTiedOperand;\n";
Sander de Smalen886510f2018-01-10 10:10:56 +00003793 OS << "\n";
3794 }
Chad Rosierf4e35dc2012-10-01 23:45:51 +00003795 OS << " return Match_Success;\n";
3796 OS << " }\n\n";
Daniel Dunbar66193402011-02-04 17:12:23 +00003797 OS << " // We have selected a definite instruction, convert the parsed\n"
3798 << " // operands into the appropriate MCInst.\n";
Sam Kolton5f10a132016-05-06 11:31:17 +00003799 if (HasOptionalOperands) {
3800 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands,\n"
3801 << " OptionalOperandsMask);\n";
3802 } else {
3803 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
3804 }
Daniel Dunbar66193402011-02-04 17:12:23 +00003805 OS << "\n";
Daniel Dunbar451a4352010-03-18 20:05:56 +00003806
Jim Grosbach120a96a2011-08-15 23:03:29 +00003807 // Verify the instruction with the target-specific match predicate function.
3808 OS << " // We have a potential match. Check the target predicate to\n"
3809 << " // handle any context sensitive constraints.\n"
Jim Grosbach120a96a2011-08-15 23:03:29 +00003810 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
3811 << " Match_Success) {\n"
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003812 << " DEBUG_WITH_TYPE(\"asm-matcher\",\n"
3813 << " dbgs() << \"Target match predicate failed with diag code \"\n"
3814 << " << MatchResult << \"\\n\");\n"
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003815 << " Inst.clear();\n";
3816 if (ReportMultipleNearMisses) {
3817 OS << " LatePredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
3818 } else {
3819 OS << " RetCode = MatchResult;\n"
3820 << " HadMatchOtherThanPredicate = true;\n"
3821 << " continue;\n";
3822 }
3823 OS << " }\n\n";
3824
3825 if (ReportMultipleNearMisses) {
3826 OS << " int NumNearMisses = ((int)(bool)OperandNearMiss +\n";
3827 OS << " (int)(bool)FeaturesNearMiss +\n";
3828 OS << " (int)(bool)EarlyPredicateNearMiss +\n";
3829 OS << " (int)(bool)LatePredicateNearMiss);\n";
3830 OS << " if (NumNearMisses == 1) {\n";
3831 OS << " // We had exactly one type of near-miss, so add that to the list.\n";
3832 OS << " assert(!OperandNearMiss && \"OperandNearMiss was handled earlier\");\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003833 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: found one type of \"\n";
3834 OS << " \"mismatch, so reporting a \"\n";
3835 OS << " \"near-miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003836 OS << " if (NearMisses && FeaturesNearMiss)\n";
3837 OS << " NearMisses->push_back(FeaturesNearMiss);\n";
3838 OS << " else if (NearMisses && EarlyPredicateNearMiss)\n";
3839 OS << " NearMisses->push_back(EarlyPredicateNearMiss);\n";
3840 OS << " else if (NearMisses && LatePredicateNearMiss)\n";
3841 OS << " NearMisses->push_back(LatePredicateNearMiss);\n";
3842 OS << "\n";
3843 OS << " continue;\n";
3844 OS << " } else if (NumNearMisses > 1) {\n";
3845 OS << " // This instruction missed in more than one way, so ignore it.\n";
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003846 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3847 OS << " \"types of mismatch, so not \"\n";
3848 OS << " \"reporting near-miss\\n\");\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003849 OS << " continue;\n";
3850 OS << " }\n";
3851 }
Jim Grosbach120a96a2011-08-15 23:03:29 +00003852
Daniel Dunbar451a4352010-03-18 20:05:56 +00003853 // Call the post-processing function, if used.
Craig Topperbcd3c372017-05-31 21:12:46 +00003854 StringRef InsnCleanupFn = AsmParser->getValueAsString("AsmParserInstCleanup");
Daniel Dunbar451a4352010-03-18 20:05:56 +00003855 if (!InsnCleanupFn.empty())
3856 OS << " " << InsnCleanupFn << "(Inst);\n";
3857
Joey Gouly0e76fa72013-09-12 10:28:05 +00003858 if (HasDeprecation) {
3859 OS << " std::string Info;\n";
Weiming Zhaob38cfce2016-12-05 23:55:13 +00003860 OS << " if (!getParser().getTargetParser().\n";
3861 OS << " getTargetOptions().MCNoDeprecatedWarn &&\n";
3862 OS << " MII.get(Inst.getOpcode()).getDeprecatedInfo(Inst, getSTI(), Info)) {\n";
David Blaikie960ea3f2014-06-08 16:18:35 +00003863 OS << " SMLoc Loc = ((" << Target.getName()
3864 << "Operand&)*Operands[0]).getStartLoc();\n";
Rafael Espindola961d4692014-11-11 05:18:41 +00003865 OS << " getParser().Warning(Loc, Info, None);\n";
Joey Gouly0e76fa72013-09-12 10:28:05 +00003866 OS << " }\n";
3867 }
3868
Sander de Smalen886510f2018-01-10 10:10:56 +00003869 if (!ReportMultipleNearMisses) {
Sander de Smalen118099a2018-06-18 13:39:29 +00003870 OS << " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
3871 "Operands, ErrorInfo))\n";
Craig Topper773ead22018-04-25 06:24:51 +00003872 OS << " return Match_InvalidTiedOperand;\n";
Sander de Smalen886510f2018-01-10 10:10:56 +00003873 OS << "\n";
3874 }
3875
Oliver Stannard4191b9e2017-10-11 09:17:43 +00003876 OS << " DEBUG_WITH_TYPE(\n";
3877 OS << " \"asm-matcher\",\n";
3878 OS << " dbgs() << \"Opcode result: complete match, selecting this opcode\\n\");\n";
Chris Lattnera22a3682010-09-06 19:22:17 +00003879 OS << " return Match_Success;\n";
Daniel Dunbar541efcc2009-08-08 07:50:56 +00003880 OS << " }\n\n";
3881
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003882 if (ReportMultipleNearMisses) {
3883 OS << " // No instruction variants matched exactly.\n";
3884 OS << " return Match_NearMisses;\n";
3885 } else {
3886 OS << " // Okay, we had no match. Try to return a useful error code.\n";
3887 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n";
3888 OS << " return RetCode;\n\n";
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003889 OS << " ErrorInfo = 0;\n";
Oliver Stannard65f7bc52017-10-03 09:33:12 +00003890 OS << " return Match_MissingFeature;\n";
3891 }
Daniel Dunbarb6d6aa22009-07-31 02:32:59 +00003892 OS << "}\n\n";
Jim Grosbach0eccfc22010-10-29 22:13:48 +00003893
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003894 if (!Info.OperandMatchInfo.empty())
Craig Topper7ecfa6d2012-09-18 07:02:21 +00003895 emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable,
Stanislav Mekhanoshine98944e2019-03-11 17:04:35 +00003896 MaxMnemonicIndex, FeatureBitsets.size(),
3897 HasMnemonicFirst);
Bruno Cardoso Lopes2315beb2011-02-07 19:38:32 +00003898
Chris Lattner3e4582a2010-09-06 19:11:01 +00003899 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
Craig Topper2a060282017-10-26 06:46:40 +00003900
3901 OS << "\n#ifdef GET_MNEMONIC_SPELL_CHECKER\n";
3902 OS << "#undef GET_MNEMONIC_SPELL_CHECKER\n\n";
3903
3904 emitMnemonicSpellChecker(OS, Target, VariantCount);
3905
3906 OS << "#endif // GET_MNEMONIC_SPELL_CHECKER\n\n";
Daniel Dunbar3085b572009-07-11 19:39:44 +00003907}
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00003908
3909namespace llvm {
3910
3911void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
3912 emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
3913 AsmMatcherEmitter(RK).run(OS);
3914}
3915
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +00003916} // end namespace llvm