blob: 7f9d4061f9b5b9b30cadfcf3d1bd0e563629e711 [file] [log] [blame]
Chris Lattner2e1f51b2004-08-01 05:59:33 +00001//===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
Chris Lattner2e1f51b2004-08-01 05:59:33 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner30609102007-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 Brukman3da94ae2005-04-22 00:00:37 +00007//
Chris Lattner2e1f51b2004-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 Callanand32c02f2010-02-09 21:50:41 +000015#include "AsmWriterInst.h"
Chris Lattner2e1f51b2004-08-01 05:59:33 +000016#include "CodeGenTarget.h"
Jakob Stoklund Olesenc19f72b2012-03-30 21:12:52 +000017#include "SequenceToOffsetTable.h"
Craig Topperf5535872012-07-27 06:44:02 +000018#include "llvm/ADT/StringExtras.h"
Owen Andersonbea6f612011-06-27 21:06:21 +000019#include "llvm/ADT/Twine.h"
Chris Lattnerbdff5f92006-07-18 17:18:03 +000020#include "llvm/Support/Debug.h"
21#include "llvm/Support/MathExtras.h"
Peter Collingbourne7c788882011-10-01 16:41:13 +000022#include "llvm/TableGen/Error.h"
23#include "llvm/TableGen/Record.h"
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +000024#include "llvm/TableGen/TableGenBackend.h"
Jeff Cohen615ed992005-01-22 18:50:10 +000025#include <algorithm>
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +000026#include <cassert>
27#include <map>
28#include <vector>
Chris Lattner2e1f51b2004-08-01 05:59:33 +000029using namespace llvm;
30
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +000031namespace {
32class AsmWriterEmitter {
33 RecordKeeper &Records;
34 std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
35 std::vector<const CodeGenInstruction*> NumberedInstructions;
36public:
37 AsmWriterEmitter(RecordKeeper &R) : Records(R) {}
38
39 void run(raw_ostream &o);
40
41private:
42 void EmitPrintInstruction(raw_ostream &o);
43 void EmitGetRegisterName(raw_ostream &o);
44 void EmitPrintAliasInstruction(raw_ostream &O);
45
46 AsmWriterInst *getAsmWriterInstByID(unsigned ID) const {
47 assert(ID < NumberedInstructions.size());
48 std::map<const CodeGenInstruction*, AsmWriterInst*>::const_iterator I =
49 CGIAWIMap.find(NumberedInstructions[ID]);
50 assert(I != CGIAWIMap.end() && "Didn't find inst!");
51 return I->second;
52 }
53 void FindUniqueOperandCommands(std::vector<std::string> &UOC,
54 std::vector<unsigned> &InstIdxs,
55 std::vector<unsigned> &InstOpsUsed) const;
56};
57} // end anonymous namespace
58
Chris Lattner38c07512005-01-22 20:31:17 +000059static void PrintCases(std::vector<std::pair<std::string,
Daniel Dunbar1a551802009-07-03 00:10:29 +000060 AsmWriterOperand> > &OpsToPrint, raw_ostream &O) {
Chris Lattner38c07512005-01-22 20:31:17 +000061 O << " case " << OpsToPrint.back().first << ": ";
62 AsmWriterOperand TheOp = OpsToPrint.back().second;
63 OpsToPrint.pop_back();
64
65 // Check to see if any other operands are identical in this list, and if so,
66 // emit a case label for them.
67 for (unsigned i = OpsToPrint.size(); i != 0; --i)
68 if (OpsToPrint[i-1].second == TheOp) {
69 O << "\n case " << OpsToPrint[i-1].first << ": ";
70 OpsToPrint.erase(OpsToPrint.begin()+i-1);
71 }
72
73 // Finally, emit the code.
Chris Lattnerbdff5f92006-07-18 17:18:03 +000074 O << TheOp.getCode();
Chris Lattner38c07512005-01-22 20:31:17 +000075 O << "break;\n";
76}
77
Chris Lattner870c0162005-01-22 18:38:13 +000078
79/// EmitInstructions - Emit the last instruction in the vector and any other
80/// instructions that are suitably similar to it.
81static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
Daniel Dunbar1a551802009-07-03 00:10:29 +000082 raw_ostream &O) {
Chris Lattner870c0162005-01-22 18:38:13 +000083 AsmWriterInst FirstInst = Insts.back();
84 Insts.pop_back();
85
86 std::vector<AsmWriterInst> SimilarInsts;
87 unsigned DifferingOperand = ~0;
88 for (unsigned i = Insts.size(); i != 0; --i) {
Chris Lattnerf8766682005-01-22 19:22:23 +000089 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
90 if (DiffOp != ~1U) {
Chris Lattner870c0162005-01-22 18:38:13 +000091 if (DifferingOperand == ~0U) // First match!
92 DifferingOperand = DiffOp;
93
94 // If this differs in the same operand as the rest of the instructions in
95 // this class, move it to the SimilarInsts list.
Chris Lattnerf8766682005-01-22 19:22:23 +000096 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
Chris Lattner870c0162005-01-22 18:38:13 +000097 SimilarInsts.push_back(Insts[i-1]);
98 Insts.erase(Insts.begin()+i-1);
99 }
100 }
101 }
102
Chris Lattnera1e8a802006-05-01 17:01:17 +0000103 O << " case " << FirstInst.CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000104 << FirstInst.CGI->TheDef->getName() << ":\n";
105 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
Chris Lattnera1e8a802006-05-01 17:01:17 +0000106 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000107 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
108 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
109 if (i != DifferingOperand) {
110 // If the operand is the same for all instructions, just print it.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000111 O << " " << FirstInst.Operands[i].getCode();
Chris Lattner870c0162005-01-22 18:38:13 +0000112 } else {
113 // If this is the operand that varies between all of the instructions,
114 // emit a switch for just this operand now.
115 O << " switch (MI->getOpcode()) {\n";
Chris Lattner38c07512005-01-22 20:31:17 +0000116 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
Chris Lattnera1e8a802006-05-01 17:01:17 +0000117 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
Chris Lattner38c07512005-01-22 20:31:17 +0000118 FirstInst.CGI->TheDef->getName(),
119 FirstInst.Operands[i]));
Misha Brukman3da94ae2005-04-22 00:00:37 +0000120
Chris Lattner870c0162005-01-22 18:38:13 +0000121 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
Chris Lattner38c07512005-01-22 20:31:17 +0000122 AsmWriterInst &AWI = SimilarInsts[si];
Chris Lattnera1e8a802006-05-01 17:01:17 +0000123 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
Chris Lattner38c07512005-01-22 20:31:17 +0000124 AWI.CGI->TheDef->getName(),
125 AWI.Operands[i]));
Chris Lattner870c0162005-01-22 18:38:13 +0000126 }
Chris Lattner38c07512005-01-22 20:31:17 +0000127 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
128 while (!OpsToPrint.empty())
129 PrintCases(OpsToPrint, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000130 O << " }";
131 }
132 O << "\n";
133 }
Chris Lattner870c0162005-01-22 18:38:13 +0000134 O << " break;\n";
135}
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000136
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000137void AsmWriterEmitter::
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000138FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
Chris Lattner96c1ade2006-07-18 18:28:27 +0000139 std::vector<unsigned> &InstIdxs,
140 std::vector<unsigned> &InstOpsUsed) const {
Chris Lattner195bb4a2006-07-18 19:27:30 +0000141 InstIdxs.assign(NumberedInstructions.size(), ~0U);
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000142
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000143 // This vector parallels UniqueOperandCommands, keeping track of which
144 // instructions each case are used for. It is a comma separated string of
145 // enums.
146 std::vector<std::string> InstrsForCase;
147 InstrsForCase.resize(UniqueOperandCommands.size());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000148 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000149
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000150 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
151 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
Bill Wendlingb9449d62010-07-16 23:10:00 +0000152 if (Inst == 0) continue; // PHI, INLINEASM, PROLOG_LABEL, etc.
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000153
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000154 std::string Command;
Chris Lattnerb8462862006-07-18 17:56:07 +0000155 if (Inst->Operands.empty())
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000156 continue; // Instruction already done.
Chris Lattner191dd1f2006-07-18 17:50:22 +0000157
Chris Lattnerb8462862006-07-18 17:56:07 +0000158 Command = " " + Inst->Operands[0].getCode() + "\n";
Chris Lattner191dd1f2006-07-18 17:50:22 +0000159
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000160 // Check to see if we already have 'Command' in UniqueOperandCommands.
161 // If not, add it.
162 bool FoundIt = false;
163 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
164 if (UniqueOperandCommands[idx] == Command) {
165 InstIdxs[i] = idx;
166 InstrsForCase[idx] += ", ";
167 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
168 FoundIt = true;
169 break;
170 }
171 if (!FoundIt) {
172 InstIdxs[i] = UniqueOperandCommands.size();
173 UniqueOperandCommands.push_back(Command);
174 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000175
176 // This command matches one operand so far.
177 InstOpsUsed.push_back(1);
178 }
179 }
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000180
Chris Lattner96c1ade2006-07-18 18:28:27 +0000181 // For each entry of UniqueOperandCommands, there is a set of instructions
182 // that uses it. If the next command of all instructions in the set are
183 // identical, fold it into the command.
184 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
185 CommandIdx != e; ++CommandIdx) {
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000186
Chris Lattner96c1ade2006-07-18 18:28:27 +0000187 for (unsigned Op = 1; ; ++Op) {
188 // Scan for the first instruction in the set.
189 std::vector<unsigned>::iterator NIT =
190 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
191 if (NIT == InstIdxs.end()) break; // No commonality.
192
193 // If this instruction has no more operands, we isn't anything to merge
194 // into this command.
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000195 const AsmWriterInst *FirstInst =
Chris Lattner96c1ade2006-07-18 18:28:27 +0000196 getAsmWriterInstByID(NIT-InstIdxs.begin());
197 if (!FirstInst || FirstInst->Operands.size() == Op)
198 break;
199
200 // Otherwise, scan to see if all of the other instructions in this command
201 // set share the operand.
202 bool AllSame = true;
David Greenec8d06052009-07-29 20:10:24 +0000203 // Keep track of the maximum, number of operands or any
204 // instruction we see in the group.
205 size_t MaxSize = FirstInst->Operands.size();
206
Chris Lattner96c1ade2006-07-18 18:28:27 +0000207 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
208 NIT != InstIdxs.end();
209 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
210 // Okay, found another instruction in this command set. If the operand
211 // matches, we're ok, otherwise bail out.
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000212 const AsmWriterInst *OtherInst =
Chris Lattner96c1ade2006-07-18 18:28:27 +0000213 getAsmWriterInstByID(NIT-InstIdxs.begin());
David Greenec8d06052009-07-29 20:10:24 +0000214
215 if (OtherInst &&
216 OtherInst->Operands.size() > FirstInst->Operands.size())
217 MaxSize = std::max(MaxSize, OtherInst->Operands.size());
218
Chris Lattner96c1ade2006-07-18 18:28:27 +0000219 if (!OtherInst || OtherInst->Operands.size() == Op ||
220 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
221 AllSame = false;
222 break;
223 }
224 }
225 if (!AllSame) break;
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000226
Chris Lattner96c1ade2006-07-18 18:28:27 +0000227 // Okay, everything in this command set has the same next operand. Add it
228 // to UniqueOperandCommands and remember that it was consumed.
229 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000230
Chris Lattner96c1ade2006-07-18 18:28:27 +0000231 UniqueOperandCommands[CommandIdx] += Command;
232 InstOpsUsed[CommandIdx]++;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000233 }
234 }
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000235
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000236 // Prepend some of the instructions each case is used for onto the case val.
237 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
238 std::string Instrs = InstrsForCase[i];
239 if (Instrs.size() > 70) {
240 Instrs.erase(Instrs.begin()+70, Instrs.end());
241 Instrs += "...";
242 }
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000243
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000244 if (!Instrs.empty())
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000245 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000246 UniqueOperandCommands[i];
247 }
248}
249
250
Daniel Dunbar9bd34602009-10-17 20:43:42 +0000251static void UnescapeString(std::string &Str) {
252 for (unsigned i = 0; i != Str.size(); ++i) {
253 if (Str[i] == '\\' && i != Str.size()-1) {
254 switch (Str[i+1]) {
255 default: continue; // Don't execute the code after the switch.
256 case 'a': Str[i] = '\a'; break;
257 case 'b': Str[i] = '\b'; break;
258 case 'e': Str[i] = 27; break;
259 case 'f': Str[i] = '\f'; break;
260 case 'n': Str[i] = '\n'; break;
261 case 'r': Str[i] = '\r'; break;
262 case 't': Str[i] = '\t'; break;
263 case 'v': Str[i] = '\v'; break;
264 case '"': Str[i] = '\"'; break;
265 case '\'': Str[i] = '\''; break;
266 case '\\': Str[i] = '\\'; break;
267 }
268 // Nuke the second character.
269 Str.erase(Str.begin()+i+1);
270 }
271 }
272}
273
Chris Lattner05af2612009-09-13 20:08:00 +0000274/// EmitPrintInstruction - Generate the code for the "printInstruction" method
275/// implementation.
276void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
Chris Lattner67db8832010-12-13 00:23:57 +0000277 CodeGenTarget Target(Records);
Chris Lattner175580c2004-08-14 22:50:53 +0000278 Record *AsmWriter = Target.getAsmWriter();
Chris Lattner953c6fe2004-10-03 20:19:02 +0000279 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
Jim Grosbachca96a862010-09-30 01:29:54 +0000280 bool isMC = AsmWriter->getValueAsBit("isMCAsmWriter");
281 const char *MachineInstrClassName = isMC ? "MCInst" : "MachineInstr";
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000282
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000283 O <<
284 "/// printInstruction - This method is automatically generated by tablegen\n"
Chris Lattner05af2612009-09-13 20:08:00 +0000285 "/// from the instruction set description.\n"
Chris Lattner41aefdc2009-08-08 01:32:19 +0000286 "void " << Target.getName() << ClassName
Jim Grosbachca96a862010-09-30 01:29:54 +0000287 << "::printInstruction(const " << MachineInstrClassName
288 << " *MI, raw_ostream &O) {\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000289
Chris Lattner5765dba2005-01-22 17:40:38 +0000290 std::vector<AsmWriterInst> Instructions;
291
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000292 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
293 E = Target.inst_end(); I != E; ++I)
Chris Lattner6a91b182010-03-19 01:00:55 +0000294 if (!(*I)->AsmString.empty() &&
295 (*I)->TheDef->getName() != "PHI")
Sean Callanand0bc7f02010-02-09 23:06:35 +0000296 Instructions.push_back(
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000297 AsmWriterInst(**I,
Sean Callanand0bc7f02010-02-09 23:06:35 +0000298 AsmWriter->getValueAsInt("Variant"),
299 AsmWriter->getValueAsInt("FirstOperandColumn"),
300 AsmWriter->getValueAsInt("OperandSpacing")));
Chris Lattner076efa72004-08-01 07:43:02 +0000301
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000302 // Get the instruction numbering.
Chris Lattnerf6502782010-03-19 00:34:35 +0000303 NumberedInstructions = Target.getInstructionsByEnumValue();
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000304
Chris Lattner6af022f2006-07-14 22:59:11 +0000305 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
306 // all machine instructions are necessarily being printed, so there may be
307 // target instructions not in this map.
Chris Lattner6af022f2006-07-14 22:59:11 +0000308 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
309 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
Chris Lattnerf8766682005-01-22 19:22:23 +0000310
Chris Lattner6af022f2006-07-14 22:59:11 +0000311 // Build an aggregate string, and build a table of offsets into it.
Benjamin Kramer94338592012-04-02 09:13:46 +0000312 SequenceToOffsetTable<std::string> StringTable;
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000313
Chris Lattner259bda42006-09-27 16:44:09 +0000314 /// OpcodeInfo - This encodes the index of the string to use for the first
Chris Lattner55616402006-07-18 17:32:27 +0000315 /// chunk of the output as well as indices used for operand printing.
Manman Ren6579cf82012-09-13 17:43:46 +0000316 /// To reduce the number of unhandled cases, we expand the size from 32-bit
317 /// to 32+16 = 48-bit.
318 std::vector<std::pair<unsigned, uint16_t> > OpcodeInfo;
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000319
Benjamin Kramer94338592012-04-02 09:13:46 +0000320 // Add all strings to the string table upfront so it can generate an optimized
321 // representation.
322 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
323 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
324 if (AWI != 0 &&
Jim Grosbach016c6792012-04-18 18:56:33 +0000325 AWI->Operands[0].OperandType ==
326 AsmWriterOperand::isLiteralTextOperand &&
Benjamin Kramer94338592012-04-02 09:13:46 +0000327 !AWI->Operands[0].Str.empty()) {
328 std::string Str = AWI->Operands[0].Str;
329 UnescapeString(Str);
330 StringTable.add(Str);
331 }
332 }
333
334 StringTable.layout();
335
Chris Lattner55616402006-07-18 17:32:27 +0000336 unsigned MaxStringIdx = 0;
Chris Lattner6af022f2006-07-14 22:59:11 +0000337 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
338 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
339 unsigned Idx;
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000340 if (AWI == 0) {
Chris Lattner6af022f2006-07-14 22:59:11 +0000341 // Something not handled by the asmwriter printer.
Chris Lattner3200fc92009-09-14 01:16:36 +0000342 Idx = ~0U;
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000343 } else if (AWI->Operands[0].OperandType !=
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000344 AsmWriterOperand::isLiteralTextOperand ||
345 AWI->Operands[0].Str.empty()) {
346 // Something handled by the asmwriter printer, but with no leading string.
Benjamin Kramer94338592012-04-02 09:13:46 +0000347 Idx = StringTable.get("");
Chris Lattner6af022f2006-07-14 22:59:11 +0000348 } else {
Chris Lattner3200fc92009-09-14 01:16:36 +0000349 std::string Str = AWI->Operands[0].Str;
350 UnescapeString(Str);
Benjamin Kramer94338592012-04-02 09:13:46 +0000351 Idx = StringTable.get(Str);
Chris Lattner3200fc92009-09-14 01:16:36 +0000352 MaxStringIdx = std::max(MaxStringIdx, Idx);
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000353
Chris Lattner6af022f2006-07-14 22:59:11 +0000354 // Nuke the string from the operand list. It is now handled!
355 AWI->Operands.erase(AWI->Operands.begin());
Chris Lattnerf8766682005-01-22 19:22:23 +0000356 }
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000357
Chris Lattner3200fc92009-09-14 01:16:36 +0000358 // Bias offset by one since we want 0 as a sentinel.
Manman Ren6579cf82012-09-13 17:43:46 +0000359 OpcodeInfo.push_back(std::make_pair(Idx+1, 0));
Chris Lattnerf8766682005-01-22 19:22:23 +0000360 }
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000361
Chris Lattner55616402006-07-18 17:32:27 +0000362 // Figure out how many bits we used for the string index.
Chris Lattner3200fc92009-09-14 01:16:36 +0000363 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000364
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000365 // To reduce code size, we compactify common instructions into a few bits
366 // in the opcode-indexed table.
Manman Ren6579cf82012-09-13 17:43:46 +0000367 unsigned BitsLeft = 32+16-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000368
369 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000370
Chris Lattnerb8462862006-07-18 17:56:07 +0000371 while (1) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000372 std::vector<std::string> UniqueOperandCommands;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000373 std::vector<unsigned> InstIdxs;
Chris Lattner96c1ade2006-07-18 18:28:27 +0000374 std::vector<unsigned> NumInstOpsHandled;
375 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
376 NumInstOpsHandled);
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000377
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000378 // If we ran out of operands to print, we're done.
379 if (UniqueOperandCommands.empty()) break;
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000380
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000381 // Compute the number of bits we need to represent these cases, this is
382 // ceil(log2(numentries)).
383 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000384
Manman Ren6579cf82012-09-13 17:43:46 +0000385 // Check whether these Bits will fit in the first 32 bits.
386 if (BitsLeft > 16 && NumBits > BitsLeft - 16)
387 // We don't have enough bits in the first 32 bits, and we skip the
388 // left-over bits.
389 BitsLeft = 16;
390 bool UseSecond = (BitsLeft <= 16);
391
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000392 // If we don't have enough bits for this operand, don't include it.
393 if (NumBits > BitsLeft) {
Chris Lattner569f1212009-08-23 04:44:11 +0000394 DEBUG(errs() << "Not enough bits to densely encode " << NumBits
395 << " more bits\n");
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000396 break;
397 }
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000398
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000399 // Otherwise, we can include this in the initial lookup table. Add it in.
400 BitsLeft -= NumBits;
401 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
Manman Ren6579cf82012-09-13 17:43:46 +0000402 // Update the first 32 bits or the second 16 bits.
403 if (InstIdxs[i] != ~0U) {
404 if (UseSecond)
405 OpcodeInfo[i].second |= InstIdxs[i] << BitsLeft;
406 else
407 OpcodeInfo[i].first |= InstIdxs[i] << (BitsLeft-16+AsmStrBits);
408 }
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000409
Chris Lattnerb8462862006-07-18 17:56:07 +0000410 // Remove the info about this operand.
411 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
412 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
Chris Lattner96c1ade2006-07-18 18:28:27 +0000413 if (!Inst->Operands.empty()) {
414 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
Chris Lattner0a012122006-07-18 19:06:01 +0000415 assert(NumOps <= Inst->Operands.size() &&
416 "Can't remove this many ops!");
Chris Lattner96c1ade2006-07-18 18:28:27 +0000417 Inst->Operands.erase(Inst->Operands.begin(),
418 Inst->Operands.begin()+NumOps);
419 }
Chris Lattnerb8462862006-07-18 17:56:07 +0000420 }
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000421
Chris Lattnerb8462862006-07-18 17:56:07 +0000422 // Remember the handlers for this set of operands.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000423 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
424 }
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000425
426
427
Chris Lattner55616402006-07-18 17:32:27 +0000428 O<<" static const unsigned OpInfo[] = {\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000429 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
Manman Ren6579cf82012-09-13 17:43:46 +0000430 O << " " << OpcodeInfo[i].first << "U,\t// "
Chris Lattner55616402006-07-18 17:32:27 +0000431 << NumberedInstructions[i]->TheDef->getName() << "\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000432 }
433 // Add a dummy entry so the array init doesn't end with a comma.
Chris Lattner55616402006-07-18 17:32:27 +0000434 O << " 0U\n";
Chris Lattner6af022f2006-07-14 22:59:11 +0000435 O << " };\n\n";
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000436
Manman Ren6579cf82012-09-13 17:43:46 +0000437 if (BitsLeft < 16) {
438 // Add a second OpInfo table only when it is necessary.
Manman Ren785a41d2012-09-13 20:47:48 +0000439 O<<" static const uint16_t OpInfo2[] = {\n";
Manman Ren6579cf82012-09-13 17:43:46 +0000440 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
441 O << " " << OpcodeInfo[i].second << "U,\t// "
442 << NumberedInstructions[i]->TheDef->getName() << "\n";
443 }
444 // Add a dummy entry so the array init doesn't end with a comma.
445 O << " 0U\n";
446 O << " };\n\n";
447 }
448
Chris Lattner6af022f2006-07-14 22:59:11 +0000449 // Emit the string itself.
Benjamin Kramer94338592012-04-02 09:13:46 +0000450 O << " const char AsmStrs[] = {\n";
451 StringTable.emit(O, printChar);
452 O << " };\n\n";
Chris Lattner6af022f2006-07-14 22:59:11 +0000453
Evan Cheng4eecdeb2008-02-02 08:39:46 +0000454 O << " O << \"\\t\";\n\n";
455
Chris Lattner6af022f2006-07-14 22:59:11 +0000456 O << " // Emit the opcode for the instruction.\n"
Manman Ren6579cf82012-09-13 17:43:46 +0000457 << " unsigned Bits = OpInfo[MI->getOpcode()];\n";
458 if (BitsLeft < 16)
459 O << " unsigned short Bits2 = OpInfo2[MI->getOpcode()];\n";
460 O << " assert(Bits != 0 && \"Cannot print this instruction.\");\n"
Chris Lattner3200fc92009-09-14 01:16:36 +0000461 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
David Greenea5bb59f2009-08-05 21:00:52 +0000462
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000463 // Output the table driven operand information.
Manman Ren6579cf82012-09-13 17:43:46 +0000464 BitsLeft = 32+16-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000465 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
466 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
467
468 // Compute the number of bits we need to represent these cases, this is
469 // ceil(log2(numentries)).
470 unsigned NumBits = Log2_32_Ceil(Commands.size());
471 assert(NumBits <= BitsLeft && "consistency error");
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000472
Manman Ren6579cf82012-09-13 17:43:46 +0000473 // Check whether these Bits will fit in the first 32 bits.
474 if (BitsLeft > 16 && NumBits > BitsLeft - 16)
475 BitsLeft = 16;
476 bool UseSecond = (BitsLeft <= 16);
477
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000478 // Emit code to extract this field from Bits.
479 BitsLeft -= NumBits;
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000480
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000481 O << "\n // Fragment " << i << " encoded into " << NumBits
Chris Lattnere7a589d2006-07-18 17:43:54 +0000482 << " bits for " << Commands.size() << " unique commands.\n";
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000483
Chris Lattner96c1ade2006-07-18 18:28:27 +0000484 if (Commands.size() == 2) {
Chris Lattnere7a589d2006-07-18 17:43:54 +0000485 // Emit two possibilitys with if/else.
Manman Ren6579cf82012-09-13 17:43:46 +0000486 O << (UseSecond ? " if ((Bits2 >> " : " if ((Bits >> ")
487 << (UseSecond ? BitsLeft : (BitsLeft-16+AsmStrBits)) << ") & "
Chris Lattnere7a589d2006-07-18 17:43:54 +0000488 << ((1 << NumBits)-1) << ") {\n"
489 << Commands[1]
490 << " } else {\n"
491 << Commands[0]
492 << " }\n\n";
Eric Christopher16870502010-09-18 18:50:27 +0000493 } else if (Commands.size() == 1) {
494 // Emit a single possibility.
495 O << Commands[0] << "\n\n";
Chris Lattnere7a589d2006-07-18 17:43:54 +0000496 } else {
Manman Ren6579cf82012-09-13 17:43:46 +0000497 O << (UseSecond ? " switch ((Bits2 >> " : " switch ((Bits >> ")
498 << (UseSecond ? BitsLeft : (BitsLeft-16+AsmStrBits)) << ") & "
Chris Lattnere7a589d2006-07-18 17:43:54 +0000499 << ((1 << NumBits)-1) << ") {\n"
500 << " default: // unreachable.\n";
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000501
Chris Lattnere7a589d2006-07-18 17:43:54 +0000502 // Print out all the cases.
503 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
504 O << " case " << i << ":\n";
505 O << Commands[i];
506 O << " break;\n";
507 }
508 O << " }\n\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000509 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000510 }
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000511
Chris Lattnerb8462862006-07-18 17:56:07 +0000512 // Okay, delete instructions with no operand info left.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000513 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
514 // Entire instruction has been emitted?
515 AsmWriterInst &Inst = Instructions[i];
Chris Lattnerb8462862006-07-18 17:56:07 +0000516 if (Inst.Operands.empty()) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000517 Instructions.erase(Instructions.begin()+i);
Chris Lattnerb8462862006-07-18 17:56:07 +0000518 --i; --e;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000519 }
520 }
521
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000522
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000523 // Because this is a vector, we want to emit from the end. Reverse all of the
Chris Lattner870c0162005-01-22 18:38:13 +0000524 // elements in the vector.
525 std::reverse(Instructions.begin(), Instructions.end());
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000526
527
Chris Lattner70067602009-09-18 18:10:19 +0000528 // Now that we've emitted all of the operand info that fit into 32 bits, emit
529 // information for those instructions that are left. This is a less dense
530 // encoding, but we expect the main 32-bit table to handle the majority of
531 // instructions.
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000532 if (!Instructions.empty()) {
533 // Find the opcode # of inline asm.
534 O << " switch (MI->getOpcode()) {\n";
535 while (!Instructions.empty())
536 EmitInstructions(Instructions, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000537
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000538 O << " }\n";
Chris Lattner41aefdc2009-08-08 01:32:19 +0000539 O << " return;\n";
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000540 }
David Greenec8d06052009-07-29 20:10:24 +0000541
Chris Lattner0a012122006-07-18 19:06:01 +0000542 O << "}\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000543}
Chris Lattner05af2612009-09-13 20:08:00 +0000544
Owen Andersonbea6f612011-06-27 21:06:21 +0000545static void
546emitRegisterNameString(raw_ostream &O, StringRef AltName,
Craig Topper9b1b25f2012-04-03 06:52:47 +0000547 const std::vector<CodeGenRegister*> &Registers) {
Jakob Stoklund Olesenc19f72b2012-03-30 21:12:52 +0000548 SequenceToOffsetTable<std::string> StringTable;
549 SmallVector<std::string, 4> AsmNames(Registers.size());
Owen Andersonbea6f612011-06-27 21:06:21 +0000550 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
551 const CodeGenRegister &Reg = *Registers[i];
Jakob Stoklund Olesenc19f72b2012-03-30 21:12:52 +0000552 std::string &AsmName = AsmNames[i];
Owen Andersonbea6f612011-06-27 21:06:21 +0000553
Owen Andersonbea6f612011-06-27 21:06:21 +0000554 // "NoRegAltName" is special. We don't need to do a lookup for that,
555 // as it's just a reference to the default register name.
556 if (AltName == "" || AltName == "NoRegAltName") {
557 AsmName = Reg.TheDef->getValueAsString("AsmName");
558 if (AsmName.empty())
559 AsmName = Reg.getName();
560 } else {
561 // Make sure the register has an alternate name for this index.
562 std::vector<Record*> AltNameList =
563 Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
564 unsigned Idx = 0, e;
565 for (e = AltNameList.size();
566 Idx < e && (AltNameList[Idx]->getName() != AltName);
567 ++Idx)
568 ;
569 // If the register has an alternate name for this index, use it.
570 // Otherwise, leave it empty as an error flag.
571 if (Idx < e) {
572 std::vector<std::string> AltNames =
573 Reg.TheDef->getValueAsListOfStrings("AltNames");
574 if (AltNames.size() <= Idx)
575 throw TGError(Reg.TheDef->getLoc(),
576 (Twine("Register definition missing alt name for '") +
577 AltName + "'.").str());
578 AsmName = AltNames[Idx];
579 }
580 }
Jakob Stoklund Olesenc19f72b2012-03-30 21:12:52 +0000581 StringTable.add(AsmName);
582 }
Owen Andersonbea6f612011-06-27 21:06:21 +0000583
Jakob Stoklund Olesenc19f72b2012-03-30 21:12:52 +0000584 StringTable.layout();
585 O << " static const char AsmStrs" << AltName << "[] = {\n";
586 StringTable.emit(O, printChar);
587 O << " };\n\n";
588
Craig Toppera4bd58b2012-04-02 00:47:39 +0000589 O << " static const unsigned RegAsmOffset" << AltName << "[] = {";
Jakob Stoklund Olesenc19f72b2012-03-30 21:12:52 +0000590 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
Craig Toppera4bd58b2012-04-02 00:47:39 +0000591 if ((i % 14) == 0)
592 O << "\n ";
593 O << StringTable.get(AsmNames[i]) << ", ";
Owen Andersonbea6f612011-06-27 21:06:21 +0000594 }
Craig Topper9b1b25f2012-04-03 06:52:47 +0000595 O << "\n };\n"
Owen Andersonbea6f612011-06-27 21:06:21 +0000596 << "\n";
Owen Andersonbea6f612011-06-27 21:06:21 +0000597}
Chris Lattner05af2612009-09-13 20:08:00 +0000598
599void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
Chris Lattner67db8832010-12-13 00:23:57 +0000600 CodeGenTarget Target(Records);
Chris Lattner05af2612009-09-13 20:08:00 +0000601 Record *AsmWriter = Target.getAsmWriter();
602 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +0000603 const std::vector<CodeGenRegister*> &Registers =
604 Target.getRegBank().getRegisters();
Owen Andersonbea6f612011-06-27 21:06:21 +0000605 std::vector<Record*> AltNameIndices = Target.getRegAltNameIndices();
606 bool hasAltNames = AltNameIndices.size() > 1;
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000607
Chris Lattner05af2612009-09-13 20:08:00 +0000608 O <<
609 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
610 "/// from the register set description. This returns the assembler name\n"
611 "/// for the specified register.\n"
Owen Andersonbea6f612011-06-27 21:06:21 +0000612 "const char *" << Target.getName() << ClassName << "::";
613 if (hasAltNames)
614 O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
615 else
616 O << "getRegisterName(unsigned RegNo) {\n";
617 O << " assert(RegNo && RegNo < " << (Registers.size()+1)
618 << " && \"Invalid register number!\");\n"
Chris Lattnerf6761be2009-09-14 01:26:18 +0000619 << "\n";
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000620
Owen Andersonbea6f612011-06-27 21:06:21 +0000621 if (hasAltNames) {
622 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i)
623 emitRegisterNameString(O, AltNameIndices[i]->getName(), Registers);
624 } else
625 emitRegisterNameString(O, "", Registers);
Jim Grosbach9255b8d2010-09-29 22:32:50 +0000626
Owen Andersonbea6f612011-06-27 21:06:21 +0000627 if (hasAltNames) {
Jakob Stoklund Olesend66b9a22012-03-15 18:05:54 +0000628 O << " const unsigned *RegAsmOffset;\n"
Owen Andersonbea6f612011-06-27 21:06:21 +0000629 << " const char *AsmStrs;\n"
630 << " switch(AltIdx) {\n"
Craig Topper655b8de2012-02-05 07:21:30 +0000631 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n";
Owen Andersonbea6f612011-06-27 21:06:21 +0000632 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i) {
633 StringRef Namespace = AltNameIndices[1]->getValueAsString("Namespace");
634 StringRef AltName(AltNameIndices[i]->getName());
635 O << " case " << Namespace << "::" << AltName
636 << ":\n"
637 << " AsmStrs = AsmStrs" << AltName << ";\n"
638 << " RegAsmOffset = RegAsmOffset" << AltName << ";\n"
639 << " break;\n";
640 }
641 O << "}\n";
642 }
643
644 O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
645 << " \"Invalid alt name index for register!\");\n"
646 << " return AsmStrs+RegAsmOffset[RegNo-1];\n"
Chris Lattner05af2612009-09-13 20:08:00 +0000647 << "}\n";
648}
649
Bill Wendling2cf6fc62011-03-21 08:31:53 +0000650namespace {
Bill Wendling4962e612011-03-21 08:40:31 +0000651// IAPrinter - Holds information about an InstAlias. Two InstAliases match if
652// they both have the same conditionals. In which case, we cannot print out the
653// alias for that pattern.
654class IAPrinter {
Bill Wendling4962e612011-03-21 08:40:31 +0000655 std::vector<std::string> Conds;
656 std::map<StringRef, unsigned> OpMap;
657 std::string Result;
658 std::string AsmString;
Jim Grosbacha5b06852012-04-18 19:02:43 +0000659 SmallVector<Record*, 4> ReqFeatures;
Bill Wendling4962e612011-03-21 08:40:31 +0000660public:
Evan Cheng68ae5b42011-07-06 02:02:33 +0000661 IAPrinter(std::string R, std::string AS)
662 : Result(R), AsmString(AS) {}
Bill Wendling4962e612011-03-21 08:40:31 +0000663
664 void addCond(const std::string &C) { Conds.push_back(C); }
Bill Wendling4962e612011-03-21 08:40:31 +0000665
666 void addOperand(StringRef Op, unsigned Idx) { OpMap[Op] = Idx; }
667 unsigned getOpIndex(StringRef Op) { return OpMap[Op]; }
668 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
669
Evan Cheng68ae5b42011-07-06 02:02:33 +0000670 void print(raw_ostream &O) {
Bill Wendling44dcfd32011-04-07 21:20:06 +0000671 if (Conds.empty() && ReqFeatures.empty()) {
672 O.indent(6) << "return true;\n";
Evan Cheng68ae5b42011-07-06 02:02:33 +0000673 return;
Bill Wendling44dcfd32011-04-07 21:20:06 +0000674 }
Bill Wendling3ce1b7d2011-03-21 08:59:17 +0000675
Bill Wendling44dcfd32011-04-07 21:20:06 +0000676 O << "if (";
Bill Wendling4962e612011-03-21 08:40:31 +0000677
678 for (std::vector<std::string>::iterator
679 I = Conds.begin(), E = Conds.end(); I != E; ++I) {
680 if (I != Conds.begin()) {
681 O << " &&\n";
Bill Wendling44dcfd32011-04-07 21:20:06 +0000682 O.indent(8);
Bill Wendling4962e612011-03-21 08:40:31 +0000683 }
Bill Wendling3ce1b7d2011-03-21 08:59:17 +0000684
Bill Wendling4962e612011-03-21 08:40:31 +0000685 O << *I;
686 }
687
Bill Wendling44dcfd32011-04-07 21:20:06 +0000688 O << ") {\n";
689 O.indent(6) << "// " << Result << "\n";
690 O.indent(6) << "AsmString = \"" << AsmString << "\";\n";
Bill Wendling4962e612011-03-21 08:40:31 +0000691
692 for (std::map<StringRef, unsigned>::iterator
693 I = OpMap.begin(), E = OpMap.end(); I != E; ++I)
Bill Wendlingf415d8b2011-05-23 00:18:33 +0000694 O.indent(6) << "OpMap.push_back(std::make_pair(\"" << I->first << "\", "
695 << I->second << "));\n";
Bill Wendling4962e612011-03-21 08:40:31 +0000696
Bill Wendling44dcfd32011-04-07 21:20:06 +0000697 O.indent(6) << "break;\n";
698 O.indent(4) << '}';
Bill Wendling4962e612011-03-21 08:40:31 +0000699 }
700
701 bool operator==(const IAPrinter &RHS) {
702 if (Conds.size() != RHS.Conds.size())
703 return false;
704
705 unsigned Idx = 0;
706 for (std::vector<std::string>::iterator
707 I = Conds.begin(), E = Conds.end(); I != E; ++I)
708 if (*I != RHS.Conds[Idx++])
709 return false;
710
711 return true;
712 }
713
714 bool operator()(const IAPrinter &RHS) {
715 if (Conds.size() < RHS.Conds.size())
716 return true;
717
718 unsigned Idx = 0;
719 for (std::vector<std::string>::iterator
720 I = Conds.begin(), E = Conds.end(); I != E; ++I)
721 if (*I != RHS.Conds[Idx++])
722 return *I < RHS.Conds[Idx++];
723
724 return false;
725 }
726};
727
Bill Wendling2cf6fc62011-03-21 08:31:53 +0000728} // end anonymous namespace
729
Bill Wendlingf415d8b2011-05-23 00:18:33 +0000730static void EmitGetMapOperandNumber(raw_ostream &O) {
731 O << "static unsigned getMapOperandNumber("
732 << "const SmallVectorImpl<std::pair<StringRef, unsigned> > &OpMap,\n";
733 O << " StringRef Name) {\n";
734 O << " for (SmallVectorImpl<std::pair<StringRef, unsigned> >::"
735 << "const_iterator\n";
736 O << " I = OpMap.begin(), E = OpMap.end(); I != E; ++I)\n";
737 O << " if (I->first == Name)\n";
738 O << " return I->second;\n";
Craig Topper58609b72012-04-04 04:55:46 +0000739 O << " llvm_unreachable(\"Operand not in map!\");\n";
Bill Wendlingf415d8b2011-05-23 00:18:33 +0000740 O << "}\n\n";
741}
742
Bill Wendling740e5b32011-06-14 03:17:20 +0000743static unsigned CountNumOperands(StringRef AsmString) {
744 unsigned NumOps = 0;
745 std::pair<StringRef, StringRef> ASM = AsmString.split(' ');
746
747 while (!ASM.second.empty()) {
748 ++NumOps;
749 ASM = ASM.second.split(' ');
750 }
751
752 return NumOps;
753}
754
Bill Wendling393c4042011-06-15 04:31:19 +0000755static unsigned CountResultNumOperands(StringRef AsmString) {
756 unsigned NumOps = 0;
757 std::pair<StringRef, StringRef> ASM = AsmString.split('\t');
758
759 if (!ASM.second.empty()) {
760 size_t I = ASM.second.find('{');
761 StringRef Str = ASM.second;
762 if (I != StringRef::npos)
763 Str = ASM.second.substr(I, ASM.second.find('|', I));
764
765 ASM = Str.split(' ');
766
767 do {
768 ++NumOps;
769 ASM = ASM.second.split(' ');
770 } while (!ASM.second.empty());
771 }
772
773 return NumOps;
774}
Bill Wendling740e5b32011-06-14 03:17:20 +0000775
Bill Wendling2cf6fc62011-03-21 08:31:53 +0000776void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
777 CodeGenTarget Target(Records);
778 Record *AsmWriter = Target.getAsmWriter();
779
Bill Wendling740e5b32011-06-14 03:17:20 +0000780 if (!AsmWriter->getValueAsBit("isMCAsmWriter"))
781 return;
782
Bill Wendling2cf6fc62011-03-21 08:31:53 +0000783 O << "\n#ifdef PRINT_ALIAS_INSTR\n";
784 O << "#undef PRINT_ALIAS_INSTR\n\n";
785
Bill Wendling7520e3a2011-02-26 03:09:12 +0000786 // Emit the method that prints the alias instruction.
787 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
788
Bill Wendling7520e3a2011-02-26 03:09:12 +0000789 std::vector<Record*> AllInstAliases =
790 Records.getAllDerivedDefinitions("InstAlias");
791
792 // Create a map from the qualified name to a list of potential matches.
Jim Grosbachb4b26f82012-04-18 20:24:49 +0000793 std::map<std::string, std::vector<CodeGenInstAlias*> > AliasMap;
Bill Wendling7520e3a2011-02-26 03:09:12 +0000794 for (std::vector<Record*>::iterator
795 I = AllInstAliases.begin(), E = AllInstAliases.end(); I != E; ++I) {
796 CodeGenInstAlias *Alias = new CodeGenInstAlias(*I, Target);
797 const Record *R = *I;
Bill Wendlingeef965f2011-04-13 23:36:21 +0000798 if (!R->getValueAsBit("EmitAlias"))
799 continue; // We were told not to emit the alias, but to emit the aliasee.
Bill Wendling7520e3a2011-02-26 03:09:12 +0000800 const DagInit *DI = R->getValueAsDag("ResultInst");
801 const DefInit *Op = dynamic_cast<const DefInit*>(DI->getOperator());
802 AliasMap[getQualifiedName(Op->getDef())].push_back(Alias);
803 }
804
Bill Wendling3ce1b7d2011-03-21 08:59:17 +0000805 // A map of which conditions need to be met for each instruction operand
806 // before it can be matched to the mnemonic.
Jim Grosbachb4b26f82012-04-18 20:24:49 +0000807 std::map<std::string, std::vector<IAPrinter*> > IAPrinterMap;
Bill Wendling3ce1b7d2011-03-21 08:59:17 +0000808
Jim Grosbachb4b26f82012-04-18 20:24:49 +0000809 for (std::map<std::string, std::vector<CodeGenInstAlias*> >::iterator
Bill Wendling3ce1b7d2011-03-21 08:59:17 +0000810 I = AliasMap.begin(), E = AliasMap.end(); I != E; ++I) {
811 std::vector<CodeGenInstAlias*> &Aliases = I->second;
812
813 for (std::vector<CodeGenInstAlias*>::iterator
814 II = Aliases.begin(), IE = Aliases.end(); II != IE; ++II) {
815 const CodeGenInstAlias *CGA = *II;
Bill Wendling740e5b32011-06-14 03:17:20 +0000816 unsigned LastOpNo = CGA->ResultInstOperandIndex.size();
Bill Wendling393c4042011-06-15 04:31:19 +0000817 unsigned NumResultOps =
818 CountResultNumOperands(CGA->ResultInst->AsmString);
Bill Wendling740e5b32011-06-14 03:17:20 +0000819
820 // Don't emit the alias if it has more operands than what it's aliasing.
Bill Wendling393c4042011-06-15 04:31:19 +0000821 if (NumResultOps < CountNumOperands(CGA->AsmString))
Bill Wendling740e5b32011-06-14 03:17:20 +0000822 continue;
823
Evan Cheng68ae5b42011-07-06 02:02:33 +0000824 IAPrinter *IAP = new IAPrinter(CGA->Result->getAsString(),
Bill Wendling3ce1b7d2011-03-21 08:59:17 +0000825 CGA->AsmString);
Bill Wendling3ce1b7d2011-03-21 08:59:17 +0000826
Bill Wendling3ce1b7d2011-03-21 08:59:17 +0000827 std::string Cond;
828 Cond = std::string("MI->getNumOperands() == ") + llvm::utostr(LastOpNo);
829 IAP->addCond(Cond);
830
831 std::map<StringRef, unsigned> OpMap;
832 bool CantHandle = false;
833
834 for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
835 const CodeGenInstAlias::ResultOperand &RO = CGA->ResultOperands[i];
836
837 switch (RO.Kind) {
Bill Wendling3ce1b7d2011-03-21 08:59:17 +0000838 case CodeGenInstAlias::ResultOperand::K_Record: {
839 const Record *Rec = RO.getRecord();
840 StringRef ROName = RO.getName();
841
Owen Andersonbea6f612011-06-27 21:06:21 +0000842
843 if (Rec->isSubClassOf("RegisterOperand"))
844 Rec = Rec->getValueAsDef("RegClass");
Bill Wendling3ce1b7d2011-03-21 08:59:17 +0000845 if (Rec->isSubClassOf("RegisterClass")) {
846 Cond = std::string("MI->getOperand(")+llvm::utostr(i)+").isReg()";
847 IAP->addCond(Cond);
848
849 if (!IAP->isOpMapped(ROName)) {
850 IAP->addOperand(ROName, i);
Benjamin Kramercef670a2012-03-30 23:13:40 +0000851 Cond = std::string("MRI.getRegClass(") + Target.getName() + "::" +
852 CGA->ResultOperands[i].getRecord()->getName() + "RegClassID)"
853 ".contains(MI->getOperand(" + llvm::utostr(i) + ").getReg())";
Bill Wendling3ce1b7d2011-03-21 08:59:17 +0000854 IAP->addCond(Cond);
855 } else {
856 Cond = std::string("MI->getOperand(") +
857 llvm::utostr(i) + ").getReg() == MI->getOperand(" +
858 llvm::utostr(IAP->getOpIndex(ROName)) + ").getReg()";
859 IAP->addCond(Cond);
860 }
861 } else {
862 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
Bill Wendling740e5b32011-06-14 03:17:20 +0000863 // FIXME: We may need to handle these situations.
Bill Wendling3ce1b7d2011-03-21 08:59:17 +0000864 delete IAP;
865 IAP = 0;
866 CantHandle = true;
867 break;
868 }
869
870 break;
871 }
872 case CodeGenInstAlias::ResultOperand::K_Imm:
873 Cond = std::string("MI->getOperand(") +
874 llvm::utostr(i) + ").getImm() == " +
875 llvm::utostr(CGA->ResultOperands[i].getImm());
876 IAP->addCond(Cond);
877 break;
878 case CodeGenInstAlias::ResultOperand::K_Reg:
Jim Grosbachbfc94292011-11-15 01:46:57 +0000879 // If this is zero_reg, something's playing tricks we're not
880 // equipped to handle.
881 if (!CGA->ResultOperands[i].getRegister()) {
882 CantHandle = true;
883 break;
884 }
885
Bill Wendling3ce1b7d2011-03-21 08:59:17 +0000886 Cond = std::string("MI->getOperand(") +
887 llvm::utostr(i) + ").getReg() == " + Target.getName() +
888 "::" + CGA->ResultOperands[i].getRegister()->getName();
889 IAP->addCond(Cond);
890 break;
891 }
892
893 if (!IAP) break;
894 }
895
896 if (CantHandle) continue;
Jim Grosbachb4b26f82012-04-18 20:24:49 +0000897 IAPrinterMap[I->first].push_back(IAP);
Bill Wendling3ce1b7d2011-03-21 08:59:17 +0000898 }
899 }
900
Bill Wendlingf415d8b2011-05-23 00:18:33 +0000901 std::string Header;
902 raw_string_ostream HeaderO(Header);
903
904 HeaderO << "bool " << Target.getName() << ClassName
Bill Wendling740e5b32011-06-14 03:17:20 +0000905 << "::printAliasInstr(const MCInst"
Bill Wendlingf415d8b2011-05-23 00:18:33 +0000906 << " *MI, raw_ostream &OS) {\n";
Bill Wendling3ce1b7d2011-03-21 08:59:17 +0000907
Bill Wendling44dcfd32011-04-07 21:20:06 +0000908 std::string Cases;
909 raw_string_ostream CasesO(Cases);
910
Jim Grosbachb4b26f82012-04-18 20:24:49 +0000911 for (std::map<std::string, std::vector<IAPrinter*> >::iterator
Bill Wendling44dcfd32011-04-07 21:20:06 +0000912 I = IAPrinterMap.begin(), E = IAPrinterMap.end(); I != E; ++I) {
913 std::vector<IAPrinter*> &IAPs = I->second;
914 std::vector<IAPrinter*> UniqueIAPs;
915
916 for (std::vector<IAPrinter*>::iterator
917 II = IAPs.begin(), IE = IAPs.end(); II != IE; ++II) {
918 IAPrinter *LHS = *II;
919 bool IsDup = false;
920 for (std::vector<IAPrinter*>::iterator
921 III = IAPs.begin(), IIE = IAPs.end(); III != IIE; ++III) {
922 IAPrinter *RHS = *III;
923 if (LHS != RHS && *LHS == *RHS) {
924 IsDup = true;
925 break;
926 }
927 }
928
929 if (!IsDup) UniqueIAPs.push_back(LHS);
930 }
931
932 if (UniqueIAPs.empty()) continue;
933
Jim Grosbachb4b26f82012-04-18 20:24:49 +0000934 CasesO.indent(2) << "case " << I->first << ":\n";
Bill Wendling44dcfd32011-04-07 21:20:06 +0000935
936 for (std::vector<IAPrinter*>::iterator
937 II = UniqueIAPs.begin(), IE = UniqueIAPs.end(); II != IE; ++II) {
938 IAPrinter *IAP = *II;
939 CasesO.indent(4);
Evan Cheng68ae5b42011-07-06 02:02:33 +0000940 IAP->print(CasesO);
Bill Wendling44dcfd32011-04-07 21:20:06 +0000941 CasesO << '\n';
942 }
943
Eric Christopher721ef662011-04-18 21:28:11 +0000944 CasesO.indent(4) << "return false;\n";
Bill Wendling44dcfd32011-04-07 21:20:06 +0000945 }
946
Bill Wendling740e5b32011-06-14 03:17:20 +0000947 if (CasesO.str().empty()) {
Bill Wendlingf415d8b2011-05-23 00:18:33 +0000948 O << HeaderO.str();
Eric Christopher721ef662011-04-18 21:28:11 +0000949 O << " return false;\n";
Bill Wendling7520e3a2011-02-26 03:09:12 +0000950 O << "}\n\n";
951 O << "#endif // PRINT_ALIAS_INSTR\n";
952 return;
953 }
954
Bill Wendlingf415d8b2011-05-23 00:18:33 +0000955 EmitGetMapOperandNumber(O);
956
957 O << HeaderO.str();
Bill Wendling44dcfd32011-04-07 21:20:06 +0000958 O.indent(2) << "StringRef AsmString;\n";
Bill Wendlingf415d8b2011-05-23 00:18:33 +0000959 O.indent(2) << "SmallVector<std::pair<StringRef, unsigned>, 4> OpMap;\n";
Bill Wendling44dcfd32011-04-07 21:20:06 +0000960 O.indent(2) << "switch (MI->getOpcode()) {\n";
Eric Christopher721ef662011-04-18 21:28:11 +0000961 O.indent(2) << "default: return false;\n";
Bill Wendling44dcfd32011-04-07 21:20:06 +0000962 O << CasesO.str();
963 O.indent(2) << "}\n\n";
Bill Wendling7520e3a2011-02-26 03:09:12 +0000964
965 // Code that prints the alias, replacing the operands with the ones from the
966 // MCInst.
Bill Wendling7520e3a2011-02-26 03:09:12 +0000967 O << " std::pair<StringRef, StringRef> ASM = AsmString.split(' ');\n";
968 O << " OS << '\\t' << ASM.first;\n";
969
970 O << " if (!ASM.second.empty()) {\n";
971 O << " OS << '\\t';\n";
972 O << " for (StringRef::iterator\n";
973 O << " I = ASM.second.begin(), E = ASM.second.end(); I != E; ) {\n";
974 O << " if (*I == '$') {\n";
975 O << " StringRef::iterator Start = ++I;\n";
976 O << " while (I != E &&\n";
977 O << " ((*I >= 'a' && *I <= 'z') ||\n";
978 O << " (*I >= 'A' && *I <= 'Z') ||\n";
979 O << " (*I >= '0' && *I <= '9') ||\n";
980 O << " *I == '_'))\n";
981 O << " ++I;\n";
982 O << " StringRef Name(Start, I - Start);\n";
Bill Wendlingf415d8b2011-05-23 00:18:33 +0000983 O << " printOperand(MI, getMapOperandNumber(OpMap, Name), OS);\n";
Bill Wendling7520e3a2011-02-26 03:09:12 +0000984 O << " } else {\n";
985 O << " OS << *I++;\n";
986 O << " }\n";
987 O << " }\n";
988 O << " }\n\n";
Jim Grosbach016c6792012-04-18 18:56:33 +0000989
Eric Christopher721ef662011-04-18 21:28:11 +0000990 O << " return true;\n";
Bill Wendling7520e3a2011-02-26 03:09:12 +0000991 O << "}\n\n";
992
993 O << "#endif // PRINT_ALIAS_INSTR\n";
994}
Chris Lattner05af2612009-09-13 20:08:00 +0000995
996void AsmWriterEmitter::run(raw_ostream &O) {
Chris Lattner05af2612009-09-13 20:08:00 +0000997 EmitPrintInstruction(O);
998 EmitGetRegisterName(O);
Bill Wendling7520e3a2011-02-26 03:09:12 +0000999 EmitPrintAliasInstruction(O);
Chris Lattner05af2612009-09-13 20:08:00 +00001000}
1001
Jakob Stoklund Olesen6f36fa92012-06-11 15:37:55 +00001002
1003namespace llvm {
1004
1005void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
1006 emitSourceFileHeader("Assembly Writer Source Fragment", OS);
1007 AsmWriterEmitter(RK).run(OS);
1008}
1009
1010} // End llvm namespace