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 is 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 "CodeGenTarget.h"
17 #include "SequenceToOffsetTable.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/TableGen/Error.h"
25 #include "llvm/TableGen/Record.h"
26 #include "llvm/TableGen/TableGenBackend.h"
33 #define DEBUG_TYPE "asm-writer-emitter"
36 class AsmWriterEmitter {
37 RecordKeeper &Records;
39 std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
40 const std::vector<const CodeGenInstruction*> *NumberedInstructions;
41 std::vector<AsmWriterInst> Instructions;
42 std::vector<std::string> PrintMethods;
44 AsmWriterEmitter(RecordKeeper &R);
46 void run(raw_ostream &o);
49 void EmitPrintInstruction(raw_ostream &o);
50 void EmitGetRegisterName(raw_ostream &o);
51 void EmitPrintAliasInstruction(raw_ostream &O);
53 AsmWriterInst *getAsmWriterInstByID(unsigned ID) const {
54 assert(ID < NumberedInstructions->size());
55 std::map<const CodeGenInstruction*, AsmWriterInst*>::const_iterator I =
56 CGIAWIMap.find(NumberedInstructions->at(ID));
57 assert(I != CGIAWIMap.end() && "Didn't find inst!");
60 void FindUniqueOperandCommands(std::vector<std::string> &UOC,
61 std::vector<unsigned> &InstIdxs,
62 std::vector<unsigned> &InstOpsUsed) const;
64 } // end anonymous namespace
66 static void PrintCases(std::vector<std::pair<std::string,
67 AsmWriterOperand> > &OpsToPrint, raw_ostream &O) {
68 O << " case " << OpsToPrint.back().first << ": ";
69 AsmWriterOperand TheOp = OpsToPrint.back().second;
70 OpsToPrint.pop_back();
72 // Check to see if any other operands are identical in this list, and if so,
73 // emit a case label for them.
74 for (unsigned i = OpsToPrint.size(); i != 0; --i)
75 if (OpsToPrint[i-1].second == TheOp) {
76 O << "\n case " << OpsToPrint[i-1].first << ": ";
77 OpsToPrint.erase(OpsToPrint.begin()+i-1);
80 // Finally, emit the code.
86 /// EmitInstructions - Emit the last instruction in the vector and any other
87 /// instructions that are suitably similar to it.
88 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
90 AsmWriterInst FirstInst = Insts.back();
93 std::vector<AsmWriterInst> SimilarInsts;
94 unsigned DifferingOperand = ~0;
95 for (unsigned i = Insts.size(); i != 0; --i) {
96 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
98 if (DifferingOperand == ~0U) // First match!
99 DifferingOperand = DiffOp;
101 // If this differs in the same operand as the rest of the instructions in
102 // this class, move it to the SimilarInsts list.
103 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
104 SimilarInsts.push_back(Insts[i-1]);
105 Insts.erase(Insts.begin()+i-1);
110 O << " case " << FirstInst.CGI->Namespace << "::"
111 << FirstInst.CGI->TheDef->getName() << ":\n";
112 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
113 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
114 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
115 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
116 if (i != DifferingOperand) {
117 // If the operand is the same for all instructions, just print it.
118 O << " " << FirstInst.Operands[i].getCode();
120 // If this is the operand that varies between all of the instructions,
121 // emit a switch for just this operand now.
122 O << " switch (MI->getOpcode()) {\n";
123 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
124 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
125 FirstInst.CGI->TheDef->getName(),
126 FirstInst.Operands[i]));
128 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
129 AsmWriterInst &AWI = SimilarInsts[si];
130 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
131 AWI.CGI->TheDef->getName(),
134 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
135 while (!OpsToPrint.empty())
136 PrintCases(OpsToPrint, O);
144 void AsmWriterEmitter::
145 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
146 std::vector<unsigned> &InstIdxs,
147 std::vector<unsigned> &InstOpsUsed) const {
148 InstIdxs.assign(NumberedInstructions->size(), ~0U);
150 // This vector parallels UniqueOperandCommands, keeping track of which
151 // instructions each case are used for. It is a comma separated string of
153 std::vector<std::string> InstrsForCase;
154 InstrsForCase.resize(UniqueOperandCommands.size());
155 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
157 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
158 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
160 continue; // PHI, INLINEASM, CFI_INSTRUCTION, etc.
163 if (Inst->Operands.empty())
164 continue; // Instruction already done.
166 Command = " " + Inst->Operands[0].getCode() + "\n";
168 // Check to see if we already have 'Command' in UniqueOperandCommands.
170 bool FoundIt = false;
171 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
172 if (UniqueOperandCommands[idx] == Command) {
174 InstrsForCase[idx] += ", ";
175 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
180 InstIdxs[i] = UniqueOperandCommands.size();
181 UniqueOperandCommands.push_back(Command);
182 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
184 // This command matches one operand so far.
185 InstOpsUsed.push_back(1);
189 // For each entry of UniqueOperandCommands, there is a set of instructions
190 // that uses it. If the next command of all instructions in the set are
191 // identical, fold it into the command.
192 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
193 CommandIdx != e; ++CommandIdx) {
195 for (unsigned Op = 1; ; ++Op) {
196 // Scan for the first instruction in the set.
197 std::vector<unsigned>::iterator NIT =
198 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
199 if (NIT == InstIdxs.end()) break; // No commonality.
201 // If this instruction has no more operands, we isn't anything to merge
202 // into this command.
203 const AsmWriterInst *FirstInst =
204 getAsmWriterInstByID(NIT-InstIdxs.begin());
205 if (!FirstInst || FirstInst->Operands.size() == Op)
208 // Otherwise, scan to see if all of the other instructions in this command
209 // set share the operand.
211 // Keep track of the maximum, number of operands or any
212 // instruction we see in the group.
213 size_t MaxSize = FirstInst->Operands.size();
215 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
216 NIT != InstIdxs.end();
217 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
218 // Okay, found another instruction in this command set. If the operand
219 // matches, we're ok, otherwise bail out.
220 const AsmWriterInst *OtherInst =
221 getAsmWriterInstByID(NIT-InstIdxs.begin());
224 OtherInst->Operands.size() > FirstInst->Operands.size())
225 MaxSize = std::max(MaxSize, OtherInst->Operands.size());
227 if (!OtherInst || OtherInst->Operands.size() == Op ||
228 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
235 // Okay, everything in this command set has the same next operand. Add it
236 // to UniqueOperandCommands and remember that it was consumed.
237 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
239 UniqueOperandCommands[CommandIdx] += Command;
240 InstOpsUsed[CommandIdx]++;
244 // Prepend some of the instructions each case is used for onto the case val.
245 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
246 std::string Instrs = InstrsForCase[i];
247 if (Instrs.size() > 70) {
248 Instrs.erase(Instrs.begin()+70, Instrs.end());
253 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
254 UniqueOperandCommands[i];
259 static void UnescapeString(std::string &Str) {
260 for (unsigned i = 0; i != Str.size(); ++i) {
261 if (Str[i] == '\\' && i != Str.size()-1) {
263 default: continue; // Don't execute the code after the switch.
264 case 'a': Str[i] = '\a'; break;
265 case 'b': Str[i] = '\b'; break;
266 case 'e': Str[i] = 27; break;
267 case 'f': Str[i] = '\f'; break;
268 case 'n': Str[i] = '\n'; break;
269 case 'r': Str[i] = '\r'; break;
270 case 't': Str[i] = '\t'; break;
271 case 'v': Str[i] = '\v'; break;
272 case '"': Str[i] = '\"'; break;
273 case '\'': Str[i] = '\''; break;
274 case '\\': Str[i] = '\\'; break;
276 // Nuke the second character.
277 Str.erase(Str.begin()+i+1);
282 /// EmitPrintInstruction - Generate the code for the "printInstruction" method
283 /// implementation. Destroys all instances of AsmWriterInst information, by
284 /// clearing the Instructions vector.
285 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
286 Record *AsmWriter = Target.getAsmWriter();
287 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
290 "/// printInstruction - This method is automatically generated by tablegen\n"
291 "/// from the instruction set description.\n"
292 "void " << Target.getName() << ClassName
293 << "::printInstruction(const MCInst *MI, raw_ostream &O) {\n";
295 // Build an aggregate string, and build a table of offsets into it.
296 SequenceToOffsetTable<std::string> StringTable;
298 /// OpcodeInfo - This encodes the index of the string to use for the first
299 /// chunk of the output as well as indices used for operand printing.
300 /// To reduce the number of unhandled cases, we expand the size from 32-bit
301 /// to 32+16 = 48-bit.
302 std::vector<uint64_t> OpcodeInfo;
304 // Add all strings to the string table upfront so it can generate an optimized
306 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
307 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions->at(i)];
309 AWI->Operands[0].OperandType ==
310 AsmWriterOperand::isLiteralTextOperand &&
311 !AWI->Operands[0].Str.empty()) {
312 std::string Str = AWI->Operands[0].Str;
314 StringTable.add(Str);
318 StringTable.layout();
320 unsigned MaxStringIdx = 0;
321 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
322 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions->at(i)];
325 // Something not handled by the asmwriter printer.
327 } else if (AWI->Operands[0].OperandType !=
328 AsmWriterOperand::isLiteralTextOperand ||
329 AWI->Operands[0].Str.empty()) {
330 // Something handled by the asmwriter printer, but with no leading string.
331 Idx = StringTable.get("");
333 std::string Str = AWI->Operands[0].Str;
335 Idx = StringTable.get(Str);
336 MaxStringIdx = std::max(MaxStringIdx, Idx);
338 // Nuke the string from the operand list. It is now handled!
339 AWI->Operands.erase(AWI->Operands.begin());
342 // Bias offset by one since we want 0 as a sentinel.
343 OpcodeInfo.push_back(Idx+1);
346 // Figure out how many bits we used for the string index.
347 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
349 // To reduce code size, we compactify common instructions into a few bits
350 // in the opcode-indexed table.
351 unsigned BitsLeft = 64-AsmStrBits;
353 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
356 std::vector<std::string> UniqueOperandCommands;
357 std::vector<unsigned> InstIdxs;
358 std::vector<unsigned> NumInstOpsHandled;
359 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
362 // If we ran out of operands to print, we're done.
363 if (UniqueOperandCommands.empty()) break;
365 // Compute the number of bits we need to represent these cases, this is
366 // ceil(log2(numentries)).
367 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
369 // If we don't have enough bits for this operand, don't include it.
370 if (NumBits > BitsLeft) {
371 DEBUG(errs() << "Not enough bits to densely encode " << NumBits
376 // Otherwise, we can include this in the initial lookup table. Add it in.
377 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
378 if (InstIdxs[i] != ~0U) {
379 OpcodeInfo[i] |= (uint64_t)InstIdxs[i] << (64-BitsLeft);
383 // Remove the info about this operand.
384 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
385 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
386 if (!Inst->Operands.empty()) {
387 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
388 assert(NumOps <= Inst->Operands.size() &&
389 "Can't remove this many ops!");
390 Inst->Operands.erase(Inst->Operands.begin(),
391 Inst->Operands.begin()+NumOps);
395 // Remember the handlers for this set of operands.
396 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
400 // We always emit at least one 32-bit table. A second table is emitted if
401 // more bits are needed.
402 O<<" static const uint32_t OpInfo[] = {\n";
403 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
404 O << " " << (OpcodeInfo[i] & 0xffffffff) << "U,\t// "
405 << NumberedInstructions->at(i)->TheDef->getName() << "\n";
407 // Add a dummy entry so the array init doesn't end with a comma.
412 // Add a second OpInfo table only when it is necessary.
413 // Adjust the type of the second table based on the number of bits needed.
414 O << " static const uint"
415 << ((BitsLeft < 16) ? "32" : (BitsLeft < 24) ? "16" : "8")
416 << "_t OpInfo2[] = {\n";
417 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
418 O << " " << (OpcodeInfo[i] >> 32) << "U,\t// "
419 << NumberedInstructions->at(i)->TheDef->getName() << "\n";
421 // Add a dummy entry so the array init doesn't end with a comma.
426 // Emit the string itself.
427 O << " const char AsmStrs[] = {\n";
428 StringTable.emit(O, printChar);
431 O << " O << \"\\t\";\n\n";
433 O << " // Emit the opcode for the instruction.\n";
435 // If we have two tables then we need to perform two lookups and combine
436 // the results into a single 64-bit value.
437 O << " uint64_t Bits1 = OpInfo[MI->getOpcode()];\n"
438 << " uint64_t Bits2 = OpInfo2[MI->getOpcode()];\n"
439 << " uint64_t Bits = (Bits2 << 32) | Bits1;\n";
441 // If only one table is used we just need to perform a single lookup.
442 O << " uint32_t Bits = OpInfo[MI->getOpcode()];\n";
444 O << " assert(Bits != 0 && \"Cannot print this instruction.\");\n"
445 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
447 // Output the table driven operand information.
448 BitsLeft = 64-AsmStrBits;
449 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
450 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
452 // Compute the number of bits we need to represent these cases, this is
453 // ceil(log2(numentries)).
454 unsigned NumBits = Log2_32_Ceil(Commands.size());
455 assert(NumBits <= BitsLeft && "consistency error");
457 // Emit code to extract this field from Bits.
458 O << "\n // Fragment " << i << " encoded into " << NumBits
459 << " bits for " << Commands.size() << " unique commands.\n";
461 if (Commands.size() == 2) {
462 // Emit two possibilitys with if/else.
463 O << " if ((Bits >> "
464 << (64-BitsLeft) << ") & "
465 << ((1 << NumBits)-1) << ") {\n"
470 } else if (Commands.size() == 1) {
471 // Emit a single possibility.
472 O << Commands[0] << "\n\n";
474 O << " switch ((Bits >> "
475 << (64-BitsLeft) << ") & "
476 << ((1 << NumBits)-1) << ") {\n"
477 << " default: // unreachable.\n";
479 // Print out all the cases.
480 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
481 O << " case " << i << ":\n";
490 // Okay, delete instructions with no operand info left.
491 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
492 // Entire instruction has been emitted?
493 AsmWriterInst &Inst = Instructions[i];
494 if (Inst.Operands.empty()) {
495 Instructions.erase(Instructions.begin()+i);
501 // Because this is a vector, we want to emit from the end. Reverse all of the
502 // elements in the vector.
503 std::reverse(Instructions.begin(), Instructions.end());
506 // Now that we've emitted all of the operand info that fit into 32 bits, emit
507 // information for those instructions that are left. This is a less dense
508 // encoding, but we expect the main 32-bit table to handle the majority of
510 if (!Instructions.empty()) {
511 // Find the opcode # of inline asm.
512 O << " switch (MI->getOpcode()) {\n";
513 while (!Instructions.empty())
514 EmitInstructions(Instructions, O);
524 emitRegisterNameString(raw_ostream &O, StringRef AltName,
525 const std::vector<CodeGenRegister*> &Registers) {
526 SequenceToOffsetTable<std::string> StringTable;
527 SmallVector<std::string, 4> AsmNames(Registers.size());
528 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
529 const CodeGenRegister &Reg = *Registers[i];
530 std::string &AsmName = AsmNames[i];
532 // "NoRegAltName" is special. We don't need to do a lookup for that,
533 // as it's just a reference to the default register name.
534 if (AltName == "" || AltName == "NoRegAltName") {
535 AsmName = Reg.TheDef->getValueAsString("AsmName");
537 AsmName = Reg.getName();
539 // Make sure the register has an alternate name for this index.
540 std::vector<Record*> AltNameList =
541 Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
543 for (e = AltNameList.size();
544 Idx < e && (AltNameList[Idx]->getName() != AltName);
547 // If the register has an alternate name for this index, use it.
548 // Otherwise, leave it empty as an error flag.
550 std::vector<std::string> AltNames =
551 Reg.TheDef->getValueAsListOfStrings("AltNames");
552 if (AltNames.size() <= Idx)
553 PrintFatalError(Reg.TheDef->getLoc(),
554 "Register definition missing alt name for '" +
556 AsmName = AltNames[Idx];
559 StringTable.add(AsmName);
562 StringTable.layout();
563 O << " static const char AsmStrs" << AltName << "[] = {\n";
564 StringTable.emit(O, printChar);
567 O << " static const uint32_t RegAsmOffset" << AltName << "[] = {";
568 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
571 O << StringTable.get(AsmNames[i]) << ", ";
577 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
578 Record *AsmWriter = Target.getAsmWriter();
579 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
580 const std::vector<CodeGenRegister*> &Registers =
581 Target.getRegBank().getRegisters();
582 std::vector<Record*> AltNameIndices = Target.getRegAltNameIndices();
583 bool hasAltNames = AltNameIndices.size() > 1;
586 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
587 "/// from the register set description. This returns the assembler name\n"
588 "/// for the specified register.\n"
589 "const char *" << Target.getName() << ClassName << "::";
591 O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
593 O << "getRegisterName(unsigned RegNo) {\n";
594 O << " assert(RegNo && RegNo < " << (Registers.size()+1)
595 << " && \"Invalid register number!\");\n"
599 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i)
600 emitRegisterNameString(O, AltNameIndices[i]->getName(), Registers);
602 emitRegisterNameString(O, "", Registers);
605 O << " const uint32_t *RegAsmOffset;\n"
606 << " const char *AsmStrs;\n"
607 << " switch(AltIdx) {\n"
608 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n";
609 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i) {
610 std::string Namespace = AltNameIndices[1]->getValueAsString("Namespace");
611 std::string AltName(AltNameIndices[i]->getName());
612 O << " case " << Namespace << "::" << AltName
614 << " AsmStrs = AsmStrs" << AltName << ";\n"
615 << " RegAsmOffset = RegAsmOffset" << AltName << ";\n"
621 O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
622 << " \"Invalid alt name index for register!\");\n"
623 << " return AsmStrs+RegAsmOffset[RegNo-1];\n"
628 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
629 // they both have the same conditionals. In which case, we cannot print out the
630 // alias for that pattern.
632 std::vector<std::string> Conds;
633 std::map<StringRef, std::pair<int, int>> OpMap;
634 SmallVector<Record*, 4> ReqFeatures;
637 std::string AsmString;
639 IAPrinter(std::string R, std::string AS) : Result(R), AsmString(AS) {}
641 void addCond(const std::string &C) { Conds.push_back(C); }
643 void addOperand(StringRef Op, int OpIdx, int PrintMethodIdx = -1) {
644 assert(OpIdx >= 0 && OpIdx < 0xFE && "Idx out of range");
645 assert(PrintMethodIdx == -1 || PrintMethodIdx < 0xFF && "Idx out of range");
646 OpMap[Op] = std::make_pair(OpIdx, PrintMethodIdx);
649 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
650 int getOpIndex(StringRef Op) { return OpMap[Op].first; }
651 std::pair<int, int> &getOpData(StringRef Op) { return OpMap[Op]; }
653 void print(raw_ostream &O) {
654 if (Conds.empty() && ReqFeatures.empty()) {
655 O.indent(6) << "return true;\n";
661 for (std::vector<std::string>::iterator
662 I = Conds.begin(), E = Conds.end(); I != E; ++I) {
663 if (I != Conds.begin()) {
672 O.indent(6) << "// " << Result << "\n";
674 // Directly mangle mapped operands into the string. Each operand is
675 // identified by a '$' sign followed by a byte identifying the number of the
676 // operand. We add one to the index to avoid zero bytes.
677 std::pair<StringRef, StringRef> ASM = StringRef(AsmString).split(' ');
678 SmallString<128> OutString = ASM.first;
679 if (!ASM.second.empty()) {
680 raw_svector_ostream OS(OutString);
682 for (StringRef::iterator I = ASM.second.begin(), E = ASM.second.end();
686 StringRef::iterator Start = ++I;
688 ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') ||
689 (*I >= '0' && *I <= '9') || *I == '_'))
691 StringRef Name(Start, I - Start);
692 assert(isOpMapped(Name) && "Unmapped operand!");
694 int OpIndex, PrintIndex;
695 std::tie(OpIndex, PrintIndex) = getOpData(Name);
696 if (PrintIndex == -1) {
697 // Can use the default printOperand route.
698 OS << format("\\x%02X", (unsigned char)OpIndex + 1);
700 // 3 bytes if a PrintMethod is needed: 0xFF, the MCInst operand
701 // number, and which of our pre-detected Methods to call.
702 OS << format("\\xFF\\x%02X\\x%02X", OpIndex + 1, PrintIndex + 1);
710 O.indent(6) << "AsmString = \"" << OutString.str() << "\";\n";
712 O.indent(6) << "break;\n";
716 bool operator==(const IAPrinter &RHS) {
717 if (Conds.size() != RHS.Conds.size())
721 for (std::vector<std::string>::iterator
722 I = Conds.begin(), E = Conds.end(); I != E; ++I)
723 if (*I != RHS.Conds[Idx++])
730 } // end anonymous namespace
732 static unsigned CountNumOperands(StringRef AsmString) {
734 std::pair<StringRef, StringRef> ASM = AsmString.split(' ');
736 while (!ASM.second.empty()) {
738 ASM = ASM.second.split(' ');
744 static unsigned CountResultNumOperands(StringRef AsmString) {
746 std::pair<StringRef, StringRef> ASM = AsmString.split('\t');
748 if (!ASM.second.empty()) {
749 size_t I = ASM.second.find('{');
750 StringRef Str = ASM.second;
751 if (I != StringRef::npos)
752 Str = ASM.second.substr(I, ASM.second.find('|', I));
754 ASM = Str.split(' ');
758 ASM = ASM.second.split(' ');
759 } while (!ASM.second.empty());
765 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
766 Record *AsmWriter = Target.getAsmWriter();
768 O << "\n#ifdef PRINT_ALIAS_INSTR\n";
769 O << "#undef PRINT_ALIAS_INSTR\n\n";
771 //////////////////////////////
772 // Gather information about aliases we need to print
773 //////////////////////////////
775 // Emit the method that prints the alias instruction.
776 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
778 std::vector<Record*> AllInstAliases =
779 Records.getAllDerivedDefinitions("InstAlias");
781 // Create a map from the qualified name to a list of potential matches.
782 std::map<std::string, std::vector<CodeGenInstAlias*> > AliasMap;
783 for (std::vector<Record*>::iterator
784 I = AllInstAliases.begin(), E = AllInstAliases.end(); I != E; ++I) {
785 CodeGenInstAlias *Alias = new CodeGenInstAlias(*I, Target);
786 const Record *R = *I;
787 if (!R->getValueAsBit("EmitAlias"))
788 continue; // We were told not to emit the alias, but to emit the aliasee.
789 const DagInit *DI = R->getValueAsDag("ResultInst");
790 const DefInit *Op = cast<DefInit>(DI->getOperator());
791 AliasMap[getQualifiedName(Op->getDef())].push_back(Alias);
794 // A map of which conditions need to be met for each instruction operand
795 // before it can be matched to the mnemonic.
796 std::map<std::string, std::vector<IAPrinter*> > IAPrinterMap;
798 for (std::map<std::string, std::vector<CodeGenInstAlias*> >::iterator
799 I = AliasMap.begin(), E = AliasMap.end(); I != E; ++I) {
800 std::vector<CodeGenInstAlias*> &Aliases = I->second;
802 for (std::vector<CodeGenInstAlias*>::iterator
803 II = Aliases.begin(), IE = Aliases.end(); II != IE; ++II) {
804 const CodeGenInstAlias *CGA = *II;
805 unsigned LastOpNo = CGA->ResultInstOperandIndex.size();
806 unsigned NumResultOps =
807 CountResultNumOperands(CGA->ResultInst->AsmString);
809 // Don't emit the alias if it has more operands than what it's aliasing.
810 if (NumResultOps < CountNumOperands(CGA->AsmString))
813 IAPrinter *IAP = new IAPrinter(CGA->Result->getAsString(),
817 Cond = std::string("MI->getNumOperands() == ") + llvm::utostr(LastOpNo);
820 bool CantHandle = false;
822 for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
823 const CodeGenInstAlias::ResultOperand &RO = CGA->ResultOperands[i];
826 case CodeGenInstAlias::ResultOperand::K_Record: {
827 const Record *Rec = RO.getRecord();
828 StringRef ROName = RO.getName();
829 int PrintMethodIdx = -1;
831 // These two may have a PrintMethod, which we want to record (if it's
832 // the first time we've seen it) and provide an index for the aliasing
834 if (Rec->isSubClassOf("RegisterOperand") ||
835 Rec->isSubClassOf("Operand")) {
836 std::string PrintMethod = Rec->getValueAsString("PrintMethod");
837 if (PrintMethod != "" && PrintMethod != "printOperand") {
838 PrintMethodIdx = std::find(PrintMethods.begin(),
839 PrintMethods.end(), PrintMethod) -
840 PrintMethods.begin();
841 if (static_cast<unsigned>(PrintMethodIdx) == PrintMethods.size())
842 PrintMethods.push_back(PrintMethod);
846 if (Rec->isSubClassOf("RegisterOperand"))
847 Rec = Rec->getValueAsDef("RegClass");
848 if (Rec->isSubClassOf("RegisterClass")) {
849 Cond = std::string("MI->getOperand(")+llvm::utostr(i)+").isReg()";
852 if (!IAP->isOpMapped(ROName)) {
853 IAP->addOperand(ROName, i, PrintMethodIdx);
854 Record *R = CGA->ResultOperands[i].getRecord();
855 if (R->isSubClassOf("RegisterOperand"))
856 R = R->getValueAsDef("RegClass");
857 Cond = std::string("MRI.getRegClass(") + Target.getName() + "::" +
858 R->getName() + "RegClassID)"
859 ".contains(MI->getOperand(" + llvm::utostr(i) + ").getReg())";
862 Cond = std::string("MI->getOperand(") +
863 llvm::utostr(i) + ").getReg() == MI->getOperand(" +
864 llvm::utostr(IAP->getOpIndex(ROName)) + ").getReg()";
868 // Assume all printable operands are desired for now. This can be
869 // overridden in the InstAlias instantiation if neccessary.
870 IAP->addOperand(ROName, i, PrintMethodIdx);
875 case CodeGenInstAlias::ResultOperand::K_Imm: {
876 std::string Op = "MI->getOperand(" + llvm::utostr(i) + ")";
878 // Just because the alias has an immediate result, doesn't mean the
879 // MCInst will. An MCExpr could be present, for example.
880 IAP->addCond(Op + ".isImm()");
882 Cond = Op + ".getImm() == "
883 + llvm::utostr(CGA->ResultOperands[i].getImm());
887 case CodeGenInstAlias::ResultOperand::K_Reg:
888 // If this is zero_reg, something's playing tricks we're not
889 // equipped to handle.
890 if (!CGA->ResultOperands[i].getRegister()) {
895 Cond = std::string("MI->getOperand(") +
896 llvm::utostr(i) + ").getReg() == " + Target.getName() +
897 "::" + CGA->ResultOperands[i].getRegister()->getName();
905 if (CantHandle) continue;
906 IAPrinterMap[I->first].push_back(IAP);
910 //////////////////////////////
911 // Write out the printAliasInstr function
912 //////////////////////////////
915 raw_string_ostream HeaderO(Header);
917 HeaderO << "bool " << Target.getName() << ClassName
918 << "::printAliasInstr(const MCInst"
919 << " *MI, raw_ostream &OS) {\n";
922 raw_string_ostream CasesO(Cases);
924 for (std::map<std::string, std::vector<IAPrinter*> >::iterator
925 I = IAPrinterMap.begin(), E = IAPrinterMap.end(); I != E; ++I) {
926 std::vector<IAPrinter*> &IAPs = I->second;
927 std::vector<IAPrinter*> UniqueIAPs;
929 for (std::vector<IAPrinter*>::iterator
930 II = IAPs.begin(), IE = IAPs.end(); II != IE; ++II) {
931 IAPrinter *LHS = *II;
933 for (std::vector<IAPrinter*>::iterator
934 III = IAPs.begin(), IIE = IAPs.end(); III != IIE; ++III) {
935 IAPrinter *RHS = *III;
936 if (LHS != RHS && *LHS == *RHS) {
942 if (!IsDup) UniqueIAPs.push_back(LHS);
945 if (UniqueIAPs.empty()) continue;
947 CasesO.indent(2) << "case " << I->first << ":\n";
949 for (std::vector<IAPrinter*>::iterator
950 II = UniqueIAPs.begin(), IE = UniqueIAPs.end(); II != IE; ++II) {
951 IAPrinter *IAP = *II;
957 CasesO.indent(4) << "return false;\n";
960 if (CasesO.str().empty()) {
962 O << " return false;\n";
964 O << "#endif // PRINT_ALIAS_INSTR\n";
969 O.indent(2) << "const char *AsmString;\n";
970 O.indent(2) << "switch (MI->getOpcode()) {\n";
971 O.indent(2) << "default: return false;\n";
973 O.indent(2) << "}\n\n";
975 // Code that prints the alias, replacing the operands with the ones from the
977 O << " unsigned I = 0;\n";
978 O << " while (AsmString[I] != ' ' && AsmString[I] != '\\0')\n";
980 O << " OS << '\\t' << StringRef(AsmString, I);\n";
982 O << " if (AsmString[I] != '\\0') {\n";
983 O << " OS << '\\t';\n";
985 O << " if (AsmString[I] == '$') {\n";
987 O << " if (AsmString[I] == (char)0xff) {\n";
989 O << " int OpIdx = AsmString[I++] - 1;\n";
990 O << " int PrintMethodIdx = AsmString[I++] - 1;\n";
991 O << " printCustomAliasOperand(MI, OpIdx, PrintMethodIdx, OS);\n";
993 O << " printOperand(MI, unsigned(AsmString[I++]) - 1, OS);\n";
995 O << " OS << AsmString[I++];\n";
997 O << " } while (AsmString[I] != '\\0');\n";
1000 O << " return true;\n";
1003 //////////////////////////////
1004 // Write out the printCustomAliasOperand function
1005 //////////////////////////////
1007 O << "void " << Target.getName() << ClassName << "::"
1008 << "printCustomAliasOperand(\n"
1009 << " const MCInst *MI, unsigned OpIdx,\n"
1010 << " unsigned PrintMethodIdx, raw_ostream &OS) {\n"
1011 << " switch (PrintMethodIdx) {\n"
1013 << " llvm_unreachable(\"Unknown PrintMethod kind\");\n"
1016 for (unsigned i = 0; i < PrintMethods.size(); ++i) {
1017 O << " case " << i << ":\n"
1018 << " " << PrintMethods[i] << "(MI, OpIdx, OS);\n"
1025 O << "#endif // PRINT_ALIAS_INSTR\n";
1028 AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) {
1029 Record *AsmWriter = Target.getAsmWriter();
1030 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
1031 E = Target.inst_end();
1033 if (!(*I)->AsmString.empty() && (*I)->TheDef->getName() != "PHI")
1034 Instructions.push_back(
1035 AsmWriterInst(**I, AsmWriter->getValueAsInt("Variant"),
1036 AsmWriter->getValueAsInt("OperandSpacing")));
1038 // Get the instruction numbering.
1039 NumberedInstructions = &Target.getInstructionsByEnumValue();
1041 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
1042 // all machine instructions are necessarily being printed, so there may be
1043 // target instructions not in this map.
1044 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
1045 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
1048 void AsmWriterEmitter::run(raw_ostream &O) {
1049 EmitPrintInstruction(O);
1050 EmitGetRegisterName(O);
1051 EmitPrintAliasInstruction(O);
1057 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
1058 emitSourceFileHeader("Assembly Writer Source Fragment", OS);
1059 AsmWriterEmitter(RK).run(OS);
1062 } // End llvm namespace