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 AsmWriterOperand(const std::string &LitStr)
42 : OperandType(isLiteralTextOperand), Str(LitStr) {}
44 AsmWriterOperand(const std::string &Printer, unsigned OpNo)
45 : OperandType(isMachineInstrOperand), Str(Printer), MIOpNo(OpNo) {}
47 bool operator!=(const AsmWriterOperand &Other) const {
48 if (OperandType != Other.OperandType || Str != Other.Str) return true;
49 if (OperandType == isMachineInstrOperand)
50 return MIOpNo != Other.MIOpNo;
53 bool operator==(const AsmWriterOperand &Other) const {
54 return !operator!=(Other);
56 void EmitCode(std::ostream &OS) const;
59 struct AsmWriterInst {
60 std::vector<AsmWriterOperand> Operands;
61 const CodeGenInstruction *CGI;
63 AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
65 /// MatchesAllButOneOp - If this instruction is exactly identical to the
66 /// specified instruction except for one differing operand, return the
67 /// differing operand number. Otherwise return ~0.
68 unsigned MatchesAllButOneOp(const AsmWriterInst &Other) const;
71 void AddLiteralString(const std::string &Str) {
72 // If the last operand was already a literal text string, append this to
73 // it, otherwise add a new operand.
74 if (!Operands.empty() &&
75 Operands.back().OperandType == AsmWriterOperand::isLiteralTextOperand)
76 Operands.back().Str.append(Str);
78 Operands.push_back(AsmWriterOperand(Str));
84 void AsmWriterOperand::EmitCode(std::ostream &OS) const {
85 if (OperandType == isLiteralTextOperand)
86 OS << "O << \"" << Str << "\"; ";
88 OS << Str << "(MI, " << MIOpNo << "); ";
92 /// ParseAsmString - Parse the specified Instruction's AsmString into this
95 AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
97 bool inVariant = false; // True if we are inside a {.|.|.} region.
99 const std::string &AsmString = CGI.AsmString;
100 std::string::size_type LastEmitted = 0;
101 while (LastEmitted != AsmString.size()) {
102 std::string::size_type DollarPos =
103 AsmString.find_first_of("${|}", LastEmitted);
104 if (DollarPos == std::string::npos) DollarPos = AsmString.size();
106 // Emit a constant string fragment.
107 if (DollarPos != LastEmitted) {
108 // TODO: this should eventually handle escaping.
109 AddLiteralString(std::string(AsmString.begin()+LastEmitted,
110 AsmString.begin()+DollarPos));
111 LastEmitted = DollarPos;
112 } else if (AsmString[DollarPos] == '{') {
114 throw "Nested variants found for instruction '" +
115 CGI.TheDef->getName() + "'!";
116 LastEmitted = DollarPos+1;
117 inVariant = true; // We are now inside of the variant!
118 for (unsigned i = 0; i != Variant; ++i) {
119 // Skip over all of the text for an irrelevant variant here. The
120 // next variant starts at |, or there may not be text for this
121 // variant if we see a }.
122 std::string::size_type NP =
123 AsmString.find_first_of("|}", LastEmitted);
124 if (NP == std::string::npos)
125 throw "Incomplete variant for instruction '" +
126 CGI.TheDef->getName() + "'!";
128 if (AsmString[NP] == '}') {
129 inVariant = false; // No text for this variant.
133 } else if (AsmString[DollarPos] == '|') {
135 throw "'|' character found outside of a variant in instruction '"
136 + CGI.TheDef->getName() + "'!";
137 // Move to the end of variant list.
138 std::string::size_type NP = AsmString.find('}', LastEmitted);
139 if (NP == std::string::npos)
140 throw "Incomplete variant for instruction '" +
141 CGI.TheDef->getName() + "'!";
144 } else if (AsmString[DollarPos] == '}') {
146 throw "'}' character found outside of a variant in instruction '"
147 + CGI.TheDef->getName() + "'!";
148 LastEmitted = DollarPos+1;
150 } else if (DollarPos+1 != AsmString.size() &&
151 AsmString[DollarPos+1] == '$') {
152 AddLiteralString("$"); // "$$" -> $
153 LastEmitted = DollarPos+2;
155 // Get the name of the variable.
156 std::string::size_type VarEnd = DollarPos+1;
158 // handle ${foo}bar as $foo by detecting whether the character following
159 // the dollar sign is a curly brace. If so, advance VarEnd and DollarPos
160 // so the variable name does not contain the leading curly brace.
161 bool hasCurlyBraces = false;
162 if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
163 hasCurlyBraces = true;
168 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
170 std::string VarName(AsmString.begin()+DollarPos+1,
171 AsmString.begin()+VarEnd);
173 // In order to avoid starting the next string at the terminating curly
174 // brace, advance the end position past it if we found an opening curly
176 if (hasCurlyBraces) {
177 if (VarEnd >= AsmString.size())
178 throw "Reached end of string before terminating curly brace in '"
179 + CGI.TheDef->getName() + "'";
180 if (AsmString[VarEnd] != '}')
181 throw "Variant name beginning with '{' did not end with '}' in '"
182 + CGI.TheDef->getName() + "'";
186 throw "Stray '$' in '" + CGI.TheDef->getName() +
187 "' asm string, maybe you want $$?";
189 unsigned OpNo = CGI.getOperandNamed(VarName);
190 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
192 // If this is a two-address instruction and we are not accessing the
193 // 0th operand, remove an operand.
194 unsigned MIOp = OpInfo.MIOperandNo;
195 if (CGI.isTwoAddress && MIOp != 0) {
197 throw "Should refer to operand #0 instead of #1 for two-address"
198 " instruction '" + CGI.TheDef->getName() + "'!";
202 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp));
203 LastEmitted = VarEnd;
207 AddLiteralString("\\n");
210 /// MatchesAllButOneOp - If this instruction is exactly identical to the
211 /// specified instruction except for one differing operand, return the differing
212 /// operand number. If more than one operand mismatches, return ~1, otherwise
213 /// if the instructions are identical return ~0.
214 unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
215 if (Operands.size() != Other.Operands.size()) return ~1;
217 unsigned MismatchOperand = ~0U;
218 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
219 if (Operands[i] != Other.Operands[i])
220 if (MismatchOperand != ~0U) // Already have one mismatch?
225 return MismatchOperand;
228 static void PrintCases(std::vector<std::pair<std::string,
229 AsmWriterOperand> > &OpsToPrint, std::ostream &O) {
230 O << " case " << OpsToPrint.back().first << ": ";
231 AsmWriterOperand TheOp = OpsToPrint.back().second;
232 OpsToPrint.pop_back();
234 // Check to see if any other operands are identical in this list, and if so,
235 // emit a case label for them.
236 for (unsigned i = OpsToPrint.size(); i != 0; --i)
237 if (OpsToPrint[i-1].second == TheOp) {
238 O << "\n case " << OpsToPrint[i-1].first << ": ";
239 OpsToPrint.erase(OpsToPrint.begin()+i-1);
242 // Finally, emit the code.
248 /// EmitInstructions - Emit the last instruction in the vector and any other
249 /// instructions that are suitably similar to it.
250 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
252 AsmWriterInst FirstInst = Insts.back();
255 std::vector<AsmWriterInst> SimilarInsts;
256 unsigned DifferingOperand = ~0;
257 for (unsigned i = Insts.size(); i != 0; --i) {
258 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
260 if (DifferingOperand == ~0U) // First match!
261 DifferingOperand = DiffOp;
263 // If this differs in the same operand as the rest of the instructions in
264 // this class, move it to the SimilarInsts list.
265 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
266 SimilarInsts.push_back(Insts[i-1]);
267 Insts.erase(Insts.begin()+i-1);
272 std::string Namespace = FirstInst.CGI->Namespace;
274 O << " case " << Namespace << "::"
275 << FirstInst.CGI->TheDef->getName() << ":\n";
276 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
277 O << " case " << Namespace << "::"
278 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
279 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
280 if (i != DifferingOperand) {
281 // If the operand is the same for all instructions, just print it.
283 FirstInst.Operands[i].EmitCode(O);
285 // If this is the operand that varies between all of the instructions,
286 // emit a switch for just this operand now.
287 O << " switch (MI->getOpcode()) {\n";
288 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
289 OpsToPrint.push_back(std::make_pair(Namespace+"::"+
290 FirstInst.CGI->TheDef->getName(),
291 FirstInst.Operands[i]));
293 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
294 AsmWriterInst &AWI = SimilarInsts[si];
295 OpsToPrint.push_back(std::make_pair(Namespace+"::"+
296 AWI.CGI->TheDef->getName(),
299 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
300 while (!OpsToPrint.empty())
301 PrintCases(OpsToPrint, O);
310 void AsmWriterEmitter::run(std::ostream &O) {
311 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
313 CodeGenTarget Target;
314 Record *AsmWriter = Target.getAsmWriter();
315 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
316 unsigned Variant = AsmWriter->getValueAsInt("Variant");
319 "/// printInstruction - This method is automatically generated by tablegen\n"
320 "/// from the instruction set description. This method returns true if the\n"
321 "/// machine instruction was sufficiently described to print it, otherwise\n"
322 "/// it returns false.\n"
323 "bool " << Target.getName() << ClassName
324 << "::printInstruction(const MachineInstr *MI) {\n";
326 std::string Namespace = Target.inst_begin()->second.Namespace;
328 std::vector<AsmWriterInst> Instructions;
330 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
331 E = Target.inst_end(); I != E; ++I)
332 if (!I->second.AsmString.empty())
333 Instructions.push_back(AsmWriterInst(I->second, Variant));
335 // If all of the instructions start with a constant string (a very very common
336 // occurance), emit all of the constant strings as a big table lookup instead
337 // of requiring a switch for them.
338 bool AllStartWithString = true;
340 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
341 if (Instructions[i].Operands.empty() ||
342 Instructions[i].Operands[0].OperandType !=
343 AsmWriterOperand::isLiteralTextOperand) {
344 AllStartWithString = false;
348 if (AllStartWithString) {
349 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
350 // all machine instructions are necessarily being printed, so there may be
351 // target instructions not in this map.
352 std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
353 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
354 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
356 // Emit a table of constant strings.
357 std::vector<const CodeGenInstruction*> NumberedInstructions;
358 Target.getInstructionsByEnumValue(NumberedInstructions);
360 O << " static const char * const OpStrs[] = {\n";
361 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
362 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
364 // Something not handled by the asmwriter printer.
367 O << " \"" << AWI->Operands[0].Str << "\",\t// ";
368 // Nuke the string from the operand list. It is now handled!
369 AWI->Operands.erase(AWI->Operands.begin());
371 O << NumberedInstructions[i]->TheDef->getName() << "\n";
374 << " // Emit the opcode for the instruction.\n"
375 << " if (const char *AsmStr = OpStrs[MI->getOpcode()])\n"
376 << " O << AsmStr;\n\n";
379 // Because this is a vector we want to emit from the end. Reverse all of the
380 // elements in the vector.
381 std::reverse(Instructions.begin(), Instructions.end());
383 O << " switch (MI->getOpcode()) {\n"
384 " default: return false;\n";
386 while (!Instructions.empty())
387 EmitInstructions(Instructions, O);