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