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