Use SequenceToOffsetTable in emitRegisterNameString.
[oota-llvm.git] / utils / TableGen / AsmWriterEmitter.cpp
1 //===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
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 "AsmWriterInst.h"
17 #include "CodeGenTarget.h"
18 #include "StringToOffsetTable.h"
19 #include "SequenceToOffsetTable.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/TableGen/Error.h"
24 #include "llvm/TableGen/Record.h"
25 #include <algorithm>
26 using namespace llvm;
27
28 static void PrintCases(std::vector<std::pair<std::string,
29                        AsmWriterOperand> > &OpsToPrint, raw_ostream &O) {
30   O << "    case " << OpsToPrint.back().first << ": ";
31   AsmWriterOperand TheOp = OpsToPrint.back().second;
32   OpsToPrint.pop_back();
33
34   // Check to see if any other operands are identical in this list, and if so,
35   // emit a case label for them.
36   for (unsigned i = OpsToPrint.size(); i != 0; --i)
37     if (OpsToPrint[i-1].second == TheOp) {
38       O << "\n    case " << OpsToPrint[i-1].first << ": ";
39       OpsToPrint.erase(OpsToPrint.begin()+i-1);
40     }
41
42   // Finally, emit the code.
43   O << TheOp.getCode();
44   O << "break;\n";
45 }
46
47
48 /// EmitInstructions - Emit the last instruction in the vector and any other
49 /// instructions that are suitably similar to it.
50 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
51                              raw_ostream &O) {
52   AsmWriterInst FirstInst = Insts.back();
53   Insts.pop_back();
54
55   std::vector<AsmWriterInst> SimilarInsts;
56   unsigned DifferingOperand = ~0;
57   for (unsigned i = Insts.size(); i != 0; --i) {
58     unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
59     if (DiffOp != ~1U) {
60       if (DifferingOperand == ~0U)  // First match!
61         DifferingOperand = DiffOp;
62
63       // If this differs in the same operand as the rest of the instructions in
64       // this class, move it to the SimilarInsts list.
65       if (DifferingOperand == DiffOp || DiffOp == ~0U) {
66         SimilarInsts.push_back(Insts[i-1]);
67         Insts.erase(Insts.begin()+i-1);
68       }
69     }
70   }
71
72   O << "  case " << FirstInst.CGI->Namespace << "::"
73     << FirstInst.CGI->TheDef->getName() << ":\n";
74   for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
75     O << "  case " << SimilarInsts[i].CGI->Namespace << "::"
76       << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
77   for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
78     if (i != DifferingOperand) {
79       // If the operand is the same for all instructions, just print it.
80       O << "    " << FirstInst.Operands[i].getCode();
81     } else {
82       // If this is the operand that varies between all of the instructions,
83       // emit a switch for just this operand now.
84       O << "    switch (MI->getOpcode()) {\n";
85       std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
86       OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
87                                           FirstInst.CGI->TheDef->getName(),
88                                           FirstInst.Operands[i]));
89
90       for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
91         AsmWriterInst &AWI = SimilarInsts[si];
92         OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
93                                             AWI.CGI->TheDef->getName(),
94                                             AWI.Operands[i]));
95       }
96       std::reverse(OpsToPrint.begin(), OpsToPrint.end());
97       while (!OpsToPrint.empty())
98         PrintCases(OpsToPrint, O);
99       O << "    }";
100     }
101     O << "\n";
102   }
103   O << "    break;\n";
104 }
105
106 void AsmWriterEmitter::
107 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
108                           std::vector<unsigned> &InstIdxs,
109                           std::vector<unsigned> &InstOpsUsed) const {
110   InstIdxs.assign(NumberedInstructions.size(), ~0U);
111
112   // This vector parallels UniqueOperandCommands, keeping track of which
113   // instructions each case are used for.  It is a comma separated string of
114   // enums.
115   std::vector<std::string> InstrsForCase;
116   InstrsForCase.resize(UniqueOperandCommands.size());
117   InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
118
119   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
120     const AsmWriterInst *Inst = getAsmWriterInstByID(i);
121     if (Inst == 0) continue;  // PHI, INLINEASM, PROLOG_LABEL, etc.
122
123     std::string Command;
124     if (Inst->Operands.empty())
125       continue;   // Instruction already done.
126
127     Command = "    " + Inst->Operands[0].getCode() + "\n";
128
129     // Check to see if we already have 'Command' in UniqueOperandCommands.
130     // If not, add it.
131     bool FoundIt = false;
132     for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
133       if (UniqueOperandCommands[idx] == Command) {
134         InstIdxs[i] = idx;
135         InstrsForCase[idx] += ", ";
136         InstrsForCase[idx] += Inst->CGI->TheDef->getName();
137         FoundIt = true;
138         break;
139       }
140     if (!FoundIt) {
141       InstIdxs[i] = UniqueOperandCommands.size();
142       UniqueOperandCommands.push_back(Command);
143       InstrsForCase.push_back(Inst->CGI->TheDef->getName());
144
145       // This command matches one operand so far.
146       InstOpsUsed.push_back(1);
147     }
148   }
149
150   // For each entry of UniqueOperandCommands, there is a set of instructions
151   // that uses it.  If the next command of all instructions in the set are
152   // identical, fold it into the command.
153   for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
154        CommandIdx != e; ++CommandIdx) {
155
156     for (unsigned Op = 1; ; ++Op) {
157       // Scan for the first instruction in the set.
158       std::vector<unsigned>::iterator NIT =
159         std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
160       if (NIT == InstIdxs.end()) break;  // No commonality.
161
162       // If this instruction has no more operands, we isn't anything to merge
163       // into this command.
164       const AsmWriterInst *FirstInst =
165         getAsmWriterInstByID(NIT-InstIdxs.begin());
166       if (!FirstInst || FirstInst->Operands.size() == Op)
167         break;
168
169       // Otherwise, scan to see if all of the other instructions in this command
170       // set share the operand.
171       bool AllSame = true;
172       // Keep track of the maximum, number of operands or any
173       // instruction we see in the group.
174       size_t MaxSize = FirstInst->Operands.size();
175
176       for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
177            NIT != InstIdxs.end();
178            NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
179         // Okay, found another instruction in this command set.  If the operand
180         // matches, we're ok, otherwise bail out.
181         const AsmWriterInst *OtherInst =
182           getAsmWriterInstByID(NIT-InstIdxs.begin());
183
184         if (OtherInst &&
185             OtherInst->Operands.size() > FirstInst->Operands.size())
186           MaxSize = std::max(MaxSize, OtherInst->Operands.size());
187
188         if (!OtherInst || OtherInst->Operands.size() == Op ||
189             OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
190           AllSame = false;
191           break;
192         }
193       }
194       if (!AllSame) break;
195
196       // Okay, everything in this command set has the same next operand.  Add it
197       // to UniqueOperandCommands and remember that it was consumed.
198       std::string Command = "    " + FirstInst->Operands[Op].getCode() + "\n";
199
200       UniqueOperandCommands[CommandIdx] += Command;
201       InstOpsUsed[CommandIdx]++;
202     }
203   }
204
205   // Prepend some of the instructions each case is used for onto the case val.
206   for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
207     std::string Instrs = InstrsForCase[i];
208     if (Instrs.size() > 70) {
209       Instrs.erase(Instrs.begin()+70, Instrs.end());
210       Instrs += "...";
211     }
212
213     if (!Instrs.empty())
214       UniqueOperandCommands[i] = "    // " + Instrs + "\n" +
215         UniqueOperandCommands[i];
216   }
217 }
218
219
220 static void UnescapeString(std::string &Str) {
221   for (unsigned i = 0; i != Str.size(); ++i) {
222     if (Str[i] == '\\' && i != Str.size()-1) {
223       switch (Str[i+1]) {
224       default: continue;  // Don't execute the code after the switch.
225       case 'a': Str[i] = '\a'; break;
226       case 'b': Str[i] = '\b'; break;
227       case 'e': Str[i] = 27; break;
228       case 'f': Str[i] = '\f'; break;
229       case 'n': Str[i] = '\n'; break;
230       case 'r': Str[i] = '\r'; break;
231       case 't': Str[i] = '\t'; break;
232       case 'v': Str[i] = '\v'; break;
233       case '"': Str[i] = '\"'; break;
234       case '\'': Str[i] = '\''; break;
235       case '\\': Str[i] = '\\'; break;
236       }
237       // Nuke the second character.
238       Str.erase(Str.begin()+i+1);
239     }
240   }
241 }
242
243 /// EmitPrintInstruction - Generate the code for the "printInstruction" method
244 /// implementation.
245 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
246   CodeGenTarget Target(Records);
247   Record *AsmWriter = Target.getAsmWriter();
248   std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
249   bool isMC = AsmWriter->getValueAsBit("isMCAsmWriter");
250   const char *MachineInstrClassName = isMC ? "MCInst" : "MachineInstr";
251
252   O <<
253   "/// printInstruction - This method is automatically generated by tablegen\n"
254   "/// from the instruction set description.\n"
255     "void " << Target.getName() << ClassName
256             << "::printInstruction(const " << MachineInstrClassName
257             << " *MI, raw_ostream &O) {\n";
258
259   std::vector<AsmWriterInst> Instructions;
260
261   for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
262          E = Target.inst_end(); I != E; ++I)
263     if (!(*I)->AsmString.empty() &&
264         (*I)->TheDef->getName() != "PHI")
265       Instructions.push_back(
266         AsmWriterInst(**I,
267                       AsmWriter->getValueAsInt("Variant"),
268                       AsmWriter->getValueAsInt("FirstOperandColumn"),
269                       AsmWriter->getValueAsInt("OperandSpacing")));
270
271   // Get the instruction numbering.
272   NumberedInstructions = Target.getInstructionsByEnumValue();
273
274   // Compute the CodeGenInstruction -> AsmWriterInst mapping.  Note that not
275   // all machine instructions are necessarily being printed, so there may be
276   // target instructions not in this map.
277   for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
278     CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
279
280   // Build an aggregate string, and build a table of offsets into it.
281   StringToOffsetTable StringTable;
282
283   /// OpcodeInfo - This encodes the index of the string to use for the first
284   /// chunk of the output as well as indices used for operand printing.
285   std::vector<unsigned> OpcodeInfo;
286
287   unsigned MaxStringIdx = 0;
288   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
289     AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
290     unsigned Idx;
291     if (AWI == 0) {
292       // Something not handled by the asmwriter printer.
293       Idx = ~0U;
294     } else if (AWI->Operands[0].OperandType !=
295                         AsmWriterOperand::isLiteralTextOperand ||
296                AWI->Operands[0].Str.empty()) {
297       // Something handled by the asmwriter printer, but with no leading string.
298       Idx = StringTable.GetOrAddStringOffset("");
299     } else {
300       std::string Str = AWI->Operands[0].Str;
301       UnescapeString(Str);
302       Idx = StringTable.GetOrAddStringOffset(Str);
303       MaxStringIdx = std::max(MaxStringIdx, Idx);
304
305       // Nuke the string from the operand list.  It is now handled!
306       AWI->Operands.erase(AWI->Operands.begin());
307     }
308
309     // Bias offset by one since we want 0 as a sentinel.
310     OpcodeInfo.push_back(Idx+1);
311   }
312
313   // Figure out how many bits we used for the string index.
314   unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
315
316   // To reduce code size, we compactify common instructions into a few bits
317   // in the opcode-indexed table.
318   unsigned BitsLeft = 32-AsmStrBits;
319
320   std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
321
322   while (1) {
323     std::vector<std::string> UniqueOperandCommands;
324     std::vector<unsigned> InstIdxs;
325     std::vector<unsigned> NumInstOpsHandled;
326     FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
327                               NumInstOpsHandled);
328
329     // If we ran out of operands to print, we're done.
330     if (UniqueOperandCommands.empty()) break;
331
332     // Compute the number of bits we need to represent these cases, this is
333     // ceil(log2(numentries)).
334     unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
335
336     // If we don't have enough bits for this operand, don't include it.
337     if (NumBits > BitsLeft) {
338       DEBUG(errs() << "Not enough bits to densely encode " << NumBits
339                    << " more bits\n");
340       break;
341     }
342
343     // Otherwise, we can include this in the initial lookup table.  Add it in.
344     BitsLeft -= NumBits;
345     for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
346       if (InstIdxs[i] != ~0U)
347         OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
348
349     // Remove the info about this operand.
350     for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
351       if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
352         if (!Inst->Operands.empty()) {
353           unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
354           assert(NumOps <= Inst->Operands.size() &&
355                  "Can't remove this many ops!");
356           Inst->Operands.erase(Inst->Operands.begin(),
357                                Inst->Operands.begin()+NumOps);
358         }
359     }
360
361     // Remember the handlers for this set of operands.
362     TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
363   }
364
365
366
367   O<<"  static const unsigned OpInfo[] = {\n";
368   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
369     O << "    " << OpcodeInfo[i] << "U,\t// "
370       << NumberedInstructions[i]->TheDef->getName() << "\n";
371   }
372   // Add a dummy entry so the array init doesn't end with a comma.
373   O << "    0U\n";
374   O << "  };\n\n";
375
376   // Emit the string itself.
377   O << "  const char *AsmStrs = \n";
378   StringTable.EmitString(O);
379   O << ";\n\n";
380
381   O << "  O << \"\\t\";\n\n";
382
383   O << "  // Emit the opcode for the instruction.\n"
384     << "  unsigned Bits = OpInfo[MI->getOpcode()];\n"
385     << "  assert(Bits != 0 && \"Cannot print this instruction.\");\n"
386     << "  O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
387
388   // Output the table driven operand information.
389   BitsLeft = 32-AsmStrBits;
390   for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
391     std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
392
393     // Compute the number of bits we need to represent these cases, this is
394     // ceil(log2(numentries)).
395     unsigned NumBits = Log2_32_Ceil(Commands.size());
396     assert(NumBits <= BitsLeft && "consistency error");
397
398     // Emit code to extract this field from Bits.
399     BitsLeft -= NumBits;
400
401     O << "\n  // Fragment " << i << " encoded into " << NumBits
402       << " bits for " << Commands.size() << " unique commands.\n";
403
404     if (Commands.size() == 2) {
405       // Emit two possibilitys with if/else.
406       O << "  if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
407         << ((1 << NumBits)-1) << ") {\n"
408         << Commands[1]
409         << "  } else {\n"
410         << Commands[0]
411         << "  }\n\n";
412     } else if (Commands.size() == 1) {
413       // Emit a single possibility.
414       O << Commands[0] << "\n\n";
415     } else {
416       O << "  switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
417         << ((1 << NumBits)-1) << ") {\n"
418         << "  default:   // unreachable.\n";
419
420       // Print out all the cases.
421       for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
422         O << "  case " << i << ":\n";
423         O << Commands[i];
424         O << "    break;\n";
425       }
426       O << "  }\n\n";
427     }
428   }
429
430   // Okay, delete instructions with no operand info left.
431   for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
432     // Entire instruction has been emitted?
433     AsmWriterInst &Inst = Instructions[i];
434     if (Inst.Operands.empty()) {
435       Instructions.erase(Instructions.begin()+i);
436       --i; --e;
437     }
438   }
439
440
441   // Because this is a vector, we want to emit from the end.  Reverse all of the
442   // elements in the vector.
443   std::reverse(Instructions.begin(), Instructions.end());
444
445
446   // Now that we've emitted all of the operand info that fit into 32 bits, emit
447   // information for those instructions that are left.  This is a less dense
448   // encoding, but we expect the main 32-bit table to handle the majority of
449   // instructions.
450   if (!Instructions.empty()) {
451     // Find the opcode # of inline asm.
452     O << "  switch (MI->getOpcode()) {\n";
453     while (!Instructions.empty())
454       EmitInstructions(Instructions, O);
455
456     O << "  }\n";
457     O << "  return;\n";
458   }
459
460   O << "}\n";
461 }
462
463 static void
464 emitRegisterNameString(raw_ostream &O, StringRef AltName,
465   const std::vector<CodeGenRegister*> &Registers) {
466   SequenceToOffsetTable<std::string> StringTable;
467   SmallVector<std::string, 4> AsmNames(Registers.size());
468   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
469     const CodeGenRegister &Reg = *Registers[i];
470     std::string &AsmName = AsmNames[i];
471
472     // "NoRegAltName" is special. We don't need to do a lookup for that,
473     // as it's just a reference to the default register name.
474     if (AltName == "" || AltName == "NoRegAltName") {
475       AsmName = Reg.TheDef->getValueAsString("AsmName");
476       if (AsmName.empty())
477         AsmName = Reg.getName();
478     } else {
479       // Make sure the register has an alternate name for this index.
480       std::vector<Record*> AltNameList =
481         Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
482       unsigned Idx = 0, e;
483       for (e = AltNameList.size();
484            Idx < e && (AltNameList[Idx]->getName() != AltName);
485            ++Idx)
486         ;
487       // If the register has an alternate name for this index, use it.
488       // Otherwise, leave it empty as an error flag.
489       if (Idx < e) {
490         std::vector<std::string> AltNames =
491           Reg.TheDef->getValueAsListOfStrings("AltNames");
492         if (AltNames.size() <= Idx)
493           throw TGError(Reg.TheDef->getLoc(),
494                         (Twine("Register definition missing alt name for '") +
495                         AltName + "'.").str());
496         AsmName = AltNames[Idx];
497       }
498     }
499     StringTable.add(AsmName);
500   }
501
502   StringTable.layout();
503   O << "  static const char AsmStrs" << AltName << "[] = {\n";
504   StringTable.emit(O, printChar);
505   O << "  };\n\n";
506
507   O << "  static const unsigned RegAsmOffset" << AltName << "[] = {\n    ";
508   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
509     O << StringTable.get(AsmNames[i]);
510     if (((i + 1) % 14) == 0)
511       O << ",\n    ";
512     else
513       O << ", ";
514
515   }
516   O << "0\n"
517     << "  };\n"
518     << "\n";
519 }
520
521 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
522   CodeGenTarget Target(Records);
523   Record *AsmWriter = Target.getAsmWriter();
524   std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
525   const std::vector<CodeGenRegister*> &Registers =
526     Target.getRegBank().getRegisters();
527   std::vector<Record*> AltNameIndices = Target.getRegAltNameIndices();
528   bool hasAltNames = AltNameIndices.size() > 1;
529
530   O <<
531   "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
532   "/// from the register set description.  This returns the assembler name\n"
533   "/// for the specified register.\n"
534   "const char *" << Target.getName() << ClassName << "::";
535   if (hasAltNames)
536     O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
537   else
538     O << "getRegisterName(unsigned RegNo) {\n";
539   O << "  assert(RegNo && RegNo < " << (Registers.size()+1)
540     << " && \"Invalid register number!\");\n"
541     << "\n";
542
543   if (hasAltNames) {
544     for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i)
545       emitRegisterNameString(O, AltNameIndices[i]->getName(), Registers);
546   } else
547     emitRegisterNameString(O, "", Registers);
548
549   if (hasAltNames) {
550     O << "  const unsigned *RegAsmOffset;\n"
551       << "  const char *AsmStrs;\n"
552       << "  switch(AltIdx) {\n"
553       << "  default: llvm_unreachable(\"Invalid register alt name index!\");\n";
554     for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i) {
555       StringRef Namespace = AltNameIndices[1]->getValueAsString("Namespace");
556       StringRef AltName(AltNameIndices[i]->getName());
557       O << "  case " << Namespace << "::" << AltName
558         << ":\n"
559         << "    AsmStrs = AsmStrs" << AltName  << ";\n"
560         << "    RegAsmOffset = RegAsmOffset" << AltName << ";\n"
561         << "    break;\n";
562     }
563     O << "}\n";
564   }
565
566   O << "  assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
567     << "          \"Invalid alt name index for register!\");\n"
568     << "  return AsmStrs+RegAsmOffset[RegNo-1];\n"
569     << "}\n";
570 }
571
572 void AsmWriterEmitter::EmitGetInstructionName(raw_ostream &O) {
573   CodeGenTarget Target(Records);
574   Record *AsmWriter = Target.getAsmWriter();
575   std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
576
577   const std::vector<const CodeGenInstruction*> &NumberedInstructions =
578     Target.getInstructionsByEnumValue();
579
580   StringToOffsetTable StringTable;
581   O <<
582 "\n\n#ifdef GET_INSTRUCTION_NAME\n"
583 "#undef GET_INSTRUCTION_NAME\n\n"
584 "/// getInstructionName: This method is automatically generated by tblgen\n"
585 "/// from the instruction set description.  This returns the enum name of the\n"
586 "/// specified instruction.\n"
587   "const char *" << Target.getName() << ClassName
588   << "::getInstructionName(unsigned Opcode) {\n"
589   << "  assert(Opcode < " << NumberedInstructions.size()
590   << " && \"Invalid instruction number!\");\n"
591   << "\n"
592   << "  static const unsigned InstAsmOffset[] = {";
593   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
594     const CodeGenInstruction &Inst = *NumberedInstructions[i];
595
596     std::string AsmName = Inst.TheDef->getName();
597     if ((i % 14) == 0)
598       O << "\n    ";
599
600     O << StringTable.GetOrAddStringOffset(AsmName) << ", ";
601   }
602   O << "0\n"
603   << "  };\n"
604   << "\n";
605
606   O << "  const char *Strs =\n";
607   StringTable.EmitString(O);
608   O << ";\n";
609
610   O << "  return Strs+InstAsmOffset[Opcode];\n"
611   << "}\n\n#endif\n";
612 }
613
614 namespace {
615 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
616 // they both have the same conditionals. In which case, we cannot print out the
617 // alias for that pattern.
618 class IAPrinter {
619   std::vector<std::string> Conds;
620   std::map<StringRef, unsigned> OpMap;
621   std::string Result;
622   std::string AsmString;
623   std::vector<Record*> ReqFeatures;
624 public:
625   IAPrinter(std::string R, std::string AS)
626     : Result(R), AsmString(AS) {}
627
628   void addCond(const std::string &C) { Conds.push_back(C); }
629
630   void addOperand(StringRef Op, unsigned Idx) { OpMap[Op] = Idx; }
631   unsigned getOpIndex(StringRef Op) { return OpMap[Op]; }
632   bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
633
634   void print(raw_ostream &O) {
635     if (Conds.empty() && ReqFeatures.empty()) {
636       O.indent(6) << "return true;\n";
637       return;
638     }
639
640     O << "if (";
641
642     for (std::vector<std::string>::iterator
643            I = Conds.begin(), E = Conds.end(); I != E; ++I) {
644       if (I != Conds.begin()) {
645         O << " &&\n";
646         O.indent(8);
647       }
648
649       O << *I;
650     }
651
652     O << ") {\n";
653     O.indent(6) << "// " << Result << "\n";
654     O.indent(6) << "AsmString = \"" << AsmString << "\";\n";
655
656     for (std::map<StringRef, unsigned>::iterator
657            I = OpMap.begin(), E = OpMap.end(); I != E; ++I)
658       O.indent(6) << "OpMap.push_back(std::make_pair(\"" << I->first << "\", "
659                   << I->second << "));\n";
660
661     O.indent(6) << "break;\n";
662     O.indent(4) << '}';
663   }
664
665   bool operator==(const IAPrinter &RHS) {
666     if (Conds.size() != RHS.Conds.size())
667       return false;
668
669     unsigned Idx = 0;
670     for (std::vector<std::string>::iterator
671            I = Conds.begin(), E = Conds.end(); I != E; ++I)
672       if (*I != RHS.Conds[Idx++])
673         return false;
674
675     return true;
676   }
677
678   bool operator()(const IAPrinter &RHS) {
679     if (Conds.size() < RHS.Conds.size())
680       return true;
681
682     unsigned Idx = 0;
683     for (std::vector<std::string>::iterator
684            I = Conds.begin(), E = Conds.end(); I != E; ++I)
685       if (*I != RHS.Conds[Idx++])
686         return *I < RHS.Conds[Idx++];
687
688     return false;
689   }
690 };
691
692 } // end anonymous namespace
693
694 static void EmitGetMapOperandNumber(raw_ostream &O) {
695   O << "static unsigned getMapOperandNumber("
696     << "const SmallVectorImpl<std::pair<StringRef, unsigned> > &OpMap,\n";
697   O << "                                    StringRef Name) {\n";
698   O << "  for (SmallVectorImpl<std::pair<StringRef, unsigned> >::"
699     << "const_iterator\n";
700   O << "         I = OpMap.begin(), E = OpMap.end(); I != E; ++I)\n";
701   O << "    if (I->first == Name)\n";
702   O << "      return I->second;\n";
703   O << "  assert(false && \"Operand not in map!\");\n";
704   O << "  return 0;\n";
705   O << "}\n\n";
706 }
707
708 void AsmWriterEmitter::EmitRegIsInRegClass(raw_ostream &O) {
709   CodeGenTarget Target(Records);
710
711   // Enumerate the register classes.
712   ArrayRef<CodeGenRegisterClass*> RegisterClasses =
713     Target.getRegBank().getRegClasses();
714
715   O << "namespace { // Register classes\n";
716   O << "  enum RegClass {\n";
717
718   // Emit the register enum value for each RegisterClass.
719   for (unsigned I = 0, E = RegisterClasses.size(); I != E; ++I) {
720     if (I != 0) O << ",\n";
721     O << "    RC_" << RegisterClasses[I]->getName();
722   }
723
724   O << "\n  };\n";
725   O << "} // end anonymous namespace\n\n";
726
727   // Emit a function that returns 'true' if a regsiter is part of a particular
728   // register class. I.e., RAX is part of GR64 on X86.
729   O << "static bool regIsInRegisterClass"
730     << "(unsigned RegClass, unsigned Reg) {\n";
731
732   // Emit the switch that checks if a register belongs to a particular register
733   // class.
734   O << "  switch (RegClass) {\n";
735   O << "  default: break;\n";
736
737   for (unsigned I = 0, E = RegisterClasses.size(); I != E; ++I) {
738     const CodeGenRegisterClass &RC = *RegisterClasses[I];
739
740     // Give the register class a legal C name if it's anonymous.
741     std::string Name = RC.getName();
742     O << "  case RC_" << Name << ":\n";
743   
744     // Emit the register list now.
745     unsigned IE = RC.getOrder().size();
746     if (IE == 1) {
747       O << "    if (Reg == " << getQualifiedName(RC.getOrder()[0]) << ")\n";
748       O << "      return true;\n";
749     } else {
750       O << "    switch (Reg) {\n";
751       O << "    default: break;\n";
752
753       for (unsigned II = 0; II != IE; ++II) {
754         Record *Reg = RC.getOrder()[II];
755         O << "    case " << getQualifiedName(Reg) << ":\n";
756       }
757
758       O << "      return true;\n";
759       O << "    }\n";
760     }
761
762     O << "    break;\n";
763   }
764
765   O << "  }\n\n";
766   O << "  return false;\n";
767   O << "}\n\n";
768 }
769
770 static unsigned CountNumOperands(StringRef AsmString) {
771   unsigned NumOps = 0;
772   std::pair<StringRef, StringRef> ASM = AsmString.split(' ');
773
774   while (!ASM.second.empty()) {
775     ++NumOps;
776     ASM = ASM.second.split(' ');
777   }
778
779   return NumOps;
780 }
781
782 static unsigned CountResultNumOperands(StringRef AsmString) {
783   unsigned NumOps = 0;
784   std::pair<StringRef, StringRef> ASM = AsmString.split('\t');
785
786   if (!ASM.second.empty()) {
787     size_t I = ASM.second.find('{');
788     StringRef Str = ASM.second;
789     if (I != StringRef::npos)
790       Str = ASM.second.substr(I, ASM.second.find('|', I));
791
792     ASM = Str.split(' ');
793
794     do {
795       ++NumOps;
796       ASM = ASM.second.split(' ');
797     } while (!ASM.second.empty());
798   }
799
800   return NumOps;
801 }
802
803 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
804   CodeGenTarget Target(Records);
805   Record *AsmWriter = Target.getAsmWriter();
806
807   if (!AsmWriter->getValueAsBit("isMCAsmWriter"))
808     return;
809
810   O << "\n#ifdef PRINT_ALIAS_INSTR\n";
811   O << "#undef PRINT_ALIAS_INSTR\n\n";
812
813   EmitRegIsInRegClass(O);
814
815   // Emit the method that prints the alias instruction.
816   std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
817
818   std::vector<Record*> AllInstAliases =
819     Records.getAllDerivedDefinitions("InstAlias");
820
821   // Create a map from the qualified name to a list of potential matches.
822   std::map<std::string, std::vector<CodeGenInstAlias*> > AliasMap;
823   for (std::vector<Record*>::iterator
824          I = AllInstAliases.begin(), E = AllInstAliases.end(); I != E; ++I) {
825     CodeGenInstAlias *Alias = new CodeGenInstAlias(*I, Target);
826     const Record *R = *I;
827     if (!R->getValueAsBit("EmitAlias"))
828       continue; // We were told not to emit the alias, but to emit the aliasee.
829     const DagInit *DI = R->getValueAsDag("ResultInst");
830     const DefInit *Op = dynamic_cast<const DefInit*>(DI->getOperator());
831     AliasMap[getQualifiedName(Op->getDef())].push_back(Alias);
832   }
833
834   // A map of which conditions need to be met for each instruction operand
835   // before it can be matched to the mnemonic.
836   std::map<std::string, std::vector<IAPrinter*> > IAPrinterMap;
837
838   for (std::map<std::string, std::vector<CodeGenInstAlias*> >::iterator
839          I = AliasMap.begin(), E = AliasMap.end(); I != E; ++I) {
840     std::vector<CodeGenInstAlias*> &Aliases = I->second;
841
842     for (std::vector<CodeGenInstAlias*>::iterator
843            II = Aliases.begin(), IE = Aliases.end(); II != IE; ++II) {
844       const CodeGenInstAlias *CGA = *II;
845       unsigned LastOpNo = CGA->ResultInstOperandIndex.size();
846       unsigned NumResultOps =
847         CountResultNumOperands(CGA->ResultInst->AsmString);
848
849       // Don't emit the alias if it has more operands than what it's aliasing.
850       if (NumResultOps < CountNumOperands(CGA->AsmString))
851         continue;
852
853       IAPrinter *IAP = new IAPrinter(CGA->Result->getAsString(),
854                                      CGA->AsmString);
855
856       std::string Cond;
857       Cond = std::string("MI->getNumOperands() == ") + llvm::utostr(LastOpNo);
858       IAP->addCond(Cond);
859
860       std::map<StringRef, unsigned> OpMap;
861       bool CantHandle = false;
862
863       for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
864         const CodeGenInstAlias::ResultOperand &RO = CGA->ResultOperands[i];
865
866         switch (RO.Kind) {
867         case CodeGenInstAlias::ResultOperand::K_Record: {
868           const Record *Rec = RO.getRecord();
869           StringRef ROName = RO.getName();
870
871
872           if (Rec->isSubClassOf("RegisterOperand"))
873             Rec = Rec->getValueAsDef("RegClass");
874           if (Rec->isSubClassOf("RegisterClass")) {
875             Cond = std::string("MI->getOperand(")+llvm::utostr(i)+").isReg()";
876             IAP->addCond(Cond);
877
878             if (!IAP->isOpMapped(ROName)) {
879               IAP->addOperand(ROName, i);
880               Cond = std::string("regIsInRegisterClass(RC_") +
881                 CGA->ResultOperands[i].getRecord()->getName() +
882                 ", MI->getOperand(" + llvm::utostr(i) + ").getReg())";
883               IAP->addCond(Cond);
884             } else {
885               Cond = std::string("MI->getOperand(") +
886                 llvm::utostr(i) + ").getReg() == MI->getOperand(" +
887                 llvm::utostr(IAP->getOpIndex(ROName)) + ").getReg()";
888               IAP->addCond(Cond);
889             }
890           } else {
891             assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
892             // FIXME: We may need to handle these situations.
893             delete IAP;
894             IAP = 0;
895             CantHandle = true;
896             break;
897           }
898
899           break;
900         }
901         case CodeGenInstAlias::ResultOperand::K_Imm:
902           Cond = std::string("MI->getOperand(") +
903             llvm::utostr(i) + ").getImm() == " +
904             llvm::utostr(CGA->ResultOperands[i].getImm());
905           IAP->addCond(Cond);
906           break;
907         case CodeGenInstAlias::ResultOperand::K_Reg:
908           // If this is zero_reg, something's playing tricks we're not
909           // equipped to handle.
910           if (!CGA->ResultOperands[i].getRegister()) {
911             CantHandle = true;
912             break;
913           }
914
915           Cond = std::string("MI->getOperand(") +
916             llvm::utostr(i) + ").getReg() == " + Target.getName() +
917             "::" + CGA->ResultOperands[i].getRegister()->getName();
918           IAP->addCond(Cond);
919           break;
920         }
921
922         if (!IAP) break;
923       }
924
925       if (CantHandle) continue;
926       IAPrinterMap[I->first].push_back(IAP);
927     }
928   }
929
930   std::string Header;
931   raw_string_ostream HeaderO(Header);
932
933   HeaderO << "bool " << Target.getName() << ClassName
934           << "::printAliasInstr(const MCInst"
935           << " *MI, raw_ostream &OS) {\n";
936
937   std::string Cases;
938   raw_string_ostream CasesO(Cases);
939
940   for (std::map<std::string, std::vector<IAPrinter*> >::iterator
941          I = IAPrinterMap.begin(), E = IAPrinterMap.end(); I != E; ++I) {
942     std::vector<IAPrinter*> &IAPs = I->second;
943     std::vector<IAPrinter*> UniqueIAPs;
944
945     for (std::vector<IAPrinter*>::iterator
946            II = IAPs.begin(), IE = IAPs.end(); II != IE; ++II) {
947       IAPrinter *LHS = *II;
948       bool IsDup = false;
949       for (std::vector<IAPrinter*>::iterator
950              III = IAPs.begin(), IIE = IAPs.end(); III != IIE; ++III) {
951         IAPrinter *RHS = *III;
952         if (LHS != RHS && *LHS == *RHS) {
953           IsDup = true;
954           break;
955         }
956       }
957
958       if (!IsDup) UniqueIAPs.push_back(LHS);
959     }
960
961     if (UniqueIAPs.empty()) continue;
962
963     CasesO.indent(2) << "case " << I->first << ":\n";
964
965     for (std::vector<IAPrinter*>::iterator
966            II = UniqueIAPs.begin(), IE = UniqueIAPs.end(); II != IE; ++II) {
967       IAPrinter *IAP = *II;
968       CasesO.indent(4);
969       IAP->print(CasesO);
970       CasesO << '\n';
971     }
972
973     CasesO.indent(4) << "return false;\n";
974   }
975
976   if (CasesO.str().empty()) {
977     O << HeaderO.str();
978     O << "  return false;\n";
979     O << "}\n\n";
980     O << "#endif // PRINT_ALIAS_INSTR\n";
981     return;
982   }
983
984   EmitGetMapOperandNumber(O);
985
986   O << HeaderO.str();
987   O.indent(2) << "StringRef AsmString;\n";
988   O.indent(2) << "SmallVector<std::pair<StringRef, unsigned>, 4> OpMap;\n";
989   O.indent(2) << "switch (MI->getOpcode()) {\n";
990   O.indent(2) << "default: return false;\n";
991   O << CasesO.str();
992   O.indent(2) << "}\n\n";
993
994   // Code that prints the alias, replacing the operands with the ones from the
995   // MCInst.
996   O << "  std::pair<StringRef, StringRef> ASM = AsmString.split(' ');\n";
997   O << "  OS << '\\t' << ASM.first;\n";
998
999   O << "  if (!ASM.second.empty()) {\n";
1000   O << "    OS << '\\t';\n";
1001   O << "    for (StringRef::iterator\n";
1002   O << "         I = ASM.second.begin(), E = ASM.second.end(); I != E; ) {\n";
1003   O << "      if (*I == '$') {\n";
1004   O << "        StringRef::iterator Start = ++I;\n";
1005   O << "        while (I != E &&\n";
1006   O << "               ((*I >= 'a' && *I <= 'z') ||\n";
1007   O << "                (*I >= 'A' && *I <= 'Z') ||\n";
1008   O << "                (*I >= '0' && *I <= '9') ||\n";
1009   O << "                *I == '_'))\n";
1010   O << "          ++I;\n";
1011   O << "        StringRef Name(Start, I - Start);\n";
1012   O << "        printOperand(MI, getMapOperandNumber(OpMap, Name), OS);\n";
1013   O << "      } else {\n";
1014   O << "        OS << *I++;\n";
1015   O << "      }\n";
1016   O << "    }\n";
1017   O << "  }\n\n";
1018   
1019   O << "  return true;\n";
1020   O << "}\n\n";
1021
1022   O << "#endif // PRINT_ALIAS_INSTR\n";
1023 }
1024
1025 void AsmWriterEmitter::run(raw_ostream &O) {
1026   EmitSourceFileHeader("Assembly Writer Source Fragment", O);
1027
1028   EmitPrintInstruction(O);
1029   EmitGetRegisterName(O);
1030   EmitGetInstructionName(O);
1031   EmitPrintAliasInstruction(O);
1032 }
1033