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 void EmitCode(std::ostream &OS) const;
61 struct AsmWriterInst {
62 std::vector<AsmWriterOperand> Operands;
63 const CodeGenInstruction *CGI;
65 AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
67 /// MatchesAllButOneOp - If this instruction is exactly identical to the
68 /// specified instruction except for one differing operand, return the
69 /// differing operand number. Otherwise return ~0.
70 unsigned MatchesAllButOneOp(const AsmWriterInst &Other) const;
73 void AddLiteralString(const std::string &Str) {
74 // If the last operand was already a literal text string, append this to
75 // it, otherwise add a new operand.
76 if (!Operands.empty() &&
77 Operands.back().OperandType == AsmWriterOperand::isLiteralTextOperand)
78 Operands.back().Str.append(Str);
80 Operands.push_back(AsmWriterOperand(Str));
86 void AsmWriterOperand::EmitCode(std::ostream &OS) const {
87 if (OperandType == isLiteralTextOperand)
88 OS << "O << \"" << Str << "\"; ";
90 OS << Str << "(MI, " << MIOpNo << ", MVT::" << getName(OpVT) << "); ";
94 /// ParseAsmString - Parse the specified Instruction's AsmString into this
97 AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
99 bool inVariant = false; // True if we are inside a {.|.|.} region.
101 const std::string &AsmString = CGI.AsmString;
102 std::string::size_type LastEmitted = 0;
103 while (LastEmitted != AsmString.size()) {
104 std::string::size_type DollarPos =
105 AsmString.find_first_of("${|}", LastEmitted);
106 if (DollarPos == std::string::npos) DollarPos = AsmString.size();
108 // Emit a constant string fragment.
109 if (DollarPos != LastEmitted) {
110 // TODO: this should eventually handle escaping.
111 AddLiteralString(std::string(AsmString.begin()+LastEmitted,
112 AsmString.begin()+DollarPos));
113 LastEmitted = DollarPos;
114 } else if (AsmString[DollarPos] == '{') {
116 throw "Nested variants found for instruction '" + CGI.Name + "'!";
117 LastEmitted = DollarPos+1;
118 inVariant = true; // We are now inside of the variant!
119 for (unsigned i = 0; i != Variant; ++i) {
120 // Skip over all of the text for an irrelevant variant here. The
121 // next variant starts at |, or there may not be text for this
122 // variant if we see a }.
123 std::string::size_type NP =
124 AsmString.find_first_of("|}", LastEmitted);
125 if (NP == std::string::npos)
126 throw "Incomplete variant for instruction '" + CGI.Name + "'!";
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 '"
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 '" + CGI.Name + "'!";
143 } else if (AsmString[DollarPos] == '}') {
145 throw "'}' character found outside of a variant in instruction '"
147 LastEmitted = DollarPos+1;
149 } else if (DollarPos+1 != AsmString.size() &&
150 AsmString[DollarPos+1] == '$') {
151 AddLiteralString("$"); // "$$" -> $
152 LastEmitted = DollarPos+2;
154 // Get the name of the variable.
155 // TODO: should eventually handle ${foo}bar as $foo
156 std::string::size_type VarEnd = DollarPos+1;
157 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
159 std::string VarName(AsmString.begin()+DollarPos+1,
160 AsmString.begin()+VarEnd);
162 throw "Stray '$' in '" + CGI.Name + "' asm string, maybe you want $$?";
164 unsigned OpNo = CGI.getOperandNamed(VarName);
165 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
167 // If this is a two-address instruction and we are not accessing the
168 // 0th operand, remove an operand.
169 unsigned MIOp = OpInfo.MIOperandNo;
170 if (CGI.isTwoAddress && MIOp != 0) {
172 throw "Should refer to operand #0 instead of #1 for two-address"
173 " instruction '" + CGI.Name + "'!";
177 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName,
179 LastEmitted = VarEnd;
183 AddLiteralString("\\n");
186 /// MatchesAllButOneOp - If this instruction is exactly identical to the
187 /// specified instruction except for one differing operand, return the differing
188 /// operand number. If more than one operand mismatches, return ~1, otherwise
189 /// if the instructions are identical return ~0.
190 unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
191 if (Operands.size() != Other.Operands.size()) return ~1;
193 unsigned MismatchOperand = ~0U;
194 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
195 if (Operands[i] != Other.Operands[i])
196 if (MismatchOperand != ~0U) // Already have one mismatch?
201 return MismatchOperand;
205 /// EmitInstructions - Emit the last instruction in the vector and any other
206 /// instructions that are suitably similar to it.
207 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
209 AsmWriterInst FirstInst = Insts.back();
212 std::vector<AsmWriterInst> SimilarInsts;
213 unsigned DifferingOperand = ~0;
214 for (unsigned i = Insts.size(); i != 0; --i) {
215 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
217 if (DifferingOperand == ~0U) // First match!
218 DifferingOperand = DiffOp;
220 // If this differs in the same operand as the rest of the instructions in
221 // this class, move it to the SimilarInsts list.
222 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
223 SimilarInsts.push_back(Insts[i-1]);
224 Insts.erase(Insts.begin()+i-1);
229 std::string Namespace = FirstInst.CGI->Namespace;
231 O << " case " << Namespace << "::"
232 << FirstInst.CGI->TheDef->getName() << ":\n";
233 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
234 O << " case " << Namespace << "::"
235 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
236 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
237 if (i != DifferingOperand) {
238 // If the operand is the same for all instructions, just print it.
240 FirstInst.Operands[i].EmitCode(O);
242 // If this is the operand that varies between all of the instructions,
243 // emit a switch for just this operand now.
244 O << " switch (MI->getOpcode()) {\n";
245 O << " case " << Namespace << "::"
246 << FirstInst.CGI->TheDef->getName() << ": ";
247 FirstInst.Operands[i].EmitCode(O);
249 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
250 O << " case " << Namespace << "::"
251 << SimilarInsts[si].CGI->TheDef->getName() << ": ";
252 SimilarInsts[si].Operands[i].EmitCode(O);
263 void AsmWriterEmitter::run(std::ostream &O) {
264 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
266 CodeGenTarget Target;
267 Record *AsmWriter = Target.getAsmWriter();
268 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
269 unsigned Variant = AsmWriter->getValueAsInt("Variant");
272 "/// printInstruction - This method is automatically generated by tablegen\n"
273 "/// from the instruction set description. This method returns true if the\n"
274 "/// machine instruction was sufficiently described to print it, otherwise\n"
275 "/// it returns false.\n"
276 "bool " << Target.getName() << ClassName
277 << "::printInstruction(const MachineInstr *MI) {\n";
279 std::string Namespace = Target.inst_begin()->second.Namespace;
281 std::vector<AsmWriterInst> Instructions;
283 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
284 E = Target.inst_end(); I != E; ++I)
285 if (!I->second.AsmString.empty())
286 Instructions.push_back(AsmWriterInst(I->second, Variant));
288 // If all of the instructions start with a constant string (a very very common
289 // occurance), emit all of the constant strings as a big table lookup instead
290 // of requiring a switch for them.
291 bool AllStartWithString = true;
293 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
294 if (Instructions[i].Operands.empty() ||
295 Instructions[i].Operands[0].OperandType !=
296 AsmWriterOperand::isLiteralTextOperand) {
297 AllStartWithString = false;
301 if (AllStartWithString) {
302 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
303 // all machine instructions are necessarily being printed, so there may be
304 // target instructions not in this map.
305 std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
306 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
307 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
309 // Emit a table of constant strings.
310 std::vector<const CodeGenInstruction*> NumberedInstructions;
311 Target.getInstructionsByEnumValue(NumberedInstructions);
313 O << " static const char * const OpStrs[] = {\n";
314 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
315 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
317 // Something not handled by the asmwriter printer.
320 O << " \"" << AWI->Operands[0].Str << "\",\t// ";
321 // Nuke the string from the operand list. It is now handled!
322 AWI->Operands.erase(AWI->Operands.begin());
324 O << NumberedInstructions[i]->TheDef->getName() << "\n";
327 << " // Emit the opcode for the instruction.\n"
328 << " if (const char *AsmStr = OpStrs[MI->getOpcode()])\n"
329 << " O << AsmStr;\n\n";
332 // Because this is a vector we want to emit from the end. Reverse all of the
333 // elements in the vector.
334 std::reverse(Instructions.begin(), Instructions.end());
336 O << " switch (MI->getOpcode()) {\n"
337 " default: return false;\n";
339 while (!Instructions.empty())
340 EmitInstructions(Instructions, O);