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