1 //===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend emits an assembly printer for the current target.
11 // Note that this is currently fairly skeletal, but will grow over time.
13 //===----------------------------------------------------------------------===//
15 #include "AsmWriterInst.h"
16 #include "CodeGenInstruction.h"
17 #include "CodeGenRegisters.h"
18 #include "CodeGenTarget.h"
19 #include "SequenceToOffsetTable.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/STLExtras.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/ErrorHandling.h"
32 #include "llvm/Support/Format.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(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 /// EmitPrintInstruction - Generate the code for the "printInstruction" method
271 /// implementation. Destroys all instances of AsmWriterInst information, by
272 /// clearing the Instructions vector.
273 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
274 Record *AsmWriter = Target.getAsmWriter();
275 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
276 bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
279 "/// printInstruction - This method is automatically generated by tablegen\n"
280 "/// from the instruction set description.\n"
281 "void " << Target.getName() << ClassName
282 << "::printInstruction(const MCInst *MI, "
283 << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
284 << "raw_ostream &O) {\n";
286 // Build an aggregate string, and build a table of offsets into it.
287 SequenceToOffsetTable<std::string> StringTable;
289 /// OpcodeInfo - This encodes the index of the string to use for the first
290 /// chunk of the output as well as indices used for operand printing.
291 std::vector<uint64_t> OpcodeInfo(NumberedInstructions.size());
292 const unsigned OpcodeInfoBits = 64;
294 // Add all strings to the string table upfront so it can generate an optimized
296 for (AsmWriterInst &AWI : Instructions) {
297 if (AWI.Operands[0].OperandType ==
298 AsmWriterOperand::isLiteralTextOperand &&
299 !AWI.Operands[0].Str.empty()) {
300 std::string Str = AWI.Operands[0].Str;
302 StringTable.add(Str);
306 StringTable.layout();
308 unsigned MaxStringIdx = 0;
309 for (AsmWriterInst &AWI : Instructions) {
311 if (AWI.Operands[0].OperandType != AsmWriterOperand::isLiteralTextOperand ||
312 AWI.Operands[0].Str.empty()) {
313 // Something handled by the asmwriter printer, but with no leading string.
314 Idx = StringTable.get("");
316 std::string Str = AWI.Operands[0].Str;
318 Idx = StringTable.get(Str);
319 MaxStringIdx = std::max(MaxStringIdx, Idx);
321 // Nuke the string from the operand list. It is now handled!
322 AWI.Operands.erase(AWI.Operands.begin());
325 // Bias offset by one since we want 0 as a sentinel.
326 OpcodeInfo[AWI.CGIIndex] = Idx+1;
329 // Figure out how many bits we used for the string index.
330 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
332 // To reduce code size, we compactify common instructions into a few bits
333 // in the opcode-indexed table.
334 unsigned BitsLeft = OpcodeInfoBits-AsmStrBits;
336 std::vector<std::vector<std::string>> TableDrivenOperandPrinters;
339 std::vector<std::string> UniqueOperandCommands;
340 std::vector<std::vector<unsigned>> InstIdxs;
341 std::vector<unsigned> NumInstOpsHandled;
342 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
343 NumInstOpsHandled, PassSubtarget);
345 // If we ran out of operands to print, we're done.
346 if (UniqueOperandCommands.empty()) break;
348 // Compute the number of bits we need to represent these cases, this is
349 // ceil(log2(numentries)).
350 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
352 // If we don't have enough bits for this operand, don't include it.
353 if (NumBits > BitsLeft) {
354 DEBUG(errs() << "Not enough bits to densely encode " << NumBits
359 // Otherwise, we can include this in the initial lookup table. Add it in.
360 for (size_t i = 0, e = InstIdxs.size(); i != e; ++i) {
361 unsigned NumOps = NumInstOpsHandled[i];
362 for (unsigned Idx : InstIdxs[i]) {
363 OpcodeInfo[Instructions[Idx].CGIIndex] |=
364 (uint64_t)i << (OpcodeInfoBits-BitsLeft);
365 // Remove the info about this operand from the instruction.
366 AsmWriterInst &Inst = Instructions[Idx];
367 if (!Inst.Operands.empty()) {
368 assert(NumOps <= Inst.Operands.size() &&
369 "Can't remove this many ops!");
370 Inst.Operands.erase(Inst.Operands.begin(),
371 Inst.Operands.begin()+NumOps);
377 // Remember the handlers for this set of operands.
378 TableDrivenOperandPrinters.push_back(std::move(UniqueOperandCommands));
381 // Emit the string table itself.
382 O << " static const char AsmStrs[] = {\n";
383 StringTable.emit(O, printChar);
386 // Emit the lookup tables in pieces to minimize wasted bytes.
387 unsigned BytesNeeded = ((OpcodeInfoBits - BitsLeft) + 7) / 8;
388 unsigned Table = 0, Shift = 0;
389 SmallString<128> BitsString;
390 raw_svector_ostream BitsOS(BitsString);
391 // If the total bits is more than 32-bits we need to use a 64-bit type.
392 BitsOS << " uint" << ((BitsLeft < (OpcodeInfoBits - 32)) ? 64 : 32)
394 while (BytesNeeded != 0) {
395 // Figure out how big this table section needs to be, but no bigger than 4.
396 unsigned TableSize = std::min(1 << Log2_32(BytesNeeded), 4);
397 BytesNeeded -= TableSize;
398 TableSize *= 8; // Convert to bits;
399 uint64_t Mask = (1ULL << TableSize) - 1;
400 O << " static const uint" << TableSize << "_t OpInfo" << Table
402 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
403 O << " " << ((OpcodeInfo[i] >> Shift) & Mask) << "U,\t// "
404 << NumberedInstructions[i]->TheDef->getName() << "\n";
407 // Emit string to combine the individual table lookups.
408 BitsOS << " Bits |= ";
409 // If the total bits is more than 32-bits we need to use a 64-bit type.
410 if (BitsLeft < (OpcodeInfoBits - 32))
411 BitsOS << "(uint64_t)";
412 BitsOS << "OpInfo" << Table << "[MI->getOpcode()] << " << Shift << ";\n";
413 // Prepare the shift for the next iteration and increment the table count.
418 // Emit the initial tab character.
419 O << " O << \"\\t\";\n\n";
421 O << " // Emit the opcode for the instruction.\n";
424 // Emit the starting string.
425 O << " assert(Bits != 0 && \"Cannot print this instruction.\");\n"
426 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
428 // Output the table driven operand information.
429 BitsLeft = OpcodeInfoBits-AsmStrBits;
430 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
431 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
433 // Compute the number of bits we need to represent these cases, this is
434 // ceil(log2(numentries)).
435 unsigned NumBits = Log2_32_Ceil(Commands.size());
436 assert(NumBits <= BitsLeft && "consistency error");
438 // Emit code to extract this field from Bits.
439 O << "\n // Fragment " << i << " encoded into " << NumBits
440 << " bits for " << Commands.size() << " unique commands.\n";
442 if (Commands.size() == 2) {
443 // Emit two possibilitys with if/else.
444 O << " if ((Bits >> "
445 << (OpcodeInfoBits-BitsLeft) << ") & "
446 << ((1 << NumBits)-1) << ") {\n"
451 } else if (Commands.size() == 1) {
452 // Emit a single possibility.
453 O << Commands[0] << "\n\n";
455 O << " switch ((Bits >> "
456 << (OpcodeInfoBits-BitsLeft) << ") & "
457 << ((1 << NumBits)-1) << ") {\n"
458 << " default: llvm_unreachable(\"Invalid command number.\");\n";
460 // Print out all the cases.
461 for (unsigned j = 0, e = Commands.size(); j != e; ++j) {
462 O << " case " << j << ":\n";
471 // Okay, delete instructions with no operand info left.
472 auto I = llvm::remove_if(Instructions,
473 [](AsmWriterInst &Inst) { return Inst.Operands.empty(); });
474 Instructions.erase(I, Instructions.end());
477 // Because this is a vector, we want to emit from the end. Reverse all of the
478 // elements in the vector.
479 std::reverse(Instructions.begin(), Instructions.end());
482 // Now that we've emitted all of the operand info that fit into 64 bits, emit
483 // information for those instructions that are left. This is a less dense
484 // encoding, but we expect the main 64-bit table to handle the majority of
486 if (!Instructions.empty()) {
487 // Find the opcode # of inline asm.
488 O << " switch (MI->getOpcode()) {\n";
489 O << " default: llvm_unreachable(\"Unexpected opcode.\");\n";
490 while (!Instructions.empty())
491 EmitInstructions(Instructions, O, PassSubtarget);
500 emitRegisterNameString(raw_ostream &O, StringRef AltName,
501 const std::deque<CodeGenRegister> &Registers) {
502 SequenceToOffsetTable<std::string> StringTable;
503 SmallVector<std::string, 4> AsmNames(Registers.size());
505 for (const auto &Reg : Registers) {
506 std::string &AsmName = AsmNames[i++];
508 // "NoRegAltName" is special. We don't need to do a lookup for that,
509 // as it's just a reference to the default register name.
510 if (AltName == "" || AltName == "NoRegAltName") {
511 AsmName = Reg.TheDef->getValueAsString("AsmName");
513 AsmName = Reg.getName();
515 // Make sure the register has an alternate name for this index.
516 std::vector<Record*> AltNameList =
517 Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
519 for (e = AltNameList.size();
520 Idx < e && (AltNameList[Idx]->getName() != AltName);
523 // If the register has an alternate name for this index, use it.
524 // Otherwise, leave it empty as an error flag.
526 std::vector<StringRef> AltNames =
527 Reg.TheDef->getValueAsListOfStrings("AltNames");
528 if (AltNames.size() <= Idx)
529 PrintFatalError(Reg.TheDef->getLoc(),
530 "Register definition missing alt name for '" +
532 AsmName = AltNames[Idx];
535 StringTable.add(AsmName);
538 StringTable.layout();
539 O << " static const char AsmStrs" << AltName << "[] = {\n";
540 StringTable.emit(O, printChar);
543 O << " static const " << getMinimalTypeForRange(StringTable.size() - 1, 32)
544 << " RegAsmOffset" << AltName << "[] = {";
545 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
548 O << StringTable.get(AsmNames[i]) << ", ";
554 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
555 Record *AsmWriter = Target.getAsmWriter();
556 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
557 const auto &Registers = Target.getRegBank().getRegisters();
558 const std::vector<Record*> &AltNameIndices = Target.getRegAltNameIndices();
559 bool hasAltNames = AltNameIndices.size() > 1;
560 StringRef Namespace = Registers.front().TheDef->getValueAsString("Namespace");
563 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
564 "/// from the register set description. This returns the assembler name\n"
565 "/// for the specified register.\n"
566 "const char *" << Target.getName() << ClassName << "::";
568 O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
570 O << "getRegisterName(unsigned RegNo) {\n";
571 O << " assert(RegNo && RegNo < " << (Registers.size()+1)
572 << " && \"Invalid register number!\");\n"
576 for (const Record *R : AltNameIndices)
577 emitRegisterNameString(O, R->getName(), Registers);
579 emitRegisterNameString(O, "", Registers);
582 O << " switch(AltIdx) {\n"
583 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n";
584 for (const Record *R : AltNameIndices) {
585 StringRef AltName = R->getName();
587 if (!Namespace.empty())
588 O << Namespace << "::";
589 O << AltName << ":\n"
590 << " assert(*(AsmStrs" << AltName << "+RegAsmOffset" << AltName
592 << " \"Invalid alt name index for register!\");\n"
593 << " return AsmStrs" << AltName << "+RegAsmOffset" << AltName
598 O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
599 << " \"Invalid alt name index for register!\");\n"
600 << " return AsmStrs+RegAsmOffset[RegNo-1];\n";
607 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
608 // they both have the same conditionals. In which case, we cannot print out the
609 // alias for that pattern.
611 std::vector<std::string> Conds;
612 std::map<StringRef, std::pair<int, int>> OpMap;
615 std::string AsmString;
618 IAPrinter(std::string R, std::string AS)
619 : Result(std::move(R)), AsmString(std::move(AS)) {}
621 void addCond(const std::string &C) { Conds.push_back(C); }
623 void addOperand(StringRef Op, int OpIdx, int PrintMethodIdx = -1) {
624 assert(OpIdx >= 0 && OpIdx < 0xFE && "Idx out of range");
625 assert(PrintMethodIdx >= -1 && PrintMethodIdx < 0xFF &&
627 OpMap[Op] = std::make_pair(OpIdx, PrintMethodIdx);
630 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
631 int getOpIndex(StringRef Op) { return OpMap[Op].first; }
632 std::pair<int, int> &getOpData(StringRef Op) { return OpMap[Op]; }
634 std::pair<StringRef, StringRef::iterator> parseName(StringRef::iterator Start,
635 StringRef::iterator End) {
636 StringRef::iterator I = Start;
637 StringRef::iterator Next;
641 while (I != End && *I != '}')
648 // $name, just eat the usual suspects.
650 ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') ||
651 (*I >= '0' && *I <= '9') || *I == '_'))
656 return std::make_pair(StringRef(Start, I - Start), Next);
659 void print(raw_ostream &O) {
661 O.indent(6) << "return true;\n";
667 for (std::vector<std::string>::iterator
668 I = Conds.begin(), E = Conds.end(); I != E; ++I) {
669 if (I != Conds.begin()) {
678 O.indent(6) << "// " << Result << "\n";
680 // Directly mangle mapped operands into the string. Each operand is
681 // identified by a '$' sign followed by a byte identifying the number of the
682 // operand. We add one to the index to avoid zero bytes.
683 StringRef ASM(AsmString);
684 SmallString<128> OutString;
685 raw_svector_ostream OS(OutString);
686 for (StringRef::iterator I = ASM.begin(), E = ASM.end(); I != E;) {
690 std::tie(Name, I) = parseName(++I, E);
691 assert(isOpMapped(Name) && "Unmapped operand!");
693 int OpIndex, PrintIndex;
694 std::tie(OpIndex, PrintIndex) = getOpData(Name);
695 if (PrintIndex == -1) {
696 // Can use the default printOperand route.
697 OS << format("\\x%02X", (unsigned char)OpIndex + 1);
699 // 3 bytes if a PrintMethod is needed: 0xFF, the MCInst operand
700 // number, and which of our pre-detected Methods to call.
701 OS << format("\\xFF\\x%02X\\x%02X", OpIndex + 1, PrintIndex + 1);
708 O.indent(6) << "AsmString = \"" << OutString << "\";\n";
710 O.indent(6) << "break;\n";
714 bool operator==(const IAPrinter &RHS) const {
715 if (Conds.size() != RHS.Conds.size())
719 for (const auto &str : Conds)
720 if (str != RHS.Conds[Idx++])
727 } // end anonymous namespace
729 static unsigned CountNumOperands(StringRef AsmString, unsigned Variant) {
730 std::string FlatAsmString =
731 CodeGenInstruction::FlattenAsmStringVariants(AsmString, Variant);
732 AsmString = FlatAsmString;
734 return AsmString.count(' ') + AsmString.count('\t');
739 struct AliasPriorityComparator {
740 typedef std::pair<CodeGenInstAlias, int> ValueType;
741 bool operator()(const ValueType &LHS, const ValueType &RHS) const {
742 if (LHS.second == RHS.second) {
743 // We don't actually care about the order, but for consistency it
744 // shouldn't depend on pointer comparisons.
745 return LessRecordByID()(LHS.first.TheDef, RHS.first.TheDef);
748 // Aliases with larger priorities should be considered first.
749 return LHS.second > RHS.second;
753 } // end anonymous namespace
755 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
756 Record *AsmWriter = Target.getAsmWriter();
758 O << "\n#ifdef PRINT_ALIAS_INSTR\n";
759 O << "#undef PRINT_ALIAS_INSTR\n\n";
761 //////////////////////////////
762 // Gather information about aliases we need to print
763 //////////////////////////////
765 // Emit the method that prints the alias instruction.
766 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
767 unsigned Variant = AsmWriter->getValueAsInt("Variant");
768 bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
770 std::vector<Record*> AllInstAliases =
771 Records.getAllDerivedDefinitions("InstAlias");
773 // Create a map from the qualified name to a list of potential matches.
774 typedef std::set<std::pair<CodeGenInstAlias, int>, AliasPriorityComparator>
776 std::map<std::string, AliasWithPriority> AliasMap;
777 for (Record *R : AllInstAliases) {
778 int Priority = R->getValueAsInt("EmitPriority");
780 continue; // Aliases with priority 0 are never emitted.
782 const DagInit *DI = R->getValueAsDag("ResultInst");
783 const DefInit *Op = cast<DefInit>(DI->getOperator());
784 AliasMap[getQualifiedName(Op->getDef())].insert(
785 std::make_pair(CodeGenInstAlias(R, Variant, Target), Priority));
788 // A map of which conditions need to be met for each instruction operand
789 // before it can be matched to the mnemonic.
790 std::map<std::string, std::vector<IAPrinter>> IAPrinterMap;
792 std::vector<std::string> PrintMethods;
794 // A list of MCOperandPredicates for all operands in use, and the reverse map
795 std::vector<const Record*> MCOpPredicates;
796 DenseMap<const Record*, unsigned> MCOpPredicateMap;
798 for (auto &Aliases : AliasMap) {
799 for (auto &Alias : Aliases.second) {
800 const CodeGenInstAlias &CGA = Alias.first;
801 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
802 unsigned NumResultOps =
803 CountNumOperands(CGA.ResultInst->AsmString, Variant);
805 // Don't emit the alias if it has more operands than what it's aliasing.
806 if (NumResultOps < CountNumOperands(CGA.AsmString, Variant))
809 IAPrinter IAP(CGA.Result->getAsString(), CGA.AsmString);
811 StringRef Namespace = Target.getName();
812 std::vector<Record *> ReqFeatures;
814 // We only consider ReqFeatures predicates if PassSubtarget
815 std::vector<Record *> RF =
816 CGA.TheDef->getValueAsListOfDefs("Predicates");
817 copy_if(RF, std::back_inserter(ReqFeatures), [](Record *R) {
818 return R->getValueAsBit("AssemblerMatcherPredicate");
822 unsigned NumMIOps = 0;
823 for (auto &ResultInstOpnd : CGA.ResultInst->Operands)
824 NumMIOps += ResultInstOpnd.MINumOperands;
827 Cond = std::string("MI->getNumOperands() == ") + utostr(NumMIOps);
830 bool CantHandle = false;
832 unsigned MIOpNum = 0;
833 for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
834 // Skip over tied operands as they're not part of an alias declaration.
835 auto &Operands = CGA.ResultInst->Operands;
836 unsigned OpNum = Operands.getSubOperandNumber(MIOpNum).first;
837 if (Operands[OpNum].MINumOperands == 1 &&
838 Operands[OpNum].getTiedRegister() != -1) {
839 // Tied operands of different RegisterClass should be explicit within
840 // an instruction's syntax and so cannot be skipped.
841 int TiedOpNum = Operands[OpNum].getTiedRegister();
842 if (Operands[OpNum].Rec->getName() ==
843 Operands[TiedOpNum].Rec->getName())
847 std::string Op = "MI->getOperand(" + utostr(MIOpNum) + ")";
849 const CodeGenInstAlias::ResultOperand &RO = CGA.ResultOperands[i];
852 case CodeGenInstAlias::ResultOperand::K_Record: {
853 const Record *Rec = RO.getRecord();
854 StringRef ROName = RO.getName();
855 int PrintMethodIdx = -1;
857 // These two may have a PrintMethod, which we want to record (if it's
858 // the first time we've seen it) and provide an index for the aliasing
860 if (Rec->isSubClassOf("RegisterOperand") ||
861 Rec->isSubClassOf("Operand")) {
862 StringRef PrintMethod = Rec->getValueAsString("PrintMethod");
863 if (PrintMethod != "" && PrintMethod != "printOperand") {
865 llvm::find(PrintMethods, PrintMethod) - PrintMethods.begin();
866 if (static_cast<unsigned>(PrintMethodIdx) == PrintMethods.size())
867 PrintMethods.push_back(PrintMethod);
871 if (Rec->isSubClassOf("RegisterOperand"))
872 Rec = Rec->getValueAsDef("RegClass");
873 if (Rec->isSubClassOf("RegisterClass")) {
874 IAP.addCond(Op + ".isReg()");
876 if (!IAP.isOpMapped(ROName)) {
877 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx);
878 Record *R = CGA.ResultOperands[i].getRecord();
879 if (R->isSubClassOf("RegisterOperand"))
880 R = R->getValueAsDef("RegClass");
881 Cond = std::string("MRI.getRegClass(") + Target.getName().str() +
882 "::" + R->getName().str() + "RegClassID).contains(" + Op +
885 Cond = Op + ".getReg() == MI->getOperand(" +
886 utostr(IAP.getOpIndex(ROName)) + ").getReg()";
889 // Assume all printable operands are desired for now. This can be
890 // overridden in the InstAlias instantiation if necessary.
891 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx);
893 // There might be an additional predicate on the MCOperand
894 unsigned Entry = MCOpPredicateMap[Rec];
896 if (!Rec->isValueUnset("MCOperandPredicate")) {
897 MCOpPredicates.push_back(Rec);
898 Entry = MCOpPredicates.size();
899 MCOpPredicateMap[Rec] = Entry;
901 break; // No conditions on this operand at all
903 Cond = (Target.getName() + ClassName + "ValidateMCOperand(" + Op +
904 ", STI, " + utostr(Entry) + ")")
907 // for all subcases of ResultOperand::K_Record:
911 case CodeGenInstAlias::ResultOperand::K_Imm: {
912 // Just because the alias has an immediate result, doesn't mean the
913 // MCInst will. An MCExpr could be present, for example.
914 IAP.addCond(Op + ".isImm()");
916 Cond = Op + ".getImm() == " + itostr(CGA.ResultOperands[i].getImm());
920 case CodeGenInstAlias::ResultOperand::K_Reg:
921 // If this is zero_reg, something's playing tricks we're not
922 // equipped to handle.
923 if (!CGA.ResultOperands[i].getRegister()) {
928 Cond = Op + ".getReg() == " + Target.getName().str() + "::" +
929 CGA.ResultOperands[i].getRegister()->getName().str();
934 MIOpNum += RO.getMINumOperands();
937 if (CantHandle) continue;
939 for (auto I = ReqFeatures.cbegin(); I != ReqFeatures.cend(); I++) {
941 StringRef AsmCondString = R->getValueAsString("AssemblerCondString");
943 // AsmCondString has syntax [!]F(,[!]F)*
944 SmallVector<StringRef, 4> Ops;
945 SplitString(AsmCondString, Ops, ",");
946 assert(!Ops.empty() && "AssemblerCondString cannot be empty");
948 for (auto &Op : Ops) {
949 assert(!Op.empty() && "Empty operator");
951 Cond = ("!STI.getFeatureBits()[" + Namespace + "::" + Op.substr(1) +
956 ("STI.getFeatureBits()[" + Namespace + "::" + Op + "]").str();
961 IAPrinterMap[Aliases.first].push_back(std::move(IAP));
965 //////////////////////////////
966 // Write out the printAliasInstr function
967 //////////////////////////////
970 raw_string_ostream HeaderO(Header);
972 HeaderO << "bool " << Target.getName() << ClassName
973 << "::printAliasInstr(const MCInst"
974 << " *MI, " << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
975 << "raw_ostream &OS) {\n";
978 raw_string_ostream CasesO(Cases);
980 for (auto &Entry : IAPrinterMap) {
981 std::vector<IAPrinter> &IAPs = Entry.second;
982 std::vector<IAPrinter*> UniqueIAPs;
984 for (auto &LHS : IAPs) {
986 for (const auto &RHS : IAPs) {
987 if (&LHS != &RHS && LHS == RHS) {
994 UniqueIAPs.push_back(&LHS);
997 if (UniqueIAPs.empty()) continue;
999 CasesO.indent(2) << "case " << Entry.first << ":\n";
1001 for (IAPrinter *IAP : UniqueIAPs) {
1007 CasesO.indent(4) << "return false;\n";
1010 if (CasesO.str().empty()) {
1012 O << " return false;\n";
1014 O << "#endif // PRINT_ALIAS_INSTR\n";
1018 if (!MCOpPredicates.empty())
1019 O << "static bool " << Target.getName() << ClassName
1020 << "ValidateMCOperand(const MCOperand &MCOp,\n"
1021 << " const MCSubtargetInfo &STI,\n"
1022 << " unsigned PredicateIndex);\n";
1025 O.indent(2) << "const char *AsmString;\n";
1026 O.indent(2) << "switch (MI->getOpcode()) {\n";
1027 O.indent(2) << "default: return false;\n";
1029 O.indent(2) << "}\n\n";
1031 // Code that prints the alias, replacing the operands with the ones from the
1033 O << " unsigned I = 0;\n";
1034 O << " while (AsmString[I] != ' ' && AsmString[I] != '\\t' &&\n";
1035 O << " AsmString[I] != '$' && AsmString[I] != '\\0')\n";
1037 O << " OS << '\\t' << StringRef(AsmString, I);\n";
1039 O << " if (AsmString[I] != '\\0') {\n";
1040 O << " if (AsmString[I] == ' ' || AsmString[I] == '\\t') {\n";
1041 O << " OS << '\\t';\n";
1045 O << " if (AsmString[I] == '$') {\n";
1047 O << " if (AsmString[I] == (char)0xff) {\n";
1049 O << " int OpIdx = AsmString[I++] - 1;\n";
1050 O << " int PrintMethodIdx = AsmString[I++] - 1;\n";
1051 O << " printCustomAliasOperand(MI, OpIdx, PrintMethodIdx, ";
1052 O << (PassSubtarget ? "STI, " : "");
1055 O << " printOperand(MI, unsigned(AsmString[I++]) - 1, ";
1056 O << (PassSubtarget ? "STI, " : "");
1059 O << " OS << AsmString[I++];\n";
1061 O << " } while (AsmString[I] != '\\0');\n";
1064 O << " return true;\n";
1067 //////////////////////////////
1068 // Write out the printCustomAliasOperand function
1069 //////////////////////////////
1071 O << "void " << Target.getName() << ClassName << "::"
1072 << "printCustomAliasOperand(\n"
1073 << " const MCInst *MI, unsigned OpIdx,\n"
1074 << " unsigned PrintMethodIdx,\n"
1075 << (PassSubtarget ? " const MCSubtargetInfo &STI,\n" : "")
1076 << " raw_ostream &OS) {\n";
1077 if (PrintMethods.empty())
1078 O << " llvm_unreachable(\"Unknown PrintMethod kind\");\n";
1080 O << " switch (PrintMethodIdx) {\n"
1082 << " llvm_unreachable(\"Unknown PrintMethod kind\");\n"
1085 for (unsigned i = 0; i < PrintMethods.size(); ++i) {
1086 O << " case " << i << ":\n"
1087 << " " << PrintMethods[i] << "(MI, OpIdx, "
1088 << (PassSubtarget ? "STI, " : "") << "OS);\n"
1095 if (!MCOpPredicates.empty()) {
1096 O << "static bool " << Target.getName() << ClassName
1097 << "ValidateMCOperand(const MCOperand &MCOp,\n"
1098 << " const MCSubtargetInfo &STI,\n"
1099 << " unsigned PredicateIndex) {\n"
1100 << " switch (PredicateIndex) {\n"
1102 << " llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n"
1105 for (unsigned i = 0; i < MCOpPredicates.size(); ++i) {
1106 Init *MCOpPred = MCOpPredicates[i]->getValueInit("MCOperandPredicate");
1107 if (CodeInit *SI = dyn_cast<CodeInit>(MCOpPred)) {
1108 O << " case " << i + 1 << ": {\n"
1109 << SI->getValue() << "\n"
1112 llvm_unreachable("Unexpected MCOperandPredicate field!");
1118 O << "#endif // PRINT_ALIAS_INSTR\n";
1121 AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) {
1122 Record *AsmWriter = Target.getAsmWriter();
1123 unsigned Variant = AsmWriter->getValueAsInt("Variant");
1125 // Get the instruction numbering.
1126 NumberedInstructions = Target.getInstructionsByEnumValue();
1128 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
1129 const CodeGenInstruction *I = NumberedInstructions[i];
1130 if (!I->AsmString.empty() && I->TheDef->getName() != "PHI")
1131 Instructions.emplace_back(*I, i, Variant);
1135 void AsmWriterEmitter::run(raw_ostream &O) {
1136 EmitPrintInstruction(O);
1137 EmitGetRegisterName(O);
1138 EmitPrintAliasInstruction(O);
1143 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
1144 emitSourceFileHeader("Assembly Writer Source Fragment", OS);
1145 AsmWriterEmitter(RK).run(OS);
1148 } // end namespace llvm