1 //===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend is emits an assembly printer for the current target.
11 // Note that this is currently fairly skeletal, but will grow over time.
13 //===----------------------------------------------------------------------===//
15 #include "AsmWriterEmitter.h"
16 #include "CodeGenTarget.h"
22 static bool isIdentChar(char C) {
23 return (C >= 'a' && C <= 'z') ||
24 (C >= 'A' && C <= 'Z') ||
25 (C >= '0' && C <= '9') ||
30 struct AsmWriterOperand {
31 enum { isLiteralTextOperand, isMachineInstrOperand } OperandType;
33 /// Str - For isLiteralTextOperand, this IS the literal text. For
34 /// isMachineInstrOperand, this is the PrinterMethodName for the operand.
37 /// MiOpNo - For isMachineInstrOperand, this is the operand number of the
38 /// machine instruction.
41 /// OpVT - For isMachineInstrOperand, this is the value type for the
45 AsmWriterOperand(const std::string &LitStr)
46 : OperandType(isLiteralTextOperand), Str(LitStr) {}
48 AsmWriterOperand(const std::string &Printer, unsigned OpNo,
49 MVT::ValueType VT) : OperandType(isMachineInstrOperand),
50 Str(Printer), MIOpNo(OpNo), OpVT(VT){}
52 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;
58 bool operator==(const AsmWriterOperand &Other) const {
59 return !operator!=(Other);
61 void EmitCode(std::ostream &OS) const;
64 struct AsmWriterInst {
65 std::vector<AsmWriterOperand> Operands;
66 const CodeGenInstruction *CGI;
68 AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
70 /// 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;
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);
83 Operands.push_back(AsmWriterOperand(Str));
89 void AsmWriterOperand::EmitCode(std::ostream &OS) const {
90 if (OperandType == isLiteralTextOperand)
91 OS << "O << \"" << Str << "\"; ";
93 OS << Str << "(MI, " << MIOpNo << ", MVT::" << getEnumName(OpVT) << "); ";
97 /// ParseAsmString - Parse the specified Instruction's AsmString into this
100 AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
102 bool inVariant = false; // True if we are inside a {.|.|.} region.
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();
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] == '{') {
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 + "'!";
131 if (AsmString[NP] == '}') {
132 inVariant = false; // No text for this variant.
136 } else if (AsmString[DollarPos] == '|') {
138 throw "'|' character found outside of a variant in instruction '"
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 + "'!";
146 } else if (AsmString[DollarPos] == '}') {
148 throw "'}' character found outside of a variant in instruction '"
150 LastEmitted = DollarPos+1;
152 } else if (DollarPos+1 != AsmString.size() &&
153 AsmString[DollarPos+1] == '$') {
154 AddLiteralString("$"); // "$$" -> $
155 LastEmitted = DollarPos+2;
157 // Get the name of the variable.
158 // TODO: should eventually handle ${foo}bar as $foo
159 std::string::size_type VarEnd = DollarPos+1;
160 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
162 std::string VarName(AsmString.begin()+DollarPos+1,
163 AsmString.begin()+VarEnd);
165 throw "Stray '$' in '" + CGI.Name + "' asm string, maybe you want $$?";
167 unsigned OpNo = CGI.getOperandNamed(VarName);
168 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
170 // If this is a two-address instruction and we are not accessing the
171 // 0th operand, remove an operand.
172 unsigned MIOp = OpInfo.MIOperandNo;
173 if (CGI.isTwoAddress && MIOp != 0) {
175 throw "Should refer to operand #0 instead of #1 for two-address"
176 " instruction '" + CGI.Name + "'!";
180 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName,
182 LastEmitted = VarEnd;
186 AddLiteralString("\\n");
189 /// MatchesAllButOneOp - If this instruction is exactly identical to the
190 /// specified instruction except for one differing operand, return the differing
191 /// operand number. If more than one operand mismatches, return ~1, otherwise
192 /// if the instructions are identical return ~0.
193 unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
194 if (Operands.size() != Other.Operands.size()) return ~1;
196 unsigned MismatchOperand = ~0U;
197 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
198 if (Operands[i] != Other.Operands[i])
199 if (MismatchOperand != ~0U) // Already have one mismatch?
204 return MismatchOperand;
207 static void PrintCases(std::vector<std::pair<std::string,
208 AsmWriterOperand> > &OpsToPrint, std::ostream &O) {
209 O << " case " << OpsToPrint.back().first << ": ";
210 AsmWriterOperand TheOp = OpsToPrint.back().second;
211 OpsToPrint.pop_back();
213 // Check to see if any other operands are identical in this list, and if so,
214 // emit a case label for them.
215 for (unsigned i = OpsToPrint.size(); i != 0; --i)
216 if (OpsToPrint[i-1].second == TheOp) {
217 O << "\n case " << OpsToPrint[i-1].first << ": ";
218 OpsToPrint.erase(OpsToPrint.begin()+i-1);
221 // Finally, emit the code.
227 /// EmitInstructions - Emit the last instruction in the vector and any other
228 /// instructions that are suitably similar to it.
229 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
231 AsmWriterInst FirstInst = Insts.back();
234 std::vector<AsmWriterInst> SimilarInsts;
235 unsigned DifferingOperand = ~0;
236 for (unsigned i = Insts.size(); i != 0; --i) {
237 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
239 if (DifferingOperand == ~0U) // First match!
240 DifferingOperand = DiffOp;
242 // If this differs in the same operand as the rest of the instructions in
243 // this class, move it to the SimilarInsts list.
244 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
245 SimilarInsts.push_back(Insts[i-1]);
246 Insts.erase(Insts.begin()+i-1);
251 std::string Namespace = FirstInst.CGI->Namespace;
253 O << " case " << Namespace << "::"
254 << FirstInst.CGI->TheDef->getName() << ":\n";
255 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
256 O << " case " << Namespace << "::"
257 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
258 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
259 if (i != DifferingOperand) {
260 // If the operand is the same for all instructions, just print it.
262 FirstInst.Operands[i].EmitCode(O);
264 // If this is the operand that varies between all of the instructions,
265 // emit a switch for just this operand now.
266 O << " switch (MI->getOpcode()) {\n";
267 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
268 OpsToPrint.push_back(std::make_pair(Namespace+"::"+
269 FirstInst.CGI->TheDef->getName(),
270 FirstInst.Operands[i]));
272 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
273 AsmWriterInst &AWI = SimilarInsts[si];
274 OpsToPrint.push_back(std::make_pair(Namespace+"::"+
275 AWI.CGI->TheDef->getName(),
278 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
279 while (!OpsToPrint.empty())
280 PrintCases(OpsToPrint, O);
289 void AsmWriterEmitter::run(std::ostream &O) {
290 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
292 CodeGenTarget Target;
293 Record *AsmWriter = Target.getAsmWriter();
294 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
295 unsigned Variant = AsmWriter->getValueAsInt("Variant");
298 "/// printInstruction - This method is automatically generated by tablegen\n"
299 "/// from the instruction set description. This method returns true if the\n"
300 "/// machine instruction was sufficiently described to print it, otherwise\n"
301 "/// it returns false.\n"
302 "bool " << Target.getName() << ClassName
303 << "::printInstruction(const MachineInstr *MI) {\n";
305 std::string Namespace = Target.inst_begin()->second.Namespace;
307 std::vector<AsmWriterInst> Instructions;
309 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
310 E = Target.inst_end(); I != E; ++I)
311 if (!I->second.AsmString.empty())
312 Instructions.push_back(AsmWriterInst(I->second, Variant));
314 // If all of the instructions start with a constant string (a very very common
315 // occurance), emit all of the constant strings as a big table lookup instead
316 // of requiring a switch for them.
317 bool AllStartWithString = true;
319 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
320 if (Instructions[i].Operands.empty() ||
321 Instructions[i].Operands[0].OperandType !=
322 AsmWriterOperand::isLiteralTextOperand) {
323 AllStartWithString = false;
327 if (AllStartWithString) {
328 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
329 // all machine instructions are necessarily being printed, so there may be
330 // target instructions not in this map.
331 std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
332 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
333 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
335 // Emit a table of constant strings.
336 std::vector<const CodeGenInstruction*> NumberedInstructions;
337 Target.getInstructionsByEnumValue(NumberedInstructions);
339 O << " static const char * const OpStrs[] = {\n";
340 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
341 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
343 // Something not handled by the asmwriter printer.
346 O << " \"" << AWI->Operands[0].Str << "\",\t// ";
347 // Nuke the string from the operand list. It is now handled!
348 AWI->Operands.erase(AWI->Operands.begin());
350 O << NumberedInstructions[i]->TheDef->getName() << "\n";
353 << " // Emit the opcode for the instruction.\n"
354 << " if (const char *AsmStr = OpStrs[MI->getOpcode()])\n"
355 << " O << AsmStr;\n\n";
358 // Because this is a vector we want to emit from the end. Reverse all of the
359 // elements in the vector.
360 std::reverse(Instructions.begin(), Instructions.end());
362 O << " switch (MI->getOpcode()) {\n"
363 " default: return false;\n";
365 while (!Instructions.empty())
366 EmitInstructions(Instructions, O);