xref: /freebsd/contrib/llvm-project/llvm/utils/TableGen/AsmWriterEmitter.cpp (revision 5def4c47d4bd90b209b9b4a4ba9faec15846d8fd)
1 //===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This tablegen backend emits an assembly printer for the current target.
10 // Note that this is currently fairly skeletal, but will grow over time.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "AsmWriterInst.h"
15 #include "CodeGenInstruction.h"
16 #include "CodeGenRegisters.h"
17 #include "CodeGenTarget.h"
18 #include "SequenceToOffsetTable.h"
19 #include "Types.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Twine.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/Format.h"
32 #include "llvm/Support/FormatVariadic.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/TableGen/Error.h"
36 #include "llvm/TableGen/Record.h"
37 #include "llvm/TableGen/TableGenBackend.h"
38 #include <algorithm>
39 #include <cassert>
40 #include <cstddef>
41 #include <cstdint>
42 #include <deque>
43 #include <iterator>
44 #include <map>
45 #include <set>
46 #include <string>
47 #include <tuple>
48 #include <utility>
49 #include <vector>
50 
51 using namespace llvm;
52 
53 #define DEBUG_TYPE "asm-writer-emitter"
54 
55 namespace {
56 
57 class AsmWriterEmitter {
58   RecordKeeper &Records;
59   CodeGenTarget Target;
60   ArrayRef<const CodeGenInstruction *> NumberedInstructions;
61   std::vector<AsmWriterInst> Instructions;
62 
63 public:
64   AsmWriterEmitter(RecordKeeper &R);
65 
66   void run(raw_ostream &o);
67 private:
68   void EmitGetMnemonic(
69       raw_ostream &o,
70       std::vector<std::vector<std::string>> &TableDrivenOperandPrinters,
71       unsigned &BitsLeft, unsigned &AsmStrBits);
72   void EmitPrintInstruction(
73       raw_ostream &o,
74       std::vector<std::vector<std::string>> &TableDrivenOperandPrinters,
75       unsigned &BitsLeft, unsigned &AsmStrBits);
76   void EmitGetRegisterName(raw_ostream &o);
77   void EmitPrintAliasInstruction(raw_ostream &O);
78 
79   void FindUniqueOperandCommands(std::vector<std::string> &UOC,
80                                  std::vector<std::vector<unsigned>> &InstIdxs,
81                                  std::vector<unsigned> &InstOpsUsed,
82                                  bool PassSubtarget) const;
83 };
84 
85 } // end anonymous namespace
86 
87 static void PrintCases(std::vector<std::pair<std::string,
88                        AsmWriterOperand>> &OpsToPrint, raw_ostream &O,
89                        bool PassSubtarget) {
90   O << "    case " << OpsToPrint.back().first << ":";
91   AsmWriterOperand TheOp = OpsToPrint.back().second;
92   OpsToPrint.pop_back();
93 
94   // Check to see if any other operands are identical in this list, and if so,
95   // emit a case label for them.
96   for (unsigned i = OpsToPrint.size(); i != 0; --i)
97     if (OpsToPrint[i-1].second == TheOp) {
98       O << "\n    case " << OpsToPrint[i-1].first << ":";
99       OpsToPrint.erase(OpsToPrint.begin()+i-1);
100     }
101 
102   // Finally, emit the code.
103   O << "\n      " << TheOp.getCode(PassSubtarget);
104   O << "\n      break;\n";
105 }
106 
107 /// EmitInstructions - Emit the last instruction in the vector and any other
108 /// instructions that are suitably similar to it.
109 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
110                              raw_ostream &O, bool PassSubtarget) {
111   AsmWriterInst FirstInst = Insts.back();
112   Insts.pop_back();
113 
114   std::vector<AsmWriterInst> SimilarInsts;
115   unsigned DifferingOperand = ~0;
116   for (unsigned i = Insts.size(); i != 0; --i) {
117     unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
118     if (DiffOp != ~1U) {
119       if (DifferingOperand == ~0U)  // First match!
120         DifferingOperand = DiffOp;
121 
122       // If this differs in the same operand as the rest of the instructions in
123       // this class, move it to the SimilarInsts list.
124       if (DifferingOperand == DiffOp || DiffOp == ~0U) {
125         SimilarInsts.push_back(Insts[i-1]);
126         Insts.erase(Insts.begin()+i-1);
127       }
128     }
129   }
130 
131   O << "  case " << FirstInst.CGI->Namespace << "::"
132     << FirstInst.CGI->TheDef->getName() << ":\n";
133   for (const AsmWriterInst &AWI : SimilarInsts)
134     O << "  case " << AWI.CGI->Namespace << "::"
135       << AWI.CGI->TheDef->getName() << ":\n";
136   for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
137     if (i != DifferingOperand) {
138       // If the operand is the same for all instructions, just print it.
139       O << "    " << FirstInst.Operands[i].getCode(PassSubtarget);
140     } else {
141       // If this is the operand that varies between all of the instructions,
142       // emit a switch for just this operand now.
143       O << "    switch (MI->getOpcode()) {\n";
144       O << "    default: llvm_unreachable(\"Unexpected opcode.\");\n";
145       std::vector<std::pair<std::string, AsmWriterOperand>> OpsToPrint;
146       OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace.str() + "::" +
147                                           FirstInst.CGI->TheDef->getName().str(),
148                                           FirstInst.Operands[i]));
149 
150       for (const AsmWriterInst &AWI : SimilarInsts) {
151         OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace.str()+"::" +
152                                             AWI.CGI->TheDef->getName().str(),
153                                             AWI.Operands[i]));
154       }
155       std::reverse(OpsToPrint.begin(), OpsToPrint.end());
156       while (!OpsToPrint.empty())
157         PrintCases(OpsToPrint, O, PassSubtarget);
158       O << "    }";
159     }
160     O << "\n";
161   }
162   O << "    break;\n";
163 }
164 
165 void AsmWriterEmitter::
166 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
167                           std::vector<std::vector<unsigned>> &InstIdxs,
168                           std::vector<unsigned> &InstOpsUsed,
169                           bool PassSubtarget) const {
170   // This vector parallels UniqueOperandCommands, keeping track of which
171   // instructions each case are used for.  It is a comma separated string of
172   // enums.
173   std::vector<std::string> InstrsForCase;
174   InstrsForCase.resize(UniqueOperandCommands.size());
175   InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
176 
177   for (size_t i = 0, e = Instructions.size(); i != e; ++i) {
178     const AsmWriterInst &Inst = Instructions[i];
179     if (Inst.Operands.empty())
180       continue;   // Instruction already done.
181 
182     std::string Command = "    "+Inst.Operands[0].getCode(PassSubtarget)+"\n";
183 
184     // Check to see if we already have 'Command' in UniqueOperandCommands.
185     // If not, add it.
186     auto I = llvm::find(UniqueOperandCommands, Command);
187     if (I != UniqueOperandCommands.end()) {
188       size_t idx = I - UniqueOperandCommands.begin();
189       InstrsForCase[idx] += ", ";
190       InstrsForCase[idx] += Inst.CGI->TheDef->getName();
191       InstIdxs[idx].push_back(i);
192     } else {
193       UniqueOperandCommands.push_back(std::move(Command));
194       InstrsForCase.push_back(std::string(Inst.CGI->TheDef->getName()));
195       InstIdxs.emplace_back();
196       InstIdxs.back().push_back(i);
197 
198       // This command matches one operand so far.
199       InstOpsUsed.push_back(1);
200     }
201   }
202 
203   // For each entry of UniqueOperandCommands, there is a set of instructions
204   // that uses it.  If the next command of all instructions in the set are
205   // identical, fold it into the command.
206   for (size_t CommandIdx = 0, e = UniqueOperandCommands.size();
207        CommandIdx != e; ++CommandIdx) {
208 
209     const auto &Idxs = InstIdxs[CommandIdx];
210 
211     for (unsigned Op = 1; ; ++Op) {
212       // Find the first instruction in the set.
213       const AsmWriterInst &FirstInst = Instructions[Idxs.front()];
214       // If this instruction has no more operands, we isn't anything to merge
215       // into this command.
216       if (FirstInst.Operands.size() == Op)
217         break;
218 
219       // Otherwise, scan to see if all of the other instructions in this command
220       // set share the operand.
221       if (any_of(drop_begin(Idxs), [&](unsigned Idx) {
222             const AsmWriterInst &OtherInst = Instructions[Idx];
223             return OtherInst.Operands.size() == Op ||
224                    OtherInst.Operands[Op] != FirstInst.Operands[Op];
225           }))
226         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 = "    " +
231         FirstInst.Operands[Op].getCode(PassSubtarget) + "\n";
232 
233       UniqueOperandCommands[CommandIdx] += Command;
234       InstOpsUsed[CommandIdx]++;
235     }
236   }
237 
238   // Prepend some of the instructions each case is used for onto the case val.
239   for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
240     std::string Instrs = InstrsForCase[i];
241     if (Instrs.size() > 70) {
242       Instrs.erase(Instrs.begin()+70, Instrs.end());
243       Instrs += "...";
244     }
245 
246     if (!Instrs.empty())
247       UniqueOperandCommands[i] = "    // " + Instrs + "\n" +
248         UniqueOperandCommands[i];
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 /// UnescapeAliasString - Supports literal braces in InstAlias asm string which
276 /// are escaped with '\\' to avoid being interpreted as variants. Braces must
277 /// be unescaped before c++ code is generated as (e.g.):
278 ///
279 ///   AsmString = "foo \{$\x01\}";
280 ///
281 /// causes non-standard escape character warnings.
282 static void UnescapeAliasString(std::string &Str) {
283   for (unsigned i = 0; i != Str.size(); ++i) {
284     if (Str[i] == '\\' && i != Str.size()-1) {
285       switch (Str[i+1]) {
286       default: continue;  // Don't execute the code after the switch.
287       case '{': Str[i] = '{'; break;
288       case '}': Str[i] = '}'; break;
289       }
290       // Nuke the second character.
291       Str.erase(Str.begin()+i+1);
292     }
293   }
294 }
295 
296 void AsmWriterEmitter::EmitGetMnemonic(
297     raw_ostream &O,
298     std::vector<std::vector<std::string>> &TableDrivenOperandPrinters,
299     unsigned &BitsLeft, unsigned &AsmStrBits) {
300   Record *AsmWriter = Target.getAsmWriter();
301   StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
302   bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
303 
304   O << "/// getMnemonic - This method is automatically generated by "
305        "tablegen\n"
306        "/// from the instruction set description.\n"
307        "std::pair<const char *, uint64_t> "
308     << Target.getName() << ClassName << "::getMnemonic(const MCInst *MI) {\n";
309 
310   // Build an aggregate string, and build a table of offsets into it.
311   SequenceToOffsetTable<std::string> StringTable;
312 
313   /// OpcodeInfo - This encodes the index of the string to use for the first
314   /// chunk of the output as well as indices used for operand printing.
315   std::vector<uint64_t> OpcodeInfo(NumberedInstructions.size());
316   const unsigned OpcodeInfoBits = 64;
317 
318   // Add all strings to the string table upfront so it can generate an optimized
319   // representation.
320   for (AsmWriterInst &AWI : Instructions) {
321     if (AWI.Operands[0].OperandType ==
322                  AsmWriterOperand::isLiteralTextOperand &&
323         !AWI.Operands[0].Str.empty()) {
324       std::string Str = AWI.Operands[0].Str;
325       UnescapeString(Str);
326       StringTable.add(Str);
327     }
328   }
329 
330   StringTable.layout();
331 
332   unsigned MaxStringIdx = 0;
333   for (AsmWriterInst &AWI : Instructions) {
334     unsigned Idx;
335     if (AWI.Operands[0].OperandType != AsmWriterOperand::isLiteralTextOperand ||
336         AWI.Operands[0].Str.empty()) {
337       // Something handled by the asmwriter printer, but with no leading string.
338       Idx = StringTable.get("");
339     } else {
340       std::string Str = AWI.Operands[0].Str;
341       UnescapeString(Str);
342       Idx = StringTable.get(Str);
343       MaxStringIdx = std::max(MaxStringIdx, Idx);
344 
345       // Nuke the string from the operand list.  It is now handled!
346       AWI.Operands.erase(AWI.Operands.begin());
347     }
348 
349     // Bias offset by one since we want 0 as a sentinel.
350     OpcodeInfo[AWI.CGIIndex] = Idx+1;
351   }
352 
353   // Figure out how many bits we used for the string index.
354   AsmStrBits = Log2_32_Ceil(MaxStringIdx + 2);
355 
356   // To reduce code size, we compactify common instructions into a few bits
357   // in the opcode-indexed table.
358   BitsLeft = OpcodeInfoBits - AsmStrBits;
359 
360   while (true) {
361     std::vector<std::string> UniqueOperandCommands;
362     std::vector<std::vector<unsigned>> InstIdxs;
363     std::vector<unsigned> NumInstOpsHandled;
364     FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
365                               NumInstOpsHandled, PassSubtarget);
366 
367     // If we ran out of operands to print, we're done.
368     if (UniqueOperandCommands.empty()) break;
369 
370     // Compute the number of bits we need to represent these cases, this is
371     // ceil(log2(numentries)).
372     unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
373 
374     // If we don't have enough bits for this operand, don't include it.
375     if (NumBits > BitsLeft) {
376       LLVM_DEBUG(errs() << "Not enough bits to densely encode " << NumBits
377                         << " more bits\n");
378       break;
379     }
380 
381     // Otherwise, we can include this in the initial lookup table.  Add it in.
382     for (size_t i = 0, e = InstIdxs.size(); i != e; ++i) {
383       unsigned NumOps = NumInstOpsHandled[i];
384       for (unsigned Idx : InstIdxs[i]) {
385         OpcodeInfo[Instructions[Idx].CGIIndex] |=
386           (uint64_t)i << (OpcodeInfoBits-BitsLeft);
387         // Remove the info about this operand from the instruction.
388         AsmWriterInst &Inst = Instructions[Idx];
389         if (!Inst.Operands.empty()) {
390           assert(NumOps <= Inst.Operands.size() &&
391                  "Can't remove this many ops!");
392           Inst.Operands.erase(Inst.Operands.begin(),
393                               Inst.Operands.begin()+NumOps);
394         }
395       }
396     }
397     BitsLeft -= NumBits;
398 
399     // Remember the handlers for this set of operands.
400     TableDrivenOperandPrinters.push_back(std::move(UniqueOperandCommands));
401   }
402 
403   // Emit the string table itself.
404   StringTable.emitStringLiteralDef(O, "  static const char AsmStrs[]");
405 
406   // Emit the lookup tables in pieces to minimize wasted bytes.
407   unsigned BytesNeeded = ((OpcodeInfoBits - BitsLeft) + 7) / 8;
408   unsigned Table = 0, Shift = 0;
409   SmallString<128> BitsString;
410   raw_svector_ostream BitsOS(BitsString);
411   // If the total bits is more than 32-bits we need to use a 64-bit type.
412   BitsOS << "  uint" << ((BitsLeft < (OpcodeInfoBits - 32)) ? 64 : 32)
413          << "_t Bits = 0;\n";
414   while (BytesNeeded != 0) {
415     // Figure out how big this table section needs to be, but no bigger than 4.
416     unsigned TableSize = std::min(1 << Log2_32(BytesNeeded), 4);
417     BytesNeeded -= TableSize;
418     TableSize *= 8; // Convert to bits;
419     uint64_t Mask = (1ULL << TableSize) - 1;
420     O << "  static const uint" << TableSize << "_t OpInfo" << Table
421       << "[] = {\n";
422     for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
423       O << "    " << ((OpcodeInfo[i] >> Shift) & Mask) << "U,\t// "
424         << NumberedInstructions[i]->TheDef->getName() << "\n";
425     }
426     O << "  };\n\n";
427     // Emit string to combine the individual table lookups.
428     BitsOS << "  Bits |= ";
429     // If the total bits is more than 32-bits we need to use a 64-bit type.
430     if (BitsLeft < (OpcodeInfoBits - 32))
431       BitsOS << "(uint64_t)";
432     BitsOS << "OpInfo" << Table << "[MI->getOpcode()] << " << Shift << ";\n";
433     // Prepare the shift for the next iteration and increment the table count.
434     Shift += TableSize;
435     ++Table;
436   }
437 
438   O << "  // Emit the opcode for the instruction.\n";
439   O << BitsString;
440 
441   // Return mnemonic string and bits.
442   O << "  return {AsmStrs+(Bits & " << (1 << AsmStrBits) - 1
443     << ")-1, Bits};\n\n";
444 
445   O << "}\n";
446 }
447 
448 /// EmitPrintInstruction - Generate the code for the "printInstruction" method
449 /// implementation. Destroys all instances of AsmWriterInst information, by
450 /// clearing the Instructions vector.
451 void AsmWriterEmitter::EmitPrintInstruction(
452     raw_ostream &O,
453     std::vector<std::vector<std::string>> &TableDrivenOperandPrinters,
454     unsigned &BitsLeft, unsigned &AsmStrBits) {
455   const unsigned OpcodeInfoBits = 64;
456   Record *AsmWriter = Target.getAsmWriter();
457   StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
458   bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
459 
460   O << "/// printInstruction - This method is automatically generated by "
461        "tablegen\n"
462        "/// from the instruction set description.\n"
463        "void "
464     << Target.getName() << ClassName
465     << "::printInstruction(const MCInst *MI, uint64_t Address, "
466     << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
467     << "raw_ostream &O) {\n";
468 
469   // Emit the initial tab character.
470   O << "  O << \"\\t\";\n\n";
471 
472   // Emit the starting string.
473   O << "  auto MnemonicInfo = getMnemonic(MI);\n\n";
474   O << "  O << MnemonicInfo.first;\n\n";
475 
476   O << "  uint" << ((BitsLeft < (OpcodeInfoBits - 32)) ? 64 : 32)
477     << "_t Bits = MnemonicInfo.second;\n"
478     << "  assert(Bits != 0 && \"Cannot print this instruction.\");\n";
479 
480   // Output the table driven operand information.
481   BitsLeft = OpcodeInfoBits-AsmStrBits;
482   for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
483     std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
484 
485     // Compute the number of bits we need to represent these cases, this is
486     // ceil(log2(numentries)).
487     unsigned NumBits = Log2_32_Ceil(Commands.size());
488     assert(NumBits <= BitsLeft && "consistency error");
489 
490     // Emit code to extract this field from Bits.
491     O << "\n  // Fragment " << i << " encoded into " << NumBits
492       << " bits for " << Commands.size() << " unique commands.\n";
493 
494     if (Commands.size() == 2) {
495       // Emit two possibilitys with if/else.
496       O << "  if ((Bits >> "
497         << (OpcodeInfoBits-BitsLeft) << ") & "
498         << ((1 << NumBits)-1) << ") {\n"
499         << Commands[1]
500         << "  } else {\n"
501         << Commands[0]
502         << "  }\n\n";
503     } else if (Commands.size() == 1) {
504       // Emit a single possibility.
505       O << Commands[0] << "\n\n";
506     } else {
507       O << "  switch ((Bits >> "
508         << (OpcodeInfoBits-BitsLeft) << ") & "
509         << ((1 << NumBits)-1) << ") {\n"
510         << "  default: llvm_unreachable(\"Invalid command number.\");\n";
511 
512       // Print out all the cases.
513       for (unsigned j = 0, e = Commands.size(); j != e; ++j) {
514         O << "  case " << j << ":\n";
515         O << Commands[j];
516         O << "    break;\n";
517       }
518       O << "  }\n\n";
519     }
520     BitsLeft -= NumBits;
521   }
522 
523   // Okay, delete instructions with no operand info left.
524   llvm::erase_if(Instructions,
525                  [](AsmWriterInst &Inst) { return Inst.Operands.empty(); });
526 
527   // Because this is a vector, we want to emit from the end.  Reverse all of the
528   // elements in the vector.
529   std::reverse(Instructions.begin(), Instructions.end());
530 
531 
532   // Now that we've emitted all of the operand info that fit into 64 bits, emit
533   // information for those instructions that are left.  This is a less dense
534   // encoding, but we expect the main 64-bit table to handle the majority of
535   // instructions.
536   if (!Instructions.empty()) {
537     // Find the opcode # of inline asm.
538     O << "  switch (MI->getOpcode()) {\n";
539     O << "  default: llvm_unreachable(\"Unexpected opcode.\");\n";
540     while (!Instructions.empty())
541       EmitInstructions(Instructions, O, PassSubtarget);
542 
543     O << "  }\n";
544   }
545 
546   O << "}\n";
547 }
548 
549 static void
550 emitRegisterNameString(raw_ostream &O, StringRef AltName,
551                        const std::deque<CodeGenRegister> &Registers) {
552   SequenceToOffsetTable<std::string> StringTable;
553   SmallVector<std::string, 4> AsmNames(Registers.size());
554   unsigned i = 0;
555   for (const auto &Reg : Registers) {
556     std::string &AsmName = AsmNames[i++];
557 
558     // "NoRegAltName" is special. We don't need to do a lookup for that,
559     // as it's just a reference to the default register name.
560     if (AltName == "" || AltName == "NoRegAltName") {
561       AsmName = std::string(Reg.TheDef->getValueAsString("AsmName"));
562       if (AsmName.empty())
563         AsmName = std::string(Reg.getName());
564     } else {
565       // Make sure the register has an alternate name for this index.
566       std::vector<Record*> AltNameList =
567         Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
568       unsigned Idx = 0, e;
569       for (e = AltNameList.size();
570            Idx < e && (AltNameList[Idx]->getName() != AltName);
571            ++Idx)
572         ;
573       // If the register has an alternate name for this index, use it.
574       // Otherwise, leave it empty as an error flag.
575       if (Idx < e) {
576         std::vector<StringRef> AltNames =
577           Reg.TheDef->getValueAsListOfStrings("AltNames");
578         if (AltNames.size() <= Idx)
579           PrintFatalError(Reg.TheDef->getLoc(),
580                           "Register definition missing alt name for '" +
581                           AltName + "'.");
582         AsmName = std::string(AltNames[Idx]);
583       }
584     }
585     StringTable.add(AsmName);
586   }
587 
588   StringTable.layout();
589   StringTable.emitStringLiteralDef(O, Twine("  static const char AsmStrs") +
590                                           AltName + "[]");
591 
592   O << "  static const " << getMinimalTypeForRange(StringTable.size() - 1, 32)
593     << " RegAsmOffset" << AltName << "[] = {";
594   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
595     if ((i % 14) == 0)
596       O << "\n    ";
597     O << StringTable.get(AsmNames[i]) << ", ";
598   }
599   O << "\n  };\n"
600     << "\n";
601 }
602 
603 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
604   Record *AsmWriter = Target.getAsmWriter();
605   StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
606   const auto &Registers = Target.getRegBank().getRegisters();
607   const std::vector<Record*> &AltNameIndices = Target.getRegAltNameIndices();
608   bool hasAltNames = AltNameIndices.size() > 1;
609   StringRef Namespace = Registers.front().TheDef->getValueAsString("Namespace");
610 
611   O <<
612   "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
613   "/// from the register set description.  This returns the assembler name\n"
614   "/// for the specified register.\n"
615   "const char *" << Target.getName() << ClassName << "::";
616   if (hasAltNames)
617     O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
618   else
619     O << "getRegisterName(unsigned RegNo) {\n";
620   O << "  assert(RegNo && RegNo < " << (Registers.size()+1)
621     << " && \"Invalid register number!\");\n"
622     << "\n";
623 
624   if (hasAltNames) {
625     for (const Record *R : AltNameIndices)
626       emitRegisterNameString(O, R->getName(), Registers);
627   } else
628     emitRegisterNameString(O, "", Registers);
629 
630   if (hasAltNames) {
631     O << "  switch(AltIdx) {\n"
632       << "  default: llvm_unreachable(\"Invalid register alt name index!\");\n";
633     for (const Record *R : AltNameIndices) {
634       StringRef AltName = R->getName();
635       O << "  case ";
636       if (!Namespace.empty())
637         O << Namespace << "::";
638       O << AltName << ":\n";
639       if (R->isValueUnset("FallbackRegAltNameIndex"))
640         O << "    assert(*(AsmStrs" << AltName << "+RegAsmOffset" << AltName
641           << "[RegNo-1]) &&\n"
642           << "           \"Invalid alt name index for register!\");\n";
643       else {
644         O << "    if (!*(AsmStrs" << AltName << "+RegAsmOffset" << AltName
645           << "[RegNo-1]))\n"
646           << "      return getRegisterName(RegNo, ";
647         if (!Namespace.empty())
648           O << Namespace << "::";
649         O << R->getValueAsDef("FallbackRegAltNameIndex")->getName() << ");\n";
650       }
651       O << "    return AsmStrs" << AltName << "+RegAsmOffset" << AltName
652         << "[RegNo-1];\n";
653     }
654     O << "  }\n";
655   } else {
656     O << "  assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
657       << "          \"Invalid alt name index for register!\");\n"
658       << "  return AsmStrs+RegAsmOffset[RegNo-1];\n";
659   }
660   O << "}\n";
661 }
662 
663 namespace {
664 
665 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
666 // they both have the same conditionals. In which case, we cannot print out the
667 // alias for that pattern.
668 class IAPrinter {
669   std::map<StringRef, std::pair<int, int>> OpMap;
670 
671   std::vector<std::string> Conds;
672 
673   std::string Result;
674   std::string AsmString;
675 
676   unsigned NumMIOps;
677 
678 public:
679   IAPrinter(std::string R, std::string AS, unsigned NumMIOps)
680       : Result(std::move(R)), AsmString(std::move(AS)), NumMIOps(NumMIOps) {}
681 
682   void addCond(std::string C) { Conds.push_back(std::move(C)); }
683   ArrayRef<std::string> getConds() const { return Conds; }
684   size_t getCondCount() const { return Conds.size(); }
685 
686   void addOperand(StringRef Op, int OpIdx, int PrintMethodIdx = -1) {
687     assert(OpIdx >= 0 && OpIdx < 0xFE && "Idx out of range");
688     assert(PrintMethodIdx >= -1 && PrintMethodIdx < 0xFF &&
689            "Idx out of range");
690     OpMap[Op] = std::make_pair(OpIdx, PrintMethodIdx);
691   }
692 
693   unsigned getNumMIOps() { return NumMIOps; }
694 
695   StringRef getResult() { return Result; }
696 
697   bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
698   int getOpIndex(StringRef Op) { return OpMap[Op].first; }
699   std::pair<int, int> &getOpData(StringRef Op) { return OpMap[Op]; }
700 
701   std::pair<StringRef, StringRef::iterator> parseName(StringRef::iterator Start,
702                                                       StringRef::iterator End) {
703     StringRef::iterator I = Start;
704     StringRef::iterator Next;
705     if (*I == '{') {
706       // ${some_name}
707       Start = ++I;
708       while (I != End && *I != '}')
709         ++I;
710       Next = I;
711       // eat the final '}'
712       if (Next != End)
713         ++Next;
714     } else {
715       // $name, just eat the usual suspects.
716       while (I != End && (isAlnum(*I) || *I == '_'))
717         ++I;
718       Next = I;
719     }
720 
721     return std::make_pair(StringRef(Start, I - Start), Next);
722   }
723 
724   std::string formatAliasString(uint32_t &UnescapedSize) {
725     // Directly mangle mapped operands into the string. Each operand is
726     // identified by a '$' sign followed by a byte identifying the number of the
727     // operand. We add one to the index to avoid zero bytes.
728     StringRef ASM(AsmString);
729     std::string OutString;
730     raw_string_ostream OS(OutString);
731     for (StringRef::iterator I = ASM.begin(), E = ASM.end(); I != E;) {
732       OS << *I;
733       ++UnescapedSize;
734       if (*I == '$') {
735         StringRef Name;
736         std::tie(Name, I) = parseName(++I, E);
737         assert(isOpMapped(Name) && "Unmapped operand!");
738 
739         int OpIndex, PrintIndex;
740         std::tie(OpIndex, PrintIndex) = getOpData(Name);
741         if (PrintIndex == -1) {
742           // Can use the default printOperand route.
743           OS << format("\\x%02X", (unsigned char)OpIndex + 1);
744           ++UnescapedSize;
745         } else {
746           // 3 bytes if a PrintMethod is needed: 0xFF, the MCInst operand
747           // number, and which of our pre-detected Methods to call.
748           OS << format("\\xFF\\x%02X\\x%02X", OpIndex + 1, PrintIndex + 1);
749           UnescapedSize += 3;
750         }
751       } else {
752         ++I;
753       }
754     }
755 
756     OS.flush();
757     return OutString;
758   }
759 
760   bool operator==(const IAPrinter &RHS) const {
761     if (NumMIOps != RHS.NumMIOps)
762       return false;
763     if (Conds.size() != RHS.Conds.size())
764       return false;
765 
766     unsigned Idx = 0;
767     for (const auto &str : Conds)
768       if (str != RHS.Conds[Idx++])
769         return false;
770 
771     return true;
772   }
773 };
774 
775 } // end anonymous namespace
776 
777 static unsigned CountNumOperands(StringRef AsmString, unsigned Variant) {
778   return AsmString.count(' ') + AsmString.count('\t');
779 }
780 
781 namespace {
782 
783 struct AliasPriorityComparator {
784   typedef std::pair<CodeGenInstAlias, int> ValueType;
785   bool operator()(const ValueType &LHS, const ValueType &RHS) const {
786     if (LHS.second ==  RHS.second) {
787       // We don't actually care about the order, but for consistency it
788       // shouldn't depend on pointer comparisons.
789       return LessRecordByID()(LHS.first.TheDef, RHS.first.TheDef);
790     }
791 
792     // Aliases with larger priorities should be considered first.
793     return LHS.second > RHS.second;
794   }
795 };
796 
797 } // end anonymous namespace
798 
799 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
800   Record *AsmWriter = Target.getAsmWriter();
801 
802   O << "\n#ifdef PRINT_ALIAS_INSTR\n";
803   O << "#undef PRINT_ALIAS_INSTR\n\n";
804 
805   //////////////////////////////
806   // Gather information about aliases we need to print
807   //////////////////////////////
808 
809   // Emit the method that prints the alias instruction.
810   StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
811   unsigned Variant = AsmWriter->getValueAsInt("Variant");
812   bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
813 
814   std::vector<Record*> AllInstAliases =
815     Records.getAllDerivedDefinitions("InstAlias");
816 
817   // Create a map from the qualified name to a list of potential matches.
818   typedef std::set<std::pair<CodeGenInstAlias, int>, AliasPriorityComparator>
819       AliasWithPriority;
820   std::map<std::string, AliasWithPriority> AliasMap;
821   for (Record *R : AllInstAliases) {
822     int Priority = R->getValueAsInt("EmitPriority");
823     if (Priority < 1)
824       continue; // Aliases with priority 0 are never emitted.
825 
826     const DagInit *DI = R->getValueAsDag("ResultInst");
827     AliasMap[getQualifiedName(DI->getOperatorAsDef(R->getLoc()))].insert(
828         std::make_pair(CodeGenInstAlias(R, Target), Priority));
829   }
830 
831   // A map of which conditions need to be met for each instruction operand
832   // before it can be matched to the mnemonic.
833   std::map<std::string, std::vector<IAPrinter>> IAPrinterMap;
834 
835   std::vector<std::pair<std::string, bool>> PrintMethods;
836 
837   // A list of MCOperandPredicates for all operands in use, and the reverse map
838   std::vector<const Record*> MCOpPredicates;
839   DenseMap<const Record*, unsigned> MCOpPredicateMap;
840 
841   for (auto &Aliases : AliasMap) {
842     // Collection of instruction alias rules. May contain ambiguous rules.
843     std::vector<IAPrinter> IAPs;
844 
845     for (auto &Alias : Aliases.second) {
846       const CodeGenInstAlias &CGA = Alias.first;
847       unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
848       std::string FlatInstAsmString =
849          CodeGenInstruction::FlattenAsmStringVariants(CGA.ResultInst->AsmString,
850                                                       Variant);
851       unsigned NumResultOps = CountNumOperands(FlatInstAsmString, Variant);
852 
853       std::string FlatAliasAsmString =
854           CodeGenInstruction::FlattenAsmStringVariants(CGA.AsmString, Variant);
855       UnescapeAliasString(FlatAliasAsmString);
856 
857       // Don't emit the alias if it has more operands than what it's aliasing.
858       if (NumResultOps < CountNumOperands(FlatAliasAsmString, Variant))
859         continue;
860 
861       StringRef Namespace = Target.getName();
862       unsigned NumMIOps = 0;
863       for (auto &ResultInstOpnd : CGA.ResultInst->Operands)
864         NumMIOps += ResultInstOpnd.MINumOperands;
865 
866       IAPrinter IAP(CGA.Result->getAsString(), FlatAliasAsmString, NumMIOps);
867 
868       bool CantHandle = false;
869 
870       unsigned MIOpNum = 0;
871       for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
872         // Skip over tied operands as they're not part of an alias declaration.
873         auto &Operands = CGA.ResultInst->Operands;
874         while (true) {
875           unsigned OpNum = Operands.getSubOperandNumber(MIOpNum).first;
876           if (Operands[OpNum].MINumOperands == 1 &&
877               Operands[OpNum].getTiedRegister() != -1) {
878             // Tied operands of different RegisterClass should be explicit within
879             // an instruction's syntax and so cannot be skipped.
880             int TiedOpNum = Operands[OpNum].getTiedRegister();
881             if (Operands[OpNum].Rec->getName() ==
882                 Operands[TiedOpNum].Rec->getName()) {
883               ++MIOpNum;
884               continue;
885             }
886           }
887           break;
888         }
889 
890         // Ignore unchecked result operands.
891         while (IAP.getCondCount() < MIOpNum)
892           IAP.addCond("AliasPatternCond::K_Ignore, 0");
893 
894         const CodeGenInstAlias::ResultOperand &RO = CGA.ResultOperands[i];
895 
896         switch (RO.Kind) {
897         case CodeGenInstAlias::ResultOperand::K_Record: {
898           const Record *Rec = RO.getRecord();
899           StringRef ROName = RO.getName();
900           int PrintMethodIdx = -1;
901 
902           // These two may have a PrintMethod, which we want to record (if it's
903           // the first time we've seen it) and provide an index for the aliasing
904           // code to use.
905           if (Rec->isSubClassOf("RegisterOperand") ||
906               Rec->isSubClassOf("Operand")) {
907             StringRef PrintMethod = Rec->getValueAsString("PrintMethod");
908             bool IsPCRel =
909                 Rec->getValueAsString("OperandType") == "OPERAND_PCREL";
910             if (PrintMethod != "" && PrintMethod != "printOperand") {
911               PrintMethodIdx = llvm::find_if(PrintMethods,
912                                              [&](auto &X) {
913                                                return X.first == PrintMethod;
914                                              }) -
915                                PrintMethods.begin();
916               if (static_cast<unsigned>(PrintMethodIdx) == PrintMethods.size())
917                 PrintMethods.emplace_back(std::string(PrintMethod), IsPCRel);
918             }
919           }
920 
921           if (Rec->isSubClassOf("RegisterOperand"))
922             Rec = Rec->getValueAsDef("RegClass");
923           if (Rec->isSubClassOf("RegisterClass")) {
924             if (!IAP.isOpMapped(ROName)) {
925               IAP.addOperand(ROName, MIOpNum, PrintMethodIdx);
926               Record *R = CGA.ResultOperands[i].getRecord();
927               if (R->isSubClassOf("RegisterOperand"))
928                 R = R->getValueAsDef("RegClass");
929               IAP.addCond(std::string(
930                   formatv("AliasPatternCond::K_RegClass, {0}::{1}RegClassID",
931                           Namespace, R->getName())));
932             } else {
933               IAP.addCond(std::string(formatv(
934                   "AliasPatternCond::K_TiedReg, {0}", IAP.getOpIndex(ROName))));
935             }
936           } else {
937             // Assume all printable operands are desired for now. This can be
938             // overridden in the InstAlias instantiation if necessary.
939             IAP.addOperand(ROName, MIOpNum, PrintMethodIdx);
940 
941             // There might be an additional predicate on the MCOperand
942             unsigned Entry = MCOpPredicateMap[Rec];
943             if (!Entry) {
944               if (!Rec->isValueUnset("MCOperandPredicate")) {
945                 MCOpPredicates.push_back(Rec);
946                 Entry = MCOpPredicates.size();
947                 MCOpPredicateMap[Rec] = Entry;
948               } else
949                 break; // No conditions on this operand at all
950             }
951             IAP.addCond(
952                 std::string(formatv("AliasPatternCond::K_Custom, {0}", Entry)));
953           }
954           break;
955         }
956         case CodeGenInstAlias::ResultOperand::K_Imm: {
957           // Just because the alias has an immediate result, doesn't mean the
958           // MCInst will. An MCExpr could be present, for example.
959           auto Imm = CGA.ResultOperands[i].getImm();
960           int32_t Imm32 = int32_t(Imm);
961           if (Imm != Imm32)
962             PrintFatalError("Matching an alias with an immediate out of the "
963                             "range of int32_t is not supported");
964           IAP.addCond(std::string(
965               formatv("AliasPatternCond::K_Imm, uint32_t({0})", Imm32)));
966           break;
967         }
968         case CodeGenInstAlias::ResultOperand::K_Reg:
969           // If this is zero_reg, something's playing tricks we're not
970           // equipped to handle.
971           if (!CGA.ResultOperands[i].getRegister()) {
972             CantHandle = true;
973             break;
974           }
975 
976           StringRef Reg = CGA.ResultOperands[i].getRegister()->getName();
977           IAP.addCond(std::string(
978               formatv("AliasPatternCond::K_Reg, {0}::{1}", Namespace, Reg)));
979           break;
980         }
981 
982         MIOpNum += RO.getMINumOperands();
983       }
984 
985       if (CantHandle) continue;
986 
987       std::vector<Record *> ReqFeatures;
988       if (PassSubtarget) {
989         // We only consider ReqFeatures predicates if PassSubtarget
990         std::vector<Record *> RF =
991             CGA.TheDef->getValueAsListOfDefs("Predicates");
992         copy_if(RF, std::back_inserter(ReqFeatures), [](Record *R) {
993           return R->getValueAsBit("AssemblerMatcherPredicate");
994         });
995       }
996 
997       for (auto I = ReqFeatures.cbegin(); I != ReqFeatures.cend(); I++) {
998         Record *R = *I;
999         const DagInit *D = R->getValueAsDag("AssemblerCondDag");
1000         std::string CombineType = D->getOperator()->getAsString();
1001         if (CombineType != "any_of" && CombineType != "all_of")
1002           PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");
1003         if (D->getNumArgs() == 0)
1004           PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");
1005         bool IsOr = CombineType == "any_of";
1006 
1007         for (auto *Arg : D->getArgs()) {
1008           bool IsNeg = false;
1009           if (auto *NotArg = dyn_cast<DagInit>(Arg)) {
1010             if (NotArg->getOperator()->getAsString() != "not" ||
1011                 NotArg->getNumArgs() != 1)
1012               PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");
1013             Arg = NotArg->getArg(0);
1014             IsNeg = true;
1015           }
1016           if (!isa<DefInit>(Arg) ||
1017               !cast<DefInit>(Arg)->getDef()->isSubClassOf("SubtargetFeature"))
1018             PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");
1019 
1020           IAP.addCond(std::string(formatv(
1021               "AliasPatternCond::K_{0}{1}Feature, {2}::{3}", IsOr ? "Or" : "",
1022               IsNeg ? "Neg" : "", Namespace, Arg->getAsString())));
1023         }
1024         // If an AssemblerPredicate with ors is used, note end of list should
1025         // these be combined.
1026         if (IsOr)
1027           IAP.addCond("AliasPatternCond::K_EndOrFeatures, 0");
1028       }
1029 
1030       IAPrinterMap[Aliases.first].push_back(std::move(IAP));
1031     }
1032   }
1033 
1034   //////////////////////////////
1035   // Write out the printAliasInstr function
1036   //////////////////////////////
1037 
1038   std::string Header;
1039   raw_string_ostream HeaderO(Header);
1040 
1041   HeaderO << "bool " << Target.getName() << ClassName
1042           << "::printAliasInstr(const MCInst"
1043           << " *MI, uint64_t Address, "
1044           << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
1045           << "raw_ostream &OS) {\n";
1046 
1047   std::string PatternsForOpcode;
1048   raw_string_ostream OpcodeO(PatternsForOpcode);
1049 
1050   unsigned PatternCount = 0;
1051   std::string Patterns;
1052   raw_string_ostream PatternO(Patterns);
1053 
1054   unsigned CondCount = 0;
1055   std::string Conds;
1056   raw_string_ostream CondO(Conds);
1057 
1058   // All flattened alias strings.
1059   std::map<std::string, uint32_t> AsmStringOffsets;
1060   std::vector<std::pair<uint32_t, std::string>> AsmStrings;
1061   size_t AsmStringsSize = 0;
1062 
1063   // Iterate over the opcodes in enum order so they are sorted by opcode for
1064   // binary search.
1065   for (const CodeGenInstruction *Inst : NumberedInstructions) {
1066     auto It = IAPrinterMap.find(getQualifiedName(Inst->TheDef));
1067     if (It == IAPrinterMap.end())
1068       continue;
1069     std::vector<IAPrinter> &IAPs = It->second;
1070     std::vector<IAPrinter*> UniqueIAPs;
1071 
1072     // Remove any ambiguous alias rules.
1073     for (auto &LHS : IAPs) {
1074       bool IsDup = false;
1075       for (const auto &RHS : IAPs) {
1076         if (&LHS != &RHS && LHS == RHS) {
1077           IsDup = true;
1078           break;
1079         }
1080       }
1081 
1082       if (!IsDup)
1083         UniqueIAPs.push_back(&LHS);
1084     }
1085 
1086     if (UniqueIAPs.empty()) continue;
1087 
1088     unsigned PatternStart = PatternCount;
1089 
1090     // Insert the pattern start and opcode in the pattern list for debugging.
1091     PatternO << formatv("    // {0} - {1}\n", It->first, PatternStart);
1092 
1093     for (IAPrinter *IAP : UniqueIAPs) {
1094       // Start each condition list with a comment of the resulting pattern that
1095       // we're trying to match.
1096       unsigned CondStart = CondCount;
1097       CondO << formatv("    // {0} - {1}\n", IAP->getResult(), CondStart);
1098       for (const auto &Cond : IAP->getConds())
1099         CondO << "    {" << Cond << "},\n";
1100       CondCount += IAP->getCondCount();
1101 
1102       // After operands have been examined, re-encode the alias string with
1103       // escapes indicating how operands should be printed.
1104       uint32_t UnescapedSize = 0;
1105       std::string EncodedAsmString = IAP->formatAliasString(UnescapedSize);
1106       auto Insertion =
1107           AsmStringOffsets.insert({EncodedAsmString, AsmStringsSize});
1108       if (Insertion.second) {
1109         // If the string is new, add it to the vector.
1110         AsmStrings.push_back({AsmStringsSize, EncodedAsmString});
1111         AsmStringsSize += UnescapedSize + 1;
1112       }
1113       unsigned AsmStrOffset = Insertion.first->second;
1114 
1115       PatternO << formatv("    {{{0}, {1}, {2}, {3} },\n", AsmStrOffset,
1116                           CondStart, IAP->getNumMIOps(), IAP->getCondCount());
1117       ++PatternCount;
1118     }
1119 
1120     OpcodeO << formatv("    {{{0}, {1}, {2} },\n", It->first, PatternStart,
1121                        PatternCount - PatternStart);
1122   }
1123 
1124   if (OpcodeO.str().empty()) {
1125     O << HeaderO.str();
1126     O << "  return false;\n";
1127     O << "}\n\n";
1128     O << "#endif // PRINT_ALIAS_INSTR\n";
1129     return;
1130   }
1131 
1132   // Forward declare the validation method if needed.
1133   if (!MCOpPredicates.empty())
1134     O << "static bool " << Target.getName() << ClassName
1135       << "ValidateMCOperand(const MCOperand &MCOp,\n"
1136       << "                  const MCSubtargetInfo &STI,\n"
1137       << "                  unsigned PredicateIndex);\n";
1138 
1139   O << HeaderO.str();
1140   O.indent(2) << "static const PatternsForOpcode OpToPatterns[] = {\n";
1141   O << OpcodeO.str();
1142   O.indent(2) << "};\n\n";
1143   O.indent(2) << "static const AliasPattern Patterns[] = {\n";
1144   O << PatternO.str();
1145   O.indent(2) << "};\n\n";
1146   O.indent(2) << "static const AliasPatternCond Conds[] = {\n";
1147   O << CondO.str();
1148   O.indent(2) << "};\n\n";
1149   O.indent(2) << "static const char AsmStrings[] =\n";
1150   for (const auto &P : AsmStrings) {
1151     O.indent(4) << "/* " << P.first << " */ \"" << P.second << "\\0\"\n";
1152   }
1153 
1154   O.indent(2) << ";\n\n";
1155 
1156   // Assert that the opcode table is sorted. Use a static local constructor to
1157   // ensure that the check only happens once on first run.
1158   O << "#ifndef NDEBUG\n";
1159   O.indent(2) << "static struct SortCheck {\n";
1160   O.indent(2) << "  SortCheck(ArrayRef<PatternsForOpcode> OpToPatterns) {\n";
1161   O.indent(2) << "    assert(std::is_sorted(\n";
1162   O.indent(2) << "               OpToPatterns.begin(), OpToPatterns.end(),\n";
1163   O.indent(2) << "               [](const PatternsForOpcode &L, const "
1164                  "PatternsForOpcode &R) {\n";
1165   O.indent(2) << "                 return L.Opcode < R.Opcode;\n";
1166   O.indent(2) << "               }) &&\n";
1167   O.indent(2) << "           \"tablegen failed to sort opcode patterns\");\n";
1168   O.indent(2) << "  }\n";
1169   O.indent(2) << "} sortCheckVar(OpToPatterns);\n";
1170   O << "#endif\n\n";
1171 
1172   O.indent(2) << "AliasMatchingData M {\n";
1173   O.indent(2) << "  makeArrayRef(OpToPatterns),\n";
1174   O.indent(2) << "  makeArrayRef(Patterns),\n";
1175   O.indent(2) << "  makeArrayRef(Conds),\n";
1176   O.indent(2) << "  StringRef(AsmStrings, array_lengthof(AsmStrings)),\n";
1177   if (MCOpPredicates.empty())
1178     O.indent(2) << "  nullptr,\n";
1179   else
1180     O.indent(2) << "  &" << Target.getName() << ClassName << "ValidateMCOperand,\n";
1181   O.indent(2) << "};\n";
1182 
1183   O.indent(2) << "const char *AsmString = matchAliasPatterns(MI, "
1184               << (PassSubtarget ? "&STI" : "nullptr") << ", M);\n";
1185   O.indent(2) << "if (!AsmString) return false;\n\n";
1186 
1187   // Code that prints the alias, replacing the operands with the ones from the
1188   // MCInst.
1189   O << "  unsigned I = 0;\n";
1190   O << "  while (AsmString[I] != ' ' && AsmString[I] != '\\t' &&\n";
1191   O << "         AsmString[I] != '$' && AsmString[I] != '\\0')\n";
1192   O << "    ++I;\n";
1193   O << "  OS << '\\t' << StringRef(AsmString, I);\n";
1194 
1195   O << "  if (AsmString[I] != '\\0') {\n";
1196   O << "    if (AsmString[I] == ' ' || AsmString[I] == '\\t') {\n";
1197   O << "      OS << '\\t';\n";
1198   O << "      ++I;\n";
1199   O << "    }\n";
1200   O << "    do {\n";
1201   O << "      if (AsmString[I] == '$') {\n";
1202   O << "        ++I;\n";
1203   O << "        if (AsmString[I] == (char)0xff) {\n";
1204   O << "          ++I;\n";
1205   O << "          int OpIdx = AsmString[I++] - 1;\n";
1206   O << "          int PrintMethodIdx = AsmString[I++] - 1;\n";
1207   O << "          printCustomAliasOperand(MI, Address, OpIdx, PrintMethodIdx, ";
1208   O << (PassSubtarget ? "STI, " : "");
1209   O << "OS);\n";
1210   O << "        } else\n";
1211   O << "          printOperand(MI, unsigned(AsmString[I++]) - 1, ";
1212   O << (PassSubtarget ? "STI, " : "");
1213   O << "OS);\n";
1214   O << "      } else {\n";
1215   O << "        OS << AsmString[I++];\n";
1216   O << "      }\n";
1217   O << "    } while (AsmString[I] != '\\0');\n";
1218   O << "  }\n\n";
1219 
1220   O << "  return true;\n";
1221   O << "}\n\n";
1222 
1223   //////////////////////////////
1224   // Write out the printCustomAliasOperand function
1225   //////////////////////////////
1226 
1227   O << "void " << Target.getName() << ClassName << "::"
1228     << "printCustomAliasOperand(\n"
1229     << "         const MCInst *MI, uint64_t Address, unsigned OpIdx,\n"
1230     << "         unsigned PrintMethodIdx,\n"
1231     << (PassSubtarget ? "         const MCSubtargetInfo &STI,\n" : "")
1232     << "         raw_ostream &OS) {\n";
1233   if (PrintMethods.empty())
1234     O << "  llvm_unreachable(\"Unknown PrintMethod kind\");\n";
1235   else {
1236     O << "  switch (PrintMethodIdx) {\n"
1237       << "  default:\n"
1238       << "    llvm_unreachable(\"Unknown PrintMethod kind\");\n"
1239       << "    break;\n";
1240 
1241     for (unsigned i = 0; i < PrintMethods.size(); ++i) {
1242       O << "  case " << i << ":\n"
1243         << "    " << PrintMethods[i].first << "(MI, "
1244         << (PrintMethods[i].second ? "Address, " : "") << "OpIdx, "
1245         << (PassSubtarget ? "STI, " : "") << "OS);\n"
1246         << "    break;\n";
1247     }
1248     O << "  }\n";
1249   }
1250   O << "}\n\n";
1251 
1252   if (!MCOpPredicates.empty()) {
1253     O << "static bool " << Target.getName() << ClassName
1254       << "ValidateMCOperand(const MCOperand &MCOp,\n"
1255       << "                  const MCSubtargetInfo &STI,\n"
1256       << "                  unsigned PredicateIndex) {\n"
1257       << "  switch (PredicateIndex) {\n"
1258       << "  default:\n"
1259       << "    llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n"
1260       << "    break;\n";
1261 
1262     for (unsigned i = 0; i < MCOpPredicates.size(); ++i) {
1263       StringRef MCOpPred = MCOpPredicates[i]->getValueAsString("MCOperandPredicate");
1264       O << "  case " << i + 1 << ": {\n"
1265         << MCOpPred.data() << "\n"
1266         << "    }\n";
1267     }
1268     O << "  }\n"
1269       << "}\n\n";
1270   }
1271 
1272   O << "#endif // PRINT_ALIAS_INSTR\n";
1273 }
1274 
1275 AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) {
1276   Record *AsmWriter = Target.getAsmWriter();
1277   unsigned Variant = AsmWriter->getValueAsInt("Variant");
1278 
1279   // Get the instruction numbering.
1280   NumberedInstructions = Target.getInstructionsByEnumValue();
1281 
1282   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
1283     const CodeGenInstruction *I = NumberedInstructions[i];
1284     if (!I->AsmString.empty() && I->TheDef->getName() != "PHI")
1285       Instructions.emplace_back(*I, i, Variant);
1286   }
1287 }
1288 
1289 void AsmWriterEmitter::run(raw_ostream &O) {
1290   std::vector<std::vector<std::string>> TableDrivenOperandPrinters;
1291   unsigned BitsLeft = 0;
1292   unsigned AsmStrBits = 0;
1293   EmitGetMnemonic(O, TableDrivenOperandPrinters, BitsLeft, AsmStrBits);
1294   EmitPrintInstruction(O, TableDrivenOperandPrinters, BitsLeft, AsmStrBits);
1295   EmitGetRegisterName(O);
1296   EmitPrintAliasInstruction(O);
1297 }
1298 
1299 namespace llvm {
1300 
1301 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
1302   emitSourceFileHeader("Assembly Writer Source Fragment", OS);
1303   AsmWriterEmitter(RK).run(OS);
1304 }
1305 
1306 } // end namespace llvm
1307