blob: d8e983940789c237222fa59d5cddd08cea8b9ad9 [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"
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 +000022#include <ostream>
23using namespace llvm;
24
Chris Lattner076efa72004-08-01 07:43:02 +000025static bool isIdentChar(char C) {
26 return (C >= 'a' && C <= 'z') ||
27 (C >= 'A' && C <= 'Z') ||
28 (C >= '0' && C <= '9') ||
29 C == '_';
30}
31
Chris Lattnerb0b55e72005-01-22 17:32:42 +000032namespace {
33 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 {
Chris Lattnerb0b55e72005-01-22 17:32:42 +000072 struct AsmWriterInst {
73 std::vector<AsmWriterOperand> Operands;
Chris Lattner5765dba2005-01-22 17:40:38 +000074 const CodeGenInstruction *CGI;
Misha Brukman3da94ae2005-04-22 00:00:37 +000075
Chris Lattner5765dba2005-01-22 17:40:38 +000076 AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
Chris Lattner870c0162005-01-22 18:38:13 +000077
Chris Lattnerf8766682005-01-22 19:22:23 +000078 /// MatchesAllButOneOp - If this instruction is exactly identical to the
79 /// specified instruction except for one differing operand, return the
80 /// differing operand number. Otherwise return ~0.
81 unsigned MatchesAllButOneOp(const AsmWriterInst &Other) const;
Chris Lattner870c0162005-01-22 18:38:13 +000082
Chris Lattnerb0b55e72005-01-22 17:32:42 +000083 private:
84 void AddLiteralString(const std::string &Str) {
85 // If the last operand was already a literal text string, append this to
86 // it, otherwise add a new operand.
87 if (!Operands.empty() &&
88 Operands.back().OperandType == AsmWriterOperand::isLiteralTextOperand)
89 Operands.back().Str.append(Str);
90 else
91 Operands.push_back(AsmWriterOperand(Str));
92 }
93 };
94}
95
96
Chris Lattnerbdff5f92006-07-18 17:18:03 +000097std::string AsmWriterOperand::getCode() const {
Chris Lattnerb0b55e72005-01-22 17:32:42 +000098 if (OperandType == isLiteralTextOperand)
Chris Lattnerbdff5f92006-07-18 17:18:03 +000099 return "O << \"" + Str + "\"; ";
100
101 std::string Result = Str + "(MI, " + utostr(MIOpNo);
102 if (!MiModifier.empty())
103 Result += ", \"" + MiModifier + '"';
104 return Result + "); ";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000105}
106
107
108/// ParseAsmString - Parse the specified Instruction's AsmString into this
109/// AsmWriterInst.
110///
Chris Lattner5765dba2005-01-22 17:40:38 +0000111AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
112 this->CGI = &CGI;
Chris Lattnerb03b0802006-02-06 22:43:28 +0000113 unsigned CurVariant = ~0U; // ~0 if we are outside a {.|.|.} region, other #.
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000114
Chris Lattner1cf9d962006-02-01 19:12:23 +0000115 // NOTE: Any extensions to this code need to be mirrored in the
116 // AsmPrinter::printInlineAsm code that executes as compile time (assuming
117 // that inline asm strings should also get the new feature)!
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000118 const std::string &AsmString = CGI.AsmString;
119 std::string::size_type LastEmitted = 0;
120 while (LastEmitted != AsmString.size()) {
121 std::string::size_type DollarPos =
122 AsmString.find_first_of("${|}", LastEmitted);
123 if (DollarPos == std::string::npos) DollarPos = AsmString.size();
124
125 // Emit a constant string fragment.
126 if (DollarPos != LastEmitted) {
127 // TODO: this should eventually handle escaping.
Chris Lattnerb03b0802006-02-06 22:43:28 +0000128 if (CurVariant == Variant || CurVariant == ~0U)
129 AddLiteralString(std::string(AsmString.begin()+LastEmitted,
130 AsmString.begin()+DollarPos));
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000131 LastEmitted = DollarPos;
132 } else if (AsmString[DollarPos] == '{') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000133 if (CurVariant != ~0U)
Jeff Cohen00b168892005-07-27 06:12:32 +0000134 throw "Nested variants found for instruction '" +
Chris Lattner3e3def92005-07-15 22:43:04 +0000135 CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000136 LastEmitted = DollarPos+1;
Chris Lattnerb03b0802006-02-06 22:43:28 +0000137 CurVariant = 0; // We are now inside of the variant!
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000138 } else if (AsmString[DollarPos] == '|') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000139 if (CurVariant == ~0U)
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000140 throw "'|' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000141 + CGI.TheDef->getName() + "'!";
Chris Lattnerb03b0802006-02-06 22:43:28 +0000142 ++CurVariant;
143 ++LastEmitted;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000144 } else if (AsmString[DollarPos] == '}') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000145 if (CurVariant == ~0U)
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000146 throw "'}' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000147 + CGI.TheDef->getName() + "'!";
Chris Lattnerb03b0802006-02-06 22:43:28 +0000148 ++LastEmitted;
149 CurVariant = ~0U;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000150 } else if (DollarPos+1 != AsmString.size() &&
151 AsmString[DollarPos+1] == '$') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000152 if (CurVariant == Variant || CurVariant == ~0U)
153 AddLiteralString("$"); // "$$" -> $
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000154 LastEmitted = DollarPos+2;
155 } else {
156 // Get the name of the variable.
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000157 std::string::size_type VarEnd = DollarPos+1;
Nate Begemanafc54562005-07-14 22:50:30 +0000158
159 // handle ${foo}bar as $foo by detecting whether the character following
160 // the dollar sign is a curly brace. If so, advance VarEnd and DollarPos
161 // so the variable name does not contain the leading curly brace.
162 bool hasCurlyBraces = false;
163 if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
164 hasCurlyBraces = true;
165 ++DollarPos;
166 ++VarEnd;
167 }
168
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000169 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
170 ++VarEnd;
171 std::string VarName(AsmString.begin()+DollarPos+1,
172 AsmString.begin()+VarEnd);
Nate Begemanafc54562005-07-14 22:50:30 +0000173
Chris Lattner04cadb32006-02-06 23:40:48 +0000174 // Modifier - Support ${foo:modifier} syntax, where "modifier" is passed
175 // into printOperand.
176 std::string Modifier;
177
Nate Begemanafc54562005-07-14 22:50:30 +0000178 // In order to avoid starting the next string at the terminating curly
179 // brace, advance the end position past it if we found an opening curly
180 // brace.
181 if (hasCurlyBraces) {
182 if (VarEnd >= AsmString.size())
183 throw "Reached end of string before terminating curly brace in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000184 + CGI.TheDef->getName() + "'";
Chris Lattner04cadb32006-02-06 23:40:48 +0000185
186 // Look for a modifier string.
187 if (AsmString[VarEnd] == ':') {
188 ++VarEnd;
189 if (VarEnd >= AsmString.size())
190 throw "Reached end of string before terminating curly brace in '"
191 + CGI.TheDef->getName() + "'";
192
193 unsigned ModifierStart = VarEnd;
194 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
195 ++VarEnd;
196 Modifier = std::string(AsmString.begin()+ModifierStart,
197 AsmString.begin()+VarEnd);
198 if (Modifier.empty())
199 throw "Bad operand modifier name in '"+ CGI.TheDef->getName() + "'";
200 }
201
Nate Begemanafc54562005-07-14 22:50:30 +0000202 if (AsmString[VarEnd] != '}')
Chris Lattnerb03b0802006-02-06 22:43:28 +0000203 throw "Variable name beginning with '{' did not end with '}' in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000204 + CGI.TheDef->getName() + "'";
Nate Begemanafc54562005-07-14 22:50:30 +0000205 ++VarEnd;
206 }
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000207 if (VarName.empty())
Jeff Cohen00b168892005-07-27 06:12:32 +0000208 throw "Stray '$' in '" + CGI.TheDef->getName() +
Chris Lattner3e3def92005-07-15 22:43:04 +0000209 "' asm string, maybe you want $$?";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000210
211 unsigned OpNo = CGI.getOperandNamed(VarName);
Chris Lattner5765dba2005-01-22 17:40:38 +0000212 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000213
214 // If this is a two-address instruction and we are not accessing the
215 // 0th operand, remove an operand.
Chris Lattner5765dba2005-01-22 17:40:38 +0000216 unsigned MIOp = OpInfo.MIOperandNo;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000217 if (CGI.isTwoAddress && MIOp != 0) {
218 if (MIOp == 1)
219 throw "Should refer to operand #0 instead of #1 for two-address"
Chris Lattner3e3def92005-07-15 22:43:04 +0000220 " instruction '" + CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000221 --MIOp;
222 }
223
Chris Lattnerb03b0802006-02-06 22:43:28 +0000224 if (CurVariant == Variant || CurVariant == ~0U)
Chris Lattner04cadb32006-02-06 23:40:48 +0000225 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp,
226 Modifier));
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000227 LastEmitted = VarEnd;
228 }
229 }
230
231 AddLiteralString("\\n");
232}
233
Chris Lattnerf8766682005-01-22 19:22:23 +0000234/// MatchesAllButOneOp - If this instruction is exactly identical to the
235/// specified instruction except for one differing operand, return the differing
236/// operand number. If more than one operand mismatches, return ~1, otherwise
237/// if the instructions are identical return ~0.
238unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
239 if (Operands.size() != Other.Operands.size()) return ~1;
Chris Lattner870c0162005-01-22 18:38:13 +0000240
241 unsigned MismatchOperand = ~0U;
242 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Chris Lattner870c0162005-01-22 18:38:13 +0000243 if (Operands[i] != Other.Operands[i])
Chris Lattnerf8766682005-01-22 19:22:23 +0000244 if (MismatchOperand != ~0U) // Already have one mismatch?
245 return ~1U;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000246 else
Chris Lattner870c0162005-01-22 18:38:13 +0000247 MismatchOperand = i;
248 }
249 return MismatchOperand;
250}
251
Chris Lattner38c07512005-01-22 20:31:17 +0000252static void PrintCases(std::vector<std::pair<std::string,
253 AsmWriterOperand> > &OpsToPrint, std::ostream &O) {
254 O << " case " << OpsToPrint.back().first << ": ";
255 AsmWriterOperand TheOp = OpsToPrint.back().second;
256 OpsToPrint.pop_back();
257
258 // Check to see if any other operands are identical in this list, and if so,
259 // emit a case label for them.
260 for (unsigned i = OpsToPrint.size(); i != 0; --i)
261 if (OpsToPrint[i-1].second == TheOp) {
262 O << "\n case " << OpsToPrint[i-1].first << ": ";
263 OpsToPrint.erase(OpsToPrint.begin()+i-1);
264 }
265
266 // Finally, emit the code.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000267 O << TheOp.getCode();
Chris Lattner38c07512005-01-22 20:31:17 +0000268 O << "break;\n";
269}
270
Chris Lattner870c0162005-01-22 18:38:13 +0000271
272/// EmitInstructions - Emit the last instruction in the vector and any other
273/// instructions that are suitably similar to it.
274static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
275 std::ostream &O) {
276 AsmWriterInst FirstInst = Insts.back();
277 Insts.pop_back();
278
279 std::vector<AsmWriterInst> SimilarInsts;
280 unsigned DifferingOperand = ~0;
281 for (unsigned i = Insts.size(); i != 0; --i) {
Chris Lattnerf8766682005-01-22 19:22:23 +0000282 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
283 if (DiffOp != ~1U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000284 if (DifferingOperand == ~0U) // First match!
285 DifferingOperand = DiffOp;
286
287 // If this differs in the same operand as the rest of the instructions in
288 // this class, move it to the SimilarInsts list.
Chris Lattnerf8766682005-01-22 19:22:23 +0000289 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000290 SimilarInsts.push_back(Insts[i-1]);
291 Insts.erase(Insts.begin()+i-1);
292 }
293 }
294 }
295
Chris Lattnera1e8a802006-05-01 17:01:17 +0000296 O << " case " << FirstInst.CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000297 << FirstInst.CGI->TheDef->getName() << ":\n";
298 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
Chris Lattnera1e8a802006-05-01 17:01:17 +0000299 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000300 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
301 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
302 if (i != DifferingOperand) {
303 // If the operand is the same for all instructions, just print it.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000304 O << " " << FirstInst.Operands[i].getCode();
Chris Lattner870c0162005-01-22 18:38:13 +0000305 } else {
306 // If this is the operand that varies between all of the instructions,
307 // emit a switch for just this operand now.
308 O << " switch (MI->getOpcode()) {\n";
Chris Lattner38c07512005-01-22 20:31:17 +0000309 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
Chris Lattnera1e8a802006-05-01 17:01:17 +0000310 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
Chris Lattner38c07512005-01-22 20:31:17 +0000311 FirstInst.CGI->TheDef->getName(),
312 FirstInst.Operands[i]));
Misha Brukman3da94ae2005-04-22 00:00:37 +0000313
Chris Lattner870c0162005-01-22 18:38:13 +0000314 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
Chris Lattner38c07512005-01-22 20:31:17 +0000315 AsmWriterInst &AWI = SimilarInsts[si];
Chris Lattnera1e8a802006-05-01 17:01:17 +0000316 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
Chris Lattner38c07512005-01-22 20:31:17 +0000317 AWI.CGI->TheDef->getName(),
318 AWI.Operands[i]));
Chris Lattner870c0162005-01-22 18:38:13 +0000319 }
Chris Lattner38c07512005-01-22 20:31:17 +0000320 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
321 while (!OpsToPrint.empty())
322 PrintCases(OpsToPrint, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000323 O << " }";
324 }
325 O << "\n";
326 }
327
328 O << " break;\n";
329}
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000330
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000331void AsmWriterEmitter::
332FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
Chris Lattner96c1ade2006-07-18 18:28:27 +0000333 std::vector<unsigned> &InstIdxs,
334 std::vector<unsigned> &InstOpsUsed) const {
335 InstIdxs.assign(NumberedInstructions.size(), 0);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000336
337 // This vector parallels UniqueOperandCommands, keeping track of which
338 // instructions each case are used for. It is a comma separated string of
339 // enums.
340 std::vector<std::string> InstrsForCase;
341 InstrsForCase.resize(UniqueOperandCommands.size());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000342 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000343
344 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
345 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
346 if (Inst == 0) continue; // PHI, INLINEASM, etc.
347
348 std::string Command;
Chris Lattnerb8462862006-07-18 17:56:07 +0000349 if (Inst->Operands.empty())
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000350 continue; // Instruction already done.
Chris Lattner191dd1f2006-07-18 17:50:22 +0000351
Chris Lattnerb8462862006-07-18 17:56:07 +0000352 Command = " " + Inst->Operands[0].getCode() + "\n";
Chris Lattner191dd1f2006-07-18 17:50:22 +0000353
354 // If this is the last operand, emit a return.
Chris Lattnerb8462862006-07-18 17:56:07 +0000355 if (Inst->Operands.size() == 1)
Chris Lattner191dd1f2006-07-18 17:50:22 +0000356 Command += " return true;\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000357
358 // Check to see if we already have 'Command' in UniqueOperandCommands.
359 // If not, add it.
360 bool FoundIt = false;
361 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
362 if (UniqueOperandCommands[idx] == Command) {
363 InstIdxs[i] = idx;
364 InstrsForCase[idx] += ", ";
365 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
366 FoundIt = true;
367 break;
368 }
369 if (!FoundIt) {
370 InstIdxs[i] = UniqueOperandCommands.size();
371 UniqueOperandCommands.push_back(Command);
372 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000373
374 // This command matches one operand so far.
375 InstOpsUsed.push_back(1);
376 }
377 }
378
379 // For each entry of UniqueOperandCommands, there is a set of instructions
380 // that uses it. If the next command of all instructions in the set are
381 // identical, fold it into the command.
382 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
383 CommandIdx != e; ++CommandIdx) {
384
385 for (unsigned Op = 1; ; ++Op) {
386 // Scan for the first instruction in the set.
387 std::vector<unsigned>::iterator NIT =
388 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
389 if (NIT == InstIdxs.end()) break; // No commonality.
390
391 // If this instruction has no more operands, we isn't anything to merge
392 // into this command.
393 const AsmWriterInst *FirstInst =
394 getAsmWriterInstByID(NIT-InstIdxs.begin());
395 if (!FirstInst || FirstInst->Operands.size() == Op)
396 break;
397
398 // Otherwise, scan to see if all of the other instructions in this command
399 // set share the operand.
400 bool AllSame = true;
401
Chris Lattner96c1ade2006-07-18 18:28:27 +0000402 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
403 NIT != InstIdxs.end();
404 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
405 // Okay, found another instruction in this command set. If the operand
406 // matches, we're ok, otherwise bail out.
407 const AsmWriterInst *OtherInst =
408 getAsmWriterInstByID(NIT-InstIdxs.begin());
409 if (!OtherInst || OtherInst->Operands.size() == Op ||
410 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
411 AllSame = false;
412 break;
413 }
414 }
415 if (!AllSame) break;
416
417 // Okay, everything in this command set has the same next operand. Add it
418 // to UniqueOperandCommands and remember that it was consumed.
419 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
420
421 // If this is the last operand, emit a return after the code.
422 if (FirstInst->Operands.size() == Op+1)
423 Command += " return true;\n";
424
425 UniqueOperandCommands[CommandIdx] += Command;
426 InstOpsUsed[CommandIdx]++;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000427 }
428 }
429
430 // Prepend some of the instructions each case is used for onto the case val.
431 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
432 std::string Instrs = InstrsForCase[i];
433 if (Instrs.size() > 70) {
434 Instrs.erase(Instrs.begin()+70, Instrs.end());
435 Instrs += "...";
436 }
437
438 if (!Instrs.empty())
439 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
440 UniqueOperandCommands[i];
441 }
442}
443
444
445
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000446void AsmWriterEmitter::run(std::ostream &O) {
447 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
448
449 CodeGenTarget Target;
Chris Lattner175580c2004-08-14 22:50:53 +0000450 Record *AsmWriter = Target.getAsmWriter();
Chris Lattner953c6fe2004-10-03 20:19:02 +0000451 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
452 unsigned Variant = AsmWriter->getValueAsInt("Variant");
Chris Lattner175580c2004-08-14 22:50:53 +0000453
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000454 O <<
455 "/// printInstruction - This method is automatically generated by tablegen\n"
456 "/// from the instruction set description. This method returns true if the\n"
457 "/// machine instruction was sufficiently described to print it, otherwise\n"
458 "/// it returns false.\n"
Chris Lattner953c6fe2004-10-03 20:19:02 +0000459 "bool " << Target.getName() << ClassName
Chris Lattner175580c2004-08-14 22:50:53 +0000460 << "::printInstruction(const MachineInstr *MI) {\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000461
Chris Lattner5765dba2005-01-22 17:40:38 +0000462 std::vector<AsmWriterInst> Instructions;
463
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000464 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
465 E = Target.inst_end(); I != E; ++I)
Chris Lattner5765dba2005-01-22 17:40:38 +0000466 if (!I->second.AsmString.empty())
467 Instructions.push_back(AsmWriterInst(I->second, Variant));
Chris Lattner076efa72004-08-01 07:43:02 +0000468
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000469 // Get the instruction numbering.
Chris Lattner0cfcc1e2006-01-27 02:10:50 +0000470 Target.getInstructionsByEnumValue(NumberedInstructions);
471
Chris Lattner6af022f2006-07-14 22:59:11 +0000472 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
473 // all machine instructions are necessarily being printed, so there may be
474 // target instructions not in this map.
Chris Lattner6af022f2006-07-14 22:59:11 +0000475 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
476 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
Chris Lattnerf8766682005-01-22 19:22:23 +0000477
Chris Lattner6af022f2006-07-14 22:59:11 +0000478 // Build an aggregate string, and build a table of offsets into it.
479 std::map<std::string, unsigned> StringOffset;
480 std::string AggregateString;
481 AggregateString += '\0';
482
Chris Lattner55616402006-07-18 17:32:27 +0000483 /// OpcodeInfo - Theis encodes the index of the string to use for the first
484 /// chunk of the output as well as indices used for operand printing.
485 std::vector<unsigned> OpcodeInfo;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000486
Chris Lattner55616402006-07-18 17:32:27 +0000487 unsigned MaxStringIdx = 0;
Chris Lattner6af022f2006-07-14 22:59:11 +0000488 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
489 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
490 unsigned Idx;
491 if (AWI == 0 || AWI->Operands[0].Str.empty()) {
492 // Something not handled by the asmwriter printer.
493 Idx = 0;
494 } else {
495 unsigned &Entry = StringOffset[AWI->Operands[0].Str];
496 if (Entry == 0) {
497 // Add the string to the aggregate if this is the first time found.
Chris Lattner55616402006-07-18 17:32:27 +0000498 MaxStringIdx = Entry = AggregateString.size();
Chris Lattner6af022f2006-07-14 22:59:11 +0000499 std::string Str = AWI->Operands[0].Str;
500 UnescapeString(Str);
501 AggregateString += Str;
502 AggregateString += '\0';
Chris Lattnerf8766682005-01-22 19:22:23 +0000503 }
Chris Lattner6af022f2006-07-14 22:59:11 +0000504 Idx = Entry;
Chris Lattner6af022f2006-07-14 22:59:11 +0000505
506 // Nuke the string from the operand list. It is now handled!
507 AWI->Operands.erase(AWI->Operands.begin());
Chris Lattnerf8766682005-01-22 19:22:23 +0000508 }
Chris Lattner55616402006-07-18 17:32:27 +0000509 OpcodeInfo.push_back(Idx);
Chris Lattnerf8766682005-01-22 19:22:23 +0000510 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000511
Chris Lattner55616402006-07-18 17:32:27 +0000512 // Figure out how many bits we used for the string index.
513 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx);
514
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000515 // To reduce code size, we compactify common instructions into a few bits
516 // in the opcode-indexed table.
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000517 unsigned BitsLeft = 32-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000518
519 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
520
Chris Lattnerb8462862006-07-18 17:56:07 +0000521 bool isFirst = true;
522 while (1) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000523 std::vector<std::string> UniqueOperandCommands;
524
525 // For the first operand check, add a default value that unhandled
526 // instructions will use.
Chris Lattnerb8462862006-07-18 17:56:07 +0000527 if (isFirst) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000528 UniqueOperandCommands.push_back(" return false;\n");
Chris Lattnerb8462862006-07-18 17:56:07 +0000529 isFirst = false;
530 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000531
532 std::vector<unsigned> InstIdxs;
Chris Lattner96c1ade2006-07-18 18:28:27 +0000533 std::vector<unsigned> NumInstOpsHandled;
534 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
535 NumInstOpsHandled);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000536
537 // If we ran out of operands to print, we're done.
538 if (UniqueOperandCommands.empty()) break;
539
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000540 // Compute the number of bits we need to represent these cases, this is
541 // ceil(log2(numentries)).
542 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
543
544 // If we don't have enough bits for this operand, don't include it.
545 if (NumBits > BitsLeft) {
546 DEBUG(std::cerr << "Not enough bits to densely encode " << NumBits
547 << " more bits\n");
548 break;
549 }
550
551 // Otherwise, we can include this in the initial lookup table. Add it in.
552 BitsLeft -= NumBits;
553 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
Chris Lattner55616402006-07-18 17:32:27 +0000554 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000555
Chris Lattnerb8462862006-07-18 17:56:07 +0000556 // Remove the info about this operand.
557 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
558 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
Chris Lattner96c1ade2006-07-18 18:28:27 +0000559 if (!Inst->Operands.empty()) {
560 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
Chris Lattner0a012122006-07-18 19:06:01 +0000561 assert(NumOps <= Inst->Operands.size() &&
562 "Can't remove this many ops!");
Chris Lattner96c1ade2006-07-18 18:28:27 +0000563 Inst->Operands.erase(Inst->Operands.begin(),
564 Inst->Operands.begin()+NumOps);
565 }
Chris Lattnerb8462862006-07-18 17:56:07 +0000566 }
567
568 // Remember the handlers for this set of operands.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000569 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
570 }
571
572
573
Chris Lattner55616402006-07-18 17:32:27 +0000574 O<<" static const unsigned OpInfo[] = {\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000575 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000576 O << " " << OpcodeInfo[i] << "U,\t// "
Chris Lattner55616402006-07-18 17:32:27 +0000577 << NumberedInstructions[i]->TheDef->getName() << "\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000578 }
579 // Add a dummy entry so the array init doesn't end with a comma.
Chris Lattner55616402006-07-18 17:32:27 +0000580 O << " 0U\n";
Chris Lattner6af022f2006-07-14 22:59:11 +0000581 O << " };\n\n";
582
583 // Emit the string itself.
584 O << " const char *AsmStrs = \n \"";
585 unsigned CharsPrinted = 0;
586 EscapeString(AggregateString);
587 for (unsigned i = 0, e = AggregateString.size(); i != e; ++i) {
588 if (CharsPrinted > 70) {
589 O << "\"\n \"";
590 CharsPrinted = 0;
591 }
592 O << AggregateString[i];
593 ++CharsPrinted;
594
595 // Print escape sequences all together.
596 if (AggregateString[i] == '\\') {
597 assert(i+1 < AggregateString.size() && "Incomplete escape sequence!");
598 if (isdigit(AggregateString[i+1])) {
599 assert(isdigit(AggregateString[i+2]) && isdigit(AggregateString[i+3]) &&
600 "Expected 3 digit octal escape!");
601 O << AggregateString[++i];
602 O << AggregateString[++i];
603 O << AggregateString[++i];
604 CharsPrinted += 3;
605 } else {
606 O << AggregateString[++i];
607 ++CharsPrinted;
608 }
609 }
610 }
611 O << "\";\n\n";
612
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000613 O << " if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {\n"
614 << " printInlineAsm(MI);\n"
615 << " return true;\n"
616 << " }\n\n";
617
Chris Lattner6af022f2006-07-14 22:59:11 +0000618 O << " // Emit the opcode for the instruction.\n"
Chris Lattner55616402006-07-18 17:32:27 +0000619 << " unsigned Bits = OpInfo[MI->getOpcode()];\n"
620 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ");\n\n";
Chris Lattnerf8766682005-01-22 19:22:23 +0000621
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000622 // Output the table driven operand information.
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000623 BitsLeft = 32-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000624 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
625 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
626
627 // Compute the number of bits we need to represent these cases, this is
628 // ceil(log2(numentries)).
629 unsigned NumBits = Log2_32_Ceil(Commands.size());
630 assert(NumBits <= BitsLeft && "consistency error");
631
632 // Emit code to extract this field from Bits.
633 BitsLeft -= NumBits;
634
635 O << "\n // Fragment " << i << " encoded into " << NumBits
Chris Lattnere7a589d2006-07-18 17:43:54 +0000636 << " bits for " << Commands.size() << " unique commands.\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000637
Chris Lattner96c1ade2006-07-18 18:28:27 +0000638 if (Commands.size() == 2) {
Chris Lattnere7a589d2006-07-18 17:43:54 +0000639 // Emit two possibilitys with if/else.
640 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
641 << ((1 << NumBits)-1) << ") {\n"
642 << Commands[1]
643 << " } else {\n"
644 << Commands[0]
645 << " }\n\n";
646 } else {
647 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
648 << ((1 << NumBits)-1) << ") {\n"
649 << " default: // unreachable.\n";
650
651 // Print out all the cases.
652 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
653 O << " case " << i << ":\n";
654 O << Commands[i];
655 O << " break;\n";
656 }
657 O << " }\n\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000658 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000659 }
660
Chris Lattnerb8462862006-07-18 17:56:07 +0000661 // Okay, delete instructions with no operand info left.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000662 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
663 // Entire instruction has been emitted?
664 AsmWriterInst &Inst = Instructions[i];
Chris Lattnerb8462862006-07-18 17:56:07 +0000665 if (Inst.Operands.empty()) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000666 Instructions.erase(Instructions.begin()+i);
Chris Lattnerb8462862006-07-18 17:56:07 +0000667 --i; --e;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000668 }
669 }
670
671
672 // Because this is a vector, we want to emit from the end. Reverse all of the
Chris Lattner870c0162005-01-22 18:38:13 +0000673 // elements in the vector.
674 std::reverse(Instructions.begin(), Instructions.end());
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000675
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000676 if (!Instructions.empty()) {
677 // Find the opcode # of inline asm.
678 O << " switch (MI->getOpcode()) {\n";
679 while (!Instructions.empty())
680 EmitInstructions(Instructions, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000681
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000682 O << " }\n";
Chris Lattner0a012122006-07-18 19:06:01 +0000683 O << " return true;\n";
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000684 }
685
Chris Lattner0a012122006-07-18 19:06:01 +0000686 O << "}\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000687}