blob: 5b4229e6468240335f49c45dfc8e9b59dfe11ebd [file] [log] [blame]
Daniel Dunbard51ffcf2009-07-11 19:39:44 +00001//===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a target specifier matcher for converting parsed
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +000011// assembly operands in the MCInst structures. It also emits a matcher for
12// custom operand parsing.
13//
14// Converting assembly operands into MCInst structures
15// ---------------------------------------------------
Daniel Dunbard51ffcf2009-07-11 19:39:44 +000016//
Daniel Dunbar20927f22009-08-07 08:26:05 +000017// The input to the target specific matcher is a list of literal tokens and
18// operands. The target specific parser should generally eliminate any syntax
19// which is not relevant for matching; for example, comma tokens should have
20// already been consumed and eliminated by the parser. Most instructions will
21// end up with a single literal token (the instruction name) and some number of
22// operands.
23//
24// Some example inputs, for X86:
25// 'addl' (immediate ...) (register ...)
26// 'add' (immediate ...) (memory ...)
Jim Grosbacha7c78222010-10-29 22:13:48 +000027// 'call' '*' %epc
Daniel Dunbar20927f22009-08-07 08:26:05 +000028//
29// The assembly matcher is responsible for converting this input into a precise
30// machine instruction (i.e., an instruction with a well defined encoding). This
31// mapping has several properties which complicate matching:
32//
33// - It may be ambiguous; many architectures can legally encode particular
34// variants of an instruction in different ways (for example, using a smaller
35// encoding for small immediates). Such ambiguities should never be
36// arbitrarily resolved by the assembler, the assembler is always responsible
37// for choosing the "best" available instruction.
38//
39// - It may depend on the subtarget or the assembler context. Instructions
40// which are invalid for the current mode, but otherwise unambiguous (e.g.,
41// an SSE instruction in a file being assembled for i486) should be accepted
42// and rejected by the assembler front end. However, if the proper encoding
43// for an instruction is dependent on the assembler context then the matcher
44// is responsible for selecting the correct machine instruction for the
45// current mode.
46//
47// The core matching algorithm attempts to exploit the regularity in most
48// instruction sets to quickly determine the set of possibly matching
49// instructions, and the simplify the generated code. Additionally, this helps
50// to ensure that the ambiguities are intentionally resolved by the user.
51//
52// The matching is divided into two distinct phases:
53//
54// 1. Classification: Each operand is mapped to the unique set which (a)
55// contains it, and (b) is the largest such subset for which a single
56// instruction could match all members.
57//
58// For register classes, we can generate these subgroups automatically. For
59// arbitrary operands, we expect the user to define the classes and their
60// relations to one another (for example, 8-bit signed immediates as a
61// subset of 32-bit immediates).
62//
63// By partitioning the operands in this way, we guarantee that for any
64// tuple of classes, any single instruction must match either all or none
65// of the sets of operands which could classify to that tuple.
66//
67// In addition, the subset relation amongst classes induces a partial order
68// on such tuples, which we use to resolve ambiguities.
69//
Daniel Dunbar20927f22009-08-07 08:26:05 +000070// 2. The input can now be treated as a tuple of classes (static tokens are
71// simple singleton sets). Each such tuple should generally map to a single
72// instruction (we currently ignore cases where this isn't true, whee!!!),
73// which we can emit a simple matcher for.
74//
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +000075// Custom Operand Parsing
76// ----------------------
77//
78// Some targets need a custom way to parse operands, some specific instructions
79// can contain arguments that can represent processor flags and other kinds of
Craig Topperbe480ff2012-09-18 01:13:36 +000080// identifiers that need to be mapped to specific values in the final encoded
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +000081// instructions. The target specific custom operand parsing works in the
82// following way:
83//
84// 1. A operand match table is built, each entry contains a mnemonic, an
85// operand class, a mask for all operand positions for that same
86// class/mnemonic and target features to be checked while trying to match.
87//
88// 2. The operand matcher will try every possible entry with the same
89// mnemonic and will check if the target feature for this mnemonic also
90// matches. After that, if the operand to be matched has its index
Chris Lattner7a2bdde2011-04-15 05:18:47 +000091// present in the mask, a successful match occurs. Otherwise, fallback
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +000092// to the regular operand parsing.
93//
94// 3. For a match success, each operand class that has a 'ParserMethod'
95// becomes part of a switch from where the custom method is called.
96//
Daniel Dunbard51ffcf2009-07-11 19:39:44 +000097//===----------------------------------------------------------------------===//
98
Daniel Dunbard51ffcf2009-07-11 19:39:44 +000099#include "CodeGenTarget.h"
Daniel Sanders57a599e2016-11-15 09:51:02 +0000100#include "SubtargetFeatureInfo.h"
Daniel Sanders90085b52016-11-19 12:21:34 +0000101#include "Types.h"
Justin Lebar2c937a12016-10-21 21:45:01 +0000102#include "llvm/ADT/CachedHashString.h"
Chris Lattnerc07bd402010-11-04 02:11:18 +0000103#include "llvm/ADT/PointerUnion.h"
Chandler Carruth4ffd89f2012-12-04 10:37:14 +0000104#include "llvm/ADT/STLExtras.h"
Chris Lattner1de88232010-11-01 01:47:07 +0000105#include "llvm/ADT/SmallPtrSet.h"
Daniel Dunbara027d222009-07-31 02:32:59 +0000106#include "llvm/ADT/SmallVector.h"
Daniel Dunbar20927f22009-08-07 08:26:05 +0000107#include "llvm/ADT/StringExtras.h"
Nico Weber0f38c602018-04-30 14:59:11 +0000108#include "llvm/Config/llvm-config.h"
Daniel Dunbar20927f22009-08-07 08:26:05 +0000109#include "llvm/Support/CommandLine.h"
Daniel Dunbara027d222009-07-31 02:32:59 +0000110#include "llvm/Support/Debug.h"
Craig Topper655b8de2012-02-05 07:21:30 +0000111#include "llvm/Support/ErrorHandling.h"
Peter Collingbourne7c788882011-10-01 16:41:13 +0000112#include "llvm/TableGen/Error.h"
113#include "llvm/TableGen/Record.h"
Douglas Gregorf657da22012-05-02 17:32:48 +0000114#include "llvm/TableGen/StringMatcher.h"
Craig Topperaae60d12013-08-29 05:09:55 +0000115#include "llvm/TableGen/StringToOffsetTable.h"
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000116#include "llvm/TableGen/TableGenBackend.h"
117#include <cassert>
Will Dietze3ba15c2013-10-12 00:55:57 +0000118#include <cctype>
Mehdi Aminif6071e12016-04-18 09:17:29 +0000119#include <forward_list>
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000120#include <map>
121#include <set>
Eugene Zelenko380d47d2016-02-02 18:20:45 +0000122
Daniel Dunbard51ffcf2009-07-11 19:39:44 +0000123using namespace llvm;
124
Chandler Carruth283b3992014-04-21 22:55:11 +0000125#define DEBUG_TYPE "asm-matcher-emitter"
126
Daniel Sandersd5d86072017-03-27 13:15:13 +0000127cl::OptionCategory AsmMatcherEmitterCat("Options for -gen-asm-matcher");
128
Daniel Dunbar27249152009-08-07 20:33:39 +0000129static cl::opt<std::string>
Daniel Sandersd5d86072017-03-27 13:15:13 +0000130 MatchPrefix("match-prefix", cl::init(""),
131 cl::desc("Only match instructions with the given prefix"),
132 cl::cat(AsmMatcherEmitterCat));
Daniel Dunbar20927f22009-08-07 08:26:05 +0000133
Daniel Dunbar20927f22009-08-07 08:26:05 +0000134namespace {
Bob Wilson828295b2011-01-26 21:26:19 +0000135class AsmMatcherInfo;
Daniel Dunbar54074b52010-07-19 05:44:09 +0000136
Tim Northover03f91972013-09-16 16:43:19 +0000137// Register sets are used as keys in some second-order sets TableGen creates
138// when generating its data structures. This means that the order of two
139// RegisterSets can be seen in the outputted AsmMatcher tables occasionally, and
140// can even affect compiler output (at least seen in diagnostics produced when
141// all matches fail). So we use a type that sorts them consistently.
142typedef std::set<Record*, LessRecordByID> RegisterSet;
143
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +0000144class AsmMatcherEmitter {
145 RecordKeeper &Records;
146public:
147 AsmMatcherEmitter(RecordKeeper &R) : Records(R) {}
148
149 void run(raw_ostream &o);
150};
151
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000152/// ClassInfo - Helper class for storing the information about a particular
153/// class of operands which can be matched.
154struct ClassInfo {
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000155 enum ClassInfoKind {
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000156 /// Invalid kind, for use as a sentinel value.
157 Invalid = 0,
158
159 /// The class for a particular token.
160 Token,
161
162 /// The (first) register class, subsequent register classes are
163 /// RegisterClass0+1, and so on.
164 RegisterClass0,
165
166 /// The (first) user defined class, subsequent user defined classes are
167 /// UserClass0+1, and so on.
168 UserClass0 = 1<<16
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000169 };
170
171 /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
172 /// N) for the Nth user defined class.
173 unsigned Kind;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000174
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000175 /// SuperClasses - The super classes of this class. Note that for simplicities
176 /// sake user operands only record their immediate super class, while register
177 /// operands include all superclasses.
178 std::vector<ClassInfo*> SuperClasses;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000179
Daniel Dunbar6745d422009-08-09 05:18:30 +0000180 /// Name - The full class name, suitable for use in an enum.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000181 std::string Name;
182
Daniel Dunbar6745d422009-08-09 05:18:30 +0000183 /// ClassName - The unadorned generic name for this class (e.g., Token).
184 std::string ClassName;
185
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000186 /// ValueName - The name of the value this class represents; for a token this
187 /// is the literal token string, for an operand it is the TableGen class (or
188 /// empty if this is a derived class).
189 std::string ValueName;
190
191 /// PredicateMethod - The name of the operand method to test whether the
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000192 /// operand matches this class; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000193 std::string PredicateMethod;
194
195 /// RenderMethod - The name of the operand method to add this operand to an
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000196 /// MCInst; this is not valid for Token or register kinds.
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000197 std::string RenderMethod;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000198
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000199 /// ParserMethod - The name of the operand method to do a target specific
200 /// parsing on the operand.
201 std::string ParserMethod;
202
Eric Christopher68c7a1c2014-05-20 17:11:11 +0000203 /// For register classes: the records for all the registers in this class.
Tim Northover03f91972013-09-16 16:43:19 +0000204 RegisterSet Registers;
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000205
Eric Christopher68c7a1c2014-05-20 17:11:11 +0000206 /// For custom match classes: the diagnostic kind for when the predicate fails.
Jim Grosbach4dbfdfb2012-06-22 23:56:44 +0000207 std::string DiagnosticType;
Tom Stellard25257d82016-02-05 19:59:33 +0000208
Oliver Stannardfe3c8f92017-10-03 14:34:57 +0000209 /// For custom match classes: the diagnostic string for when the predicate fails.
210 std::string DiagnosticString;
211
Tom Stellard25257d82016-02-05 19:59:33 +0000212 /// Is this operand optional and not always required.
213 bool IsOptional;
214
Sam Koltonf117ec12016-05-06 11:31:17 +0000215 /// DefaultMethod - The name of the method that returns the default operand
216 /// for optional operand
217 std::string DefaultMethod;
218
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000219public:
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000220 /// isRegisterClass() - Check if this is a register class.
221 bool isRegisterClass() const {
222 return Kind >= RegisterClass0 && Kind < UserClass0;
223 }
224
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000225 /// isUserClass() - Check if this is a user defined class.
226 bool isUserClass() const {
227 return Kind >= UserClass0;
228 }
229
Dmitri Gribenko4e0ae442012-09-15 20:22:05 +0000230 /// isRelatedTo - Check whether this class is "related" to \p RHS. Classes
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000231 /// are related if they are in the same class hierarchy.
232 bool isRelatedTo(const ClassInfo &RHS) const {
233 // Tokens are only related to tokens.
234 if (Kind == Token || RHS.Kind == Token)
235 return Kind == Token && RHS.Kind == Token;
236
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000237 // Registers classes are only related to registers classes, and only if
238 // their intersection is non-empty.
239 if (isRegisterClass() || RHS.isRegisterClass()) {
240 if (!isRegisterClass() || !RHS.isRegisterClass())
241 return false;
242
Tim Northover03f91972013-09-16 16:43:19 +0000243 RegisterSet Tmp;
244 std::insert_iterator<RegisterSet> II(Tmp, Tmp.begin());
Jim Grosbacha7c78222010-10-29 22:13:48 +0000245 std::set_intersection(Registers.begin(), Registers.end(),
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000246 RHS.Registers.begin(), RHS.Registers.end(),
Tim Northover03f91972013-09-16 16:43:19 +0000247 II, LessRecordByID());
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000248
249 return !Tmp.empty();
250 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000251
252 // Otherwise we have two users operands; they are related if they are in the
253 // same class hierarchy.
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000254 //
255 // FIXME: This is an oversimplification, they should only be related if they
256 // intersect, however we don't have that information.
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000257 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
258 const ClassInfo *Root = this;
259 while (!Root->SuperClasses.empty())
260 Root = Root->SuperClasses.front();
261
Daniel Dunbar8409bfb2009-08-11 20:10:07 +0000262 const ClassInfo *RHSRoot = &RHS;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000263 while (!RHSRoot->SuperClasses.empty())
264 RHSRoot = RHSRoot->SuperClasses.front();
Jim Grosbacha7c78222010-10-29 22:13:48 +0000265
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000266 return Root == RHSRoot;
267 }
268
Dmitri Gribenko4e0ae442012-09-15 20:22:05 +0000269 /// isSubsetOf - Test whether this class is a subset of \p RHS.
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000270 bool isSubsetOf(const ClassInfo &RHS) const {
271 // This is a subset of RHS if it is the same class...
272 if (this == &RHS)
273 return true;
274
275 // ... or if any of its super classes are a subset of RHS.
Marcello Maggionif185b902018-07-13 16:36:14 +0000276 SmallVector<const ClassInfo *, 16> Worklist(SuperClasses.begin(),
277 SuperClasses.end());
278 SmallPtrSet<const ClassInfo *, 16> Visited;
279 while (!Worklist.empty()) {
280 auto *CI = Worklist.pop_back_val();
281 if (CI == &RHS)
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000282 return true;
Marcello Maggionif185b902018-07-13 16:36:14 +0000283 for (auto *Super : CI->SuperClasses)
284 if (Visited.insert(Super).second)
285 Worklist.push_back(Super);
286 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000287
288 return false;
Daniel Dunbar5fe63382009-08-09 07:20:21 +0000289 }
290
Oliver Stannard09f29b22016-01-25 10:20:19 +0000291 int getTreeDepth() const {
292 int Depth = 0;
293 const ClassInfo *Root = this;
294 while (!Root->SuperClasses.empty()) {
295 Depth++;
296 Root = Root->SuperClasses.front();
297 }
298 return Depth;
299 }
300
301 const ClassInfo *findRoot() const {
302 const ClassInfo *Root = this;
303 while (!Root->SuperClasses.empty())
304 Root = Root->SuperClasses.front();
305 return Root;
306 }
307
308 /// Compare two classes. This does not produce a total ordering, but does
309 /// guarantee that subclasses are sorted before their parents, and that the
310 /// ordering is transitive.
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000311 bool operator<(const ClassInfo &RHS) const {
Daniel Dunbar368a4562010-05-27 05:31:32 +0000312 if (this == &RHS)
313 return false;
314
Oliver Stannard09f29b22016-01-25 10:20:19 +0000315 // First, enforce the ordering between the three different types of class.
316 // Tokens sort before registers, which sort before user classes.
317 if (Kind == Token) {
318 if (RHS.Kind != Token)
Duncan Sands34727662010-07-12 08:16:59 +0000319 return true;
Oliver Stannard09f29b22016-01-25 10:20:19 +0000320 assert(RHS.Kind == Token);
321 } else if (isRegisterClass()) {
322 if (RHS.Kind == Token)
Duncan Sands34727662010-07-12 08:16:59 +0000323 return false;
Oliver Stannard09f29b22016-01-25 10:20:19 +0000324 else if (RHS.isUserClass())
325 return true;
326 assert(RHS.isRegisterClass());
327 } else if (isUserClass()) {
328 if (!RHS.isUserClass())
329 return false;
330 assert(RHS.isUserClass());
331 } else {
332 llvm_unreachable("Unknown ClassInfoKind");
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000333 }
Oliver Stannard09f29b22016-01-25 10:20:19 +0000334
335 if (Kind == Token || isUserClass()) {
336 // Related tokens and user classes get sorted by depth in the inheritence
337 // tree (so that subclasses are before their parents).
338 if (isRelatedTo(RHS)) {
339 if (getTreeDepth() > RHS.getTreeDepth())
340 return true;
341 if (getTreeDepth() < RHS.getTreeDepth())
342 return false;
343 } else {
344 // Unrelated tokens and user classes are ordered by the name of their
345 // root nodes, so that there is a consistent ordering between
346 // unconnected trees.
347 return findRoot()->ValueName < RHS.findRoot()->ValueName;
348 }
349 } else if (isRegisterClass()) {
350 // For register sets, sort by number of registers. This guarantees that
351 // a set will always sort before all of it's strict supersets.
352 if (Registers.size() != RHS.Registers.size())
353 return Registers.size() < RHS.Registers.size();
354 } else {
355 llvm_unreachable("Unknown ClassInfoKind");
356 }
357
358 // FIXME: We should be able to just return false here, as we only need a
359 // partial order (we use stable sorts, so this is deterministic) and the
360 // name of a class shouldn't be significant. However, some of the backends
361 // accidentally rely on this behaviour, so it will have to stay like this
362 // until they are fixed.
363 return ValueName < RHS.ValueName;
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000364 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000365};
366
Colin LeMahieu1539acf2015-11-09 00:31:07 +0000367class AsmVariantInfo {
368public:
Craig Topper2a129872017-05-31 21:12:46 +0000369 StringRef RegisterPrefix;
370 StringRef TokenizingCharacters;
371 StringRef SeparatorCharacters;
372 StringRef BreakCharacters;
373 StringRef Name;
Craig Toppere6b50232015-12-30 06:00:18 +0000374 int AsmVariantNo;
Colin LeMahieu1539acf2015-11-09 00:31:07 +0000375};
376
Chris Lattner22bc5c42010-11-01 05:06:45 +0000377/// MatchableInfo - Helper class for storing the necessary information for an
378/// instruction or alias which is capable of being matched.
379struct MatchableInfo {
Chris Lattnerc0b14a22010-11-03 19:47:34 +0000380 struct AsmOperand {
Chris Lattnerd19ec052010-11-02 17:30:52 +0000381 /// Token - This is the token that the operand came from.
382 StringRef Token;
Bob Wilson828295b2011-01-26 21:26:19 +0000383
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000384 /// The unique class instance this operand should match.
385 ClassInfo *Class;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000386
Chris Lattner567820c2010-11-04 01:42:59 +0000387 /// The operand name this is, if anything.
388 StringRef SrcOpName;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000389
Sander de Smalencb6c95b2018-02-04 16:24:17 +0000390 /// The operand name this is, before renaming for tied operands.
391 StringRef OrigSrcOpName;
392
Bob Wilsona49c7df2011-01-26 19:44:55 +0000393 /// The suboperand index within SrcOpName, or -1 for the entire operand.
394 int SubOpIdx;
Bob Wilson828295b2011-01-26 21:26:19 +0000395
Ahmed Bougachad4b59dc2015-05-29 01:03:37 +0000396 /// Whether the token is "isolated", i.e., it is preceded and followed
397 /// by separators.
398 bool IsIsolatedToken;
399
Devang Patel63faf822012-01-07 01:33:34 +0000400 /// Register record if this token is singleton register.
401 Record *SingletonReg;
402
Ahmed Bougachad4b59dc2015-05-29 01:03:37 +0000403 explicit AsmOperand(bool IsIsolatedToken, StringRef T)
404 : Token(T), Class(nullptr), SubOpIdx(-1),
405 IsIsolatedToken(IsIsolatedToken), SingletonReg(nullptr) {}
Daniel Dunbar20927f22009-08-07 08:26:05 +0000406 };
Bob Wilson828295b2011-01-26 21:26:19 +0000407
Chris Lattner1d13bda2010-11-04 00:43:46 +0000408 /// ResOperand - This represents a single operand in the result instruction
409 /// generated by the match. In cases (like addressing modes) where a single
410 /// assembler operand expands to multiple MCOperands, this represents the
411 /// single assembler operand, not the MCOperand.
412 struct ResOperand {
413 enum {
414 /// RenderAsmOperand - This represents an operand result that is
415 /// generated by calling the render method on the assembly operand. The
416 /// corresponding AsmOperand is specified by AsmOperandNum.
417 RenderAsmOperand,
Bob Wilson828295b2011-01-26 21:26:19 +0000418
Chris Lattner1d13bda2010-11-04 00:43:46 +0000419 /// TiedOperand - This represents a result operand that is a duplicate of
420 /// a previous result operand.
Chris Lattner98c870f2010-11-06 19:25:43 +0000421 TiedOperand,
Bob Wilson828295b2011-01-26 21:26:19 +0000422
Chris Lattner98c870f2010-11-06 19:25:43 +0000423 /// ImmOperand - This represents an immediate value that is dumped into
424 /// the operand.
Chris Lattner90fd7972010-11-06 19:57:21 +0000425 ImmOperand,
Bob Wilson828295b2011-01-26 21:26:19 +0000426
Chris Lattner90fd7972010-11-06 19:57:21 +0000427 /// RegOperand - This represents a fixed register that is dumped in.
428 RegOperand
Chris Lattner1d13bda2010-11-04 00:43:46 +0000429 } Kind;
Bob Wilson828295b2011-01-26 21:26:19 +0000430
Sander de Smalencb6c95b2018-02-04 16:24:17 +0000431 /// Tuple containing the index of the (earlier) result operand that should
432 /// be copied from, as well as the indices of the corresponding (parsed)
433 /// operands in the asm string.
434 struct TiedOperandsTuple {
435 unsigned ResOpnd;
436 unsigned SrcOpnd1Idx;
437 unsigned SrcOpnd2Idx;
438 };
439
Chris Lattner1d13bda2010-11-04 00:43:46 +0000440 union {
441 /// This is the operand # in the AsmOperands list that this should be
442 /// copied from.
443 unsigned AsmOperandNum;
Bob Wilson828295b2011-01-26 21:26:19 +0000444
Sander de Smalencb6c95b2018-02-04 16:24:17 +0000445 /// Description of tied operands.
446 TiedOperandsTuple TiedOperands;
Bob Wilson828295b2011-01-26 21:26:19 +0000447
Chris Lattner98c870f2010-11-06 19:25:43 +0000448 /// ImmVal - This is the immediate value added to the instruction.
449 int64_t ImmVal;
Bob Wilson828295b2011-01-26 21:26:19 +0000450
Chris Lattner90fd7972010-11-06 19:57:21 +0000451 /// Register - This is the register record.
452 Record *Register;
Chris Lattner1d13bda2010-11-04 00:43:46 +0000453 };
Bob Wilson828295b2011-01-26 21:26:19 +0000454
Bob Wilsona49c7df2011-01-26 19:44:55 +0000455 /// MINumOperands - The number of MCInst operands populated by this
456 /// operand.
457 unsigned MINumOperands;
Bob Wilson828295b2011-01-26 21:26:19 +0000458
Bob Wilsona49c7df2011-01-26 19:44:55 +0000459 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
Chris Lattner1d13bda2010-11-04 00:43:46 +0000460 ResOperand X;
461 X.Kind = RenderAsmOperand;
462 X.AsmOperandNum = AsmOpNum;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000463 X.MINumOperands = NumOperands;
Chris Lattner1d13bda2010-11-04 00:43:46 +0000464 return X;
465 }
Bob Wilson828295b2011-01-26 21:26:19 +0000466
Sander de Smalencb6c95b2018-02-04 16:24:17 +0000467 static ResOperand getTiedOp(unsigned TiedOperandNum, unsigned SrcOperand1,
468 unsigned SrcOperand2) {
Chris Lattner1d13bda2010-11-04 00:43:46 +0000469 ResOperand X;
470 X.Kind = TiedOperand;
Sander de Smalencb6c95b2018-02-04 16:24:17 +0000471 X.TiedOperands = { TiedOperandNum, SrcOperand1, SrcOperand2 };
Bob Wilsona49c7df2011-01-26 19:44:55 +0000472 X.MINumOperands = 1;
Chris Lattner1d13bda2010-11-04 00:43:46 +0000473 return X;
474 }
Bob Wilson828295b2011-01-26 21:26:19 +0000475
Bob Wilsona49c7df2011-01-26 19:44:55 +0000476 static ResOperand getImmOp(int64_t Val) {
Chris Lattner98c870f2010-11-06 19:25:43 +0000477 ResOperand X;
478 X.Kind = ImmOperand;
479 X.ImmVal = Val;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000480 X.MINumOperands = 1;
Chris Lattner98c870f2010-11-06 19:25:43 +0000481 return X;
482 }
Bob Wilson828295b2011-01-26 21:26:19 +0000483
Bob Wilsona49c7df2011-01-26 19:44:55 +0000484 static ResOperand getRegOp(Record *Reg) {
Chris Lattner90fd7972010-11-06 19:57:21 +0000485 ResOperand X;
486 X.Kind = RegOperand;
487 X.Register = Reg;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000488 X.MINumOperands = 1;
Chris Lattner90fd7972010-11-06 19:57:21 +0000489 return X;
490 }
Chris Lattner1d13bda2010-11-04 00:43:46 +0000491 };
Daniel Dunbar20927f22009-08-07 08:26:05 +0000492
Devang Patel56315d32012-01-10 17:50:43 +0000493 /// AsmVariantID - Target's assembly syntax variant no.
494 int AsmVariantID;
495
David Blaikied39a5d42014-12-22 21:26:26 +0000496 /// AsmString - The assembly string for this instruction (with variants
497 /// removed), e.g. "movsx $src, $dst".
498 std::string AsmString;
499
Chris Lattner3b5aec62010-11-02 17:34:28 +0000500 /// TheDef - This is the definition of the instruction or InstAlias that this
501 /// matchable came from.
Chris Lattner5bc93872010-11-01 04:34:44 +0000502 Record *const TheDef;
Bob Wilson828295b2011-01-26 21:26:19 +0000503
Chris Lattnerc07bd402010-11-04 02:11:18 +0000504 /// DefRec - This is the definition that it came from.
505 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
Bob Wilson828295b2011-01-26 21:26:19 +0000506
Chris Lattner662e5a32010-11-06 07:14:44 +0000507 const CodeGenInstruction *getResultInst() const {
508 if (DefRec.is<const CodeGenInstruction*>())
509 return DefRec.get<const CodeGenInstruction*>();
510 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
511 }
Bob Wilson828295b2011-01-26 21:26:19 +0000512
Chris Lattner1d13bda2010-11-04 00:43:46 +0000513 /// ResOperands - This is the operand list that should be built for the result
514 /// MCInst.
Jim Grosbachb423d182012-04-19 17:52:34 +0000515 SmallVector<ResOperand, 8> ResOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000516
Chris Lattnerd19ec052010-11-02 17:30:52 +0000517 /// Mnemonic - This is the first token of the matched instruction, its
518 /// mnemonic.
519 StringRef Mnemonic;
Bob Wilson828295b2011-01-26 21:26:19 +0000520
Chris Lattner3116fef2010-11-02 01:03:43 +0000521 /// AsmOperands - The textual operands that this instruction matches,
Chris Lattner3b5aec62010-11-02 17:34:28 +0000522 /// annotated with a class and where in the OperandList they were defined.
523 /// This directly corresponds to the tokenized AsmString after the mnemonic is
524 /// removed.
Jim Grosbachb423d182012-04-19 17:52:34 +0000525 SmallVector<AsmOperand, 8> AsmOperands;
Daniel Dunbar20927f22009-08-07 08:26:05 +0000526
Daniel Dunbar54074b52010-07-19 05:44:09 +0000527 /// Predicates - The required subtarget features to match this instruction.
David Blaikie5f951402014-11-28 22:15:06 +0000528 SmallVector<const SubtargetFeatureInfo *, 4> RequiredFeatures;
Daniel Dunbar54074b52010-07-19 05:44:09 +0000529
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000530 /// ConversionFnKind - The enum value which is passed to the generated
Chad Rosier90e11f82012-09-05 01:02:38 +0000531 /// convertToMCInst to convert parsed operands into an MCInst for this
Daniel Dunbarb7479c02009-08-08 05:24:34 +0000532 /// function.
533 std::string ConversionFnKind;
Bob Wilson828295b2011-01-26 21:26:19 +0000534
Joey Gouly715d98d2013-09-12 10:28:05 +0000535 /// If this instruction is deprecated in some form.
536 bool HasDeprecation;
537
Tom Stellard75775932015-05-26 15:55:50 +0000538 /// If this is an alias, this is use to determine whether or not to using
539 /// the conversion function defined by the instruction's AsmMatchConverter
540 /// or to use the function generated by the alias.
541 bool UseInstAsmMatchConverter;
542
Chris Lattner22bc5c42010-11-01 05:06:45 +0000543 MatchableInfo(const CodeGenInstruction &CGI)
Tom Stellard75775932015-05-26 15:55:50 +0000544 : AsmVariantID(0), AsmString(CGI.AsmString), TheDef(CGI.TheDef), DefRec(&CGI),
545 UseInstAsmMatchConverter(true) {
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +0000546 }
Chris Lattner5bc93872010-11-01 04:34:44 +0000547
David Blaikied39a5d42014-12-22 21:26:26 +0000548 MatchableInfo(std::unique_ptr<const CodeGenInstAlias> Alias)
Tom Stellard75775932015-05-26 15:55:50 +0000549 : AsmVariantID(0), AsmString(Alias->AsmString), TheDef(Alias->TheDef),
550 DefRec(Alias.release()),
551 UseInstAsmMatchConverter(
552 TheDef->getValueAsBit("UseInstAsmMatchConverter")) {
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +0000553 }
Bob Wilson828295b2011-01-26 21:26:19 +0000554
David Blaikie8bf187c2015-08-01 01:08:30 +0000555 // Could remove this and the dtor if PointerUnion supported unique_ptr
556 // elements with a dynamic failure/assertion (like the one below) in the case
557 // where it was copied while being in an owning state.
558 MatchableInfo(const MatchableInfo &RHS)
559 : AsmVariantID(RHS.AsmVariantID), AsmString(RHS.AsmString),
560 TheDef(RHS.TheDef), DefRec(RHS.DefRec), ResOperands(RHS.ResOperands),
561 Mnemonic(RHS.Mnemonic), AsmOperands(RHS.AsmOperands),
562 RequiredFeatures(RHS.RequiredFeatures),
563 ConversionFnKind(RHS.ConversionFnKind),
564 HasDeprecation(RHS.HasDeprecation),
565 UseInstAsmMatchConverter(RHS.UseInstAsmMatchConverter) {
566 assert(!DefRec.is<const CodeGenInstAlias *>());
567 }
568
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +0000569 ~MatchableInfo() {
David Blaikied39a5d42014-12-22 21:26:26 +0000570 delete DefRec.dyn_cast<const CodeGenInstAlias*>();
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +0000571 }
Craig Topper9fd6eeb2014-11-28 05:01:21 +0000572
Jim Grosbachc1922c72012-04-19 23:59:23 +0000573 // Two-operand aliases clone from the main matchable, but mark the second
574 // operand as a tied operand of the first for purposes of the assembler.
575 void formTwoOperandAlias(StringRef Constraint);
576
Jim Grosbach8caecde2012-04-19 17:52:32 +0000577 void initialize(const AsmMatcherInfo &Info,
Craig Topper431bdfc2014-08-21 05:55:13 +0000578 SmallPtrSetImpl<Record*> &SingletonRegisters,
Craig Topper5ef13492015-12-31 08:18:23 +0000579 AsmVariantInfo const &Variant,
580 bool HasMnemonicFirst);
Bob Wilson828295b2011-01-26 21:26:19 +0000581
Jim Grosbach8caecde2012-04-19 17:52:32 +0000582 /// validate - Return true if this matchable is a valid thing to match against
Chris Lattner22bc5c42010-11-01 05:06:45 +0000583 /// and perform a bunch of validity checking.
Sander de Smalencb6c95b2018-02-04 16:24:17 +0000584 bool validate(StringRef CommentDelimiter, bool IsAlias) const;
Bob Wilson828295b2011-01-26 21:26:19 +0000585
Jim Grosbach8caecde2012-04-19 17:52:32 +0000586 /// findAsmOperand - Find the AsmOperand with the specified name and
Bob Wilsona49c7df2011-01-26 19:44:55 +0000587 /// suboperand index.
Jim Grosbach8caecde2012-04-19 17:52:32 +0000588 int findAsmOperand(StringRef N, int SubOpIdx) const {
David Majnemerb0353c62016-08-12 00:18:03 +0000589 auto I = find_if(AsmOperands, [&](const AsmOperand &Op) {
590 return Op.SrcOpName == N && Op.SubOpIdx == SubOpIdx;
591 });
Craig Topper9bb66bd2016-01-03 07:33:36 +0000592 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
Bob Wilsona49c7df2011-01-26 19:44:55 +0000593 }
Bob Wilson828295b2011-01-26 21:26:19 +0000594
Jim Grosbach8caecde2012-04-19 17:52:32 +0000595 /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
Bob Wilsona49c7df2011-01-26 19:44:55 +0000596 /// This does not check the suboperand index.
Sander de Smalencb6c95b2018-02-04 16:24:17 +0000597 int findAsmOperandNamed(StringRef N, int LastIdx = -1) const {
598 auto I = std::find_if(AsmOperands.begin() + LastIdx + 1, AsmOperands.end(),
David Majnemerb0353c62016-08-12 00:18:03 +0000599 [&](const AsmOperand &Op) { return Op.SrcOpName == N; });
Craig Topper9bb66bd2016-01-03 07:33:36 +0000600 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
Chris Lattnerba3b5b62010-11-04 01:55:23 +0000601 }
Bob Wilson828295b2011-01-26 21:26:19 +0000602
Sander de Smalencb6c95b2018-02-04 16:24:17 +0000603 int findAsmOperandOriginallyNamed(StringRef N) const {
604 auto I =
605 find_if(AsmOperands,
606 [&](const AsmOperand &Op) { return Op.OrigSrcOpName == N; });
607 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
608 }
609
Jim Grosbach8caecde2012-04-19 17:52:32 +0000610 void buildInstructionResultOperands();
Sander de Smalencb6c95b2018-02-04 16:24:17 +0000611 void buildAliasResultOperands(bool AliasConstraintsAreChecked);
Chris Lattner1d13bda2010-11-04 00:43:46 +0000612
Chris Lattner22bc5c42010-11-01 05:06:45 +0000613 /// operator< - Compare two matchables.
614 bool operator<(const MatchableInfo &RHS) const {
Chris Lattnere206fcf2010-09-06 21:01:37 +0000615 // The primary comparator is the instruction mnemonic.
Ahmed Bougachabcf03bb2016-06-23 17:09:49 +0000616 if (int Cmp = Mnemonic.compare(RHS.Mnemonic))
617 return Cmp == -1;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000618
Chris Lattner3116fef2010-11-02 01:03:43 +0000619 if (AsmOperands.size() != RHS.AsmOperands.size())
620 return AsmOperands.size() < RHS.AsmOperands.size();
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000621
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000622 // Compare lexicographically by operand. The matcher validates that other
Jim Grosbach8caecde2012-04-19 17:52:32 +0000623 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
Chris Lattner3116fef2010-11-02 01:03:43 +0000624 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
625 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000626 return true;
Chris Lattner3116fef2010-11-02 01:03:43 +0000627 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbardb2ddb52009-08-09 08:23:23 +0000628 return false;
629 }
630
Andrew Trick2b70dfa2012-08-29 03:52:57 +0000631 // Give matches that require more features higher precedence. This is useful
632 // because we cannot define AssemblerPredicates with the negation of
633 // processor features. For example, ARM v6 "nop" may be either a HINT or
634 // MOV. With v6, we want to match HINT. The assembler has no way to
635 // predicate MOV under "NoV6", but HINT will always match first because it
636 // requires V6 while MOV does not.
637 if (RequiredFeatures.size() != RHS.RequiredFeatures.size())
638 return RequiredFeatures.size() > RHS.RequiredFeatures.size();
639
Daniel Dunbar606e8ad2009-08-09 04:00:06 +0000640 return false;
641 }
642
Jim Grosbach8caecde2012-04-19 17:52:32 +0000643 /// couldMatchAmbiguouslyWith - Check whether this matchable could
Dmitri Gribenko4e0ae442012-09-15 20:22:05 +0000644 /// ambiguously match the same set of operands as \p RHS (without being a
Daniel Dunbar2b544812009-08-09 06:05:33 +0000645 /// strictly superior match).
Craig Topper99a21702014-11-28 03:53:00 +0000646 bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) const {
Chris Lattnere66b7eb2010-11-01 23:57:23 +0000647 // The primary comparator is the instruction mnemonic.
Chris Lattnerd19ec052010-11-02 17:30:52 +0000648 if (Mnemonic != RHS.Mnemonic)
Chris Lattnere66b7eb2010-11-01 23:57:23 +0000649 return false;
Bob Wilson828295b2011-01-26 21:26:19 +0000650
Craig Topperbaa93cd2018-01-06 19:20:32 +0000651 // Different variants can't conflict.
652 if (AsmVariantID != RHS.AsmVariantID)
653 return false;
654
Daniel Dunbar2b544812009-08-09 06:05:33 +0000655 // The number of operands is unambiguous.
Chris Lattner3116fef2010-11-02 01:03:43 +0000656 if (AsmOperands.size() != RHS.AsmOperands.size())
Daniel Dunbar2b544812009-08-09 06:05:33 +0000657 return false;
658
Daniel Dunbar1402f0b2010-01-23 00:26:16 +0000659 // Otherwise, make sure the ordering of the two instructions is unambiguous
660 // by checking that either (a) a token or operand kind discriminates them,
661 // or (b) the ordering among equivalent kinds is consistent.
662
Daniel Dunbar2b544812009-08-09 06:05:33 +0000663 // Tokens and operand kinds are unambiguous (assuming a correct target
664 // specific parser).
Chris Lattner3116fef2010-11-02 01:03:43 +0000665 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
666 if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
667 AsmOperands[i].Class->Kind == ClassInfo::Token)
668 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
669 *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbar2b544812009-08-09 06:05:33 +0000670 return false;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000671
Daniel Dunbar2b544812009-08-09 06:05:33 +0000672 // Otherwise, this operand could commute if all operands are equivalent, or
673 // there is a pair of operands that compare less than and a pair that
674 // compare greater than.
675 bool HasLT = false, HasGT = false;
Chris Lattner3116fef2010-11-02 01:03:43 +0000676 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
677 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
Daniel Dunbar2b544812009-08-09 06:05:33 +0000678 HasLT = true;
Chris Lattner3116fef2010-11-02 01:03:43 +0000679 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
Daniel Dunbar2b544812009-08-09 06:05:33 +0000680 HasGT = true;
681 }
682
Craig Topper4d34e542016-01-03 07:33:39 +0000683 return HasLT == HasGT;
Daniel Dunbar2b544812009-08-09 06:05:33 +0000684 }
685
Craig Topper99a21702014-11-28 03:53:00 +0000686 void dump() const;
Bob Wilson828295b2011-01-26 21:26:19 +0000687
Chris Lattnerd19ec052010-11-02 17:30:52 +0000688private:
Colin LeMahieu1539acf2015-11-09 00:31:07 +0000689 void tokenizeAsmString(AsmMatcherInfo const &Info,
690 AsmVariantInfo const &Variant);
Craig Topperee721e92015-12-31 05:01:45 +0000691 void addAsmOperand(StringRef Token, bool IsIsolatedToken = false);
Daniel Dunbar20927f22009-08-07 08:26:05 +0000692};
693
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000694struct OperandMatchEntry {
695 unsigned OperandMask;
Craig Topper99a21702014-11-28 03:53:00 +0000696 const MatchableInfo* MI;
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000697 ClassInfo *CI;
698
Craig Topper99a21702014-11-28 03:53:00 +0000699 static OperandMatchEntry create(const MatchableInfo *mi, ClassInfo *ci,
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000700 unsigned opMask) {
701 OperandMatchEntry X;
702 X.OperandMask = opMask;
703 X.CI = ci;
704 X.MI = mi;
705 return X;
706 }
707};
708
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000709class AsmMatcherInfo {
710public:
Chris Lattner67db8832010-12-13 00:23:57 +0000711 /// Tracked Records
Chris Lattner9c6b60e2010-12-15 04:48:22 +0000712 RecordKeeper &Records;
Chris Lattner67db8832010-12-13 00:23:57 +0000713
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000714 /// The tablegen AsmParser record.
715 Record *AsmParser;
716
Chris Lattner02bcbc92010-11-01 01:37:30 +0000717 /// Target - The target information.
718 CodeGenTarget &Target;
719
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000720 /// The classes which are needed for matching.
David Blaikie841db2c2014-11-28 20:35:57 +0000721 std::forward_list<ClassInfo> Classes;
Jim Grosbacha7c78222010-10-29 22:13:48 +0000722
Chris Lattner22bc5c42010-11-01 05:06:45 +0000723 /// The information on the matchables to match.
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +0000724 std::vector<std::unique_ptr<MatchableInfo>> Matchables;
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000725
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000726 /// Info for custom matching operands by user defined methods.
727 std::vector<OperandMatchEntry> OperandMatchInfo;
728
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000729 /// Map of Register records to their class information.
Sean Silvadecfdf52012-09-19 01:47:01 +0000730 typedef std::map<Record*, ClassInfo*, LessRecordByID> RegisterClassesTy;
731 RegisterClassesTy RegisterClasses;
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000732
Daniel Dunbar54074b52010-07-19 05:44:09 +0000733 /// Map of Predicate records to their subtarget information.
David Blaikie5f951402014-11-28 22:15:06 +0000734 std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures;
Bob Wilson828295b2011-01-26 21:26:19 +0000735
Jim Grosbach4dbfdfb2012-06-22 23:56:44 +0000736 /// Map of AsmOperandClass records to their class information.
737 std::map<Record*, ClassInfo*> AsmOperandClasses;
738
Oliver Stannard0e4cc592017-10-10 11:00:40 +0000739 /// Map of RegisterClass records to their class information.
740 std::map<Record*, ClassInfo*> RegisterClassClasses;
741
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000742private:
743 /// Map of token to class information which has already been constructed.
744 std::map<std::string, ClassInfo*> TokenClasses;
745
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000746private:
747 /// getTokenClass - Lookup or create the class for the given token.
Chris Lattnerb8d6e982010-02-09 00:34:28 +0000748 ClassInfo *getTokenClass(StringRef Token);
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000749
750 /// getOperandClass - Lookup or create the class for the given operand.
Bob Wilsona49c7df2011-01-26 19:44:55 +0000751 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
Jim Grosbach48c1f842011-10-28 22:32:53 +0000752 int SubOpIdx);
753 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000754
Jim Grosbach8caecde2012-04-19 17:52:32 +0000755 /// buildRegisterClasses - Build the ClassInfo* instances for register
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000756 /// classes.
Craig Topper431bdfc2014-08-21 05:55:13 +0000757 void buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters);
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000758
Jim Grosbach8caecde2012-04-19 17:52:32 +0000759 /// buildOperandClasses - Build the ClassInfo* instances for user defined
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000760 /// operand classes.
Jim Grosbach8caecde2012-04-19 17:52:32 +0000761 void buildOperandClasses();
Daniel Dunbarea6408f2009-08-11 02:59:53 +0000762
Jim Grosbach8caecde2012-04-19 17:52:32 +0000763 void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
Bob Wilsona49c7df2011-01-26 19:44:55 +0000764 unsigned AsmOpIdx);
Jim Grosbach8caecde2012-04-19 17:52:32 +0000765 void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
Chris Lattnerc07bd402010-11-04 02:11:18 +0000766 MatchableInfo::AsmOperand &Op);
Bob Wilson828295b2011-01-26 21:26:19 +0000767
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000768public:
Bob Wilson828295b2011-01-26 21:26:19 +0000769 AsmMatcherInfo(Record *AsmParser,
770 CodeGenTarget &Target,
Chris Lattner9c6b60e2010-12-15 04:48:22 +0000771 RecordKeeper &Records);
Daniel Dunbar59fc42d2009-08-11 20:59:47 +0000772
Daniel Sanders57a599e2016-11-15 09:51:02 +0000773 /// Construct the various tables used during matching.
Jim Grosbach8caecde2012-04-19 17:52:32 +0000774 void buildInfo();
Bob Wilson828295b2011-01-26 21:26:19 +0000775
Jim Grosbach8caecde2012-04-19 17:52:32 +0000776 /// buildOperandMatchInfo - Build the necessary information to handle user
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000777 /// defined operand parsing methods.
Jim Grosbach8caecde2012-04-19 17:52:32 +0000778 void buildOperandMatchInfo();
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +0000779
Chris Lattner6fa152c2010-10-30 20:15:02 +0000780 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
781 /// given operand.
David Blaikie5f951402014-11-28 22:15:06 +0000782 const SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
Chris Lattner6fa152c2010-10-30 20:15:02 +0000783 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
Craig Topper99a21702014-11-28 03:53:00 +0000784 const auto &I = SubtargetFeatures.find(Def);
David Blaikie5f951402014-11-28 22:15:06 +0000785 return I == SubtargetFeatures.end() ? nullptr : &I->second;
Chris Lattner6fa152c2010-10-30 20:15:02 +0000786 }
Chris Lattner67db8832010-12-13 00:23:57 +0000787
Chris Lattner9c6b60e2010-12-15 04:48:22 +0000788 RecordKeeper &getRecords() const {
789 return Records;
Chris Lattner67db8832010-12-13 00:23:57 +0000790 }
Sam Koltonf117ec12016-05-06 11:31:17 +0000791
792 bool hasOptionalOperands() const {
David Majnemerb0353c62016-08-12 00:18:03 +0000793 return find_if(Classes, [](const ClassInfo &Class) {
794 return Class.IsOptional;
795 }) != Classes.end();
Sam Koltonf117ec12016-05-06 11:31:17 +0000796 }
Daniel Dunbara3741fa2009-08-08 07:50:56 +0000797};
798
Eugene Zelenko380d47d2016-02-02 18:20:45 +0000799} // end anonymous namespace
Daniel Dunbar20927f22009-08-07 08:26:05 +0000800
Aaron Ballman1d03d382017-10-15 14:32:27 +0000801#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Galina Kistanova733dbc62017-05-17 02:20:05 +0000802LLVM_DUMP_METHOD void MatchableInfo::dump() const {
Chris Lattner5abd1eb2010-11-06 06:43:11 +0000803 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +0000804
Craig Topperbaa93cd2018-01-06 19:20:32 +0000805 errs() << " variant: " << AsmVariantID << "\n";
806
Chris Lattner3116fef2010-11-02 01:03:43 +0000807 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
Craig Topper99a21702014-11-28 03:53:00 +0000808 const AsmOperand &Op = AsmOperands[i];
Daniel Dunbar6745d422009-08-09 05:18:30 +0000809 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
Chris Lattner0bb780c2010-11-04 00:57:06 +0000810 errs() << '\"' << Op.Token << "\"\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +0000811 }
812}
Galina Kistanova733dbc62017-05-17 02:20:05 +0000813#endif
Daniel Dunbar20927f22009-08-07 08:26:05 +0000814
Jim Grosbachc1922c72012-04-19 23:59:23 +0000815static std::pair<StringRef, StringRef>
Jakob Stoklund Olesen376a8a72012-08-22 23:33:58 +0000816parseTwoOperandConstraint(StringRef S, ArrayRef<SMLoc> Loc) {
Jim Grosbachc1922c72012-04-19 23:59:23 +0000817 // Split via the '='.
818 std::pair<StringRef, StringRef> Ops = S.split('=');
819 if (Ops.second == "")
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000820 PrintFatalError(Loc, "missing '=' in two-operand alias constraint");
Jim Grosbachc1922c72012-04-19 23:59:23 +0000821 // Trim whitespace and the leading '$' on the operand names.
822 size_t start = Ops.first.find_first_of('$');
823 if (start == std::string::npos)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000824 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
Jim Grosbachc1922c72012-04-19 23:59:23 +0000825 Ops.first = Ops.first.slice(start + 1, std::string::npos);
826 size_t end = Ops.first.find_last_of(" \t");
827 Ops.first = Ops.first.slice(0, end);
828 // Now the second operand.
829 start = Ops.second.find_first_of('$');
830 if (start == std::string::npos)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000831 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
Jim Grosbachc1922c72012-04-19 23:59:23 +0000832 Ops.second = Ops.second.slice(start + 1, std::string::npos);
833 end = Ops.second.find_last_of(" \t");
834 Ops.first = Ops.first.slice(0, end);
835 return Ops;
836}
837
838void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
839 // Figure out which operands are aliased and mark them as tied.
840 std::pair<StringRef, StringRef> Ops =
841 parseTwoOperandConstraint(Constraint, TheDef->getLoc());
842
843 // Find the AsmOperands that refer to the operands we're aliasing.
844 int SrcAsmOperand = findAsmOperandNamed(Ops.first);
845 int DstAsmOperand = findAsmOperandNamed(Ops.second);
846 if (SrcAsmOperand == -1)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000847 PrintFatalError(TheDef->getLoc(),
Benjamin Kramerabe43b52014-03-29 17:17:15 +0000848 "unknown source two-operand alias operand '" + Ops.first +
849 "'.");
Jim Grosbachc1922c72012-04-19 23:59:23 +0000850 if (DstAsmOperand == -1)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000851 PrintFatalError(TheDef->getLoc(),
Benjamin Kramerabe43b52014-03-29 17:17:15 +0000852 "unknown destination two-operand alias operand '" +
853 Ops.second + "'.");
Jim Grosbachc1922c72012-04-19 23:59:23 +0000854
855 // Find the ResOperand that refers to the operand we're aliasing away
856 // and update it to refer to the combined operand instead.
Craig Topper300c9662015-12-29 07:03:23 +0000857 for (ResOperand &Op : ResOperands) {
Jim Grosbachc1922c72012-04-19 23:59:23 +0000858 if (Op.Kind == ResOperand::RenderAsmOperand &&
859 Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
860 Op.AsmOperandNum = DstAsmOperand;
861 break;
862 }
863 }
864 // Remove the AsmOperand for the alias operand.
865 AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
866 // Adjust the ResOperand references to any AsmOperands that followed
867 // the one we just deleted.
Craig Topper300c9662015-12-29 07:03:23 +0000868 for (ResOperand &Op : ResOperands) {
Jim Grosbachc1922c72012-04-19 23:59:23 +0000869 switch(Op.Kind) {
870 default:
871 // Nothing to do for operands that don't reference AsmOperands.
872 break;
873 case ResOperand::RenderAsmOperand:
874 if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
875 --Op.AsmOperandNum;
876 break;
Jim Grosbachc1922c72012-04-19 23:59:23 +0000877 }
878 }
879}
880
Craig Topper6fa20dc2015-09-13 18:01:25 +0000881/// extractSingletonRegisterForAsmOperand - Extract singleton register,
882/// if present, from specified token.
883static void
884extractSingletonRegisterForAsmOperand(MatchableInfo::AsmOperand &Op,
885 const AsmMatcherInfo &Info,
886 StringRef RegisterPrefix) {
887 StringRef Tok = Op.Token;
888
889 // If this token is not an isolated token, i.e., it isn't separated from
890 // other tokens (e.g. with whitespace), don't interpret it as a register name.
891 if (!Op.IsIsolatedToken)
892 return;
893
894 if (RegisterPrefix.empty()) {
895 std::string LoweredTok = Tok.lower();
896 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
897 Op.SingletonReg = Reg->TheDef;
898 return;
899 }
900
901 if (!Tok.startswith(RegisterPrefix))
902 return;
903
904 StringRef RegName = Tok.substr(RegisterPrefix.size());
905 if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
906 Op.SingletonReg = Reg->TheDef;
907
908 // If there is no register prefix (i.e. "%" in "%eax"), then this may
909 // be some random non-register token, just ignore it.
Craig Topper6fa20dc2015-09-13 18:01:25 +0000910}
911
Jim Grosbach8caecde2012-04-19 17:52:32 +0000912void MatchableInfo::initialize(const AsmMatcherInfo &Info,
Craig Topper431bdfc2014-08-21 05:55:13 +0000913 SmallPtrSetImpl<Record*> &SingletonRegisters,
Craig Topper5ef13492015-12-31 08:18:23 +0000914 AsmVariantInfo const &Variant,
915 bool HasMnemonicFirst) {
Craig Toppere6b50232015-12-30 06:00:18 +0000916 AsmVariantID = Variant.AsmVariantNo;
Jim Grosbachf35307c2012-01-24 21:06:59 +0000917 AsmString =
Craig Toppere6b50232015-12-30 06:00:18 +0000918 CodeGenInstruction::FlattenAsmStringVariants(AsmString,
919 Variant.AsmVariantNo);
Bob Wilson828295b2011-01-26 21:26:19 +0000920
Colin LeMahieu1539acf2015-11-09 00:31:07 +0000921 tokenizeAsmString(Info, Variant);
Bob Wilson828295b2011-01-26 21:26:19 +0000922
Craig Topper5ef13492015-12-31 08:18:23 +0000923 // The first token of the instruction is the mnemonic, which must be a
924 // simple string, not a $foo variable or a singleton register.
925 if (AsmOperands.empty())
926 PrintFatalError(TheDef->getLoc(),
927 "Instruction '" + TheDef->getName() + "' has no tokens");
928
929 assert(!AsmOperands[0].Token.empty());
930 if (HasMnemonicFirst) {
931 Mnemonic = AsmOperands[0].Token;
932 if (Mnemonic[0] == '$')
933 PrintFatalError(TheDef->getLoc(),
934 "Invalid instruction mnemonic '" + Mnemonic + "'!");
935
936 // Remove the first operand, it is tracked in the mnemonic field.
937 AsmOperands.erase(AsmOperands.begin());
938 } else if (AsmOperands[0].Token[0] != '$')
939 Mnemonic = AsmOperands[0].Token;
940
Chris Lattnerc2d67bb2010-11-01 04:53:48 +0000941 // Compute the require features.
Craig Topper6fa20dc2015-09-13 18:01:25 +0000942 for (Record *Predicate : TheDef->getValueAsListOfDefs("Predicates"))
David Blaikie5f951402014-11-28 22:15:06 +0000943 if (const SubtargetFeatureInfo *Feature =
Craig Topper6fa20dc2015-09-13 18:01:25 +0000944 Info.getSubtargetFeature(Predicate))
Chris Lattnerc2d67bb2010-11-01 04:53:48 +0000945 RequiredFeatures.push_back(Feature);
Bob Wilson828295b2011-01-26 21:26:19 +0000946
Chris Lattnerc2d67bb2010-11-01 04:53:48 +0000947 // Collect singleton registers, if used.
Craig Topper6fa20dc2015-09-13 18:01:25 +0000948 for (MatchableInfo::AsmOperand &Op : AsmOperands) {
Craig Toppere6b50232015-12-30 06:00:18 +0000949 extractSingletonRegisterForAsmOperand(Op, Info, Variant.RegisterPrefix);
Craig Topper6fa20dc2015-09-13 18:01:25 +0000950 if (Record *Reg = Op.SingletonReg)
Chris Lattnerc2d67bb2010-11-01 04:53:48 +0000951 SingletonRegisters.insert(Reg);
952 }
Joey Gouly715d98d2013-09-12 10:28:05 +0000953
954 const RecordVal *DepMask = TheDef->getValue("DeprecatedFeatureMask");
955 if (!DepMask)
956 DepMask = TheDef->getValue("ComplexDeprecationPredicate");
957
958 HasDeprecation =
959 DepMask ? !DepMask->getValue()->getAsUnquotedString().empty() : false;
Chris Lattnerc2d67bb2010-11-01 04:53:48 +0000960}
961
Ahmed Bougacha85f66de2015-05-29 00:55:55 +0000962/// Append an AsmOperand for the given substring of AsmString.
Craig Topperee721e92015-12-31 05:01:45 +0000963void MatchableInfo::addAsmOperand(StringRef Token, bool IsIsolatedToken) {
964 AsmOperands.push_back(AsmOperand(IsIsolatedToken, Token));
Ahmed Bougacha85f66de2015-05-29 00:55:55 +0000965}
966
Jim Grosbach8caecde2012-04-19 17:52:32 +0000967/// tokenizeAsmString - Tokenize a simplified assembly string.
Colin LeMahieu1539acf2015-11-09 00:31:07 +0000968void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info,
969 AsmVariantInfo const &Variant) {
Chris Lattnerd19ec052010-11-02 17:30:52 +0000970 StringRef String = AsmString;
Craig Toppera1a9b682015-12-30 06:00:15 +0000971 size_t Prev = 0;
Colin LeMahieu1539acf2015-11-09 00:31:07 +0000972 bool InTok = false;
Craig Topperee721e92015-12-31 05:01:45 +0000973 bool IsIsolatedToken = true;
Craig Toppera1a9b682015-12-30 06:00:15 +0000974 for (size_t i = 0, e = String.size(); i != e; ++i) {
Craig Topperee721e92015-12-31 05:01:45 +0000975 char Char = String[i];
976 if (Variant.BreakCharacters.find(Char) != std::string::npos) {
977 if (InTok) {
978 addAsmOperand(String.slice(Prev, i), false);
Colin LeMahieu1539acf2015-11-09 00:31:07 +0000979 Prev = i;
Craig Topperee721e92015-12-31 05:01:45 +0000980 IsIsolatedToken = false;
Colin LeMahieu1539acf2015-11-09 00:31:07 +0000981 }
982 InTok = true;
983 continue;
984 }
Craig Topperee721e92015-12-31 05:01:45 +0000985 if (Variant.TokenizingCharacters.find(Char) != std::string::npos) {
986 if (InTok) {
987 addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
Chris Lattnerd19ec052010-11-02 17:30:52 +0000988 InTok = false;
Craig Topperee721e92015-12-31 05:01:45 +0000989 IsIsolatedToken = false;
Chris Lattnerd19ec052010-11-02 17:30:52 +0000990 }
Craig Topperee721e92015-12-31 05:01:45 +0000991 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
Chris Lattnerd19ec052010-11-02 17:30:52 +0000992 Prev = i + 1;
Craig Topperee721e92015-12-31 05:01:45 +0000993 IsIsolatedToken = true;
Colin LeMahieu1539acf2015-11-09 00:31:07 +0000994 continue;
995 }
Craig Topperee721e92015-12-31 05:01:45 +0000996 if (Variant.SeparatorCharacters.find(Char) != std::string::npos) {
997 if (InTok) {
998 addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
Colin LeMahieu1539acf2015-11-09 00:31:07 +0000999 InTok = false;
1000 }
1001 Prev = i + 1;
Craig Topperee721e92015-12-31 05:01:45 +00001002 IsIsolatedToken = true;
Colin LeMahieu1539acf2015-11-09 00:31:07 +00001003 continue;
1004 }
Craig Topperee721e92015-12-31 05:01:45 +00001005
1006 switch (Char) {
Chris Lattnerd19ec052010-11-02 17:30:52 +00001007 case '\\':
1008 if (InTok) {
Craig Topperee721e92015-12-31 05:01:45 +00001009 addAsmOperand(String.slice(Prev, i), false);
Chris Lattnerd19ec052010-11-02 17:30:52 +00001010 InTok = false;
Craig Topperee721e92015-12-31 05:01:45 +00001011 IsIsolatedToken = false;
Chris Lattnerd19ec052010-11-02 17:30:52 +00001012 }
1013 ++i;
1014 assert(i != String.size() && "Invalid quoted character");
Craig Topperee721e92015-12-31 05:01:45 +00001015 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
Chris Lattnerd19ec052010-11-02 17:30:52 +00001016 Prev = i + 1;
Craig Topperee721e92015-12-31 05:01:45 +00001017 IsIsolatedToken = false;
Chris Lattnerd19ec052010-11-02 17:30:52 +00001018 break;
1019
1020 case '$': {
Craig Topperee721e92015-12-31 05:01:45 +00001021 if (InTok) {
1022 addAsmOperand(String.slice(Prev, i), false);
Chris Lattnerd19ec052010-11-02 17:30:52 +00001023 InTok = false;
Craig Topperee721e92015-12-31 05:01:45 +00001024 IsIsolatedToken = false;
Chris Lattnerd19ec052010-11-02 17:30:52 +00001025 }
Bob Wilson828295b2011-01-26 21:26:19 +00001026
Colin LeMahieueb9e5f02015-08-10 19:58:06 +00001027 // If this isn't "${", start new identifier looking like "$xxx"
Chris Lattner7ad31472010-11-06 22:06:03 +00001028 if (i + 1 == String.size() || String[i + 1] != '{') {
1029 Prev = i;
1030 break;
1031 }
Chris Lattnerd19ec052010-11-02 17:30:52 +00001032
Craig Toppera1a9b682015-12-30 06:00:15 +00001033 size_t EndPos = String.find('}', i);
1034 assert(EndPos != StringRef::npos &&
1035 "Missing brace in operand reference!");
Craig Topperee721e92015-12-31 05:01:45 +00001036 addAsmOperand(String.slice(i, EndPos+1), IsIsolatedToken);
Chris Lattnerd19ec052010-11-02 17:30:52 +00001037 Prev = EndPos + 1;
1038 i = EndPos;
Craig Topperee721e92015-12-31 05:01:45 +00001039 IsIsolatedToken = false;
Chris Lattnerd19ec052010-11-02 17:30:52 +00001040 break;
1041 }
Craig Topperee721e92015-12-31 05:01:45 +00001042
Chris Lattnerd19ec052010-11-02 17:30:52 +00001043 default:
1044 InTok = true;
Craig Topperee721e92015-12-31 05:01:45 +00001045 break;
Chris Lattnerd19ec052010-11-02 17:30:52 +00001046 }
1047 }
1048 if (InTok && Prev != String.size())
Craig Topperee721e92015-12-31 05:01:45 +00001049 addAsmOperand(String.substr(Prev), IsIsolatedToken);
Chris Lattnerd19ec052010-11-02 17:30:52 +00001050}
1051
Sander de Smalencb6c95b2018-02-04 16:24:17 +00001052bool MatchableInfo::validate(StringRef CommentDelimiter, bool IsAlias) const {
Chris Lattner22bc5c42010-11-01 05:06:45 +00001053 // Reject matchables with no .s string.
Chris Lattner5bc93872010-11-01 04:34:44 +00001054 if (AsmString.empty())
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001055 PrintFatalError(TheDef->getLoc(), "instruction with empty asm string");
Bob Wilson828295b2011-01-26 21:26:19 +00001056
Chris Lattner22bc5c42010-11-01 05:06:45 +00001057 // Reject any matchables with a newline in them, they should be marked
Chris Lattner5bc93872010-11-01 04:34:44 +00001058 // isCodeGenOnly if they are pseudo instructions.
1059 if (AsmString.find('\n') != std::string::npos)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001060 PrintFatalError(TheDef->getLoc(),
Chris Lattner5bc93872010-11-01 04:34:44 +00001061 "multiline instruction is not valid for the asmparser, "
1062 "mark it isCodeGenOnly");
Bob Wilson828295b2011-01-26 21:26:19 +00001063
Chris Lattner4164f6b2010-11-01 04:44:29 +00001064 // Remove comments from the asm string. We know that the asmstring only
1065 // has one line.
1066 if (!CommentDelimiter.empty() &&
1067 StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001068 PrintFatalError(TheDef->getLoc(),
Chris Lattner4164f6b2010-11-01 04:44:29 +00001069 "asmstring for instruction has comment character in it, "
1070 "mark it isCodeGenOnly");
Bob Wilson828295b2011-01-26 21:26:19 +00001071
Chris Lattner22bc5c42010-11-01 05:06:45 +00001072 // Reject matchables with operand modifiers, these aren't something we can
Bob Wilson906bc362011-01-20 18:38:07 +00001073 // handle, the target should be refactored to use operands instead of
1074 // modifiers.
Chris Lattner5bc93872010-11-01 04:34:44 +00001075 //
1076 // Also, check for instructions which reference the operand multiple times;
1077 // this implies a constraint we would not honor.
1078 std::set<std::string> OperandNames;
Craig Topper65438a72015-12-30 06:00:20 +00001079 for (const AsmOperand &Op : AsmOperands) {
1080 StringRef Tok = Op.Token;
Chris Lattnerd19ec052010-11-02 17:30:52 +00001081 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001082 PrintFatalError(TheDef->getLoc(),
Benjamin Kramerabe43b52014-03-29 17:17:15 +00001083 "matchable with operand modifier '" + Tok +
1084 "' not supported by asm matcher. Mark isCodeGenOnly!");
Chris Lattner22bc5c42010-11-01 05:06:45 +00001085 // Verify that any operand is only mentioned once.
Chris Lattnerd51257a2010-11-02 23:18:43 +00001086 // We reject aliases and ignore instructions for now.
Sander de Smalencb6c95b2018-02-04 16:24:17 +00001087 if (!IsAlias && Tok[0] == '$' && !OperandNames.insert(Tok).second) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001088 LLVM_DEBUG({
Chris Lattner5abd1eb2010-11-06 06:43:11 +00001089 errs() << "warning: '" << TheDef->getName() << "': "
Chris Lattner22bc5c42010-11-01 05:06:45 +00001090 << "ignoring instruction with tied operand '"
Benjamin Kramerabe43b52014-03-29 17:17:15 +00001091 << Tok << "'\n";
Chris Lattner5bc93872010-11-01 04:34:44 +00001092 });
1093 return false;
1094 }
1095 }
Bob Wilson828295b2011-01-26 21:26:19 +00001096
Chris Lattner5bc93872010-11-01 04:34:44 +00001097 return true;
1098}
1099
Chris Lattnerb8d6e982010-02-09 00:34:28 +00001100static std::string getEnumNameForToken(StringRef Str) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001101 std::string Res;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001102
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001103 for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
1104 switch (*it) {
1105 case '*': Res += "_STAR_"; break;
1106 case '%': Res += "_PCT_"; break;
1107 case ':': Res += "_COLON_"; break;
Bill Wendlingbd9c77b2010-11-18 23:36:54 +00001108 case '!': Res += "_EXCLAIM_"; break;
Bill Wendling0ef755d2011-01-22 09:44:32 +00001109 case '.': Res += "_DOT_"; break;
Tim Northover12da5052013-01-10 16:47:31 +00001110 case '<': Res += "_LT_"; break;
1111 case '>': Res += "_GT_"; break;
Hal Finkel5a40bef2015-01-15 01:33:00 +00001112 case '-': Res += "_MINUS_"; break;
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001113 default:
Tim Northover12da5052013-01-10 16:47:31 +00001114 if ((*it >= 'A' && *it <= 'Z') ||
1115 (*it >= 'a' && *it <= 'z') ||
1116 (*it >= '0' && *it <= '9'))
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001117 Res += *it;
Chris Lattner39ee0362010-10-31 19:10:56 +00001118 else
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001119 Res += "_" + utostr((unsigned) *it) + "_";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001120 }
1121 }
1122
1123 return Res;
1124}
1125
Chris Lattnerb8d6e982010-02-09 00:34:28 +00001126ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001127 ClassInfo *&Entry = TokenClasses[Token];
Jim Grosbacha7c78222010-10-29 22:13:48 +00001128
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001129 if (!Entry) {
David Blaikie841db2c2014-11-28 20:35:57 +00001130 Classes.emplace_front();
1131 Entry = &Classes.front();
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001132 Entry->Kind = ClassInfo::Token;
Daniel Dunbar6745d422009-08-09 05:18:30 +00001133 Entry->ClassName = "Token";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001134 Entry->Name = "MCK_" + getEnumNameForToken(Token);
1135 Entry->ValueName = Token;
1136 Entry->PredicateMethod = "<invalid>";
1137 Entry->RenderMethod = "<invalid>";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001138 Entry->ParserMethod = "";
Jim Grosbach4dbfdfb2012-06-22 23:56:44 +00001139 Entry->DiagnosticType = "";
Tom Stellard25257d82016-02-05 19:59:33 +00001140 Entry->IsOptional = false;
Sam Koltonf117ec12016-05-06 11:31:17 +00001141 Entry->DefaultMethod = "<invalid>";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001142 }
1143
1144 return Entry;
1145}
1146
1147ClassInfo *
Bob Wilsona49c7df2011-01-26 19:44:55 +00001148AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
1149 int SubOpIdx) {
1150 Record *Rec = OI.Rec;
1151 if (SubOpIdx != -1)
Sean Silva3f7b7f82012-10-10 20:24:47 +00001152 Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
Jim Grosbach48c1f842011-10-28 22:32:53 +00001153 return getOperandClass(Rec, SubOpIdx);
1154}
Bob Wilsona49c7df2011-01-26 19:44:55 +00001155
Jim Grosbach48c1f842011-10-28 22:32:53 +00001156ClassInfo *
1157AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
Owen Andersonbea6f612011-06-27 21:06:21 +00001158 if (Rec->isSubClassOf("RegisterOperand")) {
1159 // RegisterOperand may have an associated ParserMatchClass. If it does,
1160 // use it, else just fall back to the underlying register class.
1161 const RecordVal *R = Rec->getValue("ParserMatchClass");
Craig Topper095734c2014-04-15 07:20:03 +00001162 if (!R || !R->getValue())
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001163 PrintFatalError("Record `" + Rec->getName() +
1164 "' does not have a ParserMatchClass!\n");
Owen Andersonbea6f612011-06-27 21:06:21 +00001165
Sean Silva6cfc8062012-10-10 20:24:43 +00001166 if (DefInit *DI= dyn_cast<DefInit>(R->getValue())) {
Owen Andersonbea6f612011-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 Sonnenberger61131ab2012-10-25 20:33:17 +00001175 PrintFatalError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
Owen Andersonbea6f612011-06-27 21:06:21 +00001176 "' has no associated register class!\n");
1177 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
1178 return CI;
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001179 PrintFatalError(Rec->getLoc(), "register class has no class info!");
Owen Andersonbea6f612011-06-27 21:06:21 +00001180 }
1181
Bob Wilsona49c7df2011-01-26 19:44:55 +00001182 if (Rec->isSubClassOf("RegisterClass")) {
1183 if (ClassInfo *CI = RegisterClassClasses[Rec])
Chris Lattnerec6f0962010-11-02 18:10:06 +00001184 return CI;
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001185 PrintFatalError(Rec->getLoc(), "register class has no class info!");
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001186 }
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001187
Jim Grosbacha562dc72012-09-12 17:40:25 +00001188 if (!Rec->isSubClassOf("Operand"))
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001189 PrintFatalError(Rec->getLoc(), "Operand `" + Rec->getName() +
Jim Grosbacha562dc72012-09-12 17:40:25 +00001190 "' does not derive from class Operand!\n");
Bob Wilsona49c7df2011-01-26 19:44:55 +00001191 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
Chris Lattnerec6f0962010-11-02 18:10:06 +00001192 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1193 return CI;
Daniel Dunbar338825c2009-08-10 18:41:10 +00001194
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001195 PrintFatalError(Rec->getLoc(), "operand has no match class!");
Daniel Dunbara3741fa2009-08-08 07:50:56 +00001196}
1197
Tim Northover03f91972013-09-16 16:43:19 +00001198struct LessRegisterSet {
Tim Northover107cfa22013-09-16 17:33:40 +00001199 bool operator() (const RegisterSet &LHS, const RegisterSet & RHS) const {
Tim Northover03f91972013-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 Lattner1de88232010-11-01 01:47:07 +00001210void AsmMatcherInfo::
Craig Topper431bdfc2014-08-21 05:55:13 +00001211buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters) {
David Blaikiee7227132014-11-29 18:13:39 +00001212 const auto &Registers = Target.getRegBank().getRegisters();
David Blaikie89036eb2014-12-03 19:58:41 +00001213 auto &RegClassList = Target.getRegBank().getRegClasses();
Daniel Dunbar338825c2009-08-10 18:41:10 +00001214
Tim Northover03f91972013-09-16 16:43:19 +00001215 typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet;
1216
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001217 // The register sets used for matching.
Tim Northover03f91972013-09-16 16:43:19 +00001218 RegisterSetSet RegisterSets;
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001219
Jim Grosbacha7c78222010-10-29 22:13:48 +00001220 // Gather the defined sets.
David Blaikie7a16f342014-12-03 19:58:45 +00001221 for (const CodeGenRegisterClass &RC : RegClassList)
1222 RegisterSets.insert(
1223 RegisterSet(RC.getOrder().begin(), RC.getOrder().end()));
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001224
1225 // Add any required singleton sets.
Craig Topperf78e3332014-11-25 20:11:31 +00001226 for (Record *Rec : SingletonRegisters) {
Tim Northover03f91972013-09-16 16:43:19 +00001227 RegisterSets.insert(RegisterSet(&Rec, &Rec + 1));
Chris Lattner1de88232010-11-01 01:47:07 +00001228 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00001229
Daniel Dunbarea6408f2009-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 Northover03f91972013-09-16 16:43:19 +00001233 std::map<Record*, RegisterSet> RegisterMap;
David Blaikiee7227132014-11-29 18:13:39 +00001234 for (const CodeGenRegister &CGR : Registers) {
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001235 // Compute the intersection of all sets containing this register.
Tim Northover03f91972013-09-16 16:43:19 +00001236 RegisterSet ContainingSet;
Jim Grosbacha7c78222010-10-29 22:13:48 +00001237
Craig Topperf78e3332014-11-25 20:11:31 +00001238 for (const RegisterSet &RS : RegisterSets) {
David Blaikiee7227132014-11-29 18:13:39 +00001239 if (!RS.count(CGR.TheDef))
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001240 continue;
1241
1242 if (ContainingSet.empty()) {
Craig Topperf78e3332014-11-25 20:11:31 +00001243 ContainingSet = RS;
Chris Lattnerec6f0962010-11-02 18:10:06 +00001244 continue;
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001245 }
Bob Wilson828295b2011-01-26 21:26:19 +00001246
Tim Northover03f91972013-09-16 16:43:19 +00001247 RegisterSet Tmp;
Chris Lattnerec6f0962010-11-02 18:10:06 +00001248 std::swap(Tmp, ContainingSet);
Tim Northover03f91972013-09-16 16:43:19 +00001249 std::insert_iterator<RegisterSet> II(ContainingSet,
1250 ContainingSet.begin());
Craig Topperf78e3332014-11-25 20:11:31 +00001251 std::set_intersection(Tmp.begin(), Tmp.end(), RS.begin(), RS.end(), II,
Tim Northover03f91972013-09-16 16:43:19 +00001252 LessRecordByID());
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001253 }
1254
1255 if (!ContainingSet.empty()) {
1256 RegisterSets.insert(ContainingSet);
David Blaikiee7227132014-11-29 18:13:39 +00001257 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001258 }
1259 }
1260
1261 // Construct the register classes.
Tim Northover03f91972013-09-16 16:43:19 +00001262 std::map<RegisterSet, ClassInfo*, LessRegisterSet> RegisterSetClasses;
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001263 unsigned Index = 0;
Craig Topperf78e3332014-11-25 20:11:31 +00001264 for (const RegisterSet &RS : RegisterSets) {
David Blaikie841db2c2014-11-28 20:35:57 +00001265 Classes.emplace_front();
1266 ClassInfo *CI = &Classes.front();
Daniel Dunbarea6408f2009-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 Topperf78e3332014-11-25 20:11:31 +00001273 CI->Registers = RS;
Jim Grosbach4dbfdfb2012-06-22 23:56:44 +00001274 // FIXME: diagnostic type.
1275 CI->DiagnosticType = "";
Tom Stellard25257d82016-02-05 19:59:33 +00001276 CI->IsOptional = false;
Sam Koltonf117ec12016-05-06 11:31:17 +00001277 CI->DefaultMethod = ""; // unused
Craig Topperf78e3332014-11-25 20:11:31 +00001278 RegisterSetClasses.insert(std::make_pair(RS, CI));
1279 ++Index;
Daniel Dunbarea6408f2009-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 Topperf78e3332014-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 Northover03f91972013-09-16 16:43:19 +00001289 LessRecordByID()))
Craig Topperf78e3332014-11-25 20:11:31 +00001290 CI->SuperClasses.push_back(RegisterSetClasses[RS2]);
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001291 }
1292
1293 // Name the register classes which correspond to a user defined RegisterClass.
David Blaikie7a16f342014-12-03 19:58:45 +00001294 for (const CodeGenRegisterClass &RC : RegClassList) {
Jakob Stoklund Olesen6fea31e2011-10-04 15:28:08 +00001295 // Def will be NULL for non-user defined register classes.
David Blaikie7a16f342014-12-03 19:58:45 +00001296 Record *Def = RC.getDef();
Jakob Stoklund Olesen6fea31e2011-10-04 15:28:08 +00001297 if (!Def)
1298 continue;
David Blaikie7a16f342014-12-03 19:58:45 +00001299 ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(),
1300 RC.getOrder().end())];
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001301 if (CI->ValueName.empty()) {
David Blaikie7a16f342014-12-03 19:58:45 +00001302 CI->ClassName = RC.getName();
1303 CI->Name = "MCK_" + RC.getName();
1304 CI->ValueName = RC.getName();
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001305 } else
David Blaikie7a16f342014-12-03 19:58:45 +00001306 CI->ValueName = CI->ValueName + "," + RC.getName();
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001307
Oliver Stannard0e4cc592017-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 Olesen6fea31e2011-10-04 15:28:08 +00001321 RegisterClassClasses.insert(std::make_pair(Def, CI));
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001322 }
1323
1324 // Populate the map for individual registers.
Tim Northover03f91972013-09-16 16:43:19 +00001325 for (std::map<Record*, RegisterSet>::iterator it = RegisterMap.begin(),
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001326 ie = RegisterMap.end(); it != ie; ++it)
Chris Lattnerec6f0962010-11-02 18:10:06 +00001327 RegisterClasses[it->first] = RegisterSetClasses[it->second];
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001328
1329 // Name the register classes which correspond to singleton registers.
Craig Topperf78e3332014-11-25 20:11:31 +00001330 for (Record *Rec : SingletonRegisters) {
Chris Lattnerec6f0962010-11-02 18:10:06 +00001331 ClassInfo *CI = RegisterClasses[Rec];
Chris Lattner1de88232010-11-01 01:47:07 +00001332 assert(CI && "Missing singleton register class info!");
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001333
Chris Lattner1de88232010-11-01 01:47:07 +00001334 if (CI->ValueName.empty()) {
1335 CI->ClassName = Rec->getName();
Matthias Braun0c517c82016-12-04 05:48:16 +00001336 CI->Name = "MCK_" + Rec->getName().str();
Chris Lattner1de88232010-11-01 01:47:07 +00001337 CI->ValueName = Rec->getName();
1338 } else
Matthias Braun0c517c82016-12-04 05:48:16 +00001339 CI->ValueName = CI->ValueName + "," + Rec->getName().str();
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001340 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001341}
1342
Jim Grosbach8caecde2012-04-19 17:52:32 +00001343void AsmMatcherInfo::buildOperandClasses() {
Chris Lattnere66b7eb2010-11-01 23:57:23 +00001344 std::vector<Record*> AsmOperands =
1345 Records.getAllDerivedDefinitions("AsmOperandClass");
Daniel Dunbara2f5e002010-01-30 01:02:37 +00001346
1347 // Pre-populate AsmOperandClasses map.
David Blaikie841db2c2014-11-28 20:35:57 +00001348 for (Record *Rec : AsmOperands) {
1349 Classes.emplace_front();
1350 AsmOperandClasses[Rec] = &Classes.front();
1351 }
Daniel Dunbara2f5e002010-01-30 01:02:37 +00001352
Daniel Dunbar338825c2009-08-10 18:41:10 +00001353 unsigned Index = 0;
Craig Topperf78e3332014-11-25 20:11:31 +00001354 for (Record *Rec : AsmOperands) {
1355 ClassInfo *CI = AsmOperandClasses[Rec];
Daniel Dunbar338825c2009-08-10 18:41:10 +00001356 CI->Kind = ClassInfo::UserClass0 + Index;
1357
Craig Topperf78e3332014-11-25 20:11:31 +00001358 ListInit *Supers = Rec->getValueAsListInit("SuperClasses");
Craig Toppera1bedd72015-06-02 04:15:51 +00001359 for (Init *I : Supers->getValues()) {
1360 DefInit *DI = dyn_cast<DefInit>(I);
Daniel Dunbar54ddf3d2010-05-22 21:02:29 +00001361 if (!DI) {
Craig Topperf78e3332014-11-25 20:11:31 +00001362 PrintError(Rec->getLoc(), "Invalid super class reference!");
Daniel Dunbar54ddf3d2010-05-22 21:02:29 +00001363 continue;
1364 }
1365
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001366 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1367 if (!SC)
Craig Topperf78e3332014-11-25 20:11:31 +00001368 PrintError(Rec->getLoc(), "Invalid super class reference!");
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001369 else
1370 CI->SuperClasses.push_back(SC);
Daniel Dunbar338825c2009-08-10 18:41:10 +00001371 }
Craig Topperf78e3332014-11-25 20:11:31 +00001372 CI->ClassName = Rec->getValueAsString("Name");
Daniel Dunbar338825c2009-08-10 18:41:10 +00001373 CI->Name = "MCK_" + CI->ClassName;
Craig Topperf78e3332014-11-25 20:11:31 +00001374 CI->ValueName = Rec->getName();
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001375
1376 // Get or construct the predicate method name.
Craig Topperf78e3332014-11-25 20:11:31 +00001377 Init *PMName = Rec->getValueInit("PredicateMethod");
Sean Silva6cfc8062012-10-10 20:24:43 +00001378 if (StringInit *SI = dyn_cast<StringInit>(PMName)) {
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001379 CI->PredicateMethod = SI->getValue();
1380 } else {
Sean Silva3f7b7f82012-10-10 20:24:47 +00001381 assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!");
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001382 CI->PredicateMethod = "is" + CI->ClassName;
1383 }
1384
1385 // Get or construct the render method name.
Craig Topperf78e3332014-11-25 20:11:31 +00001386 Init *RMName = Rec->getValueInit("RenderMethod");
Sean Silva6cfc8062012-10-10 20:24:43 +00001387 if (StringInit *SI = dyn_cast<StringInit>(RMName)) {
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001388 CI->RenderMethod = SI->getValue();
1389 } else {
Sean Silva3f7b7f82012-10-10 20:24:47 +00001390 assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!");
Daniel Dunbar5c468e32009-08-10 21:00:45 +00001391 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1392 }
1393
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001394 // Get the parse method name or leave it as empty.
Craig Topperf78e3332014-11-25 20:11:31 +00001395 Init *PRMName = Rec->getValueInit("ParserMethod");
Sean Silva6cfc8062012-10-10 20:24:43 +00001396 if (StringInit *SI = dyn_cast<StringInit>(PRMName))
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001397 CI->ParserMethod = SI->getValue();
1398
Oliver Stannardfe3c8f92017-10-03 14:34:57 +00001399 // Get the diagnostic type and string or leave them as empty.
Craig Topperf78e3332014-11-25 20:11:31 +00001400 Init *DiagnosticType = Rec->getValueInit("DiagnosticType");
Sean Silva6cfc8062012-10-10 20:24:43 +00001401 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
Jim Grosbach4dbfdfb2012-06-22 23:56:44 +00001402 CI->DiagnosticType = SI->getValue();
Oliver Stannardfe3c8f92017-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 Grosbach4dbfdfb2012-06-22 23:56:44 +00001410
Tom Stellard25257d82016-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 Koltonf117ec12016-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 Topperf78e3332014-11-25 20:11:31 +00001424 ++Index;
Daniel Dunbar338825c2009-08-10 18:41:10 +00001425 }
Daniel Dunbarea6408f2009-08-11 02:59:53 +00001426}
1427
Bob Wilson828295b2011-01-26 21:26:19 +00001428AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1429 CodeGenTarget &target,
Chris Lattner9c6b60e2010-12-15 04:48:22 +00001430 RecordKeeper &records)
Devang Patel63faf822012-01-07 01:33:34 +00001431 : Records(records), AsmParser(asmParser), Target(target) {
Daniel Dunbar59fc42d2009-08-11 20:59:47 +00001432}
1433
Jim Grosbach8caecde2012-04-19 17:52:32 +00001434/// buildOperandMatchInfo - Build the necessary information to handle user
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001435/// defined operand parsing methods.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001436void AsmMatcherInfo::buildOperandMatchInfo() {
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001437
Jim Grosbachd4824fc2012-04-18 23:46:25 +00001438 /// Map containing a mask with all operands indices that can be found for
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001439 /// that class inside a instruction.
Benjamin Krameree5e6072014-03-01 11:47:00 +00001440 typedef std::map<ClassInfo *, unsigned, less_ptr<ClassInfo>> OpClassMaskTy;
Sean Silvab2df6102012-09-19 01:47:03 +00001441 OpClassMaskTy OpClassMask;
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001442
Craig Topper44ebfb72014-11-28 03:53:02 +00001443 for (const auto &MI : Matchables) {
Bruno Cardoso Lopese7a54522011-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 Smithb60bcfd2014-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 Lopese7a54522011-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 Topper99a21702014-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 Smithb60bcfd2014-11-28 23:00:22 +00001460 OperandMatchInfo.push_back(OperandMatchEntry::create(MI.get(), CI,
1461 OpMask));
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00001462 }
1463 }
1464}
1465
Jim Grosbach8caecde2012-04-19 17:52:32 +00001466void AsmMatcherInfo::buildInfo() {
Chris Lattner0aed1e72010-10-30 20:07:57 +00001467 // Build information about all of the AssemblerPredicates.
Daniel Sanders57a599e2016-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 Sanders027cab52016-11-15 10:13:09 +00001472#ifndef NDEBUG
Daniel Sanders57a599e2016-11-15 09:51:02 +00001473 for (const auto &Pair : SubtargetFeatures)
Nicola Zaghen0818e782018-05-14 12:53:11 +00001474 LLVM_DEBUG(Pair.second.dump());
Daniel Sanders027cab52016-11-15 10:13:09 +00001475#endif // NDEBUG
Daniel Sanders57a599e2016-11-15 09:51:02 +00001476 assert(SubtargetFeatures.size() <= 64 && "Too many subtarget features!");
Jim Grosbacha7c78222010-10-29 22:13:48 +00001477
Craig Topper5ef13492015-12-31 08:18:23 +00001478 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
Sander de Smalencb6c95b2018-02-04 16:24:17 +00001479 bool ReportMultipleNearMisses =
1480 AsmParser->getValueAsBit("ReportMultipleNearMisses");
Craig Topper5ef13492015-12-31 08:18:23 +00001481
Chris Lattner39ee0362010-10-31 19:10:56 +00001482 // Parse the instructions; we need to do this first so that we can gather the
1483 // singleton register classes.
Chris Lattner1de88232010-11-01 01:47:07 +00001484 SmallPtrSet<Record*, 16> SingletonRegisters;
Devang Patel0dbcada2012-01-09 19:13:28 +00001485 unsigned VariantCount = Target.getAsmParserVariantCount();
1486 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1487 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topper2a129872017-05-31 21:12:46 +00001488 StringRef CommentDelimiter =
1489 AsmVariant->getValueAsString("CommentDelimiter");
Colin LeMahieu1539acf2015-11-09 00:31:07 +00001490 AsmVariantInfo Variant;
Craig Toppere6b50232015-12-30 06:00:18 +00001491 Variant.RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
Colin LeMahieu1539acf2015-11-09 00:31:07 +00001492 Variant.TokenizingCharacters =
1493 AsmVariant->getValueAsString("TokenizingCharacters");
1494 Variant.SeparatorCharacters =
1495 AsmVariant->getValueAsString("SeparatorCharacters");
1496 Variant.BreakCharacters =
1497 AsmVariant->getValueAsString("BreakCharacters");
Sam Koltone3aa0d92016-09-08 15:50:52 +00001498 Variant.Name = AsmVariant->getValueAsString("Name");
Craig Toppere6b50232015-12-30 06:00:18 +00001499 Variant.AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Jim Grosbachf35307c2012-01-24 21:06:59 +00001500
Craig Toppere4b85522016-01-17 20:38:18 +00001501 for (const CodeGenInstruction *CGI : Target.getInstructionsByEnumValue()) {
Jim Grosbachf35307c2012-01-24 21:06:59 +00001502
Devang Patel0dbcada2012-01-09 19:13:28 +00001503 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1504 // filter the set of instructions we consider.
Craig Topperf78e3332014-11-25 20:11:31 +00001505 if (!StringRef(CGI->TheDef->getName()).startswith(MatchPrefix))
Jim Grosbach11fc6462012-04-11 21:02:33 +00001506 continue;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001507
Devang Patel0dbcada2012-01-09 19:13:28 +00001508 // Ignore "codegen only" instructions.
Craig Topperf78e3332014-11-25 20:11:31 +00001509 if (CGI->TheDef->getValueAsBit("isCodeGenOnly"))
Jim Grosbach11fc6462012-04-11 21:02:33 +00001510 continue;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001511
Sam Koltone3aa0d92016-09-08 15:50:52 +00001512 // Ignore instructions for different instructions
Craig Topper2a129872017-05-31 21:12:46 +00001513 StringRef V = CGI->TheDef->getValueAsString("AsmVariantName");
Sam Koltone3aa0d92016-09-08 15:50:52 +00001514 if (!V.empty() && V != Variant.Name)
1515 continue;
1516
Craig Toppercb52ea52015-09-06 03:44:50 +00001517 auto II = llvm::make_unique<MatchableInfo>(*CGI);
Jim Grosbachf35307c2012-01-24 21:06:59 +00001518
Craig Topper5ef13492015-12-31 08:18:23 +00001519 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
Jim Grosbachf35307c2012-01-24 21:06:59 +00001520
Devang Patel0dbcada2012-01-09 19:13:28 +00001521 // Ignore instructions which shouldn't be matched and diagnose invalid
1522 // instruction definitions with an error.
Sander de Smalencb6c95b2018-02-04 16:24:17 +00001523 if (!II->validate(CommentDelimiter, false))
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00001524 continue;
1525
1526 Matchables.push_back(std::move(II));
Chris Lattner1d13bda2010-11-04 00:43:46 +00001527 }
Jim Grosbachf35307c2012-01-24 21:06:59 +00001528
Devang Patel0dbcada2012-01-09 19:13:28 +00001529 // Parse all of the InstAlias definitions and stick them in the list of
1530 // matchables.
1531 std::vector<Record*> AllInstAliases =
1532 Records.getAllDerivedDefinitions("InstAlias");
1533 for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
David Blaikied39a5d42014-12-22 21:26:26 +00001534 auto Alias = llvm::make_unique<CodeGenInstAlias>(AllInstAliases[i],
Craig Toppere6b50232015-12-30 06:00:18 +00001535 Target);
Jim Grosbachf35307c2012-01-24 21:06:59 +00001536
Devang Patel0dbcada2012-01-09 19:13:28 +00001537 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1538 // filter the set of instruction aliases we consider, based on the target
1539 // instruction.
Jim Grosbach65da6fc2012-04-17 00:01:04 +00001540 if (!StringRef(Alias->ResultInst->TheDef->getName())
1541 .startswith( MatchPrefix))
Jim Grosbach11fc6462012-04-11 21:02:33 +00001542 continue;
Jim Grosbachf35307c2012-01-24 21:06:59 +00001543
Craig Topper2a129872017-05-31 21:12:46 +00001544 StringRef V = Alias->TheDef->getValueAsString("AsmVariantName");
Sam Koltone3aa0d92016-09-08 15:50:52 +00001545 if (!V.empty() && V != Variant.Name)
1546 continue;
1547
Craig Toppercb52ea52015-09-06 03:44:50 +00001548 auto II = llvm::make_unique<MatchableInfo>(std::move(Alias));
Jim Grosbachf35307c2012-01-24 21:06:59 +00001549
Craig Topper5ef13492015-12-31 08:18:23 +00001550 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
Jim Grosbachf35307c2012-01-24 21:06:59 +00001551
Devang Patel0dbcada2012-01-09 19:13:28 +00001552 // Validate the alias definitions.
Sander de Smalencb6c95b2018-02-04 16:24:17 +00001553 II->validate(CommentDelimiter, true);
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00001554
1555 Matchables.push_back(std::move(II));
Devang Patel0dbcada2012-01-09 19:13:28 +00001556 }
Chris Lattnerc76e80d2010-11-01 04:05:41 +00001557 }
Chris Lattnerc240bb02010-11-01 04:03:32 +00001558
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001559 // Build info for the register classes.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001560 buildRegisterClasses(SingletonRegisters);
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001561
1562 // Build info for the user defined assembly operand classes.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001563 buildOperandClasses();
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001564
Chris Lattner0bb780c2010-11-04 00:57:06 +00001565 // Build the information about matchables, now that we have fully formed
1566 // classes.
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00001567 std::vector<std::unique_ptr<MatchableInfo>> NewMatchables;
Craig Topper44ebfb72014-11-28 03:53:02 +00001568 for (auto &II : Matchables) {
Chris Lattnere206fcf2010-09-06 21:01:37 +00001569 // Parse the tokens after the mnemonic.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001570 // Note: buildInstructionOperandReference may insert new AsmOperands, so
Bob Wilsona49c7df2011-01-26 19:44:55 +00001571 // don't precompute the loop bound.
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00001572 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1573 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
Chris Lattnerd19ec052010-11-02 17:30:52 +00001574 StringRef Token = Op.Token;
Daniel Dunbar20927f22009-08-07 08:26:05 +00001575
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001576 // Check for singleton registers.
Craig Topper300c9662015-12-29 07:03:23 +00001577 if (Record *RegRecord = Op.SingletonReg) {
Chris Lattnerd19ec052010-11-02 17:30:52 +00001578 Op.Class = RegisterClasses[RegRecord];
Chris Lattner02bcbc92010-11-01 01:37:30 +00001579 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1580 "Unexpected class for singleton register");
Chris Lattner02bcbc92010-11-01 01:37:30 +00001581 continue;
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00001582 }
1583
Daniel Dunbar20927f22009-08-07 08:26:05 +00001584 // Check for simple tokens.
1585 if (Token[0] != '$') {
Chris Lattnerd19ec052010-11-02 17:30:52 +00001586 Op.Class = getTokenClass(Token);
Daniel Dunbar20927f22009-08-07 08:26:05 +00001587 continue;
1588 }
1589
Chris Lattner7ad31472010-11-06 22:06:03 +00001590 if (Token.size() > 1 && isdigit(Token[1])) {
1591 Op.Class = getTokenClass(Token);
1592 continue;
1593 }
Bob Wilson828295b2011-01-26 21:26:19 +00001594
Chris Lattnerc07bd402010-11-04 02:11:18 +00001595 // Otherwise this is an operand reference.
Chris Lattner5f4280c2010-11-04 01:58:23 +00001596 StringRef OperandName;
1597 if (Token[1] == '{')
1598 OperandName = Token.substr(2, Token.size() - 3);
1599 else
1600 OperandName = Token.substr(1);
Bob Wilson828295b2011-01-26 21:26:19 +00001601
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00001602 if (II->DefRec.is<const CodeGenInstruction*>())
1603 buildInstructionOperandReference(II.get(), OperandName, i);
Chris Lattnerc07bd402010-11-04 02:11:18 +00001604 else
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00001605 buildAliasOperandReference(II.get(), OperandName, Op);
Daniel Dunbar20927f22009-08-07 08:26:05 +00001606 }
Bob Wilson828295b2011-01-26 21:26:19 +00001607
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00001608 if (II->DefRec.is<const CodeGenInstruction*>()) {
1609 II->buildInstructionResultOperands();
Jim Grosbachc1922c72012-04-19 23:59:23 +00001610 // If the instruction has a two-operand alias, build up the
1611 // matchable here. We'll add them in bulk at the end to avoid
1612 // confusing this loop.
Craig Topper2a129872017-05-31 21:12:46 +00001613 StringRef Constraint =
1614 II->TheDef->getValueAsString("TwoOperandAliasConstraint");
Jim Grosbachc1922c72012-04-19 23:59:23 +00001615 if (Constraint != "") {
1616 // Start by making a copy of the original matchable.
Craig Toppercb52ea52015-09-06 03:44:50 +00001617 auto AliasII = llvm::make_unique<MatchableInfo>(*II);
Jim Grosbachc1922c72012-04-19 23:59:23 +00001618
1619 // Adjust it to be a two-operand alias.
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00001620 AliasII->formTwoOperandAlias(Constraint);
1621
1622 // Add the alias to the matchables list.
1623 NewMatchables.push_back(std::move(AliasII));
Jim Grosbachc1922c72012-04-19 23:59:23 +00001624 }
1625 } else
Sander de Smalencb6c95b2018-02-04 16:24:17 +00001626 // FIXME: The tied operands checking is not yet integrated with the
1627 // framework for reporting multiple near misses. To prevent invalid
1628 // formats from being matched with an alias if a tied-operands check
1629 // would otherwise have disallowed it, we just disallow such constructs
1630 // in TableGen completely.
1631 II->buildAliasResultOperands(!ReportMultipleNearMisses);
Daniel Dunbar20927f22009-08-07 08:26:05 +00001632 }
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00001633 if (!NewMatchables.empty())
Benjamin Kramer31fbd9f2015-02-28 10:11:12 +00001634 Matchables.insert(Matchables.end(),
1635 std::make_move_iterator(NewMatchables.begin()),
1636 std::make_move_iterator(NewMatchables.end()));
Daniel Dunbar5fe63382009-08-09 07:20:21 +00001637
Jim Grosbacha66512e2011-12-06 23:43:54 +00001638 // Process token alias definitions and set up the associated superclass
1639 // information.
1640 std::vector<Record*> AllTokenAliases =
1641 Records.getAllDerivedDefinitions("TokenAlias");
Craig Topper300c9662015-12-29 07:03:23 +00001642 for (Record *Rec : AllTokenAliases) {
Jim Grosbacha66512e2011-12-06 23:43:54 +00001643 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1644 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
Jim Grosbach67cd20d2012-04-17 21:23:52 +00001645 if (FromClass == ToClass)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001646 PrintFatalError(Rec->getLoc(),
Jim Grosbach67cd20d2012-04-17 21:23:52 +00001647 "error: Destination value identical to source value.");
Jim Grosbacha66512e2011-12-06 23:43:54 +00001648 FromClass->SuperClasses.push_back(ToClass);
1649 }
1650
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001651 // Reorder classes so that classes precede super classes.
David Blaikie841db2c2014-11-28 20:35:57 +00001652 Classes.sort();
Oliver Stannard09f29b22016-01-25 10:20:19 +00001653
Matthias Braun94785562016-12-05 19:44:31 +00001654#ifdef EXPENSIVE_CHECKS
1655 // Verify that the table is sorted and operator < works transitively.
Oliver Stannard09f29b22016-01-25 10:20:19 +00001656 for (auto I = Classes.begin(), E = Classes.end(); I != E; ++I) {
1657 for (auto J = I; J != E; ++J) {
1658 assert(!(*J < *I));
1659 assert(I == J || !J->isSubsetOf(*I));
1660 }
1661 }
Matthias Braun94785562016-12-05 19:44:31 +00001662#endif
Daniel Dunbar20927f22009-08-07 08:26:05 +00001663}
1664
Jim Grosbach8caecde2012-04-19 17:52:32 +00001665/// buildInstructionOperandReference - The specified operand is a reference to a
Chris Lattner0bb780c2010-11-04 00:57:06 +00001666/// named operand such as $src. Resolve the Class and OperandInfo pointers.
1667void AsmMatcherInfo::
Jim Grosbach8caecde2012-04-19 17:52:32 +00001668buildInstructionOperandReference(MatchableInfo *II,
Chris Lattner5f4280c2010-11-04 01:58:23 +00001669 StringRef OperandName,
Bob Wilsona49c7df2011-01-26 19:44:55 +00001670 unsigned AsmOpIdx) {
Chris Lattnerc07bd402010-11-04 02:11:18 +00001671 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1672 const CGIOperandList &Operands = CGI.Operands;
Bob Wilsona49c7df2011-01-26 19:44:55 +00001673 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
Bob Wilson828295b2011-01-26 21:26:19 +00001674
Chris Lattner662e5a32010-11-06 07:14:44 +00001675 // Map this token to an operand.
Chris Lattner0bb780c2010-11-04 00:57:06 +00001676 unsigned Idx;
1677 if (!Operands.hasOperandNamed(OperandName, Idx))
Benjamin Kramerabe43b52014-03-29 17:17:15 +00001678 PrintFatalError(II->TheDef->getLoc(),
1679 "error: unable to find operand: '" + OperandName + "'");
Chris Lattnerba3b5b62010-11-04 01:55:23 +00001680
Bob Wilsona49c7df2011-01-26 19:44:55 +00001681 // If the instruction operand has multiple suboperands, but the parser
1682 // match class for the asm operand is still the default "ImmAsmOperand",
1683 // then handle each suboperand separately.
1684 if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
1685 Record *Rec = Operands[Idx].Rec;
1686 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
1687 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1688 if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
1689 // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
1690 StringRef Token = Op->Token; // save this in case Op gets moved
1691 for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
Ahmed Bougachad4b59dc2015-05-29 01:03:37 +00001692 MatchableInfo::AsmOperand NewAsmOp(/*IsIsolatedToken=*/true, Token);
Bob Wilsona49c7df2011-01-26 19:44:55 +00001693 NewAsmOp.SubOpIdx = SI;
1694 II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
1695 }
1696 // Replace Op with first suboperand.
1697 Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
1698 Op->SubOpIdx = 0;
1699 }
1700 }
1701
Chris Lattnerba3b5b62010-11-04 01:55:23 +00001702 // Set up the operand class.
Bob Wilsona49c7df2011-01-26 19:44:55 +00001703 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
Sander de Smalencb6c95b2018-02-04 16:24:17 +00001704 Op->OrigSrcOpName = OperandName;
Chris Lattnerba3b5b62010-11-04 01:55:23 +00001705
1706 // If the named operand is tied, canonicalize it to the untied operand.
1707 // For example, something like:
1708 // (outs GPR:$dst), (ins GPR:$src)
1709 // with an asmstring of
1710 // "inc $src"
1711 // we want to canonicalize to:
1712 // "inc $dst"
1713 // so that we know how to provide the $dst operand when filling in the result.
Ulrich Weigandd9990622013-04-27 18:48:23 +00001714 int OITied = -1;
1715 if (Operands[Idx].MINumOperands == 1)
1716 OITied = Operands[Idx].getTiedRegister();
Chris Lattner0bb780c2010-11-04 00:57:06 +00001717 if (OITied != -1) {
1718 // The tied operand index is an MIOperand index, find the operand that
1719 // contains it.
Bob Wilsona49c7df2011-01-26 19:44:55 +00001720 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1721 OperandName = Operands[Idx.first].Name;
1722 Op->SubOpIdx = Idx.second;
Chris Lattner0bb780c2010-11-04 00:57:06 +00001723 }
Bob Wilson828295b2011-01-26 21:26:19 +00001724
Bob Wilsona49c7df2011-01-26 19:44:55 +00001725 Op->SrcOpName = OperandName;
Chris Lattner0bb780c2010-11-04 00:57:06 +00001726}
1727
Jim Grosbach8caecde2012-04-19 17:52:32 +00001728/// buildAliasOperandReference - When parsing an operand reference out of the
Chris Lattner3f2c8e42010-11-06 07:06:09 +00001729/// matching string (e.g. "movsx $src, $dst"), determine what the class of the
1730/// operand reference is by looking it up in the result pattern definition.
Jim Grosbach8caecde2012-04-19 17:52:32 +00001731void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
Chris Lattnerc07bd402010-11-04 02:11:18 +00001732 StringRef OperandName,
1733 MatchableInfo::AsmOperand &Op) {
1734 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
Bob Wilson828295b2011-01-26 21:26:19 +00001735
Chris Lattnerc07bd402010-11-04 02:11:18 +00001736 // Set up the operand class.
Chris Lattner3f2c8e42010-11-06 07:06:09 +00001737 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
Chris Lattner98c870f2010-11-06 19:25:43 +00001738 if (CGA.ResultOperands[i].isRecord() &&
1739 CGA.ResultOperands[i].getName() == OperandName) {
Chris Lattner662e5a32010-11-06 07:14:44 +00001740 // It's safe to go with the first one we find, because CodeGenInstAlias
1741 // validates that all operands with the same name have the same record.
Bob Wilsona49c7df2011-01-26 19:44:55 +00001742 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
Jim Grosbach48c1f842011-10-28 22:32:53 +00001743 // Use the match class from the Alias definition, not the
1744 // destination instruction, as we may have an immediate that's
1745 // being munged by the match class.
1746 Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
Bob Wilsona49c7df2011-01-26 19:44:55 +00001747 Op.SubOpIdx);
Chris Lattner3f2c8e42010-11-06 07:06:09 +00001748 Op.SrcOpName = OperandName;
Sander de Smalencb6c95b2018-02-04 16:24:17 +00001749 Op.OrigSrcOpName = OperandName;
Chris Lattner3f2c8e42010-11-06 07:06:09 +00001750 return;
Chris Lattnerc07bd402010-11-04 02:11:18 +00001751 }
Chris Lattner3f2c8e42010-11-06 07:06:09 +00001752
Benjamin Kramerabe43b52014-03-29 17:17:15 +00001753 PrintFatalError(II->TheDef->getLoc(),
1754 "error: unable to find operand: '" + OperandName + "'");
Chris Lattnerc07bd402010-11-04 02:11:18 +00001755}
1756
Jim Grosbach8caecde2012-04-19 17:52:32 +00001757void MatchableInfo::buildInstructionResultOperands() {
Chris Lattner662e5a32010-11-06 07:14:44 +00001758 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilson828295b2011-01-26 21:26:19 +00001759
Chris Lattner662e5a32010-11-06 07:14:44 +00001760 // Loop over all operands of the result instruction, determining how to
1761 // populate them.
Craig Topper300c9662015-12-29 07:03:23 +00001762 for (const CGIOperandList::OperandInfo &OpInfo : ResultInst->Operands) {
Chris Lattner567820c2010-11-04 01:42:59 +00001763 // If this is a tied operand, just copy from the previously handled operand.
Ulrich Weigandd9990622013-04-27 18:48:23 +00001764 int TiedOp = -1;
1765 if (OpInfo.MINumOperands == 1)
1766 TiedOp = OpInfo.getTiedRegister();
Chris Lattner567820c2010-11-04 01:42:59 +00001767 if (TiedOp != -1) {
Sander de Smalencb6c95b2018-02-04 16:24:17 +00001768 int TiedSrcOperand = findAsmOperandOriginallyNamed(OpInfo.Name);
1769 if (TiedSrcOperand != -1 &&
1770 ResOperands[TiedOp].Kind == ResOperand::RenderAsmOperand)
1771 ResOperands.push_back(ResOperand::getTiedOp(
1772 TiedOp, ResOperands[TiedOp].AsmOperandNum, TiedSrcOperand));
1773 else
1774 ResOperands.push_back(ResOperand::getTiedOp(TiedOp, 0, 0));
Chris Lattner567820c2010-11-04 01:42:59 +00001775 continue;
1776 }
Bob Wilson828295b2011-01-26 21:26:19 +00001777
Jim Grosbach8caecde2012-04-19 17:52:32 +00001778 int SrcOperand = findAsmOperandNamed(OpInfo.Name);
Ulrich Weigandd9990622013-04-27 18:48:23 +00001779 if (OpInfo.Name.empty() || SrcOperand == -1) {
1780 // This may happen for operands that are tied to a suboperand of a
1781 // complex operand. Simply use a dummy value here; nobody should
1782 // use this operand slot.
1783 // FIXME: The long term goal is for the MCOperand list to not contain
1784 // tied operands at all.
1785 ResOperands.push_back(ResOperand::getImmOp(0));
1786 continue;
1787 }
Chris Lattner567820c2010-11-04 01:42:59 +00001788
Bob Wilsona49c7df2011-01-26 19:44:55 +00001789 // Check if the one AsmOperand populates the entire operand.
1790 unsigned NumOperands = OpInfo.MINumOperands;
1791 if (AsmOperands[SrcOperand].SubOpIdx == -1) {
1792 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
Chris Lattner1d13bda2010-11-04 00:43:46 +00001793 continue;
1794 }
Bob Wilsona49c7df2011-01-26 19:44:55 +00001795
1796 // Add a separate ResOperand for each suboperand.
1797 for (unsigned AI = 0; AI < NumOperands; ++AI) {
1798 assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
1799 AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
1800 "unexpected AsmOperands for suboperands");
1801 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
1802 }
Chris Lattner1d13bda2010-11-04 00:43:46 +00001803 }
1804}
1805
Sander de Smalencb6c95b2018-02-04 16:24:17 +00001806void MatchableInfo::buildAliasResultOperands(bool AliasConstraintsAreChecked) {
Chris Lattner41409852010-11-06 07:31:43 +00001807 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1808 const CodeGenInstruction *ResultInst = getResultInst();
Bob Wilson828295b2011-01-26 21:26:19 +00001809
Sander de Smalencb6c95b2018-02-04 16:24:17 +00001810 // Map of: $reg -> #lastref
1811 // where $reg is the name of the operand in the asm string
1812 // where #lastref is the last processed index where $reg was referenced in
1813 // the asm string.
1814 SmallDenseMap<StringRef, int> OperandRefs;
1815
Chris Lattner41409852010-11-06 07:31:43 +00001816 // Loop over all operands of the result instruction, determining how to
1817 // populate them.
1818 unsigned AliasOpNo = 0;
Bob Wilsona49c7df2011-01-26 19:44:55 +00001819 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
Chris Lattner41409852010-11-06 07:31:43 +00001820 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
Bob Wilsona49c7df2011-01-26 19:44:55 +00001821 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
Bob Wilson828295b2011-01-26 21:26:19 +00001822
Chris Lattner41409852010-11-06 07:31:43 +00001823 // If this is a tied operand, just copy from the previously handled operand.
Ulrich Weigandd9990622013-04-27 18:48:23 +00001824 int TiedOp = -1;
1825 if (OpInfo->MINumOperands == 1)
1826 TiedOp = OpInfo->getTiedRegister();
Chris Lattner41409852010-11-06 07:31:43 +00001827 if (TiedOp != -1) {
Sander de Smalencb6c95b2018-02-04 16:24:17 +00001828 unsigned SrcOp1 = 0;
1829 unsigned SrcOp2 = 0;
1830
1831 // If an operand has been specified twice in the asm string,
1832 // add the two source operand's indices to the TiedOp so that
1833 // at runtime the 'tied' constraint is checked.
1834 if (ResOperands[TiedOp].Kind == ResOperand::RenderAsmOperand) {
1835 SrcOp1 = ResOperands[TiedOp].AsmOperandNum;
1836
1837 // Find the next operand (similarly named operand) in the string.
1838 StringRef Name = AsmOperands[SrcOp1].SrcOpName;
1839 auto Insert = OperandRefs.try_emplace(Name, SrcOp1);
1840 SrcOp2 = findAsmOperandNamed(Name, Insert.first->second);
1841
1842 // Not updating the record in OperandRefs will cause TableGen
1843 // to fail with an error at the end of this function.
1844 if (AliasConstraintsAreChecked)
1845 Insert.first->second = SrcOp2;
1846
1847 // In case it only has one reference in the asm string,
1848 // it doesn't need to be checked for tied constraints.
1849 SrcOp2 = (SrcOp2 == (unsigned)-1) ? SrcOp1 : SrcOp2;
1850 }
1851
Sander de Smalenb0c87382018-06-18 13:39:29 +00001852 // If the alias operand is of a different operand class, we only want
1853 // to benefit from the tied-operands check and just match the operand
1854 // as a normal, but not copy the original (TiedOp) to the result
1855 // instruction. We do this by passing -1 as the tied operand to copy.
1856 if (ResultInst->Operands[i].Rec->getName() !=
1857 ResultInst->Operands[TiedOp].Rec->getName()) {
1858 SrcOp1 = ResOperands[TiedOp].AsmOperandNum;
1859 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1860 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1861 SrcOp2 = findAsmOperand(Name, SubIdx);
1862 ResOperands.push_back(
1863 ResOperand::getTiedOp((unsigned)-1, SrcOp1, SrcOp2));
1864 } else {
1865 ResOperands.push_back(ResOperand::getTiedOp(TiedOp, SrcOp1, SrcOp2));
1866 continue;
1867 }
Chris Lattner90fd7972010-11-06 19:57:21 +00001868 }
1869
Bob Wilsona49c7df2011-01-26 19:44:55 +00001870 // Handle all the suboperands for this operand.
1871 const std::string &OpName = OpInfo->Name;
1872 for ( ; AliasOpNo < LastOpNo &&
1873 CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
1874 int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
1875
1876 // Find out what operand from the asmparser that this MCInst operand
1877 // comes from.
1878 switch (CGA.ResultOperands[AliasOpNo].Kind) {
Bob Wilsona49c7df2011-01-26 19:44:55 +00001879 case CodeGenInstAlias::ResultOperand::K_Record: {
1880 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
Jim Grosbach8caecde2012-04-19 17:52:32 +00001881 int SrcOperand = findAsmOperand(Name, SubIdx);
Bob Wilsona49c7df2011-01-26 19:44:55 +00001882 if (SrcOperand == -1)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001883 PrintFatalError(TheDef->getLoc(), "Instruction '" +
Bob Wilsona49c7df2011-01-26 19:44:55 +00001884 TheDef->getName() + "' has operand '" + OpName +
1885 "' that doesn't appear in asm string!");
Sander de Smalencb6c95b2018-02-04 16:24:17 +00001886
1887 // Add it to the operand references. If it is added a second time, the
1888 // record won't be updated and it will fail later on.
1889 OperandRefs.try_emplace(Name, SrcOperand);
1890
Bob Wilsona49c7df2011-01-26 19:44:55 +00001891 unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
1892 ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
1893 NumOperands));
1894 break;
1895 }
1896 case CodeGenInstAlias::ResultOperand::K_Imm: {
1897 int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
1898 ResOperands.push_back(ResOperand::getImmOp(ImmVal));
1899 break;
1900 }
1901 case CodeGenInstAlias::ResultOperand::K_Reg: {
1902 Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
1903 ResOperands.push_back(ResOperand::getRegOp(Reg));
1904 break;
1905 }
1906 }
Chris Lattner90fd7972010-11-06 19:57:21 +00001907 }
Chris Lattner41409852010-11-06 07:31:43 +00001908 }
Sander de Smalencb6c95b2018-02-04 16:24:17 +00001909
1910 // Check that operands are not repeated more times than is supported.
1911 for (auto &T : OperandRefs) {
1912 if (T.second != -1 && findAsmOperandNamed(T.first, T.second) != -1)
1913 PrintFatalError(TheDef->getLoc(),
1914 "Operand '" + T.first + "' can never be matched");
1915 }
Chris Lattner41409852010-11-06 07:31:43 +00001916}
Chris Lattner1d13bda2010-11-04 00:43:46 +00001917
Justin Lebar2c937a12016-10-21 21:45:01 +00001918static unsigned
1919getConverterOperandID(const std::string &Name,
1920 SmallSetVector<CachedHashString, 16> &Table,
1921 bool &IsNew) {
1922 IsNew = Table.insert(CachedHashString(Name));
Jim Grosbachc8f267f2012-08-22 01:06:23 +00001923
David Majnemer975248e2016-08-11 22:21:41 +00001924 unsigned ID = IsNew ? Table.size() - 1 : find(Table, Name) - Table.begin();
Jim Grosbachc8f267f2012-08-22 01:06:23 +00001925
1926 assert(ID < Table.size());
1927
1928 return ID;
1929}
1930
Chad Rosier22685872012-10-01 23:45:51 +00001931static void emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName,
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00001932 std::vector<std::unique_ptr<MatchableInfo>> &Infos,
Sam Koltonf117ec12016-05-06 11:31:17 +00001933 bool HasMnemonicFirst, bool HasOptionalOperands,
1934 raw_ostream &OS) {
Justin Lebar2c937a12016-10-21 21:45:01 +00001935 SmallSetVector<CachedHashString, 16> OperandConversionKinds;
1936 SmallSetVector<CachedHashString, 16> InstructionConversionKinds;
Jim Grosbachc8f267f2012-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 Grosbacha7c78222010-10-29 22:13:48 +00001939
Chris Lattner98986712010-01-14 22:21:20 +00001940 // TargetOperandClass - This is the target's operand class, like X86Operand.
Matthias Braun0c517c82016-12-04 05:48:16 +00001941 std::string TargetOperandClass = Target.getName().str() + "Operand";
Jim Grosbacha7c78222010-10-29 22:13:48 +00001942
Jim Grosbachc8f267f2012-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 Koltonf117ec12016-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 Daveb02dd202017-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 Koltonf117ec12016-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 Daveb02dd202017-08-07 13:55:27 +00001982 CvtOS << " OpIdx = *(p + 1) - DefaultsOffset[*(p + 1)];\n";
Sam Koltonf117ec12016-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 Smalencb6c95b2018-02-04 16:24:17 +00001992 CvtOS << " case CVT_Tied: {\n";
Simon Pilgrim7abdc5f2018-02-17 12:29:47 +00001993 CvtOS << " assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
1994 CvtOS << " std::begin(TiedAsmOperandTable)) &&\n";
Sander de Smalencb6c95b2018-02-04 16:24:17 +00001995 CvtOS << " \"Tied operand not found\");\n";
1996 CvtOS << " unsigned TiedResOpnd = TiedAsmOperandTable[OpIdx][0];\n";
Sander de Smalenb0c87382018-06-18 13:39:29 +00001997 CvtOS << " if (TiedResOpnd != (uint8_t) -1)\n";
1998 CvtOS << " Inst.addOperand(Inst.getOperand(TiedResOpnd));\n";
Sam Koltonf117ec12016-05-06 11:31:17 +00001999 CvtOS << " break;\n";
Sander de Smalencb6c95b2018-02-04 16:24:17 +00002000 CvtOS << " }\n";
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002001
Chad Rosier62316fa2012-08-30 17:59:25 +00002002 std::string OperandFnBody;
2003 raw_string_ostream OpOS(OperandFnBody);
2004 // Start the operand number lookup function.
Chad Rosier22685872012-10-01 23:45:51 +00002005 OpOS << "void " << Target.getName() << ClassName << "::\n"
2006 << "convertToMapAndConstraints(unsigned Kind,\n";
Chad Rosierc69bb702012-10-02 00:25:57 +00002007 OpOS.indent(27);
David Blaikiec50f9862014-06-08 16:18:35 +00002008 OpOS << "const OperandVector &Operands) {\n"
Chad Rosier359956d2012-08-31 00:03:31 +00002009 << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
Chad Rosier22685872012-10-01 23:45:51 +00002010 << " unsigned NumMCOperands = 0;\n"
Craig Topperb198f5c2012-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 Rosier62316fa2012-08-30 17:59:25 +00002013 << " switch (*p) {\n"
2014 << " default: llvm_unreachable(\"invalid conversion entry!\");\n"
2015 << " case CVT_Reg:\n"
Chad Rosier6e006d32012-10-12 22:53:36 +00002016 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
Chad Rosier1c99a7f2013-01-15 23:07:53 +00002017 << " Operands[*(p + 1)]->setConstraint(\"r\");\n"
Chad Rosier6e006d32012-10-12 22:53:36 +00002018 << " ++NumMCOperands;\n"
2019 << " break;\n"
Chad Rosier62316fa2012-08-30 17:59:25 +00002020 << " case CVT_Tied:\n"
Chad Rosier22685872012-10-01 23:45:51 +00002021 << " ++NumMCOperands;\n"
Chad Rosier62316fa2012-08-30 17:59:25 +00002022 << " break;\n";
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002023
2024 // Pre-populate the operand conversion kinds with the standard always
2025 // available entries.
Justin Lebar2c937a12016-10-21 21:45:01 +00002026 OperandConversionKinds.insert(CachedHashString("CVT_Done"));
2027 OperandConversionKinds.insert(CachedHashString("CVT_Reg"));
2028 OperandConversionKinds.insert(CachedHashString("CVT_Tied"));
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002029 enum { CVT_Done, CVT_Reg, CVT_Tied };
2030
Sander de Smalencb6c95b2018-02-04 16:24:17 +00002031 // Map of e.g. <0, 2, 3> -> "Tie_0_2_3" enum label.
Sander de Smalenb0c87382018-06-18 13:39:29 +00002032 std::map<std::tuple<uint8_t, uint8_t, uint8_t>, std::string>
Sander de Smalencb6c95b2018-02-04 16:24:17 +00002033 TiedOperandsEnumMap;
2034
Craig Topper44ebfb72014-11-28 03:53:02 +00002035 for (auto &II : Infos) {
Daniel Dunbarcf120672011-02-04 17:12:15 +00002036 // Check if we have a custom match function.
Craig Topper2a129872017-05-31 21:12:46 +00002037 StringRef AsmMatchConverter =
2038 II->getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
Tom Stellard75775932015-05-26 15:55:50 +00002039 if (!AsmMatchConverter.empty() && II->UseInstAsmMatchConverter) {
Craig Topper2a129872017-05-31 21:12:46 +00002040 std::string Signature = ("ConvertCustom_" + AsmMatchConverter).str();
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00002041 II->ConversionFnKind = Signature;
Daniel Dunbarcf120672011-02-04 17:12:15 +00002042
2043 // Check if we have already generated this signature.
Justin Lebar2c937a12016-10-21 21:45:01 +00002044 if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
Daniel Dunbarcf120672011-02-04 17:12:15 +00002045 continue;
2046
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002047 // Remember this converter for the kind enum.
2048 unsigned KindID = OperandConversionKinds.size();
Justin Lebar2c937a12016-10-21 21:45:01 +00002049 OperandConversionKinds.insert(
2050 CachedHashString("CVT_" + getEnumNameForToken(AsmMatchConverter)));
Daniel Dunbarcf120672011-02-04 17:12:15 +00002051
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002052 // Add the converter row for this instruction.
Benjamin Kramer9589ff82015-05-29 19:43:39 +00002053 ConversionTable.emplace_back();
Jim Grosbachc8f267f2012-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 Northover12da5052013-01-10 16:47:31 +00002058 CvtOS << " case CVT_"
2059 << getEnumNameForToken(AsmMatchConverter) << ":\n"
Chad Rosier756d2cc2012-08-31 22:12:31 +00002060 << " " << AsmMatchConverter << "(Inst, Operands);\n"
Chad Rosier359956d2012-08-31 00:03:31 +00002061 << " break;\n";
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002062
Chad Rosier62316fa2012-08-30 17:59:25 +00002063 // FIXME: Handle the operand number lookup for custom match functions.
Daniel Dunbarcf120672011-02-04 17:12:15 +00002064 continue;
2065 }
2066
Daniel Dunbar20927f22009-08-07 08:26:05 +00002067 // Build the conversion function signature.
2068 std::string Signature = "Convert";
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002069
2070 std::vector<uint8_t> ConversionRow;
Bob Wilson828295b2011-01-26 21:26:19 +00002071
Chris Lattnerdda855d2010-11-02 21:49:44 +00002072 // Compute the convert enum and the case body.
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00002073 MaxRowLength = std::max(MaxRowLength, II->ResOperands.size()*2 + 1 );
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002074
Duncan P. N. Exon Smithb60bcfd2014-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 Grosbacha7c78222010-10-29 22:13:48 +00002077
Chris Lattner1d13bda2010-11-04 00:43:46 +00002078 // Generate code to populate each result operand.
2079 switch (OpInfo.Kind) {
Chris Lattner1d13bda2010-11-04 00:43:46 +00002080 case MatchableInfo::ResOperand::RenderAsmOperand: {
2081 // This comes from something we parsed.
Craig Topperf78e3332014-11-25 20:11:31 +00002082 const MatchableInfo::AsmOperand &Op =
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00002083 II->AsmOperands[OpInfo.AsmOperandNum];
Bob Wilson828295b2011-01-26 21:26:19 +00002084
Chris Lattner9b0d4bf2010-11-02 22:55:03 +00002085 // Registers are always converted the same, don't duplicate the
2086 // conversion function based on them.
Chris Lattner9b0d4bf2010-11-02 22:55:03 +00002087 Signature += "__";
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002088 std::string Class;
2089 Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName;
2090 Signature += Class;
Bob Wilsona49c7df2011-01-26 19:44:55 +00002091 Signature += utostr(OpInfo.MINumOperands);
Chris Lattner1d13bda2010-11-04 00:43:46 +00002092 Signature += "_" + itostr(OpInfo.AsmOperandNum);
Bob Wilson828295b2011-01-26 21:26:19 +00002093
Jim Grosbachc8f267f2012-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 Koltonf117ec12016-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 Northover12da5052013-01-10 16:47:31 +00002103 Name = getEnumNameForToken(Name);
Jim Grosbachc8f267f2012-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 Topper5ef13492015-12-31 08:18:23 +00002111 ConversionRow.push_back(OpInfo.AsmOperandNum + HasMnemonicFirst);
Jim Grosbachc8f267f2012-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 Koltonf117ec12016-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 Koltonf117ec12016-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 Rosier62316fa2012-08-30 17:59:25 +00002138
2139 // Add a handler for the operand number lookup.
2140 OpOS << " case " << Name << ":\n"
Chad Rosier1c99a7f2013-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 Rosier62316fa2012-08-30 17:59:25 +00002148 << " break;\n";
Chris Lattner1d13bda2010-11-04 00:43:46 +00002149 break;
Daniel Dunbaraf616812010-02-10 08:15:48 +00002150 }
Chris Lattner1d13bda2010-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 Weigandd9990622013-04-27 18:48:23 +00002154 assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
Sander de Smalenb0c87382018-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 Smalencb6c95b2018-02-04 16:24:17 +00002162 auto TiedTupleName = std::string("Tie") + utostr(TiedOp) + '_' +
2163 utostr(SrcOp1) + '_' + utostr(SrcOp2);
2164 Signature += "__" + TiedTupleName;
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002165 ConversionRow.push_back(CVT_Tied);
2166 ConversionRow.push_back(TiedOp);
Sander de Smalencb6c95b2018-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 Lattner1d13bda2010-11-04 00:43:46 +00002173 break;
2174 }
Chris Lattner98c870f2010-11-06 19:25:43 +00002175 case MatchableInfo::ResOperand::ImmOperand: {
2176 int64_t Val = OpInfo.ImmVal;
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002177 std::string Ty = "imm_" + itostr(Val);
Hal Finkel5a40bef2015-01-15 01:33:00 +00002178 Ty = getEnumNameForToken(Ty);
Jim Grosbachc8f267f2012-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 Grosbachdb703aa2015-05-13 18:37:00 +00002193 << " Inst.addOperand(MCOperand::createImm(" << Val << "));\n"
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002194 << " break;\n";
2195
Chad Rosier62316fa2012-08-30 17:59:25 +00002196 OpOS << " case " << Name << ":\n"
Chad Rosier6e006d32012-10-12 22:53:36 +00002197 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2198 << " Operands[*(p + 1)]->setConstraint(\"\");\n"
Chad Rosier22685872012-10-01 23:45:51 +00002199 << " ++NumMCOperands;\n"
Chad Rosier62316fa2012-08-30 17:59:25 +00002200 << " break;\n";
Chris Lattner98c870f2010-11-06 19:25:43 +00002201 break;
2202 }
Chris Lattner90fd7972010-11-06 19:57:21 +00002203 case MatchableInfo::ResOperand::RegOperand: {
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002204 std::string Reg, Name;
Craig Topper095734c2014-04-15 07:20:03 +00002205 if (!OpInfo.Register) {
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002206 Name = "reg0";
2207 Reg = "0";
Bob Wilsondc1a2bd2011-01-14 22:58:09 +00002208 } else {
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002209 Reg = getQualifiedName(OpInfo.Register);
Matthias Braun0c517c82016-12-04 05:48:16 +00002210 Name = "reg" + OpInfo.Register->getName().str();
Bob Wilsondc1a2bd2011-01-14 22:58:09 +00002211 }
Jim Grosbachc8f267f2012-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 Grosbachdb703aa2015-05-13 18:37:00 +00002224 << " Inst.addOperand(MCOperand::createReg(" << Reg << "));\n"
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002225 << " break;\n";
Chad Rosier62316fa2012-08-30 17:59:25 +00002226
2227 OpOS << " case " << Name << ":\n"
Chad Rosier6e006d32012-10-12 22:53:36 +00002228 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2229 << " Operands[*(p + 1)]->setConstraint(\"m\");\n"
Chad Rosier22685872012-10-01 23:45:51 +00002230 << " ++NumMCOperands;\n"
Chad Rosier62316fa2012-08-30 17:59:25 +00002231 << " break;\n";
Bob Wilson828295b2011-01-26 21:26:19 +00002232 }
Chris Lattner1d13bda2010-11-04 00:43:46 +00002233 }
Daniel Dunbar20927f22009-08-07 08:26:05 +00002234 }
Bob Wilson828295b2011-01-26 21:26:19 +00002235
Jim Grosbachc8f267f2012-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 Smithb60bcfd2014-11-28 23:00:22 +00002240 II->ConversionFnKind = Signature;
Daniel Dunbar20927f22009-08-07 08:26:05 +00002241
Jim Grosbachc8f267f2012-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 Lebar2c937a12016-10-21 21:45:01 +00002244 if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
Daniel Dunbar20927f22009-08-07 08:26:05 +00002245 continue;
2246
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002247 // Add the row to the table.
Craig Topperc18d9282015-08-16 21:27:08 +00002248 ConversionTable.push_back(std::move(ConversionRow));
Daniel Dunbar20927f22009-08-07 08:26:05 +00002249 }
Daniel Dunbarb7479c02009-08-08 05:24:34 +00002250
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002251 // Finish up the converter driver function.
Chad Rosierad2d3e62012-09-03 17:39:57 +00002252 CvtOS << " }\n }\n}\n\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00002253
Chad Rosier62316fa2012-08-30 17:59:25 +00002254 // Finish up the operand number lookup function.
Chad Rosier22685872012-10-01 23:45:51 +00002255 OpOS << " }\n }\n}\n\n";
Chad Rosier62316fa2012-08-30 17:59:25 +00002256
Sander de Smalencb6c95b2018-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 Smalenb0c87382018-06-18 13:39:29 +00002261 assert(TiedOperandsEnumMap.size() <= 254 &&
Sander de Smalencb6c95b2018-02-04 16:24:17 +00002262 "Too many tied-operand combinations to reference with "
Sander de Smalenb0c87382018-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 Smalencb6c95b2018-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 Topper46cd4ae2018-06-18 16:17:46 +00002272 OS << "static const uint8_t TiedAsmOperandTable[][3] = {\n";
Sander de Smalencb6c95b2018-02-04 16:24:17 +00002273 for (auto &KV : TiedOperandsEnumMap) {
Sander de Smalenb0c87382018-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 Smalencb6c95b2018-02-04 16:24:17 +00002278 }
2279 OS << "};\n\n";
2280 } else
Craig Topper46cd4ae2018-06-18 16:17:46 +00002281 OS << "static const uint8_t TiedAsmOperandTable[][3] = "
Sander de Smalenb0c87382018-06-18 13:39:29 +00002282 "{ /* empty */ {0, 0, 0} };\n\n";
Sander de Smalencb6c95b2018-02-04 16:24:17 +00002283
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002284 OS << "namespace {\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00002285
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002286 // Output the operand conversion kind enum.
2287 OS << "enum OperatorConversionKind {\n";
Justin Lebar2c937a12016-10-21 21:45:01 +00002288 for (const auto &Converter : OperandConversionKinds)
Craig Topper4d0e4052016-01-03 07:33:30 +00002289 OS << " " << Converter << ",\n";
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002290 OS << " CVT_NUM_CONVERTERS\n";
Daniel Dunbarb7479c02009-08-08 05:24:34 +00002291 OS << "};\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00002292
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002293 // Output the instruction conversion kind enum.
2294 OS << "enum InstructionConversionKind {\n";
Justin Lebar2c937a12016-10-21 21:45:01 +00002295 for (const auto &Signature : InstructionConversionKinds)
Craig Topper28d23b82015-08-16 21:27:10 +00002296 OS << " " << Signature << ",\n";
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002297 OS << " CVT_NUM_SIGNATURES\n";
2298 OS << "};\n\n";
2299
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002300 OS << "} // end anonymous namespace\n\n";
2301
2302 // Output the conversion table.
Craig Topperb198f5c2012-09-18 01:41:49 +00002303 OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES]["
Jim Grosbachc8f267f2012-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 Smalencb6c95b2018-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 Smalenb0c87382018-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 Smalencb6c95b2018-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 Grosbachc8f267f2012-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 Dunbarb7479c02009-08-08 05:24:34 +00002336 OS << CvtOS.str();
Jim Grosbachc8f267f2012-08-22 01:06:23 +00002337
Chad Rosier62316fa2012-08-30 17:59:25 +00002338 // Spit out the operand number lookup function.
2339 OS << OpOS.str();
Daniel Dunbara027d222009-07-31 02:32:59 +00002340}
2341
Jim Grosbach8caecde2012-04-19 17:52:32 +00002342/// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
2343static void emitMatchClassEnumeration(CodeGenTarget &Target,
David Blaikie841db2c2014-11-28 20:35:57 +00002344 std::forward_list<ClassInfo> &Infos,
2345 raw_ostream &OS) {
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002346 OS << "namespace {\n\n";
2347
2348 OS << "/// MatchClassKind - The kinds of classes which participate in\n"
2349 << "/// instruction matching.\n";
2350 OS << "enum MatchClassKind {\n";
2351 OS << " InvalidMatchClass = 0,\n";
Tom Stellard25257d82016-02-05 19:59:33 +00002352 OS << " OptionalMatchClass = 1,\n";
Oliver Stannard0e4cc592017-10-10 11:00:40 +00002353 ClassInfo::ClassInfoKind LastKind = ClassInfo::Token;
2354 StringRef LastName = "OptionalMatchClass";
Craig Topper44ebfb72014-11-28 03:53:02 +00002355 for (const auto &CI : Infos) {
Oliver Stannard0e4cc592017-10-10 11:00:40 +00002356 if (LastKind == ClassInfo::Token && CI.Kind != ClassInfo::Token) {
2357 OS << " MCK_LAST_TOKEN = " << LastName << ",\n";
2358 } else if (LastKind < ClassInfo::UserClass0 &&
2359 CI.Kind >= ClassInfo::UserClass0) {
2360 OS << " MCK_LAST_REGISTER = " << LastName << ",\n";
2361 }
2362 LastKind = (ClassInfo::ClassInfoKind)CI.Kind;
2363 LastName = CI.Name;
2364
David Blaikie841db2c2014-11-28 20:35:57 +00002365 OS << " " << CI.Name << ", // ";
2366 if (CI.Kind == ClassInfo::Token) {
2367 OS << "'" << CI.ValueName << "'\n";
2368 } else if (CI.isRegisterClass()) {
2369 if (!CI.ValueName.empty())
2370 OS << "register class '" << CI.ValueName << "'\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002371 else
2372 OS << "derived register class\n";
2373 } else {
David Blaikie841db2c2014-11-28 20:35:57 +00002374 OS << "user defined class '" << CI.ValueName << "'\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002375 }
2376 }
2377 OS << " NumMatchClassKinds\n";
2378 OS << "};\n\n";
2379
2380 OS << "}\n\n";
2381}
2382
Oliver Stannardfe3c8f92017-10-03 14:34:57 +00002383/// emitMatchClassDiagStrings - Emit a function to get the diagnostic text to be
2384/// used when an assembly operand does not match the expected operand class.
2385static void emitOperandMatchErrorDiagStrings(AsmMatcherInfo &Info, raw_ostream &OS) {
2386 // If the target does not use DiagnosticString for any operands, don't emit
2387 // an unused function.
2388 if (std::all_of(
2389 Info.Classes.begin(), Info.Classes.end(),
2390 [](const ClassInfo &CI) { return CI.DiagnosticString.empty(); }))
2391 return;
2392
2393 OS << "static const char *getMatchKindDiag(" << Info.Target.getName()
2394 << "AsmParser::" << Info.Target.getName()
2395 << "MatchResultTy MatchResult) {\n";
2396 OS << " switch (MatchResult) {\n";
2397
2398 for (const auto &CI: Info.Classes) {
2399 if (!CI.DiagnosticString.empty()) {
2400 assert(!CI.DiagnosticType.empty() &&
2401 "DiagnosticString set without DiagnosticType");
2402 OS << " case " << Info.Target.getName()
2403 << "AsmParser::Match_" << CI.DiagnosticType << ":\n";
2404 OS << " return \"" << CI.DiagnosticString << "\";\n";
2405 }
2406 }
2407
2408 OS << " default:\n";
2409 OS << " return nullptr;\n";
2410
2411 OS << " }\n";
2412 OS << "}\n\n";
2413}
2414
Oliver Stannard0e4cc592017-10-10 11:00:40 +00002415static void emitRegisterMatchErrorFunc(AsmMatcherInfo &Info, raw_ostream &OS) {
2416 OS << "static unsigned getDiagKindFromRegisterClass(MatchClassKind "
2417 "RegisterClass) {\n";
Fangrui Song7d3ea702018-10-19 06:12:02 +00002418 if (none_of(Info.Classes, [](const ClassInfo &CI) {
2419 return CI.isRegisterClass() && !CI.DiagnosticType.empty();
2420 })) {
Oliver Stannardb5e990c2017-10-12 09:28:23 +00002421 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2422 } else {
2423 OS << " switch (RegisterClass) {\n";
2424 for (const auto &CI: Info.Classes) {
2425 if (CI.isRegisterClass() && !CI.DiagnosticType.empty()) {
2426 OS << " case " << CI.Name << ":\n";
2427 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
2428 << CI.DiagnosticType << ";\n";
2429 }
Oliver Stannard0e4cc592017-10-10 11:00:40 +00002430 }
Oliver Stannardb5e990c2017-10-12 09:28:23 +00002431
2432 OS << " default:\n";
2433 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2434
2435 OS << " }\n";
Oliver Stannard0e4cc592017-10-10 11:00:40 +00002436 }
Oliver Stannard0e4cc592017-10-10 11:00:40 +00002437 OS << "}\n\n";
2438}
2439
Jim Grosbach8caecde2012-04-19 17:52:32 +00002440/// emitValidateOperandClass - Emit the function to validate an operand class.
2441static void emitValidateOperandClass(AsmMatcherInfo &Info,
Jim Grosbachb9db0c52011-02-10 00:08:28 +00002442 raw_ostream &OS) {
David Blaikiec50f9862014-06-08 16:18:35 +00002443 OS << "static unsigned validateOperandClass(MCParsedAsmOperand &GOp, "
Jim Grosbachb9db0c52011-02-10 00:08:28 +00002444 << "MatchClassKind Kind) {\n";
David Blaikiec50f9862014-06-08 16:18:35 +00002445 OS << " " << Info.Target.getName() << "Operand &Operand = ("
2446 << Info.Target.getName() << "Operand&)GOp;\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00002447
Kevin Enderby89381832011-07-15 18:30:43 +00002448 // The InvalidMatchClass is not to match any operand.
2449 OS << " if (Kind == InvalidMatchClass)\n";
Jim Grosbach4dbfdfb2012-06-22 23:56:44 +00002450 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n\n";
Kevin Enderby89381832011-07-15 18:30:43 +00002451
Jim Grosbachb9db0c52011-02-10 00:08:28 +00002452 // Check for Token operands first.
Jim Grosbach4dbfdfb2012-06-22 23:56:44 +00002453 // FIXME: Use a more specific diagnostic type.
Oliver Stannard0e4cc592017-10-10 11:00:40 +00002454 OS << " if (Operand.isToken() && Kind <= MCK_LAST_TOKEN)\n";
Jim Grosbach4dbfdfb2012-06-22 23:56:44 +00002455 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
2456 << " MCTargetAsmParser::Match_Success :\n"
2457 << " MCTargetAsmParser::Match_InvalidOperand;\n\n";
Daniel Dunbarea6408f2009-08-11 02:59:53 +00002458
Jim Grosbachb9db0c52011-02-10 00:08:28 +00002459 // Check the user classes. We don't care what order since we're only
2460 // actually matching against one of them.
Valery Pykhtin89372a52016-04-05 16:18:16 +00002461 OS << " switch (Kind) {\n"
2462 " default: break;\n";
Craig Topper44ebfb72014-11-28 03:53:02 +00002463 for (const auto &CI : Info.Classes) {
David Blaikie841db2c2014-11-28 20:35:57 +00002464 if (!CI.isUserClass())
Daniel Dunbarea6408f2009-08-11 02:59:53 +00002465 continue;
Bob Wilson828295b2011-01-26 21:26:19 +00002466
David Blaikie841db2c2014-11-28 20:35:57 +00002467 OS << " // '" << CI.ClassName << "' class\n";
Sander de Smalenbe4cc032018-04-26 09:24:45 +00002468 OS << " case " << CI.Name << ": {\n";
2469 OS << " DiagnosticPredicate DP(Operand." << CI.PredicateMethod
2470 << "());\n";
2471 OS << " if (DP.isMatch())\n";
Jim Grosbach4dbfdfb2012-06-22 23:56:44 +00002472 OS << " return MCTargetAsmParser::Match_Success;\n";
Sander de Smalenbe4cc032018-04-26 09:24:45 +00002473 if (!CI.DiagnosticType.empty()) {
2474 OS << " if (DP.isNearMatch())\n";
2475 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
David Blaikie841db2c2014-11-28 20:35:57 +00002476 << CI.DiagnosticType << ";\n";
Sander de Smalenbe4cc032018-04-26 09:24:45 +00002477 OS << " break;\n";
2478 }
Valery Pykhtin89372a52016-04-05 16:18:16 +00002479 else
2480 OS << " break;\n";
Sander de Smalenbe4cc032018-04-26 09:24:45 +00002481 OS << " }\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002482 }
Valery Pykhtin89372a52016-04-05 16:18:16 +00002483 OS << " } // end switch (Kind)\n\n";
Bob Wilson828295b2011-01-26 21:26:19 +00002484
Owen Andersonb885dc82012-07-16 23:20:09 +00002485 // Check for register operands, including sub-classes.
2486 OS << " if (Operand.isReg()) {\n";
2487 OS << " MatchClassKind OpKind;\n";
2488 OS << " switch (Operand.getReg()) {\n";
2489 OS << " default: OpKind = InvalidMatchClass; break;\n";
Craig Topperf78e3332014-11-25 20:11:31 +00002490 for (const auto &RC : Info.RegisterClasses)
Craig Topper3e595d02017-07-07 05:19:25 +00002491 OS << " case " << RC.first->getValueAsString("Namespace") << "::"
Craig Topperf78e3332014-11-25 20:11:31 +00002492 << RC.first->getName() << ": OpKind = " << RC.second->Name
Owen Andersonb885dc82012-07-16 23:20:09 +00002493 << "; break;\n";
2494 OS << " }\n";
2495 OS << " return isSubclass(OpKind, Kind) ? "
Oliver Stannard0e4cc592017-10-10 11:00:40 +00002496 << "(unsigned)MCTargetAsmParser::Match_Success :\n "
2497 << " getDiagKindFromRegisterClass(Kind);\n }\n\n";
2498
2499 // Expected operand is a register, but actual is not.
2500 OS << " if (Kind > MCK_LAST_TOKEN && Kind <= MCK_LAST_REGISTER)\n";
2501 OS << " return getDiagKindFromRegisterClass(Kind);\n\n";
Owen Andersonb885dc82012-07-16 23:20:09 +00002502
Jim Grosbach4dbfdfb2012-06-22 23:56:44 +00002503 // Generic fallthrough match failure case for operands that don't have
2504 // specialized diagnostic types.
2505 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00002506 OS << "}\n\n";
2507}
2508
Jim Grosbach8caecde2012-04-19 17:52:32 +00002509/// emitIsSubclass - Emit the subclass predicate function.
2510static void emitIsSubclass(CodeGenTarget &Target,
David Blaikie841db2c2014-11-28 20:35:57 +00002511 std::forward_list<ClassInfo> &Infos,
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00002512 raw_ostream &OS) {
Dmitri Gribenko4e0ae442012-09-15 20:22:05 +00002513 OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n";
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00002514 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00002515 OS << " if (A == B)\n";
2516 OS << " return true;\n\n";
2517
Craig Toppere18e2bb2015-12-30 06:00:22 +00002518 bool EmittedSwitch = false;
Craig Topper44ebfb72014-11-28 03:53:02 +00002519 for (const auto &A : Infos) {
Jim Grosbacha66512e2011-12-06 23:43:54 +00002520 std::vector<StringRef> SuperClasses;
Tom Stellard25257d82016-02-05 19:59:33 +00002521 if (A.IsOptional)
2522 SuperClasses.push_back("OptionalMatchClass");
Craig Topper44ebfb72014-11-28 03:53:02 +00002523 for (const auto &B : Infos) {
David Blaikie841db2c2014-11-28 20:35:57 +00002524 if (&A != &B && A.isSubsetOf(B))
2525 SuperClasses.push_back(B.Name);
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00002526 }
Jim Grosbacha66512e2011-12-06 23:43:54 +00002527
2528 if (SuperClasses.empty())
2529 continue;
2530
Craig Toppere18e2bb2015-12-30 06:00:22 +00002531 // If this is the first SuperClass, emit the switch header.
2532 if (!EmittedSwitch) {
Craig Topperdb4180c2015-12-30 06:00:24 +00002533 OS << " switch (A) {\n";
Craig Toppere18e2bb2015-12-30 06:00:22 +00002534 OS << " default:\n";
2535 OS << " return false;\n";
2536 EmittedSwitch = true;
2537 }
2538
2539 OS << "\n case " << A.Name << ":\n";
Jim Grosbacha66512e2011-12-06 23:43:54 +00002540
2541 if (SuperClasses.size() == 1) {
Craig Topperdb4180c2015-12-30 06:00:24 +00002542 OS << " return B == " << SuperClasses.back() << ";\n";
Jim Grosbacha66512e2011-12-06 23:43:54 +00002543 continue;
2544 }
2545
Aaron Ballman54911a52013-07-15 16:53:32 +00002546 if (!SuperClasses.empty()) {
Craig Toppere18e2bb2015-12-30 06:00:22 +00002547 OS << " switch (B) {\n";
2548 OS << " default: return false;\n";
Craig Topper65438a72015-12-30 06:00:20 +00002549 for (StringRef SC : SuperClasses)
Craig Toppere18e2bb2015-12-30 06:00:22 +00002550 OS << " case " << SC << ": return true;\n";
2551 OS << " }\n";
Aaron Ballman54911a52013-07-15 16:53:32 +00002552 } else {
2553 // No case statement to emit
Craig Toppere18e2bb2015-12-30 06:00:22 +00002554 OS << " return false;\n";
Aaron Ballman54911a52013-07-15 16:53:32 +00002555 }
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00002556 }
Aaron Ballman54911a52013-07-15 16:53:32 +00002557
Craig Toppere18e2bb2015-12-30 06:00:22 +00002558 // If there were case statements emitted into the string stream write the
2559 // default.
Craig Topper8dd99ee2016-01-03 07:33:34 +00002560 if (EmittedSwitch)
2561 OS << " }\n";
2562 else
Aaron Ballman54911a52013-07-15 16:53:32 +00002563 OS << " return false;\n";
2564
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00002565 OS << "}\n\n";
2566}
2567
Jim Grosbach8caecde2012-04-19 17:52:32 +00002568/// emitMatchTokenString - Emit the function to match a token string to the
Daniel Dunbar245f0582009-08-08 21:22:41 +00002569/// appropriate match class value.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002570static void emitMatchTokenString(CodeGenTarget &Target,
David Blaikie841db2c2014-11-28 20:35:57 +00002571 std::forward_list<ClassInfo> &Infos,
Daniel Dunbar245f0582009-08-08 21:22:41 +00002572 raw_ostream &OS) {
2573 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00002574 std::vector<StringMatcher::StringPair> Matches;
Craig Topper44ebfb72014-11-28 03:53:02 +00002575 for (const auto &CI : Infos) {
David Blaikie841db2c2014-11-28 20:35:57 +00002576 if (CI.Kind == ClassInfo::Token)
Benjamin Kramer9589ff82015-05-29 19:43:39 +00002577 Matches.emplace_back(CI.ValueName, "return " + CI.Name + ";");
Daniel Dunbar245f0582009-08-08 21:22:41 +00002578 }
2579
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00002580 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00002581
Chris Lattner5845e5c2010-09-06 02:01:51 +00002582 StringMatcher("Name", Matches, OS).Emit();
Daniel Dunbar245f0582009-08-08 21:22:41 +00002583
2584 OS << " return InvalidMatchClass;\n";
2585 OS << "}\n\n";
2586}
Chris Lattner70add882009-08-08 20:02:57 +00002587
Jim Grosbach8caecde2012-04-19 17:52:32 +00002588/// emitMatchRegisterName - Emit the function to match a string to the target
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00002589/// specific register enum.
Jim Grosbach8caecde2012-04-19 17:52:32 +00002590static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00002591 raw_ostream &OS) {
Daniel Dunbar245f0582009-08-08 21:22:41 +00002592 // Construct the match list.
Chris Lattner5845e5c2010-09-06 02:01:51 +00002593 std::vector<StringMatcher::StringPair> Matches;
David Blaikiee7227132014-11-29 18:13:39 +00002594 const auto &Regs = Target.getRegBank().getRegisters();
2595 for (const CodeGenRegister &Reg : Regs) {
2596 if (Reg.TheDef->getValueAsString("AsmName").empty())
Daniel Dunbar22be5222009-07-17 18:51:11 +00002597 continue;
2598
Benjamin Kramer9589ff82015-05-29 19:43:39 +00002599 Matches.emplace_back(Reg.TheDef->getValueAsString("AsmName"),
2600 "return " + utostr(Reg.EnumValue) + ";");
Daniel Dunbar22be5222009-07-17 18:51:11 +00002601 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00002602
Chris Lattnerb8d6e982010-02-09 00:34:28 +00002603 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
Daniel Dunbar245f0582009-08-08 21:22:41 +00002604
Alex Bradbury2bd79102017-12-07 09:51:55 +00002605 bool IgnoreDuplicates =
2606 AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
2607 StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
Jim Grosbacha7c78222010-10-29 22:13:48 +00002608
Daniel Dunbar245f0582009-08-08 21:22:41 +00002609 OS << " return 0;\n";
Daniel Dunbar20927f22009-08-07 08:26:05 +00002610 OS << "}\n\n";
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00002611}
Daniel Dunbara027d222009-07-31 02:32:59 +00002612
Dylan McKayf4afd082016-02-03 10:30:16 +00002613/// Emit the function to match a string to the target
2614/// specific register enum.
2615static void emitMatchRegisterAltName(CodeGenTarget &Target, Record *AsmParser,
2616 raw_ostream &OS) {
2617 // Construct the match list.
2618 std::vector<StringMatcher::StringPair> Matches;
2619 const auto &Regs = Target.getRegBank().getRegisters();
2620 for (const CodeGenRegister &Reg : Regs) {
2621
2622 auto AltNames = Reg.TheDef->getValueAsListOfStrings("AltNames");
2623
2624 for (auto AltName : AltNames) {
2625 AltName = StringRef(AltName).trim();
2626
2627 // don't handle empty alternative names
2628 if (AltName.empty())
2629 continue;
2630
2631 Matches.emplace_back(AltName,
2632 "return " + utostr(Reg.EnumValue) + ";");
2633 }
2634 }
2635
2636 OS << "static unsigned MatchRegisterAltName(StringRef Name) {\n";
2637
Alex Bradbury2bd79102017-12-07 09:51:55 +00002638 bool IgnoreDuplicates =
2639 AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
2640 StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
Dylan McKayf4afd082016-02-03 10:30:16 +00002641
2642 OS << " return 0;\n";
2643 OS << "}\n\n";
2644}
2645
Jim Grosbach4dbfdfb2012-06-22 23:56:44 +00002646/// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
2647static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) {
2648 // Get the set of diagnostic types from all of the operand classes.
2649 std::set<StringRef> Types;
Craig Topper4d0e4052016-01-03 07:33:30 +00002650 for (const auto &OpClassEntry : Info.AsmOperandClasses) {
2651 if (!OpClassEntry.second->DiagnosticType.empty())
2652 Types.insert(OpClassEntry.second->DiagnosticType);
Jim Grosbach4dbfdfb2012-06-22 23:56:44 +00002653 }
Oliver Stannard0e4cc592017-10-10 11:00:40 +00002654 for (const auto &OpClassEntry : Info.RegisterClassClasses) {
2655 if (!OpClassEntry.second->DiagnosticType.empty())
2656 Types.insert(OpClassEntry.second->DiagnosticType);
2657 }
Jim Grosbach4dbfdfb2012-06-22 23:56:44 +00002658
2659 if (Types.empty()) return;
2660
2661 // Now emit the enum entries.
Craig Topper4d0e4052016-01-03 07:33:30 +00002662 for (StringRef Type : Types)
2663 OS << " Match_" << Type << ",\n";
Jim Grosbach4dbfdfb2012-06-22 23:56:44 +00002664 OS << " END_OPERAND_DIAGNOSTIC_TYPES\n";
2665}
2666
Jim Grosbach14ce6fa2012-04-24 22:40:08 +00002667/// emitGetSubtargetFeatureName - Emit the helper function to get the
2668/// user-level name for a subtarget feature.
2669static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
2670 OS << "// User-level names for subtarget features that participate in\n"
2671 << "// instruction matching.\n"
Ranjeet Singhb0f78712015-06-30 12:32:53 +00002672 << "static const char *getSubtargetFeatureName(uint64_t Val) {\n";
Aaron Ballman54911a52013-07-15 16:53:32 +00002673 if (!Info.SubtargetFeatures.empty()) {
Ranjeet Singhb0f78712015-06-30 12:32:53 +00002674 OS << " switch(Val) {\n";
Craig Topper99a21702014-11-28 03:53:00 +00002675 for (const auto &SF : Info.SubtargetFeatures) {
David Blaikie5f951402014-11-28 22:15:06 +00002676 const SubtargetFeatureInfo &SFI = SF.second;
Aaron Ballman54911a52013-07-15 16:53:32 +00002677 // FIXME: Totally just a placeholder name to get the algorithm working.
2678 OS << " case " << SFI.getEnumName() << ": return \""
2679 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
2680 }
2681 OS << " default: return \"(unknown)\";\n";
2682 OS << " }\n";
2683 } else {
2684 // Nothing to emit, so skip the switch
2685 OS << " return \"(unknown)\";\n";
Jim Grosbach14ce6fa2012-04-24 22:40:08 +00002686 }
Aaron Ballman54911a52013-07-15 16:53:32 +00002687 OS << "}\n\n";
Jim Grosbach14ce6fa2012-04-24 22:40:08 +00002688}
2689
Chris Lattner6fa152c2010-10-30 20:15:02 +00002690static std::string GetAliasRequiredFeatures(Record *R,
2691 const AsmMatcherInfo &Info) {
Chris Lattner693173f2010-10-30 19:23:13 +00002692 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
Chris Lattner693173f2010-10-30 19:23:13 +00002693 std::string Result;
2694 unsigned NumFeatures = 0;
2695 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
David Blaikie5f951402014-11-28 22:15:06 +00002696 const SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
Bob Wilson828295b2011-01-26 21:26:19 +00002697
Craig Topper095734c2014-04-15 07:20:03 +00002698 if (!F)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002699 PrintFatalError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
Chris Lattner4a74ee72010-11-01 02:09:21 +00002700 "' is not marked as an AssemblerPredicate!");
Bob Wilson828295b2011-01-26 21:26:19 +00002701
Chris Lattner4a74ee72010-11-01 02:09:21 +00002702 if (NumFeatures)
2703 Result += '|';
Bob Wilson828295b2011-01-26 21:26:19 +00002704
Chris Lattner4a74ee72010-11-01 02:09:21 +00002705 Result += F->getEnumName();
2706 ++NumFeatures;
Chris Lattner693173f2010-10-30 19:23:13 +00002707 }
Bob Wilson828295b2011-01-26 21:26:19 +00002708
Chris Lattner693173f2010-10-30 19:23:13 +00002709 if (NumFeatures > 1)
2710 Result = '(' + Result + ')';
2711 return Result;
2712}
2713
Chad Rosier88eb89b2013-04-18 22:35:36 +00002714static void emitMnemonicAliasVariant(raw_ostream &OS,const AsmMatcherInfo &Info,
2715 std::vector<Record*> &Aliases,
2716 unsigned Indent = 0,
2717 StringRef AsmParserVariantName = StringRef()){
Chris Lattner4fd32c62010-10-30 18:56:12 +00002718 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
2719 // iteration order of the map is stable.
2720 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
Bob Wilson828295b2011-01-26 21:26:19 +00002721
Craig Topper4d0e4052016-01-03 07:33:30 +00002722 for (Record *R : Aliases) {
Chad Rosier88eb89b2013-04-18 22:35:36 +00002723 // FIXME: Allow AssemblerVariantName to be a comma separated list.
Craig Topper2a129872017-05-31 21:12:46 +00002724 StringRef AsmVariantName = R->getValueAsString("AsmVariantName");
Chad Rosier88eb89b2013-04-18 22:35:36 +00002725 if (AsmVariantName != AsmParserVariantName)
2726 continue;
Chris Lattner4fd32c62010-10-30 18:56:12 +00002727 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
Chris Lattner674c1dc2010-10-30 17:36:36 +00002728 }
Chad Rosier88eb89b2013-04-18 22:35:36 +00002729 if (AliasesFromMnemonic.empty())
2730 return;
Vladimir Medic92731512013-07-16 09:22:38 +00002731
Chris Lattner4fd32c62010-10-30 18:56:12 +00002732 // Process each alias a "from" mnemonic at a time, building the code executed
2733 // by the string remapper.
2734 std::vector<StringMatcher::StringPair> Cases;
Craig Topper4d0e4052016-01-03 07:33:30 +00002735 for (const auto &AliasEntry : AliasesFromMnemonic) {
2736 const std::vector<Record*> &ToVec = AliasEntry.second;
Chris Lattner693173f2010-10-30 19:23:13 +00002737
2738 // Loop through each alias and emit code that handles each case. If there
2739 // are two instructions without predicates, emit an error. If there is one,
2740 // emit it last.
2741 std::string MatchCode;
2742 int AliasWithNoPredicate = -1;
Bob Wilson828295b2011-01-26 21:26:19 +00002743
Chris Lattner693173f2010-10-30 19:23:13 +00002744 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
2745 Record *R = ToVec[i];
Chris Lattner6fa152c2010-10-30 20:15:02 +00002746 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
Bob Wilson828295b2011-01-26 21:26:19 +00002747
Chris Lattner693173f2010-10-30 19:23:13 +00002748 // If this unconditionally matches, remember it for later and diagnose
2749 // duplicates.
2750 if (FeatureMask.empty()) {
2751 if (AliasWithNoPredicate != -1) {
2752 // We can't have two aliases from the same mnemonic with no predicate.
2753 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
2754 "two MnemonicAliases with the same 'from' mnemonic!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002755 PrintFatalError(R->getLoc(), "this is the other MnemonicAlias.");
Chris Lattner693173f2010-10-30 19:23:13 +00002756 }
Bob Wilson828295b2011-01-26 21:26:19 +00002757
Chris Lattner693173f2010-10-30 19:23:13 +00002758 AliasWithNoPredicate = i;
2759 continue;
2760 }
Craig Topper4d0e4052016-01-03 07:33:30 +00002761 if (R->getValueAsString("ToMnemonic") == AliasEntry.first)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002762 PrintFatalError(R->getLoc(), "MnemonicAlias to the same string");
Bob Wilson828295b2011-01-26 21:26:19 +00002763
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00002764 if (!MatchCode.empty())
2765 MatchCode += "else ";
Ranjeet Singhb0f78712015-06-30 12:32:53 +00002766 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
Craig Topperc469be32017-05-31 19:01:11 +00002767 MatchCode += " Mnemonic = \"";
2768 MatchCode += R->getValueAsString("ToMnemonic");
2769 MatchCode += "\";\n";
Chris Lattner4fd32c62010-10-30 18:56:12 +00002770 }
Bob Wilson828295b2011-01-26 21:26:19 +00002771
Chris Lattner693173f2010-10-30 19:23:13 +00002772 if (AliasWithNoPredicate != -1) {
2773 Record *R = ToVec[AliasWithNoPredicate];
Chris Lattner8cf8bcc2010-10-30 19:47:49 +00002774 if (!MatchCode.empty())
2775 MatchCode += "else\n ";
Craig Topperc469be32017-05-31 19:01:11 +00002776 MatchCode += "Mnemonic = \"";
2777 MatchCode += R->getValueAsString("ToMnemonic");
2778 MatchCode += "\";\n";
Chris Lattner693173f2010-10-30 19:23:13 +00002779 }
Bob Wilson828295b2011-01-26 21:26:19 +00002780
Chris Lattner693173f2010-10-30 19:23:13 +00002781 MatchCode += "return;";
2782
Craig Topper4d0e4052016-01-03 07:33:30 +00002783 Cases.push_back(std::make_pair(AliasEntry.first, MatchCode));
Chris Lattner4fd32c62010-10-30 18:56:12 +00002784 }
Chad Rosier88eb89b2013-04-18 22:35:36 +00002785 StringMatcher("Mnemonic", Cases, OS).Emit(Indent);
2786}
Bob Wilson828295b2011-01-26 21:26:19 +00002787
Chad Rosier88eb89b2013-04-18 22:35:36 +00002788/// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
2789/// emit a function for them and return true, otherwise return false.
2790static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info,
2791 CodeGenTarget &Target) {
2792 // Ignore aliases when match-prefix is set.
2793 if (!MatchPrefix.empty())
2794 return false;
2795
2796 std::vector<Record*> Aliases =
2797 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
2798 if (Aliases.empty()) return false;
2799
2800 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
Ranjeet Singhb0f78712015-06-30 12:32:53 +00002801 "uint64_t Features, unsigned VariantID) {\n";
Chad Rosier88eb89b2013-04-18 22:35:36 +00002802 OS << " switch (VariantID) {\n";
2803 unsigned VariantCount = Target.getAsmParserVariantCount();
2804 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2805 Record *AsmVariant = Target.getAsmParserVariant(VC);
2806 int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant");
Craig Topper2a129872017-05-31 21:12:46 +00002807 StringRef AsmParserVariantName = AsmVariant->getValueAsString("Name");
Chad Rosier88eb89b2013-04-18 22:35:36 +00002808 OS << " case " << AsmParserVariantNo << ":\n";
2809 emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2,
2810 AsmParserVariantName);
2811 OS << " break;\n";
2812 }
2813 OS << " }\n";
2814
2815 // Emit aliases that apply to all variants.
2816 emitMnemonicAliasVariant(OS, Info, Aliases);
2817
Daniel Dunbar55b5e852011-01-18 01:59:30 +00002818 OS << "}\n\n";
Bob Wilson828295b2011-01-26 21:26:19 +00002819
Chris Lattner7fd44892010-10-30 18:48:18 +00002820 return true;
Chris Lattner674c1dc2010-10-30 17:36:36 +00002821}
2822
Jim Grosbach8caecde2012-04-19 17:52:32 +00002823static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
Craig Topper3a364442012-09-18 07:02:21 +00002824 const AsmMatcherInfo &Info, StringRef ClassName,
2825 StringToOffsetTable &StringTable,
Craig Topper5ef13492015-12-31 08:18:23 +00002826 unsigned MaxMnemonicIndex, bool HasMnemonicFirst) {
Craig Topper3a364442012-09-18 07:02:21 +00002827 unsigned MaxMask = 0;
Craig Topper11590592015-12-31 08:18:20 +00002828 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
2829 MaxMask |= OMI.OperandMask;
Craig Topper3a364442012-09-18 07:02:21 +00002830 }
2831
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002832 // Emit the static custom operand parsing table;
2833 OS << "namespace {\n";
2834 OS << " struct OperandMatchEntry {\n";
Daniel Sandersb313c742016-11-19 13:05:44 +00002835 OS << " " << getMinimalTypeForEnumBitfield(Info.SubtargetFeatures.size())
Ranjeet Singhb0f78712015-06-30 12:32:53 +00002836 << " RequiredFeatures;\n";
Craig Topper3a364442012-09-18 07:02:21 +00002837 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
2838 << " Mnemonic;\n";
David Blaikie841db2c2014-11-28 20:35:57 +00002839 OS << " " << getMinimalTypeForRange(std::distance(
2840 Info.Classes.begin(), Info.Classes.end())) << " Class;\n";
Craig Topper3a364442012-09-18 07:02:21 +00002841 OS << " " << getMinimalTypeForRange(MaxMask)
2842 << " OperandMask;\n\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002843 OS << " StringRef getMnemonic() const {\n";
2844 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2845 OS << " MnemonicTable[Mnemonic]);\n";
2846 OS << " }\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002847 OS << " };\n\n";
2848
2849 OS << " // Predicate for searching for an opcode.\n";
2850 OS << " struct LessOpcodeOperand {\n";
2851 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002852 OS << " return LHS.getMnemonic() < RHS;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002853 OS << " }\n";
2854 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002855 OS << " return LHS < RHS.getMnemonic();\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002856 OS << " }\n";
2857 OS << " bool operator()(const OperandMatchEntry &LHS,";
2858 OS << " const OperandMatchEntry &RHS) {\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002859 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002860 OS << " }\n";
2861 OS << " };\n";
2862
2863 OS << "} // end anonymous namespace.\n\n";
2864
2865 OS << "static const OperandMatchEntry OperandMatchTable["
2866 << Info.OperandMatchInfo.size() << "] = {\n";
2867
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002868 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
Craig Topper11590592015-12-31 08:18:20 +00002869 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002870 const MatchableInfo &II = *OMI.MI;
2871
Craig Topper3a364442012-09-18 07:02:21 +00002872 OS << " { ";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002873
Craig Topper3a364442012-09-18 07:02:21 +00002874 // Write the required features mask.
2875 if (!II.RequiredFeatures.empty()) {
2876 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
Ranjeet Singhb0f78712015-06-30 12:32:53 +00002877 if (i) OS << "|";
Craig Topper3a364442012-09-18 07:02:21 +00002878 OS << II.RequiredFeatures[i]->getEnumName();
2879 }
2880 } else
Ranjeet Singhb0f78712015-06-30 12:32:53 +00002881 OS << "0";
Craig Topper3a364442012-09-18 07:02:21 +00002882
2883 // Store a pascal-style length byte in the mnemonic.
2884 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2885 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2886 << " /* " << II.Mnemonic << " */, ";
2887
2888 OS << OMI.CI->Name;
2889
2890 OS << ", " << OMI.OperandMask;
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002891 OS << " /* ";
2892 bool printComma = false;
2893 for (int i = 0, e = 31; i !=e; ++i)
2894 if (OMI.OperandMask & (1 << i)) {
2895 if (printComma)
2896 OS << ", ";
2897 OS << i;
2898 printComma = true;
2899 }
2900 OS << " */";
2901
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002902 OS << " },\n";
2903 }
2904 OS << "};\n\n";
2905
2906 // Emit the operand class switch to call the correct custom parser for
2907 // the found operand class.
Alex Bradbury5a675ff2016-11-01 16:32:05 +00002908 OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
David Blaikiec50f9862014-06-08 16:18:35 +00002909 << "tryCustomParseOperand(OperandVector"
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002910 << " &Operands,\n unsigned MCK) {\n\n"
2911 << " switch(MCK) {\n";
2912
Craig Topper44ebfb72014-11-28 03:53:02 +00002913 for (const auto &CI : Info.Classes) {
David Blaikie841db2c2014-11-28 20:35:57 +00002914 if (CI.ParserMethod.empty())
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002915 continue;
David Blaikie841db2c2014-11-28 20:35:57 +00002916 OS << " case " << CI.Name << ":\n"
2917 << " return " << CI.ParserMethod << "(Operands);\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002918 }
2919
2920 OS << " default:\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002921 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002922 OS << " }\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002923 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002924 OS << "}\n\n";
2925
2926 // Emit the static custom operand parser. This code is very similar with
2927 // the other matcher. Also use MatchResultTy here just in case we go for
2928 // a better error handling.
Alex Bradbury5a675ff2016-11-01 16:32:05 +00002929 OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
David Blaikiec50f9862014-06-08 16:18:35 +00002930 << "MatchOperandParserImpl(OperandVector"
Sander de Smalenbb614152017-12-20 11:02:42 +00002931 << " &Operands,\n StringRef Mnemonic,\n"
2932 << " bool ParseForAllFeatures) {\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002933
2934 // Emit code to get the available features.
2935 OS << " // Get the current feature set.\n";
Ranjeet Singhb0f78712015-06-30 12:32:53 +00002936 OS << " uint64_t AvailableFeatures = getAvailableFeatures();\n\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002937
2938 OS << " // Get the next operand index.\n";
Craig Topper5ef13492015-12-31 08:18:23 +00002939 OS << " unsigned NextOpNum = Operands.size()"
2940 << (HasMnemonicFirst ? " - 1" : "") << ";\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002941
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002942 // Emit code to search the table.
2943 OS << " // Search the table.\n";
Craig Topper5ef13492015-12-31 08:18:23 +00002944 if (HasMnemonicFirst) {
2945 OS << " auto MnemonicRange =\n";
2946 OS << " std::equal_range(std::begin(OperandMatchTable), "
2947 "std::end(OperandMatchTable),\n";
2948 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2949 } else {
2950 OS << " auto MnemonicRange = std::make_pair(std::begin(OperandMatchTable),"
2951 " std::end(OperandMatchTable));\n";
2952 OS << " if (!Mnemonic.empty())\n";
2953 OS << " MnemonicRange =\n";
2954 OS << " std::equal_range(std::begin(OperandMatchTable), "
2955 "std::end(OperandMatchTable),\n";
2956 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2957 }
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002958
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002959 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002960 OS << " return MatchOperand_NoMatch;\n\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002961
2962 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2963 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2964
2965 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
Benjamin Kramerb08bb342012-03-03 20:44:43 +00002966 OS << " assert(Mnemonic == it->getMnemonic());\n\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002967
2968 // Emit check that the required features are available.
2969 OS << " // check if the available features match\n";
Sander de Smalenbb614152017-12-20 11:02:42 +00002970 OS << " if (!ParseForAllFeatures && (AvailableFeatures & "
2971 "it->RequiredFeatures) != it->RequiredFeatures)\n";
2972 OS << " continue;\n\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002973
2974 // Emit check to ensure the operand number matches.
2975 OS << " // check if the operand in question has a custom parser.\n";
2976 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2977 OS << " continue;\n\n";
2978
2979 // Emit call to the custom parser method
2980 OS << " // call custom parse method to handle the operand\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002981 OS << " OperandMatchResultTy Result = ";
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00002982 OS << "tryCustomParseOperand(Operands, it->Class);\n";
Jim Grosbachf922c472011-02-12 01:34:40 +00002983 OS << " if (Result != MatchOperand_NoMatch)\n";
2984 OS << " return Result;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002985 OS << " }\n\n";
2986
Jim Grosbachf922c472011-02-12 01:34:40 +00002987 OS << " // Okay, we had no match.\n";
2988 OS << " return MatchOperand_NoMatch;\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00002989 OS << "}\n\n";
2990}
2991
Sander de Smalen1d8ca3c2018-01-10 10:10:56 +00002992static void emitAsmTiedOperandConstraints(CodeGenTarget &Target,
2993 AsmMatcherInfo &Info,
2994 raw_ostream &OS) {
Sander de Smalenb0c87382018-06-18 13:39:29 +00002995 std::string AsmParserName =
2996 Info.AsmParser->getValueAsString("AsmParserClassName");
Sander de Smalen1d8ca3c2018-01-10 10:10:56 +00002997 OS << "static bool ";
Sander de Smalenb0c87382018-06-18 13:39:29 +00002998 OS << "checkAsmTiedOperandConstraints(const " << Target.getName()
2999 << AsmParserName << "&AsmParser,\n";
3000 OS << " unsigned Kind,\n";
Sander de Smalen1d8ca3c2018-01-10 10:10:56 +00003001 OS << " const OperandVector &Operands,\n";
Sander de Smalencb6c95b2018-02-04 16:24:17 +00003002 OS << " uint64_t &ErrorInfo) {\n";
3003 OS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
3004 OS << " const uint8_t *Converter = ConversionTable[Kind];\n";
3005 OS << " for (const uint8_t *p = Converter; *p; p+= 2) {\n";
3006 OS << " switch (*p) {\n";
3007 OS << " case CVT_Tied: {\n";
3008 OS << " unsigned OpIdx = *(p+1);\n";
Simon Pilgrim7abdc5f2018-02-17 12:29:47 +00003009 OS << " assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
3010 OS << " std::begin(TiedAsmOperandTable)) &&\n";
Sander de Smalencb6c95b2018-02-04 16:24:17 +00003011 OS << " \"Tied operand not found\");\n";
3012 OS << " unsigned OpndNum1 = TiedAsmOperandTable[OpIdx][1];\n";
3013 OS << " unsigned OpndNum2 = TiedAsmOperandTable[OpIdx][2];\n";
3014 OS << " if (OpndNum1 != OpndNum2) {\n";
3015 OS << " auto &SrcOp1 = Operands[OpndNum1];\n";
3016 OS << " auto &SrcOp2 = Operands[OpndNum2];\n";
Sander de Smalenb0c87382018-06-18 13:39:29 +00003017 OS << " if (SrcOp1->isReg() && SrcOp2->isReg()) {\n";
3018 OS << " if (!AsmParser.regsEqual(*SrcOp1, *SrcOp2)) {\n";
3019 OS << " ErrorInfo = OpndNum2;\n";
3020 OS << " return false;\n";
3021 OS << " }\n";
Sander de Smalencb6c95b2018-02-04 16:24:17 +00003022 OS << " }\n";
3023 OS << " }\n";
3024 OS << " break;\n";
3025 OS << " }\n";
3026 OS << " default:\n";
3027 OS << " break;\n";
Sander de Smalen1d8ca3c2018-01-10 10:10:56 +00003028 OS << " }\n";
3029 OS << " }\n";
3030 OS << " return true;\n";
3031 OS << "}\n\n";
3032}
3033
Sjoerd Meijer8b755a32017-07-05 12:39:13 +00003034static void emitMnemonicSpellChecker(raw_ostream &OS, CodeGenTarget &Target,
3035 unsigned VariantCount) {
Craig Topper939e9702017-10-26 06:46:40 +00003036 OS << "static std::string " << Target.getName()
Craig Toppere1b56f02017-10-26 06:46:41 +00003037 << "MnemonicSpellCheck(StringRef S, uint64_t FBS, unsigned VariantID) {\n";
Sjoerd Meijer8b755a32017-07-05 12:39:13 +00003038 if (!VariantCount)
3039 OS << " return \"\";";
3040 else {
3041 OS << " const unsigned MaxEditDist = 2;\n";
3042 OS << " std::vector<StringRef> Candidates;\n";
Craig Toppere1b56f02017-10-26 06:46:41 +00003043 OS << " StringRef Prev = \"\";\n\n";
3044
3045 OS << " // Find the appropriate table for this asm variant.\n";
3046 OS << " const MatchEntry *Start, *End;\n";
3047 OS << " switch (VariantID) {\n";
3048 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
3049 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3050 Record *AsmVariant = Target.getAsmParserVariant(VC);
3051 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3052 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3053 << "); End = std::end(MatchTable" << VC << "); break;\n";
3054 }
3055 OS << " }\n\n";
3056 OS << " for (auto I = Start; I < End; I++) {\n";
Sjoerd Meijer8b755a32017-07-05 12:39:13 +00003057 OS << " // Ignore unsupported instructions.\n";
3058 OS << " if ((FBS & I->RequiredFeatures) != I->RequiredFeatures)\n";
3059 OS << " continue;\n";
3060 OS << "\n";
3061 OS << " StringRef T = I->getMnemonic();\n";
3062 OS << " // Avoid recomputing the edit distance for the same string.\n";
3063 OS << " if (T.equals(Prev))\n";
3064 OS << " continue;\n";
3065 OS << "\n";
3066 OS << " Prev = T;\n";
3067 OS << " unsigned Dist = S.edit_distance(T, false, MaxEditDist);\n";
3068 OS << " if (Dist <= MaxEditDist)\n";
3069 OS << " Candidates.push_back(T);\n";
3070 OS << " }\n";
3071 OS << "\n";
3072 OS << " if (Candidates.empty())\n";
3073 OS << " return \"\";\n";
3074 OS << "\n";
3075 OS << " std::string Res = \", did you mean: \";\n";
3076 OS << " unsigned i = 0;\n";
3077 OS << " for( ; i < Candidates.size() - 1; i++)\n";
3078 OS << " Res += Candidates[i].str() + \", \";\n";
3079 OS << " return Res + Candidates[i].str() + \"?\";\n";
3080 }
3081 OS << "}\n";
3082 OS << "\n";
3083}
3084
3085
Oliver Stannarde2711b82017-10-11 09:17:43 +00003086// Emit a function mapping match classes to strings, for debugging.
3087static void emitMatchClassKindNames(std::forward_list<ClassInfo> &Infos,
3088 raw_ostream &OS) {
3089 OS << "#ifndef NDEBUG\n";
3090 OS << "const char *getMatchClassName(MatchClassKind Kind) {\n";
3091 OS << " switch (Kind) {\n";
3092
3093 OS << " case InvalidMatchClass: return \"InvalidMatchClass\";\n";
3094 OS << " case OptionalMatchClass: return \"OptionalMatchClass\";\n";
3095 for (const auto &CI : Infos) {
3096 OS << " case " << CI.Name << ": return \"" << CI.Name << "\";\n";
3097 }
3098 OS << " case NumMatchClassKinds: return \"NumMatchClassKinds\";\n";
3099
3100 OS << " }\n";
3101 OS << " llvm_unreachable(\"unhandled MatchClassKind!\");\n";
3102 OS << "}\n\n";
3103 OS << "#endif // NDEBUG\n";
3104}
3105
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00003106void AsmMatcherEmitter::run(raw_ostream &OS) {
Chris Lattner67db8832010-12-13 00:23:57 +00003107 CodeGenTarget Target(Records);
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00003108 Record *AsmParser = Target.getAsmParser();
Craig Topper2a129872017-05-31 21:12:46 +00003109 StringRef ClassName = AsmParser->getValueAsString("AsmParserClassName");
Daniel Dunbar2234e5e2009-08-07 21:01:44 +00003110
Daniel Dunbara3741fa2009-08-08 07:50:56 +00003111 // Compute the information on the instructions to match.
Chris Lattner67db8832010-12-13 00:23:57 +00003112 AsmMatcherInfo Info(AsmParser, Target, Records);
Jim Grosbach8caecde2012-04-19 17:52:32 +00003113 Info.buildInfo();
Daniel Dunbara027d222009-07-31 02:32:59 +00003114
Daniel Dunbare1f6de32010-02-02 23:46:36 +00003115 // Sort the instruction table using the partial order on classes. We use
3116 // stable_sort to ensure that ambiguous instructions are still
3117 // deterministically ordered.
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00003118 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
3119 [](const std::unique_ptr<MatchableInfo> &a,
3120 const std::unique_ptr<MatchableInfo> &b){
3121 return *a < *b;});
Jim Grosbacha7c78222010-10-29 22:13:48 +00003122
Matthias Braun94785562016-12-05 19:44:31 +00003123#ifdef EXPENSIVE_CHECKS
3124 // Verify that the table is sorted and operator < works transitively.
3125 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
3126 ++I) {
3127 for (auto J = I; J != E; ++J) {
3128 assert(!(**J < **I));
3129 }
3130 }
3131#endif
3132
Daniel Dunbarb7479c02009-08-08 05:24:34 +00003133 DEBUG_WITH_TYPE("instruction_info", {
Craig Topper44ebfb72014-11-28 03:53:02 +00003134 for (const auto &MI : Info.Matchables)
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00003135 MI->dump();
Daniel Dunbar20927f22009-08-07 08:26:05 +00003136 });
Daniel Dunbara027d222009-07-31 02:32:59 +00003137
Chris Lattner22bc5c42010-11-01 05:06:45 +00003138 // Check for ambiguous matchables.
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00003139 DEBUG_WITH_TYPE("ambiguous_instrs", {
3140 unsigned NumAmbiguous = 0;
David Blaikie1b153042014-12-22 21:26:38 +00003141 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
3142 ++I) {
3143 for (auto J = std::next(I); J != E; ++J) {
3144 const MatchableInfo &A = **I;
3145 const MatchableInfo &B = **J;
Jim Grosbacha7c78222010-10-29 22:13:48 +00003146
Jim Grosbach8caecde2012-04-19 17:52:32 +00003147 if (A.couldMatchAmbiguouslyWith(B)) {
Chris Lattner22bc5c42010-11-01 05:06:45 +00003148 errs() << "warning: ambiguous matchables:\n";
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00003149 A.dump();
3150 errs() << "\nis incomparable with:\n";
3151 B.dump();
3152 errs() << "\n\n";
Chris Lattner87410362010-09-06 20:21:47 +00003153 ++NumAmbiguous;
3154 }
Daniel Dunbar2b544812009-08-09 06:05:33 +00003155 }
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00003156 }
Chris Lattner87410362010-09-06 20:21:47 +00003157 if (NumAmbiguous)
Jim Grosbacha7c78222010-10-29 22:13:48 +00003158 errs() << "warning: " << NumAmbiguous
Chris Lattner22bc5c42010-11-01 05:06:45 +00003159 << " ambiguous matchables!\n";
Chris Lattnerfa0d74d2010-09-06 21:28:52 +00003160 });
Daniel Dunbar606e8ad2009-08-09 04:00:06 +00003161
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00003162 // Compute the information on the custom operand parsing.
Jim Grosbach8caecde2012-04-19 17:52:32 +00003163 Info.buildOperandMatchInfo();
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00003164
Craig Topper5ef13492015-12-31 08:18:23 +00003165 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
Sam Koltonf117ec12016-05-06 11:31:17 +00003166 bool HasOptionalOperands = Info.hasOptionalOperands();
Oliver Stannard13e36102017-10-03 09:33:12 +00003167 bool ReportMultipleNearMisses =
3168 AsmParser->getValueAsBit("ReportMultipleNearMisses");
Craig Topper5ef13492015-12-31 08:18:23 +00003169
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00003170 // Write the output.
3171
Chris Lattner0692ee62010-09-06 19:11:01 +00003172 // Information for the class declaration.
3173 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
3174 OS << "#undef GET_ASSEMBLER_HEADER\n";
Jim Grosbach84cb0332011-02-11 21:31:55 +00003175 OS << " // This should be included into the middle of the declaration of\n";
Evan Cheng94b95502011-07-26 00:24:13 +00003176 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
Ranjeet Singhb0f78712015-06-30 12:32:53 +00003177 OS << " uint64_t ComputeAvailableFeatures(const FeatureBitset& FB) const;\n";
Sam Koltonf117ec12016-05-06 11:31:17 +00003178 if (HasOptionalOperands) {
3179 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
3180 << "unsigned Opcode,\n"
3181 << " const OperandVector &Operands,\n"
3182 << " const SmallBitVector &OptionalOperandsMask);\n";
3183 } else {
3184 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
3185 << "unsigned Opcode,\n"
3186 << " const OperandVector &Operands);\n";
3187 }
Chad Rosierc69bb702012-10-02 00:25:57 +00003188 OS << " void convertToMapAndConstraints(unsigned Kind,\n ";
Peter Collingbourned735fd72016-10-10 22:49:37 +00003189 OS << " const OperandVector &Operands) override;\n";
Craig Topper2717b062015-01-03 08:16:29 +00003190 OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
Oliver Stannard13e36102017-10-03 09:33:12 +00003191 << " MCInst &Inst,\n";
3192 if (ReportMultipleNearMisses)
3193 OS << " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
3194 else
3195 OS << " uint64_t &ErrorInfo,\n";
3196 OS << " bool matchingInlineAsm,\n"
Chad Rosierc69bb702012-10-02 00:25:57 +00003197 << " unsigned VariantID = 0);\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00003198
Alexander Kornienkob4c62672015-01-15 11:41:30 +00003199 if (!Info.OperandMatchInfo.empty()) {
Jim Grosbachf922c472011-02-12 01:34:40 +00003200 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
David Blaikiec50f9862014-06-08 16:18:35 +00003201 OS << " OperandVector &Operands,\n";
Sander de Smalenbb614152017-12-20 11:02:42 +00003202 OS << " StringRef Mnemonic,\n";
3203 OS << " bool ParseForAllFeatures = false);\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00003204
Jim Grosbach3d5d8f62011-12-06 22:07:02 +00003205 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
David Blaikiec50f9862014-06-08 16:18:35 +00003206 OS << " OperandVector &Operands,\n";
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00003207 OS << " unsigned MCK);\n\n";
3208 }
3209
Chris Lattner0692ee62010-09-06 19:11:01 +00003210 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
3211
Jim Grosbach4dbfdfb2012-06-22 23:56:44 +00003212 // Emit the operand match diagnostic enum names.
3213 OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
3214 OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3215 emitOperandDiagnosticTypes(Info, OS);
3216 OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3217
Chris Lattner0692ee62010-09-06 19:11:01 +00003218 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
3219 OS << "#undef GET_REGISTER_MATCHER\n\n";
3220
Daniel Dunbar54074b52010-07-19 05:44:09 +00003221 // Emit the subtarget feature enumeration.
Daniel Sandersb313c742016-11-19 13:05:44 +00003222 SubtargetFeatureInfo::emitSubtargetFeatureFlagEnumeration(
3223 Info.SubtargetFeatures, OS);
Daniel Dunbar54074b52010-07-19 05:44:09 +00003224
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00003225 // Emit the function to match a register name to number.
Akira Hatanaka72e9b6a2012-08-17 20:16:42 +00003226 // This should be omitted for Mips target
3227 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName"))
3228 emitMatchRegisterName(Target, AsmParser, OS);
Chris Lattner0692ee62010-09-06 19:11:01 +00003229
Dylan McKayf4afd082016-02-03 10:30:16 +00003230 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterAltName"))
3231 emitMatchRegisterAltName(Target, AsmParser, OS);
3232
Chris Lattner0692ee62010-09-06 19:11:01 +00003233 OS << "#endif // GET_REGISTER_MATCHER\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00003234
Craig Topper8030e1a2012-04-25 06:56:34 +00003235 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
3236 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
Daniel Dunbar1095f2a2009-08-11 23:23:44 +00003237
Jim Grosbach14ce6fa2012-04-24 22:40:08 +00003238 // Generate the helper function to get the names for subtarget features.
3239 emitGetSubtargetFeatureName(Info, OS);
3240
Craig Topper8030e1a2012-04-25 06:56:34 +00003241 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
3242
3243 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
3244 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
3245
Chris Lattner7fd44892010-10-30 18:48:18 +00003246 // Generate the function that remaps for mnemonic aliases.
Chad Rosier88eb89b2013-04-18 22:35:36 +00003247 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target);
Bob Wilson828295b2011-01-26 21:26:19 +00003248
Chad Rosier22685872012-10-01 23:45:51 +00003249 // Generate the convertToMCInst function to convert operands into an MCInst.
3250 // Also, generate the convertToMapAndConstraints function for MS-style inline
3251 // assembly. The latter doesn't actually generate a MCInst.
Sam Koltonf117ec12016-05-06 11:31:17 +00003252 emitConvertFuncs(Target, ClassName, Info.Matchables, HasMnemonicFirst,
3253 HasOptionalOperands, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00003254
Daniel Dunbara3741fa2009-08-08 07:50:56 +00003255 // Emit the enumeration for classes which participate in matching.
Jim Grosbach8caecde2012-04-19 17:52:32 +00003256 emitMatchClassEnumeration(Target, Info.Classes, OS);
Daniel Dunbara027d222009-07-31 02:32:59 +00003257
Oliver Stannardfe3c8f92017-10-03 14:34:57 +00003258 // Emit a function to get the user-visible string to describe an operand
3259 // match failure in diagnostics.
3260 emitOperandMatchErrorDiagStrings(Info, OS);
3261
Oliver Stannard0e4cc592017-10-10 11:00:40 +00003262 // Emit a function to map register classes to operand match failure codes.
3263 emitRegisterMatchErrorFunc(Info, OS);
3264
Daniel Dunbara3741fa2009-08-08 07:50:56 +00003265 // Emit the routine to match token strings to their match class.
Jim Grosbach8caecde2012-04-19 17:52:32 +00003266 emitMatchTokenString(Target, Info.Classes, OS);
Daniel Dunbara3741fa2009-08-08 07:50:56 +00003267
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00003268 // Emit the subclass predicate routine.
Jim Grosbach8caecde2012-04-19 17:52:32 +00003269 emitIsSubclass(Target, Info.Classes, OS);
Daniel Dunbarfdb1f492009-08-10 16:05:47 +00003270
Jim Grosbachb9db0c52011-02-10 00:08:28 +00003271 // Emit the routine to validate an operand against a match class.
Jim Grosbach8caecde2012-04-19 17:52:32 +00003272 emitValidateOperandClass(Info, OS);
Jim Grosbachb9db0c52011-02-10 00:08:28 +00003273
Oliver Stannarde2711b82017-10-11 09:17:43 +00003274 emitMatchClassKindNames(Info.Classes, OS);
3275
Daniel Dunbar54074b52010-07-19 05:44:09 +00003276 // Emit the available features compute function.
Daniel Sanderse8660ea2017-04-21 15:59:56 +00003277 SubtargetFeatureInfo::emitComputeAssemblerAvailableFeatures(
Daniel Sandersb313c742016-11-19 13:05:44 +00003278 Info.Target.getName(), ClassName, "ComputeAvailableFeatures",
3279 Info.SubtargetFeatures, OS);
Daniel Dunbar54074b52010-07-19 05:44:09 +00003280
Sander de Smalen1d8ca3c2018-01-10 10:10:56 +00003281 if (!ReportMultipleNearMisses)
3282 emitAsmTiedOperandConstraints(Target, Info, OS);
3283
Craig Topperfee7f012012-09-18 06:10:45 +00003284 StringToOffsetTable StringTable;
3285
Daniel Dunbara3741fa2009-08-08 07:50:56 +00003286 size_t MaxNumOperands = 0;
Craig Topperfee7f012012-09-18 06:10:45 +00003287 unsigned MaxMnemonicIndex = 0;
Joey Gouly715d98d2013-09-12 10:28:05 +00003288 bool HasDeprecation = false;
Craig Topper44ebfb72014-11-28 03:53:02 +00003289 for (const auto &MI : Info.Matchables) {
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00003290 MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
3291 HasDeprecation |= MI->HasDeprecation;
Craig Topperfee7f012012-09-18 06:10:45 +00003292
3293 // Store a pascal-style length byte in the mnemonic.
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00003294 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
Craig Topperfee7f012012-09-18 06:10:45 +00003295 MaxMnemonicIndex = std::max(MaxMnemonicIndex,
3296 StringTable.GetOrAddStringOffset(LenMnemonic, false));
3297 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00003298
Craig Topper3a364442012-09-18 07:02:21 +00003299 OS << "static const char *const MnemonicTable =\n";
3300 StringTable.EmitString(OS);
3301 OS << ";\n\n";
3302
Simon Pilgrim8d28e342017-03-31 10:59:37 +00003303 // Emit the static match table; unused classes get initialized to 0 which is
Daniel Dunbara3741fa2009-08-08 07:50:56 +00003304 // guaranteed to be InvalidMatchClass.
3305 //
3306 // FIXME: We can reduce the size of this table very easily. First, we change
3307 // it so that store the kinds in separate bit-fields for each index, which
3308 // only needs to be the max width used for classes at that index (we also need
3309 // to reject based on this during classification). If we then make sure to
3310 // order the match kinds appropriately (putting mnemonics last), then we
3311 // should only end up using a few bits for each class, especially the ones
3312 // following the mnemonic.
Chris Lattner96352e52010-09-06 21:08:38 +00003313 OS << "namespace {\n";
3314 OS << " struct MatchEntry {\n";
Craig Topperfee7f012012-09-18 06:10:45 +00003315 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
3316 << " Mnemonic;\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00003317 OS << " uint16_t Opcode;\n";
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00003318 OS << " " << getMinimalTypeForRange(Info.Matchables.size())
3319 << " ConvertFn;\n";
Daniel Sandersb313c742016-11-19 13:05:44 +00003320 OS << " " << getMinimalTypeForEnumBitfield(Info.SubtargetFeatures.size())
Ranjeet Singhb0f78712015-06-30 12:32:53 +00003321 << " RequiredFeatures;\n";
David Blaikie841db2c2014-11-28 20:35:57 +00003322 OS << " " << getMinimalTypeForRange(
3323 std::distance(Info.Classes.begin(), Info.Classes.end()))
3324 << " Classes[" << MaxNumOperands << "];\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00003325 OS << " StringRef getMnemonic() const {\n";
3326 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
3327 OS << " MnemonicTable[Mnemonic]);\n";
3328 OS << " }\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00003329 OS << " };\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00003330
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00003331 OS << " // Predicate for searching for an opcode.\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00003332 OS << " struct LessOpcode {\n";
3333 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00003334 OS << " return LHS.getMnemonic() < RHS;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00003335 OS << " }\n";
3336 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00003337 OS << " return LHS < RHS.getMnemonic();\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00003338 OS << " }\n";
Chris Lattner32c685c2010-09-07 06:10:48 +00003339 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
Benjamin Kramera4c5ecf2012-03-03 19:13:26 +00003340 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
Chris Lattner32c685c2010-09-07 06:10:48 +00003341 OS << " }\n";
Chris Lattner96352e52010-09-06 21:08:38 +00003342 OS << " };\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00003343
Chris Lattner96352e52010-09-06 21:08:38 +00003344 OS << "} // end anonymous namespace.\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00003345
Craig Topperf63ef912013-07-24 07:33:14 +00003346 unsigned VariantCount = Target.getAsmParserVariantCount();
3347 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3348 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topperf63ef912013-07-24 07:33:14 +00003349 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Jim Grosbacha7c78222010-10-29 22:13:48 +00003350
Craig Topperf63ef912013-07-24 07:33:14 +00003351 OS << "static const MatchEntry MatchTable" << VC << "[] = {\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00003352
Craig Topper44ebfb72014-11-28 03:53:02 +00003353 for (const auto &MI : Info.Matchables) {
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00003354 if (MI->AsmVariantID != AsmVariantNo)
Craig Topperf63ef912013-07-24 07:33:14 +00003355 continue;
Jim Grosbacha7c78222010-10-29 22:13:48 +00003356
Craig Topperf63ef912013-07-24 07:33:14 +00003357 // Store a pascal-style length byte in the mnemonic.
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00003358 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
Craig Topperf63ef912013-07-24 07:33:14 +00003359 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00003360 << " /* " << MI->Mnemonic << " */, "
Craig Topper3e595d02017-07-07 05:19:25 +00003361 << Target.getInstNamespace() << "::"
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00003362 << MI->getResultInst()->TheDef->getName() << ", "
3363 << MI->ConversionFnKind << ", ";
Craig Topperf63ef912013-07-24 07:33:14 +00003364
3365 // Write the required features mask.
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00003366 if (!MI->RequiredFeatures.empty()) {
3367 for (unsigned i = 0, e = MI->RequiredFeatures.size(); i != e; ++i) {
Ranjeet Singhb0f78712015-06-30 12:32:53 +00003368 if (i) OS << "|";
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00003369 OS << MI->RequiredFeatures[i]->getEnumName();
Craig Topperf63ef912013-07-24 07:33:14 +00003370 }
3371 } else
Ranjeet Singhb0f78712015-06-30 12:32:53 +00003372 OS << "0";
Craig Topperf63ef912013-07-24 07:33:14 +00003373
3374 OS << ", { ";
Duncan P. N. Exon Smithb60bcfd2014-11-28 23:00:22 +00003375 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
3376 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
Craig Topperf63ef912013-07-24 07:33:14 +00003377
3378 if (i) OS << ", ";
3379 OS << Op.Class->Name;
Daniel Dunbar54074b52010-07-19 05:44:09 +00003380 }
Craig Topperf63ef912013-07-24 07:33:14 +00003381 OS << " }, },\n";
Craig Topperfab3f7e2012-04-02 07:48:39 +00003382 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00003383
Craig Topperf63ef912013-07-24 07:33:14 +00003384 OS << "};\n\n";
3385 }
Daniel Dunbara027d222009-07-31 02:32:59 +00003386
Oliver Stannarde2711b82017-10-11 09:17:43 +00003387 OS << "#include \"llvm/Support/Debug.h\"\n";
3388 OS << "#include \"llvm/Support/Format.h\"\n\n";
3389
Chris Lattner96352e52010-09-06 21:08:38 +00003390 // Finally, build the match function.
David Blaikiec50f9862014-06-08 16:18:35 +00003391 OS << "unsigned " << Target.getName() << ClassName << "::\n"
Craig Topper2717b062015-01-03 08:16:29 +00003392 << "MatchInstructionImpl(const OperandVector &Operands,\n";
Oliver Stannard13e36102017-10-03 09:33:12 +00003393 OS << " MCInst &Inst,\n";
3394 if (ReportMultipleNearMisses)
3395 OS << " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
3396 else
3397 OS << " uint64_t &ErrorInfo,\n";
3398 OS << " bool matchingInlineAsm, unsigned VariantID) {\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00003399
Oliver Stannard13e36102017-10-03 09:33:12 +00003400 if (!ReportMultipleNearMisses) {
3401 OS << " // Eliminate obvious mismatches.\n";
3402 OS << " if (Operands.size() > "
3403 << (MaxNumOperands + HasMnemonicFirst) << ") {\n";
3404 OS << " ErrorInfo = "
3405 << (MaxNumOperands + HasMnemonicFirst) << ";\n";
3406 OS << " return Match_InvalidOperand;\n";
3407 OS << " }\n\n";
3408 }
Chad Rosier0bad0862012-08-30 21:43:05 +00003409
Daniel Dunbar54074b52010-07-19 05:44:09 +00003410 // Emit code to get the available features.
3411 OS << " // Get the current feature set.\n";
Ranjeet Singhb0f78712015-06-30 12:32:53 +00003412 OS << " uint64_t AvailableFeatures = getAvailableFeatures();\n\n";
Daniel Dunbar54074b52010-07-19 05:44:09 +00003413
Chris Lattner674c1dc2010-10-30 17:36:36 +00003414 OS << " // Get the instruction mnemonic, which is the first token.\n";
Craig Topper5ef13492015-12-31 08:18:23 +00003415 if (HasMnemonicFirst) {
3416 OS << " StringRef Mnemonic = ((" << Target.getName()
3417 << "Operand&)*Operands[0]).getToken();\n\n";
3418 } else {
3419 OS << " StringRef Mnemonic;\n";
3420 OS << " if (Operands[0]->isToken())\n";
3421 OS << " Mnemonic = ((" << Target.getName()
3422 << "Operand&)*Operands[0]).getToken();\n\n";
3423 }
Chris Lattner674c1dc2010-10-30 17:36:36 +00003424
Chris Lattner7fd44892010-10-30 18:48:18 +00003425 if (HasMnemonicAliases) {
3426 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
Chad Rosier88eb89b2013-04-18 22:35:36 +00003427 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n";
Chris Lattner7fd44892010-10-30 18:48:18 +00003428 }
Bob Wilson828295b2011-01-26 21:26:19 +00003429
Daniel Dunbara3741fa2009-08-08 07:50:56 +00003430 // Emit code to compute the class list for this operand vector.
Oliver Stannard13e36102017-10-03 09:33:12 +00003431 if (!ReportMultipleNearMisses) {
3432 OS << " // Some state to try to produce better error messages.\n";
3433 OS << " bool HadMatchOtherThanFeatures = false;\n";
3434 OS << " bool HadMatchOtherThanPredicate = false;\n";
3435 OS << " unsigned RetCode = Match_InvalidOperand;\n";
3436 OS << " uint64_t MissingFeatures = ~0ULL;\n";
3437 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
3438 OS << " // wrong for all instances of the instruction.\n";
3439 OS << " ErrorInfo = ~0ULL;\n";
3440 }
3441
Sam Koltonf117ec12016-05-06 11:31:17 +00003442 if (HasOptionalOperands) {
3443 OS << " SmallBitVector OptionalOperandsMask(" << MaxNumOperands << ");\n";
3444 }
Chris Lattner2b1f9432010-09-06 21:22:45 +00003445
Daniel Dunbara3741fa2009-08-08 07:50:56 +00003446 // Emit code to search the table.
Craig Topperf63ef912013-07-24 07:33:14 +00003447 OS << " // Find the appropriate table for this asm variant.\n";
3448 OS << " const MatchEntry *Start, *End;\n";
3449 OS << " switch (VariantID) {\n";
Craig Topper577a7682015-01-03 08:16:14 +00003450 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
Craig Topperf63ef912013-07-24 07:33:14 +00003451 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3452 Record *AsmVariant = Target.getAsmParserVariant(VC);
Craig Topperf63ef912013-07-24 07:33:14 +00003453 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
Benjamin Kramer15c435a2014-04-12 16:15:53 +00003454 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3455 << "); End = std::end(MatchTable" << VC << "); break;\n";
Craig Topperf63ef912013-07-24 07:33:14 +00003456 }
3457 OS << " }\n";
Craig Topper5ef13492015-12-31 08:18:23 +00003458
Daniel Dunbara3741fa2009-08-08 07:50:56 +00003459 OS << " // Search the table.\n";
Craig Topper5ef13492015-12-31 08:18:23 +00003460 if (HasMnemonicFirst) {
3461 OS << " auto MnemonicRange = "
3462 "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
3463 } else {
3464 OS << " auto MnemonicRange = std::make_pair(Start, End);\n";
3465 OS << " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
3466 OS << " if (!Mnemonic.empty())\n";
3467 OS << " MnemonicRange = "
3468 "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
3469 }
Jim Grosbacha7c78222010-10-29 22:13:48 +00003470
Oliver Stannarde2711b82017-10-11 09:17:43 +00003471 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"AsmMatcher: found \" <<\n"
3472 << " std::distance(MnemonicRange.first, MnemonicRange.second) << \n"
3473 << " \" encodings with mnemonic '\" << Mnemonic << \"'\\n\");\n\n";
3474
Chris Lattnera008e8a2010-09-06 21:54:15 +00003475 OS << " // Return a more specific error code if no mnemonics match.\n";
3476 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
3477 OS << " return Match_MnemonicFail;\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00003478
Chris Lattner2b1f9432010-09-06 21:22:45 +00003479 OS << " for (const MatchEntry *it = MnemonicRange.first, "
Chris Lattner80db4e52010-09-06 21:23:43 +00003480 << "*ie = MnemonicRange.second;\n";
Chris Lattner2b1f9432010-09-06 21:22:45 +00003481 OS << " it != ie; ++it) {\n";
Sander de Smalenbb614152017-12-20 11:02:42 +00003482 OS << " bool HasRequiredFeatures =\n";
3483 OS << " (AvailableFeatures & it->RequiredFeatures) == "
3484 "it->RequiredFeatures;\n";
Oliver Stannarde2711b82017-10-11 09:17:43 +00003485 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Trying to match opcode \"\n";
3486 OS << " << MII.getName(it->Opcode) << \"\\n\");\n";
3487
Oliver Stannard13e36102017-10-03 09:33:12 +00003488 if (ReportMultipleNearMisses) {
3489 OS << " // Some state to record ways in which this instruction did not match.\n";
3490 OS << " NearMissInfo OperandNearMiss = NearMissInfo::getSuccess();\n";
3491 OS << " NearMissInfo FeaturesNearMiss = NearMissInfo::getSuccess();\n";
3492 OS << " NearMissInfo EarlyPredicateNearMiss = NearMissInfo::getSuccess();\n";
3493 OS << " NearMissInfo LatePredicateNearMiss = NearMissInfo::getSuccess();\n";
Oliver Stannard9d998102017-12-04 13:42:22 +00003494 OS << " bool MultipleInvalidOperands = false;\n";
Oliver Stannard13e36102017-10-03 09:33:12 +00003495 }
3496
Craig Topper5ef13492015-12-31 08:18:23 +00003497 if (HasMnemonicFirst) {
3498 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
3499 OS << " assert(Mnemonic == it->getMnemonic());\n";
3500 }
3501
Daniel Dunbar54074b52010-07-19 05:44:09 +00003502 // Emit check that the subclasses match.
Oliver Stannard13e36102017-10-03 09:33:12 +00003503 if (!ReportMultipleNearMisses)
3504 OS << " bool OperandsValid = true;\n";
Sam Koltonf117ec12016-05-06 11:31:17 +00003505 if (HasOptionalOperands) {
3506 OS << " OptionalOperandsMask.reset(0, " << MaxNumOperands << ");\n";
3507 }
Nikolay Haustov344528b2016-03-01 08:34:43 +00003508 OS << " for (unsigned FormalIdx = " << (HasMnemonicFirst ? "0" : "SIndex")
3509 << ", ActualIdx = " << (HasMnemonicFirst ? "1" : "SIndex")
3510 << "; FormalIdx != " << MaxNumOperands << "; ++FormalIdx) {\n";
3511 OS << " auto Formal = "
3512 << "static_cast<MatchClassKind>(it->Classes[FormalIdx]);\n";
Oliver Stannarde2711b82017-10-11 09:17:43 +00003513 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3514 OS << " dbgs() << \" Matching formal operand class \" << getMatchClassName(Formal)\n";
3515 OS << " << \" against actual operand at index \" << ActualIdx);\n";
3516 OS << " if (ActualIdx < Operands.size())\n";
3517 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \" (\";\n";
3518 OS << " Operands[ActualIdx]->print(dbgs()); dbgs() << \"): \");\n";
3519 OS << " else\n";
3520 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \": \");\n";
Nikolay Haustov344528b2016-03-01 08:34:43 +00003521 OS << " if (ActualIdx >= Operands.size()) {\n";
Oliver Stannarde2711b82017-10-11 09:17:43 +00003522 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"actual operand index out of range \");\n";
Oliver Stannard13e36102017-10-03 09:33:12 +00003523 if (ReportMultipleNearMisses) {
3524 OS << " bool ThisOperandValid = (Formal == " <<"InvalidMatchClass) || "
3525 "isSubclass(Formal, OptionalMatchClass);\n";
3526 OS << " if (!ThisOperandValid) {\n";
3527 OS << " if (!OperandNearMiss) {\n";
3528 OS << " // Record info about match failure for later use.\n";
Oliver Stannarde2711b82017-10-11 09:17:43 +00003529 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"recording too-few-operands near miss\\n\");\n";
Oliver Stannard13e36102017-10-03 09:33:12 +00003530 OS << " OperandNearMiss =\n";
3531 OS << " NearMissInfo::getTooFewOperands(Formal, it->Opcode);\n";
Oliver Stannard252ae732017-11-21 15:16:50 +00003532 OS << " } else if (OperandNearMiss.getKind() != NearMissInfo::NearMissTooFewOperands) {\n";
Oliver Stannard9d998102017-12-04 13:42:22 +00003533 OS << " // If more than one operand is invalid, give up on this match entry.\n";
Oliver Stannarde2711b82017-10-11 09:17:43 +00003534 OS << " DEBUG_WITH_TYPE(\n";
3535 OS << " \"asm-matcher\",\n";
3536 OS << " dbgs() << \"second invalid operand, giving up on this opcode\\n\");\n";
Oliver Stannard9d998102017-12-04 13:42:22 +00003537 OS << " MultipleInvalidOperands = true;\n";
Oliver Stannard13e36102017-10-03 09:33:12 +00003538 OS << " break;\n";
3539 OS << " }\n";
Oliver Stannarde2711b82017-10-11 09:17:43 +00003540 OS << " } else {\n";
3541 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"but formal operand not required\\n\");\n";
Oliver Stannard175246c2017-11-21 15:12:05 +00003542 OS << " break;\n";
Oliver Stannard13e36102017-10-03 09:33:12 +00003543 OS << " }\n";
3544 OS << " continue;\n";
3545 } else {
3546 OS << " OperandsValid = (Formal == InvalidMatchClass) || isSubclass(Formal, OptionalMatchClass);\n";
3547 OS << " if (!OperandsValid) ErrorInfo = ActualIdx;\n";
3548 if (HasOptionalOperands) {
3549 OS << " OptionalOperandsMask.set(FormalIdx, " << MaxNumOperands
3550 << ");\n";
3551 }
3552 OS << " break;\n";
Sam Koltonf117ec12016-05-06 11:31:17 +00003553 }
Jim Grosbachb9db0c52011-02-10 00:08:28 +00003554 OS << " }\n";
Nikolay Haustov344528b2016-03-01 08:34:43 +00003555 OS << " MCParsedAsmOperand &Actual = *Operands[ActualIdx];\n";
Colin LeMahieu503438e2015-11-09 00:46:46 +00003556 OS << " unsigned Diag = validateOperandClass(Actual, Formal);\n";
Nikolay Haustov344528b2016-03-01 08:34:43 +00003557 OS << " if (Diag == Match_Success) {\n";
Oliver Stannarde2711b82017-10-11 09:17:43 +00003558 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3559 OS << " dbgs() << \"match success using generic matcher\\n\");\n";
Nikolay Haustov344528b2016-03-01 08:34:43 +00003560 OS << " ++ActualIdx;\n";
Chris Lattnerce4a3352010-09-06 22:11:18 +00003561 OS << " continue;\n";
Nikolay Haustov344528b2016-03-01 08:34:43 +00003562 OS << " }\n";
Jim Grosbachfa05def2013-02-06 06:00:06 +00003563 OS << " // If the generic handler indicates an invalid operand\n";
3564 OS << " // failure, check for a special case.\n";
Oliver Stannard0e4cc592017-10-10 11:00:40 +00003565 OS << " if (Diag != Match_Success) {\n";
3566 OS << " unsigned TargetDiag = validateTargetOperandClass(Actual, Formal);\n";
3567 OS << " if (TargetDiag == Match_Success) {\n";
Oliver Stannarde2711b82017-10-11 09:17:43 +00003568 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3569 OS << " dbgs() << \"match success using target matcher\\n\");\n";
Nikolay Haustov344528b2016-03-01 08:34:43 +00003570 OS << " ++ActualIdx;\n";
Jim Grosbachfa05def2013-02-06 06:00:06 +00003571 OS << " continue;\n";
Nikolay Haustov344528b2016-03-01 08:34:43 +00003572 OS << " }\n";
Oliver Stannard0e4cc592017-10-10 11:00:40 +00003573 OS << " // If the target matcher returned a specific error code use\n";
3574 OS << " // that, else use the one from the generic matcher.\n";
Sander de Smalenbb614152017-12-20 11:02:42 +00003575 OS << " if (TargetDiag != Match_InvalidOperand && "
3576 "HasRequiredFeatures)\n";
Oliver Stannard0e4cc592017-10-10 11:00:40 +00003577 OS << " Diag = TargetDiag;\n";
Jim Grosbachfa05def2013-02-06 06:00:06 +00003578 OS << " }\n";
Nikolay Haustov344528b2016-03-01 08:34:43 +00003579 OS << " // If current formal operand wasn't matched and it is optional\n"
3580 << " // then try to match next formal operand\n";
3581 OS << " if (Diag == Match_InvalidOperand "
Sam Koltonf117ec12016-05-06 11:31:17 +00003582 << "&& isSubclass(Formal, OptionalMatchClass)) {\n";
3583 if (HasOptionalOperands) {
3584 OS << " OptionalOperandsMask.set(FormalIdx);\n";
3585 }
Oliver Stannarde2711b82017-10-11 09:17:43 +00003586 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"ignoring optional operand\\n\");\n";
Nikolay Haustov344528b2016-03-01 08:34:43 +00003587 OS << " continue;\n";
Sam Koltonf117ec12016-05-06 11:31:17 +00003588 OS << " }\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00003589
Oliver Stannard13e36102017-10-03 09:33:12 +00003590 if (ReportMultipleNearMisses) {
3591 OS << " if (!OperandNearMiss) {\n";
3592 OS << " // If this is the first invalid operand we have seen, record some\n";
3593 OS << " // information about it.\n";
Oliver Stannarde2711b82017-10-11 09:17:43 +00003594 OS << " DEBUG_WITH_TYPE(\n";
3595 OS << " \"asm-matcher\",\n";
3596 OS << " dbgs()\n";
3597 OS << " << \"operand match failed, recording near-miss with diag code \"\n";
3598 OS << " << Diag << \"\\n\");\n";
Oliver Stannard13e36102017-10-03 09:33:12 +00003599 OS << " OperandNearMiss =\n";
3600 OS << " NearMissInfo::getMissedOperand(Diag, Formal, it->Opcode, ActualIdx);\n";
3601 OS << " ++ActualIdx;\n";
3602 OS << " } else {\n";
3603 OS << " // If more than one operand is invalid, give up on this match entry.\n";
Oliver Stannarde2711b82017-10-11 09:17:43 +00003604 OS << " DEBUG_WITH_TYPE(\n";
3605 OS << " \"asm-matcher\",\n";
3606 OS << " dbgs() << \"second operand mismatch, skipping this opcode\\n\");\n";
Oliver Stannard9d998102017-12-04 13:42:22 +00003607 OS << " MultipleInvalidOperands = true;\n";
Oliver Stannard13e36102017-10-03 09:33:12 +00003608 OS << " break;\n";
3609 OS << " }\n";
3610 OS << " }\n\n";
3611 } else {
3612 OS << " // If this operand is broken for all of the instances of this\n";
3613 OS << " // mnemonic, keep track of it so we can report loc info.\n";
3614 OS << " // If we already had a match that only failed due to a\n";
3615 OS << " // target predicate, that diagnostic is preferred.\n";
3616 OS << " if (!HadMatchOtherThanPredicate &&\n";
3617 OS << " (it == MnemonicRange.first || ErrorInfo <= ActualIdx)) {\n";
Sander de Smalenbb614152017-12-20 11:02:42 +00003618 OS << " if (HasRequiredFeatures && (ErrorInfo != ActualIdx || Diag "
3619 "!= Match_InvalidOperand))\n";
Sander de Smalenb1812792017-11-21 15:07:43 +00003620 OS << " RetCode = Diag;\n";
Sander de Smalen9a94efd2017-12-14 16:09:48 +00003621 OS << " ErrorInfo = ActualIdx;\n";
Oliver Stannard13e36102017-10-03 09:33:12 +00003622 OS << " }\n";
3623 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
3624 OS << " OperandsValid = false;\n";
3625 OS << " break;\n";
3626 OS << " }\n\n";
3627 }
3628
Oliver Stannard9d998102017-12-04 13:42:22 +00003629 if (ReportMultipleNearMisses)
3630 OS << " if (MultipleInvalidOperands) {\n";
3631 else
Oliver Stannarde2711b82017-10-11 09:17:43 +00003632 OS << " if (!OperandsValid) {\n";
Oliver Stannard9d998102017-12-04 13:42:22 +00003633 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3634 OS << " \"operand mismatches, ignoring \"\n";
3635 OS << " \"this opcode\\n\");\n";
3636 OS << " continue;\n";
3637 OS << " }\n";
Chris Lattnerec6789f2010-09-06 20:08:02 +00003638
3639 // Emit check that the required features are available.
Sander de Smalenbb614152017-12-20 11:02:42 +00003640 OS << " if (!HasRequiredFeatures) {\n";
Oliver Stannard13e36102017-10-03 09:33:12 +00003641 if (!ReportMultipleNearMisses)
3642 OS << " HadMatchOtherThanFeatures = true;\n";
Ranjeet Singhb0f78712015-06-30 12:32:53 +00003643 OS << " uint64_t NewMissingFeatures = it->RequiredFeatures & "
Jim Grosbach325bd662012-06-18 19:45:46 +00003644 "~AvailableFeatures;\n";
Oliver Stannarde2711b82017-10-11 09:17:43 +00003645 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Missing target features: \"\n";
3646 OS << " << format_hex(NewMissingFeatures, 18)\n";
3647 OS << " << \"\\n\");\n";
Oliver Stannard13e36102017-10-03 09:33:12 +00003648 if (ReportMultipleNearMisses) {
3649 OS << " FeaturesNearMiss = NearMissInfo::getMissedFeature(NewMissingFeatures);\n";
3650 } else {
3651 OS << " if (countPopulation(NewMissingFeatures) <=\n"
3652 " countPopulation(MissingFeatures))\n";
3653 OS << " MissingFeatures = NewMissingFeatures;\n";
3654 OS << " continue;\n";
3655 }
Chris Lattnerec6789f2010-09-06 20:08:02 +00003656 OS << " }\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00003657 OS << "\n";
Ahmed Bougacha3ddc3222014-12-16 18:05:28 +00003658 OS << " Inst.clear();\n\n";
Daniel Sanders1f35f2f2016-07-27 13:49:44 +00003659 OS << " Inst.setOpcode(it->Opcode);\n";
3660 // Verify the instruction with the target-specific match predicate function.
3661 OS << " // We have a potential match but have not rendered the operands.\n"
3662 << " // Check the target predicate to handle any context sensitive\n"
3663 " // constraints.\n"
3664 << " // For example, Ties that are referenced multiple times must be\n"
3665 " // checked here to ensure the input is the same for each match\n"
3666 " // constraints. If we leave it any later the ties will have been\n"
3667 " // canonicalized\n"
3668 << " unsigned MatchResult;\n"
3669 << " if ((MatchResult = checkEarlyTargetMatchPredicate(Inst, "
3670 "Operands)) != Match_Success) {\n"
Oliver Stannard13e36102017-10-03 09:33:12 +00003671 << " Inst.clear();\n";
Oliver Stannarde2711b82017-10-11 09:17:43 +00003672 OS << " DEBUG_WITH_TYPE(\n";
3673 OS << " \"asm-matcher\",\n";
3674 OS << " dbgs() << \"Early target match predicate failed with diag code \"\n";
3675 OS << " << MatchResult << \"\\n\");\n";
Oliver Stannard13e36102017-10-03 09:33:12 +00003676 if (ReportMultipleNearMisses) {
3677 OS << " EarlyPredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
3678 } else {
3679 OS << " RetCode = MatchResult;\n"
3680 << " HadMatchOtherThanPredicate = true;\n"
3681 << " continue;\n";
3682 }
3683 OS << " }\n\n";
3684
3685 if (ReportMultipleNearMisses) {
3686 OS << " // If we did not successfully match the operands, then we can't convert to\n";
3687 OS << " // an MCInst, so bail out on this instruction variant now.\n";
3688 OS << " if (OperandNearMiss) {\n";
3689 OS << " // If the operand mismatch was the only problem, reprrt it as a near-miss.\n";
3690 OS << " if (NearMisses && !FeaturesNearMiss && !EarlyPredicateNearMiss) {\n";
Oliver Stannarde2711b82017-10-11 09:17:43 +00003691 OS << " DEBUG_WITH_TYPE(\n";
3692 OS << " \"asm-matcher\",\n";
3693 OS << " dbgs()\n";
3694 OS << " << \"Opcode result: one mismatched operand, adding near-miss\\n\");\n";
Oliver Stannard13e36102017-10-03 09:33:12 +00003695 OS << " NearMisses->push_back(OperandNearMiss);\n";
Oliver Stannarde2711b82017-10-11 09:17:43 +00003696 OS << " } else {\n";
3697 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3698 OS << " \"types of mismatch, so not \"\n";
3699 OS << " \"reporting near-miss\\n\");\n";
Oliver Stannard13e36102017-10-03 09:33:12 +00003700 OS << " }\n";
3701 OS << " continue;\n";
3702 OS << " }\n\n";
3703 }
3704
Chad Rosier22685872012-10-01 23:45:51 +00003705 OS << " if (matchingInlineAsm) {\n";
Chad Rosier6e006d32012-10-12 22:53:36 +00003706 OS << " convertToMapAndConstraints(it->ConvertFn, Operands);\n";
Sander de Smalen1d8ca3c2018-01-10 10:10:56 +00003707 if (!ReportMultipleNearMisses) {
Sander de Smalenb0c87382018-06-18 13:39:29 +00003708 OS << " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
3709 "Operands, ErrorInfo))\n";
Sander de Smalen1d8ca3c2018-01-10 10:10:56 +00003710 OS << " return Match_InvalidTiedOperand;\n";
Sander de Smalen1d8ca3c2018-01-10 10:10:56 +00003711 OS << "\n";
3712 }
Chad Rosier22685872012-10-01 23:45:51 +00003713 OS << " return Match_Success;\n";
3714 OS << " }\n\n";
Daniel Dunbarb4129152011-02-04 17:12:23 +00003715 OS << " // We have selected a definite instruction, convert the parsed\n"
3716 << " // operands into the appropriate MCInst.\n";
Sam Koltonf117ec12016-05-06 11:31:17 +00003717 if (HasOptionalOperands) {
3718 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands,\n"
3719 << " OptionalOperandsMask);\n";
3720 } else {
3721 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
3722 }
Daniel Dunbarb4129152011-02-04 17:12:23 +00003723 OS << "\n";
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00003724
Jim Grosbach19cb7f42011-08-15 23:03:29 +00003725 // Verify the instruction with the target-specific match predicate function.
3726 OS << " // We have a potential match. Check the target predicate to\n"
3727 << " // handle any context sensitive constraints.\n"
Jim Grosbach19cb7f42011-08-15 23:03:29 +00003728 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
3729 << " Match_Success) {\n"
Oliver Stannarde2711b82017-10-11 09:17:43 +00003730 << " DEBUG_WITH_TYPE(\"asm-matcher\",\n"
3731 << " dbgs() << \"Target match predicate failed with diag code \"\n"
3732 << " << MatchResult << \"\\n\");\n"
Oliver Stannard13e36102017-10-03 09:33:12 +00003733 << " Inst.clear();\n";
3734 if (ReportMultipleNearMisses) {
3735 OS << " LatePredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
3736 } else {
3737 OS << " RetCode = MatchResult;\n"
3738 << " HadMatchOtherThanPredicate = true;\n"
3739 << " continue;\n";
3740 }
3741 OS << " }\n\n";
3742
3743 if (ReportMultipleNearMisses) {
3744 OS << " int NumNearMisses = ((int)(bool)OperandNearMiss +\n";
3745 OS << " (int)(bool)FeaturesNearMiss +\n";
3746 OS << " (int)(bool)EarlyPredicateNearMiss +\n";
3747 OS << " (int)(bool)LatePredicateNearMiss);\n";
3748 OS << " if (NumNearMisses == 1) {\n";
3749 OS << " // We had exactly one type of near-miss, so add that to the list.\n";
3750 OS << " assert(!OperandNearMiss && \"OperandNearMiss was handled earlier\");\n";
Oliver Stannarde2711b82017-10-11 09:17:43 +00003751 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: found one type of \"\n";
3752 OS << " \"mismatch, so reporting a \"\n";
3753 OS << " \"near-miss\\n\");\n";
Oliver Stannard13e36102017-10-03 09:33:12 +00003754 OS << " if (NearMisses && FeaturesNearMiss)\n";
3755 OS << " NearMisses->push_back(FeaturesNearMiss);\n";
3756 OS << " else if (NearMisses && EarlyPredicateNearMiss)\n";
3757 OS << " NearMisses->push_back(EarlyPredicateNearMiss);\n";
3758 OS << " else if (NearMisses && LatePredicateNearMiss)\n";
3759 OS << " NearMisses->push_back(LatePredicateNearMiss);\n";
3760 OS << "\n";
3761 OS << " continue;\n";
3762 OS << " } else if (NumNearMisses > 1) {\n";
3763 OS << " // This instruction missed in more than one way, so ignore it.\n";
Oliver Stannarde2711b82017-10-11 09:17:43 +00003764 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3765 OS << " \"types of mismatch, so not \"\n";
3766 OS << " \"reporting near-miss\\n\");\n";
Oliver Stannard13e36102017-10-03 09:33:12 +00003767 OS << " continue;\n";
3768 OS << " }\n";
3769 }
Jim Grosbach19cb7f42011-08-15 23:03:29 +00003770
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00003771 // Call the post-processing function, if used.
Craig Topper2a129872017-05-31 21:12:46 +00003772 StringRef InsnCleanupFn = AsmParser->getValueAsString("AsmParserInstCleanup");
Daniel Dunbar8cc9c0c2010-03-18 20:05:56 +00003773 if (!InsnCleanupFn.empty())
3774 OS << " " << InsnCleanupFn << "(Inst);\n";
3775
Joey Gouly715d98d2013-09-12 10:28:05 +00003776 if (HasDeprecation) {
3777 OS << " std::string Info;\n";
Weiming Zhao943496f2016-12-05 23:55:13 +00003778 OS << " if (!getParser().getTargetParser().\n";
3779 OS << " getTargetOptions().MCNoDeprecatedWarn &&\n";
3780 OS << " MII.get(Inst.getOpcode()).getDeprecatedInfo(Inst, getSTI(), Info)) {\n";
David Blaikiec50f9862014-06-08 16:18:35 +00003781 OS << " SMLoc Loc = ((" << Target.getName()
3782 << "Operand&)*Operands[0]).getStartLoc();\n";
Rafael Espindola92723052014-11-11 05:18:41 +00003783 OS << " getParser().Warning(Loc, Info, None);\n";
Joey Gouly715d98d2013-09-12 10:28:05 +00003784 OS << " }\n";
3785 }
3786
Sander de Smalen1d8ca3c2018-01-10 10:10:56 +00003787 if (!ReportMultipleNearMisses) {
Sander de Smalenb0c87382018-06-18 13:39:29 +00003788 OS << " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
3789 "Operands, ErrorInfo))\n";
Craig Topper57fd3bd2018-04-25 06:24:51 +00003790 OS << " return Match_InvalidTiedOperand;\n";
Sander de Smalen1d8ca3c2018-01-10 10:10:56 +00003791 OS << "\n";
3792 }
3793
Oliver Stannarde2711b82017-10-11 09:17:43 +00003794 OS << " DEBUG_WITH_TYPE(\n";
3795 OS << " \"asm-matcher\",\n";
3796 OS << " dbgs() << \"Opcode result: complete match, selecting this opcode\\n\");\n";
Chris Lattner79ed3f72010-09-06 19:22:17 +00003797 OS << " return Match_Success;\n";
Daniel Dunbara3741fa2009-08-08 07:50:56 +00003798 OS << " }\n\n";
3799
Oliver Stannard13e36102017-10-03 09:33:12 +00003800 if (ReportMultipleNearMisses) {
3801 OS << " // No instruction variants matched exactly.\n";
3802 OS << " return Match_NearMisses;\n";
3803 } else {
3804 OS << " // Okay, we had no match. Try to return a useful error code.\n";
3805 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n";
3806 OS << " return RetCode;\n\n";
3807 OS << " // Missing feature matches return which features were missing\n";
3808 OS << " ErrorInfo = MissingFeatures;\n";
3809 OS << " return Match_MissingFeature;\n";
3810 }
Daniel Dunbara027d222009-07-31 02:32:59 +00003811 OS << "}\n\n";
Jim Grosbacha7c78222010-10-29 22:13:48 +00003812
Alexander Kornienkob4c62672015-01-15 11:41:30 +00003813 if (!Info.OperandMatchInfo.empty())
Craig Topper3a364442012-09-18 07:02:21 +00003814 emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable,
Craig Topper5ef13492015-12-31 08:18:23 +00003815 MaxMnemonicIndex, HasMnemonicFirst);
Bruno Cardoso Lopese7a54522011-02-07 19:38:32 +00003816
Chris Lattner0692ee62010-09-06 19:11:01 +00003817 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
Craig Topper939e9702017-10-26 06:46:40 +00003818
3819 OS << "\n#ifdef GET_MNEMONIC_SPELL_CHECKER\n";
3820 OS << "#undef GET_MNEMONIC_SPELL_CHECKER\n\n";
3821
3822 emitMnemonicSpellChecker(OS, Target, VariantCount);
3823
3824 OS << "#endif // GET_MNEMONIC_SPELL_CHECKER\n\n";
Daniel Dunbard51ffcf2009-07-11 19:39:44 +00003825}
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +00003826
3827namespace llvm {
3828
3829void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
3830 emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
3831 AsmMatcherEmitter(RK).run(OS);
3832}
3833
Eugene Zelenko380d47d2016-02-02 18:20:45 +00003834} // end namespace llvm