blob: 34aaf15b5a7517522040071c4155fad643022bf5 [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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
15#include "AsmWriterEmitter.h"
16#include "CodeGenTarget.h"
Chris Lattner175580c2004-08-14 22:50:53 +000017#include "Record.h"
Jeff Cohen615ed992005-01-22 18:50:10 +000018#include <algorithm>
Chris Lattner2e1f51b2004-08-01 05:59:33 +000019#include <ostream>
20using namespace llvm;
21
Chris Lattner076efa72004-08-01 07:43:02 +000022static bool isIdentChar(char C) {
23 return (C >= 'a' && C <= 'z') ||
24 (C >= 'A' && C <= 'Z') ||
25 (C >= '0' && C <= '9') ||
26 C == '_';
27}
28
Chris Lattnerb0b55e72005-01-22 17:32:42 +000029namespace {
30 struct AsmWriterOperand {
31 enum { isLiteralTextOperand, isMachineInstrOperand } OperandType;
32
33 /// Str - For isLiteralTextOperand, this IS the literal text. For
34 /// isMachineInstrOperand, this is the PrinterMethodName for the operand.
35 std::string Str;
36
37 /// MiOpNo - For isMachineInstrOperand, this is the operand number of the
38 /// machine instruction.
39 unsigned MIOpNo;
40
41 /// OpVT - For isMachineInstrOperand, this is the value type for the
42 /// operand.
43 MVT::ValueType OpVT;
44
45 AsmWriterOperand(const std::string &LitStr)
46 : OperandType(isLiteralTextOperand), Str(LitStr) {}
47
48 AsmWriterOperand(const std::string &Printer, unsigned OpNo,
49 MVT::ValueType VT) : OperandType(isMachineInstrOperand),
50 Str(Printer), MIOpNo(OpNo), OpVT(VT){}
51
Chris Lattner870c0162005-01-22 18:38:13 +000052 bool operator!=(const AsmWriterOperand &Other) const {
53 if (OperandType != Other.OperandType || Str != Other.Str) return true;
54 if (OperandType == isMachineInstrOperand)
55 return MIOpNo != Other.MIOpNo || OpVT != Other.OpVT;
56 return false;
57 }
Chris Lattner38c07512005-01-22 20:31:17 +000058 bool operator==(const AsmWriterOperand &Other) const {
59 return !operator!=(Other);
60 }
Chris Lattnerb0b55e72005-01-22 17:32:42 +000061 void EmitCode(std::ostream &OS) const;
62 };
63
64 struct AsmWriterInst {
65 std::vector<AsmWriterOperand> Operands;
Chris Lattner5765dba2005-01-22 17:40:38 +000066 const CodeGenInstruction *CGI;
Misha Brukman3da94ae2005-04-22 00:00:37 +000067
Chris Lattner5765dba2005-01-22 17:40:38 +000068 AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
Chris Lattner870c0162005-01-22 18:38:13 +000069
Chris Lattnerf8766682005-01-22 19:22:23 +000070 /// MatchesAllButOneOp - If this instruction is exactly identical to the
71 /// specified instruction except for one differing operand, return the
72 /// differing operand number. Otherwise return ~0.
73 unsigned MatchesAllButOneOp(const AsmWriterInst &Other) const;
Chris Lattner870c0162005-01-22 18:38:13 +000074
Chris Lattnerb0b55e72005-01-22 17:32:42 +000075 private:
76 void AddLiteralString(const std::string &Str) {
77 // If the last operand was already a literal text string, append this to
78 // it, otherwise add a new operand.
79 if (!Operands.empty() &&
80 Operands.back().OperandType == AsmWriterOperand::isLiteralTextOperand)
81 Operands.back().Str.append(Str);
82 else
83 Operands.push_back(AsmWriterOperand(Str));
84 }
85 };
86}
87
88
89void AsmWriterOperand::EmitCode(std::ostream &OS) const {
90 if (OperandType == isLiteralTextOperand)
91 OS << "O << \"" << Str << "\"; ";
92 else
Chris Lattner131ca382005-01-22 20:59:38 +000093 OS << Str << "(MI, " << MIOpNo << ", MVT::" << getEnumName(OpVT) << "); ";
Chris Lattnerb0b55e72005-01-22 17:32:42 +000094}
95
96
97/// ParseAsmString - Parse the specified Instruction's AsmString into this
98/// AsmWriterInst.
99///
Chris Lattner5765dba2005-01-22 17:40:38 +0000100AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
101 this->CGI = &CGI;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000102 bool inVariant = false; // True if we are inside a {.|.|.} region.
103
104 const std::string &AsmString = CGI.AsmString;
105 std::string::size_type LastEmitted = 0;
106 while (LastEmitted != AsmString.size()) {
107 std::string::size_type DollarPos =
108 AsmString.find_first_of("${|}", LastEmitted);
109 if (DollarPos == std::string::npos) DollarPos = AsmString.size();
110
111 // Emit a constant string fragment.
112 if (DollarPos != LastEmitted) {
113 // TODO: this should eventually handle escaping.
114 AddLiteralString(std::string(AsmString.begin()+LastEmitted,
115 AsmString.begin()+DollarPos));
116 LastEmitted = DollarPos;
117 } else if (AsmString[DollarPos] == '{') {
118 if (inVariant)
119 throw "Nested variants found for instruction '" + CGI.Name + "'!";
120 LastEmitted = DollarPos+1;
121 inVariant = true; // We are now inside of the variant!
122 for (unsigned i = 0; i != Variant; ++i) {
123 // Skip over all of the text for an irrelevant variant here. The
124 // next variant starts at |, or there may not be text for this
125 // variant if we see a }.
126 std::string::size_type NP =
127 AsmString.find_first_of("|}", LastEmitted);
128 if (NP == std::string::npos)
129 throw "Incomplete variant for instruction '" + CGI.Name + "'!";
130 LastEmitted = NP+1;
131 if (AsmString[NP] == '}') {
132 inVariant = false; // No text for this variant.
133 break;
134 }
135 }
136 } else if (AsmString[DollarPos] == '|') {
137 if (!inVariant)
138 throw "'|' character found outside of a variant in instruction '"
139 + CGI.Name + "'!";
140 // Move to the end of variant list.
141 std::string::size_type NP = AsmString.find('}', LastEmitted);
142 if (NP == std::string::npos)
143 throw "Incomplete variant for instruction '" + CGI.Name + "'!";
144 LastEmitted = NP+1;
145 inVariant = false;
146 } else if (AsmString[DollarPos] == '}') {
147 if (!inVariant)
148 throw "'}' character found outside of a variant in instruction '"
149 + CGI.Name + "'!";
150 LastEmitted = DollarPos+1;
151 inVariant = false;
152 } else if (DollarPos+1 != AsmString.size() &&
153 AsmString[DollarPos+1] == '$') {
154 AddLiteralString("$"); // "$$" -> $
155 LastEmitted = DollarPos+2;
156 } else {
157 // Get the name of the variable.
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000158 std::string::size_type VarEnd = DollarPos+1;
Nate Begemanafc54562005-07-14 22:50:30 +0000159
160 // handle ${foo}bar as $foo by detecting whether the character following
161 // the dollar sign is a curly brace. If so, advance VarEnd and DollarPos
162 // so the variable name does not contain the leading curly brace.
163 bool hasCurlyBraces = false;
164 if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
165 hasCurlyBraces = true;
166 ++DollarPos;
167 ++VarEnd;
168 }
169
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000170 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
171 ++VarEnd;
172 std::string VarName(AsmString.begin()+DollarPos+1,
173 AsmString.begin()+VarEnd);
Nate Begemanafc54562005-07-14 22:50:30 +0000174
175 // In order to avoid starting the next string at the terminating curly
176 // brace, advance the end position past it if we found an opening curly
177 // brace.
178 if (hasCurlyBraces) {
179 if (VarEnd >= AsmString.size())
180 throw "Reached end of string before terminating curly brace in '"
181 + CGI.Name + "'";
182 if (AsmString[VarEnd] != '}')
183 throw "Variant name beginning with '{' did not end with '}' in '"
184 + CGI.Name + "'";
185 ++VarEnd;
186 }
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000187 if (VarName.empty())
188 throw "Stray '$' in '" + CGI.Name + "' asm string, maybe you want $$?";
189
190 unsigned OpNo = CGI.getOperandNamed(VarName);
Chris Lattner5765dba2005-01-22 17:40:38 +0000191 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000192
193 // If this is a two-address instruction and we are not accessing the
194 // 0th operand, remove an operand.
Chris Lattner5765dba2005-01-22 17:40:38 +0000195 unsigned MIOp = OpInfo.MIOperandNo;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000196 if (CGI.isTwoAddress && MIOp != 0) {
197 if (MIOp == 1)
198 throw "Should refer to operand #0 instead of #1 for two-address"
199 " instruction '" + CGI.Name + "'!";
200 --MIOp;
201 }
202
Chris Lattner5765dba2005-01-22 17:40:38 +0000203 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName,
204 MIOp, OpInfo.Ty));
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000205 LastEmitted = VarEnd;
206 }
207 }
208
209 AddLiteralString("\\n");
210}
211
Chris Lattnerf8766682005-01-22 19:22:23 +0000212/// MatchesAllButOneOp - If this instruction is exactly identical to the
213/// specified instruction except for one differing operand, return the differing
214/// operand number. If more than one operand mismatches, return ~1, otherwise
215/// if the instructions are identical return ~0.
216unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
217 if (Operands.size() != Other.Operands.size()) return ~1;
Chris Lattner870c0162005-01-22 18:38:13 +0000218
219 unsigned MismatchOperand = ~0U;
220 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Chris Lattner870c0162005-01-22 18:38:13 +0000221 if (Operands[i] != Other.Operands[i])
Chris Lattnerf8766682005-01-22 19:22:23 +0000222 if (MismatchOperand != ~0U) // Already have one mismatch?
223 return ~1U;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000224 else
Chris Lattner870c0162005-01-22 18:38:13 +0000225 MismatchOperand = i;
226 }
227 return MismatchOperand;
228}
229
Chris Lattner38c07512005-01-22 20:31:17 +0000230static void PrintCases(std::vector<std::pair<std::string,
231 AsmWriterOperand> > &OpsToPrint, std::ostream &O) {
232 O << " case " << OpsToPrint.back().first << ": ";
233 AsmWriterOperand TheOp = OpsToPrint.back().second;
234 OpsToPrint.pop_back();
235
236 // Check to see if any other operands are identical in this list, and if so,
237 // emit a case label for them.
238 for (unsigned i = OpsToPrint.size(); i != 0; --i)
239 if (OpsToPrint[i-1].second == TheOp) {
240 O << "\n case " << OpsToPrint[i-1].first << ": ";
241 OpsToPrint.erase(OpsToPrint.begin()+i-1);
242 }
243
244 // Finally, emit the code.
245 TheOp.EmitCode(O);
246 O << "break;\n";
247}
248
Chris Lattner870c0162005-01-22 18:38:13 +0000249
250/// EmitInstructions - Emit the last instruction in the vector and any other
251/// instructions that are suitably similar to it.
252static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
253 std::ostream &O) {
254 AsmWriterInst FirstInst = Insts.back();
255 Insts.pop_back();
256
257 std::vector<AsmWriterInst> SimilarInsts;
258 unsigned DifferingOperand = ~0;
259 for (unsigned i = Insts.size(); i != 0; --i) {
Chris Lattnerf8766682005-01-22 19:22:23 +0000260 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
261 if (DiffOp != ~1U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000262 if (DifferingOperand == ~0U) // First match!
263 DifferingOperand = DiffOp;
264
265 // If this differs in the same operand as the rest of the instructions in
266 // this class, move it to the SimilarInsts list.
Chris Lattnerf8766682005-01-22 19:22:23 +0000267 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000268 SimilarInsts.push_back(Insts[i-1]);
269 Insts.erase(Insts.begin()+i-1);
270 }
271 }
272 }
273
274 std::string Namespace = FirstInst.CGI->Namespace;
275
276 O << " case " << Namespace << "::"
277 << FirstInst.CGI->TheDef->getName() << ":\n";
278 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
279 O << " case " << Namespace << "::"
280 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
281 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
282 if (i != DifferingOperand) {
283 // If the operand is the same for all instructions, just print it.
284 O << " ";
285 FirstInst.Operands[i].EmitCode(O);
286 } else {
287 // If this is the operand that varies between all of the instructions,
288 // emit a switch for just this operand now.
289 O << " switch (MI->getOpcode()) {\n";
Chris Lattner38c07512005-01-22 20:31:17 +0000290 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
291 OpsToPrint.push_back(std::make_pair(Namespace+"::"+
292 FirstInst.CGI->TheDef->getName(),
293 FirstInst.Operands[i]));
Misha Brukman3da94ae2005-04-22 00:00:37 +0000294
Chris Lattner870c0162005-01-22 18:38:13 +0000295 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
Chris Lattner38c07512005-01-22 20:31:17 +0000296 AsmWriterInst &AWI = SimilarInsts[si];
297 OpsToPrint.push_back(std::make_pair(Namespace+"::"+
298 AWI.CGI->TheDef->getName(),
299 AWI.Operands[i]));
Chris Lattner870c0162005-01-22 18:38:13 +0000300 }
Chris Lattner38c07512005-01-22 20:31:17 +0000301 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
302 while (!OpsToPrint.empty())
303 PrintCases(OpsToPrint, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000304 O << " }";
305 }
306 O << "\n";
307 }
308
309 O << " break;\n";
310}
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000311
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000312void AsmWriterEmitter::run(std::ostream &O) {
313 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
314
315 CodeGenTarget Target;
Chris Lattner175580c2004-08-14 22:50:53 +0000316 Record *AsmWriter = Target.getAsmWriter();
Chris Lattner953c6fe2004-10-03 20:19:02 +0000317 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
318 unsigned Variant = AsmWriter->getValueAsInt("Variant");
Chris Lattner175580c2004-08-14 22:50:53 +0000319
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000320 O <<
321 "/// printInstruction - This method is automatically generated by tablegen\n"
322 "/// from the instruction set description. This method returns true if the\n"
323 "/// machine instruction was sufficiently described to print it, otherwise\n"
324 "/// it returns false.\n"
Chris Lattner953c6fe2004-10-03 20:19:02 +0000325 "bool " << Target.getName() << ClassName
Chris Lattner175580c2004-08-14 22:50:53 +0000326 << "::printInstruction(const MachineInstr *MI) {\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000327
328 std::string Namespace = Target.inst_begin()->second.Namespace;
329
Chris Lattner5765dba2005-01-22 17:40:38 +0000330 std::vector<AsmWriterInst> Instructions;
331
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000332 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
333 E = Target.inst_end(); I != E; ++I)
Chris Lattner5765dba2005-01-22 17:40:38 +0000334 if (!I->second.AsmString.empty())
335 Instructions.push_back(AsmWriterInst(I->second, Variant));
Chris Lattner076efa72004-08-01 07:43:02 +0000336
Chris Lattnerf8766682005-01-22 19:22:23 +0000337 // If all of the instructions start with a constant string (a very very common
338 // occurance), emit all of the constant strings as a big table lookup instead
Misha Brukman3da94ae2005-04-22 00:00:37 +0000339 // of requiring a switch for them.
Chris Lattnerf8766682005-01-22 19:22:23 +0000340 bool AllStartWithString = true;
341
342 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
343 if (Instructions[i].Operands.empty() ||
344 Instructions[i].Operands[0].OperandType !=
345 AsmWriterOperand::isLiteralTextOperand) {
346 AllStartWithString = false;
347 break;
348 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000349
Chris Lattnerf8766682005-01-22 19:22:23 +0000350 if (AllStartWithString) {
351 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
352 // all machine instructions are necessarily being printed, so there may be
353 // target instructions not in this map.
354 std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
355 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
356 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
357
358 // Emit a table of constant strings.
359 std::vector<const CodeGenInstruction*> NumberedInstructions;
360 Target.getInstructionsByEnumValue(NumberedInstructions);
361
362 O << " static const char * const OpStrs[] = {\n";
363 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
364 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
365 if (AWI == 0) {
366 // Something not handled by the asmwriter printer.
367 O << " 0,\t// ";
368 } else {
369 O << " \"" << AWI->Operands[0].Str << "\",\t// ";
370 // Nuke the string from the operand list. It is now handled!
371 AWI->Operands.erase(AWI->Operands.begin());
372 }
373 O << NumberedInstructions[i]->TheDef->getName() << "\n";
374 }
375 O << " };\n\n"
376 << " // Emit the opcode for the instruction.\n"
377 << " if (const char *AsmStr = OpStrs[MI->getOpcode()])\n"
378 << " O << AsmStr;\n\n";
379 }
380
Chris Lattner870c0162005-01-22 18:38:13 +0000381 // Because this is a vector we want to emit from the end. Reverse all of the
382 // elements in the vector.
383 std::reverse(Instructions.begin(), Instructions.end());
Chris Lattnerf8766682005-01-22 19:22:23 +0000384
385 O << " switch (MI->getOpcode()) {\n"
386 " default: return false;\n";
Misha Brukman3da94ae2005-04-22 00:00:37 +0000387
Chris Lattner870c0162005-01-22 18:38:13 +0000388 while (!Instructions.empty())
389 EmitInstructions(Instructions, O);
390
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000391 O << " }\n"
392 " return true;\n"
393 "}\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000394}