blob: a67ee531a654a5a2b4cd2505c47016f146d28e49 [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
Chris Lattner1bf63612006-09-26 23:45:08 +0000101 std::string Result = Str + "(MI";
102 if (MIOpNo != ~0U)
103 Result += ", " + utostr(MIOpNo);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000104 if (!MiModifier.empty())
105 Result += ", \"" + MiModifier + '"';
106 return Result + "); ";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000107}
108
109
110/// ParseAsmString - Parse the specified Instruction's AsmString into this
111/// AsmWriterInst.
112///
Chris Lattner5765dba2005-01-22 17:40:38 +0000113AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
114 this->CGI = &CGI;
Chris Lattnerb03b0802006-02-06 22:43:28 +0000115 unsigned CurVariant = ~0U; // ~0 if we are outside a {.|.|.} region, other #.
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000116
Chris Lattner1cf9d962006-02-01 19:12:23 +0000117 // NOTE: Any extensions to this code need to be mirrored in the
118 // AsmPrinter::printInlineAsm code that executes as compile time (assuming
119 // that inline asm strings should also get the new feature)!
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000120 const std::string &AsmString = CGI.AsmString;
121 std::string::size_type LastEmitted = 0;
122 while (LastEmitted != AsmString.size()) {
123 std::string::size_type DollarPos =
124 AsmString.find_first_of("${|}", LastEmitted);
125 if (DollarPos == std::string::npos) DollarPos = AsmString.size();
126
127 // Emit a constant string fragment.
128 if (DollarPos != LastEmitted) {
129 // TODO: this should eventually handle escaping.
Chris Lattnerb03b0802006-02-06 22:43:28 +0000130 if (CurVariant == Variant || CurVariant == ~0U)
131 AddLiteralString(std::string(AsmString.begin()+LastEmitted,
132 AsmString.begin()+DollarPos));
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000133 LastEmitted = DollarPos;
134 } else if (AsmString[DollarPos] == '{') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000135 if (CurVariant != ~0U)
Jeff Cohen00b168892005-07-27 06:12:32 +0000136 throw "Nested variants found for instruction '" +
Chris Lattner3e3def92005-07-15 22:43:04 +0000137 CGI.TheDef->getName() + "'!";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000138 LastEmitted = DollarPos+1;
Chris Lattnerb03b0802006-02-06 22:43:28 +0000139 CurVariant = 0; // We are now inside of the variant!
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000140 } else if (AsmString[DollarPos] == '|') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000141 if (CurVariant == ~0U)
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000142 throw "'|' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000143 + CGI.TheDef->getName() + "'!";
Chris Lattnerb03b0802006-02-06 22:43:28 +0000144 ++CurVariant;
145 ++LastEmitted;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000146 } else if (AsmString[DollarPos] == '}') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000147 if (CurVariant == ~0U)
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000148 throw "'}' character found outside of a variant in instruction '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000149 + CGI.TheDef->getName() + "'!";
Chris Lattnerb03b0802006-02-06 22:43:28 +0000150 ++LastEmitted;
151 CurVariant = ~0U;
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000152 } else if (DollarPos+1 != AsmString.size() &&
153 AsmString[DollarPos+1] == '$') {
Chris Lattnerb03b0802006-02-06 22:43:28 +0000154 if (CurVariant == Variant || CurVariant == ~0U)
155 AddLiteralString("$"); // "$$" -> $
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000156 LastEmitted = DollarPos+2;
157 } else {
158 // Get the name of the variable.
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000159 std::string::size_type VarEnd = DollarPos+1;
Nate Begemanafc54562005-07-14 22:50:30 +0000160
161 // handle ${foo}bar as $foo by detecting whether the character following
162 // the dollar sign is a curly brace. If so, advance VarEnd and DollarPos
163 // so the variable name does not contain the leading curly brace.
164 bool hasCurlyBraces = false;
165 if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
166 hasCurlyBraces = true;
167 ++DollarPos;
168 ++VarEnd;
169 }
170
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000171 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
172 ++VarEnd;
173 std::string VarName(AsmString.begin()+DollarPos+1,
174 AsmString.begin()+VarEnd);
Nate Begemanafc54562005-07-14 22:50:30 +0000175
Chris Lattner04cadb32006-02-06 23:40:48 +0000176 // Modifier - Support ${foo:modifier} syntax, where "modifier" is passed
Chris Lattner1bf63612006-09-26 23:45:08 +0000177 // into printOperand. Also support ${:feature}, which is passed into
178 // printSpecial.
Chris Lattner04cadb32006-02-06 23:40:48 +0000179 std::string Modifier;
180
Nate Begemanafc54562005-07-14 22:50:30 +0000181 // In order to avoid starting the next string at the terminating curly
182 // brace, advance the end position past it if we found an opening curly
183 // brace.
184 if (hasCurlyBraces) {
185 if (VarEnd >= AsmString.size())
186 throw "Reached end of string before terminating curly brace in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000187 + CGI.TheDef->getName() + "'";
Chris Lattner04cadb32006-02-06 23:40:48 +0000188
189 // Look for a modifier string.
190 if (AsmString[VarEnd] == ':') {
191 ++VarEnd;
192 if (VarEnd >= AsmString.size())
193 throw "Reached end of string before terminating curly brace in '"
194 + CGI.TheDef->getName() + "'";
195
196 unsigned ModifierStart = VarEnd;
197 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
198 ++VarEnd;
199 Modifier = std::string(AsmString.begin()+ModifierStart,
200 AsmString.begin()+VarEnd);
201 if (Modifier.empty())
202 throw "Bad operand modifier name in '"+ CGI.TheDef->getName() + "'";
203 }
204
Nate Begemanafc54562005-07-14 22:50:30 +0000205 if (AsmString[VarEnd] != '}')
Chris Lattnerb03b0802006-02-06 22:43:28 +0000206 throw "Variable name beginning with '{' did not end with '}' in '"
Chris Lattner3e3def92005-07-15 22:43:04 +0000207 + CGI.TheDef->getName() + "'";
Nate Begemanafc54562005-07-14 22:50:30 +0000208 ++VarEnd;
209 }
Chris Lattner1bf63612006-09-26 23:45:08 +0000210 if (VarName.empty() && Modifier.empty())
Jeff Cohen00b168892005-07-27 06:12:32 +0000211 throw "Stray '$' in '" + CGI.TheDef->getName() +
Chris Lattner3e3def92005-07-15 22:43:04 +0000212 "' asm string, maybe you want $$?";
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000213
Chris Lattner1bf63612006-09-26 23:45:08 +0000214 if (VarName.empty()) {
215 // Just a modifier, pass this into printSpecial.
216 Operands.push_back(AsmWriterOperand("printSpecial", ~0U, Modifier));
217 } else {
218 // Otherwise, normal operand.
219 unsigned OpNo = CGI.getOperandNamed(VarName);
220 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000221
Chris Lattner1bf63612006-09-26 23:45:08 +0000222 // If this is a two-address instruction, verify the second operand isn't
223 // used.
224 unsigned MIOp = OpInfo.MIOperandNo;
225 if (CGI.isTwoAddress && MIOp == 1)
226 throw "Should refer to operand #0 instead of #1 for two-address"
227 " instruction '" + CGI.TheDef->getName() + "'!";
228
229 if (CurVariant == Variant || CurVariant == ~0U)
230 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp,
231 Modifier));
232 }
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000233 LastEmitted = VarEnd;
234 }
235 }
236
237 AddLiteralString("\\n");
238}
239
Chris Lattnerf8766682005-01-22 19:22:23 +0000240/// MatchesAllButOneOp - If this instruction is exactly identical to the
241/// specified instruction except for one differing operand, return the differing
242/// operand number. If more than one operand mismatches, return ~1, otherwise
243/// if the instructions are identical return ~0.
244unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
245 if (Operands.size() != Other.Operands.size()) return ~1;
Chris Lattner870c0162005-01-22 18:38:13 +0000246
247 unsigned MismatchOperand = ~0U;
248 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Chris Lattner870c0162005-01-22 18:38:13 +0000249 if (Operands[i] != Other.Operands[i])
Chris Lattnerf8766682005-01-22 19:22:23 +0000250 if (MismatchOperand != ~0U) // Already have one mismatch?
251 return ~1U;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000252 else
Chris Lattner870c0162005-01-22 18:38:13 +0000253 MismatchOperand = i;
254 }
255 return MismatchOperand;
256}
257
Chris Lattner38c07512005-01-22 20:31:17 +0000258static void PrintCases(std::vector<std::pair<std::string,
259 AsmWriterOperand> > &OpsToPrint, std::ostream &O) {
260 O << " case " << OpsToPrint.back().first << ": ";
261 AsmWriterOperand TheOp = OpsToPrint.back().second;
262 OpsToPrint.pop_back();
263
264 // Check to see if any other operands are identical in this list, and if so,
265 // emit a case label for them.
266 for (unsigned i = OpsToPrint.size(); i != 0; --i)
267 if (OpsToPrint[i-1].second == TheOp) {
268 O << "\n case " << OpsToPrint[i-1].first << ": ";
269 OpsToPrint.erase(OpsToPrint.begin()+i-1);
270 }
271
272 // Finally, emit the code.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000273 O << TheOp.getCode();
Chris Lattner38c07512005-01-22 20:31:17 +0000274 O << "break;\n";
275}
276
Chris Lattner870c0162005-01-22 18:38:13 +0000277
278/// EmitInstructions - Emit the last instruction in the vector and any other
279/// instructions that are suitably similar to it.
280static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
281 std::ostream &O) {
282 AsmWriterInst FirstInst = Insts.back();
283 Insts.pop_back();
284
285 std::vector<AsmWriterInst> SimilarInsts;
286 unsigned DifferingOperand = ~0;
287 for (unsigned i = Insts.size(); i != 0; --i) {
Chris Lattnerf8766682005-01-22 19:22:23 +0000288 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
289 if (DiffOp != ~1U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000290 if (DifferingOperand == ~0U) // First match!
291 DifferingOperand = DiffOp;
292
293 // If this differs in the same operand as the rest of the instructions in
294 // this class, move it to the SimilarInsts list.
Chris Lattnerf8766682005-01-22 19:22:23 +0000295 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
Chris Lattner870c0162005-01-22 18:38:13 +0000296 SimilarInsts.push_back(Insts[i-1]);
297 Insts.erase(Insts.begin()+i-1);
298 }
299 }
300 }
301
Chris Lattnera1e8a802006-05-01 17:01:17 +0000302 O << " case " << FirstInst.CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000303 << FirstInst.CGI->TheDef->getName() << ":\n";
304 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
Chris Lattnera1e8a802006-05-01 17:01:17 +0000305 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
Chris Lattner870c0162005-01-22 18:38:13 +0000306 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
307 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
308 if (i != DifferingOperand) {
309 // If the operand is the same for all instructions, just print it.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000310 O << " " << FirstInst.Operands[i].getCode();
Chris Lattner870c0162005-01-22 18:38:13 +0000311 } else {
312 // If this is the operand that varies between all of the instructions,
313 // emit a switch for just this operand now.
314 O << " switch (MI->getOpcode()) {\n";
Chris Lattner38c07512005-01-22 20:31:17 +0000315 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
Chris Lattnera1e8a802006-05-01 17:01:17 +0000316 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
Chris Lattner38c07512005-01-22 20:31:17 +0000317 FirstInst.CGI->TheDef->getName(),
318 FirstInst.Operands[i]));
Misha Brukman3da94ae2005-04-22 00:00:37 +0000319
Chris Lattner870c0162005-01-22 18:38:13 +0000320 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
Chris Lattner38c07512005-01-22 20:31:17 +0000321 AsmWriterInst &AWI = SimilarInsts[si];
Chris Lattnera1e8a802006-05-01 17:01:17 +0000322 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
Chris Lattner38c07512005-01-22 20:31:17 +0000323 AWI.CGI->TheDef->getName(),
324 AWI.Operands[i]));
Chris Lattner870c0162005-01-22 18:38:13 +0000325 }
Chris Lattner38c07512005-01-22 20:31:17 +0000326 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
327 while (!OpsToPrint.empty())
328 PrintCases(OpsToPrint, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000329 O << " }";
330 }
331 O << "\n";
332 }
333
334 O << " break;\n";
335}
Chris Lattnerb0b55e72005-01-22 17:32:42 +0000336
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000337void AsmWriterEmitter::
338FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
Chris Lattner96c1ade2006-07-18 18:28:27 +0000339 std::vector<unsigned> &InstIdxs,
340 std::vector<unsigned> &InstOpsUsed) const {
Chris Lattner195bb4a2006-07-18 19:27:30 +0000341 InstIdxs.assign(NumberedInstructions.size(), ~0U);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000342
343 // This vector parallels UniqueOperandCommands, keeping track of which
344 // instructions each case are used for. It is a comma separated string of
345 // enums.
346 std::vector<std::string> InstrsForCase;
347 InstrsForCase.resize(UniqueOperandCommands.size());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000348 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000349
350 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
351 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
352 if (Inst == 0) continue; // PHI, INLINEASM, etc.
353
354 std::string Command;
Chris Lattnerb8462862006-07-18 17:56:07 +0000355 if (Inst->Operands.empty())
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000356 continue; // Instruction already done.
Chris Lattner191dd1f2006-07-18 17:50:22 +0000357
Chris Lattnerb8462862006-07-18 17:56:07 +0000358 Command = " " + Inst->Operands[0].getCode() + "\n";
Chris Lattner191dd1f2006-07-18 17:50:22 +0000359
360 // If this is the last operand, emit a return.
Chris Lattnerb8462862006-07-18 17:56:07 +0000361 if (Inst->Operands.size() == 1)
Chris Lattner191dd1f2006-07-18 17:50:22 +0000362 Command += " return true;\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000363
364 // Check to see if we already have 'Command' in UniqueOperandCommands.
365 // If not, add it.
366 bool FoundIt = false;
367 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
368 if (UniqueOperandCommands[idx] == Command) {
369 InstIdxs[i] = idx;
370 InstrsForCase[idx] += ", ";
371 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
372 FoundIt = true;
373 break;
374 }
375 if (!FoundIt) {
376 InstIdxs[i] = UniqueOperandCommands.size();
377 UniqueOperandCommands.push_back(Command);
378 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
Chris Lattner96c1ade2006-07-18 18:28:27 +0000379
380 // This command matches one operand so far.
381 InstOpsUsed.push_back(1);
382 }
383 }
384
385 // For each entry of UniqueOperandCommands, there is a set of instructions
386 // that uses it. If the next command of all instructions in the set are
387 // identical, fold it into the command.
388 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
389 CommandIdx != e; ++CommandIdx) {
390
391 for (unsigned Op = 1; ; ++Op) {
392 // Scan for the first instruction in the set.
393 std::vector<unsigned>::iterator NIT =
394 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
395 if (NIT == InstIdxs.end()) break; // No commonality.
396
397 // If this instruction has no more operands, we isn't anything to merge
398 // into this command.
399 const AsmWriterInst *FirstInst =
400 getAsmWriterInstByID(NIT-InstIdxs.begin());
401 if (!FirstInst || FirstInst->Operands.size() == Op)
402 break;
403
404 // Otherwise, scan to see if all of the other instructions in this command
405 // set share the operand.
406 bool AllSame = true;
407
Chris Lattner96c1ade2006-07-18 18:28:27 +0000408 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
409 NIT != InstIdxs.end();
410 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
411 // Okay, found another instruction in this command set. If the operand
412 // matches, we're ok, otherwise bail out.
413 const AsmWriterInst *OtherInst =
414 getAsmWriterInstByID(NIT-InstIdxs.begin());
415 if (!OtherInst || OtherInst->Operands.size() == Op ||
416 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
417 AllSame = false;
418 break;
419 }
420 }
421 if (!AllSame) break;
422
423 // Okay, everything in this command set has the same next operand. Add it
424 // to UniqueOperandCommands and remember that it was consumed.
425 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
426
427 // If this is the last operand, emit a return after the code.
428 if (FirstInst->Operands.size() == Op+1)
429 Command += " return true;\n";
430
431 UniqueOperandCommands[CommandIdx] += Command;
432 InstOpsUsed[CommandIdx]++;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000433 }
434 }
435
436 // Prepend some of the instructions each case is used for onto the case val.
437 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
438 std::string Instrs = InstrsForCase[i];
439 if (Instrs.size() > 70) {
440 Instrs.erase(Instrs.begin()+70, Instrs.end());
441 Instrs += "...";
442 }
443
444 if (!Instrs.empty())
445 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
446 UniqueOperandCommands[i];
447 }
448}
449
450
451
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000452void AsmWriterEmitter::run(std::ostream &O) {
453 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
454
455 CodeGenTarget Target;
Chris Lattner175580c2004-08-14 22:50:53 +0000456 Record *AsmWriter = Target.getAsmWriter();
Chris Lattner953c6fe2004-10-03 20:19:02 +0000457 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
458 unsigned Variant = AsmWriter->getValueAsInt("Variant");
Chris Lattner175580c2004-08-14 22:50:53 +0000459
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000460 O <<
461 "/// printInstruction - This method is automatically generated by tablegen\n"
462 "/// from the instruction set description. This method returns true if the\n"
463 "/// machine instruction was sufficiently described to print it, otherwise\n"
464 "/// it returns false.\n"
Chris Lattner953c6fe2004-10-03 20:19:02 +0000465 "bool " << Target.getName() << ClassName
Chris Lattner175580c2004-08-14 22:50:53 +0000466 << "::printInstruction(const MachineInstr *MI) {\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000467
Chris Lattner5765dba2005-01-22 17:40:38 +0000468 std::vector<AsmWriterInst> Instructions;
469
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000470 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
471 E = Target.inst_end(); I != E; ++I)
Chris Lattner5765dba2005-01-22 17:40:38 +0000472 if (!I->second.AsmString.empty())
473 Instructions.push_back(AsmWriterInst(I->second, Variant));
Chris Lattner076efa72004-08-01 07:43:02 +0000474
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000475 // Get the instruction numbering.
Chris Lattner0cfcc1e2006-01-27 02:10:50 +0000476 Target.getInstructionsByEnumValue(NumberedInstructions);
477
Chris Lattner6af022f2006-07-14 22:59:11 +0000478 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
479 // all machine instructions are necessarily being printed, so there may be
480 // target instructions not in this map.
Chris Lattner6af022f2006-07-14 22:59:11 +0000481 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
482 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
Chris Lattnerf8766682005-01-22 19:22:23 +0000483
Chris Lattner6af022f2006-07-14 22:59:11 +0000484 // Build an aggregate string, and build a table of offsets into it.
485 std::map<std::string, unsigned> StringOffset;
486 std::string AggregateString;
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000487 AggregateString += "\0\0";
Chris Lattner6af022f2006-07-14 22:59:11 +0000488
Chris Lattner55616402006-07-18 17:32:27 +0000489 /// OpcodeInfo - Theis encodes the index of the string to use for the first
490 /// chunk of the output as well as indices used for operand printing.
491 std::vector<unsigned> OpcodeInfo;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000492
Chris Lattner55616402006-07-18 17:32:27 +0000493 unsigned MaxStringIdx = 0;
Chris Lattner6af022f2006-07-14 22:59:11 +0000494 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
495 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
496 unsigned Idx;
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000497 if (AWI == 0) {
Chris Lattner6af022f2006-07-14 22:59:11 +0000498 // Something not handled by the asmwriter printer.
499 Idx = 0;
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000500 } else if (AWI->Operands[0].OperandType !=
501 AsmWriterOperand::isLiteralTextOperand ||
502 AWI->Operands[0].Str.empty()) {
503 // Something handled by the asmwriter printer, but with no leading string.
504 Idx = 1;
Chris Lattner6af022f2006-07-14 22:59:11 +0000505 } else {
506 unsigned &Entry = StringOffset[AWI->Operands[0].Str];
507 if (Entry == 0) {
508 // Add the string to the aggregate if this is the first time found.
Chris Lattner55616402006-07-18 17:32:27 +0000509 MaxStringIdx = Entry = AggregateString.size();
Chris Lattner6af022f2006-07-14 22:59:11 +0000510 std::string Str = AWI->Operands[0].Str;
511 UnescapeString(Str);
512 AggregateString += Str;
513 AggregateString += '\0';
Chris Lattnerf8766682005-01-22 19:22:23 +0000514 }
Chris Lattner6af022f2006-07-14 22:59:11 +0000515 Idx = Entry;
Chris Lattner6af022f2006-07-14 22:59:11 +0000516
517 // Nuke the string from the operand list. It is now handled!
518 AWI->Operands.erase(AWI->Operands.begin());
Chris Lattnerf8766682005-01-22 19:22:23 +0000519 }
Chris Lattner55616402006-07-18 17:32:27 +0000520 OpcodeInfo.push_back(Idx);
Chris Lattnerf8766682005-01-22 19:22:23 +0000521 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000522
Chris Lattner55616402006-07-18 17:32:27 +0000523 // Figure out how many bits we used for the string index.
524 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx);
525
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000526 // To reduce code size, we compactify common instructions into a few bits
527 // in the opcode-indexed table.
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000528 unsigned BitsLeft = 32-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000529
530 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
531
Chris Lattnerb8462862006-07-18 17:56:07 +0000532 bool isFirst = true;
533 while (1) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000534 std::vector<std::string> UniqueOperandCommands;
535
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000536 // For the first operand check, add a default value for instructions with
537 // just opcode strings to use.
Chris Lattnerb8462862006-07-18 17:56:07 +0000538 if (isFirst) {
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000539 UniqueOperandCommands.push_back(" return true;\n");
Chris Lattnerb8462862006-07-18 17:56:07 +0000540 isFirst = false;
541 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000542
543 std::vector<unsigned> InstIdxs;
Chris Lattner96c1ade2006-07-18 18:28:27 +0000544 std::vector<unsigned> NumInstOpsHandled;
545 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
546 NumInstOpsHandled);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000547
548 // If we ran out of operands to print, we're done.
549 if (UniqueOperandCommands.empty()) break;
550
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000551 // Compute the number of bits we need to represent these cases, this is
552 // ceil(log2(numentries)).
553 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
554
555 // If we don't have enough bits for this operand, don't include it.
556 if (NumBits > BitsLeft) {
557 DEBUG(std::cerr << "Not enough bits to densely encode " << NumBits
558 << " more bits\n");
559 break;
560 }
561
562 // Otherwise, we can include this in the initial lookup table. Add it in.
563 BitsLeft -= NumBits;
564 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
Chris Lattner195bb4a2006-07-18 19:27:30 +0000565 if (InstIdxs[i] != ~0U)
566 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000567
Chris Lattnerb8462862006-07-18 17:56:07 +0000568 // Remove the info about this operand.
569 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
570 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
Chris Lattner96c1ade2006-07-18 18:28:27 +0000571 if (!Inst->Operands.empty()) {
572 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
Chris Lattner0a012122006-07-18 19:06:01 +0000573 assert(NumOps <= Inst->Operands.size() &&
574 "Can't remove this many ops!");
Chris Lattner96c1ade2006-07-18 18:28:27 +0000575 Inst->Operands.erase(Inst->Operands.begin(),
576 Inst->Operands.begin()+NumOps);
577 }
Chris Lattnerb8462862006-07-18 17:56:07 +0000578 }
579
580 // Remember the handlers for this set of operands.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000581 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
582 }
583
584
585
Chris Lattner55616402006-07-18 17:32:27 +0000586 O<<" static const unsigned OpInfo[] = {\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000587 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000588 O << " " << OpcodeInfo[i] << "U,\t// "
Chris Lattner55616402006-07-18 17:32:27 +0000589 << NumberedInstructions[i]->TheDef->getName() << "\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000590 }
591 // Add a dummy entry so the array init doesn't end with a comma.
Chris Lattner55616402006-07-18 17:32:27 +0000592 O << " 0U\n";
Chris Lattner6af022f2006-07-14 22:59:11 +0000593 O << " };\n\n";
594
595 // Emit the string itself.
596 O << " const char *AsmStrs = \n \"";
597 unsigned CharsPrinted = 0;
598 EscapeString(AggregateString);
599 for (unsigned i = 0, e = AggregateString.size(); i != e; ++i) {
600 if (CharsPrinted > 70) {
601 O << "\"\n \"";
602 CharsPrinted = 0;
603 }
604 O << AggregateString[i];
605 ++CharsPrinted;
606
607 // Print escape sequences all together.
608 if (AggregateString[i] == '\\') {
609 assert(i+1 < AggregateString.size() && "Incomplete escape sequence!");
610 if (isdigit(AggregateString[i+1])) {
611 assert(isdigit(AggregateString[i+2]) && isdigit(AggregateString[i+3]) &&
612 "Expected 3 digit octal escape!");
613 O << AggregateString[++i];
614 O << AggregateString[++i];
615 O << AggregateString[++i];
616 CharsPrinted += 3;
617 } else {
618 O << AggregateString[++i];
619 ++CharsPrinted;
620 }
621 }
622 }
623 O << "\";\n\n";
624
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000625 O << " if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {\n"
626 << " printInlineAsm(MI);\n"
627 << " return true;\n"
628 << " }\n\n";
629
Chris Lattner6af022f2006-07-14 22:59:11 +0000630 O << " // Emit the opcode for the instruction.\n"
Chris Lattner55616402006-07-18 17:32:27 +0000631 << " unsigned Bits = OpInfo[MI->getOpcode()];\n"
Chris Lattnera6dc9fb2006-07-19 01:39:06 +0000632 << " if (Bits == 0) return false;\n"
Chris Lattner55616402006-07-18 17:32:27 +0000633 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ");\n\n";
Chris Lattnerf8766682005-01-22 19:22:23 +0000634
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000635 // Output the table driven operand information.
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000636 BitsLeft = 32-AsmStrBits;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000637 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
638 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
639
640 // Compute the number of bits we need to represent these cases, this is
641 // ceil(log2(numentries)).
642 unsigned NumBits = Log2_32_Ceil(Commands.size());
643 assert(NumBits <= BitsLeft && "consistency error");
644
645 // Emit code to extract this field from Bits.
646 BitsLeft -= NumBits;
647
648 O << "\n // Fragment " << i << " encoded into " << NumBits
Chris Lattnere7a589d2006-07-18 17:43:54 +0000649 << " bits for " << Commands.size() << " unique commands.\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000650
Chris Lattner96c1ade2006-07-18 18:28:27 +0000651 if (Commands.size() == 2) {
Chris Lattnere7a589d2006-07-18 17:43:54 +0000652 // Emit two possibilitys with if/else.
653 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
654 << ((1 << NumBits)-1) << ") {\n"
655 << Commands[1]
656 << " } else {\n"
657 << Commands[0]
658 << " }\n\n";
659 } else {
660 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
661 << ((1 << NumBits)-1) << ") {\n"
662 << " default: // unreachable.\n";
663
664 // Print out all the cases.
665 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
666 O << " case " << i << ":\n";
667 O << Commands[i];
668 O << " break;\n";
669 }
670 O << " }\n\n";
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000671 }
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000672 }
673
Chris Lattnerb8462862006-07-18 17:56:07 +0000674 // Okay, delete instructions with no operand info left.
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000675 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
676 // Entire instruction has been emitted?
677 AsmWriterInst &Inst = Instructions[i];
Chris Lattnerb8462862006-07-18 17:56:07 +0000678 if (Inst.Operands.empty()) {
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000679 Instructions.erase(Instructions.begin()+i);
Chris Lattnerb8462862006-07-18 17:56:07 +0000680 --i; --e;
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000681 }
682 }
683
684
685 // Because this is a vector, we want to emit from the end. Reverse all of the
Chris Lattner870c0162005-01-22 18:38:13 +0000686 // elements in the vector.
687 std::reverse(Instructions.begin(), Instructions.end());
Chris Lattnerbdff5f92006-07-18 17:18:03 +0000688
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000689 if (!Instructions.empty()) {
690 // Find the opcode # of inline asm.
691 O << " switch (MI->getOpcode()) {\n";
692 while (!Instructions.empty())
693 EmitInstructions(Instructions, O);
Chris Lattner870c0162005-01-22 18:38:13 +0000694
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000695 O << " }\n";
Chris Lattner0a012122006-07-18 19:06:01 +0000696 O << " return true;\n";
Chris Lattnerb51ecd42006-07-18 17:38:46 +0000697 }
698
Chris Lattner0a012122006-07-18 19:06:01 +0000699 O << "}\n";
Chris Lattner2e1f51b2004-08-01 05:59:33 +0000700}