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