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   auto I = llvm::remove_if(Instructions,
526                      [](AsmWriterInst &Inst) { return Inst.Operands.empty(); });
527   Instructions.erase(I, Instructions.end());
528 
529 
530   // Because this is a vector, we want to emit from the end.  Reverse all of the
531   // elements in the vector.
532   std::reverse(Instructions.begin(), Instructions.end());
533 
534 
535   // Now that we've emitted all of the operand info that fit into 64 bits, emit
536   // information for those instructions that are left.  This is a less dense
537   // encoding, but we expect the main 64-bit table to handle the majority of
538   // instructions.
539   if (!Instructions.empty()) {
540     // Find the opcode # of inline asm.
541     O << "  switch (MI->getOpcode()) {\n";
542     O << "  default: llvm_unreachable(\"Unexpected opcode.\");\n";
543     while (!Instructions.empty())
544       EmitInstructions(Instructions, O, PassSubtarget);
545 
546     O << "  }\n";
547   }
548 
549   O << "}\n";
550 }
551 
552 static void
553 emitRegisterNameString(raw_ostream &O, StringRef AltName,
554                        const std::deque<CodeGenRegister> &Registers) {
555   SequenceToOffsetTable<std::string> StringTable;
556   SmallVector<std::string, 4> AsmNames(Registers.size());
557   unsigned i = 0;
558   for (const auto &Reg : Registers) {
559     std::string &AsmName = AsmNames[i++];
560 
561     // "NoRegAltName" is special. We don't need to do a lookup for that,
562     // as it's just a reference to the default register name.
563     if (AltName == "" || AltName == "NoRegAltName") {
564       AsmName = std::string(Reg.TheDef->getValueAsString("AsmName"));
565       if (AsmName.empty())
566         AsmName = std::string(Reg.getName());
567     } else {
568       // Make sure the register has an alternate name for this index.
569       std::vector<Record*> AltNameList =
570         Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
571       unsigned Idx = 0, e;
572       for (e = AltNameList.size();
573            Idx < e && (AltNameList[Idx]->getName() != AltName);
574            ++Idx)
575         ;
576       // If the register has an alternate name for this index, use it.
577       // Otherwise, leave it empty as an error flag.
578       if (Idx < e) {
579         std::vector<StringRef> AltNames =
580           Reg.TheDef->getValueAsListOfStrings("AltNames");
581         if (AltNames.size() <= Idx)
582           PrintFatalError(Reg.TheDef->getLoc(),
583                           "Register definition missing alt name for '" +
584                           AltName + "'.");
585         AsmName = std::string(AltNames[Idx]);
586       }
587     }
588     StringTable.add(AsmName);
589   }
590 
591   StringTable.layout();
592   StringTable.emitStringLiteralDef(O, Twine("  static const char AsmStrs") +
593                                           AltName + "[]");
594 
595   O << "  static const " << getMinimalTypeForRange(StringTable.size() - 1, 32)
596     << " RegAsmOffset" << AltName << "[] = {";
597   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
598     if ((i % 14) == 0)
599       O << "\n    ";
600     O << StringTable.get(AsmNames[i]) << ", ";
601   }
602   O << "\n  };\n"
603     << "\n";
604 }
605 
606 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
607   Record *AsmWriter = Target.getAsmWriter();
608   StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
609   const auto &Registers = Target.getRegBank().getRegisters();
610   const std::vector<Record*> &AltNameIndices = Target.getRegAltNameIndices();
611   bool hasAltNames = AltNameIndices.size() > 1;
612   StringRef Namespace = Registers.front().TheDef->getValueAsString("Namespace");
613 
614   O <<
615   "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
616   "/// from the register set description.  This returns the assembler name\n"
617   "/// for the specified register.\n"
618   "const char *" << Target.getName() << ClassName << "::";
619   if (hasAltNames)
620     O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
621   else
622     O << "getRegisterName(unsigned RegNo) {\n";
623   O << "  assert(RegNo && RegNo < " << (Registers.size()+1)
624     << " && \"Invalid register number!\");\n"
625     << "\n";
626 
627   if (hasAltNames) {
628     for (const Record *R : AltNameIndices)
629       emitRegisterNameString(O, R->getName(), Registers);
630   } else
631     emitRegisterNameString(O, "", Registers);
632 
633   if (hasAltNames) {
634     O << "  switch(AltIdx) {\n"
635       << "  default: llvm_unreachable(\"Invalid register alt name index!\");\n";
636     for (const Record *R : AltNameIndices) {
637       StringRef AltName = R->getName();
638       O << "  case ";
639       if (!Namespace.empty())
640         O << Namespace << "::";
641       O << AltName << ":\n";
642       if (R->isValueUnset("FallbackRegAltNameIndex"))
643         O << "    assert(*(AsmStrs" << AltName << "+RegAsmOffset" << AltName
644           << "[RegNo-1]) &&\n"
645           << "           \"Invalid alt name index for register!\");\n";
646       else {
647         O << "    if (!*(AsmStrs" << AltName << "+RegAsmOffset" << AltName
648           << "[RegNo-1]))\n"
649           << "      return getRegisterName(RegNo, ";
650         if (!Namespace.empty())
651           O << Namespace << "::";
652         O << R->getValueAsDef("FallbackRegAltNameIndex")->getName() << ");\n";
653       }
654       O << "    return AsmStrs" << AltName << "+RegAsmOffset" << AltName
655         << "[RegNo-1];\n";
656     }
657     O << "  }\n";
658   } else {
659     O << "  assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
660       << "          \"Invalid alt name index for register!\");\n"
661       << "  return AsmStrs+RegAsmOffset[RegNo-1];\n";
662   }
663   O << "}\n";
664 }
665 
666 namespace {
667 
668 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
669 // they both have the same conditionals. In which case, we cannot print out the
670 // alias for that pattern.
671 class IAPrinter {
672   std::map<StringRef, std::pair<int, int>> OpMap;
673 
674   std::vector<std::string> Conds;
675 
676   std::string Result;
677   std::string AsmString;
678 
679   unsigned NumMIOps;
680 
681 public:
682   IAPrinter(std::string R, std::string AS, unsigned NumMIOps)
683       : Result(std::move(R)), AsmString(std::move(AS)), NumMIOps(NumMIOps) {}
684 
685   void addCond(std::string C) { Conds.push_back(std::move(C)); }
686   ArrayRef<std::string> getConds() const { return Conds; }
687   size_t getCondCount() const { return Conds.size(); }
688 
689   void addOperand(StringRef Op, int OpIdx, int PrintMethodIdx = -1) {
690     assert(OpIdx >= 0 && OpIdx < 0xFE && "Idx out of range");
691     assert(PrintMethodIdx >= -1 && PrintMethodIdx < 0xFF &&
692            "Idx out of range");
693     OpMap[Op] = std::make_pair(OpIdx, PrintMethodIdx);
694   }
695 
696   unsigned getNumMIOps() { return NumMIOps; }
697 
698   StringRef getResult() { return Result; }
699 
700   bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
701   int getOpIndex(StringRef Op) { return OpMap[Op].first; }
702   std::pair<int, int> &getOpData(StringRef Op) { return OpMap[Op]; }
703 
704   std::pair<StringRef, StringRef::iterator> parseName(StringRef::iterator Start,
705                                                       StringRef::iterator End) {
706     StringRef::iterator I = Start;
707     StringRef::iterator Next;
708     if (*I == '{') {
709       // ${some_name}
710       Start = ++I;
711       while (I != End && *I != '}')
712         ++I;
713       Next = I;
714       // eat the final '}'
715       if (Next != End)
716         ++Next;
717     } else {
718       // $name, just eat the usual suspects.
719       while (I != End &&
720              ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') ||
721               (*I >= '0' && *I <= '9') || *I == '_'))
722         ++I;
723       Next = I;
724     }
725 
726     return std::make_pair(StringRef(Start, I - Start), Next);
727   }
728 
729   std::string formatAliasString(uint32_t &UnescapedSize) {
730     // Directly mangle mapped operands into the string. Each operand is
731     // identified by a '$' sign followed by a byte identifying the number of the
732     // operand. We add one to the index to avoid zero bytes.
733     StringRef ASM(AsmString);
734     std::string OutString;
735     raw_string_ostream OS(OutString);
736     for (StringRef::iterator I = ASM.begin(), E = ASM.end(); I != E;) {
737       OS << *I;
738       ++UnescapedSize;
739       if (*I == '$') {
740         StringRef Name;
741         std::tie(Name, I) = parseName(++I, E);
742         assert(isOpMapped(Name) && "Unmapped operand!");
743 
744         int OpIndex, PrintIndex;
745         std::tie(OpIndex, PrintIndex) = getOpData(Name);
746         if (PrintIndex == -1) {
747           // Can use the default printOperand route.
748           OS << format("\\x%02X", (unsigned char)OpIndex + 1);
749           ++UnescapedSize;
750         } else {
751           // 3 bytes if a PrintMethod is needed: 0xFF, the MCInst operand
752           // number, and which of our pre-detected Methods to call.
753           OS << format("\\xFF\\x%02X\\x%02X", OpIndex + 1, PrintIndex + 1);
754           UnescapedSize += 3;
755         }
756       } else {
757         ++I;
758       }
759     }
760 
761     OS.flush();
762     return OutString;
763   }
764 
765   bool operator==(const IAPrinter &RHS) const {
766     if (NumMIOps != RHS.NumMIOps)
767       return false;
768     if (Conds.size() != RHS.Conds.size())
769       return false;
770 
771     unsigned Idx = 0;
772     for (const auto &str : Conds)
773       if (str != RHS.Conds[Idx++])
774         return false;
775 
776     return true;
777   }
778 };
779 
780 } // end anonymous namespace
781 
782 static unsigned CountNumOperands(StringRef AsmString, unsigned Variant) {
783   return AsmString.count(' ') + AsmString.count('\t');
784 }
785 
786 namespace {
787 
788 struct AliasPriorityComparator {
789   typedef std::pair<CodeGenInstAlias, int> ValueType;
790   bool operator()(const ValueType &LHS, const ValueType &RHS) const {
791     if (LHS.second ==  RHS.second) {
792       // We don't actually care about the order, but for consistency it
793       // shouldn't depend on pointer comparisons.
794       return LessRecordByID()(LHS.first.TheDef, RHS.first.TheDef);
795     }
796 
797     // Aliases with larger priorities should be considered first.
798     return LHS.second > RHS.second;
799   }
800 };
801 
802 } // end anonymous namespace
803 
804 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
805   Record *AsmWriter = Target.getAsmWriter();
806 
807   O << "\n#ifdef PRINT_ALIAS_INSTR\n";
808   O << "#undef PRINT_ALIAS_INSTR\n\n";
809 
810   //////////////////////////////
811   // Gather information about aliases we need to print
812   //////////////////////////////
813 
814   // Emit the method that prints the alias instruction.
815   StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
816   unsigned Variant = AsmWriter->getValueAsInt("Variant");
817   bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
818 
819   std::vector<Record*> AllInstAliases =
820     Records.getAllDerivedDefinitions("InstAlias");
821 
822   // Create a map from the qualified name to a list of potential matches.
823   typedef std::set<std::pair<CodeGenInstAlias, int>, AliasPriorityComparator>
824       AliasWithPriority;
825   std::map<std::string, AliasWithPriority> AliasMap;
826   for (Record *R : AllInstAliases) {
827     int Priority = R->getValueAsInt("EmitPriority");
828     if (Priority < 1)
829       continue; // Aliases with priority 0 are never emitted.
830 
831     const DagInit *DI = R->getValueAsDag("ResultInst");
832     AliasMap[getQualifiedName(DI->getOperatorAsDef(R->getLoc()))].insert(
833         std::make_pair(CodeGenInstAlias(R, Target), Priority));
834   }
835 
836   // A map of which conditions need to be met for each instruction operand
837   // before it can be matched to the mnemonic.
838   std::map<std::string, std::vector<IAPrinter>> IAPrinterMap;
839 
840   std::vector<std::pair<std::string, bool>> PrintMethods;
841 
842   // A list of MCOperandPredicates for all operands in use, and the reverse map
843   std::vector<const Record*> MCOpPredicates;
844   DenseMap<const Record*, unsigned> MCOpPredicateMap;
845 
846   for (auto &Aliases : AliasMap) {
847     // Collection of instruction alias rules. May contain ambiguous rules.
848     std::vector<IAPrinter> IAPs;
849 
850     for (auto &Alias : Aliases.second) {
851       const CodeGenInstAlias &CGA = Alias.first;
852       unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
853       std::string FlatInstAsmString =
854          CodeGenInstruction::FlattenAsmStringVariants(CGA.ResultInst->AsmString,
855                                                       Variant);
856       unsigned NumResultOps = CountNumOperands(FlatInstAsmString, Variant);
857 
858       std::string FlatAliasAsmString =
859           CodeGenInstruction::FlattenAsmStringVariants(CGA.AsmString, Variant);
860       UnescapeAliasString(FlatAliasAsmString);
861 
862       // Don't emit the alias if it has more operands than what it's aliasing.
863       if (NumResultOps < CountNumOperands(FlatAliasAsmString, Variant))
864         continue;
865 
866       StringRef Namespace = Target.getName();
867       unsigned NumMIOps = 0;
868       for (auto &ResultInstOpnd : CGA.ResultInst->Operands)
869         NumMIOps += ResultInstOpnd.MINumOperands;
870 
871       IAPrinter IAP(CGA.Result->getAsString(), FlatAliasAsmString, NumMIOps);
872 
873       bool CantHandle = false;
874 
875       unsigned MIOpNum = 0;
876       for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
877         // Skip over tied operands as they're not part of an alias declaration.
878         auto &Operands = CGA.ResultInst->Operands;
879         while (true) {
880           unsigned OpNum = Operands.getSubOperandNumber(MIOpNum).first;
881           if (Operands[OpNum].MINumOperands == 1 &&
882               Operands[OpNum].getTiedRegister() != -1) {
883             // Tied operands of different RegisterClass should be explicit within
884             // an instruction's syntax and so cannot be skipped.
885             int TiedOpNum = Operands[OpNum].getTiedRegister();
886             if (Operands[OpNum].Rec->getName() ==
887                 Operands[TiedOpNum].Rec->getName()) {
888               ++MIOpNum;
889               continue;
890             }
891           }
892           break;
893         }
894 
895         // Ignore unchecked result operands.
896         while (IAP.getCondCount() < MIOpNum)
897           IAP.addCond("AliasPatternCond::K_Ignore, 0");
898 
899         const CodeGenInstAlias::ResultOperand &RO = CGA.ResultOperands[i];
900 
901         switch (RO.Kind) {
902         case CodeGenInstAlias::ResultOperand::K_Record: {
903           const Record *Rec = RO.getRecord();
904           StringRef ROName = RO.getName();
905           int PrintMethodIdx = -1;
906 
907           // These two may have a PrintMethod, which we want to record (if it's
908           // the first time we've seen it) and provide an index for the aliasing
909           // code to use.
910           if (Rec->isSubClassOf("RegisterOperand") ||
911               Rec->isSubClassOf("Operand")) {
912             StringRef PrintMethod = Rec->getValueAsString("PrintMethod");
913             bool IsPCRel =
914                 Rec->getValueAsString("OperandType") == "OPERAND_PCREL";
915             if (PrintMethod != "" && PrintMethod != "printOperand") {
916               PrintMethodIdx = llvm::find_if(PrintMethods,
917                                              [&](auto &X) {
918                                                return X.first == PrintMethod;
919                                              }) -
920                                PrintMethods.begin();
921               if (static_cast<unsigned>(PrintMethodIdx) == PrintMethods.size())
922                 PrintMethods.emplace_back(std::string(PrintMethod), IsPCRel);
923             }
924           }
925 
926           if (Rec->isSubClassOf("RegisterOperand"))
927             Rec = Rec->getValueAsDef("RegClass");
928           if (Rec->isSubClassOf("RegisterClass")) {
929             if (!IAP.isOpMapped(ROName)) {
930               IAP.addOperand(ROName, MIOpNum, PrintMethodIdx);
931               Record *R = CGA.ResultOperands[i].getRecord();
932               if (R->isSubClassOf("RegisterOperand"))
933                 R = R->getValueAsDef("RegClass");
934               IAP.addCond(std::string(
935                   formatv("AliasPatternCond::K_RegClass, {0}::{1}RegClassID",
936                           Namespace, R->getName())));
937             } else {
938               IAP.addCond(std::string(formatv(
939                   "AliasPatternCond::K_TiedReg, {0}", IAP.getOpIndex(ROName))));
940             }
941           } else {
942             // Assume all printable operands are desired for now. This can be
943             // overridden in the InstAlias instantiation if necessary.
944             IAP.addOperand(ROName, MIOpNum, PrintMethodIdx);
945 
946             // There might be an additional predicate on the MCOperand
947             unsigned Entry = MCOpPredicateMap[Rec];
948             if (!Entry) {
949               if (!Rec->isValueUnset("MCOperandPredicate")) {
950                 MCOpPredicates.push_back(Rec);
951                 Entry = MCOpPredicates.size();
952                 MCOpPredicateMap[Rec] = Entry;
953               } else
954                 break; // No conditions on this operand at all
955             }
956             IAP.addCond(
957                 std::string(formatv("AliasPatternCond::K_Custom, {0}", Entry)));
958           }
959           break;
960         }
961         case CodeGenInstAlias::ResultOperand::K_Imm: {
962           // Just because the alias has an immediate result, doesn't mean the
963           // MCInst will. An MCExpr could be present, for example.
964           auto Imm = CGA.ResultOperands[i].getImm();
965           int32_t Imm32 = int32_t(Imm);
966           if (Imm != Imm32)
967             PrintFatalError("Matching an alias with an immediate out of the "
968                             "range of int32_t is not supported");
969           IAP.addCond(std::string(
970               formatv("AliasPatternCond::K_Imm, uint32_t({0})", Imm32)));
971           break;
972         }
973         case CodeGenInstAlias::ResultOperand::K_Reg:
974           // If this is zero_reg, something's playing tricks we're not
975           // equipped to handle.
976           if (!CGA.ResultOperands[i].getRegister()) {
977             CantHandle = true;
978             break;
979           }
980 
981           StringRef Reg = CGA.ResultOperands[i].getRegister()->getName();
982           IAP.addCond(std::string(
983               formatv("AliasPatternCond::K_Reg, {0}::{1}", Namespace, Reg)));
984           break;
985         }
986 
987         MIOpNum += RO.getMINumOperands();
988       }
989 
990       if (CantHandle) continue;
991 
992       std::vector<Record *> ReqFeatures;
993       if (PassSubtarget) {
994         // We only consider ReqFeatures predicates if PassSubtarget
995         std::vector<Record *> RF =
996             CGA.TheDef->getValueAsListOfDefs("Predicates");
997         copy_if(RF, std::back_inserter(ReqFeatures), [](Record *R) {
998           return R->getValueAsBit("AssemblerMatcherPredicate");
999         });
1000       }
1001 
1002       for (auto I = ReqFeatures.cbegin(); I != ReqFeatures.cend(); I++) {
1003         Record *R = *I;
1004         const DagInit *D = R->getValueAsDag("AssemblerCondDag");
1005         std::string CombineType = D->getOperator()->getAsString();
1006         if (CombineType != "any_of" && CombineType != "all_of")
1007           PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");
1008         if (D->getNumArgs() == 0)
1009           PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");
1010         bool IsOr = CombineType == "any_of";
1011 
1012         for (auto *Arg : D->getArgs()) {
1013           bool IsNeg = false;
1014           if (auto *NotArg = dyn_cast<DagInit>(Arg)) {
1015             if (NotArg->getOperator()->getAsString() != "not" ||
1016                 NotArg->getNumArgs() != 1)
1017               PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");
1018             Arg = NotArg->getArg(0);
1019             IsNeg = true;
1020           }
1021           if (!isa<DefInit>(Arg) ||
1022               !cast<DefInit>(Arg)->getDef()->isSubClassOf("SubtargetFeature"))
1023             PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");
1024 
1025           IAP.addCond(std::string(formatv(
1026               "AliasPatternCond::K_{0}{1}Feature, {2}::{3}", IsOr ? "Or" : "",
1027               IsNeg ? "Neg" : "", Namespace, Arg->getAsString())));
1028         }
1029         // If an AssemblerPredicate with ors is used, note end of list should
1030         // these be combined.
1031         if (IsOr)
1032           IAP.addCond("AliasPatternCond::K_EndOrFeatures, 0");
1033       }
1034 
1035       IAPrinterMap[Aliases.first].push_back(std::move(IAP));
1036     }
1037   }
1038 
1039   //////////////////////////////
1040   // Write out the printAliasInstr function
1041   //////////////////////////////
1042 
1043   std::string Header;
1044   raw_string_ostream HeaderO(Header);
1045 
1046   HeaderO << "bool " << Target.getName() << ClassName
1047           << "::printAliasInstr(const MCInst"
1048           << " *MI, uint64_t Address, "
1049           << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
1050           << "raw_ostream &OS) {\n";
1051 
1052   std::string PatternsForOpcode;
1053   raw_string_ostream OpcodeO(PatternsForOpcode);
1054 
1055   unsigned PatternCount = 0;
1056   std::string Patterns;
1057   raw_string_ostream PatternO(Patterns);
1058 
1059   unsigned CondCount = 0;
1060   std::string Conds;
1061   raw_string_ostream CondO(Conds);
1062 
1063   // All flattened alias strings.
1064   std::map<std::string, uint32_t> AsmStringOffsets;
1065   std::vector<std::pair<uint32_t, std::string>> AsmStrings;
1066   size_t AsmStringsSize = 0;
1067 
1068   // Iterate over the opcodes in enum order so they are sorted by opcode for
1069   // binary search.
1070   for (const CodeGenInstruction *Inst : NumberedInstructions) {
1071     auto It = IAPrinterMap.find(getQualifiedName(Inst->TheDef));
1072     if (It == IAPrinterMap.end())
1073       continue;
1074     std::vector<IAPrinter> &IAPs = It->second;
1075     std::vector<IAPrinter*> UniqueIAPs;
1076 
1077     // Remove any ambiguous alias rules.
1078     for (auto &LHS : IAPs) {
1079       bool IsDup = false;
1080       for (const auto &RHS : IAPs) {
1081         if (&LHS != &RHS && LHS == RHS) {
1082           IsDup = true;
1083           break;
1084         }
1085       }
1086 
1087       if (!IsDup)
1088         UniqueIAPs.push_back(&LHS);
1089     }
1090 
1091     if (UniqueIAPs.empty()) continue;
1092 
1093     unsigned PatternStart = PatternCount;
1094 
1095     // Insert the pattern start and opcode in the pattern list for debugging.
1096     PatternO << formatv("    // {0} - {1}\n", It->first, PatternStart);
1097 
1098     for (IAPrinter *IAP : UniqueIAPs) {
1099       // Start each condition list with a comment of the resulting pattern that
1100       // we're trying to match.
1101       unsigned CondStart = CondCount;
1102       CondO << formatv("    // {0} - {1}\n", IAP->getResult(), CondStart);
1103       for (const auto &Cond : IAP->getConds())
1104         CondO << "    {" << Cond << "},\n";
1105       CondCount += IAP->getCondCount();
1106 
1107       // After operands have been examined, re-encode the alias string with
1108       // escapes indicating how operands should be printed.
1109       uint32_t UnescapedSize = 0;
1110       std::string EncodedAsmString = IAP->formatAliasString(UnescapedSize);
1111       auto Insertion =
1112           AsmStringOffsets.insert({EncodedAsmString, AsmStringsSize});
1113       if (Insertion.second) {
1114         // If the string is new, add it to the vector.
1115         AsmStrings.push_back({AsmStringsSize, EncodedAsmString});
1116         AsmStringsSize += UnescapedSize + 1;
1117       }
1118       unsigned AsmStrOffset = Insertion.first->second;
1119 
1120       PatternO << formatv("    {{{0}, {1}, {2}, {3} },\n", AsmStrOffset,
1121                           CondStart, IAP->getNumMIOps(), IAP->getCondCount());
1122       ++PatternCount;
1123     }
1124 
1125     OpcodeO << formatv("    {{{0}, {1}, {2} },\n", It->first, PatternStart,
1126                        PatternCount - PatternStart);
1127   }
1128 
1129   if (OpcodeO.str().empty()) {
1130     O << HeaderO.str();
1131     O << "  return false;\n";
1132     O << "}\n\n";
1133     O << "#endif // PRINT_ALIAS_INSTR\n";
1134     return;
1135   }
1136 
1137   // Forward declare the validation method if needed.
1138   if (!MCOpPredicates.empty())
1139     O << "static bool " << Target.getName() << ClassName
1140       << "ValidateMCOperand(const MCOperand &MCOp,\n"
1141       << "                  const MCSubtargetInfo &STI,\n"
1142       << "                  unsigned PredicateIndex);\n";
1143 
1144   O << HeaderO.str();
1145   O.indent(2) << "static const PatternsForOpcode OpToPatterns[] = {\n";
1146   O << OpcodeO.str();
1147   O.indent(2) << "};\n\n";
1148   O.indent(2) << "static const AliasPattern Patterns[] = {\n";
1149   O << PatternO.str();
1150   O.indent(2) << "};\n\n";
1151   O.indent(2) << "static const AliasPatternCond Conds[] = {\n";
1152   O << CondO.str();
1153   O.indent(2) << "};\n\n";
1154   O.indent(2) << "static const char AsmStrings[] =\n";
1155   for (const auto &P : AsmStrings) {
1156     O.indent(4) << "/* " << P.first << " */ \"" << P.second << "\\0\"\n";
1157   }
1158 
1159   O.indent(2) << ";\n\n";
1160 
1161   // Assert that the opcode table is sorted. Use a static local constructor to
1162   // ensure that the check only happens once on first run.
1163   O << "#ifndef NDEBUG\n";
1164   O.indent(2) << "static struct SortCheck {\n";
1165   O.indent(2) << "  SortCheck(ArrayRef<PatternsForOpcode> OpToPatterns) {\n";
1166   O.indent(2) << "    assert(std::is_sorted(\n";
1167   O.indent(2) << "               OpToPatterns.begin(), OpToPatterns.end(),\n";
1168   O.indent(2) << "               [](const PatternsForOpcode &L, const "
1169                  "PatternsForOpcode &R) {\n";
1170   O.indent(2) << "                 return L.Opcode < R.Opcode;\n";
1171   O.indent(2) << "               }) &&\n";
1172   O.indent(2) << "           \"tablegen failed to sort opcode patterns\");\n";
1173   O.indent(2) << "  }\n";
1174   O.indent(2) << "} sortCheckVar(OpToPatterns);\n";
1175   O << "#endif\n\n";
1176 
1177   O.indent(2) << "AliasMatchingData M {\n";
1178   O.indent(2) << "  makeArrayRef(OpToPatterns),\n";
1179   O.indent(2) << "  makeArrayRef(Patterns),\n";
1180   O.indent(2) << "  makeArrayRef(Conds),\n";
1181   O.indent(2) << "  StringRef(AsmStrings, array_lengthof(AsmStrings)),\n";
1182   if (MCOpPredicates.empty())
1183     O.indent(2) << "  nullptr,\n";
1184   else
1185     O.indent(2) << "  &" << Target.getName() << ClassName << "ValidateMCOperand,\n";
1186   O.indent(2) << "};\n";
1187 
1188   O.indent(2) << "const char *AsmString = matchAliasPatterns(MI, "
1189               << (PassSubtarget ? "&STI" : "nullptr") << ", M);\n";
1190   O.indent(2) << "if (!AsmString) return false;\n\n";
1191 
1192   // Code that prints the alias, replacing the operands with the ones from the
1193   // MCInst.
1194   O << "  unsigned I = 0;\n";
1195   O << "  while (AsmString[I] != ' ' && AsmString[I] != '\\t' &&\n";
1196   O << "         AsmString[I] != '$' && AsmString[I] != '\\0')\n";
1197   O << "    ++I;\n";
1198   O << "  OS << '\\t' << StringRef(AsmString, I);\n";
1199 
1200   O << "  if (AsmString[I] != '\\0') {\n";
1201   O << "    if (AsmString[I] == ' ' || AsmString[I] == '\\t') {\n";
1202   O << "      OS << '\\t';\n";
1203   O << "      ++I;\n";
1204   O << "    }\n";
1205   O << "    do {\n";
1206   O << "      if (AsmString[I] == '$') {\n";
1207   O << "        ++I;\n";
1208   O << "        if (AsmString[I] == (char)0xff) {\n";
1209   O << "          ++I;\n";
1210   O << "          int OpIdx = AsmString[I++] - 1;\n";
1211   O << "          int PrintMethodIdx = AsmString[I++] - 1;\n";
1212   O << "          printCustomAliasOperand(MI, Address, OpIdx, PrintMethodIdx, ";
1213   O << (PassSubtarget ? "STI, " : "");
1214   O << "OS);\n";
1215   O << "        } else\n";
1216   O << "          printOperand(MI, unsigned(AsmString[I++]) - 1, ";
1217   O << (PassSubtarget ? "STI, " : "");
1218   O << "OS);\n";
1219   O << "      } else {\n";
1220   O << "        OS << AsmString[I++];\n";
1221   O << "      }\n";
1222   O << "    } while (AsmString[I] != '\\0');\n";
1223   O << "  }\n\n";
1224 
1225   O << "  return true;\n";
1226   O << "}\n\n";
1227 
1228   //////////////////////////////
1229   // Write out the printCustomAliasOperand function
1230   //////////////////////////////
1231 
1232   O << "void " << Target.getName() << ClassName << "::"
1233     << "printCustomAliasOperand(\n"
1234     << "         const MCInst *MI, uint64_t Address, unsigned OpIdx,\n"
1235     << "         unsigned PrintMethodIdx,\n"
1236     << (PassSubtarget ? "         const MCSubtargetInfo &STI,\n" : "")
1237     << "         raw_ostream &OS) {\n";
1238   if (PrintMethods.empty())
1239     O << "  llvm_unreachable(\"Unknown PrintMethod kind\");\n";
1240   else {
1241     O << "  switch (PrintMethodIdx) {\n"
1242       << "  default:\n"
1243       << "    llvm_unreachable(\"Unknown PrintMethod kind\");\n"
1244       << "    break;\n";
1245 
1246     for (unsigned i = 0; i < PrintMethods.size(); ++i) {
1247       O << "  case " << i << ":\n"
1248         << "    " << PrintMethods[i].first << "(MI, "
1249         << (PrintMethods[i].second ? "Address, " : "") << "OpIdx, "
1250         << (PassSubtarget ? "STI, " : "") << "OS);\n"
1251         << "    break;\n";
1252     }
1253     O << "  }\n";
1254   }
1255   O << "}\n\n";
1256 
1257   if (!MCOpPredicates.empty()) {
1258     O << "static bool " << Target.getName() << ClassName
1259       << "ValidateMCOperand(const MCOperand &MCOp,\n"
1260       << "                  const MCSubtargetInfo &STI,\n"
1261       << "                  unsigned PredicateIndex) {\n"
1262       << "  switch (PredicateIndex) {\n"
1263       << "  default:\n"
1264       << "    llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n"
1265       << "    break;\n";
1266 
1267     for (unsigned i = 0; i < MCOpPredicates.size(); ++i) {
1268       StringRef MCOpPred = MCOpPredicates[i]->getValueAsString("MCOperandPredicate");
1269       O << "  case " << i + 1 << ": {\n"
1270         << MCOpPred.data() << "\n"
1271         << "    }\n";
1272     }
1273     O << "  }\n"
1274       << "}\n\n";
1275   }
1276 
1277   O << "#endif // PRINT_ALIAS_INSTR\n";
1278 }
1279 
1280 AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) {
1281   Record *AsmWriter = Target.getAsmWriter();
1282   unsigned Variant = AsmWriter->getValueAsInt("Variant");
1283 
1284   // Get the instruction numbering.
1285   NumberedInstructions = Target.getInstructionsByEnumValue();
1286 
1287   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
1288     const CodeGenInstruction *I = NumberedInstructions[i];
1289     if (!I->AsmString.empty() && I->TheDef->getName() != "PHI")
1290       Instructions.emplace_back(*I, i, Variant);
1291   }
1292 }
1293 
1294 void AsmWriterEmitter::run(raw_ostream &O) {
1295   std::vector<std::vector<std::string>> TableDrivenOperandPrinters;
1296   unsigned BitsLeft = 0;
1297   unsigned AsmStrBits = 0;
1298   EmitGetMnemonic(O, TableDrivenOperandPrinters, BitsLeft, AsmStrBits);
1299   EmitPrintInstruction(O, TableDrivenOperandPrinters, BitsLeft, AsmStrBits);
1300   EmitGetRegisterName(O);
1301   EmitPrintAliasInstruction(O);
1302 }
1303 
1304 namespace llvm {
1305 
1306 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
1307   emitSourceFileHeader("Assembly Writer Source Fragment", OS);
1308   AsmWriterEmitter(RK).run(OS);
1309 }
1310 
1311 } // end namespace llvm
1312