1 //===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This tablegen backend emits an assembly printer for the current target.
10 // Note that this is currently fairly skeletal, but will grow over time.
12 //===----------------------------------------------------------------------===//
14 #include "Basic/SequenceToOffsetTable.h"
15 #include "Common/AsmWriterInst.h"
16 #include "Common/CodeGenInstAlias.h"
17 #include "Common/CodeGenInstruction.h"
18 #include "Common/CodeGenRegisters.h"
19 #include "Common/CodeGenTarget.h"
20 #include "Common/Types.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Format.h"
32 #include "llvm/Support/FormatVariadic.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/TableGen/Error.h"
36 #include "llvm/TableGen/Record.h"
37 #include "llvm/TableGen/TableGenBackend.h"
53 #define DEBUG_TYPE "asm-writer-emitter"
57 class AsmWriterEmitter
{
58 const RecordKeeper
&Records
;
60 ArrayRef
<const CodeGenInstruction
*> NumberedInstructions
;
61 std::vector
<AsmWriterInst
> Instructions
;
64 AsmWriterEmitter(const RecordKeeper
&R
);
66 void run(raw_ostream
&o
);
71 std::vector
<std::vector
<std::string
>> &TableDrivenOperandPrinters
,
72 unsigned &BitsLeft
, unsigned &AsmStrBits
);
73 void EmitPrintInstruction(
75 std::vector
<std::vector
<std::string
>> &TableDrivenOperandPrinters
,
76 unsigned &BitsLeft
, unsigned &AsmStrBits
);
77 void EmitGetRegisterName(raw_ostream
&o
);
78 void EmitPrintAliasInstruction(raw_ostream
&O
);
80 void FindUniqueOperandCommands(std::vector
<std::string
> &UOC
,
81 std::vector
<std::vector
<unsigned>> &InstIdxs
,
82 std::vector
<unsigned> &InstOpsUsed
,
83 bool PassSubtarget
) const;
86 } // end anonymous namespace
89 PrintCases(std::vector
<std::pair
<std::string
, AsmWriterOperand
>> &OpsToPrint
,
90 raw_ostream
&O
, bool PassSubtarget
) {
91 O
<< " case " << OpsToPrint
.back().first
<< ":";
92 AsmWriterOperand TheOp
= OpsToPrint
.back().second
;
93 OpsToPrint
.pop_back();
95 // Check to see if any other operands are identical in this list, and if so,
96 // emit a case label for them.
97 for (unsigned i
= OpsToPrint
.size(); i
!= 0; --i
)
98 if (OpsToPrint
[i
- 1].second
== TheOp
) {
99 O
<< "\n case " << OpsToPrint
[i
- 1].first
<< ":";
100 OpsToPrint
.erase(OpsToPrint
.begin() + i
- 1);
103 // Finally, emit the code.
104 O
<< "\n " << TheOp
.getCode(PassSubtarget
);
108 /// EmitInstructions - Emit the last instruction in the vector and any other
109 /// instructions that are suitably similar to it.
110 static void EmitInstructions(std::vector
<AsmWriterInst
> &Insts
, raw_ostream
&O
,
111 bool PassSubtarget
) {
112 AsmWriterInst FirstInst
= Insts
.back();
115 std::vector
<AsmWriterInst
> SimilarInsts
;
116 unsigned DifferingOperand
= ~0;
117 for (unsigned i
= Insts
.size(); i
!= 0; --i
) {
118 unsigned DiffOp
= Insts
[i
- 1].MatchesAllButOneOp(FirstInst
);
120 if (DifferingOperand
== ~0U) // First match!
121 DifferingOperand
= DiffOp
;
123 // If this differs in the same operand as the rest of the instructions in
124 // this class, move it to the SimilarInsts list.
125 if (DifferingOperand
== DiffOp
|| DiffOp
== ~0U) {
126 SimilarInsts
.push_back(Insts
[i
- 1]);
127 Insts
.erase(Insts
.begin() + i
- 1);
132 O
<< " case " << FirstInst
.CGI
->Namespace
133 << "::" << FirstInst
.CGI
->TheDef
->getName() << ":\n";
134 for (const AsmWriterInst
&AWI
: SimilarInsts
)
135 O
<< " case " << AWI
.CGI
->Namespace
<< "::" << AWI
.CGI
->TheDef
->getName()
137 for (unsigned i
= 0, e
= FirstInst
.Operands
.size(); i
!= e
; ++i
) {
138 if (i
!= DifferingOperand
) {
139 // If the operand is the same for all instructions, just print it.
140 O
<< " " << FirstInst
.Operands
[i
].getCode(PassSubtarget
);
142 // If this is the operand that varies between all of the instructions,
143 // emit a switch for just this operand now.
144 O
<< " switch (MI->getOpcode()) {\n";
145 O
<< " default: llvm_unreachable(\"Unexpected opcode.\");\n";
146 std::vector
<std::pair
<std::string
, AsmWriterOperand
>> OpsToPrint
;
147 OpsToPrint
.push_back(std::pair(FirstInst
.CGI
->Namespace
.str() + "::" +
148 FirstInst
.CGI
->TheDef
->getName().str(),
149 FirstInst
.Operands
[i
]));
151 for (const AsmWriterInst
&AWI
: SimilarInsts
) {
152 OpsToPrint
.push_back(std::pair(
153 AWI
.CGI
->Namespace
.str() + "::" + AWI
.CGI
->TheDef
->getName().str(),
156 std::reverse(OpsToPrint
.begin(), OpsToPrint
.end());
157 while (!OpsToPrint
.empty())
158 PrintCases(OpsToPrint
, O
, PassSubtarget
);
166 void AsmWriterEmitter::FindUniqueOperandCommands(
167 std::vector
<std::string
> &UniqueOperandCommands
,
168 std::vector
<std::vector
<unsigned>> &InstIdxs
,
169 std::vector
<unsigned> &InstOpsUsed
, bool PassSubtarget
) const {
170 // This vector parallels UniqueOperandCommands, keeping track of which
171 // instructions each case are used for. It is a comma separated string of
173 std::vector
<std::string
> InstrsForCase
;
174 InstrsForCase
.resize(UniqueOperandCommands
.size());
175 InstOpsUsed
.assign(UniqueOperandCommands
.size(), 0);
177 for (size_t i
= 0, e
= Instructions
.size(); i
!= e
; ++i
) {
178 const AsmWriterInst
&Inst
= Instructions
[i
];
179 if (Inst
.Operands
.empty())
180 continue; // Instruction already done.
182 std::string Command
=
183 " " + Inst
.Operands
[0].getCode(PassSubtarget
) + "\n";
185 // Check to see if we already have 'Command' in UniqueOperandCommands.
187 auto I
= llvm::find(UniqueOperandCommands
, Command
);
188 if (I
!= UniqueOperandCommands
.end()) {
189 size_t idx
= I
- UniqueOperandCommands
.begin();
190 InstrsForCase
[idx
] += ", ";
191 InstrsForCase
[idx
] += Inst
.CGI
->TheDef
->getName();
192 InstIdxs
[idx
].push_back(i
);
194 UniqueOperandCommands
.push_back(std::move(Command
));
195 InstrsForCase
.push_back(std::string(Inst
.CGI
->TheDef
->getName()));
196 InstIdxs
.emplace_back();
197 InstIdxs
.back().push_back(i
);
199 // This command matches one operand so far.
200 InstOpsUsed
.push_back(1);
204 // For each entry of UniqueOperandCommands, there is a set of instructions
205 // that uses it. If the next command of all instructions in the set are
206 // identical, fold it into the command.
207 for (size_t CommandIdx
= 0, e
= UniqueOperandCommands
.size(); CommandIdx
!= e
;
210 const auto &Idxs
= InstIdxs
[CommandIdx
];
212 for (unsigned Op
= 1;; ++Op
) {
213 // Find the first instruction in the set.
214 const AsmWriterInst
&FirstInst
= Instructions
[Idxs
.front()];
215 // If this instruction has no more operands, we isn't anything to merge
216 // into this command.
217 if (FirstInst
.Operands
.size() == Op
)
220 // Otherwise, scan to see if all of the other instructions in this command
221 // set share the operand.
222 if (any_of(drop_begin(Idxs
), [&](unsigned Idx
) {
223 const AsmWriterInst
&OtherInst
= Instructions
[Idx
];
224 return OtherInst
.Operands
.size() == Op
||
225 OtherInst
.Operands
[Op
] != FirstInst
.Operands
[Op
];
229 // Okay, everything in this command set has the same next operand. Add it
230 // to UniqueOperandCommands and remember that it was consumed.
231 std::string Command
=
232 " " + FirstInst
.Operands
[Op
].getCode(PassSubtarget
) + "\n";
234 UniqueOperandCommands
[CommandIdx
] += Command
;
235 InstOpsUsed
[CommandIdx
]++;
239 // Prepend some of the instructions each case is used for onto the case val.
240 for (unsigned i
= 0, e
= InstrsForCase
.size(); i
!= e
; ++i
) {
241 std::string Instrs
= InstrsForCase
[i
];
242 if (Instrs
.size() > 70) {
243 Instrs
.erase(Instrs
.begin() + 70, Instrs
.end());
248 UniqueOperandCommands
[i
] =
249 " // " + Instrs
+ "\n" + UniqueOperandCommands
[i
];
253 static void UnescapeString(std::string
&Str
) {
254 for (unsigned i
= 0; i
!= Str
.size(); ++i
) {
255 if (Str
[i
] == '\\' && i
!= Str
.size() - 1) {
256 switch (Str
[i
+ 1]) {
258 continue; // Don't execute the code after the switch.
293 // Nuke the second character.
294 Str
.erase(Str
.begin() + i
+ 1);
299 /// UnescapeAliasString - Supports literal braces in InstAlias asm string which
300 /// are escaped with '\\' to avoid being interpreted as variants. Braces must
301 /// be unescaped before c++ code is generated as (e.g.):
303 /// AsmString = "foo \{$\x01\}";
305 /// causes non-standard escape character warnings.
306 static void UnescapeAliasString(std::string
&Str
) {
307 for (unsigned i
= 0; i
!= Str
.size(); ++i
) {
308 if (Str
[i
] == '\\' && i
!= Str
.size() - 1) {
309 switch (Str
[i
+ 1]) {
311 continue; // Don't execute the code after the switch.
319 // Nuke the second character.
320 Str
.erase(Str
.begin() + i
+ 1);
325 void AsmWriterEmitter::EmitGetMnemonic(
327 std::vector
<std::vector
<std::string
>> &TableDrivenOperandPrinters
,
328 unsigned &BitsLeft
, unsigned &AsmStrBits
) {
329 const Record
*AsmWriter
= Target
.getAsmWriter();
330 StringRef ClassName
= AsmWriter
->getValueAsString("AsmWriterClassName");
331 bool PassSubtarget
= AsmWriter
->getValueAsInt("PassSubtarget");
333 O
<< "/// getMnemonic - This method is automatically generated by "
335 "/// from the instruction set description.\n"
336 "std::pair<const char *, uint64_t>\n"
337 << Target
.getName() << ClassName
338 << "::getMnemonic(const MCInst &MI) const {\n";
340 // Build an aggregate string, and build a table of offsets into it.
341 SequenceToOffsetTable
<std::string
> StringTable
;
343 /// OpcodeInfo - This encodes the index of the string to use for the first
344 /// chunk of the output as well as indices used for operand printing.
345 std::vector
<uint64_t> OpcodeInfo(NumberedInstructions
.size());
346 const unsigned OpcodeInfoBits
= 64;
348 // Add all strings to the string table upfront so it can generate an optimized
350 for (AsmWriterInst
&AWI
: Instructions
) {
351 if (AWI
.Operands
[0].OperandType
== AsmWriterOperand::isLiteralTextOperand
&&
352 !AWI
.Operands
[0].Str
.empty()) {
353 std::string Str
= AWI
.Operands
[0].Str
;
355 StringTable
.add(Str
);
359 StringTable
.layout();
361 unsigned MaxStringIdx
= 0;
362 for (AsmWriterInst
&AWI
: Instructions
) {
364 if (AWI
.Operands
[0].OperandType
!= AsmWriterOperand::isLiteralTextOperand
||
365 AWI
.Operands
[0].Str
.empty()) {
366 // Something handled by the asmwriter printer, but with no leading string.
367 Idx
= StringTable
.get("");
369 std::string Str
= AWI
.Operands
[0].Str
;
371 Idx
= StringTable
.get(Str
);
372 MaxStringIdx
= std::max(MaxStringIdx
, Idx
);
374 // Nuke the string from the operand list. It is now handled!
375 AWI
.Operands
.erase(AWI
.Operands
.begin());
378 // Bias offset by one since we want 0 as a sentinel.
379 OpcodeInfo
[AWI
.CGIIndex
] = Idx
+ 1;
382 // Figure out how many bits we used for the string index.
383 AsmStrBits
= Log2_32_Ceil(MaxStringIdx
+ 2);
385 // To reduce code size, we compactify common instructions into a few bits
386 // in the opcode-indexed table.
387 BitsLeft
= OpcodeInfoBits
- AsmStrBits
;
390 std::vector
<std::string
> UniqueOperandCommands
;
391 std::vector
<std::vector
<unsigned>> InstIdxs
;
392 std::vector
<unsigned> NumInstOpsHandled
;
393 FindUniqueOperandCommands(UniqueOperandCommands
, InstIdxs
,
394 NumInstOpsHandled
, PassSubtarget
);
396 // If we ran out of operands to print, we're done.
397 if (UniqueOperandCommands
.empty())
400 // Compute the number of bits we need to represent these cases, this is
401 // ceil(log2(numentries)).
402 unsigned NumBits
= Log2_32_Ceil(UniqueOperandCommands
.size());
404 // If we don't have enough bits for this operand, don't include it.
405 if (NumBits
> BitsLeft
) {
406 LLVM_DEBUG(errs() << "Not enough bits to densely encode " << NumBits
411 // Otherwise, we can include this in the initial lookup table. Add it in.
412 for (size_t i
= 0, e
= InstIdxs
.size(); i
!= e
; ++i
) {
413 unsigned NumOps
= NumInstOpsHandled
[i
];
414 for (unsigned Idx
: InstIdxs
[i
]) {
415 OpcodeInfo
[Instructions
[Idx
].CGIIndex
] |=
416 (uint64_t)i
<< (OpcodeInfoBits
- BitsLeft
);
417 // Remove the info about this operand from the instruction.
418 AsmWriterInst
&Inst
= Instructions
[Idx
];
419 if (!Inst
.Operands
.empty()) {
420 assert(NumOps
<= Inst
.Operands
.size() &&
421 "Can't remove this many ops!");
422 Inst
.Operands
.erase(Inst
.Operands
.begin(),
423 Inst
.Operands
.begin() + NumOps
);
429 // Remember the handlers for this set of operands.
430 TableDrivenOperandPrinters
.push_back(std::move(UniqueOperandCommands
));
433 // Emit the string table itself.
434 StringTable
.emitStringLiteralDef(O
, " static const char AsmStrs[]");
436 // Emit the lookup tables in pieces to minimize wasted bytes.
437 unsigned BytesNeeded
= ((OpcodeInfoBits
- BitsLeft
) + 7) / 8;
438 unsigned Table
= 0, Shift
= 0;
439 SmallString
<128> BitsString
;
440 raw_svector_ostream
BitsOS(BitsString
);
441 // If the total bits is more than 32-bits we need to use a 64-bit type.
442 BitsOS
<< " uint" << ((BitsLeft
< (OpcodeInfoBits
- 32)) ? 64 : 32)
444 while (BytesNeeded
!= 0) {
445 // Figure out how big this table section needs to be, but no bigger than 4.
446 unsigned TableSize
= std::min(llvm::bit_floor(BytesNeeded
), 4u);
447 BytesNeeded
-= TableSize
;
448 TableSize
*= 8; // Convert to bits;
449 uint64_t Mask
= (1ULL << TableSize
) - 1;
450 O
<< " static const uint" << TableSize
<< "_t OpInfo" << Table
452 for (unsigned i
= 0, e
= NumberedInstructions
.size(); i
!= e
; ++i
) {
453 O
<< " " << ((OpcodeInfo
[i
] >> Shift
) & Mask
) << "U,\t// "
454 << NumberedInstructions
[i
]->TheDef
->getName() << "\n";
457 // Emit string to combine the individual table lookups.
458 BitsOS
<< " Bits |= ";
459 // If the total bits is more than 32-bits we need to use a 64-bit type.
460 if (BitsLeft
< (OpcodeInfoBits
- 32))
461 BitsOS
<< "(uint64_t)";
462 BitsOS
<< "OpInfo" << Table
<< "[MI.getOpcode()] << " << Shift
<< ";\n";
463 // Prepare the shift for the next iteration and increment the table count.
468 O
<< " // Emit the opcode for the instruction.\n";
471 // Make sure we don't return an invalid pointer if bits is 0
472 O
<< " if (Bits == 0)\n"
473 " return {nullptr, Bits};\n";
475 // Return mnemonic string and bits.
476 O
<< " return {AsmStrs+(Bits & " << (1 << AsmStrBits
) - 1
477 << ")-1, Bits};\n\n";
482 /// EmitPrintInstruction - Generate the code for the "printInstruction" method
483 /// implementation. Destroys all instances of AsmWriterInst information, by
484 /// clearing the Instructions vector.
485 void AsmWriterEmitter::EmitPrintInstruction(
487 std::vector
<std::vector
<std::string
>> &TableDrivenOperandPrinters
,
488 unsigned &BitsLeft
, unsigned &AsmStrBits
) {
489 const unsigned OpcodeInfoBits
= 64;
490 const Record
*AsmWriter
= Target
.getAsmWriter();
491 StringRef ClassName
= AsmWriter
->getValueAsString("AsmWriterClassName");
492 bool PassSubtarget
= AsmWriter
->getValueAsInt("PassSubtarget");
494 // This function has some huge switch statements that causing excessive
495 // compile time in LLVM profile instrumenation build. This print function
496 // usually is not frequently called in compilation. Here we disable the
497 // profile instrumenation for this function.
498 O
<< "/// printInstruction - This method is automatically generated by "
500 "/// from the instruction set description.\n"
501 "LLVM_NO_PROFILE_INSTRUMENT_FUNCTION\n"
503 << Target
.getName() << ClassName
504 << "::printInstruction(const MCInst *MI, uint64_t Address, "
505 << (PassSubtarget
? "const MCSubtargetInfo &STI, " : "")
506 << "raw_ostream &O) {\n";
508 // Emit the initial tab character.
509 O
<< " O << \"\\t\";\n\n";
511 // Emit the starting string.
512 O
<< " auto MnemonicInfo = getMnemonic(*MI);\n\n";
513 O
<< " O << MnemonicInfo.first;\n\n";
515 O
<< " uint" << ((BitsLeft
< (OpcodeInfoBits
- 32)) ? 64 : 32)
516 << "_t Bits = MnemonicInfo.second;\n"
517 << " assert(Bits != 0 && \"Cannot print this instruction.\");\n";
519 // Output the table driven operand information.
520 BitsLeft
= OpcodeInfoBits
- AsmStrBits
;
521 for (unsigned i
= 0, e
= TableDrivenOperandPrinters
.size(); i
!= e
; ++i
) {
522 std::vector
<std::string
> &Commands
= TableDrivenOperandPrinters
[i
];
524 // Compute the number of bits we need to represent these cases, this is
525 // ceil(log2(numentries)).
526 unsigned NumBits
= Log2_32_Ceil(Commands
.size());
527 assert(NumBits
<= BitsLeft
&& "consistency error");
529 // Emit code to extract this field from Bits.
530 O
<< "\n // Fragment " << i
<< " encoded into " << NumBits
<< " bits for "
531 << Commands
.size() << " unique commands.\n";
533 if (Commands
.size() == 2) {
534 // Emit two possibilitys with if/else.
535 O
<< " if ((Bits >> " << (OpcodeInfoBits
- BitsLeft
) << ") & "
536 << ((1 << NumBits
) - 1) << ") {\n"
537 << Commands
[1] << " } else {\n"
538 << Commands
[0] << " }\n\n";
539 } else if (Commands
.size() == 1) {
540 // Emit a single possibility.
541 O
<< Commands
[0] << "\n\n";
543 O
<< " switch ((Bits >> " << (OpcodeInfoBits
- BitsLeft
) << ") & "
544 << ((1 << NumBits
) - 1) << ") {\n"
545 << " default: llvm_unreachable(\"Invalid command number.\");\n";
547 // Print out all the cases.
548 for (unsigned j
= 0, e
= Commands
.size(); j
!= e
; ++j
) {
549 O
<< " case " << j
<< ":\n";
558 // Okay, delete instructions with no operand info left.
559 llvm::erase_if(Instructions
,
560 [](AsmWriterInst
&Inst
) { return Inst
.Operands
.empty(); });
562 // Because this is a vector, we want to emit from the end. Reverse all of the
563 // elements in the vector.
564 std::reverse(Instructions
.begin(), Instructions
.end());
566 // Now that we've emitted all of the operand info that fit into 64 bits, emit
567 // information for those instructions that are left. This is a less dense
568 // encoding, but we expect the main 64-bit table to handle the majority of
570 if (!Instructions
.empty()) {
571 // Find the opcode # of inline asm.
572 O
<< " switch (MI->getOpcode()) {\n";
573 O
<< " default: llvm_unreachable(\"Unexpected opcode.\");\n";
574 while (!Instructions
.empty())
575 EmitInstructions(Instructions
, O
, PassSubtarget
);
584 emitRegisterNameString(raw_ostream
&O
, StringRef AltName
,
585 const std::deque
<CodeGenRegister
> &Registers
) {
586 SequenceToOffsetTable
<std::string
> StringTable
;
587 SmallVector
<std::string
, 4> AsmNames(Registers
.size());
589 for (const auto &Reg
: Registers
) {
590 std::string
&AsmName
= AsmNames
[i
++];
592 // "NoRegAltName" is special. We don't need to do a lookup for that,
593 // as it's just a reference to the default register name.
594 if (AltName
== "" || AltName
== "NoRegAltName") {
595 AsmName
= std::string(Reg
.TheDef
->getValueAsString("AsmName"));
597 AsmName
= std::string(Reg
.getName());
599 // Make sure the register has an alternate name for this index.
600 std::vector
<const Record
*> AltNameList
=
601 Reg
.TheDef
->getValueAsListOfDefs("RegAltNameIndices");
603 for (e
= AltNameList
.size();
604 Idx
< e
&& (AltNameList
[Idx
]->getName() != AltName
); ++Idx
)
606 // If the register has an alternate name for this index, use it.
607 // Otherwise, leave it empty as an error flag.
609 std::vector
<StringRef
> AltNames
=
610 Reg
.TheDef
->getValueAsListOfStrings("AltNames");
611 if (AltNames
.size() <= Idx
)
612 PrintFatalError(Reg
.TheDef
->getLoc(),
613 "Register definition missing alt name for '" +
615 AsmName
= std::string(AltNames
[Idx
]);
618 StringTable
.add(AsmName
);
621 StringTable
.layout();
622 StringTable
.emitStringLiteralDef(O
, Twine(" static const char AsmStrs") +
625 O
<< " static const " << getMinimalTypeForRange(StringTable
.size() - 1, 32)
626 << " RegAsmOffset" << AltName
<< "[] = {";
627 for (unsigned i
= 0, e
= Registers
.size(); i
!= e
; ++i
) {
630 O
<< StringTable
.get(AsmNames
[i
]) << ", ";
636 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream
&O
) {
637 const Record
*AsmWriter
= Target
.getAsmWriter();
638 StringRef ClassName
= AsmWriter
->getValueAsString("AsmWriterClassName");
639 const auto &Registers
= Target
.getRegBank().getRegisters();
640 ArrayRef
<const Record
*> AltNameIndices
= Target
.getRegAltNameIndices();
641 bool hasAltNames
= AltNameIndices
.size() > 1;
642 StringRef Namespace
= Registers
.front().TheDef
->getValueAsString("Namespace");
644 O
<< "\n\n/// getRegisterName - This method is automatically generated by "
646 "/// from the register set description. This returns the assembler "
648 "/// for the specified register.\n"
650 << Target
.getName() << ClassName
<< "::";
652 O
<< "\ngetRegisterName(MCRegister Reg, unsigned AltIdx) {\n";
654 O
<< "getRegisterName(MCRegister Reg) {\n";
655 O
<< " unsigned RegNo = Reg.id();\n"
656 << " assert(RegNo && RegNo < " << (Registers
.size() + 1)
657 << " && \"Invalid register number!\");\n"
661 for (const Record
*R
: AltNameIndices
)
662 emitRegisterNameString(O
, R
->getName(), Registers
);
664 emitRegisterNameString(O
, "", Registers
);
667 O
<< " switch(AltIdx) {\n"
668 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n";
669 for (const Record
*R
: AltNameIndices
) {
670 StringRef AltName
= R
->getName();
672 if (!Namespace
.empty())
673 O
<< Namespace
<< "::";
674 O
<< AltName
<< ":\n";
675 if (R
->isValueUnset("FallbackRegAltNameIndex"))
676 O
<< " assert(*(AsmStrs" << AltName
<< "+RegAsmOffset" << AltName
678 << " \"Invalid alt name index for register!\");\n";
680 O
<< " if (!*(AsmStrs" << AltName
<< "+RegAsmOffset" << AltName
682 << " return getRegisterName(RegNo, ";
683 if (!Namespace
.empty())
684 O
<< Namespace
<< "::";
685 O
<< R
->getValueAsDef("FallbackRegAltNameIndex")->getName() << ");\n";
687 O
<< " return AsmStrs" << AltName
<< "+RegAsmOffset" << AltName
692 O
<< " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
693 << " \"Invalid alt name index for register!\");\n"
694 << " return AsmStrs+RegAsmOffset[RegNo-1];\n";
701 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
702 // they both have the same conditionals. In which case, we cannot print out the
703 // alias for that pattern.
705 std::map
<StringRef
, std::pair
<int, int>> OpMap
;
707 std::vector
<std::string
> Conds
;
710 std::string AsmString
;
715 IAPrinter(std::string R
, std::string AS
, unsigned NumMIOps
)
716 : Result(std::move(R
)), AsmString(std::move(AS
)), NumMIOps(NumMIOps
) {}
718 void addCond(std::string C
) { Conds
.push_back(std::move(C
)); }
719 ArrayRef
<std::string
> getConds() const { return Conds
; }
720 size_t getCondCount() const { return Conds
.size(); }
722 void addOperand(StringRef Op
, int OpIdx
, int PrintMethodIdx
= -1) {
723 assert(OpIdx
>= 0 && OpIdx
< 0xFE && "Idx out of range");
724 assert(PrintMethodIdx
>= -1 && PrintMethodIdx
< 0xFF && "Idx out of range");
725 OpMap
[Op
] = std::pair(OpIdx
, PrintMethodIdx
);
728 unsigned getNumMIOps() { return NumMIOps
; }
730 StringRef
getResult() { return Result
; }
732 bool isOpMapped(StringRef Op
) { return OpMap
.find(Op
) != OpMap
.end(); }
733 int getOpIndex(StringRef Op
) { return OpMap
[Op
].first
; }
734 std::pair
<int, int> &getOpData(StringRef Op
) { return OpMap
[Op
]; }
736 std::pair
<StringRef
, StringRef::iterator
> parseName(StringRef::iterator Start
,
737 StringRef::iterator End
) {
738 StringRef::iterator I
= Start
;
739 StringRef::iterator Next
;
743 while (I
!= End
&& *I
!= '}')
750 // $name, just eat the usual suspects.
751 while (I
!= End
&& (isAlnum(*I
) || *I
== '_'))
756 return std::pair(StringRef(Start
, I
- Start
), Next
);
759 std::string
formatAliasString(uint32_t &UnescapedSize
) {
760 // Directly mangle mapped operands into the string. Each operand is
761 // identified by a '$' sign followed by a byte identifying the number of the
762 // operand. We add one to the index to avoid zero bytes.
763 StringRef
ASM(AsmString
);
764 std::string OutString
;
765 raw_string_ostream
OS(OutString
);
766 for (StringRef::iterator I
= ASM
.begin(), E
= ASM
.end(); I
!= E
;) {
771 std::tie(Name
, I
) = parseName(++I
, E
);
772 assert(isOpMapped(Name
) && "Unmapped operand!");
774 int OpIndex
, PrintIndex
;
775 std::tie(OpIndex
, PrintIndex
) = getOpData(Name
);
776 if (PrintIndex
== -1) {
777 // Can use the default printOperand route.
778 OS
<< format("\\x%02X", (unsigned char)OpIndex
+ 1);
781 // 3 bytes if a PrintMethod is needed: 0xFF, the MCInst operand
782 // number, and which of our pre-detected Methods to call.
783 OS
<< format("\\xFF\\x%02X\\x%02X", OpIndex
+ 1, PrintIndex
+ 1);
793 bool operator==(const IAPrinter
&RHS
) const {
794 if (NumMIOps
!= RHS
.NumMIOps
)
796 if (Conds
.size() != RHS
.Conds
.size())
800 for (const auto &str
: Conds
)
801 if (str
!= RHS
.Conds
[Idx
++])
808 } // end anonymous namespace
810 static unsigned CountNumOperands(StringRef AsmString
, unsigned Variant
) {
811 return AsmString
.count(' ') + AsmString
.count('\t');
816 struct AliasPriorityComparator
{
817 typedef std::pair
<CodeGenInstAlias
, int> ValueType
;
818 bool operator()(const ValueType
&LHS
, const ValueType
&RHS
) const {
819 if (LHS
.second
== RHS
.second
) {
820 // We don't actually care about the order, but for consistency it
821 // shouldn't depend on pointer comparisons.
822 return LessRecordByID()(LHS
.first
.TheDef
, RHS
.first
.TheDef
);
825 // Aliases with larger priorities should be considered first.
826 return LHS
.second
> RHS
.second
;
830 } // end anonymous namespace
832 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream
&O
) {
833 const Record
*AsmWriter
= Target
.getAsmWriter();
835 O
<< "\n#ifdef PRINT_ALIAS_INSTR\n";
836 O
<< "#undef PRINT_ALIAS_INSTR\n\n";
838 //////////////////////////////
839 // Gather information about aliases we need to print
840 //////////////////////////////
842 // Emit the method that prints the alias instruction.
843 StringRef ClassName
= AsmWriter
->getValueAsString("AsmWriterClassName");
844 unsigned Variant
= AsmWriter
->getValueAsInt("Variant");
845 bool PassSubtarget
= AsmWriter
->getValueAsInt("PassSubtarget");
847 // Create a map from the qualified name to a list of potential matches.
848 typedef std::set
<std::pair
<CodeGenInstAlias
, int>, AliasPriorityComparator
>
850 std::map
<std::string
, AliasWithPriority
> AliasMap
;
851 for (const Record
*R
: Records
.getAllDerivedDefinitions("InstAlias")) {
852 int Priority
= R
->getValueAsInt("EmitPriority");
854 continue; // Aliases with priority 0 are never emitted.
856 const DagInit
*DI
= R
->getValueAsDag("ResultInst");
857 AliasMap
[getQualifiedName(DI
->getOperatorAsDef(R
->getLoc()))].insert(
858 std::pair(CodeGenInstAlias(R
, Target
), Priority
));
861 // A map of which conditions need to be met for each instruction operand
862 // before it can be matched to the mnemonic.
863 std::map
<std::string
, std::vector
<IAPrinter
>> IAPrinterMap
;
865 std::vector
<std::pair
<std::string
, bool>> PrintMethods
;
867 // A list of MCOperandPredicates for all operands in use, and the reverse map
868 std::vector
<const Record
*> MCOpPredicates
;
869 DenseMap
<const Record
*, unsigned> MCOpPredicateMap
;
871 for (auto &Aliases
: AliasMap
) {
872 // Collection of instruction alias rules. May contain ambiguous rules.
873 std::vector
<IAPrinter
> IAPs
;
875 for (auto &Alias
: Aliases
.second
) {
876 const CodeGenInstAlias
&CGA
= Alias
.first
;
877 unsigned LastOpNo
= CGA
.ResultInstOperandIndex
.size();
878 std::string FlatInstAsmString
=
879 CodeGenInstruction::FlattenAsmStringVariants(
880 CGA
.ResultInst
->AsmString
, Variant
);
881 unsigned NumResultOps
= CountNumOperands(FlatInstAsmString
, Variant
);
883 std::string FlatAliasAsmString
=
884 CodeGenInstruction::FlattenAsmStringVariants(CGA
.AsmString
, Variant
);
885 UnescapeAliasString(FlatAliasAsmString
);
887 // Don't emit the alias if it has more operands than what it's aliasing.
888 if (NumResultOps
< CountNumOperands(FlatAliasAsmString
, Variant
))
891 StringRef Namespace
= Target
.getName();
892 unsigned NumMIOps
= 0;
893 for (auto &ResultInstOpnd
: CGA
.ResultInst
->Operands
)
894 NumMIOps
+= ResultInstOpnd
.MINumOperands
;
896 IAPrinter
IAP(CGA
.Result
->getAsString(), FlatAliasAsmString
, NumMIOps
);
898 unsigned MIOpNum
= 0;
899 for (unsigned i
= 0, e
= LastOpNo
; i
!= e
; ++i
) {
900 // Skip over tied operands as they're not part of an alias declaration.
901 auto &Operands
= CGA
.ResultInst
->Operands
;
903 unsigned OpNum
= Operands
.getSubOperandNumber(MIOpNum
).first
;
904 if (Operands
[OpNum
].MINumOperands
== 1 &&
905 Operands
[OpNum
].getTiedRegister() != -1) {
906 // Tied operands of different RegisterClass should be explicit
907 // within an instruction's syntax and so cannot be skipped.
908 int TiedOpNum
= Operands
[OpNum
].getTiedRegister();
909 if (Operands
[OpNum
].Rec
->getName() ==
910 Operands
[TiedOpNum
].Rec
->getName()) {
918 // Ignore unchecked result operands.
919 while (IAP
.getCondCount() < MIOpNum
)
920 IAP
.addCond("AliasPatternCond::K_Ignore, 0");
922 const CodeGenInstAlias::ResultOperand
&RO
= CGA
.ResultOperands
[i
];
925 case CodeGenInstAlias::ResultOperand::K_Record
: {
926 const Record
*Rec
= RO
.getRecord();
927 StringRef ROName
= RO
.getName();
928 int PrintMethodIdx
= -1;
930 // These two may have a PrintMethod, which we want to record (if it's
931 // the first time we've seen it) and provide an index for the aliasing
933 if (Rec
->isSubClassOf("RegisterOperand") ||
934 Rec
->isSubClassOf("Operand")) {
935 StringRef PrintMethod
= Rec
->getValueAsString("PrintMethod");
937 Rec
->getValueAsString("OperandType") == "OPERAND_PCREL";
938 if (PrintMethod
!= "" && PrintMethod
!= "printOperand") {
939 PrintMethodIdx
= llvm::find_if(PrintMethods
,
941 return X
.first
== PrintMethod
;
943 PrintMethods
.begin();
944 if (static_cast<unsigned>(PrintMethodIdx
) == PrintMethods
.size())
945 PrintMethods
.emplace_back(std::string(PrintMethod
), IsPCRel
);
949 if (Rec
->isSubClassOf("RegisterOperand"))
950 Rec
= Rec
->getValueAsDef("RegClass");
951 if (Rec
->isSubClassOf("RegisterClass")) {
952 if (!IAP
.isOpMapped(ROName
)) {
953 IAP
.addOperand(ROName
, MIOpNum
, PrintMethodIdx
);
954 const Record
*R
= CGA
.ResultOperands
[i
].getRecord();
955 if (R
->isSubClassOf("RegisterOperand"))
956 R
= R
->getValueAsDef("RegClass");
957 IAP
.addCond(std::string(
958 formatv("AliasPatternCond::K_RegClass, {}::{}RegClassID",
959 Namespace
, R
->getName())));
961 IAP
.addCond(std::string(formatv("AliasPatternCond::K_TiedReg, {}",
962 IAP
.getOpIndex(ROName
))));
965 // Assume all printable operands are desired for now. This can be
966 // overridden in the InstAlias instantiation if necessary.
967 IAP
.addOperand(ROName
, MIOpNum
, PrintMethodIdx
);
969 // There might be an additional predicate on the MCOperand
970 unsigned Entry
= MCOpPredicateMap
[Rec
];
972 if (!Rec
->isValueUnset("MCOperandPredicate")) {
973 MCOpPredicates
.push_back(Rec
);
974 Entry
= MCOpPredicates
.size();
975 MCOpPredicateMap
[Rec
] = Entry
;
977 break; // No conditions on this operand at all
980 std::string(formatv("AliasPatternCond::K_Custom, {}", Entry
)));
984 case CodeGenInstAlias::ResultOperand::K_Imm
: {
985 // Just because the alias has an immediate result, doesn't mean the
986 // MCInst will. An MCExpr could be present, for example.
987 auto Imm
= CGA
.ResultOperands
[i
].getImm();
988 int32_t Imm32
= int32_t(Imm
);
990 PrintFatalError("Matching an alias with an immediate out of the "
991 "range of int32_t is not supported");
992 IAP
.addCond(std::string(
993 formatv("AliasPatternCond::K_Imm, uint32_t({})", Imm32
)));
996 case CodeGenInstAlias::ResultOperand::K_Reg
:
997 if (!CGA
.ResultOperands
[i
].getRegister()) {
998 IAP
.addCond(std::string(
999 formatv("AliasPatternCond::K_Reg, {}::NoRegister", Namespace
)));
1003 StringRef Reg
= CGA
.ResultOperands
[i
].getRegister()->getName();
1004 IAP
.addCond(std::string(
1005 formatv("AliasPatternCond::K_Reg, {}::{}", Namespace
, Reg
)));
1009 MIOpNum
+= RO
.getMINumOperands();
1012 std::vector
<const Record
*> ReqFeatures
;
1013 if (PassSubtarget
) {
1014 // We only consider ReqFeatures predicates if PassSubtarget
1015 std::vector
<const Record
*> RF
=
1016 CGA
.TheDef
->getValueAsListOfDefs("Predicates");
1017 copy_if(RF
, std::back_inserter(ReqFeatures
), [](const Record
*R
) {
1018 return R
->getValueAsBit("AssemblerMatcherPredicate");
1022 for (const Record
*R
: ReqFeatures
) {
1023 const DagInit
*D
= R
->getValueAsDag("AssemblerCondDag");
1024 auto *Op
= dyn_cast
<DefInit
>(D
->getOperator());
1026 PrintFatalError(R
->getLoc(), "Invalid AssemblerCondDag!");
1027 StringRef CombineType
= Op
->getDef()->getName();
1028 if (CombineType
!= "any_of" && CombineType
!= "all_of")
1029 PrintFatalError(R
->getLoc(), "Invalid AssemblerCondDag!");
1030 if (D
->getNumArgs() == 0)
1031 PrintFatalError(R
->getLoc(), "Invalid AssemblerCondDag!");
1032 bool IsOr
= CombineType
== "any_of";
1033 // Change (any_of FeatureAll, (any_of ...)) to (any_of FeatureAll, ...).
1034 if (IsOr
&& D
->getNumArgs() == 2 && isa
<DagInit
>(D
->getArg(1))) {
1035 const DagInit
*RHS
= cast
<DagInit
>(D
->getArg(1));
1036 SmallVector
<const Init
*> Args
{D
->getArg(0)};
1037 SmallVector
<const StringInit
*> ArgNames
{D
->getArgName(0)};
1038 for (unsigned i
= 0, e
= RHS
->getNumArgs(); i
!= e
; ++i
) {
1039 Args
.push_back(RHS
->getArg(i
));
1040 ArgNames
.push_back(RHS
->getArgName(i
));
1042 D
= DagInit::get(D
->getOperator(), nullptr, Args
, ArgNames
);
1045 for (auto *Arg
: D
->getArgs()) {
1047 if (auto *NotArg
= dyn_cast
<DagInit
>(Arg
)) {
1048 if (NotArg
->getOperator()->getAsString() != "not" ||
1049 NotArg
->getNumArgs() != 1)
1050 PrintFatalError(R
->getLoc(), "Invalid AssemblerCondDag!");
1051 Arg
= NotArg
->getArg(0);
1054 if (!isa
<DefInit
>(Arg
) ||
1055 !cast
<DefInit
>(Arg
)->getDef()->isSubClassOf("SubtargetFeature"))
1056 PrintFatalError(R
->getLoc(), "Invalid AssemblerCondDag!");
1058 IAP
.addCond(std::string(formatv(
1059 "AliasPatternCond::K_{}{}Feature, {}::{}", IsOr
? "Or" : "",
1060 IsNeg
? "Neg" : "", Namespace
, Arg
->getAsString())));
1062 // If an AssemblerPredicate with ors is used, note end of list should
1063 // these be combined.
1065 IAP
.addCond("AliasPatternCond::K_EndOrFeatures, 0");
1068 IAPrinterMap
[Aliases
.first
].push_back(std::move(IAP
));
1072 //////////////////////////////
1073 // Write out the printAliasInstr function
1074 //////////////////////////////
1077 raw_string_ostream
HeaderO(Header
);
1079 HeaderO
<< "bool " << Target
.getName() << ClassName
1080 << "::printAliasInstr(const MCInst"
1081 << " *MI, uint64_t Address, "
1082 << (PassSubtarget
? "const MCSubtargetInfo &STI, " : "")
1083 << "raw_ostream &OS) {\n";
1085 std::string PatternsForOpcode
;
1086 raw_string_ostream
OpcodeO(PatternsForOpcode
);
1088 unsigned PatternCount
= 0;
1089 std::string Patterns
;
1090 raw_string_ostream
PatternO(Patterns
);
1092 unsigned CondCount
= 0;
1094 raw_string_ostream
CondO(Conds
);
1096 // All flattened alias strings.
1097 std::map
<std::string
, uint32_t> AsmStringOffsets
;
1098 std::vector
<std::pair
<uint32_t, std::string
>> AsmStrings
;
1099 size_t AsmStringsSize
= 0;
1101 // Iterate over the opcodes in enum order so they are sorted by opcode for
1103 for (const CodeGenInstruction
*Inst
: NumberedInstructions
) {
1104 auto It
= IAPrinterMap
.find(getQualifiedName(Inst
->TheDef
));
1105 if (It
== IAPrinterMap
.end())
1107 std::vector
<IAPrinter
> &IAPs
= It
->second
;
1108 std::vector
<IAPrinter
*> UniqueIAPs
;
1110 // Remove any ambiguous alias rules.
1111 for (auto &LHS
: IAPs
) {
1113 for (const auto &RHS
: IAPs
) {
1114 if (&LHS
!= &RHS
&& LHS
== RHS
) {
1121 UniqueIAPs
.push_back(&LHS
);
1124 if (UniqueIAPs
.empty())
1127 unsigned PatternStart
= PatternCount
;
1129 // Insert the pattern start and opcode in the pattern list for debugging.
1130 PatternO
<< formatv(" // {} - {}\n", It
->first
, PatternStart
);
1132 for (IAPrinter
*IAP
: UniqueIAPs
) {
1133 // Start each condition list with a comment of the resulting pattern that
1134 // we're trying to match.
1135 unsigned CondStart
= CondCount
;
1136 CondO
<< formatv(" // {} - {}\n", IAP
->getResult(), CondStart
);
1137 for (const auto &Cond
: IAP
->getConds())
1138 CondO
<< " {" << Cond
<< "},\n";
1139 CondCount
+= IAP
->getCondCount();
1141 // After operands have been examined, re-encode the alias string with
1142 // escapes indicating how operands should be printed.
1143 uint32_t UnescapedSize
= 0;
1144 std::string EncodedAsmString
= IAP
->formatAliasString(UnescapedSize
);
1146 AsmStringOffsets
.insert({EncodedAsmString
, AsmStringsSize
});
1147 if (Insertion
.second
) {
1148 // If the string is new, add it to the vector.
1149 AsmStrings
.push_back({AsmStringsSize
, EncodedAsmString
});
1150 AsmStringsSize
+= UnescapedSize
+ 1;
1152 unsigned AsmStrOffset
= Insertion
.first
->second
;
1154 PatternO
<< formatv(" {{{}, {}, {}, {} },\n", AsmStrOffset
, CondStart
,
1155 IAP
->getNumMIOps(), IAP
->getCondCount());
1159 OpcodeO
<< formatv(" {{{}, {}, {} },\n", It
->first
, PatternStart
,
1160 PatternCount
- PatternStart
);
1163 if (PatternsForOpcode
.empty()) {
1165 O
<< " return false;\n";
1167 O
<< "#endif // PRINT_ALIAS_INSTR\n";
1171 // Forward declare the validation method if needed.
1172 if (!MCOpPredicates
.empty())
1173 O
<< "static bool " << Target
.getName() << ClassName
1174 << "ValidateMCOperand(const MCOperand &MCOp,\n"
1175 << " const MCSubtargetInfo &STI,\n"
1176 << " unsigned PredicateIndex);\n";
1179 O
.indent(2) << "static const PatternsForOpcode OpToPatterns[] = {\n";
1180 O
<< PatternsForOpcode
;
1181 O
.indent(2) << "};\n\n";
1182 O
.indent(2) << "static const AliasPattern Patterns[] = {\n";
1184 O
.indent(2) << "};\n\n";
1185 O
.indent(2) << "static const AliasPatternCond Conds[] = {\n";
1187 O
.indent(2) << "};\n\n";
1188 O
.indent(2) << "static const char AsmStrings[] =\n";
1189 for (const auto &P
: AsmStrings
) {
1190 O
.indent(4) << "/* " << P
.first
<< " */ \"" << P
.second
<< "\\0\"\n";
1193 O
.indent(2) << ";\n\n";
1195 // Assert that the opcode table is sorted. Use a static local constructor to
1196 // ensure that the check only happens once on first run.
1197 O
<< "#ifndef NDEBUG\n";
1198 O
.indent(2) << "static struct SortCheck {\n";
1199 O
.indent(2) << " SortCheck(ArrayRef<PatternsForOpcode> OpToPatterns) {\n";
1200 O
.indent(2) << " assert(std::is_sorted(\n";
1201 O
.indent(2) << " OpToPatterns.begin(), OpToPatterns.end(),\n";
1202 O
.indent(2) << " [](const PatternsForOpcode &L, const "
1203 "PatternsForOpcode &R) {\n";
1204 O
.indent(2) << " return L.Opcode < R.Opcode;\n";
1205 O
.indent(2) << " }) &&\n";
1206 O
.indent(2) << " \"tablegen failed to sort opcode patterns\");\n";
1207 O
.indent(2) << " }\n";
1208 O
.indent(2) << "} sortCheckVar(OpToPatterns);\n";
1211 O
.indent(2) << "AliasMatchingData M {\n";
1212 O
.indent(2) << " ArrayRef(OpToPatterns),\n";
1213 O
.indent(2) << " ArrayRef(Patterns),\n";
1214 O
.indent(2) << " ArrayRef(Conds),\n";
1215 O
.indent(2) << " StringRef(AsmStrings, std::size(AsmStrings)),\n";
1216 if (MCOpPredicates
.empty())
1217 O
.indent(2) << " nullptr,\n";
1219 O
.indent(2) << " &" << Target
.getName() << ClassName
1220 << "ValidateMCOperand,\n";
1221 O
.indent(2) << "};\n";
1223 O
.indent(2) << "const char *AsmString = matchAliasPatterns(MI, "
1224 << (PassSubtarget
? "&STI" : "nullptr") << ", M);\n";
1225 O
.indent(2) << "if (!AsmString) return false;\n\n";
1227 // Code that prints the alias, replacing the operands with the ones from the
1229 O
<< " unsigned I = 0;\n";
1230 O
<< " while (AsmString[I] != ' ' && AsmString[I] != '\\t' &&\n";
1231 O
<< " AsmString[I] != '$' && AsmString[I] != '\\0')\n";
1233 O
<< " OS << '\\t' << StringRef(AsmString, I);\n";
1235 O
<< " if (AsmString[I] != '\\0') {\n";
1236 O
<< " if (AsmString[I] == ' ' || AsmString[I] == '\\t') {\n";
1237 O
<< " OS << '\\t';\n";
1241 O
<< " if (AsmString[I] == '$') {\n";
1243 O
<< " if (AsmString[I] == (char)0xff) {\n";
1245 O
<< " int OpIdx = AsmString[I++] - 1;\n";
1246 O
<< " int PrintMethodIdx = AsmString[I++] - 1;\n";
1247 O
<< " printCustomAliasOperand(MI, Address, OpIdx, PrintMethodIdx, ";
1248 O
<< (PassSubtarget
? "STI, " : "");
1251 O
<< " printOperand(MI, unsigned(AsmString[I++]) - 1, ";
1252 O
<< (PassSubtarget
? "STI, " : "");
1255 O
<< " OS << AsmString[I++];\n";
1257 O
<< " } while (AsmString[I] != '\\0');\n";
1260 O
<< " return true;\n";
1263 //////////////////////////////
1264 // Write out the printCustomAliasOperand function
1265 //////////////////////////////
1267 O
<< "void " << Target
.getName() << ClassName
<< "::"
1268 << "printCustomAliasOperand(\n"
1269 << " const MCInst *MI, uint64_t Address, unsigned OpIdx,\n"
1270 << " unsigned PrintMethodIdx,\n"
1271 << (PassSubtarget
? " const MCSubtargetInfo &STI,\n" : "")
1272 << " raw_ostream &OS) {\n";
1273 if (PrintMethods
.empty())
1274 O
<< " llvm_unreachable(\"Unknown PrintMethod kind\");\n";
1276 O
<< " switch (PrintMethodIdx) {\n"
1278 << " llvm_unreachable(\"Unknown PrintMethod kind\");\n"
1281 for (unsigned i
= 0; i
< PrintMethods
.size(); ++i
) {
1282 O
<< " case " << i
<< ":\n"
1283 << " " << PrintMethods
[i
].first
<< "(MI, "
1284 << (PrintMethods
[i
].second
? "Address, " : "") << "OpIdx, "
1285 << (PassSubtarget
? "STI, " : "") << "OS);\n"
1292 if (!MCOpPredicates
.empty()) {
1293 O
<< "static bool " << Target
.getName() << ClassName
1294 << "ValidateMCOperand(const MCOperand &MCOp,\n"
1295 << " const MCSubtargetInfo &STI,\n"
1296 << " unsigned PredicateIndex) {\n"
1297 << " switch (PredicateIndex) {\n"
1299 << " llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n"
1302 for (unsigned i
= 0; i
< MCOpPredicates
.size(); ++i
) {
1303 StringRef MCOpPred
=
1304 MCOpPredicates
[i
]->getValueAsString("MCOperandPredicate");
1305 O
<< " case " << i
+ 1 << ": {\n"
1306 << MCOpPred
.data() << "\n"
1313 O
<< "#endif // PRINT_ALIAS_INSTR\n";
1316 AsmWriterEmitter::AsmWriterEmitter(const RecordKeeper
&R
)
1317 : Records(R
), Target(R
) {
1318 const Record
*AsmWriter
= Target
.getAsmWriter();
1319 unsigned Variant
= AsmWriter
->getValueAsInt("Variant");
1321 // Get the instruction numbering.
1322 NumberedInstructions
= Target
.getInstructionsByEnumValue();
1324 for (const auto &[Idx
, I
] : enumerate(NumberedInstructions
)) {
1325 if (!I
->AsmString
.empty() && I
->TheDef
->getName() != "PHI")
1326 Instructions
.emplace_back(*I
, Idx
, Variant
);
1330 void AsmWriterEmitter::run(raw_ostream
&O
) {
1331 std::vector
<std::vector
<std::string
>> TableDrivenOperandPrinters
;
1332 unsigned BitsLeft
= 0;
1333 unsigned AsmStrBits
= 0;
1334 emitSourceFileHeader("Assembly Writer Source Fragment", O
, Records
);
1335 EmitGetMnemonic(O
, TableDrivenOperandPrinters
, BitsLeft
, AsmStrBits
);
1336 EmitPrintInstruction(O
, TableDrivenOperandPrinters
, BitsLeft
, AsmStrBits
);
1337 EmitGetRegisterName(O
);
1338 EmitPrintAliasInstruction(O
);
1341 static TableGen::Emitter::OptClass
<AsmWriterEmitter
>
1342 X("gen-asm-writer", "Generate assembly writer");