blob: 6466b5fecd92ba98b6c400b9bbed5770331e6770 [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 {
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 =
125 AsmString.find_first_of("${|}", LastEmitted);
126 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;
135 } else if (AsmString[DollarPos] == '{') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000136 if (CurVariant != ~0U)
Jeff Cohen00b168892005-07-27 06:12:32 +0000137 throw "Nested variants found for instruction '" +
Chris Lattner3e3def92005-07-15 22:43:04 +0000138 CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000139 LastEmitted = DollarPos+1;
Chris Lattnerb03b0802006-02-06 22:43:28 +0000140 CurVariant = 0; // We are now inside of the variant!
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000141 } else if (AsmString[DollarPos] == '|') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000142 if (CurVariant == ~0U)
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000143 throw "'|' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000144 + CGI.TheDef->getName() + "'!";
Chris Lattnerb03b0802006-02-06 22:43:28 +0000145 ++CurVariant;
146 ++LastEmitted;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000147 } else if (AsmString[DollarPos] == '}') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000148 if (CurVariant == ~0U)
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000149 throw "'}' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000150 + CGI.TheDef->getName() + "'!";
Chris Lattnerb03b0802006-02-06 22:43:28 +0000151 ++LastEmitted;
152 CurVariant = ~0U;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000153 } else if (DollarPos+1 != AsmString.size() &&
154 AsmString[DollarPos+1] == '$') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000155 if (CurVariant == Variant || CurVariant == ~0U)
156 AddLiteralString("$"); // "$$" -> $
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000157 LastEmitted = DollarPos+2;
158 } else {
159 // Get the name of the variable.
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000160 std::string::size_type VarEnd = DollarPos+1;
Nate Begemanafc54562005-07-14 22:50:30 +0000161
162 // handle ${foo}bar as $foo by detecting whether the character following
163 // the dollar sign is a curly brace. If so, advance VarEnd and DollarPos
164 // so the variable name does not contain the leading curly brace.
165 bool hasCurlyBraces = false;
166 if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
167 hasCurlyBraces = true;
168 ++DollarPos;
169 ++VarEnd;
170 }
171
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000172 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
173 ++VarEnd;
174 std::string VarName(AsmString.begin()+DollarPos+1,
175 AsmString.begin()+VarEnd);
Nate Begemanafc54562005-07-14 22:50:30 +0000176
Chris Lattner04cadb32006-02-06 23:40:48 +0000177 // Modifier - Support ${foo:modifier} syntax, where "modifier" is passed
Chris Lattner1bf63612006-09-26 23:45:08 +0000178 // into printOperand. Also support ${:feature}, which is passed into
Chris Lattner16f046a2006-09-26 23:47:10 +0000179 // PrintSpecial.
Chris Lattner04cadb32006-02-06 23:40:48 +0000180 std::string Modifier;
181
Nate Begemanafc54562005-07-14 22:50:30 +0000182 // In order to avoid starting the next string at the terminating curly
183 // brace, advance the end position past it if we found an opening curly
184 // brace.
185 if (hasCurlyBraces) {
186 if (VarEnd >= AsmString.size())
187 throw "Reached end of string before terminating curly brace in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000188 + CGI.TheDef->getName() + "'";
Chris Lattner04cadb32006-02-06 23:40:48 +0000189
190 // Look for a modifier string.
191 if (AsmString[VarEnd] == ':') {
192 ++VarEnd;
193 if (VarEnd >= AsmString.size())
194 throw "Reached end of string before terminating curly brace in '"
195 + CGI.TheDef->getName() + "'";
196
197 unsigned ModifierStart = VarEnd;
198 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
199 ++VarEnd;
200 Modifier = std::string(AsmString.begin()+ModifierStart,
201 AsmString.begin()+VarEnd);
202 if (Modifier.empty())
203 throw "Bad operand modifier name in '"+ CGI.TheDef->getName() + "'";
204 }
205
Nate Begemanafc54562005-07-14 22:50:30 +0000206 if (AsmString[VarEnd] != '}')
Chris Lattnerb03b0802006-02-06 22:43:28 +0000207 throw "Variable name beginning with '{' did not end with '}' in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000208 + CGI.TheDef->getName() + "'";
Nate Begemanafc54562005-07-14 22:50:30 +0000209 ++VarEnd;
210 }
Chris Lattner1bf63612006-09-26 23:45:08 +0000211 if (VarName.empty() && Modifier.empty())
Jeff Cohen00b168892005-07-27 06:12:32 +0000212 throw "Stray '$' in '" + CGI.TheDef->getName() +
Chris Lattner3e3def92005-07-15 22:43:04 +0000213 "' asm string, maybe you want $$?";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000214
Chris Lattner1bf63612006-09-26 23:45:08 +0000215 if (VarName.empty()) {
Chris Lattner16f046a2006-09-26 23:47:10 +0000216 // Just a modifier, pass this into PrintSpecial.
217 Operands.push_back(AsmWriterOperand("PrintSpecial", ~0U, Modifier));
Chris Lattner1bf63612006-09-26 23:45:08 +0000218 } else {
219 // Otherwise, normal operand.
220 unsigned OpNo = CGI.getOperandNamed(VarName);
221 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000222
Chris Lattner1bf63612006-09-26 23:45:08 +0000223 // If this is a two-address instruction, verify the second operand isn't
224 // used.
225 unsigned MIOp = OpInfo.MIOperandNo;
226 if (CGI.isTwoAddress && MIOp == 1)
227 throw "Should refer to operand #0 instead of #1 for two-address"
228 " instruction '" + CGI.TheDef->getName() + "'!";
229
230 if (CurVariant == Variant || CurVariant == ~0U)
231 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp,
232 Modifier));
233 }
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000234 LastEmitted = VarEnd;
235 }
236 }
237
238 AddLiteralString("\\n");
239}
240
Chris Lattnerf8766682005-01-22 19:22:23 +0000241/// MatchesAllButOneOp - If this instruction is exactly identical to the
242/// specified instruction except for one differing operand, return the differing
243/// operand number. If more than one operand mismatches, return ~1, otherwise
244/// if the instructions are identical return ~0.
245unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
246 if (Operands.size() != Other.Operands.size()) return ~1;
Chris Lattner870c0162005-01-22 18:38:13 +0000247
248 unsigned MismatchOperand = ~0U;
249 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Chris Lattner870c0162005-01-22 18:38:13 +0000250 if (Operands[i] != Other.Operands[i])
Chris Lattnerf8766682005-01-22 19:22:23 +0000251 if (MismatchOperand != ~0U) // Already have one mismatch?
252 return ~1U;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000253 else
Chris Lattner870c0162005-01-22 18:38:13 +0000254 MismatchOperand = i;
255 }
256 return MismatchOperand;
257}
258
Chris Lattner38c07512005-01-22 20:31:17 +0000259static void PrintCases(std::vector<std::pair<std::string,
260 AsmWriterOperand> > &OpsToPrint, std::ostream &O) {
261 O << " case " << OpsToPrint.back().first << ": ";
262 AsmWriterOperand TheOp = OpsToPrint.back().second;
263 OpsToPrint.pop_back();
264
265 // Check to see if any other operands are identical in this list, and if so,
266 // emit a case label for them.
267 for (unsigned i = OpsToPrint.size(); i != 0; --i)
268 if (OpsToPrint[i-1].second == TheOp) {
269 O << "\n case " << OpsToPrint[i-1].first << ": ";
270 OpsToPrint.erase(OpsToPrint.begin()+i-1);
271 }
272
273 // Finally, emit the code.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000274 O << TheOp.getCode();
Chris Lattner38c07512005-01-22 20:31:17 +0000275 O << "break;\n";
276}
277
Chris Lattner870c0162005-01-22 18:38:13 +0000278
279/// EmitInstructions - Emit the last instruction in the vector and any other
280/// instructions that are suitably similar to it.
281static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
282 std::ostream &O) {
283 AsmWriterInst FirstInst = Insts.back();
284 Insts.pop_back();
285
286 std::vector<AsmWriterInst> SimilarInsts;
287 unsigned DifferingOperand = ~0;
288 for (unsigned i = Insts.size(); i != 0; --i) {
Chris Lattnerf8766682005-01-22 19:22:23 +0000289 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
290 if (DiffOp != ~1U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000291 if (DifferingOperand == ~0U) // First match!
292 DifferingOperand = DiffOp;
293
294 // If this differs in the same operand as the rest of the instructions in
295 // this class, move it to the SimilarInsts list.
Chris Lattnerf8766682005-01-22 19:22:23 +0000296 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000297 SimilarInsts.push_back(Insts[i-1]);
298 Insts.erase(Insts.begin()+i-1);
299 }
300 }
301 }
302
Chris Lattnera1e8a802006-05-01 17:01:17 +0000303 O << " case " << FirstInst.CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000304 << FirstInst.CGI->TheDef->getName() << ":\n";
305 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
Chris Lattnera1e8a802006-05-01 17:01:17 +0000306 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000307 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
308 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
309 if (i != DifferingOperand) {
310 // If the operand is the same for all instructions, just print it.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000311 O << " " << FirstInst.Operands[i].getCode();
Chris Lattner870c0162005-01-22 18:38:13 +0000312 } else {
313 // If this is the operand that varies between all of the instructions,
314 // emit a switch for just this operand now.
315 O << " switch (MI->getOpcode()) {\n";
Chris Lattner38c07512005-01-22 20:31:17 +0000316 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
Chris Lattnera1e8a802006-05-01 17:01:17 +0000317 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
Chris Lattner38c07512005-01-22 20:31:17 +0000318 FirstInst.CGI->TheDef->getName(),
319 FirstInst.Operands[i]));
Misha Brukman3da94ae2005-04-22 00:00:37 +0000320
Chris Lattner870c0162005-01-22 18:38:13 +0000321 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
Chris Lattner38c07512005-01-22 20:31:17 +0000322 AsmWriterInst &AWI = SimilarInsts[si];
Chris Lattnera1e8a802006-05-01 17:01:17 +0000323 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
Chris Lattner38c07512005-01-22 20:31:17 +0000324 AWI.CGI->TheDef->getName(),
325 AWI.Operands[i]));
Chris Lattner870c0162005-01-22 18:38:13 +0000326 }
Chris Lattner38c07512005-01-22 20:31:17 +0000327 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
328 while (!OpsToPrint.empty())
329 PrintCases(OpsToPrint, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000330 O << " }";
331 }
332 O << "\n";
333 }
334
335 O << " break;\n";
336}
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000337
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000338void AsmWriterEmitter::
339FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
Chris Lattner96c1ade2006-07-18 18:28:27 +0000340 std::vector<unsigned> &InstIdxs,
341 std::vector<unsigned> &InstOpsUsed) const {
Chris Lattner195bb4a2006-07-18 19:27:30 +0000342 InstIdxs.assign(NumberedInstructions.size(), ~0U);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000343
344 // This vector parallels UniqueOperandCommands, keeping track of which
345 // instructions each case are used for. It is a comma separated string of
346 // enums.
347 std::vector<std::string> InstrsForCase;
348 InstrsForCase.resize(UniqueOperandCommands.size());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000349 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000350
351 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
352 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
353 if (Inst == 0) continue; // PHI, INLINEASM, etc.
354
355 std::string Command;
Chris Lattnerb8462862006-07-18 17:56:07 +0000356 if (Inst->Operands.empty())
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000357 continue; // Instruction already done.
Chris Lattner191dd1f2006-07-18 17:50:22 +0000358
Chris Lattnerb8462862006-07-18 17:56:07 +0000359 Command = " " + Inst->Operands[0].getCode() + "\n";
Chris Lattner191dd1f2006-07-18 17:50:22 +0000360
361 // If this is the last operand, emit a return.
Chris Lattnerb8462862006-07-18 17:56:07 +0000362 if (Inst->Operands.size() == 1)
Chris Lattner191dd1f2006-07-18 17:50:22 +0000363 Command += " return true;\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000364
365 // Check to see if we already have 'Command' in UniqueOperandCommands.
366 // If not, add it.
367 bool FoundIt = false;
368 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
369 if (UniqueOperandCommands[idx] == Command) {
370 InstIdxs[i] = idx;
371 InstrsForCase[idx] += ", ";
372 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
373 FoundIt = true;
374 break;
375 }
376 if (!FoundIt) {
377 InstIdxs[i] = UniqueOperandCommands.size();
378 UniqueOperandCommands.push_back(Command);
379 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000380
381 // This command matches one operand so far.
382 InstOpsUsed.push_back(1);
383 }
384 }
385
386 // For each entry of UniqueOperandCommands, there is a set of instructions
387 // that uses it. If the next command of all instructions in the set are
388 // identical, fold it into the command.
389 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
390 CommandIdx != e; ++CommandIdx) {
391
392 for (unsigned Op = 1; ; ++Op) {
393 // Scan for the first instruction in the set.
394 std::vector<unsigned>::iterator NIT =
395 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
396 if (NIT == InstIdxs.end()) break; // No commonality.
397
398 // If this instruction has no more operands, we isn't anything to merge
399 // into this command.
400 const AsmWriterInst *FirstInst =
401 getAsmWriterInstByID(NIT-InstIdxs.begin());
402 if (!FirstInst || FirstInst->Operands.size() == Op)
403 break;
404
405 // Otherwise, scan to see if all of the other instructions in this command
406 // set share the operand.
407 bool AllSame = true;
408
Chris Lattner96c1ade2006-07-18 18:28:27 +0000409 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
410 NIT != InstIdxs.end();
411 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
412 // Okay, found another instruction in this command set. If the operand
413 // matches, we're ok, otherwise bail out.
414 const AsmWriterInst *OtherInst =
415 getAsmWriterInstByID(NIT-InstIdxs.begin());
416 if (!OtherInst || OtherInst->Operands.size() == Op ||
417 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
418 AllSame = false;
419 break;
420 }
421 }
422 if (!AllSame) break;
423
424 // Okay, everything in this command set has the same next operand. Add it
425 // to UniqueOperandCommands and remember that it was consumed.
426 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
427
428 // If this is the last operand, emit a return after the code.
429 if (FirstInst->Operands.size() == Op+1)
430 Command += " return true;\n";
431
432 UniqueOperandCommands[CommandIdx] += Command;
433 InstOpsUsed[CommandIdx]++;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000434 }
435 }
436
437 // Prepend some of the instructions each case is used for onto the case val.
438 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
439 std::string Instrs = InstrsForCase[i];
440 if (Instrs.size() > 70) {
441 Instrs.erase(Instrs.begin()+70, Instrs.end());
442 Instrs += "...";
443 }
444
445 if (!Instrs.empty())
446 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
447 UniqueOperandCommands[i];
448 }
449}
450
451
452
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000453void AsmWriterEmitter::run(std::ostream &O) {
454 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
455
456 CodeGenTarget Target;
Chris Lattner175580c2004-08-14 22:50:53 +0000457 Record *AsmWriter = Target.getAsmWriter();
Chris Lattner953c6fe2004-10-03 20:19:02 +0000458 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
459 unsigned Variant = AsmWriter->getValueAsInt("Variant");
Chris Lattner175580c2004-08-14 22:50:53 +0000460
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000461 O <<
462 "/// printInstruction - This method is automatically generated by tablegen\n"
463 "/// from the instruction set description. This method returns true if the\n"
464 "/// machine instruction was sufficiently described to print it, otherwise\n"
465 "/// it returns false.\n"
Chris Lattner953c6fe2004-10-03 20:19:02 +0000466 "bool " << Target.getName() << ClassName
Chris Lattner175580c2004-08-14 22:50:53 +0000467 << "::printInstruction(const MachineInstr *MI) {\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000468
Chris Lattner5765dba2005-01-22 17:40:38 +0000469 std::vector<AsmWriterInst> Instructions;
470
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000471 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
472 E = Target.inst_end(); I != E; ++I)
Chris Lattner5765dba2005-01-22 17:40:38 +0000473 if (!I->second.AsmString.empty())
474 Instructions.push_back(AsmWriterInst(I->second, Variant));
Chris Lattner076efa72004-08-01 07:43:02 +0000475
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000476 // Get the instruction numbering.
Chris Lattner0cfcc1e2006-01-27 02:10:50 +0000477 Target.getInstructionsByEnumValue(NumberedInstructions);
478
Chris Lattner6af022f2006-07-14 22:59:11 +0000479 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
480 // all machine instructions are necessarily being printed, so there may be
481 // target instructions not in this map.
Chris Lattner6af022f2006-07-14 22:59:11 +0000482 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
483 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
Chris Lattnerf8766682005-01-22 19:22:23 +0000484
Chris Lattner6af022f2006-07-14 22:59:11 +0000485 // Build an aggregate string, and build a table of offsets into it.
486 std::map<std::string, unsigned> StringOffset;
487 std::string AggregateString;
Chris Lattner259bda42006-09-27 16:44:09 +0000488 AggregateString.push_back(0); // "\0"
489 AggregateString.push_back(0); // "\0"
Chris Lattner6af022f2006-07-14 22:59:11 +0000490
Chris Lattner259bda42006-09-27 16:44:09 +0000491 /// OpcodeInfo - This encodes the index of the string to use for the first
Chris Lattner55616402006-07-18 17:32:27 +0000492 /// chunk of the output as well as indices used for operand printing.
493 std::vector<unsigned> OpcodeInfo;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000494
Chris Lattner55616402006-07-18 17:32:27 +0000495 unsigned MaxStringIdx = 0;
Chris Lattner6af022f2006-07-14 22:59:11 +0000496 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
497 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
498 unsigned Idx;
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000499 if (AWI == 0) {
Chris Lattner6af022f2006-07-14 22:59:11 +0000500 // Something not handled by the asmwriter printer.
501 Idx = 0;
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000502 } else if (AWI->Operands[0].OperandType !=
503 AsmWriterOperand::isLiteralTextOperand ||
504 AWI->Operands[0].Str.empty()) {
505 // Something handled by the asmwriter printer, but with no leading string.
506 Idx = 1;
Chris Lattner6af022f2006-07-14 22:59:11 +0000507 } else {
508 unsigned &Entry = StringOffset[AWI->Operands[0].Str];
509 if (Entry == 0) {
510 // Add the string to the aggregate if this is the first time found.
Chris Lattner55616402006-07-18 17:32:27 +0000511 MaxStringIdx = Entry = AggregateString.size();
Chris Lattner6af022f2006-07-14 22:59:11 +0000512 std::string Str = AWI->Operands[0].Str;
513 UnescapeString(Str);
514 AggregateString += Str;
515 AggregateString += '\0';
Chris Lattnerf8766682005-01-22 19:22:23 +0000516 }
Chris Lattner6af022f2006-07-14 22:59:11 +0000517 Idx = Entry;
Chris Lattner6af022f2006-07-14 22:59:11 +0000518
519 // Nuke the string from the operand list. It is now handled!
520 AWI->Operands.erase(AWI->Operands.begin());
Chris Lattnerf8766682005-01-22 19:22:23 +0000521 }
Chris Lattner55616402006-07-18 17:32:27 +0000522 OpcodeInfo.push_back(Idx);
Chris Lattnerf8766682005-01-22 19:22:23 +0000523 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000524
Chris Lattner55616402006-07-18 17:32:27 +0000525 // Figure out how many bits we used for the string index.
526 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx);
527
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000528 // To reduce code size, we compactify common instructions into a few bits
529 // in the opcode-indexed table.
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000530 unsigned BitsLeft = 32-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000531
532 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
533
Chris Lattnerb8462862006-07-18 17:56:07 +0000534 bool isFirst = true;
535 while (1) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000536 std::vector<std::string> UniqueOperandCommands;
537
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000538 // For the first operand check, add a default value for instructions with
539 // just opcode strings to use.
Chris Lattnerb8462862006-07-18 17:56:07 +0000540 if (isFirst) {
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000541 UniqueOperandCommands.push_back(" return true;\n");
Chris Lattnerb8462862006-07-18 17:56:07 +0000542 isFirst = false;
543 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000544
545 std::vector<unsigned> InstIdxs;
Chris Lattner96c1ade2006-07-18 18:28:27 +0000546 std::vector<unsigned> NumInstOpsHandled;
547 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
548 NumInstOpsHandled);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000549
550 // If we ran out of operands to print, we're done.
551 if (UniqueOperandCommands.empty()) break;
552
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000553 // Compute the number of bits we need to represent these cases, this is
554 // ceil(log2(numentries)).
555 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
556
557 // If we don't have enough bits for this operand, don't include it.
558 if (NumBits > BitsLeft) {
559 DEBUG(std::cerr << "Not enough bits to densely encode " << NumBits
560 << " more bits\n");
561 break;
562 }
563
564 // Otherwise, we can include this in the initial lookup table. Add it in.
565 BitsLeft -= NumBits;
566 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
Chris Lattner195bb4a2006-07-18 19:27:30 +0000567 if (InstIdxs[i] != ~0U)
568 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000569
Chris Lattnerb8462862006-07-18 17:56:07 +0000570 // Remove the info about this operand.
571 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
572 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
Chris Lattner96c1ade2006-07-18 18:28:27 +0000573 if (!Inst->Operands.empty()) {
574 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
Chris Lattner0a012122006-07-18 19:06:01 +0000575 assert(NumOps <= Inst->Operands.size() &&
576 "Can't remove this many ops!");
Chris Lattner96c1ade2006-07-18 18:28:27 +0000577 Inst->Operands.erase(Inst->Operands.begin(),
578 Inst->Operands.begin()+NumOps);
579 }
Chris Lattnerb8462862006-07-18 17:56:07 +0000580 }
581
582 // Remember the handlers for this set of operands.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000583 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
584 }
585
586
587
Chris Lattner55616402006-07-18 17:32:27 +0000588 O<<" static const unsigned OpInfo[] = {\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000589 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000590 O << " " << OpcodeInfo[i] << "U,\t// "
Chris Lattner55616402006-07-18 17:32:27 +0000591 << NumberedInstructions[i]->TheDef->getName() << "\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000592 }
593 // Add a dummy entry so the array init doesn't end with a comma.
Chris Lattner55616402006-07-18 17:32:27 +0000594 O << " 0U\n";
Chris Lattner6af022f2006-07-14 22:59:11 +0000595 O << " };\n\n";
596
597 // Emit the string itself.
598 O << " const char *AsmStrs = \n \"";
599 unsigned CharsPrinted = 0;
600 EscapeString(AggregateString);
601 for (unsigned i = 0, e = AggregateString.size(); i != e; ++i) {
602 if (CharsPrinted > 70) {
603 O << "\"\n \"";
604 CharsPrinted = 0;
605 }
606 O << AggregateString[i];
607 ++CharsPrinted;
608
609 // Print escape sequences all together.
610 if (AggregateString[i] == '\\') {
611 assert(i+1 < AggregateString.size() && "Incomplete escape sequence!");
612 if (isdigit(AggregateString[i+1])) {
613 assert(isdigit(AggregateString[i+2]) && isdigit(AggregateString[i+3]) &&
614 "Expected 3 digit octal escape!");
615 O << AggregateString[++i];
616 O << AggregateString[++i];
617 O << AggregateString[++i];
618 CharsPrinted += 3;
619 } else {
620 O << AggregateString[++i];
621 ++CharsPrinted;
622 }
623 }
624 }
625 O << "\";\n\n";
626
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000627 O << " if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {\n"
628 << " printInlineAsm(MI);\n"
629 << " return true;\n"
630 << " }\n\n";
631
Chris Lattner6af022f2006-07-14 22:59:11 +0000632 O << " // Emit the opcode for the instruction.\n"
Chris Lattner55616402006-07-18 17:32:27 +0000633 << " unsigned Bits = OpInfo[MI->getOpcode()];\n"
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000634 << " if (Bits == 0) return false;\n"
Chris Lattner55616402006-07-18 17:32:27 +0000635 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ");\n\n";
Chris Lattnerf8766682005-01-22 19:22:23 +0000636
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000637 // Output the table driven operand information.
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000638 BitsLeft = 32-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000639 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
640 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
641
642 // Compute the number of bits we need to represent these cases, this is
643 // ceil(log2(numentries)).
644 unsigned NumBits = Log2_32_Ceil(Commands.size());
645 assert(NumBits <= BitsLeft && "consistency error");
646
647 // Emit code to extract this field from Bits.
648 BitsLeft -= NumBits;
649
650 O << "\n // Fragment " << i << " encoded into " << NumBits
Chris Lattnere7a589d2006-07-18 17:43:54 +0000651 << " bits for " << Commands.size() << " unique commands.\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000652
Chris Lattner96c1ade2006-07-18 18:28:27 +0000653 if (Commands.size() == 2) {
Chris Lattnere7a589d2006-07-18 17:43:54 +0000654 // Emit two possibilitys with if/else.
655 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
656 << ((1 << NumBits)-1) << ") {\n"
657 << Commands[1]
658 << " } else {\n"
659 << Commands[0]
660 << " }\n\n";
661 } else {
662 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
663 << ((1 << NumBits)-1) << ") {\n"
664 << " default: // unreachable.\n";
665
666 // Print out all the cases.
667 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
668 O << " case " << i << ":\n";
669 O << Commands[i];
670 O << " break;\n";
671 }
672 O << " }\n\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000673 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000674 }
675
Chris Lattnerb8462862006-07-18 17:56:07 +0000676 // Okay, delete instructions with no operand info left.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000677 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
678 // Entire instruction has been emitted?
679 AsmWriterInst &Inst = Instructions[i];
Chris Lattnerb8462862006-07-18 17:56:07 +0000680 if (Inst.Operands.empty()) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000681 Instructions.erase(Instructions.begin()+i);
Chris Lattnerb8462862006-07-18 17:56:07 +0000682 --i; --e;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000683 }
684 }
685
686
687 // Because this is a vector, we want to emit from the end. Reverse all of the
Chris Lattner870c0162005-01-22 18:38:13 +0000688 // elements in the vector.
689 std::reverse(Instructions.begin(), Instructions.end());
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000690
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000691 if (!Instructions.empty()) {
692 // Find the opcode # of inline asm.
693 O << " switch (MI->getOpcode()) {\n";
694 while (!Instructions.empty())
695 EmitInstructions(Instructions, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000696
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000697 O << " }\n";
Chris Lattner0a012122006-07-18 19:06:01 +0000698 O << " return true;\n";
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000699 }
700
Chris Lattner0a012122006-07-18 19:06:01 +0000701 O << "}\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000702}