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