1 //===- 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
11 // 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 // ---------------------------------------------------
16 //
17 // 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 ...)
27 // 'call' '*' %epc
28 //
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 //
70 // 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 //
75 // 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
80 // identifiers that need to be mapped to specific values in the final encoded
81 // 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
91 // present in the mask, a successful match occurs. Otherwise, fallback
92 // 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 //
97 //===----------------------------------------------------------------------===//
98
99 #include "CodeGenTarget.h"
100 #include "SubtargetFeatureInfo.h"
101 #include "Types.h"
102 #include "llvm/ADT/CachedHashString.h"
103 #include "llvm/ADT/PointerUnion.h"
104 #include "llvm/ADT/STLExtras.h"
105 #include "llvm/ADT/SmallPtrSet.h"
106 #include "llvm/ADT/SmallVector.h"
107 #include "llvm/ADT/StringExtras.h"
108 #include "llvm/Config/llvm-config.h"
109 #include "llvm/Support/CommandLine.h"
110 #include "llvm/Support/Debug.h"
111 #include "llvm/Support/ErrorHandling.h"
112 #include "llvm/TableGen/Error.h"
113 #include "llvm/TableGen/Record.h"
114 #include "llvm/TableGen/StringMatcher.h"
115 #include "llvm/TableGen/StringToOffsetTable.h"
116 #include "llvm/TableGen/TableGenBackend.h"
117 #include <cassert>
118 #include <cctype>
119 #include <forward_list>
120 #include <map>
121 #include <set>
122
123 using namespace llvm;
124
125 #define DEBUG_TYPE "asm-matcher-emitter"
126
127 cl::OptionCategory AsmMatcherEmitterCat("Options for -gen-asm-matcher");
128
129 static cl::opt<std::string>
130 MatchPrefix("match-prefix", cl::init(""),
131 cl::desc("Only match instructions with the given prefix"),
132 cl::cat(AsmMatcherEmitterCat));
133
134 namespace {
135 class AsmMatcherInfo;
136
137 // 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.
142 typedef std::set<Record*, LessRecordByID> RegisterSet;
143
144 class AsmMatcherEmitter {
145 RecordKeeper &Records;
146 public:
AsmMatcherEmitter(RecordKeeper & R)147 AsmMatcherEmitter(RecordKeeper &R) : Records(R) {}
148
149 void run(raw_ostream &o);
150 };
151
152 /// ClassInfo - Helper class for storing the information about a particular
153 /// class of operands which can be matched.
154 struct ClassInfo {
155 enum ClassInfoKind {
156 /// 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
169 };
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;
174
175 /// 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;
179
180 /// Name - The full class name, suitable for use in an enum.
181 std::string Name;
182
183 /// ClassName - The unadorned generic name for this class (e.g., Token).
184 std::string ClassName;
185
186 /// 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
192 /// operand matches this class; this is not valid for Token or register kinds.
193 std::string PredicateMethod;
194
195 /// RenderMethod - The name of the operand method to add this operand to an
196 /// MCInst; this is not valid for Token or register kinds.
197 std::string RenderMethod;
198
199 /// ParserMethod - The name of the operand method to do a target specific
200 /// parsing on the operand.
201 std::string ParserMethod;
202
203 /// For register classes: the records for all the registers in this class.
204 RegisterSet Registers;
205
206 /// For custom match classes: the diagnostic kind for when the predicate fails.
207 std::string DiagnosticType;
208
209 /// For custom match classes: the diagnostic string for when the predicate fails.
210 std::string DiagnosticString;
211
212 /// Is this operand optional and not always required.
213 bool IsOptional;
214
215 /// DefaultMethod - The name of the method that returns the default operand
216 /// for optional operand
217 std::string DefaultMethod;
218
219 public:
220 /// isRegisterClass() - Check if this is a register class.
isRegisterClass__anon02d6c29f0111::ClassInfo221 bool isRegisterClass() const {
222 return Kind >= RegisterClass0 && Kind < UserClass0;
223 }
224
225 /// isUserClass() - Check if this is a user defined class.
isUserClass__anon02d6c29f0111::ClassInfo226 bool isUserClass() const {
227 return Kind >= UserClass0;
228 }
229
230 /// isRelatedTo - Check whether this class is "related" to \p RHS. Classes
231 /// are related if they are in the same class hierarchy.
isRelatedTo__anon02d6c29f0111::ClassInfo232 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
237 // 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
243 RegisterSet Tmp;
244 std::insert_iterator<RegisterSet> II(Tmp, Tmp.begin());
245 std::set_intersection(Registers.begin(), Registers.end(),
246 RHS.Registers.begin(), RHS.Registers.end(),
247 II, LessRecordByID());
248
249 return !Tmp.empty();
250 }
251
252 // Otherwise we have two users operands; they are related if they are in the
253 // same class hierarchy.
254 //
255 // FIXME: This is an oversimplification, they should only be related if they
256 // intersect, however we don't have that information.
257 assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
258 const ClassInfo *Root = this;
259 while (!Root->SuperClasses.empty())
260 Root = Root->SuperClasses.front();
261
262 const ClassInfo *RHSRoot = &RHS;
263 while (!RHSRoot->SuperClasses.empty())
264 RHSRoot = RHSRoot->SuperClasses.front();
265
266 return Root == RHSRoot;
267 }
268
269 /// isSubsetOf - Test whether this class is a subset of \p RHS.
isSubsetOf__anon02d6c29f0111::ClassInfo270 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.
276 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)
282 return true;
283 for (auto *Super : CI->SuperClasses)
284 if (Visited.insert(Super).second)
285 Worklist.push_back(Super);
286 }
287
288 return false;
289 }
290
getTreeDepth__anon02d6c29f0111::ClassInfo291 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
findRoot__anon02d6c29f0111::ClassInfo301 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.
operator <__anon02d6c29f0111::ClassInfo311 bool operator<(const ClassInfo &RHS) const {
312 if (this == &RHS)
313 return false;
314
315 // 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)
319 return true;
320 assert(RHS.Kind == Token);
321 } else if (isRegisterClass()) {
322 if (RHS.Kind == Token)
323 return false;
324 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");
333 }
334
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;
364 }
365 };
366
367 class AsmVariantInfo {
368 public:
369 StringRef RegisterPrefix;
370 StringRef TokenizingCharacters;
371 StringRef SeparatorCharacters;
372 StringRef BreakCharacters;
373 StringRef Name;
374 int AsmVariantNo;
375 };
376
377 /// MatchableInfo - Helper class for storing the necessary information for an
378 /// instruction or alias which is capable of being matched.
379 struct MatchableInfo {
380 struct AsmOperand {
381 /// Token - This is the token that the operand came from.
382 StringRef Token;
383
384 /// The unique class instance this operand should match.
385 ClassInfo *Class;
386
387 /// The operand name this is, if anything.
388 StringRef SrcOpName;
389
390 /// The operand name this is, before renaming for tied operands.
391 StringRef OrigSrcOpName;
392
393 /// The suboperand index within SrcOpName, or -1 for the entire operand.
394 int SubOpIdx;
395
396 /// Whether the token is "isolated", i.e., it is preceded and followed
397 /// by separators.
398 bool IsIsolatedToken;
399
400 /// Register record if this token is singleton register.
401 Record *SingletonReg;
402
AsmOperand__anon02d6c29f0111::MatchableInfo::AsmOperand403 explicit AsmOperand(bool IsIsolatedToken, StringRef T)
404 : Token(T), Class(nullptr), SubOpIdx(-1),
405 IsIsolatedToken(IsIsolatedToken), SingletonReg(nullptr) {}
406 };
407
408 /// 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,
418
419 /// TiedOperand - This represents a result operand that is a duplicate of
420 /// a previous result operand.
421 TiedOperand,
422
423 /// ImmOperand - This represents an immediate value that is dumped into
424 /// the operand.
425 ImmOperand,
426
427 /// RegOperand - This represents a fixed register that is dumped in.
428 RegOperand
429 } Kind;
430
431 /// 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
440 union {
441 /// This is the operand # in the AsmOperands list that this should be
442 /// copied from.
443 unsigned AsmOperandNum;
444
445 /// Description of tied operands.
446 TiedOperandsTuple TiedOperands;
447
448 /// ImmVal - This is the immediate value added to the instruction.
449 int64_t ImmVal;
450
451 /// Register - This is the register record.
452 Record *Register;
453 };
454
455 /// MINumOperands - The number of MCInst operands populated by this
456 /// operand.
457 unsigned MINumOperands;
458
getRenderedOp__anon02d6c29f0111::MatchableInfo::ResOperand459 static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
460 ResOperand X;
461 X.Kind = RenderAsmOperand;
462 X.AsmOperandNum = AsmOpNum;
463 X.MINumOperands = NumOperands;
464 return X;
465 }
466
getTiedOp__anon02d6c29f0111::MatchableInfo::ResOperand467 static ResOperand getTiedOp(unsigned TiedOperandNum, unsigned SrcOperand1,
468 unsigned SrcOperand2) {
469 ResOperand X;
470 X.Kind = TiedOperand;
471 X.TiedOperands = { TiedOperandNum, SrcOperand1, SrcOperand2 };
472 X.MINumOperands = 1;
473 return X;
474 }
475
getImmOp__anon02d6c29f0111::MatchableInfo::ResOperand476 static ResOperand getImmOp(int64_t Val) {
477 ResOperand X;
478 X.Kind = ImmOperand;
479 X.ImmVal = Val;
480 X.MINumOperands = 1;
481 return X;
482 }
483
getRegOp__anon02d6c29f0111::MatchableInfo::ResOperand484 static ResOperand getRegOp(Record *Reg) {
485 ResOperand X;
486 X.Kind = RegOperand;
487 X.Register = Reg;
488 X.MINumOperands = 1;
489 return X;
490 }
491 };
492
493 /// AsmVariantID - Target's assembly syntax variant no.
494 int AsmVariantID;
495
496 /// AsmString - The assembly string for this instruction (with variants
497 /// removed), e.g. "movsx $src, $dst".
498 std::string AsmString;
499
500 /// TheDef - This is the definition of the instruction or InstAlias that this
501 /// matchable came from.
502 Record *const TheDef;
503
504 /// DefRec - This is the definition that it came from.
505 PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
506
getResultInst__anon02d6c29f0111::MatchableInfo507 const CodeGenInstruction *getResultInst() const {
508 if (DefRec.is<const CodeGenInstruction*>())
509 return DefRec.get<const CodeGenInstruction*>();
510 return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
511 }
512
513 /// ResOperands - This is the operand list that should be built for the result
514 /// MCInst.
515 SmallVector<ResOperand, 8> ResOperands;
516
517 /// Mnemonic - This is the first token of the matched instruction, its
518 /// mnemonic.
519 StringRef Mnemonic;
520
521 /// AsmOperands - The textual operands that this instruction matches,
522 /// 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.
525 SmallVector<AsmOperand, 8> AsmOperands;
526
527 /// Predicates - The required subtarget features to match this instruction.
528 SmallVector<const SubtargetFeatureInfo *, 4> RequiredFeatures;
529
530 /// ConversionFnKind - The enum value which is passed to the generated
531 /// convertToMCInst to convert parsed operands into an MCInst for this
532 /// function.
533 std::string ConversionFnKind;
534
535 /// If this instruction is deprecated in some form.
536 bool HasDeprecation;
537
538 /// 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
MatchableInfo__anon02d6c29f0111::MatchableInfo543 MatchableInfo(const CodeGenInstruction &CGI)
544 : AsmVariantID(0), AsmString(CGI.AsmString), TheDef(CGI.TheDef), DefRec(&CGI),
545 UseInstAsmMatchConverter(true) {
546 }
547
MatchableInfo__anon02d6c29f0111::MatchableInfo548 MatchableInfo(std::unique_ptr<const CodeGenInstAlias> Alias)
549 : AsmVariantID(0), AsmString(Alias->AsmString), TheDef(Alias->TheDef),
550 DefRec(Alias.release()),
551 UseInstAsmMatchConverter(
552 TheDef->getValueAsBit("UseInstAsmMatchConverter")) {
553 }
554
555 // 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.
MatchableInfo__anon02d6c29f0111::MatchableInfo558 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
~MatchableInfo__anon02d6c29f0111::MatchableInfo569 ~MatchableInfo() {
570 delete DefRec.dyn_cast<const CodeGenInstAlias*>();
571 }
572
573 // 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
577 void initialize(const AsmMatcherInfo &Info,
578 SmallPtrSetImpl<Record*> &SingletonRegisters,
579 AsmVariantInfo const &Variant,
580 bool HasMnemonicFirst);
581
582 /// validate - Return true if this matchable is a valid thing to match against
583 /// and perform a bunch of validity checking.
584 bool validate(StringRef CommentDelimiter, bool IsAlias) const;
585
586 /// findAsmOperand - Find the AsmOperand with the specified name and
587 /// suboperand index.
findAsmOperand__anon02d6c29f0111::MatchableInfo588 int findAsmOperand(StringRef N, int SubOpIdx) const {
589 auto I = find_if(AsmOperands, [&](const AsmOperand &Op) {
590 return Op.SrcOpName == N && Op.SubOpIdx == SubOpIdx;
591 });
592 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
593 }
594
595 /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
596 /// This does not check the suboperand index.
findAsmOperandNamed__anon02d6c29f0111::MatchableInfo597 int findAsmOperandNamed(StringRef N, int LastIdx = -1) const {
598 auto I = std::find_if(AsmOperands.begin() + LastIdx + 1, AsmOperands.end(),
599 [&](const AsmOperand &Op) { return Op.SrcOpName == N; });
600 return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
601 }
602
findAsmOperandOriginallyNamed__anon02d6c29f0111::MatchableInfo603 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
610 void buildInstructionResultOperands();
611 void buildAliasResultOperands(bool AliasConstraintsAreChecked);
612
613 /// operator< - Compare two matchables.
operator <__anon02d6c29f0111::MatchableInfo614 bool operator<(const MatchableInfo &RHS) const {
615 // The primary comparator is the instruction mnemonic.
616 if (int Cmp = Mnemonic.compare(RHS.Mnemonic))
617 return Cmp == -1;
618
619 if (AsmOperands.size() != RHS.AsmOperands.size())
620 return AsmOperands.size() < RHS.AsmOperands.size();
621
622 // Compare lexicographically by operand. The matcher validates that other
623 // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
624 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
625 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
626 return true;
627 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
628 return false;
629 }
630
631 // 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
640 return false;
641 }
642
643 /// couldMatchAmbiguouslyWith - Check whether this matchable could
644 /// ambiguously match the same set of operands as \p RHS (without being a
645 /// strictly superior match).
couldMatchAmbiguouslyWith__anon02d6c29f0111::MatchableInfo646 bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) const {
647 // The primary comparator is the instruction mnemonic.
648 if (Mnemonic != RHS.Mnemonic)
649 return false;
650
651 // Different variants can't conflict.
652 if (AsmVariantID != RHS.AsmVariantID)
653 return false;
654
655 // The number of operands is unambiguous.
656 if (AsmOperands.size() != RHS.AsmOperands.size())
657 return false;
658
659 // 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
663 // Tokens and operand kinds are unambiguous (assuming a correct target
664 // specific parser).
665 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)
670 return false;
671
672 // 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;
676 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
677 if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
678 HasLT = true;
679 if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
680 HasGT = true;
681 }
682
683 return HasLT == HasGT;
684 }
685
686 void dump() const;
687
688 private:
689 void tokenizeAsmString(AsmMatcherInfo const &Info,
690 AsmVariantInfo const &Variant);
691 void addAsmOperand(StringRef Token, bool IsIsolatedToken = false);
692 };
693
694 struct OperandMatchEntry {
695 unsigned OperandMask;
696 const MatchableInfo* MI;
697 ClassInfo *CI;
698
create__anon02d6c29f0111::OperandMatchEntry699 static OperandMatchEntry create(const MatchableInfo *mi, ClassInfo *ci,
700 unsigned opMask) {
701 OperandMatchEntry X;
702 X.OperandMask = opMask;
703 X.CI = ci;
704 X.MI = mi;
705 return X;
706 }
707 };
708
709 class AsmMatcherInfo {
710 public:
711 /// Tracked Records
712 RecordKeeper &Records;
713
714 /// The tablegen AsmParser record.
715 Record *AsmParser;
716
717 /// Target - The target information.
718 CodeGenTarget &Target;
719
720 /// The classes which are needed for matching.
721 std::forward_list<ClassInfo> Classes;
722
723 /// The information on the matchables to match.
724 std::vector<std::unique_ptr<MatchableInfo>> Matchables;
725
726 /// Info for custom matching operands by user defined methods.
727 std::vector<OperandMatchEntry> OperandMatchInfo;
728
729 /// Map of Register records to their class information.
730 typedef std::map<Record*, ClassInfo*, LessRecordByID> RegisterClassesTy;
731 RegisterClassesTy RegisterClasses;
732
733 /// Map of Predicate records to their subtarget information.
734 std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures;
735
736 /// Map of AsmOperandClass records to their class information.
737 std::map<Record*, ClassInfo*> AsmOperandClasses;
738
739 /// Map of RegisterClass records to their class information.
740 std::map<Record*, ClassInfo*> RegisterClassClasses;
741
742 private:
743 /// Map of token to class information which has already been constructed.
744 std::map<std::string, ClassInfo*> TokenClasses;
745
746 private:
747 /// getTokenClass - Lookup or create the class for the given token.
748 ClassInfo *getTokenClass(StringRef Token);
749
750 /// getOperandClass - Lookup or create the class for the given operand.
751 ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
752 int SubOpIdx);
753 ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
754
755 /// buildRegisterClasses - Build the ClassInfo* instances for register
756 /// classes.
757 void buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters);
758
759 /// buildOperandClasses - Build the ClassInfo* instances for user defined
760 /// operand classes.
761 void buildOperandClasses();
762
763 void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
764 unsigned AsmOpIdx);
765 void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
766 MatchableInfo::AsmOperand &Op);
767
768 public:
769 AsmMatcherInfo(Record *AsmParser,
770 CodeGenTarget &Target,
771 RecordKeeper &Records);
772
773 /// Construct the various tables used during matching.
774 void buildInfo();
775
776 /// buildOperandMatchInfo - Build the necessary information to handle user
777 /// defined operand parsing methods.
778 void buildOperandMatchInfo();
779
780 /// getSubtargetFeature - Lookup or create the subtarget feature info for the
781 /// given operand.
getSubtargetFeature(Record * Def) const782 const SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
783 assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
784 const auto &I = SubtargetFeatures.find(Def);
785 return I == SubtargetFeatures.end() ? nullptr : &I->second;
786 }
787
getRecords() const788 RecordKeeper &getRecords() const {
789 return Records;
790 }
791
hasOptionalOperands() const792 bool hasOptionalOperands() const {
793 return find_if(Classes, [](const ClassInfo &Class) {
794 return Class.IsOptional;
795 }) != Classes.end();
796 }
797 };
798
799 } // end anonymous namespace
800
801 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const802 LLVM_DUMP_METHOD void MatchableInfo::dump() const {
803 errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
804
805 errs() << " variant: " << AsmVariantID << "\n";
806
807 for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
808 const AsmOperand &Op = AsmOperands[i];
809 errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
810 errs() << '\"' << Op.Token << "\"\n";
811 }
812 }
813 #endif
814
815 static std::pair<StringRef, StringRef>
parseTwoOperandConstraint(StringRef S,ArrayRef<SMLoc> Loc)816 parseTwoOperandConstraint(StringRef S, ArrayRef<SMLoc> Loc) {
817 // Split via the '='.
818 std::pair<StringRef, StringRef> Ops = S.split('=');
819 if (Ops.second == "")
820 PrintFatalError(Loc, "missing '=' in two-operand alias constraint");
821 // Trim whitespace and the leading '$' on the operand names.
822 size_t start = Ops.first.find_first_of('$');
823 if (start == std::string::npos)
824 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
825 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)
831 PrintFatalError(Loc, "expected '$' prefix on asm operand name");
832 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
formTwoOperandAlias(StringRef Constraint)838 void 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)
847 PrintFatalError(TheDef->getLoc(),
848 "unknown source two-operand alias operand '" + Ops.first +
849 "'.");
850 if (DstAsmOperand == -1)
851 PrintFatalError(TheDef->getLoc(),
852 "unknown destination two-operand alias operand '" +
853 Ops.second + "'.");
854
855 // Find the ResOperand that refers to the operand we're aliasing away
856 // and update it to refer to the combined operand instead.
857 for (ResOperand &Op : ResOperands) {
858 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.
868 for (ResOperand &Op : ResOperands) {
869 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;
877 }
878 }
879 }
880
881 /// extractSingletonRegisterForAsmOperand - Extract singleton register,
882 /// if present, from specified token.
883 static void
extractSingletonRegisterForAsmOperand(MatchableInfo::AsmOperand & Op,const AsmMatcherInfo & Info,StringRef RegisterPrefix)884 extractSingletonRegisterForAsmOperand(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.
910 }
911
initialize(const AsmMatcherInfo & Info,SmallPtrSetImpl<Record * > & SingletonRegisters,AsmVariantInfo const & Variant,bool HasMnemonicFirst)912 void MatchableInfo::initialize(const AsmMatcherInfo &Info,
913 SmallPtrSetImpl<Record*> &SingletonRegisters,
914 AsmVariantInfo const &Variant,
915 bool HasMnemonicFirst) {
916 AsmVariantID = Variant.AsmVariantNo;
917 AsmString =
918 CodeGenInstruction::FlattenAsmStringVariants(AsmString,
919 Variant.AsmVariantNo);
920
921 tokenizeAsmString(Info, Variant);
922
923 // 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
941 // Compute the require features.
942 for (Record *Predicate : TheDef->getValueAsListOfDefs("Predicates"))
943 if (const SubtargetFeatureInfo *Feature =
944 Info.getSubtargetFeature(Predicate))
945 RequiredFeatures.push_back(Feature);
946
947 // Collect singleton registers, if used.
948 for (MatchableInfo::AsmOperand &Op : AsmOperands) {
949 extractSingletonRegisterForAsmOperand(Op, Info, Variant.RegisterPrefix);
950 if (Record *Reg = Op.SingletonReg)
951 SingletonRegisters.insert(Reg);
952 }
953
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;
960 }
961
962 /// Append an AsmOperand for the given substring of AsmString.
addAsmOperand(StringRef Token,bool IsIsolatedToken)963 void MatchableInfo::addAsmOperand(StringRef Token, bool IsIsolatedToken) {
964 AsmOperands.push_back(AsmOperand(IsIsolatedToken, Token));
965 }
966
967 /// tokenizeAsmString - Tokenize a simplified assembly string.
tokenizeAsmString(const AsmMatcherInfo & Info,AsmVariantInfo const & Variant)968 void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info,
969 AsmVariantInfo const &Variant) {
970 StringRef String = AsmString;
971 size_t Prev = 0;
972 bool InTok = false;
973 bool IsIsolatedToken = true;
974 for (size_t i = 0, e = String.size(); i != e; ++i) {
975 char Char = String[i];
976 if (Variant.BreakCharacters.find(Char) != std::string::npos) {
977 if (InTok) {
978 addAsmOperand(String.slice(Prev, i), false);
979 Prev = i;
980 IsIsolatedToken = false;
981 }
982 InTok = true;
983 continue;
984 }
985 if (Variant.TokenizingCharacters.find(Char) != std::string::npos) {
986 if (InTok) {
987 addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
988 InTok = false;
989 IsIsolatedToken = false;
990 }
991 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
992 Prev = i + 1;
993 IsIsolatedToken = true;
994 continue;
995 }
996 if (Variant.SeparatorCharacters.find(Char) != std::string::npos) {
997 if (InTok) {
998 addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
999 InTok = false;
1000 }
1001 Prev = i + 1;
1002 IsIsolatedToken = true;
1003 continue;
1004 }
1005
1006 switch (Char) {
1007 case '\\':
1008 if (InTok) {
1009 addAsmOperand(String.slice(Prev, i), false);
1010 InTok = false;
1011 IsIsolatedToken = false;
1012 }
1013 ++i;
1014 assert(i != String.size() && "Invalid quoted character");
1015 addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
1016 Prev = i + 1;
1017 IsIsolatedToken = false;
1018 break;
1019
1020 case '$': {
1021 if (InTok) {
1022 addAsmOperand(String.slice(Prev, i), false);
1023 InTok = false;
1024 IsIsolatedToken = false;
1025 }
1026
1027 // If this isn't "${", start new identifier looking like "$xxx"
1028 if (i + 1 == String.size() || String[i + 1] != '{') {
1029 Prev = i;
1030 break;
1031 }
1032
1033 size_t EndPos = String.find('}', i);
1034 assert(EndPos != StringRef::npos &&
1035 "Missing brace in operand reference!");
1036 addAsmOperand(String.slice(i, EndPos+1), IsIsolatedToken);
1037 Prev = EndPos + 1;
1038 i = EndPos;
1039 IsIsolatedToken = false;
1040 break;
1041 }
1042
1043 default:
1044 InTok = true;
1045 break;
1046 }
1047 }
1048 if (InTok && Prev != String.size())
1049 addAsmOperand(String.substr(Prev), IsIsolatedToken);
1050 }
1051
validate(StringRef CommentDelimiter,bool IsAlias) const1052 bool MatchableInfo::validate(StringRef CommentDelimiter, bool IsAlias) const {
1053 // Reject matchables with no .s string.
1054 if (AsmString.empty())
1055 PrintFatalError(TheDef->getLoc(), "instruction with empty asm string");
1056
1057 // Reject any matchables with a newline in them, they should be marked
1058 // isCodeGenOnly if they are pseudo instructions.
1059 if (AsmString.find('\n') != std::string::npos)
1060 PrintFatalError(TheDef->getLoc(),
1061 "multiline instruction is not valid for the asmparser, "
1062 "mark it isCodeGenOnly");
1063
1064 // 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)
1068 PrintFatalError(TheDef->getLoc(),
1069 "asmstring for instruction has comment character in it, "
1070 "mark it isCodeGenOnly");
1071
1072 // Reject matchables with operand modifiers, these aren't something we can
1073 // handle, the target should be refactored to use operands instead of
1074 // modifiers.
1075 //
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;
1079 for (const AsmOperand &Op : AsmOperands) {
1080 StringRef Tok = Op.Token;
1081 if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
1082 PrintFatalError(TheDef->getLoc(),
1083 "matchable with operand modifier '" + Tok +
1084 "' not supported by asm matcher. Mark isCodeGenOnly!");
1085 // Verify that any operand is only mentioned once.
1086 // We reject aliases and ignore instructions for now.
1087 if (!IsAlias && Tok[0] == '$' && !OperandNames.insert(Tok).second) {
1088 LLVM_DEBUG({
1089 errs() << "warning: '" << TheDef->getName() << "': "
1090 << "ignoring instruction with tied operand '"
1091 << Tok << "'\n";
1092 });
1093 return false;
1094 }
1095 }
1096
1097 return true;
1098 }
1099
getEnumNameForToken(StringRef Str)1100 static std::string getEnumNameForToken(StringRef Str) {
1101 std::string Res;
1102
1103 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;
1108 case '!': Res += "_EXCLAIM_"; break;
1109 case '.': Res += "_DOT_"; break;
1110 case '<': Res += "_LT_"; break;
1111 case '>': Res += "_GT_"; break;
1112 case '-': Res += "_MINUS_"; break;
1113 default:
1114 if ((*it >= 'A' && *it <= 'Z') ||
1115 (*it >= 'a' && *it <= 'z') ||
1116 (*it >= '0' && *it <= '9'))
1117 Res += *it;
1118 else
1119 Res += "_" + utostr((unsigned) *it) + "_";
1120 }
1121 }
1122
1123 return Res;
1124 }
1125
getTokenClass(StringRef Token)1126 ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
1127 ClassInfo *&Entry = TokenClasses[Token];
1128
1129 if (!Entry) {
1130 Classes.emplace_front();
1131 Entry = &Classes.front();
1132 Entry->Kind = ClassInfo::Token;
1133 Entry->ClassName = "Token";
1134 Entry->Name = "MCK_" + getEnumNameForToken(Token);
1135 Entry->ValueName = Token;
1136 Entry->PredicateMethod = "<invalid>";
1137 Entry->RenderMethod = "<invalid>";
1138 Entry->ParserMethod = "";
1139 Entry->DiagnosticType = "";
1140 Entry->IsOptional = false;
1141 Entry->DefaultMethod = "<invalid>";
1142 }
1143
1144 return Entry;
1145 }
1146
1147 ClassInfo *
getOperandClass(const CGIOperandList::OperandInfo & OI,int SubOpIdx)1148 AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
1149 int SubOpIdx) {
1150 Record *Rec = OI.Rec;
1151 if (SubOpIdx != -1)
1152 Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
1153 return getOperandClass(Rec, SubOpIdx);
1154 }
1155
1156 ClassInfo *
getOperandClass(Record * Rec,int SubOpIdx)1157 AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
1158 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");
1162 if (!R || !R->getValue())
1163 PrintFatalError("Record `" + Rec->getName() +
1164 "' does not have a ParserMatchClass!\n");
1165
1166 if (DefInit *DI= dyn_cast<DefInit>(R->getValue())) {
1167 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)
1175 PrintFatalError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
1176 "' has no associated register class!\n");
1177 if (ClassInfo *CI = RegisterClassClasses[ClassRec])
1178 return CI;
1179 PrintFatalError(Rec->getLoc(), "register class has no class info!");
1180 }
1181
1182 if (Rec->isSubClassOf("RegisterClass")) {
1183 if (ClassInfo *CI = RegisterClassClasses[Rec])
1184 return CI;
1185 PrintFatalError(Rec->getLoc(), "register class has no class info!");
1186 }
1187
1188 if (!Rec->isSubClassOf("Operand"))
1189 PrintFatalError(Rec->getLoc(), "Operand `" + Rec->getName() +
1190 "' does not derive from class Operand!\n");
1191 Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
1192 if (ClassInfo *CI = AsmOperandClasses[MatchClass])
1193 return CI;
1194
1195 PrintFatalError(Rec->getLoc(), "operand has no match class!");
1196 }
1197
1198 struct LessRegisterSet {
operator ()LessRegisterSet1199 bool operator() (const RegisterSet &LHS, const RegisterSet & RHS) const {
1200 // 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
1210 void AsmMatcherInfo::
buildRegisterClasses(SmallPtrSetImpl<Record * > & SingletonRegisters)1211 buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters) {
1212 const auto &Registers = Target.getRegBank().getRegisters();
1213 auto &RegClassList = Target.getRegBank().getRegClasses();
1214
1215 typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet;
1216
1217 // The register sets used for matching.
1218 RegisterSetSet RegisterSets;
1219
1220 // Gather the defined sets.
1221 for (const CodeGenRegisterClass &RC : RegClassList)
1222 RegisterSets.insert(
1223 RegisterSet(RC.getOrder().begin(), RC.getOrder().end()));
1224
1225 // Add any required singleton sets.
1226 for (Record *Rec : SingletonRegisters) {
1227 RegisterSets.insert(RegisterSet(&Rec, &Rec + 1));
1228 }
1229
1230 // 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.
1233 std::map<Record*, RegisterSet> RegisterMap;
1234 for (const CodeGenRegister &CGR : Registers) {
1235 // Compute the intersection of all sets containing this register.
1236 RegisterSet ContainingSet;
1237
1238 for (const RegisterSet &RS : RegisterSets) {
1239 if (!RS.count(CGR.TheDef))
1240 continue;
1241
1242 if (ContainingSet.empty()) {
1243 ContainingSet = RS;
1244 continue;
1245 }
1246
1247 RegisterSet Tmp;
1248 std::swap(Tmp, ContainingSet);
1249 std::insert_iterator<RegisterSet> II(ContainingSet,
1250 ContainingSet.begin());
1251 std::set_intersection(Tmp.begin(), Tmp.end(), RS.begin(), RS.end(), II,
1252 LessRecordByID());
1253 }
1254
1255 if (!ContainingSet.empty()) {
1256 RegisterSets.insert(ContainingSet);
1257 RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
1258 }
1259 }
1260
1261 // Construct the register classes.
1262 std::map<RegisterSet, ClassInfo*, LessRegisterSet> RegisterSetClasses;
1263 unsigned Index = 0;
1264 for (const RegisterSet &RS : RegisterSets) {
1265 Classes.emplace_front();
1266 ClassInfo *CI = &Classes.front();
1267 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";
1273 CI->Registers = RS;
1274 // FIXME: diagnostic type.
1275 CI->DiagnosticType = "";
1276 CI->IsOptional = false;
1277 CI->DefaultMethod = ""; // unused
1278 RegisterSetClasses.insert(std::make_pair(RS, CI));
1279 ++Index;
1280 }
1281
1282 // Find the superclasses; we could compute only the subgroup lattice edges,
1283 // but there isn't really a point.
1284 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(),
1289 LessRecordByID()))
1290 CI->SuperClasses.push_back(RegisterSetClasses[RS2]);
1291 }
1292
1293 // Name the register classes which correspond to a user defined RegisterClass.
1294 for (const CodeGenRegisterClass &RC : RegClassList) {
1295 // Def will be NULL for non-user defined register classes.
1296 Record *Def = RC.getDef();
1297 if (!Def)
1298 continue;
1299 ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(),
1300 RC.getOrder().end())];
1301 if (CI->ValueName.empty()) {
1302 CI->ClassName = RC.getName();
1303 CI->Name = "MCK_" + RC.getName();
1304 CI->ValueName = RC.getName();
1305 } else
1306 CI->ValueName = CI->ValueName + "," + RC.getName();
1307
1308 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
1321 RegisterClassClasses.insert(std::make_pair(Def, CI));
1322 }
1323
1324 // Populate the map for individual registers.
1325 for (std::map<Record*, RegisterSet>::iterator it = RegisterMap.begin(),
1326 ie = RegisterMap.end(); it != ie; ++it)
1327 RegisterClasses[it->first] = RegisterSetClasses[it->second];
1328
1329 // Name the register classes which correspond to singleton registers.
1330 for (Record *Rec : SingletonRegisters) {
1331 ClassInfo *CI = RegisterClasses[Rec];
1332 assert(CI && "Missing singleton register class info!");
1333
1334 if (CI->ValueName.empty()) {
1335 CI->ClassName = Rec->getName();
1336 CI->Name = "MCK_" + Rec->getName().str();
1337 CI->ValueName = Rec->getName();
1338 } else
1339 CI->ValueName = CI->ValueName + "," + Rec->getName().str();
1340 }
1341 }
1342
buildOperandClasses()1343 void AsmMatcherInfo::buildOperandClasses() {
1344 std::vector<Record*> AsmOperands =
1345 Records.getAllDerivedDefinitions("AsmOperandClass");
1346
1347 // Pre-populate AsmOperandClasses map.
1348 for (Record *Rec : AsmOperands) {
1349 Classes.emplace_front();
1350 AsmOperandClasses[Rec] = &Classes.front();
1351 }
1352
1353 unsigned Index = 0;
1354 for (Record *Rec : AsmOperands) {
1355 ClassInfo *CI = AsmOperandClasses[Rec];
1356 CI->Kind = ClassInfo::UserClass0 + Index;
1357
1358 ListInit *Supers = Rec->getValueAsListInit("SuperClasses");
1359 for (Init *I : Supers->getValues()) {
1360 DefInit *DI = dyn_cast<DefInit>(I);
1361 if (!DI) {
1362 PrintError(Rec->getLoc(), "Invalid super class reference!");
1363 continue;
1364 }
1365
1366 ClassInfo *SC = AsmOperandClasses[DI->getDef()];
1367 if (!SC)
1368 PrintError(Rec->getLoc(), "Invalid super class reference!");
1369 else
1370 CI->SuperClasses.push_back(SC);
1371 }
1372 CI->ClassName = Rec->getValueAsString("Name");
1373 CI->Name = "MCK_" + CI->ClassName;
1374 CI->ValueName = Rec->getName();
1375
1376 // Get or construct the predicate method name.
1377 Init *PMName = Rec->getValueInit("PredicateMethod");
1378 if (StringInit *SI = dyn_cast<StringInit>(PMName)) {
1379 CI->PredicateMethod = SI->getValue();
1380 } else {
1381 assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!");
1382 CI->PredicateMethod = "is" + CI->ClassName;
1383 }
1384
1385 // Get or construct the render method name.
1386 Init *RMName = Rec->getValueInit("RenderMethod");
1387 if (StringInit *SI = dyn_cast<StringInit>(RMName)) {
1388 CI->RenderMethod = SI->getValue();
1389 } else {
1390 assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!");
1391 CI->RenderMethod = "add" + CI->ClassName + "Operands";
1392 }
1393
1394 // Get the parse method name or leave it as empty.
1395 Init *PRMName = Rec->getValueInit("ParserMethod");
1396 if (StringInit *SI = dyn_cast<StringInit>(PRMName))
1397 CI->ParserMethod = SI->getValue();
1398
1399 // Get the diagnostic type and string or leave them as empty.
1400 Init *DiagnosticType = Rec->getValueInit("DiagnosticType");
1401 if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
1402 CI->DiagnosticType = SI->getValue();
1403 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;
1410
1411 Init *IsOptional = Rec->getValueInit("IsOptional");
1412 if (BitInit *BI = dyn_cast<BitInit>(IsOptional))
1413 CI->IsOptional = BI->getValue();
1414
1415 // 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
1424 ++Index;
1425 }
1426 }
1427
AsmMatcherInfo(Record * asmParser,CodeGenTarget & target,RecordKeeper & records)1428 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
1429 CodeGenTarget &target,
1430 RecordKeeper &records)
1431 : Records(records), AsmParser(asmParser), Target(target) {
1432 }
1433
1434 /// buildOperandMatchInfo - Build the necessary information to handle user
1435 /// defined operand parsing methods.
buildOperandMatchInfo()1436 void AsmMatcherInfo::buildOperandMatchInfo() {
1437
1438 /// Map containing a mask with all operands indices that can be found for
1439 /// that class inside a instruction.
1440 typedef std::map<ClassInfo *, unsigned, less_ptr<ClassInfo>> OpClassMaskTy;
1441 OpClassMaskTy OpClassMask;
1442
1443 for (const auto &MI : Matchables) {
1444 OpClassMask.clear();
1445
1446 // Keep track of all operands of this instructions which belong to the
1447 // same class.
1448 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
1449 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
1450 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.
1457 for (const auto &OCM : OpClassMask) {
1458 unsigned OpMask = OCM.second;
1459 ClassInfo *CI = OCM.first;
1460 OperandMatchInfo.push_back(OperandMatchEntry::create(MI.get(), CI,
1461 OpMask));
1462 }
1463 }
1464 }
1465
buildInfo()1466 void AsmMatcherInfo::buildInfo() {
1467 // Build information about all of the AssemblerPredicates.
1468 const std::vector<std::pair<Record *, SubtargetFeatureInfo>>
1469 &SubtargetFeaturePairs = SubtargetFeatureInfo::getAll(Records);
1470 SubtargetFeatures.insert(SubtargetFeaturePairs.begin(),
1471 SubtargetFeaturePairs.end());
1472 #ifndef NDEBUG
1473 for (const auto &Pair : SubtargetFeatures)
1474 LLVM_DEBUG(Pair.second.dump());
1475 #endif // NDEBUG
1476 assert(SubtargetFeatures.size() <= 64 && "Too many subtarget features!");
1477
1478 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
1479 bool ReportMultipleNearMisses =
1480 AsmParser->getValueAsBit("ReportMultipleNearMisses");
1481
1482 // Parse the instructions; we need to do this first so that we can gather the
1483 // singleton register classes.
1484 SmallPtrSet<Record*, 16> SingletonRegisters;
1485 unsigned VariantCount = Target.getAsmParserVariantCount();
1486 for (unsigned VC = 0; VC != VariantCount; ++VC) {
1487 Record *AsmVariant = Target.getAsmParserVariant(VC);
1488 StringRef CommentDelimiter =
1489 AsmVariant->getValueAsString("CommentDelimiter");
1490 AsmVariantInfo Variant;
1491 Variant.RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
1492 Variant.TokenizingCharacters =
1493 AsmVariant->getValueAsString("TokenizingCharacters");
1494 Variant.SeparatorCharacters =
1495 AsmVariant->getValueAsString("SeparatorCharacters");
1496 Variant.BreakCharacters =
1497 AsmVariant->getValueAsString("BreakCharacters");
1498 Variant.Name = AsmVariant->getValueAsString("Name");
1499 Variant.AsmVariantNo = AsmVariant->getValueAsInt("Variant");
1500
1501 for (const CodeGenInstruction *CGI : Target.getInstructionsByEnumValue()) {
1502
1503 // If the tblgen -match-prefix option is specified (for tblgen hackers),
1504 // filter the set of instructions we consider.
1505 if (!StringRef(CGI->TheDef->getName()).startswith(MatchPrefix))
1506 continue;
1507
1508 // Ignore "codegen only" instructions.
1509 if (CGI->TheDef->getValueAsBit("isCodeGenOnly"))
1510 continue;
1511
1512 // Ignore instructions for different instructions
1513 StringRef V = CGI->TheDef->getValueAsString("AsmVariantName");
1514 if (!V.empty() && V != Variant.Name)
1515 continue;
1516
1517 auto II = llvm::make_unique<MatchableInfo>(*CGI);
1518
1519 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
1520
1521 // Ignore instructions which shouldn't be matched and diagnose invalid
1522 // instruction definitions with an error.
1523 if (!II->validate(CommentDelimiter, false))
1524 continue;
1525
1526 Matchables.push_back(std::move(II));
1527 }
1528
1529 // 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) {
1534 auto Alias = llvm::make_unique<CodeGenInstAlias>(AllInstAliases[i],
1535 Target);
1536
1537 // 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.
1540 if (!StringRef(Alias->ResultInst->TheDef->getName())
1541 .startswith( MatchPrefix))
1542 continue;
1543
1544 StringRef V = Alias->TheDef->getValueAsString("AsmVariantName");
1545 if (!V.empty() && V != Variant.Name)
1546 continue;
1547
1548 auto II = llvm::make_unique<MatchableInfo>(std::move(Alias));
1549
1550 II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
1551
1552 // Validate the alias definitions.
1553 II->validate(CommentDelimiter, true);
1554
1555 Matchables.push_back(std::move(II));
1556 }
1557 }
1558
1559 // Build info for the register classes.
1560 buildRegisterClasses(SingletonRegisters);
1561
1562 // Build info for the user defined assembly operand classes.
1563 buildOperandClasses();
1564
1565 // Build the information about matchables, now that we have fully formed
1566 // classes.
1567 std::vector<std::unique_ptr<MatchableInfo>> NewMatchables;
1568 for (auto &II : Matchables) {
1569 // Parse the tokens after the mnemonic.
1570 // Note: buildInstructionOperandReference may insert new AsmOperands, so
1571 // don't precompute the loop bound.
1572 for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
1573 MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
1574 StringRef Token = Op.Token;
1575
1576 // Check for singleton registers.
1577 if (Record *RegRecord = Op.SingletonReg) {
1578 Op.Class = RegisterClasses[RegRecord];
1579 assert(Op.Class && Op.Class->Registers.size() == 1 &&
1580 "Unexpected class for singleton register");
1581 continue;
1582 }
1583
1584 // Check for simple tokens.
1585 if (Token[0] != '$') {
1586 Op.Class = getTokenClass(Token);
1587 continue;
1588 }
1589
1590 if (Token.size() > 1 && isdigit(Token[1])) {
1591 Op.Class = getTokenClass(Token);
1592 continue;
1593 }
1594
1595 // Otherwise this is an operand reference.
1596 StringRef OperandName;
1597 if (Token[1] == '{')
1598 OperandName = Token.substr(2, Token.size() - 3);
1599 else
1600 OperandName = Token.substr(1);
1601
1602 if (II->DefRec.is<const CodeGenInstruction*>())
1603 buildInstructionOperandReference(II.get(), OperandName, i);
1604 else
1605 buildAliasOperandReference(II.get(), OperandName, Op);
1606 }
1607
1608 if (II->DefRec.is<const CodeGenInstruction*>()) {
1609 II->buildInstructionResultOperands();
1610 // 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.
1613 StringRef Constraint =
1614 II->TheDef->getValueAsString("TwoOperandAliasConstraint");
1615 if (Constraint != "") {
1616 // Start by making a copy of the original matchable.
1617 auto AliasII = llvm::make_unique<MatchableInfo>(*II);
1618
1619 // Adjust it to be a two-operand alias.
1620 AliasII->formTwoOperandAlias(Constraint);
1621
1622 // Add the alias to the matchables list.
1623 NewMatchables.push_back(std::move(AliasII));
1624 }
1625 } else
1626 // 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);
1632 }
1633 if (!NewMatchables.empty())
1634 Matchables.insert(Matchables.end(),
1635 std::make_move_iterator(NewMatchables.begin()),
1636 std::make_move_iterator(NewMatchables.end()));
1637
1638 // Process token alias definitions and set up the associated superclass
1639 // information.
1640 std::vector<Record*> AllTokenAliases =
1641 Records.getAllDerivedDefinitions("TokenAlias");
1642 for (Record *Rec : AllTokenAliases) {
1643 ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
1644 ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
1645 if (FromClass == ToClass)
1646 PrintFatalError(Rec->getLoc(),
1647 "error: Destination value identical to source value.");
1648 FromClass->SuperClasses.push_back(ToClass);
1649 }
1650
1651 // Reorder classes so that classes precede super classes.
1652 Classes.sort();
1653
1654 #ifdef EXPENSIVE_CHECKS
1655 // Verify that the table is sorted and operator < works transitively.
1656 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 }
1662 #endif
1663 }
1664
1665 /// buildInstructionOperandReference - The specified operand is a reference to a
1666 /// named operand such as $src. Resolve the Class and OperandInfo pointers.
1667 void AsmMatcherInfo::
buildInstructionOperandReference(MatchableInfo * II,StringRef OperandName,unsigned AsmOpIdx)1668 buildInstructionOperandReference(MatchableInfo *II,
1669 StringRef OperandName,
1670 unsigned AsmOpIdx) {
1671 const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
1672 const CGIOperandList &Operands = CGI.Operands;
1673 MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
1674
1675 // Map this token to an operand.
1676 unsigned Idx;
1677 if (!Operands.hasOperandNamed(OperandName, Idx))
1678 PrintFatalError(II->TheDef->getLoc(),
1679 "error: unable to find operand: '" + OperandName + "'");
1680
1681 // 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) {
1692 MatchableInfo::AsmOperand NewAsmOp(/*IsIsolatedToken=*/true, Token);
1693 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
1702 // Set up the operand class.
1703 Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
1704 Op->OrigSrcOpName = OperandName;
1705
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.
1714 int OITied = -1;
1715 if (Operands[Idx].MINumOperands == 1)
1716 OITied = Operands[Idx].getTiedRegister();
1717 if (OITied != -1) {
1718 // The tied operand index is an MIOperand index, find the operand that
1719 // contains it.
1720 std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
1721 OperandName = Operands[Idx.first].Name;
1722 Op->SubOpIdx = Idx.second;
1723 }
1724
1725 Op->SrcOpName = OperandName;
1726 }
1727
1728 /// buildAliasOperandReference - When parsing an operand reference out of the
1729 /// 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.
buildAliasOperandReference(MatchableInfo * II,StringRef OperandName,MatchableInfo::AsmOperand & Op)1731 void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
1732 StringRef OperandName,
1733 MatchableInfo::AsmOperand &Op) {
1734 const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
1735
1736 // Set up the operand class.
1737 for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
1738 if (CGA.ResultOperands[i].isRecord() &&
1739 CGA.ResultOperands[i].getName() == OperandName) {
1740 // 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.
1742 Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
1743 // 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(),
1747 Op.SubOpIdx);
1748 Op.SrcOpName = OperandName;
1749 Op.OrigSrcOpName = OperandName;
1750 return;
1751 }
1752
1753 PrintFatalError(II->TheDef->getLoc(),
1754 "error: unable to find operand: '" + OperandName + "'");
1755 }
1756
buildInstructionResultOperands()1757 void MatchableInfo::buildInstructionResultOperands() {
1758 const CodeGenInstruction *ResultInst = getResultInst();
1759
1760 // Loop over all operands of the result instruction, determining how to
1761 // populate them.
1762 for (const CGIOperandList::OperandInfo &OpInfo : ResultInst->Operands) {
1763 // If this is a tied operand, just copy from the previously handled operand.
1764 int TiedOp = -1;
1765 if (OpInfo.MINumOperands == 1)
1766 TiedOp = OpInfo.getTiedRegister();
1767 if (TiedOp != -1) {
1768 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));
1775 continue;
1776 }
1777
1778 int SrcOperand = findAsmOperandNamed(OpInfo.Name);
1779 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 }
1788
1789 // 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));
1793 continue;
1794 }
1795
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 }
1803 }
1804 }
1805
buildAliasResultOperands(bool AliasConstraintsAreChecked)1806 void MatchableInfo::buildAliasResultOperands(bool AliasConstraintsAreChecked) {
1807 const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
1808 const CodeGenInstruction *ResultInst = getResultInst();
1809
1810 // 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
1816 // Loop over all operands of the result instruction, determining how to
1817 // populate them.
1818 unsigned AliasOpNo = 0;
1819 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
1820 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
1821 const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
1822
1823 // If this is a tied operand, just copy from the previously handled operand.
1824 int TiedOp = -1;
1825 if (OpInfo->MINumOperands == 1)
1826 TiedOp = OpInfo->getTiedRegister();
1827 if (TiedOp != -1) {
1828 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
1852 // 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 }
1868 }
1869
1870 // 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) {
1879 case CodeGenInstAlias::ResultOperand::K_Record: {
1880 StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
1881 int SrcOperand = findAsmOperand(Name, SubIdx);
1882 if (SrcOperand == -1)
1883 PrintFatalError(TheDef->getLoc(), "Instruction '" +
1884 TheDef->getName() + "' has operand '" + OpName +
1885 "' that doesn't appear in asm string!");
1886
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
1891 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 }
1907 }
1908 }
1909
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 }
1916 }
1917
1918 static unsigned
getConverterOperandID(const std::string & Name,SmallSetVector<CachedHashString,16> & Table,bool & IsNew)1919 getConverterOperandID(const std::string &Name,
1920 SmallSetVector<CachedHashString, 16> &Table,
1921 bool &IsNew) {
1922 IsNew = Table.insert(CachedHashString(Name));
1923
1924 unsigned ID = IsNew ? Table.size() - 1 : find(Table, Name) - Table.begin();
1925
1926 assert(ID < Table.size());
1927
1928 return ID;
1929 }
1930
emitConvertFuncs(CodeGenTarget & Target,StringRef ClassName,std::vector<std::unique_ptr<MatchableInfo>> & Infos,bool HasMnemonicFirst,bool HasOptionalOperands,raw_ostream & OS)1931 static void emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName,
1932 std::vector<std::unique_ptr<MatchableInfo>> &Infos,
1933 bool HasMnemonicFirst, bool HasOptionalOperands,
1934 raw_ostream &OS) {
1935 SmallSetVector<CachedHashString, 16> OperandConversionKinds;
1936 SmallSetVector<CachedHashString, 16> InstructionConversionKinds;
1937 std::vector<std::vector<uint8_t> > ConversionTable;
1938 size_t MaxRowLength = 2; // minimum is custom converter plus terminator.
1939
1940 // TargetOperandClass - This is the target's operand class, like X86Operand.
1941 std::string TargetOperandClass = Target.getName().str() + "Operand";
1942
1943 // 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.
1949 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) {
1964 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";
1977 }
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) {
1982 CvtOS << " OpIdx = *(p + 1) - DefaultsOffset[*(p + 1)];\n";
1983 } 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";
1992 CvtOS << " case CVT_Tied: {\n";
1993 CvtOS << " assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
1994 CvtOS << " std::begin(TiedAsmOperandTable)) &&\n";
1995 CvtOS << " \"Tied operand not found\");\n";
1996 CvtOS << " unsigned TiedResOpnd = TiedAsmOperandTable[OpIdx][0];\n";
1997 CvtOS << " if (TiedResOpnd != (uint8_t) -1)\n";
1998 CvtOS << " Inst.addOperand(Inst.getOperand(TiedResOpnd));\n";
1999 CvtOS << " break;\n";
2000 CvtOS << " }\n";
2001
2002 std::string OperandFnBody;
2003 raw_string_ostream OpOS(OperandFnBody);
2004 // Start the operand number lookup function.
2005 OpOS << "void " << Target.getName() << ClassName << "::\n"
2006 << "convertToMapAndConstraints(unsigned Kind,\n";
2007 OpOS.indent(27);
2008 OpOS << "const OperandVector &Operands) {\n"
2009 << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
2010 << " unsigned NumMCOperands = 0;\n"
2011 << " const uint8_t *Converter = ConversionTable[Kind];\n"
2012 << " for (const uint8_t *p = Converter; *p; p+= 2) {\n"
2013 << " switch (*p) {\n"
2014 << " default: llvm_unreachable(\"invalid conversion entry!\");\n"
2015 << " case CVT_Reg:\n"
2016 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2017 << " Operands[*(p + 1)]->setConstraint(\"r\");\n"
2018 << " ++NumMCOperands;\n"
2019 << " break;\n"
2020 << " case CVT_Tied:\n"
2021 << " ++NumMCOperands;\n"
2022 << " break;\n";
2023
2024 // Pre-populate the operand conversion kinds with the standard always
2025 // available entries.
2026 OperandConversionKinds.insert(CachedHashString("CVT_Done"));
2027 OperandConversionKinds.insert(CachedHashString("CVT_Reg"));
2028 OperandConversionKinds.insert(CachedHashString("CVT_Tied"));
2029 enum { CVT_Done, CVT_Reg, CVT_Tied };
2030
2031 // Map of e.g. <0, 2, 3> -> "Tie_0_2_3" enum label.
2032 std::map<std::tuple<uint8_t, uint8_t, uint8_t>, std::string>
2033 TiedOperandsEnumMap;
2034
2035 for (auto &II : Infos) {
2036 // Check if we have a custom match function.
2037 StringRef AsmMatchConverter =
2038 II->getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
2039 if (!AsmMatchConverter.empty() && II->UseInstAsmMatchConverter) {
2040 std::string Signature = ("ConvertCustom_" + AsmMatchConverter).str();
2041 II->ConversionFnKind = Signature;
2042
2043 // Check if we have already generated this signature.
2044 if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
2045 continue;
2046
2047 // Remember this converter for the kind enum.
2048 unsigned KindID = OperandConversionKinds.size();
2049 OperandConversionKinds.insert(
2050 CachedHashString("CVT_" + getEnumNameForToken(AsmMatchConverter)));
2051
2052 // Add the converter row for this instruction.
2053 ConversionTable.emplace_back();
2054 ConversionTable.back().push_back(KindID);
2055 ConversionTable.back().push_back(CVT_Done);
2056
2057 // Add the handler to the conversion driver function.
2058 CvtOS << " case CVT_"
2059 << getEnumNameForToken(AsmMatchConverter) << ":\n"
2060 << " " << AsmMatchConverter << "(Inst, Operands);\n"
2061 << " break;\n";
2062
2063 // FIXME: Handle the operand number lookup for custom match functions.
2064 continue;
2065 }
2066
2067 // Build the conversion function signature.
2068 std::string Signature = "Convert";
2069
2070 std::vector<uint8_t> ConversionRow;
2071
2072 // Compute the convert enum and the case body.
2073 MaxRowLength = std::max(MaxRowLength, II->ResOperands.size()*2 + 1 );
2074
2075 for (unsigned i = 0, e = II->ResOperands.size(); i != e; ++i) {
2076 const MatchableInfo::ResOperand &OpInfo = II->ResOperands[i];
2077
2078 // Generate code to populate each result operand.
2079 switch (OpInfo.Kind) {
2080 case MatchableInfo::ResOperand::RenderAsmOperand: {
2081 // This comes from something we parsed.
2082 const MatchableInfo::AsmOperand &Op =
2083 II->AsmOperands[OpInfo.AsmOperandNum];
2084
2085 // Registers are always converted the same, don't duplicate the
2086 // conversion function based on them.
2087 Signature += "__";
2088 std::string Class;
2089 Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName;
2090 Signature += Class;
2091 Signature += utostr(OpInfo.MINumOperands);
2092 Signature += "_" + itostr(OpInfo.AsmOperandNum);
2093
2094 // 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);
2098 if (Op.Class->IsOptional) {
2099 // For optional operands we must also care about DefaultMethod
2100 assert(HasOptionalOperands);
2101 Name += "_" + Op.Class->DefaultMethod;
2102 }
2103 Name = getEnumNameForToken(Name);
2104
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);
2111 ConversionRow.push_back(OpInfo.AsmOperandNum + HasMnemonicFirst);
2112
2113 if (!IsNewConverter)
2114 break;
2115
2116 // This is a new operand kind. Add a handler for it to the
2117 // converter driver.
2118 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"
2127 << " } 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";
2138
2139 // Add a handler for the operand number lookup.
2140 OpOS << " case " << Name << ":\n"
2141 << " 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"
2148 << " break;\n";
2149 break;
2150 }
2151 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.
2154 assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
2155 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!");
2162 auto TiedTupleName = std::string("Tie") + utostr(TiedOp) + '_' +
2163 utostr(SrcOp1) + '_' + utostr(SrcOp2);
2164 Signature += "__" + TiedTupleName;
2165 ConversionRow.push_back(CVT_Tied);
2166 ConversionRow.push_back(TiedOp);
2167 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);
2173 break;
2174 }
2175 case MatchableInfo::ResOperand::ImmOperand: {
2176 int64_t Val = OpInfo.ImmVal;
2177 std::string Ty = "imm_" + itostr(Val);
2178 Ty = getEnumNameForToken(Ty);
2179 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"
2193 << " Inst.addOperand(MCOperand::createImm(" << Val << "));\n"
2194 << " break;\n";
2195
2196 OpOS << " case " << Name << ":\n"
2197 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2198 << " Operands[*(p + 1)]->setConstraint(\"\");\n"
2199 << " ++NumMCOperands;\n"
2200 << " break;\n";
2201 break;
2202 }
2203 case MatchableInfo::ResOperand::RegOperand: {
2204 std::string Reg, Name;
2205 if (!OpInfo.Register) {
2206 Name = "reg0";
2207 Reg = "0";
2208 } else {
2209 Reg = getQualifiedName(OpInfo.Register);
2210 Name = "reg" + OpInfo.Register->getName().str();
2211 }
2212 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"
2224 << " Inst.addOperand(MCOperand::createReg(" << Reg << "));\n"
2225 << " break;\n";
2226
2227 OpOS << " case " << Name << ":\n"
2228 << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
2229 << " Operands[*(p + 1)]->setConstraint(\"m\");\n"
2230 << " ++NumMCOperands;\n"
2231 << " break;\n";
2232 }
2233 }
2234 }
2235
2236 // If there were no operands, add to the signature to that effect
2237 if (Signature == "Convert")
2238 Signature += "_NoOperands";
2239
2240 II->ConversionFnKind = Signature;
2241
2242 // Save the signature. If we already have it, don't add a new row
2243 // to the table.
2244 if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
2245 continue;
2246
2247 // Add the row to the table.
2248 ConversionTable.push_back(std::move(ConversionRow));
2249 }
2250
2251 // Finish up the converter driver function.
2252 CvtOS << " }\n }\n}\n\n";
2253
2254 // Finish up the operand number lookup function.
2255 OpOS << " }\n }\n}\n\n";
2256
2257 // 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.
2261 assert(TiedOperandsEnumMap.size() <= 254 &&
2262 "Too many tied-operand combinations to reference with "
2263 "an 8bit offset from the conversion table, where index "
2264 "'255' is reserved as operand not to be copied.");
2265
2266 OS << "enum {\n";
2267 for (auto &KV : TiedOperandsEnumMap) {
2268 OS << " " << KV.second << ",\n";
2269 }
2270 OS << "};\n\n";
2271
2272 OS << "static const uint8_t TiedAsmOperandTable[][3] = {\n";
2273 for (auto &KV : TiedOperandsEnumMap) {
2274 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";
2278 }
2279 OS << "};\n\n";
2280 } else
2281 OS << "static const uint8_t TiedAsmOperandTable[][3] = "
2282 "{ /* empty */ {0, 0, 0} };\n\n";
2283
2284 OS << "namespace {\n";
2285
2286 // Output the operand conversion kind enum.
2287 OS << "enum OperatorConversionKind {\n";
2288 for (const auto &Converter : OperandConversionKinds)
2289 OS << " " << Converter << ",\n";
2290 OS << " CVT_NUM_CONVERTERS\n";
2291 OS << "};\n\n";
2292
2293 // Output the instruction conversion kind enum.
2294 OS << "enum InstructionConversionKind {\n";
2295 for (const auto &Signature : InstructionConversionKinds)
2296 OS << " " << Signature << ",\n";
2297 OS << " CVT_NUM_SIGNATURES\n";
2298 OS << "};\n\n";
2299
2300 OS << "} // end anonymous namespace\n\n";
2301
2302 // Output the conversion table.
2303 OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES]["
2304 << 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 << " { ";
2310 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.
2321 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]);
2324 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 }
2330 OS << "CVT_Done },\n";
2331 }
2332
2333 OS << "};\n\n";
2334
2335 // Spit out the conversion driver function.
2336 OS << CvtOS.str();
2337
2338 // Spit out the operand number lookup function.
2339 OS << OpOS.str();
2340 }
2341
2342 /// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
emitMatchClassEnumeration(CodeGenTarget & Target,std::forward_list<ClassInfo> & Infos,raw_ostream & OS)2343 static void emitMatchClassEnumeration(CodeGenTarget &Target,
2344 std::forward_list<ClassInfo> &Infos,
2345 raw_ostream &OS) {
2346 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";
2352 OS << " OptionalMatchClass = 1,\n";
2353 ClassInfo::ClassInfoKind LastKind = ClassInfo::Token;
2354 StringRef LastName = "OptionalMatchClass";
2355 for (const auto &CI : Infos) {
2356 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
2365 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";
2371 else
2372 OS << "derived register class\n";
2373 } else {
2374 OS << "user defined class '" << CI.ValueName << "'\n";
2375 }
2376 }
2377 OS << " NumMatchClassKinds\n";
2378 OS << "};\n\n";
2379
2380 OS << "}\n\n";
2381 }
2382
2383 /// emitMatchClassDiagStrings - Emit a function to get the diagnostic text to be
2384 /// used when an assembly operand does not match the expected operand class.
emitOperandMatchErrorDiagStrings(AsmMatcherInfo & Info,raw_ostream & OS)2385 static 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
emitRegisterMatchErrorFunc(AsmMatcherInfo & Info,raw_ostream & OS)2415 static void emitRegisterMatchErrorFunc(AsmMatcherInfo &Info, raw_ostream &OS) {
2416 OS << "static unsigned getDiagKindFromRegisterClass(MatchClassKind "
2417 "RegisterClass) {\n";
2418 if (std::none_of(Info.Classes.begin(), Info.Classes.end(),
2419 [](const ClassInfo &CI) {
2420 return CI.isRegisterClass() && !CI.DiagnosticType.empty();
2421 })) {
2422 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2423 } else {
2424 OS << " switch (RegisterClass) {\n";
2425 for (const auto &CI: Info.Classes) {
2426 if (CI.isRegisterClass() && !CI.DiagnosticType.empty()) {
2427 OS << " case " << CI.Name << ":\n";
2428 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
2429 << CI.DiagnosticType << ";\n";
2430 }
2431 }
2432
2433 OS << " default:\n";
2434 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2435
2436 OS << " }\n";
2437 }
2438 OS << "}\n\n";
2439 }
2440
2441 /// emitValidateOperandClass - Emit the function to validate an operand class.
emitValidateOperandClass(AsmMatcherInfo & Info,raw_ostream & OS)2442 static void emitValidateOperandClass(AsmMatcherInfo &Info,
2443 raw_ostream &OS) {
2444 OS << "static unsigned validateOperandClass(MCParsedAsmOperand &GOp, "
2445 << "MatchClassKind Kind) {\n";
2446 OS << " " << Info.Target.getName() << "Operand &Operand = ("
2447 << Info.Target.getName() << "Operand&)GOp;\n";
2448
2449 // The InvalidMatchClass is not to match any operand.
2450 OS << " if (Kind == InvalidMatchClass)\n";
2451 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n\n";
2452
2453 // Check for Token operands first.
2454 // FIXME: Use a more specific diagnostic type.
2455 OS << " if (Operand.isToken() && Kind <= MCK_LAST_TOKEN)\n";
2456 OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
2457 << " MCTargetAsmParser::Match_Success :\n"
2458 << " MCTargetAsmParser::Match_InvalidOperand;\n\n";
2459
2460 // Check the user classes. We don't care what order since we're only
2461 // actually matching against one of them.
2462 OS << " switch (Kind) {\n"
2463 " default: break;\n";
2464 for (const auto &CI : Info.Classes) {
2465 if (!CI.isUserClass())
2466 continue;
2467
2468 OS << " // '" << CI.ClassName << "' class\n";
2469 OS << " case " << CI.Name << ": {\n";
2470 OS << " DiagnosticPredicate DP(Operand." << CI.PredicateMethod
2471 << "());\n";
2472 OS << " if (DP.isMatch())\n";
2473 OS << " return MCTargetAsmParser::Match_Success;\n";
2474 if (!CI.DiagnosticType.empty()) {
2475 OS << " if (DP.isNearMatch())\n";
2476 OS << " return " << Info.Target.getName() << "AsmParser::Match_"
2477 << CI.DiagnosticType << ";\n";
2478 OS << " break;\n";
2479 }
2480 else
2481 OS << " break;\n";
2482 OS << " }\n";
2483 }
2484 OS << " } // end switch (Kind)\n\n";
2485
2486 // Check for register operands, including sub-classes.
2487 OS << " if (Operand.isReg()) {\n";
2488 OS << " MatchClassKind OpKind;\n";
2489 OS << " switch (Operand.getReg()) {\n";
2490 OS << " default: OpKind = InvalidMatchClass; break;\n";
2491 for (const auto &RC : Info.RegisterClasses)
2492 OS << " case " << RC.first->getValueAsString("Namespace") << "::"
2493 << RC.first->getName() << ": OpKind = " << RC.second->Name
2494 << "; break;\n";
2495 OS << " }\n";
2496 OS << " return isSubclass(OpKind, Kind) ? "
2497 << "(unsigned)MCTargetAsmParser::Match_Success :\n "
2498 << " getDiagKindFromRegisterClass(Kind);\n }\n\n";
2499
2500 // Expected operand is a register, but actual is not.
2501 OS << " if (Kind > MCK_LAST_TOKEN && Kind <= MCK_LAST_REGISTER)\n";
2502 OS << " return getDiagKindFromRegisterClass(Kind);\n\n";
2503
2504 // Generic fallthrough match failure case for operands that don't have
2505 // specialized diagnostic types.
2506 OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
2507 OS << "}\n\n";
2508 }
2509
2510 /// emitIsSubclass - Emit the subclass predicate function.
emitIsSubclass(CodeGenTarget & Target,std::forward_list<ClassInfo> & Infos,raw_ostream & OS)2511 static void emitIsSubclass(CodeGenTarget &Target,
2512 std::forward_list<ClassInfo> &Infos,
2513 raw_ostream &OS) {
2514 OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n";
2515 OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
2516 OS << " if (A == B)\n";
2517 OS << " return true;\n\n";
2518
2519 bool EmittedSwitch = false;
2520 for (const auto &A : Infos) {
2521 std::vector<StringRef> SuperClasses;
2522 if (A.IsOptional)
2523 SuperClasses.push_back("OptionalMatchClass");
2524 for (const auto &B : Infos) {
2525 if (&A != &B && A.isSubsetOf(B))
2526 SuperClasses.push_back(B.Name);
2527 }
2528
2529 if (SuperClasses.empty())
2530 continue;
2531
2532 // If this is the first SuperClass, emit the switch header.
2533 if (!EmittedSwitch) {
2534 OS << " switch (A) {\n";
2535 OS << " default:\n";
2536 OS << " return false;\n";
2537 EmittedSwitch = true;
2538 }
2539
2540 OS << "\n case " << A.Name << ":\n";
2541
2542 if (SuperClasses.size() == 1) {
2543 OS << " return B == " << SuperClasses.back() << ";\n";
2544 continue;
2545 }
2546
2547 if (!SuperClasses.empty()) {
2548 OS << " switch (B) {\n";
2549 OS << " default: return false;\n";
2550 for (StringRef SC : SuperClasses)
2551 OS << " case " << SC << ": return true;\n";
2552 OS << " }\n";
2553 } else {
2554 // No case statement to emit
2555 OS << " return false;\n";
2556 }
2557 }
2558
2559 // If there were case statements emitted into the string stream write the
2560 // default.
2561 if (EmittedSwitch)
2562 OS << " }\n";
2563 else
2564 OS << " return false;\n";
2565
2566 OS << "}\n\n";
2567 }
2568
2569 /// emitMatchTokenString - Emit the function to match a token string to the
2570 /// appropriate match class value.
emitMatchTokenString(CodeGenTarget & Target,std::forward_list<ClassInfo> & Infos,raw_ostream & OS)2571 static void emitMatchTokenString(CodeGenTarget &Target,
2572 std::forward_list<ClassInfo> &Infos,
2573 raw_ostream &OS) {
2574 // Construct the match list.
2575 std::vector<StringMatcher::StringPair> Matches;
2576 for (const auto &CI : Infos) {
2577 if (CI.Kind == ClassInfo::Token)
2578 Matches.emplace_back(CI.ValueName, "return " + CI.Name + ";");
2579 }
2580
2581 OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
2582
2583 StringMatcher("Name", Matches, OS).Emit();
2584
2585 OS << " return InvalidMatchClass;\n";
2586 OS << "}\n\n";
2587 }
2588
2589 /// emitMatchRegisterName - Emit the function to match a string to the target
2590 /// specific register enum.
emitMatchRegisterName(CodeGenTarget & Target,Record * AsmParser,raw_ostream & OS)2591 static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
2592 raw_ostream &OS) {
2593 // Construct the match list.
2594 std::vector<StringMatcher::StringPair> Matches;
2595 const auto &Regs = Target.getRegBank().getRegisters();
2596 for (const CodeGenRegister &Reg : Regs) {
2597 if (Reg.TheDef->getValueAsString("AsmName").empty())
2598 continue;
2599
2600 Matches.emplace_back(Reg.TheDef->getValueAsString("AsmName"),
2601 "return " + utostr(Reg.EnumValue) + ";");
2602 }
2603
2604 OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
2605
2606 bool IgnoreDuplicates =
2607 AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
2608 StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
2609
2610 OS << " return 0;\n";
2611 OS << "}\n\n";
2612 }
2613
2614 /// Emit the function to match a string to the target
2615 /// specific register enum.
emitMatchRegisterAltName(CodeGenTarget & Target,Record * AsmParser,raw_ostream & OS)2616 static void emitMatchRegisterAltName(CodeGenTarget &Target, Record *AsmParser,
2617 raw_ostream &OS) {
2618 // Construct the match list.
2619 std::vector<StringMatcher::StringPair> Matches;
2620 const auto &Regs = Target.getRegBank().getRegisters();
2621 for (const CodeGenRegister &Reg : Regs) {
2622
2623 auto AltNames = Reg.TheDef->getValueAsListOfStrings("AltNames");
2624
2625 for (auto AltName : AltNames) {
2626 AltName = StringRef(AltName).trim();
2627
2628 // don't handle empty alternative names
2629 if (AltName.empty())
2630 continue;
2631
2632 Matches.emplace_back(AltName,
2633 "return " + utostr(Reg.EnumValue) + ";");
2634 }
2635 }
2636
2637 OS << "static unsigned MatchRegisterAltName(StringRef Name) {\n";
2638
2639 bool IgnoreDuplicates =
2640 AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
2641 StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
2642
2643 OS << " return 0;\n";
2644 OS << "}\n\n";
2645 }
2646
2647 /// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
emitOperandDiagnosticTypes(AsmMatcherInfo & Info,raw_ostream & OS)2648 static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) {
2649 // Get the set of diagnostic types from all of the operand classes.
2650 std::set<StringRef> Types;
2651 for (const auto &OpClassEntry : Info.AsmOperandClasses) {
2652 if (!OpClassEntry.second->DiagnosticType.empty())
2653 Types.insert(OpClassEntry.second->DiagnosticType);
2654 }
2655 for (const auto &OpClassEntry : Info.RegisterClassClasses) {
2656 if (!OpClassEntry.second->DiagnosticType.empty())
2657 Types.insert(OpClassEntry.second->DiagnosticType);
2658 }
2659
2660 if (Types.empty()) return;
2661
2662 // Now emit the enum entries.
2663 for (StringRef Type : Types)
2664 OS << " Match_" << Type << ",\n";
2665 OS << " END_OPERAND_DIAGNOSTIC_TYPES\n";
2666 }
2667
2668 /// emitGetSubtargetFeatureName - Emit the helper function to get the
2669 /// user-level name for a subtarget feature.
emitGetSubtargetFeatureName(AsmMatcherInfo & Info,raw_ostream & OS)2670 static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
2671 OS << "// User-level names for subtarget features that participate in\n"
2672 << "// instruction matching.\n"
2673 << "static const char *getSubtargetFeatureName(uint64_t Val) {\n";
2674 if (!Info.SubtargetFeatures.empty()) {
2675 OS << " switch(Val) {\n";
2676 for (const auto &SF : Info.SubtargetFeatures) {
2677 const SubtargetFeatureInfo &SFI = SF.second;
2678 // FIXME: Totally just a placeholder name to get the algorithm working.
2679 OS << " case " << SFI.getEnumName() << ": return \""
2680 << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
2681 }
2682 OS << " default: return \"(unknown)\";\n";
2683 OS << " }\n";
2684 } else {
2685 // Nothing to emit, so skip the switch
2686 OS << " return \"(unknown)\";\n";
2687 }
2688 OS << "}\n\n";
2689 }
2690
GetAliasRequiredFeatures(Record * R,const AsmMatcherInfo & Info)2691 static std::string GetAliasRequiredFeatures(Record *R,
2692 const AsmMatcherInfo &Info) {
2693 std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
2694 std::string Result;
2695 unsigned NumFeatures = 0;
2696 for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
2697 const SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
2698
2699 if (!F)
2700 PrintFatalError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
2701 "' is not marked as an AssemblerPredicate!");
2702
2703 if (NumFeatures)
2704 Result += '|';
2705
2706 Result += F->getEnumName();
2707 ++NumFeatures;
2708 }
2709
2710 if (NumFeatures > 1)
2711 Result = '(' + Result + ')';
2712 return Result;
2713 }
2714
emitMnemonicAliasVariant(raw_ostream & OS,const AsmMatcherInfo & Info,std::vector<Record * > & Aliases,unsigned Indent=0,StringRef AsmParserVariantName=StringRef ())2715 static void emitMnemonicAliasVariant(raw_ostream &OS,const AsmMatcherInfo &Info,
2716 std::vector<Record*> &Aliases,
2717 unsigned Indent = 0,
2718 StringRef AsmParserVariantName = StringRef()){
2719 // Keep track of all the aliases from a mnemonic. Use an std::map so that the
2720 // iteration order of the map is stable.
2721 std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
2722
2723 for (Record *R : Aliases) {
2724 // FIXME: Allow AssemblerVariantName to be a comma separated list.
2725 StringRef AsmVariantName = R->getValueAsString("AsmVariantName");
2726 if (AsmVariantName != AsmParserVariantName)
2727 continue;
2728 AliasesFromMnemonic[R->getValueAsString("FromMnemonic")].push_back(R);
2729 }
2730 if (AliasesFromMnemonic.empty())
2731 return;
2732
2733 // Process each alias a "from" mnemonic at a time, building the code executed
2734 // by the string remapper.
2735 std::vector<StringMatcher::StringPair> Cases;
2736 for (const auto &AliasEntry : AliasesFromMnemonic) {
2737 const std::vector<Record*> &ToVec = AliasEntry.second;
2738
2739 // Loop through each alias and emit code that handles each case. If there
2740 // are two instructions without predicates, emit an error. If there is one,
2741 // emit it last.
2742 std::string MatchCode;
2743 int AliasWithNoPredicate = -1;
2744
2745 for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
2746 Record *R = ToVec[i];
2747 std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
2748
2749 // If this unconditionally matches, remember it for later and diagnose
2750 // duplicates.
2751 if (FeatureMask.empty()) {
2752 if (AliasWithNoPredicate != -1) {
2753 // We can't have two aliases from the same mnemonic with no predicate.
2754 PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
2755 "two MnemonicAliases with the same 'from' mnemonic!");
2756 PrintFatalError(R->getLoc(), "this is the other MnemonicAlias.");
2757 }
2758
2759 AliasWithNoPredicate = i;
2760 continue;
2761 }
2762 if (R->getValueAsString("ToMnemonic") == AliasEntry.first)
2763 PrintFatalError(R->getLoc(), "MnemonicAlias to the same string");
2764
2765 if (!MatchCode.empty())
2766 MatchCode += "else ";
2767 MatchCode += "if ((Features & " + FeatureMask + ") == "+FeatureMask+")\n";
2768 MatchCode += " Mnemonic = \"";
2769 MatchCode += R->getValueAsString("ToMnemonic");
2770 MatchCode += "\";\n";
2771 }
2772
2773 if (AliasWithNoPredicate != -1) {
2774 Record *R = ToVec[AliasWithNoPredicate];
2775 if (!MatchCode.empty())
2776 MatchCode += "else\n ";
2777 MatchCode += "Mnemonic = \"";
2778 MatchCode += R->getValueAsString("ToMnemonic");
2779 MatchCode += "\";\n";
2780 }
2781
2782 MatchCode += "return;";
2783
2784 Cases.push_back(std::make_pair(AliasEntry.first, MatchCode));
2785 }
2786 StringMatcher("Mnemonic", Cases, OS).Emit(Indent);
2787 }
2788
2789 /// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
2790 /// emit a function for them and return true, otherwise return false.
emitMnemonicAliases(raw_ostream & OS,const AsmMatcherInfo & Info,CodeGenTarget & Target)2791 static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info,
2792 CodeGenTarget &Target) {
2793 // Ignore aliases when match-prefix is set.
2794 if (!MatchPrefix.empty())
2795 return false;
2796
2797 std::vector<Record*> Aliases =
2798 Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
2799 if (Aliases.empty()) return false;
2800
2801 OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
2802 "uint64_t Features, unsigned VariantID) {\n";
2803 OS << " switch (VariantID) {\n";
2804 unsigned VariantCount = Target.getAsmParserVariantCount();
2805 for (unsigned VC = 0; VC != VariantCount; ++VC) {
2806 Record *AsmVariant = Target.getAsmParserVariant(VC);
2807 int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant");
2808 StringRef AsmParserVariantName = AsmVariant->getValueAsString("Name");
2809 OS << " case " << AsmParserVariantNo << ":\n";
2810 emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2,
2811 AsmParserVariantName);
2812 OS << " break;\n";
2813 }
2814 OS << " }\n";
2815
2816 // Emit aliases that apply to all variants.
2817 emitMnemonicAliasVariant(OS, Info, Aliases);
2818
2819 OS << "}\n\n";
2820
2821 return true;
2822 }
2823
emitCustomOperandParsing(raw_ostream & OS,CodeGenTarget & Target,const AsmMatcherInfo & Info,StringRef ClassName,StringToOffsetTable & StringTable,unsigned MaxMnemonicIndex,bool HasMnemonicFirst)2824 static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
2825 const AsmMatcherInfo &Info, StringRef ClassName,
2826 StringToOffsetTable &StringTable,
2827 unsigned MaxMnemonicIndex, bool HasMnemonicFirst) {
2828 unsigned MaxMask = 0;
2829 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
2830 MaxMask |= OMI.OperandMask;
2831 }
2832
2833 // Emit the static custom operand parsing table;
2834 OS << "namespace {\n";
2835 OS << " struct OperandMatchEntry {\n";
2836 OS << " " << getMinimalTypeForEnumBitfield(Info.SubtargetFeatures.size())
2837 << " RequiredFeatures;\n";
2838 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
2839 << " Mnemonic;\n";
2840 OS << " " << getMinimalTypeForRange(std::distance(
2841 Info.Classes.begin(), Info.Classes.end())) << " Class;\n";
2842 OS << " " << getMinimalTypeForRange(MaxMask)
2843 << " OperandMask;\n\n";
2844 OS << " StringRef getMnemonic() const {\n";
2845 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
2846 OS << " MnemonicTable[Mnemonic]);\n";
2847 OS << " }\n";
2848 OS << " };\n\n";
2849
2850 OS << " // Predicate for searching for an opcode.\n";
2851 OS << " struct LessOpcodeOperand {\n";
2852 OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
2853 OS << " return LHS.getMnemonic() < RHS;\n";
2854 OS << " }\n";
2855 OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
2856 OS << " return LHS < RHS.getMnemonic();\n";
2857 OS << " }\n";
2858 OS << " bool operator()(const OperandMatchEntry &LHS,";
2859 OS << " const OperandMatchEntry &RHS) {\n";
2860 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
2861 OS << " }\n";
2862 OS << " };\n";
2863
2864 OS << "} // end anonymous namespace.\n\n";
2865
2866 OS << "static const OperandMatchEntry OperandMatchTable["
2867 << Info.OperandMatchInfo.size() << "] = {\n";
2868
2869 OS << " /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
2870 for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
2871 const MatchableInfo &II = *OMI.MI;
2872
2873 OS << " { ";
2874
2875 // Write the required features mask.
2876 if (!II.RequiredFeatures.empty()) {
2877 for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i) {
2878 if (i) OS << "|";
2879 OS << II.RequiredFeatures[i]->getEnumName();
2880 }
2881 } else
2882 OS << "0";
2883
2884 // Store a pascal-style length byte in the mnemonic.
2885 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.str();
2886 OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
2887 << " /* " << II.Mnemonic << " */, ";
2888
2889 OS << OMI.CI->Name;
2890
2891 OS << ", " << OMI.OperandMask;
2892 OS << " /* ";
2893 bool printComma = false;
2894 for (int i = 0, e = 31; i !=e; ++i)
2895 if (OMI.OperandMask & (1 << i)) {
2896 if (printComma)
2897 OS << ", ";
2898 OS << i;
2899 printComma = true;
2900 }
2901 OS << " */";
2902
2903 OS << " },\n";
2904 }
2905 OS << "};\n\n";
2906
2907 // Emit the operand class switch to call the correct custom parser for
2908 // the found operand class.
2909 OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
2910 << "tryCustomParseOperand(OperandVector"
2911 << " &Operands,\n unsigned MCK) {\n\n"
2912 << " switch(MCK) {\n";
2913
2914 for (const auto &CI : Info.Classes) {
2915 if (CI.ParserMethod.empty())
2916 continue;
2917 OS << " case " << CI.Name << ":\n"
2918 << " return " << CI.ParserMethod << "(Operands);\n";
2919 }
2920
2921 OS << " default:\n";
2922 OS << " return MatchOperand_NoMatch;\n";
2923 OS << " }\n";
2924 OS << " return MatchOperand_NoMatch;\n";
2925 OS << "}\n\n";
2926
2927 // Emit the static custom operand parser. This code is very similar with
2928 // the other matcher. Also use MatchResultTy here just in case we go for
2929 // a better error handling.
2930 OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
2931 << "MatchOperandParserImpl(OperandVector"
2932 << " &Operands,\n StringRef Mnemonic,\n"
2933 << " bool ParseForAllFeatures) {\n";
2934
2935 // Emit code to get the available features.
2936 OS << " // Get the current feature set.\n";
2937 OS << " uint64_t AvailableFeatures = getAvailableFeatures();\n\n";
2938
2939 OS << " // Get the next operand index.\n";
2940 OS << " unsigned NextOpNum = Operands.size()"
2941 << (HasMnemonicFirst ? " - 1" : "") << ";\n";
2942
2943 // Emit code to search the table.
2944 OS << " // Search the table.\n";
2945 if (HasMnemonicFirst) {
2946 OS << " auto MnemonicRange =\n";
2947 OS << " std::equal_range(std::begin(OperandMatchTable), "
2948 "std::end(OperandMatchTable),\n";
2949 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2950 } else {
2951 OS << " auto MnemonicRange = std::make_pair(std::begin(OperandMatchTable),"
2952 " std::end(OperandMatchTable));\n";
2953 OS << " if (!Mnemonic.empty())\n";
2954 OS << " MnemonicRange =\n";
2955 OS << " std::equal_range(std::begin(OperandMatchTable), "
2956 "std::end(OperandMatchTable),\n";
2957 OS << " Mnemonic, LessOpcodeOperand());\n\n";
2958 }
2959
2960 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
2961 OS << " return MatchOperand_NoMatch;\n\n";
2962
2963 OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
2964 << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
2965
2966 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
2967 OS << " assert(Mnemonic == it->getMnemonic());\n\n";
2968
2969 // Emit check that the required features are available.
2970 OS << " // check if the available features match\n";
2971 OS << " if (!ParseForAllFeatures && (AvailableFeatures & "
2972 "it->RequiredFeatures) != it->RequiredFeatures)\n";
2973 OS << " continue;\n\n";
2974
2975 // Emit check to ensure the operand number matches.
2976 OS << " // check if the operand in question has a custom parser.\n";
2977 OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
2978 OS << " continue;\n\n";
2979
2980 // Emit call to the custom parser method
2981 OS << " // call custom parse method to handle the operand\n";
2982 OS << " OperandMatchResultTy Result = ";
2983 OS << "tryCustomParseOperand(Operands, it->Class);\n";
2984 OS << " if (Result != MatchOperand_NoMatch)\n";
2985 OS << " return Result;\n";
2986 OS << " }\n\n";
2987
2988 OS << " // Okay, we had no match.\n";
2989 OS << " return MatchOperand_NoMatch;\n";
2990 OS << "}\n\n";
2991 }
2992
emitAsmTiedOperandConstraints(CodeGenTarget & Target,AsmMatcherInfo & Info,raw_ostream & OS)2993 static void emitAsmTiedOperandConstraints(CodeGenTarget &Target,
2994 AsmMatcherInfo &Info,
2995 raw_ostream &OS) {
2996 std::string AsmParserName =
2997 Info.AsmParser->getValueAsString("AsmParserClassName");
2998 OS << "static bool ";
2999 OS << "checkAsmTiedOperandConstraints(const " << Target.getName()
3000 << AsmParserName << "&AsmParser,\n";
3001 OS << " unsigned Kind,\n";
3002 OS << " const OperandVector &Operands,\n";
3003 OS << " uint64_t &ErrorInfo) {\n";
3004 OS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
3005 OS << " const uint8_t *Converter = ConversionTable[Kind];\n";
3006 OS << " for (const uint8_t *p = Converter; *p; p+= 2) {\n";
3007 OS << " switch (*p) {\n";
3008 OS << " case CVT_Tied: {\n";
3009 OS << " unsigned OpIdx = *(p+1);\n";
3010 OS << " assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
3011 OS << " std::begin(TiedAsmOperandTable)) &&\n";
3012 OS << " \"Tied operand not found\");\n";
3013 OS << " unsigned OpndNum1 = TiedAsmOperandTable[OpIdx][1];\n";
3014 OS << " unsigned OpndNum2 = TiedAsmOperandTable[OpIdx][2];\n";
3015 OS << " if (OpndNum1 != OpndNum2) {\n";
3016 OS << " auto &SrcOp1 = Operands[OpndNum1];\n";
3017 OS << " auto &SrcOp2 = Operands[OpndNum2];\n";
3018 OS << " if (SrcOp1->isReg() && SrcOp2->isReg()) {\n";
3019 OS << " if (!AsmParser.regsEqual(*SrcOp1, *SrcOp2)) {\n";
3020 OS << " ErrorInfo = OpndNum2;\n";
3021 OS << " return false;\n";
3022 OS << " }\n";
3023 OS << " }\n";
3024 OS << " }\n";
3025 OS << " break;\n";
3026 OS << " }\n";
3027 OS << " default:\n";
3028 OS << " break;\n";
3029 OS << " }\n";
3030 OS << " }\n";
3031 OS << " return true;\n";
3032 OS << "}\n\n";
3033 }
3034
emitMnemonicSpellChecker(raw_ostream & OS,CodeGenTarget & Target,unsigned VariantCount)3035 static void emitMnemonicSpellChecker(raw_ostream &OS, CodeGenTarget &Target,
3036 unsigned VariantCount) {
3037 OS << "static std::string " << Target.getName()
3038 << "MnemonicSpellCheck(StringRef S, uint64_t FBS, unsigned VariantID) {\n";
3039 if (!VariantCount)
3040 OS << " return \"\";";
3041 else {
3042 OS << " const unsigned MaxEditDist = 2;\n";
3043 OS << " std::vector<StringRef> Candidates;\n";
3044 OS << " StringRef Prev = \"\";\n\n";
3045
3046 OS << " // Find the appropriate table for this asm variant.\n";
3047 OS << " const MatchEntry *Start, *End;\n";
3048 OS << " switch (VariantID) {\n";
3049 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
3050 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3051 Record *AsmVariant = Target.getAsmParserVariant(VC);
3052 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3053 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3054 << "); End = std::end(MatchTable" << VC << "); break;\n";
3055 }
3056 OS << " }\n\n";
3057 OS << " for (auto I = Start; I < End; I++) {\n";
3058 OS << " // Ignore unsupported instructions.\n";
3059 OS << " if ((FBS & I->RequiredFeatures) != I->RequiredFeatures)\n";
3060 OS << " continue;\n";
3061 OS << "\n";
3062 OS << " StringRef T = I->getMnemonic();\n";
3063 OS << " // Avoid recomputing the edit distance for the same string.\n";
3064 OS << " if (T.equals(Prev))\n";
3065 OS << " continue;\n";
3066 OS << "\n";
3067 OS << " Prev = T;\n";
3068 OS << " unsigned Dist = S.edit_distance(T, false, MaxEditDist);\n";
3069 OS << " if (Dist <= MaxEditDist)\n";
3070 OS << " Candidates.push_back(T);\n";
3071 OS << " }\n";
3072 OS << "\n";
3073 OS << " if (Candidates.empty())\n";
3074 OS << " return \"\";\n";
3075 OS << "\n";
3076 OS << " std::string Res = \", did you mean: \";\n";
3077 OS << " unsigned i = 0;\n";
3078 OS << " for( ; i < Candidates.size() - 1; i++)\n";
3079 OS << " Res += Candidates[i].str() + \", \";\n";
3080 OS << " return Res + Candidates[i].str() + \"?\";\n";
3081 }
3082 OS << "}\n";
3083 OS << "\n";
3084 }
3085
3086
3087 // Emit a function mapping match classes to strings, for debugging.
emitMatchClassKindNames(std::forward_list<ClassInfo> & Infos,raw_ostream & OS)3088 static void emitMatchClassKindNames(std::forward_list<ClassInfo> &Infos,
3089 raw_ostream &OS) {
3090 OS << "#ifndef NDEBUG\n";
3091 OS << "const char *getMatchClassName(MatchClassKind Kind) {\n";
3092 OS << " switch (Kind) {\n";
3093
3094 OS << " case InvalidMatchClass: return \"InvalidMatchClass\";\n";
3095 OS << " case OptionalMatchClass: return \"OptionalMatchClass\";\n";
3096 for (const auto &CI : Infos) {
3097 OS << " case " << CI.Name << ": return \"" << CI.Name << "\";\n";
3098 }
3099 OS << " case NumMatchClassKinds: return \"NumMatchClassKinds\";\n";
3100
3101 OS << " }\n";
3102 OS << " llvm_unreachable(\"unhandled MatchClassKind!\");\n";
3103 OS << "}\n\n";
3104 OS << "#endif // NDEBUG\n";
3105 }
3106
run(raw_ostream & OS)3107 void AsmMatcherEmitter::run(raw_ostream &OS) {
3108 CodeGenTarget Target(Records);
3109 Record *AsmParser = Target.getAsmParser();
3110 StringRef ClassName = AsmParser->getValueAsString("AsmParserClassName");
3111
3112 // Compute the information on the instructions to match.
3113 AsmMatcherInfo Info(AsmParser, Target, Records);
3114 Info.buildInfo();
3115
3116 // Sort the instruction table using the partial order on classes. We use
3117 // stable_sort to ensure that ambiguous instructions are still
3118 // deterministically ordered.
3119 std::stable_sort(Info.Matchables.begin(), Info.Matchables.end(),
3120 [](const std::unique_ptr<MatchableInfo> &a,
3121 const std::unique_ptr<MatchableInfo> &b){
3122 return *a < *b;});
3123
3124 #ifdef EXPENSIVE_CHECKS
3125 // Verify that the table is sorted and operator < works transitively.
3126 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
3127 ++I) {
3128 for (auto J = I; J != E; ++J) {
3129 assert(!(**J < **I));
3130 }
3131 }
3132 #endif
3133
3134 DEBUG_WITH_TYPE("instruction_info", {
3135 for (const auto &MI : Info.Matchables)
3136 MI->dump();
3137 });
3138
3139 // Check for ambiguous matchables.
3140 DEBUG_WITH_TYPE("ambiguous_instrs", {
3141 unsigned NumAmbiguous = 0;
3142 for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
3143 ++I) {
3144 for (auto J = std::next(I); J != E; ++J) {
3145 const MatchableInfo &A = **I;
3146 const MatchableInfo &B = **J;
3147
3148 if (A.couldMatchAmbiguouslyWith(B)) {
3149 errs() << "warning: ambiguous matchables:\n";
3150 A.dump();
3151 errs() << "\nis incomparable with:\n";
3152 B.dump();
3153 errs() << "\n\n";
3154 ++NumAmbiguous;
3155 }
3156 }
3157 }
3158 if (NumAmbiguous)
3159 errs() << "warning: " << NumAmbiguous
3160 << " ambiguous matchables!\n";
3161 });
3162
3163 // Compute the information on the custom operand parsing.
3164 Info.buildOperandMatchInfo();
3165
3166 bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
3167 bool HasOptionalOperands = Info.hasOptionalOperands();
3168 bool ReportMultipleNearMisses =
3169 AsmParser->getValueAsBit("ReportMultipleNearMisses");
3170
3171 // Write the output.
3172
3173 // Information for the class declaration.
3174 OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
3175 OS << "#undef GET_ASSEMBLER_HEADER\n";
3176 OS << " // This should be included into the middle of the declaration of\n";
3177 OS << " // your subclasses implementation of MCTargetAsmParser.\n";
3178 OS << " uint64_t ComputeAvailableFeatures(const FeatureBitset& FB) const;\n";
3179 if (HasOptionalOperands) {
3180 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
3181 << "unsigned Opcode,\n"
3182 << " const OperandVector &Operands,\n"
3183 << " const SmallBitVector &OptionalOperandsMask);\n";
3184 } else {
3185 OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
3186 << "unsigned Opcode,\n"
3187 << " const OperandVector &Operands);\n";
3188 }
3189 OS << " void convertToMapAndConstraints(unsigned Kind,\n ";
3190 OS << " const OperandVector &Operands) override;\n";
3191 OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
3192 << " MCInst &Inst,\n";
3193 if (ReportMultipleNearMisses)
3194 OS << " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
3195 else
3196 OS << " uint64_t &ErrorInfo,\n";
3197 OS << " bool matchingInlineAsm,\n"
3198 << " unsigned VariantID = 0);\n";
3199
3200 if (!Info.OperandMatchInfo.empty()) {
3201 OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
3202 OS << " OperandVector &Operands,\n";
3203 OS << " StringRef Mnemonic,\n";
3204 OS << " bool ParseForAllFeatures = false);\n";
3205
3206 OS << " OperandMatchResultTy tryCustomParseOperand(\n";
3207 OS << " OperandVector &Operands,\n";
3208 OS << " unsigned MCK);\n\n";
3209 }
3210
3211 OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
3212
3213 // Emit the operand match diagnostic enum names.
3214 OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
3215 OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3216 emitOperandDiagnosticTypes(Info, OS);
3217 OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
3218
3219 OS << "\n#ifdef GET_REGISTER_MATCHER\n";
3220 OS << "#undef GET_REGISTER_MATCHER\n\n";
3221
3222 // Emit the subtarget feature enumeration.
3223 SubtargetFeatureInfo::emitSubtargetFeatureFlagEnumeration(
3224 Info.SubtargetFeatures, OS);
3225
3226 // Emit the function to match a register name to number.
3227 // This should be omitted for Mips target
3228 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName"))
3229 emitMatchRegisterName(Target, AsmParser, OS);
3230
3231 if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterAltName"))
3232 emitMatchRegisterAltName(Target, AsmParser, OS);
3233
3234 OS << "#endif // GET_REGISTER_MATCHER\n\n";
3235
3236 OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
3237 OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
3238
3239 // Generate the helper function to get the names for subtarget features.
3240 emitGetSubtargetFeatureName(Info, OS);
3241
3242 OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
3243
3244 OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
3245 OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
3246
3247 // Generate the function that remaps for mnemonic aliases.
3248 bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target);
3249
3250 // Generate the convertToMCInst function to convert operands into an MCInst.
3251 // Also, generate the convertToMapAndConstraints function for MS-style inline
3252 // assembly. The latter doesn't actually generate a MCInst.
3253 emitConvertFuncs(Target, ClassName, Info.Matchables, HasMnemonicFirst,
3254 HasOptionalOperands, OS);
3255
3256 // Emit the enumeration for classes which participate in matching.
3257 emitMatchClassEnumeration(Target, Info.Classes, OS);
3258
3259 // Emit a function to get the user-visible string to describe an operand
3260 // match failure in diagnostics.
3261 emitOperandMatchErrorDiagStrings(Info, OS);
3262
3263 // Emit a function to map register classes to operand match failure codes.
3264 emitRegisterMatchErrorFunc(Info, OS);
3265
3266 // Emit the routine to match token strings to their match class.
3267 emitMatchTokenString(Target, Info.Classes, OS);
3268
3269 // Emit the subclass predicate routine.
3270 emitIsSubclass(Target, Info.Classes, OS);
3271
3272 // Emit the routine to validate an operand against a match class.
3273 emitValidateOperandClass(Info, OS);
3274
3275 emitMatchClassKindNames(Info.Classes, OS);
3276
3277 // Emit the available features compute function.
3278 SubtargetFeatureInfo::emitComputeAssemblerAvailableFeatures(
3279 Info.Target.getName(), ClassName, "ComputeAvailableFeatures",
3280 Info.SubtargetFeatures, OS);
3281
3282 if (!ReportMultipleNearMisses)
3283 emitAsmTiedOperandConstraints(Target, Info, OS);
3284
3285 StringToOffsetTable StringTable;
3286
3287 size_t MaxNumOperands = 0;
3288 unsigned MaxMnemonicIndex = 0;
3289 bool HasDeprecation = false;
3290 for (const auto &MI : Info.Matchables) {
3291 MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
3292 HasDeprecation |= MI->HasDeprecation;
3293
3294 // Store a pascal-style length byte in the mnemonic.
3295 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
3296 MaxMnemonicIndex = std::max(MaxMnemonicIndex,
3297 StringTable.GetOrAddStringOffset(LenMnemonic, false));
3298 }
3299
3300 OS << "static const char *const MnemonicTable =\n";
3301 StringTable.EmitString(OS);
3302 OS << ";\n\n";
3303
3304 // Emit the static match table; unused classes get initialized to 0 which is
3305 // guaranteed to be InvalidMatchClass.
3306 //
3307 // FIXME: We can reduce the size of this table very easily. First, we change
3308 // it so that store the kinds in separate bit-fields for each index, which
3309 // only needs to be the max width used for classes at that index (we also need
3310 // to reject based on this during classification). If we then make sure to
3311 // order the match kinds appropriately (putting mnemonics last), then we
3312 // should only end up using a few bits for each class, especially the ones
3313 // following the mnemonic.
3314 OS << "namespace {\n";
3315 OS << " struct MatchEntry {\n";
3316 OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
3317 << " Mnemonic;\n";
3318 OS << " uint16_t Opcode;\n";
3319 OS << " " << getMinimalTypeForRange(Info.Matchables.size())
3320 << " ConvertFn;\n";
3321 OS << " " << getMinimalTypeForEnumBitfield(Info.SubtargetFeatures.size())
3322 << " RequiredFeatures;\n";
3323 OS << " " << getMinimalTypeForRange(
3324 std::distance(Info.Classes.begin(), Info.Classes.end()))
3325 << " Classes[" << MaxNumOperands << "];\n";
3326 OS << " StringRef getMnemonic() const {\n";
3327 OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
3328 OS << " MnemonicTable[Mnemonic]);\n";
3329 OS << " }\n";
3330 OS << " };\n\n";
3331
3332 OS << " // Predicate for searching for an opcode.\n";
3333 OS << " struct LessOpcode {\n";
3334 OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
3335 OS << " return LHS.getMnemonic() < RHS;\n";
3336 OS << " }\n";
3337 OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
3338 OS << " return LHS < RHS.getMnemonic();\n";
3339 OS << " }\n";
3340 OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
3341 OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
3342 OS << " }\n";
3343 OS << " };\n";
3344
3345 OS << "} // end anonymous namespace.\n\n";
3346
3347 unsigned VariantCount = Target.getAsmParserVariantCount();
3348 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3349 Record *AsmVariant = Target.getAsmParserVariant(VC);
3350 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3351
3352 OS << "static const MatchEntry MatchTable" << VC << "[] = {\n";
3353
3354 for (const auto &MI : Info.Matchables) {
3355 if (MI->AsmVariantID != AsmVariantNo)
3356 continue;
3357
3358 // Store a pascal-style length byte in the mnemonic.
3359 std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.str();
3360 OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
3361 << " /* " << MI->Mnemonic << " */, "
3362 << Target.getInstNamespace() << "::"
3363 << MI->getResultInst()->TheDef->getName() << ", "
3364 << MI->ConversionFnKind << ", ";
3365
3366 // Write the required features mask.
3367 if (!MI->RequiredFeatures.empty()) {
3368 for (unsigned i = 0, e = MI->RequiredFeatures.size(); i != e; ++i) {
3369 if (i) OS << "|";
3370 OS << MI->RequiredFeatures[i]->getEnumName();
3371 }
3372 } else
3373 OS << "0";
3374
3375 OS << ", { ";
3376 for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
3377 const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
3378
3379 if (i) OS << ", ";
3380 OS << Op.Class->Name;
3381 }
3382 OS << " }, },\n";
3383 }
3384
3385 OS << "};\n\n";
3386 }
3387
3388 OS << "#include \"llvm/Support/Debug.h\"\n";
3389 OS << "#include \"llvm/Support/Format.h\"\n\n";
3390
3391 // Finally, build the match function.
3392 OS << "unsigned " << Target.getName() << ClassName << "::\n"
3393 << "MatchInstructionImpl(const OperandVector &Operands,\n";
3394 OS << " MCInst &Inst,\n";
3395 if (ReportMultipleNearMisses)
3396 OS << " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
3397 else
3398 OS << " uint64_t &ErrorInfo,\n";
3399 OS << " bool matchingInlineAsm, unsigned VariantID) {\n";
3400
3401 if (!ReportMultipleNearMisses) {
3402 OS << " // Eliminate obvious mismatches.\n";
3403 OS << " if (Operands.size() > "
3404 << (MaxNumOperands + HasMnemonicFirst) << ") {\n";
3405 OS << " ErrorInfo = "
3406 << (MaxNumOperands + HasMnemonicFirst) << ";\n";
3407 OS << " return Match_InvalidOperand;\n";
3408 OS << " }\n\n";
3409 }
3410
3411 // Emit code to get the available features.
3412 OS << " // Get the current feature set.\n";
3413 OS << " uint64_t AvailableFeatures = getAvailableFeatures();\n\n";
3414
3415 OS << " // Get the instruction mnemonic, which is the first token.\n";
3416 if (HasMnemonicFirst) {
3417 OS << " StringRef Mnemonic = ((" << Target.getName()
3418 << "Operand&)*Operands[0]).getToken();\n\n";
3419 } else {
3420 OS << " StringRef Mnemonic;\n";
3421 OS << " if (Operands[0]->isToken())\n";
3422 OS << " Mnemonic = ((" << Target.getName()
3423 << "Operand&)*Operands[0]).getToken();\n\n";
3424 }
3425
3426 if (HasMnemonicAliases) {
3427 OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
3428 OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n";
3429 }
3430
3431 // Emit code to compute the class list for this operand vector.
3432 if (!ReportMultipleNearMisses) {
3433 OS << " // Some state to try to produce better error messages.\n";
3434 OS << " bool HadMatchOtherThanFeatures = false;\n";
3435 OS << " bool HadMatchOtherThanPredicate = false;\n";
3436 OS << " unsigned RetCode = Match_InvalidOperand;\n";
3437 OS << " uint64_t MissingFeatures = ~0ULL;\n";
3438 OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
3439 OS << " // wrong for all instances of the instruction.\n";
3440 OS << " ErrorInfo = ~0ULL;\n";
3441 }
3442
3443 if (HasOptionalOperands) {
3444 OS << " SmallBitVector OptionalOperandsMask(" << MaxNumOperands << ");\n";
3445 }
3446
3447 // Emit code to search the table.
3448 OS << " // Find the appropriate table for this asm variant.\n";
3449 OS << " const MatchEntry *Start, *End;\n";
3450 OS << " switch (VariantID) {\n";
3451 OS << " default: llvm_unreachable(\"invalid variant!\");\n";
3452 for (unsigned VC = 0; VC != VariantCount; ++VC) {
3453 Record *AsmVariant = Target.getAsmParserVariant(VC);
3454 int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
3455 OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
3456 << "); End = std::end(MatchTable" << VC << "); break;\n";
3457 }
3458 OS << " }\n";
3459
3460 OS << " // Search the table.\n";
3461 if (HasMnemonicFirst) {
3462 OS << " auto MnemonicRange = "
3463 "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
3464 } else {
3465 OS << " auto MnemonicRange = std::make_pair(Start, End);\n";
3466 OS << " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
3467 OS << " if (!Mnemonic.empty())\n";
3468 OS << " MnemonicRange = "
3469 "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
3470 }
3471
3472 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"AsmMatcher: found \" <<\n"
3473 << " std::distance(MnemonicRange.first, MnemonicRange.second) << \n"
3474 << " \" encodings with mnemonic '\" << Mnemonic << \"'\\n\");\n\n";
3475
3476 OS << " // Return a more specific error code if no mnemonics match.\n";
3477 OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
3478 OS << " return Match_MnemonicFail;\n\n";
3479
3480 OS << " for (const MatchEntry *it = MnemonicRange.first, "
3481 << "*ie = MnemonicRange.second;\n";
3482 OS << " it != ie; ++it) {\n";
3483 OS << " bool HasRequiredFeatures =\n";
3484 OS << " (AvailableFeatures & it->RequiredFeatures) == "
3485 "it->RequiredFeatures;\n";
3486 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Trying to match opcode \"\n";
3487 OS << " << MII.getName(it->Opcode) << \"\\n\");\n";
3488
3489 if (ReportMultipleNearMisses) {
3490 OS << " // Some state to record ways in which this instruction did not match.\n";
3491 OS << " NearMissInfo OperandNearMiss = NearMissInfo::getSuccess();\n";
3492 OS << " NearMissInfo FeaturesNearMiss = NearMissInfo::getSuccess();\n";
3493 OS << " NearMissInfo EarlyPredicateNearMiss = NearMissInfo::getSuccess();\n";
3494 OS << " NearMissInfo LatePredicateNearMiss = NearMissInfo::getSuccess();\n";
3495 OS << " bool MultipleInvalidOperands = false;\n";
3496 }
3497
3498 if (HasMnemonicFirst) {
3499 OS << " // equal_range guarantees that instruction mnemonic matches.\n";
3500 OS << " assert(Mnemonic == it->getMnemonic());\n";
3501 }
3502
3503 // Emit check that the subclasses match.
3504 if (!ReportMultipleNearMisses)
3505 OS << " bool OperandsValid = true;\n";
3506 if (HasOptionalOperands) {
3507 OS << " OptionalOperandsMask.reset(0, " << MaxNumOperands << ");\n";
3508 }
3509 OS << " for (unsigned FormalIdx = " << (HasMnemonicFirst ? "0" : "SIndex")
3510 << ", ActualIdx = " << (HasMnemonicFirst ? "1" : "SIndex")
3511 << "; FormalIdx != " << MaxNumOperands << "; ++FormalIdx) {\n";
3512 OS << " auto Formal = "
3513 << "static_cast<MatchClassKind>(it->Classes[FormalIdx]);\n";
3514 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3515 OS << " dbgs() << \" Matching formal operand class \" << getMatchClassName(Formal)\n";
3516 OS << " << \" against actual operand at index \" << ActualIdx);\n";
3517 OS << " if (ActualIdx < Operands.size())\n";
3518 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \" (\";\n";
3519 OS << " Operands[ActualIdx]->print(dbgs()); dbgs() << \"): \");\n";
3520 OS << " else\n";
3521 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \": \");\n";
3522 OS << " if (ActualIdx >= Operands.size()) {\n";
3523 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"actual operand index out of range \");\n";
3524 if (ReportMultipleNearMisses) {
3525 OS << " bool ThisOperandValid = (Formal == " <<"InvalidMatchClass) || "
3526 "isSubclass(Formal, OptionalMatchClass);\n";
3527 OS << " if (!ThisOperandValid) {\n";
3528 OS << " if (!OperandNearMiss) {\n";
3529 OS << " // Record info about match failure for later use.\n";
3530 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"recording too-few-operands near miss\\n\");\n";
3531 OS << " OperandNearMiss =\n";
3532 OS << " NearMissInfo::getTooFewOperands(Formal, it->Opcode);\n";
3533 OS << " } else if (OperandNearMiss.getKind() != NearMissInfo::NearMissTooFewOperands) {\n";
3534 OS << " // If more than one operand is invalid, give up on this match entry.\n";
3535 OS << " DEBUG_WITH_TYPE(\n";
3536 OS << " \"asm-matcher\",\n";
3537 OS << " dbgs() << \"second invalid operand, giving up on this opcode\\n\");\n";
3538 OS << " MultipleInvalidOperands = true;\n";
3539 OS << " break;\n";
3540 OS << " }\n";
3541 OS << " } else {\n";
3542 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"but formal operand not required\\n\");\n";
3543 OS << " break;\n";
3544 OS << " }\n";
3545 OS << " continue;\n";
3546 } else {
3547 OS << " OperandsValid = (Formal == InvalidMatchClass) || isSubclass(Formal, OptionalMatchClass);\n";
3548 OS << " if (!OperandsValid) ErrorInfo = ActualIdx;\n";
3549 if (HasOptionalOperands) {
3550 OS << " OptionalOperandsMask.set(FormalIdx, " << MaxNumOperands
3551 << ");\n";
3552 }
3553 OS << " break;\n";
3554 }
3555 OS << " }\n";
3556 OS << " MCParsedAsmOperand &Actual = *Operands[ActualIdx];\n";
3557 OS << " unsigned Diag = validateOperandClass(Actual, Formal);\n";
3558 OS << " if (Diag == Match_Success) {\n";
3559 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3560 OS << " dbgs() << \"match success using generic matcher\\n\");\n";
3561 OS << " ++ActualIdx;\n";
3562 OS << " continue;\n";
3563 OS << " }\n";
3564 OS << " // If the generic handler indicates an invalid operand\n";
3565 OS << " // failure, check for a special case.\n";
3566 OS << " if (Diag != Match_Success) {\n";
3567 OS << " unsigned TargetDiag = validateTargetOperandClass(Actual, Formal);\n";
3568 OS << " if (TargetDiag == Match_Success) {\n";
3569 OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
3570 OS << " dbgs() << \"match success using target matcher\\n\");\n";
3571 OS << " ++ActualIdx;\n";
3572 OS << " continue;\n";
3573 OS << " }\n";
3574 OS << " // If the target matcher returned a specific error code use\n";
3575 OS << " // that, else use the one from the generic matcher.\n";
3576 OS << " if (TargetDiag != Match_InvalidOperand && "
3577 "HasRequiredFeatures)\n";
3578 OS << " Diag = TargetDiag;\n";
3579 OS << " }\n";
3580 OS << " // If current formal operand wasn't matched and it is optional\n"
3581 << " // then try to match next formal operand\n";
3582 OS << " if (Diag == Match_InvalidOperand "
3583 << "&& isSubclass(Formal, OptionalMatchClass)) {\n";
3584 if (HasOptionalOperands) {
3585 OS << " OptionalOperandsMask.set(FormalIdx);\n";
3586 }
3587 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"ignoring optional operand\\n\");\n";
3588 OS << " continue;\n";
3589 OS << " }\n";
3590
3591 if (ReportMultipleNearMisses) {
3592 OS << " if (!OperandNearMiss) {\n";
3593 OS << " // If this is the first invalid operand we have seen, record some\n";
3594 OS << " // information about it.\n";
3595 OS << " DEBUG_WITH_TYPE(\n";
3596 OS << " \"asm-matcher\",\n";
3597 OS << " dbgs()\n";
3598 OS << " << \"operand match failed, recording near-miss with diag code \"\n";
3599 OS << " << Diag << \"\\n\");\n";
3600 OS << " OperandNearMiss =\n";
3601 OS << " NearMissInfo::getMissedOperand(Diag, Formal, it->Opcode, ActualIdx);\n";
3602 OS << " ++ActualIdx;\n";
3603 OS << " } else {\n";
3604 OS << " // If more than one operand is invalid, give up on this match entry.\n";
3605 OS << " DEBUG_WITH_TYPE(\n";
3606 OS << " \"asm-matcher\",\n";
3607 OS << " dbgs() << \"second operand mismatch, skipping this opcode\\n\");\n";
3608 OS << " MultipleInvalidOperands = true;\n";
3609 OS << " break;\n";
3610 OS << " }\n";
3611 OS << " }\n\n";
3612 } else {
3613 OS << " // If this operand is broken for all of the instances of this\n";
3614 OS << " // mnemonic, keep track of it so we can report loc info.\n";
3615 OS << " // If we already had a match that only failed due to a\n";
3616 OS << " // target predicate, that diagnostic is preferred.\n";
3617 OS << " if (!HadMatchOtherThanPredicate &&\n";
3618 OS << " (it == MnemonicRange.first || ErrorInfo <= ActualIdx)) {\n";
3619 OS << " if (HasRequiredFeatures && (ErrorInfo != ActualIdx || Diag "
3620 "!= Match_InvalidOperand))\n";
3621 OS << " RetCode = Diag;\n";
3622 OS << " ErrorInfo = ActualIdx;\n";
3623 OS << " }\n";
3624 OS << " // Otherwise, just reject this instance of the mnemonic.\n";
3625 OS << " OperandsValid = false;\n";
3626 OS << " break;\n";
3627 OS << " }\n\n";
3628 }
3629
3630 if (ReportMultipleNearMisses)
3631 OS << " if (MultipleInvalidOperands) {\n";
3632 else
3633 OS << " if (!OperandsValid) {\n";
3634 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3635 OS << " \"operand mismatches, ignoring \"\n";
3636 OS << " \"this opcode\\n\");\n";
3637 OS << " continue;\n";
3638 OS << " }\n";
3639
3640 // Emit check that the required features are available.
3641 OS << " if (!HasRequiredFeatures) {\n";
3642 if (!ReportMultipleNearMisses)
3643 OS << " HadMatchOtherThanFeatures = true;\n";
3644 OS << " uint64_t NewMissingFeatures = it->RequiredFeatures & "
3645 "~AvailableFeatures;\n";
3646 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Missing target features: \"\n";
3647 OS << " << format_hex(NewMissingFeatures, 18)\n";
3648 OS << " << \"\\n\");\n";
3649 if (ReportMultipleNearMisses) {
3650 OS << " FeaturesNearMiss = NearMissInfo::getMissedFeature(NewMissingFeatures);\n";
3651 } else {
3652 OS << " if (countPopulation(NewMissingFeatures) <=\n"
3653 " countPopulation(MissingFeatures))\n";
3654 OS << " MissingFeatures = NewMissingFeatures;\n";
3655 OS << " continue;\n";
3656 }
3657 OS << " }\n";
3658 OS << "\n";
3659 OS << " Inst.clear();\n\n";
3660 OS << " Inst.setOpcode(it->Opcode);\n";
3661 // Verify the instruction with the target-specific match predicate function.
3662 OS << " // We have a potential match but have not rendered the operands.\n"
3663 << " // Check the target predicate to handle any context sensitive\n"
3664 " // constraints.\n"
3665 << " // For example, Ties that are referenced multiple times must be\n"
3666 " // checked here to ensure the input is the same for each match\n"
3667 " // constraints. If we leave it any later the ties will have been\n"
3668 " // canonicalized\n"
3669 << " unsigned MatchResult;\n"
3670 << " if ((MatchResult = checkEarlyTargetMatchPredicate(Inst, "
3671 "Operands)) != Match_Success) {\n"
3672 << " Inst.clear();\n";
3673 OS << " DEBUG_WITH_TYPE(\n";
3674 OS << " \"asm-matcher\",\n";
3675 OS << " dbgs() << \"Early target match predicate failed with diag code \"\n";
3676 OS << " << MatchResult << \"\\n\");\n";
3677 if (ReportMultipleNearMisses) {
3678 OS << " EarlyPredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
3679 } else {
3680 OS << " RetCode = MatchResult;\n"
3681 << " HadMatchOtherThanPredicate = true;\n"
3682 << " continue;\n";
3683 }
3684 OS << " }\n\n";
3685
3686 if (ReportMultipleNearMisses) {
3687 OS << " // If we did not successfully match the operands, then we can't convert to\n";
3688 OS << " // an MCInst, so bail out on this instruction variant now.\n";
3689 OS << " if (OperandNearMiss) {\n";
3690 OS << " // If the operand mismatch was the only problem, reprrt it as a near-miss.\n";
3691 OS << " if (NearMisses && !FeaturesNearMiss && !EarlyPredicateNearMiss) {\n";
3692 OS << " DEBUG_WITH_TYPE(\n";
3693 OS << " \"asm-matcher\",\n";
3694 OS << " dbgs()\n";
3695 OS << " << \"Opcode result: one mismatched operand, adding near-miss\\n\");\n";
3696 OS << " NearMisses->push_back(OperandNearMiss);\n";
3697 OS << " } else {\n";
3698 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3699 OS << " \"types of mismatch, so not \"\n";
3700 OS << " \"reporting near-miss\\n\");\n";
3701 OS << " }\n";
3702 OS << " continue;\n";
3703 OS << " }\n\n";
3704 }
3705
3706 OS << " if (matchingInlineAsm) {\n";
3707 OS << " convertToMapAndConstraints(it->ConvertFn, Operands);\n";
3708 if (!ReportMultipleNearMisses) {
3709 OS << " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
3710 "Operands, ErrorInfo))\n";
3711 OS << " return Match_InvalidTiedOperand;\n";
3712 OS << "\n";
3713 }
3714 OS << " return Match_Success;\n";
3715 OS << " }\n\n";
3716 OS << " // We have selected a definite instruction, convert the parsed\n"
3717 << " // operands into the appropriate MCInst.\n";
3718 if (HasOptionalOperands) {
3719 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands,\n"
3720 << " OptionalOperandsMask);\n";
3721 } else {
3722 OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
3723 }
3724 OS << "\n";
3725
3726 // Verify the instruction with the target-specific match predicate function.
3727 OS << " // We have a potential match. Check the target predicate to\n"
3728 << " // handle any context sensitive constraints.\n"
3729 << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
3730 << " Match_Success) {\n"
3731 << " DEBUG_WITH_TYPE(\"asm-matcher\",\n"
3732 << " dbgs() << \"Target match predicate failed with diag code \"\n"
3733 << " << MatchResult << \"\\n\");\n"
3734 << " Inst.clear();\n";
3735 if (ReportMultipleNearMisses) {
3736 OS << " LatePredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
3737 } else {
3738 OS << " RetCode = MatchResult;\n"
3739 << " HadMatchOtherThanPredicate = true;\n"
3740 << " continue;\n";
3741 }
3742 OS << " }\n\n";
3743
3744 if (ReportMultipleNearMisses) {
3745 OS << " int NumNearMisses = ((int)(bool)OperandNearMiss +\n";
3746 OS << " (int)(bool)FeaturesNearMiss +\n";
3747 OS << " (int)(bool)EarlyPredicateNearMiss +\n";
3748 OS << " (int)(bool)LatePredicateNearMiss);\n";
3749 OS << " if (NumNearMisses == 1) {\n";
3750 OS << " // We had exactly one type of near-miss, so add that to the list.\n";
3751 OS << " assert(!OperandNearMiss && \"OperandNearMiss was handled earlier\");\n";
3752 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: found one type of \"\n";
3753 OS << " \"mismatch, so reporting a \"\n";
3754 OS << " \"near-miss\\n\");\n";
3755 OS << " if (NearMisses && FeaturesNearMiss)\n";
3756 OS << " NearMisses->push_back(FeaturesNearMiss);\n";
3757 OS << " else if (NearMisses && EarlyPredicateNearMiss)\n";
3758 OS << " NearMisses->push_back(EarlyPredicateNearMiss);\n";
3759 OS << " else if (NearMisses && LatePredicateNearMiss)\n";
3760 OS << " NearMisses->push_back(LatePredicateNearMiss);\n";
3761 OS << "\n";
3762 OS << " continue;\n";
3763 OS << " } else if (NumNearMisses > 1) {\n";
3764 OS << " // This instruction missed in more than one way, so ignore it.\n";
3765 OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
3766 OS << " \"types of mismatch, so not \"\n";
3767 OS << " \"reporting near-miss\\n\");\n";
3768 OS << " continue;\n";
3769 OS << " }\n";
3770 }
3771
3772 // Call the post-processing function, if used.
3773 StringRef InsnCleanupFn = AsmParser->getValueAsString("AsmParserInstCleanup");
3774 if (!InsnCleanupFn.empty())
3775 OS << " " << InsnCleanupFn << "(Inst);\n";
3776
3777 if (HasDeprecation) {
3778 OS << " std::string Info;\n";
3779 OS << " if (!getParser().getTargetParser().\n";
3780 OS << " getTargetOptions().MCNoDeprecatedWarn &&\n";
3781 OS << " MII.get(Inst.getOpcode()).getDeprecatedInfo(Inst, getSTI(), Info)) {\n";
3782 OS << " SMLoc Loc = ((" << Target.getName()
3783 << "Operand&)*Operands[0]).getStartLoc();\n";
3784 OS << " getParser().Warning(Loc, Info, None);\n";
3785 OS << " }\n";
3786 }
3787
3788 if (!ReportMultipleNearMisses) {
3789 OS << " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
3790 "Operands, ErrorInfo))\n";
3791 OS << " return Match_InvalidTiedOperand;\n";
3792 OS << "\n";
3793 }
3794
3795 OS << " DEBUG_WITH_TYPE(\n";
3796 OS << " \"asm-matcher\",\n";
3797 OS << " dbgs() << \"Opcode result: complete match, selecting this opcode\\n\");\n";
3798 OS << " return Match_Success;\n";
3799 OS << " }\n\n";
3800
3801 if (ReportMultipleNearMisses) {
3802 OS << " // No instruction variants matched exactly.\n";
3803 OS << " return Match_NearMisses;\n";
3804 } else {
3805 OS << " // Okay, we had no match. Try to return a useful error code.\n";
3806 OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n";
3807 OS << " return RetCode;\n\n";
3808 OS << " // Missing feature matches return which features were missing\n";
3809 OS << " ErrorInfo = MissingFeatures;\n";
3810 OS << " return Match_MissingFeature;\n";
3811 }
3812 OS << "}\n\n";
3813
3814 if (!Info.OperandMatchInfo.empty())
3815 emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable,
3816 MaxMnemonicIndex, HasMnemonicFirst);
3817
3818 OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
3819
3820 OS << "\n#ifdef GET_MNEMONIC_SPELL_CHECKER\n";
3821 OS << "#undef GET_MNEMONIC_SPELL_CHECKER\n\n";
3822
3823 emitMnemonicSpellChecker(OS, Target, VariantCount);
3824
3825 OS << "#endif // GET_MNEMONIC_SPELL_CHECKER\n\n";
3826 }
3827
3828 namespace llvm {
3829
EmitAsmMatcher(RecordKeeper & RK,raw_ostream & OS)3830 void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
3831 emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
3832 AsmMatcherEmitter(RK).run(OS);
3833 }
3834
3835 } // end namespace llvm
3836