blob: 221976a842d985a5053ece02a68ba1d5da4d1471 [file] [log] [blame]
Chris Lattner1c4ae852004-08-01 05:59:33 +00001//===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
Misha Brukman650ba8e2005-04-22 00:00:37 +00002//
Chris Lattner1c4ae852004-08-01 05:59:33 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner8adcd9f2007-12-29 20:37:13 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman650ba8e2005-04-22 00:00:37 +00007//
Chris Lattner1c4ae852004-08-01 05:59:33 +00008//===----------------------------------------------------------------------===//
9//
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.
12//
13//===----------------------------------------------------------------------===//
14
Sean Callananb7e8f4a2010-02-09 21:50:41 +000015#include "AsmWriterInst.h"
Chris Lattner1c4ae852004-08-01 05:59:33 +000016#include "CodeGenTarget.h"
Jakob Stoklund Olesen892f4802012-03-30 21:12:52 +000017#include "SequenceToOffsetTable.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000018#include "llvm/ADT/SmallString.h"
Craig Topperb6350132012-07-27 06:44:02 +000019#include "llvm/ADT/StringExtras.h"
Owen Andersona84be6c2011-06-27 21:06:21 +000020#include "llvm/ADT/Twine.h"
Chris Lattner692374c2006-07-18 17:18:03 +000021#include "llvm/Support/Debug.h"
Benjamin Kramer17c17bc2013-09-11 15:42:16 +000022#include "llvm/Support/Format.h"
Chris Lattner692374c2006-07-18 17:18:03 +000023#include "llvm/Support/MathExtras.h"
Peter Collingbourne84c287e2011-10-01 16:41:13 +000024#include "llvm/TableGen/Error.h"
25#include "llvm/TableGen/Record.h"
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000026#include "llvm/TableGen/TableGenBackend.h"
Jeff Cohenda636b32005-01-22 18:50:10 +000027#include <algorithm>
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000028#include <cassert>
29#include <map>
30#include <vector>
Chris Lattner1c4ae852004-08-01 05:59:33 +000031using namespace llvm;
32
Chandler Carruthe96dd892014-04-21 22:55:11 +000033#define DEBUG_TYPE "asm-writer-emitter"
34
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000035namespace {
36class AsmWriterEmitter {
37 RecordKeeper &Records;
Ahmed Bougachabd214002013-10-28 18:07:17 +000038 CodeGenTarget Target;
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000039 std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
Craig Topper4c6129a2014-02-05 07:56:49 +000040 const std::vector<const CodeGenInstruction*> *NumberedInstructions;
Ahmed Bougachabd214002013-10-28 18:07:17 +000041 std::vector<AsmWriterInst> Instructions;
Tim Northoveree20caa2014-05-12 18:04:06 +000042 std::vector<std::string> PrintMethods;
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000043public:
Ahmed Bougachabd214002013-10-28 18:07:17 +000044 AsmWriterEmitter(RecordKeeper &R);
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000045
46 void run(raw_ostream &o);
47
48private:
49 void EmitPrintInstruction(raw_ostream &o);
50 void EmitGetRegisterName(raw_ostream &o);
51 void EmitPrintAliasInstruction(raw_ostream &O);
52
53 AsmWriterInst *getAsmWriterInstByID(unsigned ID) const {
Craig Topper4c6129a2014-02-05 07:56:49 +000054 assert(ID < NumberedInstructions->size());
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000055 std::map<const CodeGenInstruction*, AsmWriterInst*>::const_iterator I =
Craig Topper4c6129a2014-02-05 07:56:49 +000056 CGIAWIMap.find(NumberedInstructions->at(ID));
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +000057 assert(I != CGIAWIMap.end() && "Didn't find inst!");
58 return I->second;
59 }
60 void FindUniqueOperandCommands(std::vector<std::string> &UOC,
61 std::vector<unsigned> &InstIdxs,
62 std::vector<unsigned> &InstOpsUsed) const;
63};
64} // end anonymous namespace
65
Chris Lattner59a7f5c2005-01-22 20:31:17 +000066static void PrintCases(std::vector<std::pair<std::string,
Daniel Dunbar38a22bf2009-07-03 00:10:29 +000067 AsmWriterOperand> > &OpsToPrint, raw_ostream &O) {
Chris Lattner59a7f5c2005-01-22 20:31:17 +000068 O << " case " << OpsToPrint.back().first << ": ";
69 AsmWriterOperand TheOp = OpsToPrint.back().second;
70 OpsToPrint.pop_back();
71
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);
78 }
79
80 // Finally, emit the code.
Chris Lattner692374c2006-07-18 17:18:03 +000081 O << TheOp.getCode();
Chris Lattner59a7f5c2005-01-22 20:31:17 +000082 O << "break;\n";
83}
84
Chris Lattner9ceb7c82005-01-22 18:38:13 +000085
86/// EmitInstructions - Emit the last instruction in the vector and any other
87/// instructions that are suitably similar to it.
88static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
Daniel Dunbar38a22bf2009-07-03 00:10:29 +000089 raw_ostream &O) {
Chris Lattner9ceb7c82005-01-22 18:38:13 +000090 AsmWriterInst FirstInst = Insts.back();
91 Insts.pop_back();
92
93 std::vector<AsmWriterInst> SimilarInsts;
94 unsigned DifferingOperand = ~0;
95 for (unsigned i = Insts.size(); i != 0; --i) {
Chris Lattner92275bb2005-01-22 19:22:23 +000096 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
97 if (DiffOp != ~1U) {
Chris Lattner9ceb7c82005-01-22 18:38:13 +000098 if (DifferingOperand == ~0U) // First match!
99 DifferingOperand = DiffOp;
100
101 // If this differs in the same operand as the rest of the instructions in
102 // this class, move it to the SimilarInsts list.
Chris Lattner92275bb2005-01-22 19:22:23 +0000103 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
Chris Lattner9ceb7c82005-01-22 18:38:13 +0000104 SimilarInsts.push_back(Insts[i-1]);
105 Insts.erase(Insts.begin()+i-1);
106 }
107 }
108 }
109
Chris Lattner017b93d2006-05-01 17:01:17 +0000110 O << " case " << FirstInst.CGI->Namespace << "::"
Chris Lattner9ceb7c82005-01-22 18:38:13 +0000111 << FirstInst.CGI->TheDef->getName() << ":\n";
112 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
Chris Lattner017b93d2006-05-01 17:01:17 +0000113 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
Chris Lattner9ceb7c82005-01-22 18:38:13 +0000114 << 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.
Chris Lattner692374c2006-07-18 17:18:03 +0000118 O << " " << FirstInst.Operands[i].getCode();
Chris Lattner9ceb7c82005-01-22 18:38:13 +0000119 } else {
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";
Chris Lattner59a7f5c2005-01-22 20:31:17 +0000123 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
Chris Lattner017b93d2006-05-01 17:01:17 +0000124 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
Chris Lattner59a7f5c2005-01-22 20:31:17 +0000125 FirstInst.CGI->TheDef->getName(),
126 FirstInst.Operands[i]));
Misha Brukman650ba8e2005-04-22 00:00:37 +0000127
Chris Lattner9ceb7c82005-01-22 18:38:13 +0000128 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
Chris Lattner59a7f5c2005-01-22 20:31:17 +0000129 AsmWriterInst &AWI = SimilarInsts[si];
Chris Lattner017b93d2006-05-01 17:01:17 +0000130 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
Chris Lattner59a7f5c2005-01-22 20:31:17 +0000131 AWI.CGI->TheDef->getName(),
132 AWI.Operands[i]));
Chris Lattner9ceb7c82005-01-22 18:38:13 +0000133 }
Chris Lattner59a7f5c2005-01-22 20:31:17 +0000134 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
135 while (!OpsToPrint.empty())
136 PrintCases(OpsToPrint, O);
Chris Lattner9ceb7c82005-01-22 18:38:13 +0000137 O << " }";
138 }
139 O << "\n";
140 }
Chris Lattner9ceb7c82005-01-22 18:38:13 +0000141 O << " break;\n";
142}
Chris Lattner0c23ba52005-01-22 17:32:42 +0000143
Chris Lattner692374c2006-07-18 17:18:03 +0000144void AsmWriterEmitter::
Jim Grosbacha5497342010-09-29 22:32:50 +0000145FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
Chris Lattneredee5252006-07-18 18:28:27 +0000146 std::vector<unsigned> &InstIdxs,
147 std::vector<unsigned> &InstOpsUsed) const {
Craig Topper4c6129a2014-02-05 07:56:49 +0000148 InstIdxs.assign(NumberedInstructions->size(), ~0U);
Jim Grosbacha5497342010-09-29 22:32:50 +0000149
Chris Lattner692374c2006-07-18 17:18:03 +0000150 // This vector parallels UniqueOperandCommands, keeping track of which
151 // instructions each case are used for. It is a comma separated string of
152 // enums.
153 std::vector<std::string> InstrsForCase;
154 InstrsForCase.resize(UniqueOperandCommands.size());
Chris Lattneredee5252006-07-18 18:28:27 +0000155 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
Jim Grosbacha5497342010-09-29 22:32:50 +0000156
Craig Topper4c6129a2014-02-05 07:56:49 +0000157 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
Chris Lattner692374c2006-07-18 17:18:03 +0000158 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
Craig Topper24064772014-04-15 07:20:03 +0000159 if (!Inst)
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000160 continue; // PHI, INLINEASM, CFI_INSTRUCTION, etc.
Jim Grosbacha5497342010-09-29 22:32:50 +0000161
Chris Lattner692374c2006-07-18 17:18:03 +0000162 std::string Command;
Chris Lattnercb0c8482006-07-18 17:56:07 +0000163 if (Inst->Operands.empty())
Chris Lattner692374c2006-07-18 17:18:03 +0000164 continue; // Instruction already done.
Chris Lattner9d250692006-07-18 17:50:22 +0000165
Chris Lattnercb0c8482006-07-18 17:56:07 +0000166 Command = " " + Inst->Operands[0].getCode() + "\n";
Chris Lattner9d250692006-07-18 17:50:22 +0000167
Chris Lattner692374c2006-07-18 17:18:03 +0000168 // Check to see if we already have 'Command' in UniqueOperandCommands.
169 // If not, add it.
170 bool FoundIt = false;
171 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
172 if (UniqueOperandCommands[idx] == Command) {
173 InstIdxs[i] = idx;
174 InstrsForCase[idx] += ", ";
175 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
176 FoundIt = true;
177 break;
178 }
179 if (!FoundIt) {
180 InstIdxs[i] = UniqueOperandCommands.size();
181 UniqueOperandCommands.push_back(Command);
182 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
Chris Lattneredee5252006-07-18 18:28:27 +0000183
184 // This command matches one operand so far.
185 InstOpsUsed.push_back(1);
186 }
187 }
Jim Grosbacha5497342010-09-29 22:32:50 +0000188
Chris Lattneredee5252006-07-18 18:28:27 +0000189 // 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) {
Jim Grosbacha5497342010-09-29 22:32:50 +0000194
Chris Lattneredee5252006-07-18 18:28:27 +0000195 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.
200
201 // If this instruction has no more operands, we isn't anything to merge
202 // into this command.
Jim Grosbacha5497342010-09-29 22:32:50 +0000203 const AsmWriterInst *FirstInst =
Chris Lattneredee5252006-07-18 18:28:27 +0000204 getAsmWriterInstByID(NIT-InstIdxs.begin());
205 if (!FirstInst || FirstInst->Operands.size() == Op)
206 break;
207
208 // Otherwise, scan to see if all of the other instructions in this command
209 // set share the operand.
210 bool AllSame = true;
David Greene5b4bc262009-07-29 20:10:24 +0000211 // Keep track of the maximum, number of operands or any
212 // instruction we see in the group.
213 size_t MaxSize = FirstInst->Operands.size();
214
Chris Lattneredee5252006-07-18 18:28:27 +0000215 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.
Jim Grosbacha5497342010-09-29 22:32:50 +0000220 const AsmWriterInst *OtherInst =
Chris Lattneredee5252006-07-18 18:28:27 +0000221 getAsmWriterInstByID(NIT-InstIdxs.begin());
David Greene5b4bc262009-07-29 20:10:24 +0000222
223 if (OtherInst &&
224 OtherInst->Operands.size() > FirstInst->Operands.size())
225 MaxSize = std::max(MaxSize, OtherInst->Operands.size());
226
Chris Lattneredee5252006-07-18 18:28:27 +0000227 if (!OtherInst || OtherInst->Operands.size() == Op ||
228 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
229 AllSame = false;
230 break;
231 }
232 }
233 if (!AllSame) break;
Jim Grosbacha5497342010-09-29 22:32:50 +0000234
Chris Lattneredee5252006-07-18 18:28:27 +0000235 // 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";
Jim Grosbacha5497342010-09-29 22:32:50 +0000238
Chris Lattneredee5252006-07-18 18:28:27 +0000239 UniqueOperandCommands[CommandIdx] += Command;
240 InstOpsUsed[CommandIdx]++;
Chris Lattner692374c2006-07-18 17:18:03 +0000241 }
242 }
Jim Grosbacha5497342010-09-29 22:32:50 +0000243
Chris Lattner692374c2006-07-18 17:18:03 +0000244 // 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());
249 Instrs += "...";
250 }
Jim Grosbacha5497342010-09-29 22:32:50 +0000251
Chris Lattner692374c2006-07-18 17:18:03 +0000252 if (!Instrs.empty())
Jim Grosbacha5497342010-09-29 22:32:50 +0000253 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
Chris Lattner692374c2006-07-18 17:18:03 +0000254 UniqueOperandCommands[i];
255 }
256}
257
258
Daniel Dunbar04f049f2009-10-17 20:43:42 +0000259static void UnescapeString(std::string &Str) {
260 for (unsigned i = 0; i != Str.size(); ++i) {
261 if (Str[i] == '\\' && i != Str.size()-1) {
262 switch (Str[i+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;
275 }
276 // Nuke the second character.
277 Str.erase(Str.begin()+i+1);
278 }
279 }
280}
281
Chris Lattner06c5eed2009-09-13 20:08:00 +0000282/// EmitPrintInstruction - Generate the code for the "printInstruction" method
Ahmed Bougachabd214002013-10-28 18:07:17 +0000283/// implementation. Destroys all instances of AsmWriterInst information, by
284/// clearing the Instructions vector.
Chris Lattner06c5eed2009-09-13 20:08:00 +0000285void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
Chris Lattner6ffa5012004-08-14 22:50:53 +0000286 Record *AsmWriter = Target.getAsmWriter();
Chris Lattner72770f52004-10-03 20:19:02 +0000287 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
Jim Grosbacha5497342010-09-29 22:32:50 +0000288
Chris Lattner1c4ae852004-08-01 05:59:33 +0000289 O <<
290 "/// printInstruction - This method is automatically generated by tablegen\n"
Chris Lattner06c5eed2009-09-13 20:08:00 +0000291 "/// from the instruction set description.\n"
Chris Lattnerb94284b2009-08-08 01:32:19 +0000292 "void " << Target.getName() << ClassName
Roman Divacky9dc6df52014-01-10 22:59:49 +0000293 << "::printInstruction(const MCInst *MI, raw_ostream &O) {\n";
Chris Lattner1c4ae852004-08-01 05:59:33 +0000294
Chris Lattnere32982c2006-07-14 22:59:11 +0000295 // Build an aggregate string, and build a table of offsets into it.
Benjamin Kramer22d093e2012-04-02 09:13:46 +0000296 SequenceToOffsetTable<std::string> StringTable;
Jim Grosbacha5497342010-09-29 22:32:50 +0000297
Chris Lattner5d751b42006-09-27 16:44:09 +0000298 /// OpcodeInfo - This encodes the index of the string to use for the first
Chris Lattner1ac0eb72006-07-18 17:32:27 +0000299 /// chunk of the output as well as indices used for operand printing.
Manman Ren68cf9fc2012-09-13 17:43:46 +0000300 /// To reduce the number of unhandled cases, we expand the size from 32-bit
301 /// to 32+16 = 48-bit.
Craig Topper06cec4c2012-09-14 08:33:11 +0000302 std::vector<uint64_t> OpcodeInfo;
Jim Grosbacha5497342010-09-29 22:32:50 +0000303
Benjamin Kramer22d093e2012-04-02 09:13:46 +0000304 // Add all strings to the string table upfront so it can generate an optimized
305 // representation.
Craig Topper4c6129a2014-02-05 07:56:49 +0000306 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
307 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions->at(i)];
Craig Topper24064772014-04-15 07:20:03 +0000308 if (AWI &&
Jim Grosbachf4e67082012-04-18 18:56:33 +0000309 AWI->Operands[0].OperandType ==
310 AsmWriterOperand::isLiteralTextOperand &&
Benjamin Kramer22d093e2012-04-02 09:13:46 +0000311 !AWI->Operands[0].Str.empty()) {
312 std::string Str = AWI->Operands[0].Str;
313 UnescapeString(Str);
314 StringTable.add(Str);
315 }
316 }
317
318 StringTable.layout();
319
Chris Lattner1ac0eb72006-07-18 17:32:27 +0000320 unsigned MaxStringIdx = 0;
Craig Topper4c6129a2014-02-05 07:56:49 +0000321 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
322 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions->at(i)];
Chris Lattnere32982c2006-07-14 22:59:11 +0000323 unsigned Idx;
Craig Topper24064772014-04-15 07:20:03 +0000324 if (!AWI) {
Chris Lattnere32982c2006-07-14 22:59:11 +0000325 // Something not handled by the asmwriter printer.
Chris Lattnerb47ed612009-09-14 01:16:36 +0000326 Idx = ~0U;
Jim Grosbacha5497342010-09-29 22:32:50 +0000327 } else if (AWI->Operands[0].OperandType !=
Chris Lattner36504652006-07-19 01:39:06 +0000328 AsmWriterOperand::isLiteralTextOperand ||
329 AWI->Operands[0].Str.empty()) {
330 // Something handled by the asmwriter printer, but with no leading string.
Benjamin Kramer22d093e2012-04-02 09:13:46 +0000331 Idx = StringTable.get("");
Chris Lattnere32982c2006-07-14 22:59:11 +0000332 } else {
Chris Lattnerb47ed612009-09-14 01:16:36 +0000333 std::string Str = AWI->Operands[0].Str;
334 UnescapeString(Str);
Benjamin Kramer22d093e2012-04-02 09:13:46 +0000335 Idx = StringTable.get(Str);
Chris Lattnerb47ed612009-09-14 01:16:36 +0000336 MaxStringIdx = std::max(MaxStringIdx, Idx);
Jim Grosbacha5497342010-09-29 22:32:50 +0000337
Chris Lattnere32982c2006-07-14 22:59:11 +0000338 // Nuke the string from the operand list. It is now handled!
339 AWI->Operands.erase(AWI->Operands.begin());
Chris Lattner92275bb2005-01-22 19:22:23 +0000340 }
Jim Grosbacha5497342010-09-29 22:32:50 +0000341
Chris Lattnerb47ed612009-09-14 01:16:36 +0000342 // Bias offset by one since we want 0 as a sentinel.
Craig Topper06cec4c2012-09-14 08:33:11 +0000343 OpcodeInfo.push_back(Idx+1);
Chris Lattner92275bb2005-01-22 19:22:23 +0000344 }
Jim Grosbacha5497342010-09-29 22:32:50 +0000345
Chris Lattner1ac0eb72006-07-18 17:32:27 +0000346 // Figure out how many bits we used for the string index.
Chris Lattnerb47ed612009-09-14 01:16:36 +0000347 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
Jim Grosbacha5497342010-09-29 22:32:50 +0000348
Chris Lattner692374c2006-07-18 17:18:03 +0000349 // To reduce code size, we compactify common instructions into a few bits
350 // in the opcode-indexed table.
Craig Topper06cec4c2012-09-14 08:33:11 +0000351 unsigned BitsLeft = 64-AsmStrBits;
Chris Lattner692374c2006-07-18 17:18:03 +0000352
353 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
Jim Grosbacha5497342010-09-29 22:32:50 +0000354
Chris Lattnercb0c8482006-07-18 17:56:07 +0000355 while (1) {
Chris Lattner692374c2006-07-18 17:18:03 +0000356 std::vector<std::string> UniqueOperandCommands;
Chris Lattner692374c2006-07-18 17:18:03 +0000357 std::vector<unsigned> InstIdxs;
Chris Lattneredee5252006-07-18 18:28:27 +0000358 std::vector<unsigned> NumInstOpsHandled;
359 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
360 NumInstOpsHandled);
Jim Grosbacha5497342010-09-29 22:32:50 +0000361
Chris Lattner692374c2006-07-18 17:18:03 +0000362 // If we ran out of operands to print, we're done.
363 if (UniqueOperandCommands.empty()) break;
Jim Grosbacha5497342010-09-29 22:32:50 +0000364
Chris Lattner692374c2006-07-18 17:18:03 +0000365 // 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());
Jim Grosbacha5497342010-09-29 22:32:50 +0000368
Chris Lattner692374c2006-07-18 17:18:03 +0000369 // If we don't have enough bits for this operand, don't include it.
370 if (NumBits > BitsLeft) {
Chris Lattner34822f62009-08-23 04:44:11 +0000371 DEBUG(errs() << "Not enough bits to densely encode " << NumBits
372 << " more bits\n");
Chris Lattner692374c2006-07-18 17:18:03 +0000373 break;
374 }
Jim Grosbacha5497342010-09-29 22:32:50 +0000375
Chris Lattner692374c2006-07-18 17:18:03 +0000376 // Otherwise, we can include this in the initial lookup table. Add it in.
Chris Lattner692374c2006-07-18 17:18:03 +0000377 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
Manman Ren68cf9fc2012-09-13 17:43:46 +0000378 if (InstIdxs[i] != ~0U) {
Craig Topper06cec4c2012-09-14 08:33:11 +0000379 OpcodeInfo[i] |= (uint64_t)InstIdxs[i] << (64-BitsLeft);
Manman Ren68cf9fc2012-09-13 17:43:46 +0000380 }
Craig Topper06cec4c2012-09-14 08:33:11 +0000381 BitsLeft -= NumBits;
Jim Grosbacha5497342010-09-29 22:32:50 +0000382
Chris Lattnercb0c8482006-07-18 17:56:07 +0000383 // Remove the info about this operand.
Craig Topper4c6129a2014-02-05 07:56:49 +0000384 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
Chris Lattnercb0c8482006-07-18 17:56:07 +0000385 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
Chris Lattneredee5252006-07-18 18:28:27 +0000386 if (!Inst->Operands.empty()) {
387 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
Chris Lattner6e172082006-07-18 19:06:01 +0000388 assert(NumOps <= Inst->Operands.size() &&
389 "Can't remove this many ops!");
Chris Lattneredee5252006-07-18 18:28:27 +0000390 Inst->Operands.erase(Inst->Operands.begin(),
391 Inst->Operands.begin()+NumOps);
392 }
Chris Lattnercb0c8482006-07-18 17:56:07 +0000393 }
Jim Grosbacha5497342010-09-29 22:32:50 +0000394
Chris Lattnercb0c8482006-07-18 17:56:07 +0000395 // Remember the handlers for this set of operands.
Chris Lattner692374c2006-07-18 17:18:03 +0000396 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
397 }
Jim Grosbacha5497342010-09-29 22:32:50 +0000398
399
Craig Topper06cec4c2012-09-14 08:33:11 +0000400 // 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";
Craig Topper4c6129a2014-02-05 07:56:49 +0000403 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
Craig Topper06cec4c2012-09-14 08:33:11 +0000404 O << " " << (OpcodeInfo[i] & 0xffffffff) << "U,\t// "
Craig Topper4c6129a2014-02-05 07:56:49 +0000405 << NumberedInstructions->at(i)->TheDef->getName() << "\n";
Chris Lattner692374c2006-07-18 17:18:03 +0000406 }
407 // Add a dummy entry so the array init doesn't end with a comma.
Chris Lattner1ac0eb72006-07-18 17:32:27 +0000408 O << " 0U\n";
Chris Lattnere32982c2006-07-14 22:59:11 +0000409 O << " };\n\n";
Jim Grosbacha5497342010-09-29 22:32:50 +0000410
Craig Topper06cec4c2012-09-14 08:33:11 +0000411 if (BitsLeft < 32) {
Manman Ren68cf9fc2012-09-13 17:43:46 +0000412 // Add a second OpInfo table only when it is necessary.
Craig Topper06cec4c2012-09-14 08:33:11 +0000413 // 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";
Craig Topper4c6129a2014-02-05 07:56:49 +0000417 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
Craig Topper06cec4c2012-09-14 08:33:11 +0000418 O << " " << (OpcodeInfo[i] >> 32) << "U,\t// "
Craig Topper4c6129a2014-02-05 07:56:49 +0000419 << NumberedInstructions->at(i)->TheDef->getName() << "\n";
Manman Ren68cf9fc2012-09-13 17:43:46 +0000420 }
421 // Add a dummy entry so the array init doesn't end with a comma.
422 O << " 0U\n";
423 O << " };\n\n";
424 }
425
Chris Lattnere32982c2006-07-14 22:59:11 +0000426 // Emit the string itself.
Benjamin Kramer22d093e2012-04-02 09:13:46 +0000427 O << " const char AsmStrs[] = {\n";
428 StringTable.emit(O, printChar);
429 O << " };\n\n";
Chris Lattnere32982c2006-07-14 22:59:11 +0000430
Evan Cheng32e53472008-02-02 08:39:46 +0000431 O << " O << \"\\t\";\n\n";
432
Craig Topper06cec4c2012-09-14 08:33:11 +0000433 O << " // Emit the opcode for the instruction.\n";
434 if (BitsLeft < 32) {
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";
440 } else {
441 // If only one table is used we just need to perform a single lookup.
442 O << " uint32_t Bits = OpInfo[MI->getOpcode()];\n";
443 }
Manman Ren68cf9fc2012-09-13 17:43:46 +0000444 O << " assert(Bits != 0 && \"Cannot print this instruction.\");\n"
Chris Lattnerb47ed612009-09-14 01:16:36 +0000445 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
David Greenefdd25192009-08-05 21:00:52 +0000446
Chris Lattner692374c2006-07-18 17:18:03 +0000447 // Output the table driven operand information.
Craig Topper06cec4c2012-09-14 08:33:11 +0000448 BitsLeft = 64-AsmStrBits;
Chris Lattner692374c2006-07-18 17:18:03 +0000449 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
450 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
451
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");
Jim Grosbacha5497342010-09-29 22:32:50 +0000456
Chris Lattner692374c2006-07-18 17:18:03 +0000457 // Emit code to extract this field from Bits.
Chris Lattner692374c2006-07-18 17:18:03 +0000458 O << "\n // Fragment " << i << " encoded into " << NumBits
Chris Lattner75dcf6c2006-07-18 17:43:54 +0000459 << " bits for " << Commands.size() << " unique commands.\n";
Jim Grosbacha5497342010-09-29 22:32:50 +0000460
Chris Lattneredee5252006-07-18 18:28:27 +0000461 if (Commands.size() == 2) {
Chris Lattner75dcf6c2006-07-18 17:43:54 +0000462 // Emit two possibilitys with if/else.
Craig Topper06cec4c2012-09-14 08:33:11 +0000463 O << " if ((Bits >> "
464 << (64-BitsLeft) << ") & "
Chris Lattner75dcf6c2006-07-18 17:43:54 +0000465 << ((1 << NumBits)-1) << ") {\n"
466 << Commands[1]
467 << " } else {\n"
468 << Commands[0]
469 << " }\n\n";
Eric Christophera573d192010-09-18 18:50:27 +0000470 } else if (Commands.size() == 1) {
471 // Emit a single possibility.
472 O << Commands[0] << "\n\n";
Chris Lattner75dcf6c2006-07-18 17:43:54 +0000473 } else {
Craig Topper06cec4c2012-09-14 08:33:11 +0000474 O << " switch ((Bits >> "
475 << (64-BitsLeft) << ") & "
Chris Lattner75dcf6c2006-07-18 17:43:54 +0000476 << ((1 << NumBits)-1) << ") {\n"
477 << " default: // unreachable.\n";
Jim Grosbacha5497342010-09-29 22:32:50 +0000478
Chris Lattner75dcf6c2006-07-18 17:43:54 +0000479 // Print out all the cases.
480 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
481 O << " case " << i << ":\n";
482 O << Commands[i];
483 O << " break;\n";
484 }
485 O << " }\n\n";
Chris Lattner692374c2006-07-18 17:18:03 +0000486 }
Craig Topper06cec4c2012-09-14 08:33:11 +0000487 BitsLeft -= NumBits;
Chris Lattner692374c2006-07-18 17:18:03 +0000488 }
Jim Grosbacha5497342010-09-29 22:32:50 +0000489
Chris Lattnercb0c8482006-07-18 17:56:07 +0000490 // Okay, delete instructions with no operand info left.
Chris Lattner692374c2006-07-18 17:18:03 +0000491 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
492 // Entire instruction has been emitted?
493 AsmWriterInst &Inst = Instructions[i];
Chris Lattnercb0c8482006-07-18 17:56:07 +0000494 if (Inst.Operands.empty()) {
Chris Lattner692374c2006-07-18 17:18:03 +0000495 Instructions.erase(Instructions.begin()+i);
Chris Lattnercb0c8482006-07-18 17:56:07 +0000496 --i; --e;
Chris Lattner692374c2006-07-18 17:18:03 +0000497 }
498 }
499
Jim Grosbacha5497342010-09-29 22:32:50 +0000500
Chris Lattner692374c2006-07-18 17:18:03 +0000501 // Because this is a vector, we want to emit from the end. Reverse all of the
Chris Lattner9ceb7c82005-01-22 18:38:13 +0000502 // elements in the vector.
503 std::reverse(Instructions.begin(), Instructions.end());
Jim Grosbacha5497342010-09-29 22:32:50 +0000504
505
Chris Lattnerbf1a7692009-09-18 18:10:19 +0000506 // 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
509 // instructions.
Chris Lattner66e288b2006-07-18 17:38:46 +0000510 if (!Instructions.empty()) {
511 // Find the opcode # of inline asm.
512 O << " switch (MI->getOpcode()) {\n";
513 while (!Instructions.empty())
514 EmitInstructions(Instructions, O);
Chris Lattner9ceb7c82005-01-22 18:38:13 +0000515
Chris Lattner66e288b2006-07-18 17:38:46 +0000516 O << " }\n";
Chris Lattnerb94284b2009-08-08 01:32:19 +0000517 O << " return;\n";
Chris Lattner66e288b2006-07-18 17:38:46 +0000518 }
David Greene5b4bc262009-07-29 20:10:24 +0000519
Chris Lattner6e172082006-07-18 19:06:01 +0000520 O << "}\n";
Chris Lattner1c4ae852004-08-01 05:59:33 +0000521}
Chris Lattner06c5eed2009-09-13 20:08:00 +0000522
Owen Andersona84be6c2011-06-27 21:06:21 +0000523static void
524emitRegisterNameString(raw_ostream &O, StringRef AltName,
Craig Topper9c252eb2012-04-03 06:52:47 +0000525 const std::vector<CodeGenRegister*> &Registers) {
Jakob Stoklund Olesen892f4802012-03-30 21:12:52 +0000526 SequenceToOffsetTable<std::string> StringTable;
527 SmallVector<std::string, 4> AsmNames(Registers.size());
Owen Andersona84be6c2011-06-27 21:06:21 +0000528 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
529 const CodeGenRegister &Reg = *Registers[i];
Jakob Stoklund Olesen892f4802012-03-30 21:12:52 +0000530 std::string &AsmName = AsmNames[i];
Owen Andersona84be6c2011-06-27 21:06:21 +0000531
Owen Andersona84be6c2011-06-27 21:06:21 +0000532 // "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");
536 if (AsmName.empty())
537 AsmName = Reg.getName();
538 } else {
539 // Make sure the register has an alternate name for this index.
540 std::vector<Record*> AltNameList =
541 Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
542 unsigned Idx = 0, e;
543 for (e = AltNameList.size();
544 Idx < e && (AltNameList[Idx]->getName() != AltName);
545 ++Idx)
546 ;
547 // If the register has an alternate name for this index, use it.
548 // Otherwise, leave it empty as an error flag.
549 if (Idx < e) {
550 std::vector<std::string> AltNames =
551 Reg.TheDef->getValueAsListOfStrings("AltNames");
552 if (AltNames.size() <= Idx)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000553 PrintFatalError(Reg.TheDef->getLoc(),
Benjamin Kramer48e7e852014-03-29 17:17:15 +0000554 "Register definition missing alt name for '" +
555 AltName + "'.");
Owen Andersona84be6c2011-06-27 21:06:21 +0000556 AsmName = AltNames[Idx];
557 }
558 }
Jakob Stoklund Olesen892f4802012-03-30 21:12:52 +0000559 StringTable.add(AsmName);
560 }
Owen Andersona84be6c2011-06-27 21:06:21 +0000561
Craig Topperf8f0a232012-09-15 01:22:42 +0000562 StringTable.layout();
Jakob Stoklund Olesen892f4802012-03-30 21:12:52 +0000563 O << " static const char AsmStrs" << AltName << "[] = {\n";
564 StringTable.emit(O, printChar);
565 O << " };\n\n";
566
Craig Topperf8f0a232012-09-15 01:22:42 +0000567 O << " static const uint32_t RegAsmOffset" << AltName << "[] = {";
Jakob Stoklund Olesen892f4802012-03-30 21:12:52 +0000568 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
Craig Topper7a2cea12012-04-02 00:47:39 +0000569 if ((i % 14) == 0)
570 O << "\n ";
571 O << StringTable.get(AsmNames[i]) << ", ";
Owen Andersona84be6c2011-06-27 21:06:21 +0000572 }
Craig Topper9c252eb2012-04-03 06:52:47 +0000573 O << "\n };\n"
Owen Andersona84be6c2011-06-27 21:06:21 +0000574 << "\n";
Owen Andersona84be6c2011-06-27 21:06:21 +0000575}
Chris Lattner06c5eed2009-09-13 20:08:00 +0000576
577void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
Chris Lattner06c5eed2009-09-13 20:08:00 +0000578 Record *AsmWriter = Target.getAsmWriter();
579 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
Jakob Stoklund Olesen8e188be2011-06-18 04:26:06 +0000580 const std::vector<CodeGenRegister*> &Registers =
581 Target.getRegBank().getRegisters();
Owen Andersona84be6c2011-06-27 21:06:21 +0000582 std::vector<Record*> AltNameIndices = Target.getRegAltNameIndices();
583 bool hasAltNames = AltNameIndices.size() > 1;
Jim Grosbacha5497342010-09-29 22:32:50 +0000584
Chris Lattner06c5eed2009-09-13 20:08:00 +0000585 O <<
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"
Owen Andersona84be6c2011-06-27 21:06:21 +0000589 "const char *" << Target.getName() << ClassName << "::";
590 if (hasAltNames)
591 O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
592 else
593 O << "getRegisterName(unsigned RegNo) {\n";
594 O << " assert(RegNo && RegNo < " << (Registers.size()+1)
595 << " && \"Invalid register number!\");\n"
Chris Lattnera7e8ae42009-09-14 01:26:18 +0000596 << "\n";
Jim Grosbacha5497342010-09-29 22:32:50 +0000597
Owen Andersona84be6c2011-06-27 21:06:21 +0000598 if (hasAltNames) {
599 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i)
600 emitRegisterNameString(O, AltNameIndices[i]->getName(), Registers);
601 } else
602 emitRegisterNameString(O, "", Registers);
Jim Grosbacha5497342010-09-29 22:32:50 +0000603
Owen Andersona84be6c2011-06-27 21:06:21 +0000604 if (hasAltNames) {
Craig Topperf8f0a232012-09-15 01:22:42 +0000605 O << " const uint32_t *RegAsmOffset;\n"
Owen Andersona84be6c2011-06-27 21:06:21 +0000606 << " const char *AsmStrs;\n"
607 << " switch(AltIdx) {\n"
Craig Topperc4965bc2012-02-05 07:21:30 +0000608 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n";
Owen Andersona84be6c2011-06-27 21:06:21 +0000609 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i) {
Tim Northover4e55afe2014-03-29 16:59:27 +0000610 std::string Namespace = AltNameIndices[1]->getValueAsString("Namespace");
611 std::string AltName(AltNameIndices[i]->getName());
Owen Andersona84be6c2011-06-27 21:06:21 +0000612 O << " case " << Namespace << "::" << AltName
613 << ":\n"
614 << " AsmStrs = AsmStrs" << AltName << ";\n"
615 << " RegAsmOffset = RegAsmOffset" << AltName << ";\n"
616 << " break;\n";
617 }
618 O << "}\n";
619 }
620
621 O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
622 << " \"Invalid alt name index for register!\");\n"
623 << " return AsmStrs+RegAsmOffset[RegNo-1];\n"
Chris Lattner06c5eed2009-09-13 20:08:00 +0000624 << "}\n";
625}
626
Bill Wendling7e5771d2011-03-21 08:31:53 +0000627namespace {
Bill Wendling5d3174c2011-03-21 08:40:31 +0000628// 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.
631class IAPrinter {
Bill Wendling5d3174c2011-03-21 08:40:31 +0000632 std::vector<std::string> Conds;
Tim Northoveree20caa2014-05-12 18:04:06 +0000633 std::map<StringRef, std::pair<int, int>> OpMap;
634 SmallVector<Record*, 4> ReqFeatures;
635
Bill Wendling5d3174c2011-03-21 08:40:31 +0000636 std::string Result;
637 std::string AsmString;
Bill Wendling5d3174c2011-03-21 08:40:31 +0000638public:
Tim Northoveree20caa2014-05-12 18:04:06 +0000639 IAPrinter(std::string R, std::string AS) : Result(R), AsmString(AS) {}
Bill Wendling5d3174c2011-03-21 08:40:31 +0000640
641 void addCond(const std::string &C) { Conds.push_back(C); }
Bill Wendling5d3174c2011-03-21 08:40:31 +0000642
Tim Northoveree20caa2014-05-12 18:04:06 +0000643 void addOperand(StringRef Op, int OpIdx, int PrintMethodIdx = -1) {
644 assert(OpIdx >= 0 && OpIdx < 0xFE && "Idx out of range");
Tim Northover0ee9e7e2014-05-13 09:37:41 +0000645 assert(PrintMethodIdx >= -1 && PrintMethodIdx < 0xFF &&
Jay Foadb3590512014-05-13 08:26:53 +0000646 "Idx out of range");
Tim Northoveree20caa2014-05-12 18:04:06 +0000647 OpMap[Op] = std::make_pair(OpIdx, PrintMethodIdx);
Benjamin Kramer17c17bc2013-09-11 15:42:16 +0000648 }
Tim Northoveree20caa2014-05-12 18:04:06 +0000649
Bill Wendling5d3174c2011-03-21 08:40:31 +0000650 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
Tim Northoveree20caa2014-05-12 18:04:06 +0000651 int getOpIndex(StringRef Op) { return OpMap[Op].first; }
652 std::pair<int, int> &getOpData(StringRef Op) { return OpMap[Op]; }
Bill Wendling5d3174c2011-03-21 08:40:31 +0000653
Evan Cheng4d806e22011-07-06 02:02:33 +0000654 void print(raw_ostream &O) {
Bill Wendlingbc3f7902011-04-07 21:20:06 +0000655 if (Conds.empty() && ReqFeatures.empty()) {
656 O.indent(6) << "return true;\n";
Evan Cheng4d806e22011-07-06 02:02:33 +0000657 return;
Bill Wendlingbc3f7902011-04-07 21:20:06 +0000658 }
Bill Wendling7e570b52011-03-21 08:59:17 +0000659
Bill Wendlingbc3f7902011-04-07 21:20:06 +0000660 O << "if (";
Bill Wendling5d3174c2011-03-21 08:40:31 +0000661
662 for (std::vector<std::string>::iterator
663 I = Conds.begin(), E = Conds.end(); I != E; ++I) {
664 if (I != Conds.begin()) {
665 O << " &&\n";
Bill Wendlingbc3f7902011-04-07 21:20:06 +0000666 O.indent(8);
Bill Wendling5d3174c2011-03-21 08:40:31 +0000667 }
Bill Wendling7e570b52011-03-21 08:59:17 +0000668
Bill Wendling5d3174c2011-03-21 08:40:31 +0000669 O << *I;
670 }
671
Bill Wendlingbc3f7902011-04-07 21:20:06 +0000672 O << ") {\n";
673 O.indent(6) << "// " << Result << "\n";
Bill Wendling5d3174c2011-03-21 08:40:31 +0000674
Benjamin Kramer17c17bc2013-09-11 15:42:16 +0000675 // Directly mangle mapped operands into the string. Each operand is
676 // identified by a '$' sign followed by a byte identifying the number of the
677 // operand. We add one to the index to avoid zero bytes.
678 std::pair<StringRef, StringRef> ASM = StringRef(AsmString).split(' ');
679 SmallString<128> OutString = ASM.first;
680 if (!ASM.second.empty()) {
681 raw_svector_ostream OS(OutString);
682 OS << ' ';
683 for (StringRef::iterator I = ASM.second.begin(), E = ASM.second.end();
684 I != E;) {
685 OS << *I;
686 if (*I == '$') {
687 StringRef::iterator Start = ++I;
688 while (I != E &&
689 ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') ||
690 (*I >= '0' && *I <= '9') || *I == '_'))
691 ++I;
692 StringRef Name(Start, I - Start);
693 assert(isOpMapped(Name) && "Unmapped operand!");
Tim Northoveree20caa2014-05-12 18:04:06 +0000694
695 int OpIndex, PrintIndex;
696 std::tie(OpIndex, PrintIndex) = getOpData(Name);
697 if (PrintIndex == -1) {
698 // Can use the default printOperand route.
699 OS << format("\\x%02X", (unsigned char)OpIndex + 1);
700 } else
701 // 3 bytes if a PrintMethod is needed: 0xFF, the MCInst operand
702 // number, and which of our pre-detected Methods to call.
703 OS << format("\\xFF\\x%02X\\x%02X", OpIndex + 1, PrintIndex + 1);
Benjamin Kramer17c17bc2013-09-11 15:42:16 +0000704 } else {
705 ++I;
706 }
707 }
708 }
709
710 // Emit the string.
711 O.indent(6) << "AsmString = \"" << OutString.str() << "\";\n";
Bill Wendling5d3174c2011-03-21 08:40:31 +0000712
Bill Wendlingbc3f7902011-04-07 21:20:06 +0000713 O.indent(6) << "break;\n";
714 O.indent(4) << '}';
Bill Wendling5d3174c2011-03-21 08:40:31 +0000715 }
716
717 bool operator==(const IAPrinter &RHS) {
718 if (Conds.size() != RHS.Conds.size())
719 return false;
720
721 unsigned Idx = 0;
722 for (std::vector<std::string>::iterator
723 I = Conds.begin(), E = Conds.end(); I != E; ++I)
724 if (*I != RHS.Conds[Idx++])
725 return false;
726
727 return true;
728 }
Bill Wendling5d3174c2011-03-21 08:40:31 +0000729};
730
Bill Wendling7e5771d2011-03-21 08:31:53 +0000731} // end anonymous namespace
732
Bill Wendlinge7124492011-06-14 03:17:20 +0000733static unsigned CountNumOperands(StringRef AsmString) {
734 unsigned NumOps = 0;
735 std::pair<StringRef, StringRef> ASM = AsmString.split(' ');
736
737 while (!ASM.second.empty()) {
738 ++NumOps;
739 ASM = ASM.second.split(' ');
740 }
741
742 return NumOps;
743}
744
Bill Wendling36c0c6d2011-06-15 04:31:19 +0000745static unsigned CountResultNumOperands(StringRef AsmString) {
746 unsigned NumOps = 0;
747 std::pair<StringRef, StringRef> ASM = AsmString.split('\t');
748
749 if (!ASM.second.empty()) {
750 size_t I = ASM.second.find('{');
751 StringRef Str = ASM.second;
752 if (I != StringRef::npos)
753 Str = ASM.second.substr(I, ASM.second.find('|', I));
754
755 ASM = Str.split(' ');
756
757 do {
758 ++NumOps;
759 ASM = ASM.second.split(' ');
760 } while (!ASM.second.empty());
761 }
762
763 return NumOps;
764}
Bill Wendlinge7124492011-06-14 03:17:20 +0000765
Bill Wendling7e5771d2011-03-21 08:31:53 +0000766void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
Bill Wendling7e5771d2011-03-21 08:31:53 +0000767 Record *AsmWriter = Target.getAsmWriter();
768
769 O << "\n#ifdef PRINT_ALIAS_INSTR\n";
770 O << "#undef PRINT_ALIAS_INSTR\n\n";
771
Tim Northoveree20caa2014-05-12 18:04:06 +0000772 //////////////////////////////
773 // Gather information about aliases we need to print
774 //////////////////////////////
775
Bill Wendling31ca7ef2011-02-26 03:09:12 +0000776 // Emit the method that prints the alias instruction.
777 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
778
Bill Wendling31ca7ef2011-02-26 03:09:12 +0000779 std::vector<Record*> AllInstAliases =
780 Records.getAllDerivedDefinitions("InstAlias");
781
782 // Create a map from the qualified name to a list of potential matches.
Jim Grosbachefe653f2012-04-18 20:24:49 +0000783 std::map<std::string, std::vector<CodeGenInstAlias*> > AliasMap;
Bill Wendling31ca7ef2011-02-26 03:09:12 +0000784 for (std::vector<Record*>::iterator
785 I = AllInstAliases.begin(), E = AllInstAliases.end(); I != E; ++I) {
786 CodeGenInstAlias *Alias = new CodeGenInstAlias(*I, Target);
787 const Record *R = *I;
Bill Wendling6dd69d92011-04-13 23:36:21 +0000788 if (!R->getValueAsBit("EmitAlias"))
789 continue; // We were told not to emit the alias, but to emit the aliasee.
Bill Wendling31ca7ef2011-02-26 03:09:12 +0000790 const DagInit *DI = R->getValueAsDag("ResultInst");
Sean Silva88eb8dd2012-10-10 20:24:47 +0000791 const DefInit *Op = cast<DefInit>(DI->getOperator());
Bill Wendling31ca7ef2011-02-26 03:09:12 +0000792 AliasMap[getQualifiedName(Op->getDef())].push_back(Alias);
793 }
794
Bill Wendling7e570b52011-03-21 08:59:17 +0000795 // A map of which conditions need to be met for each instruction operand
796 // before it can be matched to the mnemonic.
Jim Grosbachefe653f2012-04-18 20:24:49 +0000797 std::map<std::string, std::vector<IAPrinter*> > IAPrinterMap;
Bill Wendling7e570b52011-03-21 08:59:17 +0000798
Jim Grosbachefe653f2012-04-18 20:24:49 +0000799 for (std::map<std::string, std::vector<CodeGenInstAlias*> >::iterator
Bill Wendling7e570b52011-03-21 08:59:17 +0000800 I = AliasMap.begin(), E = AliasMap.end(); I != E; ++I) {
801 std::vector<CodeGenInstAlias*> &Aliases = I->second;
802
803 for (std::vector<CodeGenInstAlias*>::iterator
804 II = Aliases.begin(), IE = Aliases.end(); II != IE; ++II) {
805 const CodeGenInstAlias *CGA = *II;
Bill Wendlinge7124492011-06-14 03:17:20 +0000806 unsigned LastOpNo = CGA->ResultInstOperandIndex.size();
Bill Wendling36c0c6d2011-06-15 04:31:19 +0000807 unsigned NumResultOps =
808 CountResultNumOperands(CGA->ResultInst->AsmString);
Bill Wendlinge7124492011-06-14 03:17:20 +0000809
810 // Don't emit the alias if it has more operands than what it's aliasing.
Bill Wendling36c0c6d2011-06-15 04:31:19 +0000811 if (NumResultOps < CountNumOperands(CGA->AsmString))
Bill Wendlinge7124492011-06-14 03:17:20 +0000812 continue;
813
Evan Cheng4d806e22011-07-06 02:02:33 +0000814 IAPrinter *IAP = new IAPrinter(CGA->Result->getAsString(),
Bill Wendling7e570b52011-03-21 08:59:17 +0000815 CGA->AsmString);
Bill Wendling7e570b52011-03-21 08:59:17 +0000816
Bill Wendling7e570b52011-03-21 08:59:17 +0000817 std::string Cond;
818 Cond = std::string("MI->getNumOperands() == ") + llvm::utostr(LastOpNo);
819 IAP->addCond(Cond);
820
Bill Wendling7e570b52011-03-21 08:59:17 +0000821 bool CantHandle = false;
822
823 for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
824 const CodeGenInstAlias::ResultOperand &RO = CGA->ResultOperands[i];
825
826 switch (RO.Kind) {
Bill Wendling7e570b52011-03-21 08:59:17 +0000827 case CodeGenInstAlias::ResultOperand::K_Record: {
828 const Record *Rec = RO.getRecord();
829 StringRef ROName = RO.getName();
Tim Northoveree20caa2014-05-12 18:04:06 +0000830 int PrintMethodIdx = -1;
Bill Wendling7e570b52011-03-21 08:59:17 +0000831
Tim Northoveree20caa2014-05-12 18:04:06 +0000832 // These two may have a PrintMethod, which we want to record (if it's
833 // the first time we've seen it) and provide an index for the aliasing
834 // code to use.
835 if (Rec->isSubClassOf("RegisterOperand") ||
836 Rec->isSubClassOf("Operand")) {
837 std::string PrintMethod = Rec->getValueAsString("PrintMethod");
838 if (PrintMethod != "" && PrintMethod != "printOperand") {
839 PrintMethodIdx = std::find(PrintMethods.begin(),
840 PrintMethods.end(), PrintMethod) -
841 PrintMethods.begin();
842 if (static_cast<unsigned>(PrintMethodIdx) == PrintMethods.size())
843 PrintMethods.push_back(PrintMethod);
844 }
845 }
Owen Andersona84be6c2011-06-27 21:06:21 +0000846
847 if (Rec->isSubClassOf("RegisterOperand"))
848 Rec = Rec->getValueAsDef("RegClass");
Bill Wendling7e570b52011-03-21 08:59:17 +0000849 if (Rec->isSubClassOf("RegisterClass")) {
850 Cond = std::string("MI->getOperand(")+llvm::utostr(i)+").isReg()";
851 IAP->addCond(Cond);
852
853 if (!IAP->isOpMapped(ROName)) {
Tim Northoveree20caa2014-05-12 18:04:06 +0000854 IAP->addOperand(ROName, i, PrintMethodIdx);
Jack Carter9c1a0272013-02-05 08:32:10 +0000855 Record *R = CGA->ResultOperands[i].getRecord();
856 if (R->isSubClassOf("RegisterOperand"))
857 R = R->getValueAsDef("RegClass");
Benjamin Kramer682de392012-03-30 23:13:40 +0000858 Cond = std::string("MRI.getRegClass(") + Target.getName() + "::" +
Jack Carter9c1a0272013-02-05 08:32:10 +0000859 R->getName() + "RegClassID)"
Benjamin Kramer682de392012-03-30 23:13:40 +0000860 ".contains(MI->getOperand(" + llvm::utostr(i) + ").getReg())";
Bill Wendling7e570b52011-03-21 08:59:17 +0000861 IAP->addCond(Cond);
862 } else {
863 Cond = std::string("MI->getOperand(") +
864 llvm::utostr(i) + ").getReg() == MI->getOperand(" +
865 llvm::utostr(IAP->getOpIndex(ROName)) + ").getReg()";
866 IAP->addCond(Cond);
867 }
868 } else {
Tim Northoveree20caa2014-05-12 18:04:06 +0000869 // Assume all printable operands are desired for now. This can be
Alp Tokerbeaca192014-05-15 01:52:21 +0000870 // overridden in the InstAlias instantiation if necessary.
Tim Northoveree20caa2014-05-12 18:04:06 +0000871 IAP->addOperand(ROName, i, PrintMethodIdx);
Bill Wendling7e570b52011-03-21 08:59:17 +0000872 }
873
874 break;
875 }
Tim Northoverab7689e2013-01-09 13:32:04 +0000876 case CodeGenInstAlias::ResultOperand::K_Imm: {
877 std::string Op = "MI->getOperand(" + llvm::utostr(i) + ")";
878
879 // Just because the alias has an immediate result, doesn't mean the
880 // MCInst will. An MCExpr could be present, for example.
881 IAP->addCond(Op + ".isImm()");
882
883 Cond = Op + ".getImm() == "
884 + llvm::utostr(CGA->ResultOperands[i].getImm());
Bill Wendling7e570b52011-03-21 08:59:17 +0000885 IAP->addCond(Cond);
886 break;
Tim Northoverab7689e2013-01-09 13:32:04 +0000887 }
Bill Wendling7e570b52011-03-21 08:59:17 +0000888 case CodeGenInstAlias::ResultOperand::K_Reg:
Jim Grosbach29cdcda2011-11-15 01:46:57 +0000889 // If this is zero_reg, something's playing tricks we're not
890 // equipped to handle.
891 if (!CGA->ResultOperands[i].getRegister()) {
892 CantHandle = true;
893 break;
894 }
895
Bill Wendling7e570b52011-03-21 08:59:17 +0000896 Cond = std::string("MI->getOperand(") +
897 llvm::utostr(i) + ").getReg() == " + Target.getName() +
898 "::" + CGA->ResultOperands[i].getRegister()->getName();
899 IAP->addCond(Cond);
900 break;
901 }
902
903 if (!IAP) break;
904 }
905
906 if (CantHandle) continue;
Jim Grosbachefe653f2012-04-18 20:24:49 +0000907 IAPrinterMap[I->first].push_back(IAP);
Bill Wendling7e570b52011-03-21 08:59:17 +0000908 }
909 }
910
Tim Northoveree20caa2014-05-12 18:04:06 +0000911 //////////////////////////////
912 // Write out the printAliasInstr function
913 //////////////////////////////
914
Bill Wendlingf5199de2011-05-23 00:18:33 +0000915 std::string Header;
916 raw_string_ostream HeaderO(Header);
917
918 HeaderO << "bool " << Target.getName() << ClassName
Bill Wendlinge7124492011-06-14 03:17:20 +0000919 << "::printAliasInstr(const MCInst"
Bill Wendlingf5199de2011-05-23 00:18:33 +0000920 << " *MI, raw_ostream &OS) {\n";
Bill Wendling7e570b52011-03-21 08:59:17 +0000921
Bill Wendlingbc3f7902011-04-07 21:20:06 +0000922 std::string Cases;
923 raw_string_ostream CasesO(Cases);
924
Jim Grosbachefe653f2012-04-18 20:24:49 +0000925 for (std::map<std::string, std::vector<IAPrinter*> >::iterator
Bill Wendlingbc3f7902011-04-07 21:20:06 +0000926 I = IAPrinterMap.begin(), E = IAPrinterMap.end(); I != E; ++I) {
927 std::vector<IAPrinter*> &IAPs = I->second;
928 std::vector<IAPrinter*> UniqueIAPs;
929
930 for (std::vector<IAPrinter*>::iterator
931 II = IAPs.begin(), IE = IAPs.end(); II != IE; ++II) {
932 IAPrinter *LHS = *II;
933 bool IsDup = false;
934 for (std::vector<IAPrinter*>::iterator
935 III = IAPs.begin(), IIE = IAPs.end(); III != IIE; ++III) {
936 IAPrinter *RHS = *III;
937 if (LHS != RHS && *LHS == *RHS) {
938 IsDup = true;
939 break;
940 }
941 }
942
943 if (!IsDup) UniqueIAPs.push_back(LHS);
944 }
945
946 if (UniqueIAPs.empty()) continue;
947
Jim Grosbachefe653f2012-04-18 20:24:49 +0000948 CasesO.indent(2) << "case " << I->first << ":\n";
Bill Wendlingbc3f7902011-04-07 21:20:06 +0000949
950 for (std::vector<IAPrinter*>::iterator
951 II = UniqueIAPs.begin(), IE = UniqueIAPs.end(); II != IE; ++II) {
952 IAPrinter *IAP = *II;
953 CasesO.indent(4);
Evan Cheng4d806e22011-07-06 02:02:33 +0000954 IAP->print(CasesO);
Bill Wendlingbc3f7902011-04-07 21:20:06 +0000955 CasesO << '\n';
956 }
957
Eric Christopher2e3fbaa2011-04-18 21:28:11 +0000958 CasesO.indent(4) << "return false;\n";
Bill Wendlingbc3f7902011-04-07 21:20:06 +0000959 }
960
Bill Wendlinge7124492011-06-14 03:17:20 +0000961 if (CasesO.str().empty()) {
Bill Wendlingf5199de2011-05-23 00:18:33 +0000962 O << HeaderO.str();
Eric Christopher2e3fbaa2011-04-18 21:28:11 +0000963 O << " return false;\n";
Bill Wendling31ca7ef2011-02-26 03:09:12 +0000964 O << "}\n\n";
965 O << "#endif // PRINT_ALIAS_INSTR\n";
966 return;
967 }
968
Bill Wendlingf5199de2011-05-23 00:18:33 +0000969 O << HeaderO.str();
Benjamin Kramer17c17bc2013-09-11 15:42:16 +0000970 O.indent(2) << "const char *AsmString;\n";
Bill Wendlingbc3f7902011-04-07 21:20:06 +0000971 O.indent(2) << "switch (MI->getOpcode()) {\n";
Eric Christopher2e3fbaa2011-04-18 21:28:11 +0000972 O.indent(2) << "default: return false;\n";
Bill Wendlingbc3f7902011-04-07 21:20:06 +0000973 O << CasesO.str();
974 O.indent(2) << "}\n\n";
Bill Wendling31ca7ef2011-02-26 03:09:12 +0000975
976 // Code that prints the alias, replacing the operands with the ones from the
977 // MCInst.
Benjamin Kramer17c17bc2013-09-11 15:42:16 +0000978 O << " unsigned I = 0;\n";
979 O << " while (AsmString[I] != ' ' && AsmString[I] != '\\0')\n";
980 O << " ++I;\n";
981 O << " OS << '\\t' << StringRef(AsmString, I);\n";
Bill Wendling31ca7ef2011-02-26 03:09:12 +0000982
Benjamin Kramer17c17bc2013-09-11 15:42:16 +0000983 O << " if (AsmString[I] != '\\0') {\n";
Bill Wendling31ca7ef2011-02-26 03:09:12 +0000984 O << " OS << '\\t';\n";
Benjamin Kramer17c17bc2013-09-11 15:42:16 +0000985 O << " do {\n";
986 O << " if (AsmString[I] == '$') {\n";
987 O << " ++I;\n";
Tim Northoveree20caa2014-05-12 18:04:06 +0000988 O << " if (AsmString[I] == (char)0xff) {\n";
989 O << " ++I;\n";
990 O << " int OpIdx = AsmString[I++] - 1;\n";
991 O << " int PrintMethodIdx = AsmString[I++] - 1;\n";
992 O << " printCustomAliasOperand(MI, OpIdx, PrintMethodIdx, OS);\n";
993 O << " } else\n";
994 O << " printOperand(MI, unsigned(AsmString[I++]) - 1, OS);\n";
Bill Wendling31ca7ef2011-02-26 03:09:12 +0000995 O << " } else {\n";
Benjamin Kramer17c17bc2013-09-11 15:42:16 +0000996 O << " OS << AsmString[I++];\n";
Bill Wendling31ca7ef2011-02-26 03:09:12 +0000997 O << " }\n";
Benjamin Kramer17c17bc2013-09-11 15:42:16 +0000998 O << " } while (AsmString[I] != '\\0');\n";
Bill Wendling31ca7ef2011-02-26 03:09:12 +0000999 O << " }\n\n";
Jim Grosbachf4e67082012-04-18 18:56:33 +00001000
Eric Christopher2e3fbaa2011-04-18 21:28:11 +00001001 O << " return true;\n";
Bill Wendling31ca7ef2011-02-26 03:09:12 +00001002 O << "}\n\n";
1003
Tim Northoveree20caa2014-05-12 18:04:06 +00001004 //////////////////////////////
1005 // Write out the printCustomAliasOperand function
1006 //////////////////////////////
1007
1008 O << "void " << Target.getName() << ClassName << "::"
1009 << "printCustomAliasOperand(\n"
1010 << " const MCInst *MI, unsigned OpIdx,\n"
Aaron Ballmane58a5702014-05-13 12:52:35 +00001011 << " unsigned PrintMethodIdx, raw_ostream &OS) {\n";
1012 if (PrintMethods.empty())
1013 O << " llvm_unreachable(\"Unknown PrintMethod kind\");\n";
1014 else {
1015 O << " switch (PrintMethodIdx) {\n"
1016 << " default:\n"
1017 << " llvm_unreachable(\"Unknown PrintMethod kind\");\n"
Tim Northoveree20caa2014-05-12 18:04:06 +00001018 << " break;\n";
Tim Northoveree20caa2014-05-12 18:04:06 +00001019
Aaron Ballmane58a5702014-05-13 12:52:35 +00001020 for (unsigned i = 0; i < PrintMethods.size(); ++i) {
1021 O << " case " << i << ":\n"
1022 << " " << PrintMethods[i] << "(MI, OpIdx, OS);\n"
1023 << " break;\n";
1024 }
1025 O << " }\n";
1026 }
1027 O << "}\n\n";
Tim Northoveree20caa2014-05-12 18:04:06 +00001028
Bill Wendling31ca7ef2011-02-26 03:09:12 +00001029 O << "#endif // PRINT_ALIAS_INSTR\n";
1030}
Chris Lattner06c5eed2009-09-13 20:08:00 +00001031
Ahmed Bougachabd214002013-10-28 18:07:17 +00001032AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) {
1033 Record *AsmWriter = Target.getAsmWriter();
1034 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
1035 E = Target.inst_end();
1036 I != E; ++I)
1037 if (!(*I)->AsmString.empty() && (*I)->TheDef->getName() != "PHI")
1038 Instructions.push_back(
1039 AsmWriterInst(**I, AsmWriter->getValueAsInt("Variant"),
Ahmed Bougachabd214002013-10-28 18:07:17 +00001040 AsmWriter->getValueAsInt("OperandSpacing")));
1041
1042 // Get the instruction numbering.
Craig Topper4c6129a2014-02-05 07:56:49 +00001043 NumberedInstructions = &Target.getInstructionsByEnumValue();
Ahmed Bougachabd214002013-10-28 18:07:17 +00001044
1045 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
1046 // all machine instructions are necessarily being printed, so there may be
1047 // target instructions not in this map.
1048 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
1049 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
1050}
1051
Chris Lattner06c5eed2009-09-13 20:08:00 +00001052void AsmWriterEmitter::run(raw_ostream &O) {
Chris Lattner06c5eed2009-09-13 20:08:00 +00001053 EmitPrintInstruction(O);
1054 EmitGetRegisterName(O);
Bill Wendling31ca7ef2011-02-26 03:09:12 +00001055 EmitPrintAliasInstruction(O);
Chris Lattner06c5eed2009-09-13 20:08:00 +00001056}
1057
Jakob Stoklund Olesene6aed132012-06-11 15:37:55 +00001058
1059namespace llvm {
1060
1061void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
1062 emitSourceFileHeader("Assembly Writer Source Fragment", OS);
1063 AsmWriterEmitter(RK).run(OS);
1064}
1065
1066} // End llvm namespace