blob: 1e85ff9b7f268ccc7a6a1f73b0e2d161da42162a [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerfd6c2f02007-12-29 20:37:13 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
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"
17#include "Record.h"
18#include "llvm/ADT/StringExtras.h"
19#include "llvm/Support/Debug.h"
20#include "llvm/Support/MathExtras.h"
21#include <algorithm>
David Greene8cdbfd62009-07-29 20:10:24 +000022#include <sstream>
Daniel Dunbard4287062009-07-03 00:10:29 +000023#include <iostream>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000024using namespace llvm;
25
26static bool isIdentChar(char C) {
27 return (C >= 'a' && C <= 'z') ||
28 (C >= 'A' && C <= 'Z') ||
29 (C >= '0' && C <= '9') ||
30 C == '_';
31}
32
33// This should be an anon namespace, this works around a GCC warning.
34namespace llvm {
35 struct AsmWriterOperand {
David Greene8cdbfd62009-07-29 20:10:24 +000036 enum OpType {
David Greene4b62f5b2009-07-31 21:57:10 +000037 // Output this text surrounded by quotes to the asm.
David Greene8cdbfd62009-07-29 20:10:24 +000038 isLiteralTextOperand,
David Greene4b62f5b2009-07-31 21:57:10 +000039 // This is the name of a routine to call to print the operand.
David Greene8cdbfd62009-07-29 20:10:24 +000040 isMachineInstrOperand,
David Greene4b62f5b2009-07-31 21:57:10 +000041 // Output this text verbatim to the asm writer. It is code that
42 // will output some text to the asm.
David Greene8cdbfd62009-07-29 20:10:24 +000043 isLiteralStatementOperand
44 } OperandType;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000045
46 /// Str - For isLiteralTextOperand, this IS the literal text. For
David Greene4b62f5b2009-07-31 21:57:10 +000047 /// isMachineInstrOperand, this is the PrinterMethodName for the operand..
48 /// For isLiteralStatementOperand, this is the code to insert verbatim
49 /// into the asm writer.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000050 std::string Str;
51
52 /// MiOpNo - For isMachineInstrOperand, this is the operand number of the
53 /// machine instruction.
54 unsigned MIOpNo;
55
56 /// MiModifier - For isMachineInstrOperand, this is the modifier string for
57 /// an operand, specified with syntax like ${opname:modifier}.
58 std::string MiModifier;
59
Cédric Venetb1967722008-10-27 19:21:35 +000060 // To make VS STL happy
David Greene8cdbfd62009-07-29 20:10:24 +000061 AsmWriterOperand(OpType op = isLiteralTextOperand):OperandType(op) {}
Cédric Venet344da9b2008-10-26 15:40:44 +000062
David Greene8cdbfd62009-07-29 20:10:24 +000063 AsmWriterOperand(const std::string &LitStr,
64 OpType op = isLiteralTextOperand)
65 : OperandType(op), Str(LitStr) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000066
67 AsmWriterOperand(const std::string &Printer, unsigned OpNo,
David Greene8cdbfd62009-07-29 20:10:24 +000068 const std::string &Modifier,
69 OpType op = isMachineInstrOperand)
70 : OperandType(op), Str(Printer), MIOpNo(OpNo),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000071 MiModifier(Modifier) {}
72
73 bool operator!=(const AsmWriterOperand &Other) const {
74 if (OperandType != Other.OperandType || Str != Other.Str) return true;
75 if (OperandType == isMachineInstrOperand)
76 return MIOpNo != Other.MIOpNo || MiModifier != Other.MiModifier;
77 return false;
78 }
79 bool operator==(const AsmWriterOperand &Other) const {
80 return !operator!=(Other);
81 }
82
83 /// getCode - Return the code that prints this operand.
84 std::string getCode() const;
85 };
86}
87
88namespace llvm {
89 class AsmWriterInst {
90 public:
91 std::vector<AsmWriterOperand> Operands;
92 const CodeGenInstruction *CGI;
93
Chris Lattnerbffb6252009-08-07 23:13:38 +000094 AsmWriterInst(const CodeGenInstruction &CGI, Record *AsmWriter);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000095
96 /// MatchesAllButOneOp - If this instruction is exactly identical to the
97 /// specified instruction except for one differing operand, return the
98 /// differing operand number. Otherwise return ~0.
99 unsigned MatchesAllButOneOp(const AsmWriterInst &Other) const;
100
101 private:
102 void AddLiteralString(const std::string &Str) {
103 // If the last operand was already a literal text string, append this to
104 // it, otherwise add a new operand.
105 if (!Operands.empty() &&
106 Operands.back().OperandType == AsmWriterOperand::isLiteralTextOperand)
107 Operands.back().Str.append(Str);
108 else
109 Operands.push_back(AsmWriterOperand(Str));
110 }
111 };
112}
113
114
115std::string AsmWriterOperand::getCode() const {
Chris Lattner7d337492009-08-08 00:05:42 +0000116 if (OperandType == isLiteralTextOperand) {
117 if (Str.size() == 1)
118 return "O << '" + Str + "'; ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000119 return "O << \"" + Str + "\"; ";
David Greene8cdbfd62009-07-29 20:10:24 +0000120 }
121
Chris Lattner7d337492009-08-08 00:05:42 +0000122 if (OperandType == isLiteralStatementOperand)
123 return Str;
124
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125 std::string Result = Str + "(MI";
126 if (MIOpNo != ~0U)
127 Result += ", " + utostr(MIOpNo);
128 if (!MiModifier.empty())
129 Result += ", \"" + MiModifier + '"';
130 return Result + "); ";
131}
132
133
134/// ParseAsmString - Parse the specified Instruction's AsmString into this
135/// AsmWriterInst.
136///
Chris Lattnerbffb6252009-08-07 23:13:38 +0000137AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, Record *AsmWriter) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138 this->CGI = &CGI;
Chris Lattnerbffb6252009-08-07 23:13:38 +0000139
140 unsigned Variant = AsmWriter->getValueAsInt("Variant");
141 int FirstOperandColumn = AsmWriter->getValueAsInt("FirstOperandColumn");
142 int OperandSpacing = AsmWriter->getValueAsInt("OperandSpacing");
143
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144 unsigned CurVariant = ~0U; // ~0 if we are outside a {.|.|.} region, other #.
145
Chris Lattnerbffb6252009-08-07 23:13:38 +0000146 // This is the number of tabs we've seen if we're doing columnar layout.
147 unsigned CurColumn = 0;
148
149
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150 // NOTE: Any extensions to this code need to be mirrored in the
151 // AsmPrinter::printInlineAsm code that executes as compile time (assuming
152 // that inline asm strings should also get the new feature)!
153 const std::string &AsmString = CGI.AsmString;
154 std::string::size_type LastEmitted = 0;
155 while (LastEmitted != AsmString.size()) {
156 std::string::size_type DollarPos =
Nate Begemanb5b74722008-03-17 07:26:14 +0000157 AsmString.find_first_of("${|}\\", LastEmitted);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158 if (DollarPos == std::string::npos) DollarPos = AsmString.size();
159
160 // Emit a constant string fragment.
David Greene8cdbfd62009-07-29 20:10:24 +0000161
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162 if (DollarPos != LastEmitted) {
Chris Lattnera4bc2cd2009-03-13 21:33:17 +0000163 if (CurVariant == Variant || CurVariant == ~0U) {
164 for (; LastEmitted != DollarPos; ++LastEmitted)
165 switch (AsmString[LastEmitted]) {
David Greene8cdbfd62009-07-29 20:10:24 +0000166 case '\n':
David Greene8cdbfd62009-07-29 20:10:24 +0000167 AddLiteralString("\\n");
168 break;
Chris Lattnerbffb6252009-08-07 23:13:38 +0000169 case '\t':
170 // If the asm writer is not using a columnar layout, \t is not
171 // magic.
172 if (FirstOperandColumn == -1 || OperandSpacing == -1) {
173 AddLiteralString("\\t");
Benjamin Kramera4799c62009-08-07 23:37:47 +0000174 } else {
175 // We recognize a tab as an operand delimeter.
176 unsigned DestColumn = FirstOperandColumn +
177 CurColumn++ * OperandSpacing;
178 Operands.push_back(
179 AsmWriterOperand("O.PadToColumn(" +
Chris Lattner46148952009-08-17 15:48:08 +0000180 utostr(DestColumn) + ");\n",
Benjamin Kramera4799c62009-08-07 23:37:47 +0000181 AsmWriterOperand::isLiteralStatementOperand));
Chris Lattnerbffb6252009-08-07 23:13:38 +0000182 }
David Greene8cdbfd62009-07-29 20:10:24 +0000183 break;
184 case '"':
David Greene8cdbfd62009-07-29 20:10:24 +0000185 AddLiteralString("\\\"");
186 break;
187 case '\\':
David Greene8cdbfd62009-07-29 20:10:24 +0000188 AddLiteralString("\\\\");
189 break;
Chris Lattnera4bc2cd2009-03-13 21:33:17 +0000190 default:
191 AddLiteralString(std::string(1, AsmString[LastEmitted]));
192 break;
193 }
194 } else {
195 LastEmitted = DollarPos;
196 }
Nate Begemanb5b74722008-03-17 07:26:14 +0000197 } else if (AsmString[DollarPos] == '\\') {
198 if (DollarPos+1 != AsmString.size() &&
199 (CurVariant == Variant || CurVariant == ~0U)) {
200 if (AsmString[DollarPos+1] == 'n') {
201 AddLiteralString("\\n");
202 } else if (AsmString[DollarPos+1] == 't') {
Chris Lattnerbffb6252009-08-07 23:13:38 +0000203 // If the asm writer is not using a columnar layout, \t is not
204 // magic.
205 if (FirstOperandColumn == -1 || OperandSpacing == -1) {
206 AddLiteralString("\\t");
207 break;
208 }
209
210 // We recognize a tab as an operand delimeter.
211 unsigned DestColumn = FirstOperandColumn +
212 CurColumn++ * OperandSpacing;
David Greene4b62f5b2009-07-31 21:57:10 +0000213 Operands.push_back(
Chris Lattner46148952009-08-17 15:48:08 +0000214 AsmWriterOperand("O.PadToColumn(" + utostr(DestColumn) + ");\n",
David Greene4b62f5b2009-07-31 21:57:10 +0000215 AsmWriterOperand::isLiteralStatementOperand));
Chris Lattnerbffb6252009-08-07 23:13:38 +0000216 break;
Nate Begemanb5b74722008-03-17 07:26:14 +0000217 } else if (std::string("${|}\\").find(AsmString[DollarPos+1])
218 != std::string::npos) {
219 AddLiteralString(std::string(1, AsmString[DollarPos+1]));
220 } else {
221 throw "Non-supported escaped character found in instruction '" +
222 CGI.TheDef->getName() + "'!";
223 }
224 LastEmitted = DollarPos+2;
225 continue;
226 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000227 } else if (AsmString[DollarPos] == '{') {
228 if (CurVariant != ~0U)
229 throw "Nested variants found for instruction '" +
230 CGI.TheDef->getName() + "'!";
231 LastEmitted = DollarPos+1;
232 CurVariant = 0; // We are now inside of the variant!
233 } else if (AsmString[DollarPos] == '|') {
234 if (CurVariant == ~0U)
235 throw "'|' character found outside of a variant in instruction '"
236 + CGI.TheDef->getName() + "'!";
237 ++CurVariant;
238 ++LastEmitted;
239 } else if (AsmString[DollarPos] == '}') {
240 if (CurVariant == ~0U)
241 throw "'}' character found outside of a variant in instruction '"
242 + CGI.TheDef->getName() + "'!";
243 ++LastEmitted;
244 CurVariant = ~0U;
245 } else if (DollarPos+1 != AsmString.size() &&
246 AsmString[DollarPos+1] == '$') {
David Greene8cdbfd62009-07-29 20:10:24 +0000247 if (CurVariant == Variant || CurVariant == ~0U) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000248 AddLiteralString("$"); // "$$" -> $
David Greene8cdbfd62009-07-29 20:10:24 +0000249 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000250 LastEmitted = DollarPos+2;
251 } else {
252 // Get the name of the variable.
253 std::string::size_type VarEnd = DollarPos+1;
David Greene8cdbfd62009-07-29 20:10:24 +0000254
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255 // handle ${foo}bar as $foo by detecting whether the character following
256 // the dollar sign is a curly brace. If so, advance VarEnd and DollarPos
257 // so the variable name does not contain the leading curly brace.
258 bool hasCurlyBraces = false;
259 if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
260 hasCurlyBraces = true;
261 ++DollarPos;
262 ++VarEnd;
263 }
264
265 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
266 ++VarEnd;
267 std::string VarName(AsmString.begin()+DollarPos+1,
268 AsmString.begin()+VarEnd);
269
270 // Modifier - Support ${foo:modifier} syntax, where "modifier" is passed
271 // into printOperand. Also support ${:feature}, which is passed into
272 // PrintSpecial.
273 std::string Modifier;
274
275 // In order to avoid starting the next string at the terminating curly
276 // brace, advance the end position past it if we found an opening curly
277 // brace.
278 if (hasCurlyBraces) {
279 if (VarEnd >= AsmString.size())
280 throw "Reached end of string before terminating curly brace in '"
281 + CGI.TheDef->getName() + "'";
282
283 // Look for a modifier string.
284 if (AsmString[VarEnd] == ':') {
285 ++VarEnd;
286 if (VarEnd >= AsmString.size())
287 throw "Reached end of string before terminating curly brace in '"
288 + CGI.TheDef->getName() + "'";
289
290 unsigned ModifierStart = VarEnd;
291 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
292 ++VarEnd;
293 Modifier = std::string(AsmString.begin()+ModifierStart,
294 AsmString.begin()+VarEnd);
295 if (Modifier.empty())
296 throw "Bad operand modifier name in '"+ CGI.TheDef->getName() + "'";
297 }
298
299 if (AsmString[VarEnd] != '}')
300 throw "Variable name beginning with '{' did not end with '}' in '"
301 + CGI.TheDef->getName() + "'";
302 ++VarEnd;
303 }
304 if (VarName.empty() && Modifier.empty())
305 throw "Stray '$' in '" + CGI.TheDef->getName() +
306 "' asm string, maybe you want $$?";
307
308 if (VarName.empty()) {
309 // Just a modifier, pass this into PrintSpecial.
310 Operands.push_back(AsmWriterOperand("PrintSpecial", ~0U, Modifier));
311 } else {
312 // Otherwise, normal operand.
313 unsigned OpNo = CGI.getOperandNamed(VarName);
314 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
315
316 if (CurVariant == Variant || CurVariant == ~0U) {
317 unsigned MIOp = OpInfo.MIOperandNo;
318 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp,
319 Modifier));
320 }
321 }
322 LastEmitted = VarEnd;
323 }
324 }
Evan Chengf83cbf42009-07-20 06:10:07 +0000325
David Greene8cdbfd62009-07-29 20:10:24 +0000326 Operands.push_back(
327 AsmWriterOperand("EmitComments(*MI);\n",
328 AsmWriterOperand::isLiteralStatementOperand));
Evan Chengf83cbf42009-07-20 06:10:07 +0000329 AddLiteralString("\\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330}
331
332/// MatchesAllButOneOp - If this instruction is exactly identical to the
333/// specified instruction except for one differing operand, return the differing
334/// operand number. If more than one operand mismatches, return ~1, otherwise
335/// if the instructions are identical return ~0.
336unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
337 if (Operands.size() != Other.Operands.size()) return ~1;
338
339 unsigned MismatchOperand = ~0U;
340 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Anton Korobeynikov357a27d2008-02-20 11:08:44 +0000341 if (Operands[i] != Other.Operands[i]) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342 if (MismatchOperand != ~0U) // Already have one mismatch?
343 return ~1U;
344 else
345 MismatchOperand = i;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +0000346 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347 }
348 return MismatchOperand;
349}
350
351static void PrintCases(std::vector<std::pair<std::string,
Daniel Dunbard4287062009-07-03 00:10:29 +0000352 AsmWriterOperand> > &OpsToPrint, raw_ostream &O) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000353 O << " case " << OpsToPrint.back().first << ": ";
354 AsmWriterOperand TheOp = OpsToPrint.back().second;
355 OpsToPrint.pop_back();
356
357 // Check to see if any other operands are identical in this list, and if so,
358 // emit a case label for them.
359 for (unsigned i = OpsToPrint.size(); i != 0; --i)
360 if (OpsToPrint[i-1].second == TheOp) {
361 O << "\n case " << OpsToPrint[i-1].first << ": ";
362 OpsToPrint.erase(OpsToPrint.begin()+i-1);
363 }
364
365 // Finally, emit the code.
366 O << TheOp.getCode();
367 O << "break;\n";
368}
369
370
371/// EmitInstructions - Emit the last instruction in the vector and any other
372/// instructions that are suitably similar to it.
373static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
Daniel Dunbard4287062009-07-03 00:10:29 +0000374 raw_ostream &O) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375 AsmWriterInst FirstInst = Insts.back();
376 Insts.pop_back();
377
378 std::vector<AsmWriterInst> SimilarInsts;
379 unsigned DifferingOperand = ~0;
380 for (unsigned i = Insts.size(); i != 0; --i) {
381 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
382 if (DiffOp != ~1U) {
383 if (DifferingOperand == ~0U) // First match!
384 DifferingOperand = DiffOp;
385
386 // If this differs in the same operand as the rest of the instructions in
387 // this class, move it to the SimilarInsts list.
388 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
389 SimilarInsts.push_back(Insts[i-1]);
390 Insts.erase(Insts.begin()+i-1);
391 }
392 }
393 }
394
395 O << " case " << FirstInst.CGI->Namespace << "::"
396 << FirstInst.CGI->TheDef->getName() << ":\n";
397 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
398 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
399 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
400 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
401 if (i != DifferingOperand) {
402 // If the operand is the same for all instructions, just print it.
403 O << " " << FirstInst.Operands[i].getCode();
404 } else {
405 // If this is the operand that varies between all of the instructions,
406 // emit a switch for just this operand now.
407 O << " switch (MI->getOpcode()) {\n";
408 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
409 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
410 FirstInst.CGI->TheDef->getName(),
411 FirstInst.Operands[i]));
412
413 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
414 AsmWriterInst &AWI = SimilarInsts[si];
415 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
416 AWI.CGI->TheDef->getName(),
417 AWI.Operands[i]));
418 }
419 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
420 while (!OpsToPrint.empty())
421 PrintCases(OpsToPrint, O);
422 O << " }";
423 }
424 O << "\n";
425 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000426 O << " break;\n";
427}
428
429void AsmWriterEmitter::
430FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
431 std::vector<unsigned> &InstIdxs,
432 std::vector<unsigned> &InstOpsUsed) const {
433 InstIdxs.assign(NumberedInstructions.size(), ~0U);
434
435 // This vector parallels UniqueOperandCommands, keeping track of which
436 // instructions each case are used for. It is a comma separated string of
437 // enums.
438 std::vector<std::string> InstrsForCase;
439 InstrsForCase.resize(UniqueOperandCommands.size());
440 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
441
442 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
443 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
Dan Gohmanfa607c92008-07-01 00:05:16 +0000444 if (Inst == 0) continue; // PHI, INLINEASM, DBG_LABEL, etc.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000445
446 std::string Command;
447 if (Inst->Operands.empty())
448 continue; // Instruction already done.
449
450 Command = " " + Inst->Operands[0].getCode() + "\n";
451
452 // If this is the last operand, emit a return.
Chris Lattner7d337492009-08-08 00:05:42 +0000453 if (Inst->Operands.size() == 1)
Chris Lattnerddb259a2009-08-08 01:32:19 +0000454 Command += " return;\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000455
456 // Check to see if we already have 'Command' in UniqueOperandCommands.
457 // If not, add it.
458 bool FoundIt = false;
459 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
460 if (UniqueOperandCommands[idx] == Command) {
461 InstIdxs[i] = idx;
462 InstrsForCase[idx] += ", ";
463 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
464 FoundIt = true;
465 break;
466 }
467 if (!FoundIt) {
468 InstIdxs[i] = UniqueOperandCommands.size();
469 UniqueOperandCommands.push_back(Command);
470 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
471
472 // This command matches one operand so far.
473 InstOpsUsed.push_back(1);
474 }
475 }
476
477 // For each entry of UniqueOperandCommands, there is a set of instructions
478 // that uses it. If the next command of all instructions in the set are
479 // identical, fold it into the command.
480 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
481 CommandIdx != e; ++CommandIdx) {
482
483 for (unsigned Op = 1; ; ++Op) {
484 // Scan for the first instruction in the set.
485 std::vector<unsigned>::iterator NIT =
486 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
487 if (NIT == InstIdxs.end()) break; // No commonality.
488
489 // If this instruction has no more operands, we isn't anything to merge
490 // into this command.
491 const AsmWriterInst *FirstInst =
492 getAsmWriterInstByID(NIT-InstIdxs.begin());
493 if (!FirstInst || FirstInst->Operands.size() == Op)
494 break;
495
496 // Otherwise, scan to see if all of the other instructions in this command
497 // set share the operand.
498 bool AllSame = true;
David Greene8cdbfd62009-07-29 20:10:24 +0000499 // Keep track of the maximum, number of operands or any
500 // instruction we see in the group.
501 size_t MaxSize = FirstInst->Operands.size();
502
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000503 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
504 NIT != InstIdxs.end();
505 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
506 // Okay, found another instruction in this command set. If the operand
507 // matches, we're ok, otherwise bail out.
508 const AsmWriterInst *OtherInst =
509 getAsmWriterInstByID(NIT-InstIdxs.begin());
David Greene8cdbfd62009-07-29 20:10:24 +0000510
511 if (OtherInst &&
512 OtherInst->Operands.size() > FirstInst->Operands.size())
513 MaxSize = std::max(MaxSize, OtherInst->Operands.size());
514
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000515 if (!OtherInst || OtherInst->Operands.size() == Op ||
516 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
517 AllSame = false;
518 break;
519 }
520 }
521 if (!AllSame) break;
522
523 // Okay, everything in this command set has the same next operand. Add it
524 // to UniqueOperandCommands and remember that it was consumed.
525 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
526
527 // If this is the last operand, emit a return after the code.
David Greene8cdbfd62009-07-29 20:10:24 +0000528 if (FirstInst->Operands.size() == Op+1 &&
529 // Don't early-out too soon. Other instructions in this
530 // group may have more operands.
531 FirstInst->Operands.size() == MaxSize) {
Chris Lattnerddb259a2009-08-08 01:32:19 +0000532 Command += " return;\n";
David Greene8cdbfd62009-07-29 20:10:24 +0000533 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000534
535 UniqueOperandCommands[CommandIdx] += Command;
536 InstOpsUsed[CommandIdx]++;
537 }
538 }
539
540 // Prepend some of the instructions each case is used for onto the case val.
541 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
542 std::string Instrs = InstrsForCase[i];
543 if (Instrs.size() > 70) {
544 Instrs.erase(Instrs.begin()+70, Instrs.end());
545 Instrs += "...";
546 }
547
548 if (!Instrs.empty())
549 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
550 UniqueOperandCommands[i];
551 }
552}
553
554
555
Daniel Dunbard4287062009-07-03 00:10:29 +0000556void AsmWriterEmitter::run(raw_ostream &O) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000557 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
558
559 CodeGenTarget Target;
560 Record *AsmWriter = Target.getAsmWriter();
561 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000562
563 O <<
564 "/// printInstruction - This method is automatically generated by tablegen\n"
565 "/// from the instruction set description. This method returns true if the\n"
566 "/// machine instruction was sufficiently described to print it, otherwise\n"
567 "/// it returns false.\n"
Chris Lattnerddb259a2009-08-08 01:32:19 +0000568 "void " << Target.getName() << ClassName
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000569 << "::printInstruction(const MachineInstr *MI) {\n";
570
571 std::vector<AsmWriterInst> Instructions;
572
573 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
574 E = Target.inst_end(); I != E; ++I)
575 if (!I->second.AsmString.empty())
Chris Lattnerbffb6252009-08-07 23:13:38 +0000576 Instructions.push_back(AsmWriterInst(I->second, AsmWriter));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000577
578 // Get the instruction numbering.
579 Target.getInstructionsByEnumValue(NumberedInstructions);
580
581 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
582 // all machine instructions are necessarily being printed, so there may be
583 // target instructions not in this map.
584 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
585 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
586
587 // Build an aggregate string, and build a table of offsets into it.
588 std::map<std::string, unsigned> StringOffset;
589 std::string AggregateString;
590 AggregateString.push_back(0); // "\0"
591 AggregateString.push_back(0); // "\0"
592
593 /// OpcodeInfo - This encodes the index of the string to use for the first
594 /// chunk of the output as well as indices used for operand printing.
595 std::vector<unsigned> OpcodeInfo;
596
597 unsigned MaxStringIdx = 0;
598 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
599 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
600 unsigned Idx;
601 if (AWI == 0) {
602 // Something not handled by the asmwriter printer.
603 Idx = 0;
604 } else if (AWI->Operands[0].OperandType !=
605 AsmWriterOperand::isLiteralTextOperand ||
606 AWI->Operands[0].Str.empty()) {
607 // Something handled by the asmwriter printer, but with no leading string.
608 Idx = 1;
609 } else {
610 unsigned &Entry = StringOffset[AWI->Operands[0].Str];
611 if (Entry == 0) {
612 // Add the string to the aggregate if this is the first time found.
613 MaxStringIdx = Entry = AggregateString.size();
614 std::string Str = AWI->Operands[0].Str;
615 UnescapeString(Str);
616 AggregateString += Str;
617 AggregateString += '\0';
618 }
619 Idx = Entry;
620
621 // Nuke the string from the operand list. It is now handled!
622 AWI->Operands.erase(AWI->Operands.begin());
623 }
624 OpcodeInfo.push_back(Idx);
625 }
626
627 // Figure out how many bits we used for the string index.
Nate Begemanb6fc8db2008-04-09 16:24:11 +0000628 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000629
630 // To reduce code size, we compactify common instructions into a few bits
631 // in the opcode-indexed table.
632 unsigned BitsLeft = 32-AsmStrBits;
633
634 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
635
636 bool isFirst = true;
637 while (1) {
638 std::vector<std::string> UniqueOperandCommands;
639
640 // For the first operand check, add a default value for instructions with
641 // just opcode strings to use.
642 if (isFirst) {
Chris Lattnerddb259a2009-08-08 01:32:19 +0000643 UniqueOperandCommands.push_back(" return;\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000644 isFirst = false;
645 }
David Greene8cdbfd62009-07-29 20:10:24 +0000646
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000647 std::vector<unsigned> InstIdxs;
648 std::vector<unsigned> NumInstOpsHandled;
649 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
650 NumInstOpsHandled);
651
652 // If we ran out of operands to print, we're done.
653 if (UniqueOperandCommands.empty()) break;
654
655 // Compute the number of bits we need to represent these cases, this is
656 // ceil(log2(numentries)).
657 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
658
659 // If we don't have enough bits for this operand, don't include it.
660 if (NumBits > BitsLeft) {
Chris Lattner006d7d82009-08-23 04:44:11 +0000661 DEBUG(errs() << "Not enough bits to densely encode " << NumBits
662 << " more bits\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000663 break;
664 }
665
666 // Otherwise, we can include this in the initial lookup table. Add it in.
667 BitsLeft -= NumBits;
668 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
669 if (InstIdxs[i] != ~0U)
670 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
671
672 // Remove the info about this operand.
673 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
674 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
675 if (!Inst->Operands.empty()) {
676 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
677 assert(NumOps <= Inst->Operands.size() &&
678 "Can't remove this many ops!");
679 Inst->Operands.erase(Inst->Operands.begin(),
680 Inst->Operands.begin()+NumOps);
681 }
682 }
683
684 // Remember the handlers for this set of operands.
685 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
686 }
687
688
689
690 O<<" static const unsigned OpInfo[] = {\n";
691 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
692 O << " " << OpcodeInfo[i] << "U,\t// "
693 << NumberedInstructions[i]->TheDef->getName() << "\n";
694 }
695 // Add a dummy entry so the array init doesn't end with a comma.
696 O << " 0U\n";
697 O << " };\n\n";
698
699 // Emit the string itself.
700 O << " const char *AsmStrs = \n \"";
701 unsigned CharsPrinted = 0;
702 EscapeString(AggregateString);
703 for (unsigned i = 0, e = AggregateString.size(); i != e; ++i) {
704 if (CharsPrinted > 70) {
705 O << "\"\n \"";
706 CharsPrinted = 0;
707 }
708 O << AggregateString[i];
709 ++CharsPrinted;
710
711 // Print escape sequences all together.
712 if (AggregateString[i] == '\\') {
713 assert(i+1 < AggregateString.size() && "Incomplete escape sequence!");
714 if (isdigit(AggregateString[i+1])) {
715 assert(isdigit(AggregateString[i+2]) && isdigit(AggregateString[i+3]) &&
716 "Expected 3 digit octal escape!");
717 O << AggregateString[++i];
718 O << AggregateString[++i];
719 O << AggregateString[++i];
720 CharsPrinted += 3;
721 } else {
722 O << AggregateString[++i];
723 ++CharsPrinted;
724 }
725 }
726 }
727 O << "\";\n\n";
728
Argiris Kirtzidis3f997f82009-05-07 13:55:51 +0000729 O << " processDebugLoc(MI->getDebugLoc());\n\n";
Bill Wendling4ff1cdf2009-02-18 23:12:06 +0000730
Chris Lattnerbfc9b7e2009-06-19 23:57:53 +0000731 O << "\n#ifndef NO_ASM_WRITER_BOILERPLATE\n";
732
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733 O << " if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {\n"
Evan Cheng8b988692008-02-02 08:39:46 +0000734 << " O << \"\\t\";\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000735 << " printInlineAsm(MI);\n"
Chris Lattnerddb259a2009-08-08 01:32:19 +0000736 << " return;\n"
Dan Gohmanfa607c92008-07-01 00:05:16 +0000737 << " } else if (MI->isLabel()) {\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000738 << " printLabel(MI);\n"
Chris Lattnerddb259a2009-08-08 01:32:19 +0000739 << " return;\n"
Evan Cheng3c0eda52008-03-15 00:03:38 +0000740 << " } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {\n"
741 << " printImplicitDef(MI);\n"
Chris Lattnerddb259a2009-08-08 01:32:19 +0000742 << " return;\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000743 << " }\n\n";
Chris Lattnerbfc9b7e2009-06-19 23:57:53 +0000744
745 O << "\n#endif\n";
746
Evan Cheng8b988692008-02-02 08:39:46 +0000747 O << " O << \"\\t\";\n\n";
748
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000749 O << " // Emit the opcode for the instruction.\n"
750 << " unsigned Bits = OpInfo[MI->getOpcode()];\n"
Chris Lattnerddb259a2009-08-08 01:32:19 +0000751 << " assert(Bits != 0 && \"Cannot print this instruction.\");\n"
David Greenecdc2de32009-08-05 21:00:52 +0000752 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ");\n\n";
753
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754 // Output the table driven operand information.
755 BitsLeft = 32-AsmStrBits;
756 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
757 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
758
759 // Compute the number of bits we need to represent these cases, this is
760 // ceil(log2(numentries)).
761 unsigned NumBits = Log2_32_Ceil(Commands.size());
762 assert(NumBits <= BitsLeft && "consistency error");
763
764 // Emit code to extract this field from Bits.
765 BitsLeft -= NumBits;
766
767 O << "\n // Fragment " << i << " encoded into " << NumBits
768 << " bits for " << Commands.size() << " unique commands.\n";
769
770 if (Commands.size() == 2) {
771 // Emit two possibilitys with if/else.
772 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
773 << ((1 << NumBits)-1) << ") {\n"
774 << Commands[1]
775 << " } else {\n"
776 << Commands[0]
777 << " }\n\n";
778 } else {
779 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
780 << ((1 << NumBits)-1) << ") {\n"
781 << " default: // unreachable.\n";
782
783 // Print out all the cases.
784 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
785 O << " case " << i << ":\n";
786 O << Commands[i];
787 O << " break;\n";
788 }
789 O << " }\n\n";
790 }
791 }
792
793 // Okay, delete instructions with no operand info left.
794 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
795 // Entire instruction has been emitted?
796 AsmWriterInst &Inst = Instructions[i];
797 if (Inst.Operands.empty()) {
798 Instructions.erase(Instructions.begin()+i);
799 --i; --e;
800 }
801 }
802
803
804 // Because this is a vector, we want to emit from the end. Reverse all of the
805 // elements in the vector.
806 std::reverse(Instructions.begin(), Instructions.end());
807
808 if (!Instructions.empty()) {
809 // Find the opcode # of inline asm.
810 O << " switch (MI->getOpcode()) {\n";
811 while (!Instructions.empty())
812 EmitInstructions(Instructions, O);
813
814 O << " }\n";
Chris Lattnerddb259a2009-08-08 01:32:19 +0000815 O << " return;\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000816 }
David Greene8cdbfd62009-07-29 20:10:24 +0000817
Chris Lattnerddb259a2009-08-08 01:32:19 +0000818 O << " return;\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000819 O << "}\n";
820}