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 "AsmWriterInst.h"
15 #include "CodeGenInstruction.h"
16 #include "CodeGenRegisters.h"
17 #include "CodeGenTarget.h"
18 #include "SequenceToOffsetTable.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Twine.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.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 RecordKeeper &Records;
60 ArrayRef<const CodeGenInstruction *> NumberedInstructions;
61 std::vector<AsmWriterInst> Instructions;
64 AsmWriterEmitter(RecordKeeper &R);
66 void run(raw_ostream &o);
69 void EmitPrintInstruction(raw_ostream &o);
70 void EmitGetRegisterName(raw_ostream &o);
71 void EmitPrintAliasInstruction(raw_ostream &O);
73 void FindUniqueOperandCommands(std::vector<std::string> &UOC,
74 std::vector<std::vector<unsigned>> &InstIdxs,
75 std::vector<unsigned> &InstOpsUsed,
76 bool PassSubtarget) const;
79 } // end anonymous namespace
81 static void PrintCases(std::vector<std::pair<std::string,
82 AsmWriterOperand>> &OpsToPrint, raw_ostream &O,
84 O << " case " << OpsToPrint.back().first << ":";
85 AsmWriterOperand TheOp = OpsToPrint.back().second;
86 OpsToPrint.pop_back();
88 // Check to see if any other operands are identical in this list, and if so,
89 // emit a case label for them.
90 for (unsigned i = OpsToPrint.size(); i != 0; --i)
91 if (OpsToPrint[i-1].second == TheOp) {
92 O << "\n case " << OpsToPrint[i-1].first << ":";
93 OpsToPrint.erase(OpsToPrint.begin()+i-1);
96 // Finally, emit the code.
97 O << "\n " << TheOp.getCode(PassSubtarget);
101 /// EmitInstructions - Emit the last instruction in the vector and any other
102 /// instructions that are suitably similar to it.
103 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
104 raw_ostream &O, bool PassSubtarget) {
105 AsmWriterInst FirstInst = Insts.back();
108 std::vector<AsmWriterInst> SimilarInsts;
109 unsigned DifferingOperand = ~0;
110 for (unsigned i = Insts.size(); i != 0; --i) {
111 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
113 if (DifferingOperand == ~0U) // First match!
114 DifferingOperand = DiffOp;
116 // If this differs in the same operand as the rest of the instructions in
117 // this class, move it to the SimilarInsts list.
118 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
119 SimilarInsts.push_back(Insts[i-1]);
120 Insts.erase(Insts.begin()+i-1);
125 O << " case " << FirstInst.CGI->Namespace << "::"
126 << FirstInst.CGI->TheDef->getName() << ":\n";
127 for (const AsmWriterInst &AWI : SimilarInsts)
128 O << " case " << AWI.CGI->Namespace << "::"
129 << AWI.CGI->TheDef->getName() << ":\n";
130 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
131 if (i != DifferingOperand) {
132 // If the operand is the same for all instructions, just print it.
133 O << " " << FirstInst.Operands[i].getCode(PassSubtarget);
135 // If this is the operand that varies between all of the instructions,
136 // emit a switch for just this operand now.
137 O << " switch (MI->getOpcode()) {\n";
138 O << " default: llvm_unreachable(\"Unexpected opcode.\");\n";
139 std::vector<std::pair<std::string, AsmWriterOperand>> OpsToPrint;
140 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace.str() + "::" +
141 FirstInst.CGI->TheDef->getName().str(),
142 FirstInst.Operands[i]));
144 for (const AsmWriterInst &AWI : SimilarInsts) {
145 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace.str()+"::" +
146 AWI.CGI->TheDef->getName().str(),
149 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
150 while (!OpsToPrint.empty())
151 PrintCases(OpsToPrint, O, PassSubtarget);
159 void AsmWriterEmitter::
160 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
161 std::vector<std::vector<unsigned>> &InstIdxs,
162 std::vector<unsigned> &InstOpsUsed,
163 bool PassSubtarget) const {
164 // This vector parallels UniqueOperandCommands, keeping track of which
165 // instructions each case are used for. It is a comma separated string of
167 std::vector<std::string> InstrsForCase;
168 InstrsForCase.resize(UniqueOperandCommands.size());
169 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
171 for (size_t i = 0, e = Instructions.size(); i != e; ++i) {
172 const AsmWriterInst &Inst = Instructions[i];
173 if (Inst.Operands.empty())
174 continue; // Instruction already done.
176 std::string Command = " "+Inst.Operands[0].getCode(PassSubtarget)+"\n";
178 // Check to see if we already have 'Command' in UniqueOperandCommands.
180 auto I = llvm::find(UniqueOperandCommands, Command);
181 if (I != UniqueOperandCommands.end()) {
182 size_t idx = I - UniqueOperandCommands.begin();
183 InstrsForCase[idx] += ", ";
184 InstrsForCase[idx] += Inst.CGI->TheDef->getName();
185 InstIdxs[idx].push_back(i);
187 UniqueOperandCommands.push_back(std::move(Command));
188 InstrsForCase.push_back(std::string(Inst.CGI->TheDef->getName()));
189 InstIdxs.emplace_back();
190 InstIdxs.back().push_back(i);
192 // This command matches one operand so far.
193 InstOpsUsed.push_back(1);
197 // For each entry of UniqueOperandCommands, there is a set of instructions
198 // that uses it. If the next command of all instructions in the set are
199 // identical, fold it into the command.
200 for (size_t CommandIdx = 0, e = UniqueOperandCommands.size();
201 CommandIdx != e; ++CommandIdx) {
203 const auto &Idxs = InstIdxs[CommandIdx];
205 for (unsigned Op = 1; ; ++Op) {
206 // Find the first instruction in the set.
207 const AsmWriterInst &FirstInst = Instructions[Idxs.front()];
208 // If this instruction has no more operands, we isn't anything to merge
209 // into this command.
210 if (FirstInst.Operands.size() == Op)
213 // Otherwise, scan to see if all of the other instructions in this command
214 // set share the operand.
215 if (std::any_of(Idxs.begin()+1, Idxs.end(),
217 const AsmWriterInst &OtherInst = Instructions[Idx];
218 return OtherInst.Operands.size() == Op ||
219 OtherInst.Operands[Op] != FirstInst.Operands[Op];
223 // Okay, everything in this command set has the same next operand. Add it
224 // to UniqueOperandCommands and remember that it was consumed.
225 std::string Command = " " +
226 FirstInst.Operands[Op].getCode(PassSubtarget) + "\n";
228 UniqueOperandCommands[CommandIdx] += Command;
229 InstOpsUsed[CommandIdx]++;
233 // Prepend some of the instructions each case is used for onto the case val.
234 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
235 std::string Instrs = InstrsForCase[i];
236 if (Instrs.size() > 70) {
237 Instrs.erase(Instrs.begin()+70, Instrs.end());
242 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
243 UniqueOperandCommands[i];
247 static void UnescapeString(std::string &Str) {
248 for (unsigned i = 0; i != Str.size(); ++i) {
249 if (Str[i] == '\\' && i != Str.size()-1) {
251 default: continue; // Don't execute the code after the switch.
252 case 'a': Str[i] = '\a'; break;
253 case 'b': Str[i] = '\b'; break;
254 case 'e': Str[i] = 27; break;
255 case 'f': Str[i] = '\f'; break;
256 case 'n': Str[i] = '\n'; break;
257 case 'r': Str[i] = '\r'; break;
258 case 't': Str[i] = '\t'; break;
259 case 'v': Str[i] = '\v'; break;
260 case '"': Str[i] = '\"'; break;
261 case '\'': Str[i] = '\''; break;
262 case '\\': Str[i] = '\\'; break;
264 // Nuke the second character.
265 Str.erase(Str.begin()+i+1);
270 /// UnescapeAliasString - Supports literal braces in InstAlias asm string which
271 /// are escaped with '\\' to avoid being interpreted as variants. Braces must
272 /// be unescaped before c++ code is generated as (e.g.):
274 /// AsmString = "foo \{$\x01\}";
276 /// causes non-standard escape character warnings.
277 static void UnescapeAliasString(std::string &Str) {
278 for (unsigned i = 0; i != Str.size(); ++i) {
279 if (Str[i] == '\\' && i != Str.size()-1) {
281 default: continue; // Don't execute the code after the switch.
282 case '{': Str[i] = '{'; break;
283 case '}': Str[i] = '}'; break;
285 // Nuke the second character.
286 Str.erase(Str.begin()+i+1);
291 /// EmitPrintInstruction - Generate the code for the "printInstruction" method
292 /// implementation. Destroys all instances of AsmWriterInst information, by
293 /// clearing the Instructions vector.
294 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
295 Record *AsmWriter = Target.getAsmWriter();
296 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
297 bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
299 O << "/// printInstruction - This method is automatically generated by "
301 "/// from the instruction set description.\n"
303 << Target.getName() << ClassName
304 << "::printInstruction(const MCInst *MI, uint64_t Address, "
305 << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
306 << "raw_ostream &O) {\n";
308 // Build an aggregate string, and build a table of offsets into it.
309 SequenceToOffsetTable<std::string> StringTable;
311 /// OpcodeInfo - This encodes the index of the string to use for the first
312 /// chunk of the output as well as indices used for operand printing.
313 std::vector<uint64_t> OpcodeInfo(NumberedInstructions.size());
314 const unsigned OpcodeInfoBits = 64;
316 // Add all strings to the string table upfront so it can generate an optimized
318 for (AsmWriterInst &AWI : Instructions) {
319 if (AWI.Operands[0].OperandType ==
320 AsmWriterOperand::isLiteralTextOperand &&
321 !AWI.Operands[0].Str.empty()) {
322 std::string Str = AWI.Operands[0].Str;
324 StringTable.add(Str);
328 StringTable.layout();
330 unsigned MaxStringIdx = 0;
331 for (AsmWriterInst &AWI : Instructions) {
333 if (AWI.Operands[0].OperandType != AsmWriterOperand::isLiteralTextOperand ||
334 AWI.Operands[0].Str.empty()) {
335 // Something handled by the asmwriter printer, but with no leading string.
336 Idx = StringTable.get("");
338 std::string Str = AWI.Operands[0].Str;
340 Idx = StringTable.get(Str);
341 MaxStringIdx = std::max(MaxStringIdx, Idx);
343 // Nuke the string from the operand list. It is now handled!
344 AWI.Operands.erase(AWI.Operands.begin());
347 // Bias offset by one since we want 0 as a sentinel.
348 OpcodeInfo[AWI.CGIIndex] = Idx+1;
351 // Figure out how many bits we used for the string index.
352 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
354 // To reduce code size, we compactify common instructions into a few bits
355 // in the opcode-indexed table.
356 unsigned BitsLeft = OpcodeInfoBits-AsmStrBits;
358 std::vector<std::vector<std::string>> TableDrivenOperandPrinters;
361 std::vector<std::string> UniqueOperandCommands;
362 std::vector<std::vector<unsigned>> InstIdxs;
363 std::vector<unsigned> NumInstOpsHandled;
364 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
365 NumInstOpsHandled, PassSubtarget);
367 // If we ran out of operands to print, we're done.
368 if (UniqueOperandCommands.empty()) break;
370 // Compute the number of bits we need to represent these cases, this is
371 // ceil(log2(numentries)).
372 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
374 // If we don't have enough bits for this operand, don't include it.
375 if (NumBits > BitsLeft) {
376 LLVM_DEBUG(errs() << "Not enough bits to densely encode " << NumBits
381 // Otherwise, we can include this in the initial lookup table. Add it in.
382 for (size_t i = 0, e = InstIdxs.size(); i != e; ++i) {
383 unsigned NumOps = NumInstOpsHandled[i];
384 for (unsigned Idx : InstIdxs[i]) {
385 OpcodeInfo[Instructions[Idx].CGIIndex] |=
386 (uint64_t)i << (OpcodeInfoBits-BitsLeft);
387 // Remove the info about this operand from the instruction.
388 AsmWriterInst &Inst = Instructions[Idx];
389 if (!Inst.Operands.empty()) {
390 assert(NumOps <= Inst.Operands.size() &&
391 "Can't remove this many ops!");
392 Inst.Operands.erase(Inst.Operands.begin(),
393 Inst.Operands.begin()+NumOps);
399 // Remember the handlers for this set of operands.
400 TableDrivenOperandPrinters.push_back(std::move(UniqueOperandCommands));
403 // Emit the string table itself.
404 StringTable.emitStringLiteralDef(O, " static const char AsmStrs[]");
406 // Emit the lookup tables in pieces to minimize wasted bytes.
407 unsigned BytesNeeded = ((OpcodeInfoBits - BitsLeft) + 7) / 8;
408 unsigned Table = 0, Shift = 0;
409 SmallString<128> BitsString;
410 raw_svector_ostream BitsOS(BitsString);
411 // If the total bits is more than 32-bits we need to use a 64-bit type.
412 BitsOS << " uint" << ((BitsLeft < (OpcodeInfoBits - 32)) ? 64 : 32)
414 while (BytesNeeded != 0) {
415 // Figure out how big this table section needs to be, but no bigger than 4.
416 unsigned TableSize = std::min(1 << Log2_32(BytesNeeded), 4);
417 BytesNeeded -= TableSize;
418 TableSize *= 8; // Convert to bits;
419 uint64_t Mask = (1ULL << TableSize) - 1;
420 O << " static const uint" << TableSize << "_t OpInfo" << Table
422 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
423 O << " " << ((OpcodeInfo[i] >> Shift) & Mask) << "U,\t// "
424 << NumberedInstructions[i]->TheDef->getName() << "\n";
427 // Emit string to combine the individual table lookups.
428 BitsOS << " Bits |= ";
429 // If the total bits is more than 32-bits we need to use a 64-bit type.
430 if (BitsLeft < (OpcodeInfoBits - 32))
431 BitsOS << "(uint64_t)";
432 BitsOS << "OpInfo" << Table << "[MI->getOpcode()] << " << Shift << ";\n";
433 // Prepare the shift for the next iteration and increment the table count.
438 // Emit the initial tab character.
439 O << " O << \"\\t\";\n\n";
441 O << " // Emit the opcode for the instruction.\n";
444 // Emit the starting string.
445 O << " assert(Bits != 0 && \"Cannot print this instruction.\");\n"
446 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
448 // Output the table driven operand information.
449 BitsLeft = OpcodeInfoBits-AsmStrBits;
450 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
451 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
453 // Compute the number of bits we need to represent these cases, this is
454 // ceil(log2(numentries)).
455 unsigned NumBits = Log2_32_Ceil(Commands.size());
456 assert(NumBits <= BitsLeft && "consistency error");
458 // Emit code to extract this field from Bits.
459 O << "\n // Fragment " << i << " encoded into " << NumBits
460 << " bits for " << Commands.size() << " unique commands.\n";
462 if (Commands.size() == 2) {
463 // Emit two possibilitys with if/else.
464 O << " if ((Bits >> "
465 << (OpcodeInfoBits-BitsLeft) << ") & "
466 << ((1 << NumBits)-1) << ") {\n"
471 } else if (Commands.size() == 1) {
472 // Emit a single possibility.
473 O << Commands[0] << "\n\n";
475 O << " switch ((Bits >> "
476 << (OpcodeInfoBits-BitsLeft) << ") & "
477 << ((1 << NumBits)-1) << ") {\n"
478 << " default: llvm_unreachable(\"Invalid command number.\");\n";
480 // Print out all the cases.
481 for (unsigned j = 0, e = Commands.size(); j != e; ++j) {
482 O << " case " << j << ":\n";
491 // Okay, delete instructions with no operand info left.
492 auto I = llvm::remove_if(Instructions,
493 [](AsmWriterInst &Inst) { return Inst.Operands.empty(); });
494 Instructions.erase(I, Instructions.end());
497 // Because this is a vector, we want to emit from the end. Reverse all of the
498 // elements in the vector.
499 std::reverse(Instructions.begin(), Instructions.end());
502 // Now that we've emitted all of the operand info that fit into 64 bits, emit
503 // information for those instructions that are left. This is a less dense
504 // encoding, but we expect the main 64-bit table to handle the majority of
506 if (!Instructions.empty()) {
507 // Find the opcode # of inline asm.
508 O << " switch (MI->getOpcode()) {\n";
509 O << " default: llvm_unreachable(\"Unexpected opcode.\");\n";
510 while (!Instructions.empty())
511 EmitInstructions(Instructions, O, PassSubtarget);
520 emitRegisterNameString(raw_ostream &O, StringRef AltName,
521 const std::deque<CodeGenRegister> &Registers) {
522 SequenceToOffsetTable<std::string> StringTable;
523 SmallVector<std::string, 4> AsmNames(Registers.size());
525 for (const auto &Reg : Registers) {
526 std::string &AsmName = AsmNames[i++];
528 // "NoRegAltName" is special. We don't need to do a lookup for that,
529 // as it's just a reference to the default register name.
530 if (AltName == "" || AltName == "NoRegAltName") {
531 AsmName = std::string(Reg.TheDef->getValueAsString("AsmName"));
533 AsmName = std::string(Reg.getName());
535 // Make sure the register has an alternate name for this index.
536 std::vector<Record*> AltNameList =
537 Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
539 for (e = AltNameList.size();
540 Idx < e && (AltNameList[Idx]->getName() != AltName);
543 // If the register has an alternate name for this index, use it.
544 // Otherwise, leave it empty as an error flag.
546 std::vector<StringRef> AltNames =
547 Reg.TheDef->getValueAsListOfStrings("AltNames");
548 if (AltNames.size() <= Idx)
549 PrintFatalError(Reg.TheDef->getLoc(),
550 "Register definition missing alt name for '" +
552 AsmName = std::string(AltNames[Idx]);
555 StringTable.add(AsmName);
558 StringTable.layout();
559 StringTable.emitStringLiteralDef(O, Twine(" static const char AsmStrs") +
562 O << " static const " << getMinimalTypeForRange(StringTable.size() - 1, 32)
563 << " RegAsmOffset" << AltName << "[] = {";
564 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
567 O << StringTable.get(AsmNames[i]) << ", ";
573 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
574 Record *AsmWriter = Target.getAsmWriter();
575 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
576 const auto &Registers = Target.getRegBank().getRegisters();
577 const std::vector<Record*> &AltNameIndices = Target.getRegAltNameIndices();
578 bool hasAltNames = AltNameIndices.size() > 1;
579 StringRef Namespace = Registers.front().TheDef->getValueAsString("Namespace");
582 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
583 "/// from the register set description. This returns the assembler name\n"
584 "/// for the specified register.\n"
585 "const char *" << Target.getName() << ClassName << "::";
587 O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
589 O << "getRegisterName(unsigned RegNo) {\n";
590 O << " assert(RegNo && RegNo < " << (Registers.size()+1)
591 << " && \"Invalid register number!\");\n"
595 for (const Record *R : AltNameIndices)
596 emitRegisterNameString(O, R->getName(), Registers);
598 emitRegisterNameString(O, "", Registers);
601 O << " switch(AltIdx) {\n"
602 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n";
603 for (const Record *R : AltNameIndices) {
604 StringRef AltName = R->getName();
606 if (!Namespace.empty())
607 O << Namespace << "::";
608 O << AltName << ":\n";
609 if (R->isValueUnset("FallbackRegAltNameIndex"))
610 O << " assert(*(AsmStrs" << AltName << "+RegAsmOffset" << AltName
612 << " \"Invalid alt name index for register!\");\n";
614 O << " if (!*(AsmStrs" << AltName << "+RegAsmOffset" << AltName
616 << " return getRegisterName(RegNo, ";
617 if (!Namespace.empty())
618 O << Namespace << "::";
619 O << R->getValueAsDef("FallbackRegAltNameIndex")->getName() << ");\n";
621 O << " return AsmStrs" << AltName << "+RegAsmOffset" << AltName
626 O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
627 << " \"Invalid alt name index for register!\");\n"
628 << " return AsmStrs+RegAsmOffset[RegNo-1];\n";
635 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
636 // they both have the same conditionals. In which case, we cannot print out the
637 // alias for that pattern.
639 std::map<StringRef, std::pair<int, int>> OpMap;
641 std::vector<std::string> Conds;
644 std::string AsmString;
649 IAPrinter(std::string R, std::string AS, unsigned NumMIOps)
650 : Result(std::move(R)), AsmString(std::move(AS)), NumMIOps(NumMIOps) {}
652 void addCond(std::string C) { Conds.push_back(std::move(C)); }
653 ArrayRef<std::string> getConds() const { return Conds; }
654 size_t getCondCount() const { return Conds.size(); }
656 void addOperand(StringRef Op, int OpIdx, int PrintMethodIdx = -1) {
657 assert(OpIdx >= 0 && OpIdx < 0xFE && "Idx out of range");
658 assert(PrintMethodIdx >= -1 && PrintMethodIdx < 0xFF &&
660 OpMap[Op] = std::make_pair(OpIdx, PrintMethodIdx);
663 unsigned getNumMIOps() { return NumMIOps; }
665 StringRef getResult() { return Result; }
667 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
668 int getOpIndex(StringRef Op) { return OpMap[Op].first; }
669 std::pair<int, int> &getOpData(StringRef Op) { return OpMap[Op]; }
671 std::pair<StringRef, StringRef::iterator> parseName(StringRef::iterator Start,
672 StringRef::iterator End) {
673 StringRef::iterator I = Start;
674 StringRef::iterator Next;
678 while (I != End && *I != '}')
685 // $name, just eat the usual suspects.
687 ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') ||
688 (*I >= '0' && *I <= '9') || *I == '_'))
693 return std::make_pair(StringRef(Start, I - Start), Next);
696 std::string formatAliasString(uint32_t &UnescapedSize) {
697 // Directly mangle mapped operands into the string. Each operand is
698 // identified by a '$' sign followed by a byte identifying the number of the
699 // operand. We add one to the index to avoid zero bytes.
700 StringRef ASM(AsmString);
701 std::string OutString;
702 raw_string_ostream OS(OutString);
703 for (StringRef::iterator I = ASM.begin(), E = ASM.end(); I != E;) {
708 std::tie(Name, I) = parseName(++I, E);
709 assert(isOpMapped(Name) && "Unmapped operand!");
711 int OpIndex, PrintIndex;
712 std::tie(OpIndex, PrintIndex) = getOpData(Name);
713 if (PrintIndex == -1) {
714 // Can use the default printOperand route.
715 OS << format("\\x%02X", (unsigned char)OpIndex + 1);
718 // 3 bytes if a PrintMethod is needed: 0xFF, the MCInst operand
719 // number, and which of our pre-detected Methods to call.
720 OS << format("\\xFF\\x%02X\\x%02X", OpIndex + 1, PrintIndex + 1);
732 bool operator==(const IAPrinter &RHS) const {
733 if (NumMIOps != RHS.NumMIOps)
735 if (Conds.size() != RHS.Conds.size())
739 for (const auto &str : Conds)
740 if (str != RHS.Conds[Idx++])
747 } // end anonymous namespace
749 static unsigned CountNumOperands(StringRef AsmString, unsigned Variant) {
750 return AsmString.count(' ') + AsmString.count('\t');
755 struct AliasPriorityComparator {
756 typedef std::pair<CodeGenInstAlias, int> ValueType;
757 bool operator()(const ValueType &LHS, const ValueType &RHS) const {
758 if (LHS.second == RHS.second) {
759 // We don't actually care about the order, but for consistency it
760 // shouldn't depend on pointer comparisons.
761 return LessRecordByID()(LHS.first.TheDef, RHS.first.TheDef);
764 // Aliases with larger priorities should be considered first.
765 return LHS.second > RHS.second;
769 } // end anonymous namespace
771 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
772 Record *AsmWriter = Target.getAsmWriter();
774 O << "\n#ifdef PRINT_ALIAS_INSTR\n";
775 O << "#undef PRINT_ALIAS_INSTR\n\n";
777 //////////////////////////////
778 // Gather information about aliases we need to print
779 //////////////////////////////
781 // Emit the method that prints the alias instruction.
782 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
783 unsigned Variant = AsmWriter->getValueAsInt("Variant");
784 bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
786 std::vector<Record*> AllInstAliases =
787 Records.getAllDerivedDefinitions("InstAlias");
789 // Create a map from the qualified name to a list of potential matches.
790 typedef std::set<std::pair<CodeGenInstAlias, int>, AliasPriorityComparator>
792 std::map<std::string, AliasWithPriority> AliasMap;
793 for (Record *R : AllInstAliases) {
794 int Priority = R->getValueAsInt("EmitPriority");
796 continue; // Aliases with priority 0 are never emitted.
798 const DagInit *DI = R->getValueAsDag("ResultInst");
799 AliasMap[getQualifiedName(DI->getOperatorAsDef(R->getLoc()))].insert(
800 std::make_pair(CodeGenInstAlias(R, Target), Priority));
803 // A map of which conditions need to be met for each instruction operand
804 // before it can be matched to the mnemonic.
805 std::map<std::string, std::vector<IAPrinter>> IAPrinterMap;
807 std::vector<std::pair<std::string, bool>> PrintMethods;
809 // A list of MCOperandPredicates for all operands in use, and the reverse map
810 std::vector<const Record*> MCOpPredicates;
811 DenseMap<const Record*, unsigned> MCOpPredicateMap;
813 for (auto &Aliases : AliasMap) {
814 // Collection of instruction alias rules. May contain ambiguous rules.
815 std::vector<IAPrinter> IAPs;
817 for (auto &Alias : Aliases.second) {
818 const CodeGenInstAlias &CGA = Alias.first;
819 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
820 std::string FlatInstAsmString =
821 CodeGenInstruction::FlattenAsmStringVariants(CGA.ResultInst->AsmString,
823 unsigned NumResultOps = CountNumOperands(FlatInstAsmString, Variant);
825 std::string FlatAliasAsmString =
826 CodeGenInstruction::FlattenAsmStringVariants(CGA.AsmString, Variant);
827 UnescapeAliasString(FlatAliasAsmString);
829 // Don't emit the alias if it has more operands than what it's aliasing.
830 if (NumResultOps < CountNumOperands(FlatAliasAsmString, Variant))
833 StringRef Namespace = Target.getName();
834 unsigned NumMIOps = 0;
835 for (auto &ResultInstOpnd : CGA.ResultInst->Operands)
836 NumMIOps += ResultInstOpnd.MINumOperands;
838 IAPrinter IAP(CGA.Result->getAsString(), FlatAliasAsmString, NumMIOps);
840 bool CantHandle = false;
842 unsigned MIOpNum = 0;
843 for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
844 // Skip over tied operands as they're not part of an alias declaration.
845 auto &Operands = CGA.ResultInst->Operands;
847 unsigned OpNum = Operands.getSubOperandNumber(MIOpNum).first;
848 if (Operands[OpNum].MINumOperands == 1 &&
849 Operands[OpNum].getTiedRegister() != -1) {
850 // Tied operands of different RegisterClass should be explicit within
851 // an instruction's syntax and so cannot be skipped.
852 int TiedOpNum = Operands[OpNum].getTiedRegister();
853 if (Operands[OpNum].Rec->getName() ==
854 Operands[TiedOpNum].Rec->getName()) {
862 // Ignore unchecked result operands.
863 while (IAP.getCondCount() < MIOpNum)
864 IAP.addCond("AliasPatternCond::K_Ignore, 0");
866 const CodeGenInstAlias::ResultOperand &RO = CGA.ResultOperands[i];
869 case CodeGenInstAlias::ResultOperand::K_Record: {
870 const Record *Rec = RO.getRecord();
871 StringRef ROName = RO.getName();
872 int PrintMethodIdx = -1;
874 // These two may have a PrintMethod, which we want to record (if it's
875 // the first time we've seen it) and provide an index for the aliasing
877 if (Rec->isSubClassOf("RegisterOperand") ||
878 Rec->isSubClassOf("Operand")) {
879 StringRef PrintMethod = Rec->getValueAsString("PrintMethod");
881 Rec->getValueAsString("OperandType") == "OPERAND_PCREL";
882 if (PrintMethod != "" && PrintMethod != "printOperand") {
883 PrintMethodIdx = llvm::find_if(PrintMethods,
885 return X.first == PrintMethod;
887 PrintMethods.begin();
888 if (static_cast<unsigned>(PrintMethodIdx) == PrintMethods.size())
889 PrintMethods.emplace_back(std::string(PrintMethod), IsPCRel);
893 if (Rec->isSubClassOf("RegisterOperand"))
894 Rec = Rec->getValueAsDef("RegClass");
895 if (Rec->isSubClassOf("RegisterClass")) {
896 if (!IAP.isOpMapped(ROName)) {
897 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx);
898 Record *R = CGA.ResultOperands[i].getRecord();
899 if (R->isSubClassOf("RegisterOperand"))
900 R = R->getValueAsDef("RegClass");
901 IAP.addCond(std::string(
902 formatv("AliasPatternCond::K_RegClass, {0}::{1}RegClassID",
903 Namespace, R->getName())));
905 IAP.addCond(std::string(formatv(
906 "AliasPatternCond::K_TiedReg, {0}", IAP.getOpIndex(ROName))));
909 // Assume all printable operands are desired for now. This can be
910 // overridden in the InstAlias instantiation if necessary.
911 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx);
913 // There might be an additional predicate on the MCOperand
914 unsigned Entry = MCOpPredicateMap[Rec];
916 if (!Rec->isValueUnset("MCOperandPredicate")) {
917 MCOpPredicates.push_back(Rec);
918 Entry = MCOpPredicates.size();
919 MCOpPredicateMap[Rec] = Entry;
921 break; // No conditions on this operand at all
924 std::string(formatv("AliasPatternCond::K_Custom, {0}", Entry)));
928 case CodeGenInstAlias::ResultOperand::K_Imm: {
929 // Just because the alias has an immediate result, doesn't mean the
930 // MCInst will. An MCExpr could be present, for example.
931 auto Imm = CGA.ResultOperands[i].getImm();
932 int32_t Imm32 = int32_t(Imm);
934 PrintFatalError("Matching an alias with an immediate out of the "
935 "range of int32_t is not supported");
936 IAP.addCond(std::string(
937 formatv("AliasPatternCond::K_Imm, uint32_t({0})", Imm32)));
940 case CodeGenInstAlias::ResultOperand::K_Reg:
941 // If this is zero_reg, something's playing tricks we're not
942 // equipped to handle.
943 if (!CGA.ResultOperands[i].getRegister()) {
948 StringRef Reg = CGA.ResultOperands[i].getRegister()->getName();
949 IAP.addCond(std::string(
950 formatv("AliasPatternCond::K_Reg, {0}::{1}", Namespace, Reg)));
954 MIOpNum += RO.getMINumOperands();
957 if (CantHandle) continue;
959 std::vector<Record *> ReqFeatures;
961 // We only consider ReqFeatures predicates if PassSubtarget
962 std::vector<Record *> RF =
963 CGA.TheDef->getValueAsListOfDefs("Predicates");
964 copy_if(RF, std::back_inserter(ReqFeatures), [](Record *R) {
965 return R->getValueAsBit("AssemblerMatcherPredicate");
969 for (auto I = ReqFeatures.cbegin(); I != ReqFeatures.cend(); I++) {
971 const DagInit *D = R->getValueAsDag("AssemblerCondDag");
972 std::string CombineType = D->getOperator()->getAsString();
973 if (CombineType != "any_of" && CombineType != "all_of")
974 PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");
975 if (D->getNumArgs() == 0)
976 PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");
977 bool IsOr = CombineType == "any_of";
979 for (auto *Arg : D->getArgs()) {
981 if (auto *NotArg = dyn_cast<DagInit>(Arg)) {
982 if (NotArg->getOperator()->getAsString() != "not" ||
983 NotArg->getNumArgs() != 1)
984 PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");
985 Arg = NotArg->getArg(0);
988 if (!isa<DefInit>(Arg) ||
989 !cast<DefInit>(Arg)->getDef()->isSubClassOf("SubtargetFeature"))
990 PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");
992 IAP.addCond(std::string(formatv(
993 "AliasPatternCond::K_{0}{1}Feature, {2}::{3}", IsOr ? "Or" : "",
994 IsNeg ? "Neg" : "", Namespace, Arg->getAsString())));
996 // If an AssemblerPredicate with ors is used, note end of list should
997 // these be combined.
999 IAP.addCond("AliasPatternCond::K_EndOrFeatures, 0");
1002 IAPrinterMap[Aliases.first].push_back(std::move(IAP));
1006 //////////////////////////////
1007 // Write out the printAliasInstr function
1008 //////////////////////////////
1011 raw_string_ostream HeaderO(Header);
1013 HeaderO << "bool " << Target.getName() << ClassName
1014 << "::printAliasInstr(const MCInst"
1015 << " *MI, uint64_t Address, "
1016 << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
1017 << "raw_ostream &OS) {\n";
1019 std::string PatternsForOpcode;
1020 raw_string_ostream OpcodeO(PatternsForOpcode);
1022 unsigned PatternCount = 0;
1023 std::string Patterns;
1024 raw_string_ostream PatternO(Patterns);
1026 unsigned CondCount = 0;
1028 raw_string_ostream CondO(Conds);
1030 // All flattened alias strings.
1031 std::map<std::string, uint32_t> AsmStringOffsets;
1032 std::vector<std::pair<uint32_t, std::string>> AsmStrings;
1033 size_t AsmStringsSize = 0;
1035 // Iterate over the opcodes in enum order so they are sorted by opcode for
1037 for (const CodeGenInstruction *Inst : NumberedInstructions) {
1038 auto It = IAPrinterMap.find(getQualifiedName(Inst->TheDef));
1039 if (It == IAPrinterMap.end())
1041 std::vector<IAPrinter> &IAPs = It->second;
1042 std::vector<IAPrinter*> UniqueIAPs;
1044 // Remove any ambiguous alias rules.
1045 for (auto &LHS : IAPs) {
1047 for (const auto &RHS : IAPs) {
1048 if (&LHS != &RHS && LHS == RHS) {
1055 UniqueIAPs.push_back(&LHS);
1058 if (UniqueIAPs.empty()) continue;
1060 unsigned PatternStart = PatternCount;
1062 // Insert the pattern start and opcode in the pattern list for debugging.
1063 PatternO << formatv(" // {0} - {1}\n", It->first, PatternStart);
1065 for (IAPrinter *IAP : UniqueIAPs) {
1066 // Start each condition list with a comment of the resulting pattern that
1067 // we're trying to match.
1068 unsigned CondStart = CondCount;
1069 CondO << formatv(" // {0} - {1}\n", IAP->getResult(), CondStart);
1070 for (const auto &Cond : IAP->getConds())
1071 CondO << " {" << Cond << "},\n";
1072 CondCount += IAP->getCondCount();
1074 // After operands have been examined, re-encode the alias string with
1075 // escapes indicating how operands should be printed.
1076 uint32_t UnescapedSize = 0;
1077 std::string EncodedAsmString = IAP->formatAliasString(UnescapedSize);
1079 AsmStringOffsets.insert({EncodedAsmString, AsmStringsSize});
1080 if (Insertion.second) {
1081 // If the string is new, add it to the vector.
1082 AsmStrings.push_back({AsmStringsSize, EncodedAsmString});
1083 AsmStringsSize += UnescapedSize + 1;
1085 unsigned AsmStrOffset = Insertion.first->second;
1087 PatternO << formatv(" {{{0}, {1}, {2}, {3} },\n", AsmStrOffset,
1088 CondStart, IAP->getNumMIOps(), IAP->getCondCount());
1092 OpcodeO << formatv(" {{{0}, {1}, {2} },\n", It->first, PatternStart,
1093 PatternCount - PatternStart);
1096 if (OpcodeO.str().empty()) {
1098 O << " return false;\n";
1100 O << "#endif // PRINT_ALIAS_INSTR\n";
1104 // Forward declare the validation method if needed.
1105 if (!MCOpPredicates.empty())
1106 O << "static bool " << Target.getName() << ClassName
1107 << "ValidateMCOperand(const MCOperand &MCOp,\n"
1108 << " const MCSubtargetInfo &STI,\n"
1109 << " unsigned PredicateIndex);\n";
1112 O.indent(2) << "static const PatternsForOpcode OpToPatterns[] = {\n";
1114 O.indent(2) << "};\n\n";
1115 O.indent(2) << "static const AliasPattern Patterns[] = {\n";
1116 O << PatternO.str();
1117 O.indent(2) << "};\n\n";
1118 O.indent(2) << "static const AliasPatternCond Conds[] = {\n";
1120 O.indent(2) << "};\n\n";
1121 O.indent(2) << "static const char AsmStrings[] =\n";
1122 for (const auto &P : AsmStrings) {
1123 O.indent(4) << "/* " << P.first << " */ \"" << P.second << "\\0\"\n";
1126 O.indent(2) << ";\n\n";
1128 // Assert that the opcode table is sorted. Use a static local constructor to
1129 // ensure that the check only happens once on first run.
1130 O << "#ifndef NDEBUG\n";
1131 O.indent(2) << "static struct SortCheck {\n";
1132 O.indent(2) << " SortCheck(ArrayRef<PatternsForOpcode> OpToPatterns) {\n";
1133 O.indent(2) << " assert(std::is_sorted(\n";
1134 O.indent(2) << " OpToPatterns.begin(), OpToPatterns.end(),\n";
1135 O.indent(2) << " [](const PatternsForOpcode &L, const "
1136 "PatternsForOpcode &R) {\n";
1137 O.indent(2) << " return L.Opcode < R.Opcode;\n";
1138 O.indent(2) << " }) &&\n";
1139 O.indent(2) << " \"tablegen failed to sort opcode patterns\");\n";
1140 O.indent(2) << " }\n";
1141 O.indent(2) << "} sortCheckVar(OpToPatterns);\n";
1144 O.indent(2) << "AliasMatchingData M {\n";
1145 O.indent(2) << " makeArrayRef(OpToPatterns),\n";
1146 O.indent(2) << " makeArrayRef(Patterns),\n";
1147 O.indent(2) << " makeArrayRef(Conds),\n";
1148 O.indent(2) << " StringRef(AsmStrings, array_lengthof(AsmStrings)),\n";
1149 if (MCOpPredicates.empty())
1150 O.indent(2) << " nullptr,\n";
1152 O.indent(2) << " &" << Target.getName() << ClassName << "ValidateMCOperand,\n";
1153 O.indent(2) << "};\n";
1155 O.indent(2) << "const char *AsmString = matchAliasPatterns(MI, "
1156 << (PassSubtarget ? "&STI" : "nullptr") << ", M);\n";
1157 O.indent(2) << "if (!AsmString) return false;\n\n";
1159 // Code that prints the alias, replacing the operands with the ones from the
1161 O << " unsigned I = 0;\n";
1162 O << " while (AsmString[I] != ' ' && AsmString[I] != '\\t' &&\n";
1163 O << " AsmString[I] != '$' && AsmString[I] != '\\0')\n";
1165 O << " OS << '\\t' << StringRef(AsmString, I);\n";
1167 O << " if (AsmString[I] != '\\0') {\n";
1168 O << " if (AsmString[I] == ' ' || AsmString[I] == '\\t') {\n";
1169 O << " OS << '\\t';\n";
1173 O << " if (AsmString[I] == '$') {\n";
1175 O << " if (AsmString[I] == (char)0xff) {\n";
1177 O << " int OpIdx = AsmString[I++] - 1;\n";
1178 O << " int PrintMethodIdx = AsmString[I++] - 1;\n";
1179 O << " printCustomAliasOperand(MI, Address, OpIdx, PrintMethodIdx, ";
1180 O << (PassSubtarget ? "STI, " : "");
1183 O << " printOperand(MI, unsigned(AsmString[I++]) - 1, ";
1184 O << (PassSubtarget ? "STI, " : "");
1187 O << " OS << AsmString[I++];\n";
1189 O << " } while (AsmString[I] != '\\0');\n";
1192 O << " return true;\n";
1195 //////////////////////////////
1196 // Write out the printCustomAliasOperand function
1197 //////////////////////////////
1199 O << "void " << Target.getName() << ClassName << "::"
1200 << "printCustomAliasOperand(\n"
1201 << " const MCInst *MI, uint64_t Address, unsigned OpIdx,\n"
1202 << " unsigned PrintMethodIdx,\n"
1203 << (PassSubtarget ? " const MCSubtargetInfo &STI,\n" : "")
1204 << " raw_ostream &OS) {\n";
1205 if (PrintMethods.empty())
1206 O << " llvm_unreachable(\"Unknown PrintMethod kind\");\n";
1208 O << " switch (PrintMethodIdx) {\n"
1210 << " llvm_unreachable(\"Unknown PrintMethod kind\");\n"
1213 for (unsigned i = 0; i < PrintMethods.size(); ++i) {
1214 O << " case " << i << ":\n"
1215 << " " << PrintMethods[i].first << "(MI, "
1216 << (PrintMethods[i].second ? "Address, " : "") << "OpIdx, "
1217 << (PassSubtarget ? "STI, " : "") << "OS);\n"
1224 if (!MCOpPredicates.empty()) {
1225 O << "static bool " << Target.getName() << ClassName
1226 << "ValidateMCOperand(const MCOperand &MCOp,\n"
1227 << " const MCSubtargetInfo &STI,\n"
1228 << " unsigned PredicateIndex) {\n"
1229 << " switch (PredicateIndex) {\n"
1231 << " llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n"
1234 for (unsigned i = 0; i < MCOpPredicates.size(); ++i) {
1235 Init *MCOpPred = MCOpPredicates[i]->getValueInit("MCOperandPredicate");
1236 if (CodeInit *SI = dyn_cast<CodeInit>(MCOpPred)) {
1237 O << " case " << i + 1 << ": {\n"
1238 << SI->getValue() << "\n"
1241 llvm_unreachable("Unexpected MCOperandPredicate field!");
1247 O << "#endif // PRINT_ALIAS_INSTR\n";
1250 AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) {
1251 Record *AsmWriter = Target.getAsmWriter();
1252 unsigned Variant = AsmWriter->getValueAsInt("Variant");
1254 // Get the instruction numbering.
1255 NumberedInstructions = Target.getInstructionsByEnumValue();
1257 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
1258 const CodeGenInstruction *I = NumberedInstructions[i];
1259 if (!I->AsmString.empty() && I->TheDef->getName() != "PHI")
1260 Instructions.emplace_back(*I, i, Variant);
1264 void AsmWriterEmitter::run(raw_ostream &O) {
1265 EmitPrintInstruction(O);
1266 EmitGetRegisterName(O);
1267 EmitPrintAliasInstruction(O);
1272 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
1273 emitSourceFileHeader("Assembly Writer Source Fragment", OS);
1274 AsmWriterEmitter(RK).run(OS);
1277 } // end namespace llvm