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