RegisterInfoEmitter.cpp revision ebe69fe11e48d322045d5949c83283927a0d790b
1//===- RegisterInfoEmitter.cpp - Generate a Register File Desc. -*- C++ -*-===//
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 responsible for emitting a description of a target
11// register file for a code generator.  It uses instances of the Register,
12// RegisterAliases, and RegisterClass classes to gather this information.
13//
14//===----------------------------------------------------------------------===//
15
16#include "CodeGenRegisters.h"
17#include "CodeGenTarget.h"
18#include "SequenceToOffsetTable.h"
19#include "llvm/ADT/BitVector.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/ADT/Twine.h"
23#include "llvm/Support/Format.h"
24#include "llvm/TableGen/Error.h"
25#include "llvm/TableGen/Record.h"
26#include "llvm/TableGen/TableGenBackend.h"
27#include <algorithm>
28#include <set>
29#include <vector>
30using namespace llvm;
31
32namespace {
33class RegisterInfoEmitter {
34  RecordKeeper &Records;
35public:
36  RegisterInfoEmitter(RecordKeeper &R) : Records(R) {}
37
38  // runEnums - Print out enum values for all of the registers.
39  void runEnums(raw_ostream &o, CodeGenTarget &Target, CodeGenRegBank &Bank);
40
41  // runMCDesc - Print out MC register descriptions.
42  void runMCDesc(raw_ostream &o, CodeGenTarget &Target, CodeGenRegBank &Bank);
43
44  // runTargetHeader - Emit a header fragment for the register info emitter.
45  void runTargetHeader(raw_ostream &o, CodeGenTarget &Target,
46                       CodeGenRegBank &Bank);
47
48  // runTargetDesc - Output the target register and register file descriptions.
49  void runTargetDesc(raw_ostream &o, CodeGenTarget &Target,
50                     CodeGenRegBank &Bank);
51
52  // run - Output the register file description.
53  void run(raw_ostream &o);
54
55private:
56  void EmitRegMapping(raw_ostream &o, const std::deque<CodeGenRegister> &Regs,
57                      bool isCtor);
58  void EmitRegMappingTables(raw_ostream &o,
59                            const std::deque<CodeGenRegister> &Regs,
60                            bool isCtor);
61  void EmitRegUnitPressure(raw_ostream &OS, const CodeGenRegBank &RegBank,
62                           const std::string &ClassName);
63  void emitComposeSubRegIndices(raw_ostream &OS, CodeGenRegBank &RegBank,
64                                const std::string &ClassName);
65  void emitComposeSubRegIndexLaneMask(raw_ostream &OS, CodeGenRegBank &RegBank,
66                                      const std::string &ClassName);
67};
68} // End anonymous namespace
69
70// runEnums - Print out enum values for all of the registers.
71void RegisterInfoEmitter::runEnums(raw_ostream &OS,
72                                   CodeGenTarget &Target, CodeGenRegBank &Bank) {
73  const auto &Registers = Bank.getRegisters();
74
75  // Register enums are stored as uint16_t in the tables. Make sure we'll fit.
76  assert(Registers.size() <= 0xffff && "Too many regs to fit in tables");
77
78  std::string Namespace =
79      Registers.front().TheDef->getValueAsString("Namespace");
80
81  emitSourceFileHeader("Target Register Enum Values", OS);
82
83  OS << "\n#ifdef GET_REGINFO_ENUM\n";
84  OS << "#undef GET_REGINFO_ENUM\n";
85
86  OS << "namespace llvm {\n\n";
87
88  OS << "class MCRegisterClass;\n"
89     << "extern const MCRegisterClass " << Namespace
90     << "MCRegisterClasses[];\n\n";
91
92  if (!Namespace.empty())
93    OS << "namespace " << Namespace << " {\n";
94  OS << "enum {\n  NoRegister,\n";
95
96  for (const auto &Reg : Registers)
97    OS << "  " << Reg.getName() << " = " << Reg.EnumValue << ",\n";
98  assert(Registers.size() == Registers.back().EnumValue &&
99         "Register enum value mismatch!");
100  OS << "  NUM_TARGET_REGS \t// " << Registers.size()+1 << "\n";
101  OS << "};\n";
102  if (!Namespace.empty())
103    OS << "}\n";
104
105  const auto &RegisterClasses = Bank.getRegClasses();
106  if (!RegisterClasses.empty()) {
107
108    // RegisterClass enums are stored as uint16_t in the tables.
109    assert(RegisterClasses.size() <= 0xffff &&
110           "Too many register classes to fit in tables");
111
112    OS << "\n// Register classes\n";
113    if (!Namespace.empty())
114      OS << "namespace " << Namespace << " {\n";
115    OS << "enum {\n";
116    for (const auto &RC : RegisterClasses)
117      OS << "  " << RC.getName() << "RegClassID"
118         << " = " << RC.EnumValue << ",\n";
119    OS << "\n  };\n";
120    if (!Namespace.empty())
121      OS << "}\n";
122  }
123
124  const std::vector<Record*> &RegAltNameIndices = Target.getRegAltNameIndices();
125  // If the only definition is the default NoRegAltName, we don't need to
126  // emit anything.
127  if (RegAltNameIndices.size() > 1) {
128    OS << "\n// Register alternate name indices\n";
129    if (!Namespace.empty())
130      OS << "namespace " << Namespace << " {\n";
131    OS << "enum {\n";
132    for (unsigned i = 0, e = RegAltNameIndices.size(); i != e; ++i)
133      OS << "  " << RegAltNameIndices[i]->getName() << ",\t// " << i << "\n";
134    OS << "  NUM_TARGET_REG_ALT_NAMES = " << RegAltNameIndices.size() << "\n";
135    OS << "};\n";
136    if (!Namespace.empty())
137      OS << "}\n";
138  }
139
140  auto &SubRegIndices = Bank.getSubRegIndices();
141  if (!SubRegIndices.empty()) {
142    OS << "\n// Subregister indices\n";
143    std::string Namespace = SubRegIndices.front().getNamespace();
144    if (!Namespace.empty())
145      OS << "namespace " << Namespace << " {\n";
146    OS << "enum {\n  NoSubRegister,\n";
147    unsigned i = 0;
148    for (const auto &Idx : SubRegIndices)
149      OS << "  " << Idx.getName() << ",\t// " << ++i << "\n";
150    OS << "  NUM_TARGET_SUBREGS\n};\n";
151    if (!Namespace.empty())
152      OS << "}\n";
153  }
154
155  OS << "} // End llvm namespace\n";
156  OS << "#endif // GET_REGINFO_ENUM\n\n";
157}
158
159static void printInt(raw_ostream &OS, int Val) {
160  OS << Val;
161}
162
163static const char *getMinimalTypeForRange(uint64_t Range) {
164  assert(Range < 0xFFFFFFFFULL && "Enum too large");
165  if (Range > 0xFFFF)
166    return "uint32_t";
167  if (Range > 0xFF)
168    return "uint16_t";
169  return "uint8_t";
170}
171
172void RegisterInfoEmitter::
173EmitRegUnitPressure(raw_ostream &OS, const CodeGenRegBank &RegBank,
174                    const std::string &ClassName) {
175  unsigned NumRCs = RegBank.getRegClasses().size();
176  unsigned NumSets = RegBank.getNumRegPressureSets();
177
178  OS << "/// Get the weight in units of pressure for this register class.\n"
179     << "const RegClassWeight &" << ClassName << "::\n"
180     << "getRegClassWeight(const TargetRegisterClass *RC) const {\n"
181     << "  static const RegClassWeight RCWeightTable[] = {\n";
182  for (const auto &RC : RegBank.getRegClasses()) {
183    const CodeGenRegister::Vec &Regs = RC.getMembers();
184    if (Regs.empty())
185      OS << "    {0, 0";
186    else {
187      std::vector<unsigned> RegUnits;
188      RC.buildRegUnitSet(RegUnits);
189      OS << "    {" << (*Regs.begin())->getWeight(RegBank)
190         << ", " << RegBank.getRegUnitSetWeight(RegUnits);
191    }
192    OS << "},  \t// " << RC.getName() << "\n";
193  }
194  OS << "  };\n"
195     << "  return RCWeightTable[RC->getID()];\n"
196     << "}\n\n";
197
198  // Reasonable targets (not ARMv7) have unit weight for all units, so don't
199  // bother generating a table.
200  bool RegUnitsHaveUnitWeight = true;
201  for (unsigned UnitIdx = 0, UnitEnd = RegBank.getNumNativeRegUnits();
202       UnitIdx < UnitEnd; ++UnitIdx) {
203    if (RegBank.getRegUnit(UnitIdx).Weight > 1)
204      RegUnitsHaveUnitWeight = false;
205  }
206  OS << "/// Get the weight in units of pressure for this register unit.\n"
207     << "unsigned " << ClassName << "::\n"
208     << "getRegUnitWeight(unsigned RegUnit) const {\n"
209     << "  assert(RegUnit < " << RegBank.getNumNativeRegUnits()
210     << " && \"invalid register unit\");\n";
211  if (!RegUnitsHaveUnitWeight) {
212    OS << "  static const uint8_t RUWeightTable[] = {\n    ";
213    for (unsigned UnitIdx = 0, UnitEnd = RegBank.getNumNativeRegUnits();
214         UnitIdx < UnitEnd; ++UnitIdx) {
215      const RegUnit &RU = RegBank.getRegUnit(UnitIdx);
216      assert(RU.Weight < 256 && "RegUnit too heavy");
217      OS << RU.Weight << ", ";
218    }
219    OS << "};\n"
220       << "  return RUWeightTable[RegUnit];\n";
221  }
222  else {
223    OS << "  // All register units have unit weight.\n"
224       << "  return 1;\n";
225  }
226  OS << "}\n\n";
227
228  OS << "\n"
229     << "// Get the number of dimensions of register pressure.\n"
230     << "unsigned " << ClassName << "::getNumRegPressureSets() const {\n"
231     << "  return " << NumSets << ";\n}\n\n";
232
233  OS << "// Get the name of this register unit pressure set.\n"
234     << "const char *" << ClassName << "::\n"
235     << "getRegPressureSetName(unsigned Idx) const {\n"
236     << "  static const char *PressureNameTable[] = {\n";
237  unsigned MaxRegUnitWeight = 0;
238  for (unsigned i = 0; i < NumSets; ++i ) {
239    const RegUnitSet &RegUnits = RegBank.getRegSetAt(i);
240    MaxRegUnitWeight = std::max(MaxRegUnitWeight, RegUnits.Weight);
241    OS << "    \"" << RegUnits.Name << "\",\n";
242  }
243  OS << "    nullptr };\n"
244     << "  return PressureNameTable[Idx];\n"
245     << "}\n\n";
246
247  OS << "// Get the register unit pressure limit for this dimension.\n"
248     << "// This limit must be adjusted dynamically for reserved registers.\n"
249     << "unsigned " << ClassName << "::\n"
250     << "getRegPressureSetLimit(unsigned Idx) const {\n"
251     << "  static const " << getMinimalTypeForRange(MaxRegUnitWeight)
252     << " PressureLimitTable[] = {\n";
253  for (unsigned i = 0; i < NumSets; ++i ) {
254    const RegUnitSet &RegUnits = RegBank.getRegSetAt(i);
255    OS << "    " << RegUnits.Weight << ",  \t// " << i << ": "
256       << RegUnits.Name << "\n";
257  }
258  OS << "  };\n"
259     << "  return PressureLimitTable[Idx];\n"
260     << "}\n\n";
261
262  SequenceToOffsetTable<std::vector<int>> PSetsSeqs;
263
264  // This table may be larger than NumRCs if some register units needed a list
265  // of unit sets that did not correspond to a register class.
266  unsigned NumRCUnitSets = RegBank.getNumRegClassPressureSetLists();
267  std::vector<std::vector<int>> PSets(NumRCUnitSets);
268
269  for (unsigned i = 0, e = NumRCUnitSets; i != e; ++i) {
270    ArrayRef<unsigned> PSetIDs = RegBank.getRCPressureSetIDs(i);
271    PSets[i].reserve(PSetIDs.size());
272    for (ArrayRef<unsigned>::iterator PSetI = PSetIDs.begin(),
273           PSetE = PSetIDs.end(); PSetI != PSetE; ++PSetI) {
274      PSets[i].push_back(RegBank.getRegPressureSet(*PSetI).Order);
275    }
276    std::sort(PSets[i].begin(), PSets[i].end());
277    PSetsSeqs.add(PSets[i]);
278  }
279
280  PSetsSeqs.layout();
281
282  OS << "/// Table of pressure sets per register class or unit.\n"
283     << "static const int RCSetsTable[] = {\n";
284  PSetsSeqs.emit(OS, printInt, "-1");
285  OS << "};\n\n";
286
287  OS << "/// Get the dimensions of register pressure impacted by this "
288     << "register class.\n"
289     << "/// Returns a -1 terminated array of pressure set IDs\n"
290     << "const int* " << ClassName << "::\n"
291     << "getRegClassPressureSets(const TargetRegisterClass *RC) const {\n";
292  OS << "  static const " << getMinimalTypeForRange(PSetsSeqs.size()-1)
293     << " RCSetStartTable[] = {\n    ";
294  for (unsigned i = 0, e = NumRCs; i != e; ++i) {
295    OS << PSetsSeqs.get(PSets[i]) << ",";
296  }
297  OS << "};\n"
298     << "  return &RCSetsTable[RCSetStartTable[RC->getID()]];\n"
299     << "}\n\n";
300
301  OS << "/// Get the dimensions of register pressure impacted by this "
302     << "register unit.\n"
303     << "/// Returns a -1 terminated array of pressure set IDs\n"
304     << "const int* " << ClassName << "::\n"
305     << "getRegUnitPressureSets(unsigned RegUnit) const {\n"
306     << "  assert(RegUnit < " << RegBank.getNumNativeRegUnits()
307     << " && \"invalid register unit\");\n";
308  OS << "  static const " << getMinimalTypeForRange(PSetsSeqs.size()-1)
309     << " RUSetStartTable[] = {\n    ";
310  for (unsigned UnitIdx = 0, UnitEnd = RegBank.getNumNativeRegUnits();
311       UnitIdx < UnitEnd; ++UnitIdx) {
312    OS << PSetsSeqs.get(PSets[RegBank.getRegUnit(UnitIdx).RegClassUnitSetsIdx])
313       << ",";
314  }
315  OS << "};\n"
316     << "  return &RCSetsTable[RUSetStartTable[RegUnit]];\n"
317     << "}\n\n";
318}
319
320void RegisterInfoEmitter::EmitRegMappingTables(
321    raw_ostream &OS, const std::deque<CodeGenRegister> &Regs, bool isCtor) {
322  // Collect all information about dwarf register numbers
323  typedef std::map<Record*, std::vector<int64_t>, LessRecordRegister> DwarfRegNumsMapTy;
324  DwarfRegNumsMapTy DwarfRegNums;
325
326  // First, just pull all provided information to the map
327  unsigned maxLength = 0;
328  for (auto &RE : Regs) {
329    Record *Reg = RE.TheDef;
330    std::vector<int64_t> RegNums = Reg->getValueAsListOfInts("DwarfNumbers");
331    maxLength = std::max((size_t)maxLength, RegNums.size());
332    if (DwarfRegNums.count(Reg))
333      PrintWarning(Reg->getLoc(), Twine("DWARF numbers for register ") +
334                   getQualifiedName(Reg) + "specified multiple times");
335    DwarfRegNums[Reg] = RegNums;
336  }
337
338  if (!maxLength)
339    return;
340
341  // Now we know maximal length of number list. Append -1's, where needed
342  for (DwarfRegNumsMapTy::iterator
343       I = DwarfRegNums.begin(), E = DwarfRegNums.end(); I != E; ++I)
344    for (unsigned i = I->second.size(), e = maxLength; i != e; ++i)
345      I->second.push_back(-1);
346
347  std::string Namespace = Regs.front().TheDef->getValueAsString("Namespace");
348
349  OS << "// " << Namespace << " Dwarf<->LLVM register mappings.\n";
350
351  // Emit reverse information about the dwarf register numbers.
352  for (unsigned j = 0; j < 2; ++j) {
353    for (unsigned i = 0, e = maxLength; i != e; ++i) {
354      OS << "extern const MCRegisterInfo::DwarfLLVMRegPair " << Namespace;
355      OS << (j == 0 ? "DwarfFlavour" : "EHFlavour");
356      OS << i << "Dwarf2L[]";
357
358      if (!isCtor) {
359        OS << " = {\n";
360
361        // Store the mapping sorted by the LLVM reg num so lookup can be done
362        // with a binary search.
363        std::map<uint64_t, Record*> Dwarf2LMap;
364        for (DwarfRegNumsMapTy::iterator
365               I = DwarfRegNums.begin(), E = DwarfRegNums.end(); I != E; ++I) {
366          int DwarfRegNo = I->second[i];
367          if (DwarfRegNo < 0)
368            continue;
369          Dwarf2LMap[DwarfRegNo] = I->first;
370        }
371
372        for (std::map<uint64_t, Record*>::iterator
373               I = Dwarf2LMap.begin(), E = Dwarf2LMap.end(); I != E; ++I)
374          OS << "  { " << I->first << "U, " << getQualifiedName(I->second)
375             << " },\n";
376
377        OS << "};\n";
378      } else {
379        OS << ";\n";
380      }
381
382      // We have to store the size in a const global, it's used in multiple
383      // places.
384      OS << "extern const unsigned " << Namespace
385         << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i << "Dwarf2LSize";
386      if (!isCtor)
387        OS << " = array_lengthof(" << Namespace
388           << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i
389           << "Dwarf2L);\n\n";
390      else
391        OS << ";\n\n";
392    }
393  }
394
395  for (auto &RE : Regs) {
396    Record *Reg = RE.TheDef;
397    const RecordVal *V = Reg->getValue("DwarfAlias");
398    if (!V || !V->getValue())
399      continue;
400
401    DefInit *DI = cast<DefInit>(V->getValue());
402    Record *Alias = DI->getDef();
403    DwarfRegNums[Reg] = DwarfRegNums[Alias];
404  }
405
406  // Emit information about the dwarf register numbers.
407  for (unsigned j = 0; j < 2; ++j) {
408    for (unsigned i = 0, e = maxLength; i != e; ++i) {
409      OS << "extern const MCRegisterInfo::DwarfLLVMRegPair " << Namespace;
410      OS << (j == 0 ? "DwarfFlavour" : "EHFlavour");
411      OS << i << "L2Dwarf[]";
412      if (!isCtor) {
413        OS << " = {\n";
414        // Store the mapping sorted by the Dwarf reg num so lookup can be done
415        // with a binary search.
416        for (DwarfRegNumsMapTy::iterator
417               I = DwarfRegNums.begin(), E = DwarfRegNums.end(); I != E; ++I) {
418          int RegNo = I->second[i];
419          if (RegNo == -1) // -1 is the default value, don't emit a mapping.
420            continue;
421
422          OS << "  { " << getQualifiedName(I->first) << ", " << RegNo
423             << "U },\n";
424        }
425        OS << "};\n";
426      } else {
427        OS << ";\n";
428      }
429
430      // We have to store the size in a const global, it's used in multiple
431      // places.
432      OS << "extern const unsigned " << Namespace
433         << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i << "L2DwarfSize";
434      if (!isCtor)
435        OS << " = array_lengthof(" << Namespace
436           << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i << "L2Dwarf);\n\n";
437      else
438        OS << ";\n\n";
439    }
440  }
441}
442
443void RegisterInfoEmitter::EmitRegMapping(
444    raw_ostream &OS, const std::deque<CodeGenRegister> &Regs, bool isCtor) {
445  // Emit the initializer so the tables from EmitRegMappingTables get wired up
446  // to the MCRegisterInfo object.
447  unsigned maxLength = 0;
448  for (auto &RE : Regs) {
449    Record *Reg = RE.TheDef;
450    maxLength = std::max((size_t)maxLength,
451                         Reg->getValueAsListOfInts("DwarfNumbers").size());
452  }
453
454  if (!maxLength)
455    return;
456
457  std::string Namespace = Regs.front().TheDef->getValueAsString("Namespace");
458
459  // Emit reverse information about the dwarf register numbers.
460  for (unsigned j = 0; j < 2; ++j) {
461    OS << "  switch (";
462    if (j == 0)
463      OS << "DwarfFlavour";
464    else
465      OS << "EHFlavour";
466    OS << ") {\n"
467     << "  default:\n"
468     << "    llvm_unreachable(\"Unknown DWARF flavour\");\n";
469
470    for (unsigned i = 0, e = maxLength; i != e; ++i) {
471      OS << "  case " << i << ":\n";
472      OS << "    ";
473      if (!isCtor)
474        OS << "RI->";
475      std::string Tmp;
476      raw_string_ostream(Tmp) << Namespace
477                              << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i
478                              << "Dwarf2L";
479      OS << "mapDwarfRegsToLLVMRegs(" << Tmp << ", " << Tmp << "Size, ";
480      if (j == 0)
481          OS << "false";
482        else
483          OS << "true";
484      OS << ");\n";
485      OS << "    break;\n";
486    }
487    OS << "  }\n";
488  }
489
490  // Emit information about the dwarf register numbers.
491  for (unsigned j = 0; j < 2; ++j) {
492    OS << "  switch (";
493    if (j == 0)
494      OS << "DwarfFlavour";
495    else
496      OS << "EHFlavour";
497    OS << ") {\n"
498       << "  default:\n"
499       << "    llvm_unreachable(\"Unknown DWARF flavour\");\n";
500
501    for (unsigned i = 0, e = maxLength; i != e; ++i) {
502      OS << "  case " << i << ":\n";
503      OS << "    ";
504      if (!isCtor)
505        OS << "RI->";
506      std::string Tmp;
507      raw_string_ostream(Tmp) << Namespace
508                              << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i
509                              << "L2Dwarf";
510      OS << "mapLLVMRegsToDwarfRegs(" << Tmp << ", " << Tmp << "Size, ";
511      if (j == 0)
512          OS << "false";
513        else
514          OS << "true";
515      OS << ");\n";
516      OS << "    break;\n";
517    }
518    OS << "  }\n";
519  }
520}
521
522// Print a BitVector as a sequence of hex numbers using a little-endian mapping.
523// Width is the number of bits per hex number.
524static void printBitVectorAsHex(raw_ostream &OS,
525                                const BitVector &Bits,
526                                unsigned Width) {
527  assert(Width <= 32 && "Width too large");
528  unsigned Digits = (Width + 3) / 4;
529  for (unsigned i = 0, e = Bits.size(); i < e; i += Width) {
530    unsigned Value = 0;
531    for (unsigned j = 0; j != Width && i + j != e; ++j)
532      Value |= Bits.test(i + j) << j;
533    OS << format("0x%0*x, ", Digits, Value);
534  }
535}
536
537// Helper to emit a set of bits into a constant byte array.
538class BitVectorEmitter {
539  BitVector Values;
540public:
541  void add(unsigned v) {
542    if (v >= Values.size())
543      Values.resize(((v/8)+1)*8); // Round up to the next byte.
544    Values[v] = true;
545  }
546
547  void print(raw_ostream &OS) {
548    printBitVectorAsHex(OS, Values, 8);
549  }
550};
551
552static void printSimpleValueType(raw_ostream &OS, MVT::SimpleValueType VT) {
553  OS << getEnumName(VT);
554}
555
556static void printSubRegIndex(raw_ostream &OS, const CodeGenSubRegIndex *Idx) {
557  OS << Idx->EnumValue;
558}
559
560// Differentially encoded register and regunit lists allow for better
561// compression on regular register banks. The sequence is computed from the
562// differential list as:
563//
564//   out[0] = InitVal;
565//   out[n+1] = out[n] + diff[n]; // n = 0, 1, ...
566//
567// The initial value depends on the specific list. The list is terminated by a
568// 0 differential which means we can't encode repeated elements.
569
570typedef SmallVector<uint16_t, 4> DiffVec;
571typedef SmallVector<unsigned, 4> MaskVec;
572
573// Differentially encode a sequence of numbers into V. The starting value and
574// terminating 0 are not added to V, so it will have the same size as List.
575static
576DiffVec &diffEncode(DiffVec &V, unsigned InitVal, SparseBitVector<> List) {
577  assert(V.empty() && "Clear DiffVec before diffEncode.");
578  uint16_t Val = uint16_t(InitVal);
579
580  for (uint16_t Cur : List) {
581    V.push_back(Cur - Val);
582    Val = Cur;
583  }
584  return V;
585}
586
587template<typename Iter>
588static
589DiffVec &diffEncode(DiffVec &V, unsigned InitVal, Iter Begin, Iter End) {
590  assert(V.empty() && "Clear DiffVec before diffEncode.");
591  uint16_t Val = uint16_t(InitVal);
592  for (Iter I = Begin; I != End; ++I) {
593    uint16_t Cur = (*I)->EnumValue;
594    V.push_back(Cur - Val);
595    Val = Cur;
596  }
597  return V;
598}
599
600static void printDiff16(raw_ostream &OS, uint16_t Val) {
601  OS << Val;
602}
603
604static void printMask(raw_ostream &OS, unsigned Val) {
605  OS << format("0x%08X", Val);
606}
607
608// Try to combine Idx's compose map into Vec if it is compatible.
609// Return false if it's not possible.
610static bool combine(const CodeGenSubRegIndex *Idx,
611                    SmallVectorImpl<CodeGenSubRegIndex*> &Vec) {
612  const CodeGenSubRegIndex::CompMap &Map = Idx->getComposites();
613  for (CodeGenSubRegIndex::CompMap::const_iterator
614       I = Map.begin(), E = Map.end(); I != E; ++I) {
615    CodeGenSubRegIndex *&Entry = Vec[I->first->EnumValue - 1];
616    if (Entry && Entry != I->second)
617      return false;
618  }
619
620  // All entries are compatible. Make it so.
621  for (CodeGenSubRegIndex::CompMap::const_iterator
622       I = Map.begin(), E = Map.end(); I != E; ++I)
623    Vec[I->first->EnumValue - 1] = I->second;
624  return true;
625}
626
627void
628RegisterInfoEmitter::emitComposeSubRegIndices(raw_ostream &OS,
629                                              CodeGenRegBank &RegBank,
630                                              const std::string &ClName) {
631  const auto &SubRegIndices = RegBank.getSubRegIndices();
632  OS << "unsigned " << ClName
633     << "::composeSubRegIndicesImpl(unsigned IdxA, unsigned IdxB) const {\n";
634
635  // Many sub-register indexes are composition-compatible, meaning that
636  //
637  //   compose(IdxA, IdxB) == compose(IdxA', IdxB)
638  //
639  // for many IdxA, IdxA' pairs. Not all sub-register indexes can be composed.
640  // The illegal entries can be use as wildcards to compress the table further.
641
642  // Map each Sub-register index to a compatible table row.
643  SmallVector<unsigned, 4> RowMap;
644  SmallVector<SmallVector<CodeGenSubRegIndex*, 4>, 4> Rows;
645
646  auto SubRegIndicesSize =
647      std::distance(SubRegIndices.begin(), SubRegIndices.end());
648  for (const auto &Idx : SubRegIndices) {
649    unsigned Found = ~0u;
650    for (unsigned r = 0, re = Rows.size(); r != re; ++r) {
651      if (combine(&Idx, Rows[r])) {
652        Found = r;
653        break;
654      }
655    }
656    if (Found == ~0u) {
657      Found = Rows.size();
658      Rows.resize(Found + 1);
659      Rows.back().resize(SubRegIndicesSize);
660      combine(&Idx, Rows.back());
661    }
662    RowMap.push_back(Found);
663  }
664
665  // Output the row map if there is multiple rows.
666  if (Rows.size() > 1) {
667    OS << "  static const " << getMinimalTypeForRange(Rows.size()) << " RowMap["
668       << SubRegIndicesSize << "] = {\n    ";
669    for (unsigned i = 0, e = SubRegIndicesSize; i != e; ++i)
670      OS << RowMap[i] << ", ";
671    OS << "\n  };\n";
672  }
673
674  // Output the rows.
675  OS << "  static const " << getMinimalTypeForRange(SubRegIndicesSize + 1)
676     << " Rows[" << Rows.size() << "][" << SubRegIndicesSize << "] = {\n";
677  for (unsigned r = 0, re = Rows.size(); r != re; ++r) {
678    OS << "    { ";
679    for (unsigned i = 0, e = SubRegIndicesSize; i != e; ++i)
680      if (Rows[r][i])
681        OS << Rows[r][i]->EnumValue << ", ";
682      else
683        OS << "0, ";
684    OS << "},\n";
685  }
686  OS << "  };\n\n";
687
688  OS << "  --IdxA; assert(IdxA < " << SubRegIndicesSize << ");\n"
689     << "  --IdxB; assert(IdxB < " << SubRegIndicesSize << ");\n";
690  if (Rows.size() > 1)
691    OS << "  return Rows[RowMap[IdxA]][IdxB];\n";
692  else
693    OS << "  return Rows[0][IdxB];\n";
694  OS << "}\n\n";
695}
696
697void
698RegisterInfoEmitter::emitComposeSubRegIndexLaneMask(raw_ostream &OS,
699                                                    CodeGenRegBank &RegBank,
700                                                    const std::string &ClName) {
701  // See the comments in computeSubRegLaneMasks() for our goal here.
702  const auto &SubRegIndices = RegBank.getSubRegIndices();
703
704  // Create a list of Mask+Rotate operations, with equivalent entries merged.
705  SmallVector<unsigned, 4> SubReg2SequenceIndexMap;
706  SmallVector<SmallVector<MaskRolPair, 1>, 4> Sequences;
707  for (const auto &Idx : SubRegIndices) {
708    const SmallVector<MaskRolPair, 1> &IdxSequence
709      = Idx.CompositionLaneMaskTransform;
710
711    unsigned Found = ~0u;
712    unsigned SIdx = 0;
713    unsigned NextSIdx;
714    for (size_t s = 0, se = Sequences.size(); s != se; ++s, SIdx = NextSIdx) {
715      SmallVectorImpl<MaskRolPair> &Sequence = Sequences[s];
716      NextSIdx = SIdx + Sequence.size() + 1;
717      if (Sequence.size() != IdxSequence.size())
718        continue;
719      bool Identical = true;
720      for (size_t o = 0, oe = Sequence.size(); o != oe; ++o) {
721        if (Sequence[o] != IdxSequence[o]) {
722          Identical = false;
723          break;
724        }
725      }
726      if (Identical) {
727        Found = SIdx;
728        break;
729      }
730    }
731    if (Found == ~0u) {
732      Sequences.push_back(IdxSequence);
733      Found = SIdx;
734    }
735    SubReg2SequenceIndexMap.push_back(Found);
736  }
737
738  OS << "unsigned " << ClName
739     << "::composeSubRegIndexLaneMaskImpl(unsigned IdxA, unsigned LaneMask)"
740        " const {\n";
741
742  OS << "  struct MaskRolOp {\n"
743        "    unsigned Mask;\n"
744        "    uint8_t  RotateLeft;\n"
745        "  };\n"
746        "  static const MaskRolOp Seqs[] = {\n";
747  unsigned Idx = 0;
748  for (size_t s = 0, se = Sequences.size(); s != se; ++s) {
749    OS << "    ";
750    const SmallVectorImpl<MaskRolPair> &Sequence = Sequences[s];
751    for (size_t p = 0, pe = Sequence.size(); p != pe; ++p) {
752      const MaskRolPair &P = Sequence[p];
753      OS << format("{ 0x%08X, %2u }, ", P.Mask, P.RotateLeft);
754    }
755    OS << "{ 0, 0 }";
756    if (s+1 != se)
757      OS << ", ";
758    OS << "  // Sequence " << Idx << "\n";
759    Idx += Sequence.size() + 1;
760  }
761  OS << "  };\n"
762        "  static const MaskRolOp *CompositeSequences[] = {\n";
763  for (size_t i = 0, e = SubRegIndices.size(); i != e; ++i) {
764    OS << "    ";
765    unsigned Idx = SubReg2SequenceIndexMap[i];
766    OS << format("&Seqs[%u]", Idx);
767    if (i+1 != e)
768      OS << ",";
769    OS << " // to " << SubRegIndices[i].getName() << "\n";
770  }
771  OS << "  };\n\n";
772
773  OS << "  --IdxA; assert(IdxA < " << SubRegIndices.size()
774     << " && \"Subregister index out of bounds\");\n"
775        "  unsigned Result = 0;\n"
776        "  for (const MaskRolOp *Ops = CompositeSequences[IdxA]; Ops->Mask != 0; ++Ops)"
777        " {\n"
778        "    unsigned Masked = LaneMask & Ops->Mask;\n"
779        "    Result |= (Masked << Ops->RotateLeft) & 0xFFFFFFFF;\n"
780        "    Result |= (Masked >> ((32 - Ops->RotateLeft) & 0x1F));\n"
781        "  }\n"
782        "  return Result;\n"
783        "}\n";
784}
785
786//
787// runMCDesc - Print out MC register descriptions.
788//
789void
790RegisterInfoEmitter::runMCDesc(raw_ostream &OS, CodeGenTarget &Target,
791                               CodeGenRegBank &RegBank) {
792  emitSourceFileHeader("MC Register Information", OS);
793
794  OS << "\n#ifdef GET_REGINFO_MC_DESC\n";
795  OS << "#undef GET_REGINFO_MC_DESC\n";
796
797  const auto &Regs = RegBank.getRegisters();
798
799  auto &SubRegIndices = RegBank.getSubRegIndices();
800  // The lists of sub-registers and super-registers go in the same array.  That
801  // allows us to share suffixes.
802  typedef std::vector<const CodeGenRegister*> RegVec;
803
804  // Differentially encoded lists.
805  SequenceToOffsetTable<DiffVec> DiffSeqs;
806  SmallVector<DiffVec, 4> SubRegLists(Regs.size());
807  SmallVector<DiffVec, 4> SuperRegLists(Regs.size());
808  SmallVector<DiffVec, 4> RegUnitLists(Regs.size());
809  SmallVector<unsigned, 4> RegUnitInitScale(Regs.size());
810
811  // List of lane masks accompanying register unit sequences.
812  SequenceToOffsetTable<MaskVec> LaneMaskSeqs;
813  SmallVector<MaskVec, 4> RegUnitLaneMasks(Regs.size());
814
815  // Keep track of sub-register names as well. These are not differentially
816  // encoded.
817  typedef SmallVector<const CodeGenSubRegIndex*, 4> SubRegIdxVec;
818  SequenceToOffsetTable<SubRegIdxVec, deref<llvm::less>> SubRegIdxSeqs;
819  SmallVector<SubRegIdxVec, 4> SubRegIdxLists(Regs.size());
820
821  SequenceToOffsetTable<std::string> RegStrings;
822
823  // Precompute register lists for the SequenceToOffsetTable.
824  unsigned i = 0;
825  for (auto I = Regs.begin(), E = Regs.end(); I != E; ++I, ++i) {
826    const auto &Reg = *I;
827    RegStrings.add(Reg.getName());
828
829    // Compute the ordered sub-register list.
830    SetVector<const CodeGenRegister*> SR;
831    Reg.addSubRegsPreOrder(SR, RegBank);
832    diffEncode(SubRegLists[i], Reg.EnumValue, SR.begin(), SR.end());
833    DiffSeqs.add(SubRegLists[i]);
834
835    // Compute the corresponding sub-register indexes.
836    SubRegIdxVec &SRIs = SubRegIdxLists[i];
837    for (unsigned j = 0, je = SR.size(); j != je; ++j)
838      SRIs.push_back(Reg.getSubRegIndex(SR[j]));
839    SubRegIdxSeqs.add(SRIs);
840
841    // Super-registers are already computed.
842    const RegVec &SuperRegList = Reg.getSuperRegs();
843    diffEncode(SuperRegLists[i], Reg.EnumValue, SuperRegList.begin(),
844               SuperRegList.end());
845    DiffSeqs.add(SuperRegLists[i]);
846
847    // Differentially encode the register unit list, seeded by register number.
848    // First compute a scale factor that allows more diff-lists to be reused:
849    //
850    //   D0 -> (S0, S1)
851    //   D1 -> (S2, S3)
852    //
853    // A scale factor of 2 allows D0 and D1 to share a diff-list. The initial
854    // value for the differential decoder is the register number multiplied by
855    // the scale.
856    //
857    // Check the neighboring registers for arithmetic progressions.
858    unsigned ScaleA = ~0u, ScaleB = ~0u;
859    SparseBitVector<> RUs = Reg.getNativeRegUnits();
860    if (I != Regs.begin() &&
861        std::prev(I)->getNativeRegUnits().count() == RUs.count())
862      ScaleB = *RUs.begin() - *std::prev(I)->getNativeRegUnits().begin();
863    if (std::next(I) != Regs.end() &&
864        std::next(I)->getNativeRegUnits().count() == RUs.count())
865      ScaleA = *std::next(I)->getNativeRegUnits().begin() - *RUs.begin();
866    unsigned Scale = std::min(ScaleB, ScaleA);
867    // Default the scale to 0 if it can't be encoded in 4 bits.
868    if (Scale >= 16)
869      Scale = 0;
870    RegUnitInitScale[i] = Scale;
871    DiffSeqs.add(diffEncode(RegUnitLists[i], Scale * Reg.EnumValue, RUs));
872
873    const auto &RUMasks = Reg.getRegUnitLaneMasks();
874    MaskVec &LaneMaskVec = RegUnitLaneMasks[i];
875    assert(LaneMaskVec.empty());
876    LaneMaskVec.insert(LaneMaskVec.begin(), RUMasks.begin(), RUMasks.end());
877    // Terminator mask should not be used inside of the list.
878#ifndef NDEBUG
879    for (unsigned M : LaneMaskVec) {
880      assert(M != ~0u && "terminator mask should not be part of the list");
881    }
882#endif
883    LaneMaskSeqs.add(LaneMaskVec);
884  }
885
886  // Compute the final layout of the sequence table.
887  DiffSeqs.layout();
888  LaneMaskSeqs.layout();
889  SubRegIdxSeqs.layout();
890
891  OS << "namespace llvm {\n\n";
892
893  const std::string &TargetName = Target.getName();
894
895  // Emit the shared table of differential lists.
896  OS << "extern const MCPhysReg " << TargetName << "RegDiffLists[] = {\n";
897  DiffSeqs.emit(OS, printDiff16);
898  OS << "};\n\n";
899
900  // Emit the shared table of regunit lane mask sequences.
901  OS << "extern const unsigned " << TargetName << "LaneMaskLists[] = {\n";
902  LaneMaskSeqs.emit(OS, printMask, "~0u");
903  OS << "};\n\n";
904
905  // Emit the table of sub-register indexes.
906  OS << "extern const uint16_t " << TargetName << "SubRegIdxLists[] = {\n";
907  SubRegIdxSeqs.emit(OS, printSubRegIndex);
908  OS << "};\n\n";
909
910  // Emit the table of sub-register index sizes.
911  OS << "extern const MCRegisterInfo::SubRegCoveredBits "
912     << TargetName << "SubRegIdxRanges[] = {\n";
913  OS << "  { " << (uint16_t)-1 << ", " << (uint16_t)-1 << " },\n";
914  for (const auto &Idx : SubRegIndices) {
915    OS << "  { " << Idx.Offset << ", " << Idx.Size << " },\t// "
916       << Idx.getName() << "\n";
917  }
918  OS << "};\n\n";
919
920  // Emit the string table.
921  RegStrings.layout();
922  OS << "extern const char " << TargetName << "RegStrings[] = {\n";
923  RegStrings.emit(OS, printChar);
924  OS << "};\n\n";
925
926  OS << "extern const MCRegisterDesc " << TargetName
927     << "RegDesc[] = { // Descriptors\n";
928  OS << "  { " << RegStrings.get("") << ", 0, 0, 0, 0, 0 },\n";
929
930  // Emit the register descriptors now.
931  i = 0;
932  for (const auto &Reg : Regs) {
933    OS << "  { " << RegStrings.get(Reg.getName()) << ", "
934       << DiffSeqs.get(SubRegLists[i]) << ", " << DiffSeqs.get(SuperRegLists[i])
935       << ", " << SubRegIdxSeqs.get(SubRegIdxLists[i]) << ", "
936       << (DiffSeqs.get(RegUnitLists[i]) * 16 + RegUnitInitScale[i]) << ", "
937       << LaneMaskSeqs.get(RegUnitLaneMasks[i]) << " },\n";
938    ++i;
939  }
940  OS << "};\n\n";      // End of register descriptors...
941
942  // Emit the table of register unit roots. Each regunit has one or two root
943  // registers.
944  OS << "extern const MCPhysReg " << TargetName << "RegUnitRoots[][2] = {\n";
945  for (unsigned i = 0, e = RegBank.getNumNativeRegUnits(); i != e; ++i) {
946    ArrayRef<const CodeGenRegister*> Roots = RegBank.getRegUnit(i).getRoots();
947    assert(!Roots.empty() && "All regunits must have a root register.");
948    assert(Roots.size() <= 2 && "More than two roots not supported yet.");
949    OS << "  { " << getQualifiedName(Roots.front()->TheDef);
950    for (unsigned r = 1; r != Roots.size(); ++r)
951      OS << ", " << getQualifiedName(Roots[r]->TheDef);
952    OS << " },\n";
953  }
954  OS << "};\n\n";
955
956  const auto &RegisterClasses = RegBank.getRegClasses();
957
958  // Loop over all of the register classes... emitting each one.
959  OS << "namespace {     // Register classes...\n";
960
961  SequenceToOffsetTable<std::string> RegClassStrings;
962
963  // Emit the register enum value arrays for each RegisterClass
964  for (const auto &RC : RegisterClasses) {
965    ArrayRef<Record*> Order = RC.getOrder();
966
967    // Give the register class a legal C name if it's anonymous.
968    std::string Name = RC.getName();
969
970    RegClassStrings.add(Name);
971
972    // Emit the register list now.
973    OS << "  // " << Name << " Register Class...\n"
974       << "  const MCPhysReg " << Name
975       << "[] = {\n    ";
976    for (unsigned i = 0, e = Order.size(); i != e; ++i) {
977      Record *Reg = Order[i];
978      OS << getQualifiedName(Reg) << ", ";
979    }
980    OS << "\n  };\n\n";
981
982    OS << "  // " << Name << " Bit set.\n"
983       << "  const uint8_t " << Name
984       << "Bits[] = {\n    ";
985    BitVectorEmitter BVE;
986    for (unsigned i = 0, e = Order.size(); i != e; ++i) {
987      Record *Reg = Order[i];
988      BVE.add(Target.getRegBank().getReg(Reg)->EnumValue);
989    }
990    BVE.print(OS);
991    OS << "\n  };\n\n";
992
993  }
994  OS << "}\n\n";
995
996  RegClassStrings.layout();
997  OS << "extern const char " << TargetName << "RegClassStrings[] = {\n";
998  RegClassStrings.emit(OS, printChar);
999  OS << "};\n\n";
1000
1001  OS << "extern const MCRegisterClass " << TargetName
1002     << "MCRegisterClasses[] = {\n";
1003
1004  for (const auto &RC : RegisterClasses) {
1005    // Asserts to make sure values will fit in table assuming types from
1006    // MCRegisterInfo.h
1007    assert((RC.SpillSize/8) <= 0xffff && "SpillSize too large.");
1008    assert((RC.SpillAlignment/8) <= 0xffff && "SpillAlignment too large.");
1009    assert(RC.CopyCost >= -128 && RC.CopyCost <= 127 && "Copy cost too large.");
1010
1011    OS << "  { " << RC.getName() << ", " << RC.getName() << "Bits, "
1012       << RegClassStrings.get(RC.getName()) << ", "
1013       << RC.getOrder().size() << ", sizeof(" << RC.getName() << "Bits), "
1014       << RC.getQualifiedName() + "RegClassID" << ", "
1015       << RC.SpillSize/8 << ", "
1016       << RC.SpillAlignment/8 << ", "
1017       << RC.CopyCost << ", "
1018       << RC.Allocatable << " },\n";
1019  }
1020
1021  OS << "};\n\n";
1022
1023  EmitRegMappingTables(OS, Regs, false);
1024
1025  // Emit Reg encoding table
1026  OS << "extern const uint16_t " << TargetName;
1027  OS << "RegEncodingTable[] = {\n";
1028  // Add entry for NoRegister
1029  OS << "  0,\n";
1030  for (const auto &RE : Regs) {
1031    Record *Reg = RE.TheDef;
1032    BitsInit *BI = Reg->getValueAsBitsInit("HWEncoding");
1033    uint64_t Value = 0;
1034    for (unsigned b = 0, be = BI->getNumBits(); b != be; ++b) {
1035      if (BitInit *B = dyn_cast<BitInit>(BI->getBit(b)))
1036        Value |= (uint64_t)B->getValue() << b;
1037    }
1038    OS << "  " << Value << ",\n";
1039  }
1040  OS << "};\n";       // End of HW encoding table
1041
1042  // MCRegisterInfo initialization routine.
1043  OS << "static inline void Init" << TargetName
1044     << "MCRegisterInfo(MCRegisterInfo *RI, unsigned RA, "
1045     << "unsigned DwarfFlavour = 0, unsigned EHFlavour = 0, unsigned PC = 0) "
1046        "{\n"
1047     << "  RI->InitMCRegisterInfo(" << TargetName << "RegDesc, "
1048     << Regs.size() + 1 << ", RA, PC, " << TargetName << "MCRegisterClasses, "
1049     << RegisterClasses.size() << ", " << TargetName << "RegUnitRoots, "
1050     << RegBank.getNumNativeRegUnits() << ", " << TargetName << "RegDiffLists, "
1051     << TargetName << "LaneMaskLists, " << TargetName << "RegStrings, "
1052     << TargetName << "RegClassStrings, " << TargetName << "SubRegIdxLists, "
1053     << (std::distance(SubRegIndices.begin(), SubRegIndices.end()) + 1) << ",\n"
1054     << TargetName << "SubRegIdxRanges, " << TargetName
1055     << "RegEncodingTable);\n\n";
1056
1057  EmitRegMapping(OS, Regs, false);
1058
1059  OS << "}\n\n";
1060
1061  OS << "} // End llvm namespace\n";
1062  OS << "#endif // GET_REGINFO_MC_DESC\n\n";
1063}
1064
1065void
1066RegisterInfoEmitter::runTargetHeader(raw_ostream &OS, CodeGenTarget &Target,
1067                                     CodeGenRegBank &RegBank) {
1068  emitSourceFileHeader("Register Information Header Fragment", OS);
1069
1070  OS << "\n#ifdef GET_REGINFO_HEADER\n";
1071  OS << "#undef GET_REGINFO_HEADER\n";
1072
1073  const std::string &TargetName = Target.getName();
1074  std::string ClassName = TargetName + "GenRegisterInfo";
1075
1076  OS << "#include \"llvm/Target/TargetRegisterInfo.h\"\n\n";
1077
1078  OS << "namespace llvm {\n\n";
1079
1080  OS << "struct " << ClassName << " : public TargetRegisterInfo {\n"
1081     << "  explicit " << ClassName
1082     << "(unsigned RA, unsigned D = 0, unsigned E = 0, unsigned PC = 0);\n"
1083     << "  bool needsStackRealignment(const MachineFunction &) const override\n"
1084     << "     { return false; }\n";
1085  if (!RegBank.getSubRegIndices().empty()) {
1086    OS << "  unsigned composeSubRegIndicesImpl"
1087       << "(unsigned, unsigned) const override;\n"
1088       << "  unsigned composeSubRegIndexLaneMaskImpl"
1089       << "(unsigned, unsigned) const override;\n"
1090       << "  const TargetRegisterClass *getSubClassWithSubReg"
1091       << "(const TargetRegisterClass*, unsigned) const override;\n";
1092  }
1093  OS << "  const RegClassWeight &getRegClassWeight("
1094     << "const TargetRegisterClass *RC) const override;\n"
1095     << "  unsigned getRegUnitWeight(unsigned RegUnit) const override;\n"
1096     << "  unsigned getNumRegPressureSets() const override;\n"
1097     << "  const char *getRegPressureSetName(unsigned Idx) const override;\n"
1098     << "  unsigned getRegPressureSetLimit(unsigned Idx) const override;\n"
1099     << "  const int *getRegClassPressureSets("
1100     << "const TargetRegisterClass *RC) const override;\n"
1101     << "  const int *getRegUnitPressureSets("
1102     << "unsigned RegUnit) const override;\n"
1103     << "};\n\n";
1104
1105  const auto &RegisterClasses = RegBank.getRegClasses();
1106
1107  if (!RegisterClasses.empty()) {
1108    OS << "namespace " << RegisterClasses.front().Namespace
1109       << " { // Register classes\n";
1110
1111    for (const auto &RC : RegisterClasses) {
1112      const std::string &Name = RC.getName();
1113
1114      // Output the extern for the instance.
1115      OS << "  extern const TargetRegisterClass " << Name << "RegClass;\n";
1116    }
1117    OS << "} // end of namespace " << TargetName << "\n\n";
1118  }
1119  OS << "} // End llvm namespace\n";
1120  OS << "#endif // GET_REGINFO_HEADER\n\n";
1121}
1122
1123//
1124// runTargetDesc - Output the target register and register file descriptions.
1125//
1126void
1127RegisterInfoEmitter::runTargetDesc(raw_ostream &OS, CodeGenTarget &Target,
1128                                   CodeGenRegBank &RegBank){
1129  emitSourceFileHeader("Target Register and Register Classes Information", OS);
1130
1131  OS << "\n#ifdef GET_REGINFO_TARGET_DESC\n";
1132  OS << "#undef GET_REGINFO_TARGET_DESC\n";
1133
1134  OS << "namespace llvm {\n\n";
1135
1136  // Get access to MCRegisterClass data.
1137  OS << "extern const MCRegisterClass " << Target.getName()
1138     << "MCRegisterClasses[];\n";
1139
1140  // Start out by emitting each of the register classes.
1141  const auto &RegisterClasses = RegBank.getRegClasses();
1142  const auto &SubRegIndices = RegBank.getSubRegIndices();
1143
1144  // Collect all registers belonging to any allocatable class.
1145  std::set<Record*> AllocatableRegs;
1146
1147  // Collect allocatable registers.
1148  for (const auto &RC : RegisterClasses) {
1149    ArrayRef<Record*> Order = RC.getOrder();
1150
1151    if (RC.Allocatable)
1152      AllocatableRegs.insert(Order.begin(), Order.end());
1153  }
1154
1155  // Build a shared array of value types.
1156  SequenceToOffsetTable<SmallVector<MVT::SimpleValueType, 4> > VTSeqs;
1157  for (const auto &RC : RegisterClasses)
1158    VTSeqs.add(RC.VTs);
1159  VTSeqs.layout();
1160  OS << "\nstatic const MVT::SimpleValueType VTLists[] = {\n";
1161  VTSeqs.emit(OS, printSimpleValueType, "MVT::Other");
1162  OS << "};\n";
1163
1164  // Emit SubRegIndex names, skipping 0.
1165  OS << "\nstatic const char *const SubRegIndexNameTable[] = { \"";
1166
1167  for (const auto &Idx : SubRegIndices) {
1168    OS << Idx.getName();
1169    OS << "\", \"";
1170  }
1171  OS << "\" };\n\n";
1172
1173  // Emit SubRegIndex lane masks, including 0.
1174  OS << "\nstatic const unsigned SubRegIndexLaneMaskTable[] = {\n  ~0u,\n";
1175  for (const auto &Idx : SubRegIndices) {
1176    OS << format("  0x%08x, // ", Idx.LaneMask) << Idx.getName() << '\n';
1177  }
1178  OS << " };\n\n";
1179
1180  OS << "\n";
1181
1182  // Now that all of the structs have been emitted, emit the instances.
1183  if (!RegisterClasses.empty()) {
1184    OS << "\nstatic const TargetRegisterClass *const "
1185       << "NullRegClasses[] = { nullptr };\n\n";
1186
1187    // Emit register class bit mask tables. The first bit mask emitted for a
1188    // register class, RC, is the set of sub-classes, including RC itself.
1189    //
1190    // If RC has super-registers, also create a list of subreg indices and bit
1191    // masks, (Idx, Mask). The bit mask has a bit for every superreg regclass,
1192    // SuperRC, that satisfies:
1193    //
1194    //   For all SuperReg in SuperRC: SuperReg:Idx in RC
1195    //
1196    // The 0-terminated list of subreg indices starts at:
1197    //
1198    //   RC->getSuperRegIndices() = SuperRegIdxSeqs + ...
1199    //
1200    // The corresponding bitmasks follow the sub-class mask in memory. Each
1201    // mask has RCMaskWords uint32_t entries.
1202    //
1203    // Every bit mask present in the list has at least one bit set.
1204
1205    // Compress the sub-reg index lists.
1206    typedef std::vector<const CodeGenSubRegIndex*> IdxList;
1207    SmallVector<IdxList, 8> SuperRegIdxLists(RegisterClasses.size());
1208    SequenceToOffsetTable<IdxList, deref<llvm::less>> SuperRegIdxSeqs;
1209    BitVector MaskBV(RegisterClasses.size());
1210
1211    for (const auto &RC : RegisterClasses) {
1212      OS << "static const uint32_t " << RC.getName() << "SubClassMask[] = {\n  ";
1213      printBitVectorAsHex(OS, RC.getSubClasses(), 32);
1214
1215      // Emit super-reg class masks for any relevant SubRegIndices that can
1216      // project into RC.
1217      IdxList &SRIList = SuperRegIdxLists[RC.EnumValue];
1218      for (auto &Idx : SubRegIndices) {
1219        MaskBV.reset();
1220        RC.getSuperRegClasses(&Idx, MaskBV);
1221        if (MaskBV.none())
1222          continue;
1223        SRIList.push_back(&Idx);
1224        OS << "\n  ";
1225        printBitVectorAsHex(OS, MaskBV, 32);
1226        OS << "// " << Idx.getName();
1227      }
1228      SuperRegIdxSeqs.add(SRIList);
1229      OS << "\n};\n\n";
1230    }
1231
1232    OS << "static const uint16_t SuperRegIdxSeqs[] = {\n";
1233    SuperRegIdxSeqs.layout();
1234    SuperRegIdxSeqs.emit(OS, printSubRegIndex);
1235    OS << "};\n\n";
1236
1237    // Emit NULL terminated super-class lists.
1238    for (const auto &RC : RegisterClasses) {
1239      ArrayRef<CodeGenRegisterClass*> Supers = RC.getSuperClasses();
1240
1241      // Skip classes without supers.  We can reuse NullRegClasses.
1242      if (Supers.empty())
1243        continue;
1244
1245      OS << "static const TargetRegisterClass *const "
1246         << RC.getName() << "Superclasses[] = {\n";
1247      for (const auto *Super : Supers)
1248        OS << "  &" << Super->getQualifiedName() << "RegClass,\n";
1249      OS << "  nullptr\n};\n\n";
1250    }
1251
1252    // Emit methods.
1253    for (const auto &RC : RegisterClasses) {
1254      if (!RC.AltOrderSelect.empty()) {
1255        OS << "\nstatic inline unsigned " << RC.getName()
1256           << "AltOrderSelect(const MachineFunction &MF) {"
1257           << RC.AltOrderSelect << "}\n\n"
1258           << "static ArrayRef<MCPhysReg> " << RC.getName()
1259           << "GetRawAllocationOrder(const MachineFunction &MF) {\n";
1260        for (unsigned oi = 1 , oe = RC.getNumOrders(); oi != oe; ++oi) {
1261          ArrayRef<Record*> Elems = RC.getOrder(oi);
1262          if (!Elems.empty()) {
1263            OS << "  static const MCPhysReg AltOrder" << oi << "[] = {";
1264            for (unsigned elem = 0; elem != Elems.size(); ++elem)
1265              OS << (elem ? ", " : " ") << getQualifiedName(Elems[elem]);
1266            OS << " };\n";
1267          }
1268        }
1269        OS << "  const MCRegisterClass &MCR = " << Target.getName()
1270           << "MCRegisterClasses[" << RC.getQualifiedName() + "RegClassID];\n"
1271           << "  const ArrayRef<MCPhysReg> Order[] = {\n"
1272           << "    makeArrayRef(MCR.begin(), MCR.getNumRegs()";
1273        for (unsigned oi = 1, oe = RC.getNumOrders(); oi != oe; ++oi)
1274          if (RC.getOrder(oi).empty())
1275            OS << "),\n    ArrayRef<MCPhysReg>(";
1276          else
1277            OS << "),\n    makeArrayRef(AltOrder" << oi;
1278        OS << ")\n  };\n  const unsigned Select = " << RC.getName()
1279           << "AltOrderSelect(MF);\n  assert(Select < " << RC.getNumOrders()
1280           << ");\n  return Order[Select];\n}\n";
1281      }
1282    }
1283
1284    // Now emit the actual value-initialized register class instances.
1285    OS << "\nnamespace " << RegisterClasses.front().Namespace
1286       << " {   // Register class instances\n";
1287
1288    for (const auto &RC : RegisterClasses) {
1289      OS << "  extern const TargetRegisterClass " << RC.getName()
1290         << "RegClass = {\n    " << '&' << Target.getName()
1291         << "MCRegisterClasses[" << RC.getName() << "RegClassID],\n    "
1292         << "VTLists + " << VTSeqs.get(RC.VTs) << ",\n    " << RC.getName()
1293         << "SubClassMask,\n    SuperRegIdxSeqs + "
1294         << SuperRegIdxSeqs.get(SuperRegIdxLists[RC.EnumValue]) << ",\n    "
1295         << format("0x%08x,\n    ", RC.LaneMask);
1296      if (RC.getSuperClasses().empty())
1297        OS << "NullRegClasses,\n    ";
1298      else
1299        OS << RC.getName() << "Superclasses,\n    ";
1300      if (RC.AltOrderSelect.empty())
1301        OS << "nullptr\n";
1302      else
1303        OS << RC.getName() << "GetRawAllocationOrder\n";
1304      OS << "  };\n\n";
1305    }
1306
1307    OS << "}\n";
1308  }
1309
1310  OS << "\nnamespace {\n";
1311  OS << "  const TargetRegisterClass* const RegisterClasses[] = {\n";
1312  for (const auto &RC : RegisterClasses)
1313    OS << "    &" << RC.getQualifiedName() << "RegClass,\n";
1314  OS << "  };\n";
1315  OS << "}\n";       // End of anonymous namespace...
1316
1317  // Emit extra information about registers.
1318  const std::string &TargetName = Target.getName();
1319  OS << "\nstatic const TargetRegisterInfoDesc "
1320     << TargetName << "RegInfoDesc[] = { // Extra Descriptors\n";
1321  OS << "  { 0, 0 },\n";
1322
1323  const auto &Regs = RegBank.getRegisters();
1324  for (const auto &Reg : Regs) {
1325    OS << "  { ";
1326    OS << Reg.CostPerUse << ", "
1327       << int(AllocatableRegs.count(Reg.TheDef)) << " },\n";
1328  }
1329  OS << "};\n";      // End of register descriptors...
1330
1331
1332  std::string ClassName = Target.getName() + "GenRegisterInfo";
1333
1334  auto SubRegIndicesSize =
1335      std::distance(SubRegIndices.begin(), SubRegIndices.end());
1336
1337  if (!SubRegIndices.empty()) {
1338    emitComposeSubRegIndices(OS, RegBank, ClassName);
1339    emitComposeSubRegIndexLaneMask(OS, RegBank, ClassName);
1340  }
1341
1342  // Emit getSubClassWithSubReg.
1343  if (!SubRegIndices.empty()) {
1344    OS << "const TargetRegisterClass *" << ClassName
1345       << "::getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx)"
1346       << " const {\n";
1347    // Use the smallest type that can hold a regclass ID with room for a
1348    // sentinel.
1349    if (RegisterClasses.size() < UINT8_MAX)
1350      OS << "  static const uint8_t Table[";
1351    else if (RegisterClasses.size() < UINT16_MAX)
1352      OS << "  static const uint16_t Table[";
1353    else
1354      PrintFatalError("Too many register classes.");
1355    OS << RegisterClasses.size() << "][" << SubRegIndicesSize << "] = {\n";
1356    for (const auto &RC : RegisterClasses) {
1357      OS << "    {\t// " << RC.getName() << "\n";
1358      for (auto &Idx : SubRegIndices) {
1359        if (CodeGenRegisterClass *SRC = RC.getSubClassWithSubReg(&Idx))
1360          OS << "      " << SRC->EnumValue + 1 << ",\t// " << Idx.getName()
1361             << " -> " << SRC->getName() << "\n";
1362        else
1363          OS << "      0,\t// " << Idx.getName() << "\n";
1364      }
1365      OS << "    },\n";
1366    }
1367    OS << "  };\n  assert(RC && \"Missing regclass\");\n"
1368       << "  if (!Idx) return RC;\n  --Idx;\n"
1369       << "  assert(Idx < " << SubRegIndicesSize << " && \"Bad subreg\");\n"
1370       << "  unsigned TV = Table[RC->getID()][Idx];\n"
1371       << "  return TV ? getRegClass(TV - 1) : nullptr;\n}\n\n";
1372  }
1373
1374  EmitRegUnitPressure(OS, RegBank, ClassName);
1375
1376  // Emit the constructor of the class...
1377  OS << "extern const MCRegisterDesc " << TargetName << "RegDesc[];\n";
1378  OS << "extern const MCPhysReg " << TargetName << "RegDiffLists[];\n";
1379  OS << "extern const unsigned " << TargetName << "LaneMaskLists[];\n";
1380  OS << "extern const char " << TargetName << "RegStrings[];\n";
1381  OS << "extern const char " << TargetName << "RegClassStrings[];\n";
1382  OS << "extern const MCPhysReg " << TargetName << "RegUnitRoots[][2];\n";
1383  OS << "extern const uint16_t " << TargetName << "SubRegIdxLists[];\n";
1384  OS << "extern const MCRegisterInfo::SubRegCoveredBits "
1385     << TargetName << "SubRegIdxRanges[];\n";
1386  OS << "extern const uint16_t " << TargetName << "RegEncodingTable[];\n";
1387
1388  EmitRegMappingTables(OS, Regs, true);
1389
1390  OS << ClassName << "::\n" << ClassName
1391     << "(unsigned RA, unsigned DwarfFlavour, unsigned EHFlavour, unsigned PC)\n"
1392     << "  : TargetRegisterInfo(" << TargetName << "RegInfoDesc"
1393     << ", RegisterClasses, RegisterClasses+" << RegisterClasses.size() <<",\n"
1394     << "             SubRegIndexNameTable, SubRegIndexLaneMaskTable, 0x";
1395  OS.write_hex(RegBank.CoveringLanes);
1396  OS << ") {\n"
1397     << "  InitMCRegisterInfo(" << TargetName << "RegDesc, " << Regs.size() + 1
1398     << ", RA, PC,\n                     " << TargetName
1399     << "MCRegisterClasses, " << RegisterClasses.size() << ",\n"
1400     << "                     " << TargetName << "RegUnitRoots,\n"
1401     << "                     " << RegBank.getNumNativeRegUnits() << ",\n"
1402     << "                     " << TargetName << "RegDiffLists,\n"
1403     << "                     " << TargetName << "LaneMaskLists,\n"
1404     << "                     " << TargetName << "RegStrings,\n"
1405     << "                     " << TargetName << "RegClassStrings,\n"
1406     << "                     " << TargetName << "SubRegIdxLists,\n"
1407     << "                     " << SubRegIndicesSize + 1 << ",\n"
1408     << "                     " << TargetName << "SubRegIdxRanges,\n"
1409     << "                     " << TargetName << "RegEncodingTable);\n\n";
1410
1411  EmitRegMapping(OS, Regs, true);
1412
1413  OS << "}\n\n";
1414
1415
1416  // Emit CalleeSavedRegs information.
1417  std::vector<Record*> CSRSets =
1418    Records.getAllDerivedDefinitions("CalleeSavedRegs");
1419  for (unsigned i = 0, e = CSRSets.size(); i != e; ++i) {
1420    Record *CSRSet = CSRSets[i];
1421    const SetTheory::RecVec *Regs = RegBank.getSets().expand(CSRSet);
1422    assert(Regs && "Cannot expand CalleeSavedRegs instance");
1423
1424    // Emit the *_SaveList list of callee-saved registers.
1425    OS << "static const MCPhysReg " << CSRSet->getName()
1426       << "_SaveList[] = { ";
1427    for (unsigned r = 0, re = Regs->size(); r != re; ++r)
1428      OS << getQualifiedName((*Regs)[r]) << ", ";
1429    OS << "0 };\n";
1430
1431    // Emit the *_RegMask bit mask of call-preserved registers.
1432    BitVector Covered = RegBank.computeCoveredRegisters(*Regs);
1433
1434    // Check for an optional OtherPreserved set.
1435    // Add those registers to RegMask, but not to SaveList.
1436    if (DagInit *OPDag =
1437        dyn_cast<DagInit>(CSRSet->getValueInit("OtherPreserved"))) {
1438      SetTheory::RecSet OPSet;
1439      RegBank.getSets().evaluate(OPDag, OPSet, CSRSet->getLoc());
1440      Covered |= RegBank.computeCoveredRegisters(
1441        ArrayRef<Record*>(OPSet.begin(), OPSet.end()));
1442    }
1443
1444    OS << "static const uint32_t " << CSRSet->getName()
1445       << "_RegMask[] = { ";
1446    printBitVectorAsHex(OS, Covered, 32);
1447    OS << "};\n";
1448  }
1449  OS << "\n\n";
1450
1451  OS << "} // End llvm namespace\n";
1452  OS << "#endif // GET_REGINFO_TARGET_DESC\n\n";
1453}
1454
1455void RegisterInfoEmitter::run(raw_ostream &OS) {
1456  CodeGenTarget Target(Records);
1457  CodeGenRegBank &RegBank = Target.getRegBank();
1458  RegBank.computeDerivedInfo();
1459
1460  runEnums(OS, Target, RegBank);
1461  runMCDesc(OS, Target, RegBank);
1462  runTargetHeader(OS, Target, RegBank);
1463  runTargetDesc(OS, Target, RegBank);
1464}
1465
1466namespace llvm {
1467
1468void EmitRegisterInfo(RecordKeeper &RK, raw_ostream &OS) {
1469  RegisterInfoEmitter(RK).run(OS);
1470}
1471
1472} // End llvm namespace
1473