1 //===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend emits an assembly printer for the current target.
11 // Note that this is currently fairly skeletal, but will grow over time.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "AsmWriterInst.h"
16 #include "CodeGenTarget.h"
17 #include "SequenceToOffsetTable.h"
18 #include "Types.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/Format.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/TableGen/Error.h"
26 #include "llvm/TableGen/Record.h"
27 #include "llvm/TableGen/TableGenBackend.h"
28 #include <algorithm>
29 #include <cassert>
30 #include <map>
31 #include <utility>
32 #include <vector>
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "asm-writer-emitter"
36 
37 namespace {
38 class AsmWriterEmitter {
39   RecordKeeper &Records;
40   CodeGenTarget Target;
41   ArrayRef<const CodeGenInstruction *> NumberedInstructions;
42   std::vector<AsmWriterInst> Instructions;
43 public:
44   AsmWriterEmitter(RecordKeeper &R);
45 
46   void run(raw_ostream &o);
47 
48 private:
49   void EmitPrintInstruction(raw_ostream &o);
50   void EmitGetRegisterName(raw_ostream &o);
51   void EmitPrintAliasInstruction(raw_ostream &O);
52 
53   void FindUniqueOperandCommands(std::vector<std::string> &UOC,
54                                  std::vector<std::vector<unsigned>> &InstIdxs,
55                                  std::vector<unsigned> &InstOpsUsed,
56                                  bool PassSubtarget) const;
57 };
58 } // end anonymous namespace
59 
60 static void PrintCases(std::vector<std::pair<std::string,
61                        AsmWriterOperand> > &OpsToPrint, raw_ostream &O,
62                        bool PassSubtarget) {
63   O << "    case " << OpsToPrint.back().first << ":";
64   AsmWriterOperand TheOp = OpsToPrint.back().second;
65   OpsToPrint.pop_back();
66 
67   // Check to see if any other operands are identical in this list, and if so,
68   // emit a case label for them.
69   for (unsigned i = OpsToPrint.size(); i != 0; --i)
70     if (OpsToPrint[i-1].second == TheOp) {
71       O << "\n    case " << OpsToPrint[i-1].first << ":";
72       OpsToPrint.erase(OpsToPrint.begin()+i-1);
73     }
74 
75   // Finally, emit the code.
76   O << "\n      " << TheOp.getCode(PassSubtarget);
77   O << "\n      break;\n";
78 }
79 
80 
81 /// EmitInstructions - Emit the last instruction in the vector and any other
82 /// instructions that are suitably similar to it.
83 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
84                              raw_ostream &O, bool PassSubtarget) {
85   AsmWriterInst FirstInst = Insts.back();
86   Insts.pop_back();
87 
88   std::vector<AsmWriterInst> SimilarInsts;
89   unsigned DifferingOperand = ~0;
90   for (unsigned i = Insts.size(); i != 0; --i) {
91     unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
92     if (DiffOp != ~1U) {
93       if (DifferingOperand == ~0U)  // First match!
94         DifferingOperand = DiffOp;
95 
96       // If this differs in the same operand as the rest of the instructions in
97       // this class, move it to the SimilarInsts list.
98       if (DifferingOperand == DiffOp || DiffOp == ~0U) {
99         SimilarInsts.push_back(Insts[i-1]);
100         Insts.erase(Insts.begin()+i-1);
101       }
102     }
103   }
104 
105   O << "  case " << FirstInst.CGI->Namespace << "::"
106     << FirstInst.CGI->TheDef->getName() << ":\n";
107   for (const AsmWriterInst &AWI : SimilarInsts)
108     O << "  case " << AWI.CGI->Namespace << "::"
109       << AWI.CGI->TheDef->getName() << ":\n";
110   for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
111     if (i != DifferingOperand) {
112       // If the operand is the same for all instructions, just print it.
113       O << "    " << FirstInst.Operands[i].getCode(PassSubtarget);
114     } else {
115       // If this is the operand that varies between all of the instructions,
116       // emit a switch for just this operand now.
117       O << "    switch (MI->getOpcode()) {\n";
118       O << "    default: llvm_unreachable(\"Unexpected opcode.\");\n";
119       std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
120       OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
121                                           FirstInst.CGI->TheDef->getName(),
122                                           FirstInst.Operands[i]));
123 
124       for (const AsmWriterInst &AWI : SimilarInsts) {
125         OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
126                                             AWI.CGI->TheDef->getName(),
127                                             AWI.Operands[i]));
128       }
129       std::reverse(OpsToPrint.begin(), OpsToPrint.end());
130       while (!OpsToPrint.empty())
131         PrintCases(OpsToPrint, O, PassSubtarget);
132       O << "    }";
133     }
134     O << "\n";
135   }
136   O << "    break;\n";
137 }
138 
139 void AsmWriterEmitter::
140 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
141                           std::vector<std::vector<unsigned>> &InstIdxs,
142                           std::vector<unsigned> &InstOpsUsed,
143                           bool PassSubtarget) const {
144 
145   // This vector parallels UniqueOperandCommands, keeping track of which
146   // instructions each case are used for.  It is a comma separated string of
147   // enums.
148   std::vector<std::string> InstrsForCase;
149   InstrsForCase.resize(UniqueOperandCommands.size());
150   InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
151 
152   for (size_t i = 0, e = Instructions.size(); i != e; ++i) {
153     const AsmWriterInst &Inst = Instructions[i];
154     if (Inst.Operands.empty())
155       continue;   // Instruction already done.
156 
157     std::string Command = "    "+Inst.Operands[0].getCode(PassSubtarget)+"\n";
158 
159     // Check to see if we already have 'Command' in UniqueOperandCommands.
160     // If not, add it.
161     auto I = find(UniqueOperandCommands, Command);
162     if (I != UniqueOperandCommands.end()) {
163       size_t idx = I - UniqueOperandCommands.begin();
164       InstrsForCase[idx] += ", ";
165       InstrsForCase[idx] += Inst.CGI->TheDef->getName();
166       InstIdxs[idx].push_back(i);
167     } else {
168       UniqueOperandCommands.push_back(std::move(Command));
169       InstrsForCase.push_back(Inst.CGI->TheDef->getName());
170       InstIdxs.emplace_back();
171       InstIdxs.back().push_back(i);
172 
173       // This command matches one operand so far.
174       InstOpsUsed.push_back(1);
175     }
176   }
177 
178   // For each entry of UniqueOperandCommands, there is a set of instructions
179   // that uses it.  If the next command of all instructions in the set are
180   // identical, fold it into the command.
181   for (size_t CommandIdx = 0, e = UniqueOperandCommands.size();
182        CommandIdx != e; ++CommandIdx) {
183 
184     const auto &Idxs = InstIdxs[CommandIdx];
185 
186     for (unsigned Op = 1; ; ++Op) {
187       // Find the first instruction in the set.
188       const AsmWriterInst &FirstInst = Instructions[Idxs.front()];
189       // If this instruction has no more operands, we isn't anything to merge
190       // into this command.
191       if (FirstInst.Operands.size() == Op)
192         break;
193 
194       // Otherwise, scan to see if all of the other instructions in this command
195       // set share the operand.
196       if (std::any_of(Idxs.begin()+1, Idxs.end(),
197                       [&](unsigned Idx) {
198                         const AsmWriterInst &OtherInst = Instructions[Idx];
199                         return OtherInst.Operands.size() == Op ||
200                           OtherInst.Operands[Op] != FirstInst.Operands[Op];
201                       }))
202         break;
203 
204       // Okay, everything in this command set has the same next operand.  Add it
205       // to UniqueOperandCommands and remember that it was consumed.
206       std::string Command = "    " +
207         FirstInst.Operands[Op].getCode(PassSubtarget) + "\n";
208 
209       UniqueOperandCommands[CommandIdx] += Command;
210       InstOpsUsed[CommandIdx]++;
211     }
212   }
213 
214   // Prepend some of the instructions each case is used for onto the case val.
215   for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
216     std::string Instrs = InstrsForCase[i];
217     if (Instrs.size() > 70) {
218       Instrs.erase(Instrs.begin()+70, Instrs.end());
219       Instrs += "...";
220     }
221 
222     if (!Instrs.empty())
223       UniqueOperandCommands[i] = "    // " + Instrs + "\n" +
224         UniqueOperandCommands[i];
225   }
226 }
227 
228 
229 static void UnescapeString(std::string &Str) {
230   for (unsigned i = 0; i != Str.size(); ++i) {
231     if (Str[i] == '\\' && i != Str.size()-1) {
232       switch (Str[i+1]) {
233       default: continue;  // Don't execute the code after the switch.
234       case 'a': Str[i] = '\a'; break;
235       case 'b': Str[i] = '\b'; break;
236       case 'e': Str[i] = 27; break;
237       case 'f': Str[i] = '\f'; break;
238       case 'n': Str[i] = '\n'; break;
239       case 'r': Str[i] = '\r'; break;
240       case 't': Str[i] = '\t'; break;
241       case 'v': Str[i] = '\v'; break;
242       case '"': Str[i] = '\"'; break;
243       case '\'': Str[i] = '\''; break;
244       case '\\': Str[i] = '\\'; break;
245       }
246       // Nuke the second character.
247       Str.erase(Str.begin()+i+1);
248     }
249   }
250 }
251 
252 /// EmitPrintInstruction - Generate the code for the "printInstruction" method
253 /// implementation. Destroys all instances of AsmWriterInst information, by
254 /// clearing the Instructions vector.
255 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
256   Record *AsmWriter = Target.getAsmWriter();
257   std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
258   bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
259 
260   O <<
261   "/// printInstruction - This method is automatically generated by tablegen\n"
262   "/// from the instruction set description.\n"
263     "void " << Target.getName() << ClassName
264             << "::printInstruction(const MCInst *MI, "
265             << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
266             << "raw_ostream &O) {\n";
267 
268   // Build an aggregate string, and build a table of offsets into it.
269   SequenceToOffsetTable<std::string> StringTable;
270 
271   /// OpcodeInfo - This encodes the index of the string to use for the first
272   /// chunk of the output as well as indices used for operand printing.
273   std::vector<uint64_t> OpcodeInfo(NumberedInstructions.size());
274   const unsigned OpcodeInfoBits = 64;
275 
276   // Add all strings to the string table upfront so it can generate an optimized
277   // representation.
278   for (AsmWriterInst &AWI : Instructions) {
279     if (AWI.Operands[0].OperandType ==
280                  AsmWriterOperand::isLiteralTextOperand &&
281         !AWI.Operands[0].Str.empty()) {
282       std::string Str = AWI.Operands[0].Str;
283       UnescapeString(Str);
284       StringTable.add(Str);
285     }
286   }
287 
288   StringTable.layout();
289 
290   unsigned MaxStringIdx = 0;
291   for (AsmWriterInst &AWI : Instructions) {
292     unsigned Idx;
293     if (AWI.Operands[0].OperandType != AsmWriterOperand::isLiteralTextOperand ||
294         AWI.Operands[0].Str.empty()) {
295       // Something handled by the asmwriter printer, but with no leading string.
296       Idx = StringTable.get("");
297     } else {
298       std::string Str = AWI.Operands[0].Str;
299       UnescapeString(Str);
300       Idx = StringTable.get(Str);
301       MaxStringIdx = std::max(MaxStringIdx, Idx);
302 
303       // Nuke the string from the operand list.  It is now handled!
304       AWI.Operands.erase(AWI.Operands.begin());
305     }
306 
307     // Bias offset by one since we want 0 as a sentinel.
308     OpcodeInfo[AWI.CGIIndex] = Idx+1;
309   }
310 
311   // Figure out how many bits we used for the string index.
312   unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
313 
314   // To reduce code size, we compactify common instructions into a few bits
315   // in the opcode-indexed table.
316   unsigned BitsLeft = OpcodeInfoBits-AsmStrBits;
317 
318   std::vector<std::vector<std::string>> TableDrivenOperandPrinters;
319 
320   while (1) {
321     std::vector<std::string> UniqueOperandCommands;
322     std::vector<std::vector<unsigned>> InstIdxs;
323     std::vector<unsigned> NumInstOpsHandled;
324     FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
325                               NumInstOpsHandled, PassSubtarget);
326 
327     // If we ran out of operands to print, we're done.
328     if (UniqueOperandCommands.empty()) break;
329 
330     // Compute the number of bits we need to represent these cases, this is
331     // ceil(log2(numentries)).
332     unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
333 
334     // If we don't have enough bits for this operand, don't include it.
335     if (NumBits > BitsLeft) {
336       DEBUG(errs() << "Not enough bits to densely encode " << NumBits
337                    << " more bits\n");
338       break;
339     }
340 
341     // Otherwise, we can include this in the initial lookup table.  Add it in.
342     for (size_t i = 0, e = InstIdxs.size(); i != e; ++i) {
343       unsigned NumOps = NumInstOpsHandled[i];
344       for (unsigned Idx : InstIdxs[i]) {
345         OpcodeInfo[Instructions[Idx].CGIIndex] |=
346           (uint64_t)i << (OpcodeInfoBits-BitsLeft);
347         // Remove the info about this operand from the instruction.
348         AsmWriterInst &Inst = Instructions[Idx];
349         if (!Inst.Operands.empty()) {
350           assert(NumOps <= Inst.Operands.size() &&
351                  "Can't remove this many ops!");
352           Inst.Operands.erase(Inst.Operands.begin(),
353                               Inst.Operands.begin()+NumOps);
354         }
355       }
356     }
357     BitsLeft -= NumBits;
358 
359     // Remember the handlers for this set of operands.
360     TableDrivenOperandPrinters.push_back(std::move(UniqueOperandCommands));
361   }
362 
363   // Emit the string table itself.
364   O << "  static const char AsmStrs[] = {\n";
365   StringTable.emit(O, printChar);
366   O << "  };\n\n";
367 
368   // Emit the lookup tables in pieces to minimize wasted bytes.
369   unsigned BytesNeeded = ((OpcodeInfoBits - BitsLeft) + 7) / 8;
370   unsigned Table = 0, Shift = 0;
371   SmallString<128> BitsString;
372   raw_svector_ostream BitsOS(BitsString);
373   // If the total bits is more than 32-bits we need to use a 64-bit type.
374   BitsOS << "  uint" << ((BitsLeft < (OpcodeInfoBits - 32)) ? 64 : 32)
375          << "_t Bits = 0;\n";
376   while (BytesNeeded != 0) {
377     // Figure out how big this table section needs to be, but no bigger than 4.
378     unsigned TableSize = std::min(1 << Log2_32(BytesNeeded), 4);
379     BytesNeeded -= TableSize;
380     TableSize *= 8; // Convert to bits;
381     uint64_t Mask = (1ULL << TableSize) - 1;
382     O << "  static const uint" << TableSize << "_t OpInfo" << Table
383       << "[] = {\n";
384     for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
385       O << "    " << ((OpcodeInfo[i] >> Shift) & Mask) << "U,\t// "
386         << NumberedInstructions[i]->TheDef->getName() << "\n";
387     }
388     O << "  };\n\n";
389     // Emit string to combine the individual table lookups.
390     BitsOS << "  Bits |= ";
391     // If the total bits is more than 32-bits we need to use a 64-bit type.
392     if (BitsLeft < (OpcodeInfoBits - 32))
393       BitsOS << "(uint64_t)";
394     BitsOS << "OpInfo" << Table << "[MI->getOpcode()] << " << Shift << ";\n";
395     // Prepare the shift for the next iteration and increment the table count.
396     Shift += TableSize;
397     ++Table;
398   }
399 
400   // Emit the initial tab character.
401   O << "  O << \"\\t\";\n\n";
402 
403   O << "  // Emit the opcode for the instruction.\n";
404   O << BitsString;
405 
406   // Emit the starting string.
407   O << "  assert(Bits != 0 && \"Cannot print this instruction.\");\n"
408     << "  O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
409 
410   // Output the table driven operand information.
411   BitsLeft = OpcodeInfoBits-AsmStrBits;
412   for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
413     std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
414 
415     // Compute the number of bits we need to represent these cases, this is
416     // ceil(log2(numentries)).
417     unsigned NumBits = Log2_32_Ceil(Commands.size());
418     assert(NumBits <= BitsLeft && "consistency error");
419 
420     // Emit code to extract this field from Bits.
421     O << "\n  // Fragment " << i << " encoded into " << NumBits
422       << " bits for " << Commands.size() << " unique commands.\n";
423 
424     if (Commands.size() == 2) {
425       // Emit two possibilitys with if/else.
426       O << "  if ((Bits >> "
427         << (OpcodeInfoBits-BitsLeft) << ") & "
428         << ((1 << NumBits)-1) << ") {\n"
429         << Commands[1]
430         << "  } else {\n"
431         << Commands[0]
432         << "  }\n\n";
433     } else if (Commands.size() == 1) {
434       // Emit a single possibility.
435       O << Commands[0] << "\n\n";
436     } else {
437       O << "  switch ((Bits >> "
438         << (OpcodeInfoBits-BitsLeft) << ") & "
439         << ((1 << NumBits)-1) << ") {\n"
440         << "  default: llvm_unreachable(\"Invalid command number.\");\n";
441 
442       // Print out all the cases.
443       for (unsigned j = 0, e = Commands.size(); j != e; ++j) {
444         O << "  case " << j << ":\n";
445         O << Commands[j];
446         O << "    break;\n";
447       }
448       O << "  }\n\n";
449     }
450     BitsLeft -= NumBits;
451   }
452 
453   // Okay, delete instructions with no operand info left.
454   auto I = remove_if(Instructions,
455                      [](AsmWriterInst &Inst) { return Inst.Operands.empty(); });
456   Instructions.erase(I, Instructions.end());
457 
458 
459   // Because this is a vector, we want to emit from the end.  Reverse all of the
460   // elements in the vector.
461   std::reverse(Instructions.begin(), Instructions.end());
462 
463 
464   // Now that we've emitted all of the operand info that fit into 64 bits, emit
465   // information for those instructions that are left.  This is a less dense
466   // encoding, but we expect the main 64-bit table to handle the majority of
467   // instructions.
468   if (!Instructions.empty()) {
469     // Find the opcode # of inline asm.
470     O << "  switch (MI->getOpcode()) {\n";
471     O << "  default: llvm_unreachable(\"Unexpected opcode.\");\n";
472     while (!Instructions.empty())
473       EmitInstructions(Instructions, O, PassSubtarget);
474 
475     O << "  }\n";
476   }
477 
478   O << "}\n";
479 }
480 
481 static void
482 emitRegisterNameString(raw_ostream &O, StringRef AltName,
483                        const std::deque<CodeGenRegister> &Registers) {
484   SequenceToOffsetTable<std::string> StringTable;
485   SmallVector<std::string, 4> AsmNames(Registers.size());
486   unsigned i = 0;
487   for (const auto &Reg : Registers) {
488     std::string &AsmName = AsmNames[i++];
489 
490     // "NoRegAltName" is special. We don't need to do a lookup for that,
491     // as it's just a reference to the default register name.
492     if (AltName == "" || AltName == "NoRegAltName") {
493       AsmName = Reg.TheDef->getValueAsString("AsmName");
494       if (AsmName.empty())
495         AsmName = Reg.getName();
496     } else {
497       // Make sure the register has an alternate name for this index.
498       std::vector<Record*> AltNameList =
499         Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
500       unsigned Idx = 0, e;
501       for (e = AltNameList.size();
502            Idx < e && (AltNameList[Idx]->getName() != AltName);
503            ++Idx)
504         ;
505       // If the register has an alternate name for this index, use it.
506       // Otherwise, leave it empty as an error flag.
507       if (Idx < e) {
508         std::vector<std::string> AltNames =
509           Reg.TheDef->getValueAsListOfStrings("AltNames");
510         if (AltNames.size() <= Idx)
511           PrintFatalError(Reg.TheDef->getLoc(),
512                           "Register definition missing alt name for '" +
513                           AltName + "'.");
514         AsmName = AltNames[Idx];
515       }
516     }
517     StringTable.add(AsmName);
518   }
519 
520   StringTable.layout();
521   O << "  static const char AsmStrs" << AltName << "[] = {\n";
522   StringTable.emit(O, printChar);
523   O << "  };\n\n";
524 
525   O << "  static const " << getMinimalTypeForRange(StringTable.size() - 1, 32)
526     << " RegAsmOffset" << AltName << "[] = {";
527   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
528     if ((i % 14) == 0)
529       O << "\n    ";
530     O << StringTable.get(AsmNames[i]) << ", ";
531   }
532   O << "\n  };\n"
533     << "\n";
534 }
535 
536 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
537   Record *AsmWriter = Target.getAsmWriter();
538   std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
539   const auto &Registers = Target.getRegBank().getRegisters();
540   const std::vector<Record*> &AltNameIndices = Target.getRegAltNameIndices();
541   bool hasAltNames = AltNameIndices.size() > 1;
542   std::string Namespace =
543       Registers.front().TheDef->getValueAsString("Namespace");
544 
545   O <<
546   "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
547   "/// from the register set description.  This returns the assembler name\n"
548   "/// for the specified register.\n"
549   "const char *" << Target.getName() << ClassName << "::";
550   if (hasAltNames)
551     O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
552   else
553     O << "getRegisterName(unsigned RegNo) {\n";
554   O << "  assert(RegNo && RegNo < " << (Registers.size()+1)
555     << " && \"Invalid register number!\");\n"
556     << "\n";
557 
558   if (hasAltNames) {
559     for (const Record *R : AltNameIndices)
560       emitRegisterNameString(O, R->getName(), Registers);
561   } else
562     emitRegisterNameString(O, "", Registers);
563 
564   if (hasAltNames) {
565     O << "  switch(AltIdx) {\n"
566       << "  default: llvm_unreachable(\"Invalid register alt name index!\");\n";
567     for (const Record *R : AltNameIndices) {
568       const std::string &AltName = R->getName();
569       std::string Prefix = !Namespace.empty() ? Namespace + "::" : "";
570       O << "  case " << Prefix << AltName << ":\n"
571         << "    assert(*(AsmStrs" << AltName << "+RegAsmOffset"
572         << AltName << "[RegNo-1]) &&\n"
573         << "           \"Invalid alt name index for register!\");\n"
574         << "    return AsmStrs" << AltName << "+RegAsmOffset"
575         << AltName << "[RegNo-1];\n";
576     }
577     O << "  }\n";
578   } else {
579     O << "  assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
580       << "          \"Invalid alt name index for register!\");\n"
581       << "  return AsmStrs+RegAsmOffset[RegNo-1];\n";
582   }
583   O << "}\n";
584 }
585 
586 namespace {
587 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
588 // they both have the same conditionals. In which case, we cannot print out the
589 // alias for that pattern.
590 class IAPrinter {
591   std::vector<std::string> Conds;
592   std::map<StringRef, std::pair<int, int>> OpMap;
593 
594   std::string Result;
595   std::string AsmString;
596 public:
597   IAPrinter(std::string R, std::string AS)
598       : Result(std::move(R)), AsmString(std::move(AS)) {}
599 
600   void addCond(const std::string &C) { Conds.push_back(C); }
601 
602   void addOperand(StringRef Op, int OpIdx, int PrintMethodIdx = -1) {
603     assert(OpIdx >= 0 && OpIdx < 0xFE && "Idx out of range");
604     assert(PrintMethodIdx >= -1 && PrintMethodIdx < 0xFF &&
605            "Idx out of range");
606     OpMap[Op] = std::make_pair(OpIdx, PrintMethodIdx);
607   }
608 
609   bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
610   int getOpIndex(StringRef Op) { return OpMap[Op].first; }
611   std::pair<int, int> &getOpData(StringRef Op) { return OpMap[Op]; }
612 
613   std::pair<StringRef, StringRef::iterator> parseName(StringRef::iterator Start,
614                                                       StringRef::iterator End) {
615     StringRef::iterator I = Start;
616     StringRef::iterator Next;
617     if (*I == '{') {
618       // ${some_name}
619       Start = ++I;
620       while (I != End && *I != '}')
621         ++I;
622       Next = I;
623       // eat the final '}'
624       if (Next != End)
625         ++Next;
626     } else {
627       // $name, just eat the usual suspects.
628       while (I != End &&
629              ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') ||
630               (*I >= '0' && *I <= '9') || *I == '_'))
631         ++I;
632       Next = I;
633     }
634 
635     return std::make_pair(StringRef(Start, I - Start), Next);
636   }
637 
638   void print(raw_ostream &O) {
639     if (Conds.empty()) {
640       O.indent(6) << "return true;\n";
641       return;
642     }
643 
644     O << "if (";
645 
646     for (std::vector<std::string>::iterator
647            I = Conds.begin(), E = Conds.end(); I != E; ++I) {
648       if (I != Conds.begin()) {
649         O << " &&\n";
650         O.indent(8);
651       }
652 
653       O << *I;
654     }
655 
656     O << ") {\n";
657     O.indent(6) << "// " << Result << "\n";
658 
659     // Directly mangle mapped operands into the string. Each operand is
660     // identified by a '$' sign followed by a byte identifying the number of the
661     // operand. We add one to the index to avoid zero bytes.
662     StringRef ASM(AsmString);
663     SmallString<128> OutString;
664     raw_svector_ostream OS(OutString);
665     for (StringRef::iterator I = ASM.begin(), E = ASM.end(); I != E;) {
666       OS << *I;
667       if (*I == '$') {
668         StringRef Name;
669         std::tie(Name, I) = parseName(++I, E);
670         assert(isOpMapped(Name) && "Unmapped operand!");
671 
672         int OpIndex, PrintIndex;
673         std::tie(OpIndex, PrintIndex) = getOpData(Name);
674         if (PrintIndex == -1) {
675           // Can use the default printOperand route.
676           OS << format("\\x%02X", (unsigned char)OpIndex + 1);
677         } else
678           // 3 bytes if a PrintMethod is needed: 0xFF, the MCInst operand
679           // number, and which of our pre-detected Methods to call.
680           OS << format("\\xFF\\x%02X\\x%02X", OpIndex + 1, PrintIndex + 1);
681       } else {
682         ++I;
683       }
684     }
685 
686     // Emit the string.
687     O.indent(6) << "AsmString = \"" << OutString << "\";\n";
688 
689     O.indent(6) << "break;\n";
690     O.indent(4) << '}';
691   }
692 
693   bool operator==(const IAPrinter &RHS) const {
694     if (Conds.size() != RHS.Conds.size())
695       return false;
696 
697     unsigned Idx = 0;
698     for (const auto &str : Conds)
699       if (str != RHS.Conds[Idx++])
700         return false;
701 
702     return true;
703   }
704 };
705 
706 } // end anonymous namespace
707 
708 static unsigned CountNumOperands(StringRef AsmString, unsigned Variant) {
709   std::string FlatAsmString =
710       CodeGenInstruction::FlattenAsmStringVariants(AsmString, Variant);
711   AsmString = FlatAsmString;
712 
713   return AsmString.count(' ') + AsmString.count('\t');
714 }
715 
716 namespace {
717 struct AliasPriorityComparator {
718   typedef std::pair<CodeGenInstAlias, int> ValueType;
719   bool operator()(const ValueType &LHS, const ValueType &RHS) {
720     if (LHS.second ==  RHS.second) {
721       // We don't actually care about the order, but for consistency it
722       // shouldn't depend on pointer comparisons.
723       return LHS.first.TheDef->getName() < RHS.first.TheDef->getName();
724     }
725 
726     // Aliases with larger priorities should be considered first.
727     return LHS.second > RHS.second;
728   }
729 };
730 }
731 
732 
733 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
734   Record *AsmWriter = Target.getAsmWriter();
735 
736   O << "\n#ifdef PRINT_ALIAS_INSTR\n";
737   O << "#undef PRINT_ALIAS_INSTR\n\n";
738 
739   //////////////////////////////
740   // Gather information about aliases we need to print
741   //////////////////////////////
742 
743   // Emit the method that prints the alias instruction.
744   std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
745   unsigned Variant = AsmWriter->getValueAsInt("Variant");
746   bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
747 
748   std::vector<Record*> AllInstAliases =
749     Records.getAllDerivedDefinitions("InstAlias");
750 
751   // Create a map from the qualified name to a list of potential matches.
752   typedef std::set<std::pair<CodeGenInstAlias, int>, AliasPriorityComparator>
753       AliasWithPriority;
754   std::map<std::string, AliasWithPriority> AliasMap;
755   for (Record *R : AllInstAliases) {
756     int Priority = R->getValueAsInt("EmitPriority");
757     if (Priority < 1)
758       continue; // Aliases with priority 0 are never emitted.
759 
760     const DagInit *DI = R->getValueAsDag("ResultInst");
761     const DefInit *Op = cast<DefInit>(DI->getOperator());
762     AliasMap[getQualifiedName(Op->getDef())].insert(
763         std::make_pair(CodeGenInstAlias(R, Variant, Target), Priority));
764   }
765 
766   // A map of which conditions need to be met for each instruction operand
767   // before it can be matched to the mnemonic.
768   std::map<std::string, std::vector<IAPrinter>> IAPrinterMap;
769 
770   std::vector<std::string> PrintMethods;
771 
772   // A list of MCOperandPredicates for all operands in use, and the reverse map
773   std::vector<const Record*> MCOpPredicates;
774   DenseMap<const Record*, unsigned> MCOpPredicateMap;
775 
776   for (auto &Aliases : AliasMap) {
777     for (auto &Alias : Aliases.second) {
778       const CodeGenInstAlias &CGA = Alias.first;
779       unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
780       unsigned NumResultOps =
781           CountNumOperands(CGA.ResultInst->AsmString, Variant);
782 
783       // Don't emit the alias if it has more operands than what it's aliasing.
784       if (NumResultOps < CountNumOperands(CGA.AsmString, Variant))
785         continue;
786 
787       IAPrinter IAP(CGA.Result->getAsString(), CGA.AsmString);
788 
789       std::string Namespace = Target.getName();
790       std::vector<Record *> ReqFeatures;
791       if (PassSubtarget) {
792         // We only consider ReqFeatures predicates if PassSubtarget
793         std::vector<Record *> RF =
794             CGA.TheDef->getValueAsListOfDefs("Predicates");
795         std::copy_if(RF.begin(), RF.end(), std::back_inserter(ReqFeatures),
796                      [](Record *R) {
797                        return R->getValueAsBit("AssemblerMatcherPredicate");
798                      });
799       }
800 
801       unsigned NumMIOps = 0;
802       for (auto &Operand : CGA.ResultOperands)
803         NumMIOps += Operand.getMINumOperands();
804 
805       std::string Cond;
806       Cond = std::string("MI->getNumOperands() == ") + llvm::utostr(NumMIOps);
807       IAP.addCond(Cond);
808 
809       bool CantHandle = false;
810 
811       unsigned MIOpNum = 0;
812       for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
813         std::string Op = "MI->getOperand(" + llvm::utostr(MIOpNum) + ")";
814 
815         const CodeGenInstAlias::ResultOperand &RO = CGA.ResultOperands[i];
816 
817         switch (RO.Kind) {
818         case CodeGenInstAlias::ResultOperand::K_Record: {
819           const Record *Rec = RO.getRecord();
820           StringRef ROName = RO.getName();
821           int PrintMethodIdx = -1;
822 
823           // These two may have a PrintMethod, which we want to record (if it's
824           // the first time we've seen it) and provide an index for the aliasing
825           // code to use.
826           if (Rec->isSubClassOf("RegisterOperand") ||
827               Rec->isSubClassOf("Operand")) {
828             std::string PrintMethod = Rec->getValueAsString("PrintMethod");
829             if (PrintMethod != "" && PrintMethod != "printOperand") {
830               PrintMethodIdx =
831                   find(PrintMethods, PrintMethod) - PrintMethods.begin();
832               if (static_cast<unsigned>(PrintMethodIdx) == PrintMethods.size())
833                 PrintMethods.push_back(PrintMethod);
834             }
835           }
836 
837           if (Rec->isSubClassOf("RegisterOperand"))
838             Rec = Rec->getValueAsDef("RegClass");
839           if (Rec->isSubClassOf("RegisterClass")) {
840             IAP.addCond(Op + ".isReg()");
841 
842             if (!IAP.isOpMapped(ROName)) {
843               IAP.addOperand(ROName, MIOpNum, PrintMethodIdx);
844               Record *R = CGA.ResultOperands[i].getRecord();
845               if (R->isSubClassOf("RegisterOperand"))
846                 R = R->getValueAsDef("RegClass");
847               Cond = std::string("MRI.getRegClass(") + Target.getName() + "::" +
848                      R->getName() + "RegClassID)"
849                                     ".contains(" + Op + ".getReg())";
850             } else {
851               Cond = Op + ".getReg() == MI->getOperand(" +
852                      llvm::utostr(IAP.getOpIndex(ROName)) + ").getReg()";
853             }
854           } else {
855             // Assume all printable operands are desired for now. This can be
856             // overridden in the InstAlias instantiation if necessary.
857             IAP.addOperand(ROName, MIOpNum, PrintMethodIdx);
858 
859             // There might be an additional predicate on the MCOperand
860             unsigned Entry = MCOpPredicateMap[Rec];
861             if (!Entry) {
862               if (!Rec->isValueUnset("MCOperandPredicate")) {
863                 MCOpPredicates.push_back(Rec);
864                 Entry = MCOpPredicates.size();
865                 MCOpPredicateMap[Rec] = Entry;
866               } else
867                 break; // No conditions on this operand at all
868             }
869             Cond = Target.getName() + ClassName + "ValidateMCOperand(" +
870                    Op + ", STI, " + llvm::utostr(Entry) + ")";
871           }
872           // for all subcases of ResultOperand::K_Record:
873           IAP.addCond(Cond);
874           break;
875         }
876         case CodeGenInstAlias::ResultOperand::K_Imm: {
877           // Just because the alias has an immediate result, doesn't mean the
878           // MCInst will. An MCExpr could be present, for example.
879           IAP.addCond(Op + ".isImm()");
880 
881           Cond = Op + ".getImm() == " +
882                  llvm::itostr(CGA.ResultOperands[i].getImm());
883           IAP.addCond(Cond);
884           break;
885         }
886         case CodeGenInstAlias::ResultOperand::K_Reg:
887           // If this is zero_reg, something's playing tricks we're not
888           // equipped to handle.
889           if (!CGA.ResultOperands[i].getRegister()) {
890             CantHandle = true;
891             break;
892           }
893 
894           Cond = Op + ".getReg() == " + Target.getName() + "::" +
895                  CGA.ResultOperands[i].getRegister()->getName();
896           IAP.addCond(Cond);
897           break;
898         }
899 
900         MIOpNum += RO.getMINumOperands();
901       }
902 
903       if (CantHandle) continue;
904 
905       for (auto I = ReqFeatures.cbegin(); I != ReqFeatures.cend(); I++) {
906         Record *R = *I;
907         std::string AsmCondString = R->getValueAsString("AssemblerCondString");
908 
909         // AsmCondString has syntax [!]F(,[!]F)*
910         SmallVector<StringRef, 4> Ops;
911         SplitString(AsmCondString, Ops, ",");
912         assert(!Ops.empty() && "AssemblerCondString cannot be empty");
913 
914         for (auto &Op : Ops) {
915           assert(!Op.empty() && "Empty operator");
916           if (Op[0] == '!')
917             Cond = "!STI.getFeatureBits()[" + Namespace + "::" +
918                    Op.substr(1).str() + "]";
919           else
920             Cond = "STI.getFeatureBits()[" + Namespace + "::" + Op.str() + "]";
921           IAP.addCond(Cond);
922         }
923       }
924 
925       IAPrinterMap[Aliases.first].push_back(std::move(IAP));
926     }
927   }
928 
929   //////////////////////////////
930   // Write out the printAliasInstr function
931   //////////////////////////////
932 
933   std::string Header;
934   raw_string_ostream HeaderO(Header);
935 
936   HeaderO << "bool " << Target.getName() << ClassName
937           << "::printAliasInstr(const MCInst"
938           << " *MI, " << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
939           << "raw_ostream &OS) {\n";
940 
941   std::string Cases;
942   raw_string_ostream CasesO(Cases);
943 
944   for (auto &Entry : IAPrinterMap) {
945     std::vector<IAPrinter> &IAPs = Entry.second;
946     std::vector<IAPrinter*> UniqueIAPs;
947 
948     for (auto &LHS : IAPs) {
949       bool IsDup = false;
950       for (const auto &RHS : IAPs) {
951         if (&LHS != &RHS && LHS == RHS) {
952           IsDup = true;
953           break;
954         }
955       }
956 
957       if (!IsDup)
958         UniqueIAPs.push_back(&LHS);
959     }
960 
961     if (UniqueIAPs.empty()) continue;
962 
963     CasesO.indent(2) << "case " << Entry.first << ":\n";
964 
965     for (IAPrinter *IAP : UniqueIAPs) {
966       CasesO.indent(4);
967       IAP->print(CasesO);
968       CasesO << '\n';
969     }
970 
971     CasesO.indent(4) << "return false;\n";
972   }
973 
974   if (CasesO.str().empty()) {
975     O << HeaderO.str();
976     O << "  return false;\n";
977     O << "}\n\n";
978     O << "#endif // PRINT_ALIAS_INSTR\n";
979     return;
980   }
981 
982   if (!MCOpPredicates.empty())
983     O << "static bool " << Target.getName() << ClassName
984       << "ValidateMCOperand(const MCOperand &MCOp,\n"
985       << "                  const MCSubtargetInfo &STI,\n"
986       << "                  unsigned PredicateIndex);\n";
987 
988   O << HeaderO.str();
989   O.indent(2) << "const char *AsmString;\n";
990   O.indent(2) << "switch (MI->getOpcode()) {\n";
991   O.indent(2) << "default: return false;\n";
992   O << CasesO.str();
993   O.indent(2) << "}\n\n";
994 
995   // Code that prints the alias, replacing the operands with the ones from the
996   // MCInst.
997   O << "  unsigned I = 0;\n";
998   O << "  while (AsmString[I] != ' ' && AsmString[I] != '\\t' &&\n";
999   O << "         AsmString[I] != '$' && AsmString[I] != '\\0')\n";
1000   O << "    ++I;\n";
1001   O << "  OS << '\\t' << StringRef(AsmString, I);\n";
1002 
1003   O << "  if (AsmString[I] != '\\0') {\n";
1004   O << "    if (AsmString[I] == ' ' || AsmString[I] == '\\t')";
1005   O << "      OS << '\\t';\n";
1006   O << "    do {\n";
1007   O << "      if (AsmString[I] == '$') {\n";
1008   O << "        ++I;\n";
1009   O << "        if (AsmString[I] == (char)0xff) {\n";
1010   O << "          ++I;\n";
1011   O << "          int OpIdx = AsmString[I++] - 1;\n";
1012   O << "          int PrintMethodIdx = AsmString[I++] - 1;\n";
1013   O << "          printCustomAliasOperand(MI, OpIdx, PrintMethodIdx, ";
1014   O << (PassSubtarget ? "STI, " : "");
1015   O << "OS);\n";
1016   O << "        } else\n";
1017   O << "          printOperand(MI, unsigned(AsmString[I++]) - 1, ";
1018   O << (PassSubtarget ? "STI, " : "");
1019   O << "OS);\n";
1020   O << "      } else {\n";
1021   O << "        OS << AsmString[I++];\n";
1022   O << "      }\n";
1023   O << "    } while (AsmString[I] != '\\0');\n";
1024   O << "  }\n\n";
1025 
1026   O << "  return true;\n";
1027   O << "}\n\n";
1028 
1029   //////////////////////////////
1030   // Write out the printCustomAliasOperand function
1031   //////////////////////////////
1032 
1033   O << "void " << Target.getName() << ClassName << "::"
1034     << "printCustomAliasOperand(\n"
1035     << "         const MCInst *MI, unsigned OpIdx,\n"
1036     << "         unsigned PrintMethodIdx,\n"
1037     << (PassSubtarget ? "         const MCSubtargetInfo &STI,\n" : "")
1038     << "         raw_ostream &OS) {\n";
1039   if (PrintMethods.empty())
1040     O << "  llvm_unreachable(\"Unknown PrintMethod kind\");\n";
1041   else {
1042     O << "  switch (PrintMethodIdx) {\n"
1043       << "  default:\n"
1044       << "    llvm_unreachable(\"Unknown PrintMethod kind\");\n"
1045       << "    break;\n";
1046 
1047     for (unsigned i = 0; i < PrintMethods.size(); ++i) {
1048       O << "  case " << i << ":\n"
1049         << "    " << PrintMethods[i] << "(MI, OpIdx, "
1050         << (PassSubtarget ? "STI, " : "") << "OS);\n"
1051         << "    break;\n";
1052     }
1053     O << "  }\n";
1054   }
1055   O << "}\n\n";
1056 
1057   if (!MCOpPredicates.empty()) {
1058     O << "static bool " << Target.getName() << ClassName
1059       << "ValidateMCOperand(const MCOperand &MCOp,\n"
1060       << "                  const MCSubtargetInfo &STI,\n"
1061       << "                  unsigned PredicateIndex) {\n"
1062       << "  switch (PredicateIndex) {\n"
1063       << "  default:\n"
1064       << "    llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n"
1065       << "    break;\n";
1066 
1067     for (unsigned i = 0; i < MCOpPredicates.size(); ++i) {
1068       Init *MCOpPred = MCOpPredicates[i]->getValueInit("MCOperandPredicate");
1069       if (CodeInit *SI = dyn_cast<CodeInit>(MCOpPred)) {
1070         O << "  case " << i + 1 << ": {\n"
1071           << SI->getValue() << "\n"
1072           << "    }\n";
1073       } else
1074         llvm_unreachable("Unexpected MCOperandPredicate field!");
1075     }
1076     O << "  }\n"
1077       << "}\n\n";
1078   }
1079 
1080   O << "#endif // PRINT_ALIAS_INSTR\n";
1081 }
1082 
1083 AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) {
1084   Record *AsmWriter = Target.getAsmWriter();
1085   unsigned Variant = AsmWriter->getValueAsInt("Variant");
1086 
1087   // Get the instruction numbering.
1088   NumberedInstructions = Target.getInstructionsByEnumValue();
1089 
1090   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
1091     const CodeGenInstruction *I = NumberedInstructions[i];
1092     if (!I->AsmString.empty() && I->TheDef->getName() != "PHI")
1093       Instructions.emplace_back(*I, i, Variant);
1094   }
1095 }
1096 
1097 void AsmWriterEmitter::run(raw_ostream &O) {
1098   EmitPrintInstruction(O);
1099   EmitGetRegisterName(O);
1100   EmitPrintAliasInstruction(O);
1101 }
1102 
1103 
1104 namespace llvm {
1105 
1106 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
1107   emitSourceFileHeader("Assembly Writer Source Fragment", OS);
1108   AsmWriterEmitter(RK).run(OS);
1109 }
1110 
1111 } // End llvm namespace
1112