blob: 18b07595611b89ed84fb6f584282a84aa702fe9b [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
15#include "AsmWriterEmitter.h"
16#include "CodeGenTarget.h"
Chris Lattner175580c2004-08-14 22:50:53 +000017#include "Record.h"
Chris Lattner6af022f2006-07-14 22:59:11 +000018#include "llvm/ADT/StringExtras.h"
Chris Lattnerbdff5f92006-07-18 17:18:03 +000019#include "llvm/Support/Debug.h"
20#include "llvm/Support/MathExtras.h"
Jeff Cohen615ed992005-01-22 18:50:10 +000021#include <algorithm>
Chris Lattner2e1f51b2004-08-01 05:59:33 +000022using namespace llvm;
23
Chris Lattner076efa72004-08-01 07:43:02 +000024static bool isIdentChar(char C) {
25 return (C >= 'a' && C <= 'z') ||
26 (C >= 'A' && C <= 'Z') ||
27 (C >= '0' && C <= '9') ||
28 C == '_';
29}
30
Chris Lattnerad8c5312007-07-18 04:51:57 +000031// This should be an anon namespace, this works around a GCC warning.
32namespace llvm {
Chris Lattnerb0b55e72005-01-22 17:32:42 +000033 struct AsmWriterOperand {
34 enum { isLiteralTextOperand, isMachineInstrOperand } OperandType;
35
36 /// Str - For isLiteralTextOperand, this IS the literal text. For
37 /// isMachineInstrOperand, this is the PrinterMethodName for the operand.
38 std::string Str;
39
40 /// MiOpNo - For isMachineInstrOperand, this is the operand number of the
41 /// machine instruction.
42 unsigned MIOpNo;
Chris Lattner04cadb32006-02-06 23:40:48 +000043
44 /// MiModifier - For isMachineInstrOperand, this is the modifier string for
45 /// an operand, specified with syntax like ${opname:modifier}.
46 std::string MiModifier;
Chris Lattnerb0b55e72005-01-22 17:32:42 +000047
Chris Lattnerb0b55e72005-01-22 17:32:42 +000048 AsmWriterOperand(const std::string &LitStr)
Nate Begeman391c5d22005-11-30 18:54:35 +000049 : OperandType(isLiteralTextOperand), Str(LitStr) {}
Chris Lattnerb0b55e72005-01-22 17:32:42 +000050
Chris Lattner04cadb32006-02-06 23:40:48 +000051 AsmWriterOperand(const std::string &Printer, unsigned OpNo,
52 const std::string &Modifier)
53 : OperandType(isMachineInstrOperand), Str(Printer), MIOpNo(OpNo),
54 MiModifier(Modifier) {}
Chris Lattnerb0b55e72005-01-22 17:32:42 +000055
Chris Lattner870c0162005-01-22 18:38:13 +000056 bool operator!=(const AsmWriterOperand &Other) const {
57 if (OperandType != Other.OperandType || Str != Other.Str) return true;
58 if (OperandType == isMachineInstrOperand)
Chris Lattner04cadb32006-02-06 23:40:48 +000059 return MIOpNo != Other.MIOpNo || MiModifier != Other.MiModifier;
Chris Lattner870c0162005-01-22 18:38:13 +000060 return false;
61 }
Chris Lattner38c07512005-01-22 20:31:17 +000062 bool operator==(const AsmWriterOperand &Other) const {
63 return !operator!=(Other);
64 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +000065
66 /// getCode - Return the code that prints this operand.
67 std::string getCode() const;
Chris Lattnerb0b55e72005-01-22 17:32:42 +000068 };
Chris Lattnerbdff5f92006-07-18 17:18:03 +000069}
Chris Lattnerb0b55e72005-01-22 17:32:42 +000070
Chris Lattnerbdff5f92006-07-18 17:18:03 +000071namespace llvm {
Jeff Cohend41b30d2006-11-05 19:31:28 +000072 class AsmWriterInst {
73 public:
Chris Lattnerb0b55e72005-01-22 17:32:42 +000074 std::vector<AsmWriterOperand> Operands;
Chris Lattner5765dba2005-01-22 17:40:38 +000075 const CodeGenInstruction *CGI;
Misha Brukman3da94ae2005-04-22 00:00:37 +000076
Chris Lattner5765dba2005-01-22 17:40:38 +000077 AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
Chris Lattner870c0162005-01-22 18:38:13 +000078
Chris Lattnerf8766682005-01-22 19:22:23 +000079 /// MatchesAllButOneOp - If this instruction is exactly identical to the
80 /// specified instruction except for one differing operand, return the
81 /// differing operand number. Otherwise return ~0.
82 unsigned MatchesAllButOneOp(const AsmWriterInst &Other) const;
Chris Lattner870c0162005-01-22 18:38:13 +000083
Chris Lattnerb0b55e72005-01-22 17:32:42 +000084 private:
85 void AddLiteralString(const std::string &Str) {
86 // If the last operand was already a literal text string, append this to
87 // it, otherwise add a new operand.
88 if (!Operands.empty() &&
89 Operands.back().OperandType == AsmWriterOperand::isLiteralTextOperand)
90 Operands.back().Str.append(Str);
91 else
92 Operands.push_back(AsmWriterOperand(Str));
93 }
94 };
95}
96
97
Chris Lattnerbdff5f92006-07-18 17:18:03 +000098std::string AsmWriterOperand::getCode() const {
Chris Lattnerb0b55e72005-01-22 17:32:42 +000099 if (OperandType == isLiteralTextOperand)
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000100 return "O << \"" + Str + "\"; ";
101
Chris Lattner1bf63612006-09-26 23:45:08 +0000102 std::string Result = Str + "(MI";
103 if (MIOpNo != ~0U)
104 Result += ", " + utostr(MIOpNo);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000105 if (!MiModifier.empty())
106 Result += ", \"" + MiModifier + '"';
107 return Result + "); ";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000108}
109
110
111/// ParseAsmString - Parse the specified Instruction's AsmString into this
112/// AsmWriterInst.
113///
Chris Lattner5765dba2005-01-22 17:40:38 +0000114AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
115 this->CGI = &CGI;
Chris Lattnerb03b0802006-02-06 22:43:28 +0000116 unsigned CurVariant = ~0U; // ~0 if we are outside a {.|.|.} region, other #.
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000117
Chris Lattner1cf9d962006-02-01 19:12:23 +0000118 // NOTE: Any extensions to this code need to be mirrored in the
119 // AsmPrinter::printInlineAsm code that executes as compile time (assuming
120 // that inline asm strings should also get the new feature)!
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000121 const std::string &AsmString = CGI.AsmString;
122 std::string::size_type LastEmitted = 0;
123 while (LastEmitted != AsmString.size()) {
124 std::string::size_type DollarPos =
Nate Begeman817affc2008-03-17 07:26:14 +0000125 AsmString.find_first_of("${|}\\", LastEmitted);
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000126 if (DollarPos == std::string::npos) DollarPos = AsmString.size();
127
128 // Emit a constant string fragment.
129 if (DollarPos != LastEmitted) {
130 // TODO: this should eventually handle escaping.
Chris Lattnerb03b0802006-02-06 22:43:28 +0000131 if (CurVariant == Variant || CurVariant == ~0U)
132 AddLiteralString(std::string(AsmString.begin()+LastEmitted,
133 AsmString.begin()+DollarPos));
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000134 LastEmitted = DollarPos;
Nate Begeman817affc2008-03-17 07:26:14 +0000135 } else if (AsmString[DollarPos] == '\\') {
136 if (DollarPos+1 != AsmString.size() &&
137 (CurVariant == Variant || CurVariant == ~0U)) {
138 if (AsmString[DollarPos+1] == 'n') {
139 AddLiteralString("\\n");
140 } else if (AsmString[DollarPos+1] == 't') {
141 AddLiteralString("\\t");
142 } else if (std::string("${|}\\").find(AsmString[DollarPos+1])
143 != std::string::npos) {
144 AddLiteralString(std::string(1, AsmString[DollarPos+1]));
145 } else {
146 throw "Non-supported escaped character found in instruction '" +
147 CGI.TheDef->getName() + "'!";
148 }
149 LastEmitted = DollarPos+2;
150 continue;
151 }
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000152 } else if (AsmString[DollarPos] == '{') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000153 if (CurVariant != ~0U)
Jeff Cohen00b168892005-07-27 06:12:32 +0000154 throw "Nested variants found for instruction '" +
Chris Lattner3e3def92005-07-15 22:43:04 +0000155 CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000156 LastEmitted = DollarPos+1;
Chris Lattnerb03b0802006-02-06 22:43:28 +0000157 CurVariant = 0; // We are now inside of the variant!
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000158 } else if (AsmString[DollarPos] == '|') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000159 if (CurVariant == ~0U)
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000160 throw "'|' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000161 + CGI.TheDef->getName() + "'!";
Chris Lattnerb03b0802006-02-06 22:43:28 +0000162 ++CurVariant;
163 ++LastEmitted;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000164 } else if (AsmString[DollarPos] == '}') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000165 if (CurVariant == ~0U)
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000166 throw "'}' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000167 + CGI.TheDef->getName() + "'!";
Chris Lattnerb03b0802006-02-06 22:43:28 +0000168 ++LastEmitted;
169 CurVariant = ~0U;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000170 } else if (DollarPos+1 != AsmString.size() &&
171 AsmString[DollarPos+1] == '$') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000172 if (CurVariant == Variant || CurVariant == ~0U)
173 AddLiteralString("$"); // "$$" -> $
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000174 LastEmitted = DollarPos+2;
175 } else {
176 // Get the name of the variable.
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000177 std::string::size_type VarEnd = DollarPos+1;
Nate Begemanafc54562005-07-14 22:50:30 +0000178
179 // handle ${foo}bar as $foo by detecting whether the character following
180 // the dollar sign is a curly brace. If so, advance VarEnd and DollarPos
181 // so the variable name does not contain the leading curly brace.
182 bool hasCurlyBraces = false;
183 if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
184 hasCurlyBraces = true;
185 ++DollarPos;
186 ++VarEnd;
187 }
188
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000189 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
190 ++VarEnd;
191 std::string VarName(AsmString.begin()+DollarPos+1,
192 AsmString.begin()+VarEnd);
Nate Begemanafc54562005-07-14 22:50:30 +0000193
Chris Lattner04cadb32006-02-06 23:40:48 +0000194 // Modifier - Support ${foo:modifier} syntax, where "modifier" is passed
Chris Lattner1bf63612006-09-26 23:45:08 +0000195 // into printOperand. Also support ${:feature}, which is passed into
Chris Lattner16f046a2006-09-26 23:47:10 +0000196 // PrintSpecial.
Chris Lattner04cadb32006-02-06 23:40:48 +0000197 std::string Modifier;
198
Nate Begemanafc54562005-07-14 22:50:30 +0000199 // In order to avoid starting the next string at the terminating curly
200 // brace, advance the end position past it if we found an opening curly
201 // brace.
202 if (hasCurlyBraces) {
203 if (VarEnd >= AsmString.size())
204 throw "Reached end of string before terminating curly brace in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000205 + CGI.TheDef->getName() + "'";
Chris Lattner04cadb32006-02-06 23:40:48 +0000206
207 // Look for a modifier string.
208 if (AsmString[VarEnd] == ':') {
209 ++VarEnd;
210 if (VarEnd >= AsmString.size())
211 throw "Reached end of string before terminating curly brace in '"
212 + CGI.TheDef->getName() + "'";
213
214 unsigned ModifierStart = VarEnd;
215 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
216 ++VarEnd;
217 Modifier = std::string(AsmString.begin()+ModifierStart,
218 AsmString.begin()+VarEnd);
219 if (Modifier.empty())
220 throw "Bad operand modifier name in '"+ CGI.TheDef->getName() + "'";
221 }
222
Nate Begemanafc54562005-07-14 22:50:30 +0000223 if (AsmString[VarEnd] != '}')
Chris Lattnerb03b0802006-02-06 22:43:28 +0000224 throw "Variable name beginning with '{' did not end with '}' in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000225 + CGI.TheDef->getName() + "'";
Nate Begemanafc54562005-07-14 22:50:30 +0000226 ++VarEnd;
227 }
Chris Lattner1bf63612006-09-26 23:45:08 +0000228 if (VarName.empty() && Modifier.empty())
Jeff Cohen00b168892005-07-27 06:12:32 +0000229 throw "Stray '$' in '" + CGI.TheDef->getName() +
Chris Lattner3e3def92005-07-15 22:43:04 +0000230 "' asm string, maybe you want $$?";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000231
Chris Lattner1bf63612006-09-26 23:45:08 +0000232 if (VarName.empty()) {
Chris Lattner16f046a2006-09-26 23:47:10 +0000233 // Just a modifier, pass this into PrintSpecial.
234 Operands.push_back(AsmWriterOperand("PrintSpecial", ~0U, Modifier));
Chris Lattner1bf63612006-09-26 23:45:08 +0000235 } else {
236 // Otherwise, normal operand.
237 unsigned OpNo = CGI.getOperandNamed(VarName);
238 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000239
Chris Lattnerf64f9a42006-11-15 23:23:02 +0000240 if (CurVariant == Variant || CurVariant == ~0U) {
241 unsigned MIOp = OpInfo.MIOperandNo;
Chris Lattner1bf63612006-09-26 23:45:08 +0000242 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp,
243 Modifier));
Chris Lattnerf64f9a42006-11-15 23:23:02 +0000244 }
Chris Lattner1bf63612006-09-26 23:45:08 +0000245 }
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000246 LastEmitted = VarEnd;
247 }
248 }
249
250 AddLiteralString("\\n");
251}
252
Chris Lattnerf8766682005-01-22 19:22:23 +0000253/// MatchesAllButOneOp - If this instruction is exactly identical to the
254/// specified instruction except for one differing operand, return the differing
255/// operand number. If more than one operand mismatches, return ~1, otherwise
256/// if the instructions are identical return ~0.
257unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
258 if (Operands.size() != Other.Operands.size()) return ~1;
Chris Lattner870c0162005-01-22 18:38:13 +0000259
260 unsigned MismatchOperand = ~0U;
261 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +0000262 if (Operands[i] != Other.Operands[i]) {
Chris Lattnerf8766682005-01-22 19:22:23 +0000263 if (MismatchOperand != ~0U) // Already have one mismatch?
264 return ~1U;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000265 else
Chris Lattner870c0162005-01-22 18:38:13 +0000266 MismatchOperand = i;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +0000267 }
Chris Lattner870c0162005-01-22 18:38:13 +0000268 }
269 return MismatchOperand;
270}
271
Chris Lattner38c07512005-01-22 20:31:17 +0000272static void PrintCases(std::vector<std::pair<std::string,
273 AsmWriterOperand> > &OpsToPrint, std::ostream &O) {
274 O << " case " << OpsToPrint.back().first << ": ";
275 AsmWriterOperand TheOp = OpsToPrint.back().second;
276 OpsToPrint.pop_back();
277
278 // Check to see if any other operands are identical in this list, and if so,
279 // emit a case label for them.
280 for (unsigned i = OpsToPrint.size(); i != 0; --i)
281 if (OpsToPrint[i-1].second == TheOp) {
282 O << "\n case " << OpsToPrint[i-1].first << ": ";
283 OpsToPrint.erase(OpsToPrint.begin()+i-1);
284 }
285
286 // Finally, emit the code.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000287 O << TheOp.getCode();
Chris Lattner38c07512005-01-22 20:31:17 +0000288 O << "break;\n";
289}
290
Chris Lattner870c0162005-01-22 18:38:13 +0000291
292/// EmitInstructions - Emit the last instruction in the vector and any other
293/// instructions that are suitably similar to it.
294static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
295 std::ostream &O) {
296 AsmWriterInst FirstInst = Insts.back();
297 Insts.pop_back();
298
299 std::vector<AsmWriterInst> SimilarInsts;
300 unsigned DifferingOperand = ~0;
301 for (unsigned i = Insts.size(); i != 0; --i) {
Chris Lattnerf8766682005-01-22 19:22:23 +0000302 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
303 if (DiffOp != ~1U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000304 if (DifferingOperand == ~0U) // First match!
305 DifferingOperand = DiffOp;
306
307 // If this differs in the same operand as the rest of the instructions in
308 // this class, move it to the SimilarInsts list.
Chris Lattnerf8766682005-01-22 19:22:23 +0000309 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000310 SimilarInsts.push_back(Insts[i-1]);
311 Insts.erase(Insts.begin()+i-1);
312 }
313 }
314 }
315
Chris Lattnera1e8a802006-05-01 17:01:17 +0000316 O << " case " << FirstInst.CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000317 << FirstInst.CGI->TheDef->getName() << ":\n";
318 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
Chris Lattnera1e8a802006-05-01 17:01:17 +0000319 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000320 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
321 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
322 if (i != DifferingOperand) {
323 // If the operand is the same for all instructions, just print it.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000324 O << " " << FirstInst.Operands[i].getCode();
Chris Lattner870c0162005-01-22 18:38:13 +0000325 } else {
326 // If this is the operand that varies between all of the instructions,
327 // emit a switch for just this operand now.
328 O << " switch (MI->getOpcode()) {\n";
Chris Lattner38c07512005-01-22 20:31:17 +0000329 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
Chris Lattnera1e8a802006-05-01 17:01:17 +0000330 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
Chris Lattner38c07512005-01-22 20:31:17 +0000331 FirstInst.CGI->TheDef->getName(),
332 FirstInst.Operands[i]));
Misha Brukman3da94ae2005-04-22 00:00:37 +0000333
Chris Lattner870c0162005-01-22 18:38:13 +0000334 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
Chris Lattner38c07512005-01-22 20:31:17 +0000335 AsmWriterInst &AWI = SimilarInsts[si];
Chris Lattnera1e8a802006-05-01 17:01:17 +0000336 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
Chris Lattner38c07512005-01-22 20:31:17 +0000337 AWI.CGI->TheDef->getName(),
338 AWI.Operands[i]));
Chris Lattner870c0162005-01-22 18:38:13 +0000339 }
Chris Lattner38c07512005-01-22 20:31:17 +0000340 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
341 while (!OpsToPrint.empty())
342 PrintCases(OpsToPrint, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000343 O << " }";
344 }
345 O << "\n";
346 }
347
348 O << " break;\n";
349}
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000350
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000351void AsmWriterEmitter::
352FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
Chris Lattner96c1ade2006-07-18 18:28:27 +0000353 std::vector<unsigned> &InstIdxs,
354 std::vector<unsigned> &InstOpsUsed) const {
Chris Lattner195bb4a2006-07-18 19:27:30 +0000355 InstIdxs.assign(NumberedInstructions.size(), ~0U);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000356
357 // This vector parallels UniqueOperandCommands, keeping track of which
358 // instructions each case are used for. It is a comma separated string of
359 // enums.
360 std::vector<std::string> InstrsForCase;
361 InstrsForCase.resize(UniqueOperandCommands.size());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000362 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000363
364 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
365 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
Dan Gohman44066042008-07-01 00:05:16 +0000366 if (Inst == 0) continue; // PHI, INLINEASM, DBG_LABEL, etc.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000367
368 std::string Command;
Chris Lattnerb8462862006-07-18 17:56:07 +0000369 if (Inst->Operands.empty())
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000370 continue; // Instruction already done.
Chris Lattner191dd1f2006-07-18 17:50:22 +0000371
Chris Lattnerb8462862006-07-18 17:56:07 +0000372 Command = " " + Inst->Operands[0].getCode() + "\n";
Chris Lattner191dd1f2006-07-18 17:50:22 +0000373
374 // If this is the last operand, emit a return.
Chris Lattnerb8462862006-07-18 17:56:07 +0000375 if (Inst->Operands.size() == 1)
Chris Lattner191dd1f2006-07-18 17:50:22 +0000376 Command += " return true;\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000377
378 // Check to see if we already have 'Command' in UniqueOperandCommands.
379 // If not, add it.
380 bool FoundIt = false;
381 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
382 if (UniqueOperandCommands[idx] == Command) {
383 InstIdxs[i] = idx;
384 InstrsForCase[idx] += ", ";
385 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
386 FoundIt = true;
387 break;
388 }
389 if (!FoundIt) {
390 InstIdxs[i] = UniqueOperandCommands.size();
391 UniqueOperandCommands.push_back(Command);
392 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000393
394 // This command matches one operand so far.
395 InstOpsUsed.push_back(1);
396 }
397 }
398
399 // For each entry of UniqueOperandCommands, there is a set of instructions
400 // that uses it. If the next command of all instructions in the set are
401 // identical, fold it into the command.
402 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
403 CommandIdx != e; ++CommandIdx) {
404
405 for (unsigned Op = 1; ; ++Op) {
406 // Scan for the first instruction in the set.
407 std::vector<unsigned>::iterator NIT =
408 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
409 if (NIT == InstIdxs.end()) break; // No commonality.
410
411 // If this instruction has no more operands, we isn't anything to merge
412 // into this command.
413 const AsmWriterInst *FirstInst =
414 getAsmWriterInstByID(NIT-InstIdxs.begin());
415 if (!FirstInst || FirstInst->Operands.size() == Op)
416 break;
417
418 // Otherwise, scan to see if all of the other instructions in this command
419 // set share the operand.
420 bool AllSame = true;
421
Chris Lattner96c1ade2006-07-18 18:28:27 +0000422 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
423 NIT != InstIdxs.end();
424 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
425 // Okay, found another instruction in this command set. If the operand
426 // matches, we're ok, otherwise bail out.
427 const AsmWriterInst *OtherInst =
428 getAsmWriterInstByID(NIT-InstIdxs.begin());
429 if (!OtherInst || OtherInst->Operands.size() == Op ||
430 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
431 AllSame = false;
432 break;
433 }
434 }
435 if (!AllSame) break;
436
437 // Okay, everything in this command set has the same next operand. Add it
438 // to UniqueOperandCommands and remember that it was consumed.
439 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
440
441 // If this is the last operand, emit a return after the code.
442 if (FirstInst->Operands.size() == Op+1)
443 Command += " return true;\n";
444
445 UniqueOperandCommands[CommandIdx] += Command;
446 InstOpsUsed[CommandIdx]++;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000447 }
448 }
449
450 // Prepend some of the instructions each case is used for onto the case val.
451 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
452 std::string Instrs = InstrsForCase[i];
453 if (Instrs.size() > 70) {
454 Instrs.erase(Instrs.begin()+70, Instrs.end());
455 Instrs += "...";
456 }
457
458 if (!Instrs.empty())
459 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
460 UniqueOperandCommands[i];
461 }
462}
463
464
465
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000466void AsmWriterEmitter::run(std::ostream &O) {
467 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
468
469 CodeGenTarget Target;
Chris Lattner175580c2004-08-14 22:50:53 +0000470 Record *AsmWriter = Target.getAsmWriter();
Chris Lattner953c6fe2004-10-03 20:19:02 +0000471 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
472 unsigned Variant = AsmWriter->getValueAsInt("Variant");
Chris Lattner175580c2004-08-14 22:50:53 +0000473
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000474 O <<
475 "/// printInstruction - This method is automatically generated by tablegen\n"
476 "/// from the instruction set description. This method returns true if the\n"
477 "/// machine instruction was sufficiently described to print it, otherwise\n"
478 "/// it returns false.\n"
Chris Lattner953c6fe2004-10-03 20:19:02 +0000479 "bool " << Target.getName() << ClassName
Chris Lattner175580c2004-08-14 22:50:53 +0000480 << "::printInstruction(const MachineInstr *MI) {\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000481
Chris Lattner5765dba2005-01-22 17:40:38 +0000482 std::vector<AsmWriterInst> Instructions;
483
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000484 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
485 E = Target.inst_end(); I != E; ++I)
Chris Lattner5765dba2005-01-22 17:40:38 +0000486 if (!I->second.AsmString.empty())
487 Instructions.push_back(AsmWriterInst(I->second, Variant));
Chris Lattner076efa72004-08-01 07:43:02 +0000488
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000489 // Get the instruction numbering.
Chris Lattner0cfcc1e2006-01-27 02:10:50 +0000490 Target.getInstructionsByEnumValue(NumberedInstructions);
491
Chris Lattner6af022f2006-07-14 22:59:11 +0000492 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
493 // all machine instructions are necessarily being printed, so there may be
494 // target instructions not in this map.
Chris Lattner6af022f2006-07-14 22:59:11 +0000495 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
496 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
Chris Lattnerf8766682005-01-22 19:22:23 +0000497
Chris Lattner6af022f2006-07-14 22:59:11 +0000498 // Build an aggregate string, and build a table of offsets into it.
499 std::map<std::string, unsigned> StringOffset;
500 std::string AggregateString;
Chris Lattner259bda42006-09-27 16:44:09 +0000501 AggregateString.push_back(0); // "\0"
502 AggregateString.push_back(0); // "\0"
Chris Lattner6af022f2006-07-14 22:59:11 +0000503
Chris Lattner259bda42006-09-27 16:44:09 +0000504 /// OpcodeInfo - This encodes the index of the string to use for the first
Chris Lattner55616402006-07-18 17:32:27 +0000505 /// chunk of the output as well as indices used for operand printing.
506 std::vector<unsigned> OpcodeInfo;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000507
Chris Lattner55616402006-07-18 17:32:27 +0000508 unsigned MaxStringIdx = 0;
Chris Lattner6af022f2006-07-14 22:59:11 +0000509 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
510 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
511 unsigned Idx;
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000512 if (AWI == 0) {
Chris Lattner6af022f2006-07-14 22:59:11 +0000513 // Something not handled by the asmwriter printer.
514 Idx = 0;
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000515 } else if (AWI->Operands[0].OperandType !=
516 AsmWriterOperand::isLiteralTextOperand ||
517 AWI->Operands[0].Str.empty()) {
518 // Something handled by the asmwriter printer, but with no leading string.
519 Idx = 1;
Chris Lattner6af022f2006-07-14 22:59:11 +0000520 } else {
521 unsigned &Entry = StringOffset[AWI->Operands[0].Str];
522 if (Entry == 0) {
523 // Add the string to the aggregate if this is the first time found.
Chris Lattner55616402006-07-18 17:32:27 +0000524 MaxStringIdx = Entry = AggregateString.size();
Chris Lattner6af022f2006-07-14 22:59:11 +0000525 std::string Str = AWI->Operands[0].Str;
526 UnescapeString(Str);
527 AggregateString += Str;
528 AggregateString += '\0';
Chris Lattnerf8766682005-01-22 19:22:23 +0000529 }
Chris Lattner6af022f2006-07-14 22:59:11 +0000530 Idx = Entry;
Chris Lattner6af022f2006-07-14 22:59:11 +0000531
532 // Nuke the string from the operand list. It is now handled!
533 AWI->Operands.erase(AWI->Operands.begin());
Chris Lattnerf8766682005-01-22 19:22:23 +0000534 }
Chris Lattner55616402006-07-18 17:32:27 +0000535 OpcodeInfo.push_back(Idx);
Chris Lattnerf8766682005-01-22 19:22:23 +0000536 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000537
Chris Lattner55616402006-07-18 17:32:27 +0000538 // Figure out how many bits we used for the string index.
Nate Begeman59d28132008-04-09 16:24:11 +0000539 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+1);
Chris Lattner55616402006-07-18 17:32:27 +0000540
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000541 // To reduce code size, we compactify common instructions into a few bits
542 // in the opcode-indexed table.
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000543 unsigned BitsLeft = 32-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000544
545 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
546
Chris Lattnerb8462862006-07-18 17:56:07 +0000547 bool isFirst = true;
548 while (1) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000549 std::vector<std::string> UniqueOperandCommands;
550
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000551 // For the first operand check, add a default value for instructions with
552 // just opcode strings to use.
Chris Lattnerb8462862006-07-18 17:56:07 +0000553 if (isFirst) {
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000554 UniqueOperandCommands.push_back(" return true;\n");
Chris Lattnerb8462862006-07-18 17:56:07 +0000555 isFirst = false;
556 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000557
558 std::vector<unsigned> InstIdxs;
Chris Lattner96c1ade2006-07-18 18:28:27 +0000559 std::vector<unsigned> NumInstOpsHandled;
560 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
561 NumInstOpsHandled);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000562
563 // If we ran out of operands to print, we're done.
564 if (UniqueOperandCommands.empty()) break;
565
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000566 // Compute the number of bits we need to represent these cases, this is
567 // ceil(log2(numentries)).
568 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
569
570 // If we don't have enough bits for this operand, don't include it.
571 if (NumBits > BitsLeft) {
Bill Wendlingf5da1332006-12-07 22:21:48 +0000572 DOUT << "Not enough bits to densely encode " << NumBits
573 << " more bits\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000574 break;
575 }
576
577 // Otherwise, we can include this in the initial lookup table. Add it in.
578 BitsLeft -= NumBits;
579 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
Chris Lattner195bb4a2006-07-18 19:27:30 +0000580 if (InstIdxs[i] != ~0U)
581 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000582
Chris Lattnerb8462862006-07-18 17:56:07 +0000583 // Remove the info about this operand.
584 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
585 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
Chris Lattner96c1ade2006-07-18 18:28:27 +0000586 if (!Inst->Operands.empty()) {
587 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
Chris Lattner0a012122006-07-18 19:06:01 +0000588 assert(NumOps <= Inst->Operands.size() &&
589 "Can't remove this many ops!");
Chris Lattner96c1ade2006-07-18 18:28:27 +0000590 Inst->Operands.erase(Inst->Operands.begin(),
591 Inst->Operands.begin()+NumOps);
592 }
Chris Lattnerb8462862006-07-18 17:56:07 +0000593 }
594
595 // Remember the handlers for this set of operands.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000596 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
597 }
598
599
600
Chris Lattner55616402006-07-18 17:32:27 +0000601 O<<" static const unsigned OpInfo[] = {\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000602 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000603 O << " " << OpcodeInfo[i] << "U,\t// "
Chris Lattner55616402006-07-18 17:32:27 +0000604 << NumberedInstructions[i]->TheDef->getName() << "\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000605 }
606 // Add a dummy entry so the array init doesn't end with a comma.
Chris Lattner55616402006-07-18 17:32:27 +0000607 O << " 0U\n";
Chris Lattner6af022f2006-07-14 22:59:11 +0000608 O << " };\n\n";
609
610 // Emit the string itself.
611 O << " const char *AsmStrs = \n \"";
612 unsigned CharsPrinted = 0;
613 EscapeString(AggregateString);
614 for (unsigned i = 0, e = AggregateString.size(); i != e; ++i) {
615 if (CharsPrinted > 70) {
616 O << "\"\n \"";
617 CharsPrinted = 0;
618 }
619 O << AggregateString[i];
620 ++CharsPrinted;
621
622 // Print escape sequences all together.
623 if (AggregateString[i] == '\\') {
624 assert(i+1 < AggregateString.size() && "Incomplete escape sequence!");
625 if (isdigit(AggregateString[i+1])) {
626 assert(isdigit(AggregateString[i+2]) && isdigit(AggregateString[i+3]) &&
627 "Expected 3 digit octal escape!");
628 O << AggregateString[++i];
629 O << AggregateString[++i];
630 O << AggregateString[++i];
631 CharsPrinted += 3;
632 } else {
633 O << AggregateString[++i];
634 ++CharsPrinted;
635 }
636 }
637 }
638 O << "\";\n\n";
639
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000640 O << " if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {\n"
Evan Cheng4eecdeb2008-02-02 08:39:46 +0000641 << " O << \"\\t\";\n"
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000642 << " printInlineAsm(MI);\n"
643 << " return true;\n"
Dan Gohman44066042008-07-01 00:05:16 +0000644 << " } else if (MI->isLabel()) {\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +0000645 << " printLabel(MI);\n"
646 << " return true;\n"
Evan Chenga844bde2008-02-02 04:07:54 +0000647 << " } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {\n"
648 << " printDeclare(MI);\n"
649 << " return true;\n"
Evan Chengda47e6e2008-03-15 00:03:38 +0000650 << " } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {\n"
651 << " printImplicitDef(MI);\n"
652 << " return true;\n"
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000653 << " }\n\n";
654
Evan Cheng4eecdeb2008-02-02 08:39:46 +0000655 O << " O << \"\\t\";\n\n";
656
Chris Lattner6af022f2006-07-14 22:59:11 +0000657 O << " // Emit the opcode for the instruction.\n"
Chris Lattner55616402006-07-18 17:32:27 +0000658 << " unsigned Bits = OpInfo[MI->getOpcode()];\n"
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000659 << " if (Bits == 0) return false;\n"
Chris Lattner55616402006-07-18 17:32:27 +0000660 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ");\n\n";
Chris Lattnerf8766682005-01-22 19:22:23 +0000661
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000662 // Output the table driven operand information.
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000663 BitsLeft = 32-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000664 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
665 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
666
667 // Compute the number of bits we need to represent these cases, this is
668 // ceil(log2(numentries)).
669 unsigned NumBits = Log2_32_Ceil(Commands.size());
670 assert(NumBits <= BitsLeft && "consistency error");
671
672 // Emit code to extract this field from Bits.
673 BitsLeft -= NumBits;
674
675 O << "\n // Fragment " << i << " encoded into " << NumBits
Chris Lattnere7a589d2006-07-18 17:43:54 +0000676 << " bits for " << Commands.size() << " unique commands.\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000677
Chris Lattner96c1ade2006-07-18 18:28:27 +0000678 if (Commands.size() == 2) {
Chris Lattnere7a589d2006-07-18 17:43:54 +0000679 // Emit two possibilitys with if/else.
680 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
681 << ((1 << NumBits)-1) << ") {\n"
682 << Commands[1]
683 << " } else {\n"
684 << Commands[0]
685 << " }\n\n";
686 } else {
687 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
688 << ((1 << NumBits)-1) << ") {\n"
689 << " default: // unreachable.\n";
690
691 // Print out all the cases.
692 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
693 O << " case " << i << ":\n";
694 O << Commands[i];
695 O << " break;\n";
696 }
697 O << " }\n\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000698 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000699 }
700
Chris Lattnerb8462862006-07-18 17:56:07 +0000701 // Okay, delete instructions with no operand info left.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000702 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
703 // Entire instruction has been emitted?
704 AsmWriterInst &Inst = Instructions[i];
Chris Lattnerb8462862006-07-18 17:56:07 +0000705 if (Inst.Operands.empty()) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000706 Instructions.erase(Instructions.begin()+i);
Chris Lattnerb8462862006-07-18 17:56:07 +0000707 --i; --e;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000708 }
709 }
710
711
712 // Because this is a vector, we want to emit from the end. Reverse all of the
Chris Lattner870c0162005-01-22 18:38:13 +0000713 // elements in the vector.
714 std::reverse(Instructions.begin(), Instructions.end());
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000715
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000716 if (!Instructions.empty()) {
717 // Find the opcode # of inline asm.
718 O << " switch (MI->getOpcode()) {\n";
719 while (!Instructions.empty())
720 EmitInstructions(Instructions, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000721
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000722 O << " }\n";
Chris Lattner0a012122006-07-18 19:06:01 +0000723 O << " return true;\n";
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000724 }
725
Chris Lattner0a012122006-07-18 19:06:01 +0000726 O << "}\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000727}