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>
30 using namespace llvm;
31 
32 namespace {
33 class RegisterInfoEmitter {
34   RecordKeeper &Records;
35 public:
RegisterInfoEmitter(RecordKeeper & R)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 
55 private:
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.
runEnums(raw_ostream & OS,CodeGenTarget & Target,CodeGenRegBank & Bank)71 void 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 
printInt(raw_ostream & OS,int Val)159 static void printInt(raw_ostream &OS, int Val) {
160   OS << Val;
161 }
162 
getMinimalTypeForRange(uint64_t Range)163 static 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 
172 void RegisterInfoEmitter::
EmitRegUnitPressure(raw_ostream & OS,const CodeGenRegBank & RegBank,const std::string & ClassName)173 EmitRegUnitPressure(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 *const 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(const MachineFunction &MF, 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 
EmitRegMappingTables(raw_ostream & OS,const std::deque<CodeGenRegister> & Regs,bool isCtor)320 void 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 
EmitRegMapping(raw_ostream & OS,const std::deque<CodeGenRegister> & Regs,bool isCtor)443 void 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.
printBitVectorAsHex(raw_ostream & OS,const BitVector & Bits,unsigned Width)524 static 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.
538 class BitVectorEmitter {
539   BitVector Values;
540 public:
add(unsigned v)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 
print(raw_ostream & OS)547   void print(raw_ostream &OS) {
548     printBitVectorAsHex(OS, Values, 8);
549   }
550 };
551 
printSimpleValueType(raw_ostream & OS,MVT::SimpleValueType VT)552 static void printSimpleValueType(raw_ostream &OS, MVT::SimpleValueType VT) {
553   OS << getEnumName(VT);
554 }
555 
printSubRegIndex(raw_ostream & OS,const CodeGenSubRegIndex * Idx)556 static 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 
570 typedef SmallVector<uint16_t, 4> DiffVec;
571 typedef 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.
575 static
diffEncode(DiffVec & V,unsigned InitVal,SparseBitVector<> List)576 DiffVec &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 
587 template<typename Iter>
588 static
diffEncode(DiffVec & V,unsigned InitVal,Iter Begin,Iter End)589 DiffVec &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 
printDiff16(raw_ostream & OS,uint16_t Val)600 static void printDiff16(raw_ostream &OS, uint16_t Val) {
601   OS << Val;
602 }
603 
printMask(raw_ostream & OS,unsigned Val)604 static 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.
combine(const CodeGenSubRegIndex * Idx,SmallVectorImpl<CodeGenSubRegIndex * > & Vec)610 static bool combine(const CodeGenSubRegIndex *Idx,
611                     SmallVectorImpl<CodeGenSubRegIndex*> &Vec) {
612   const CodeGenSubRegIndex::CompMap &Map = Idx->getComposites();
613   for (const auto &I : Map) {
614     CodeGenSubRegIndex *&Entry = Vec[I.first->EnumValue - 1];
615     if (Entry && Entry != I.second)
616       return false;
617   }
618 
619   // All entries are compatible. Make it so.
620   for (const auto &I : Map) {
621     auto *&Entry = Vec[I.first->EnumValue - 1];
622     assert((!Entry || Entry == I.second) &&
623            "Expected EnumValue to be unique");
624     Entry = I.second;
625   }
626   return true;
627 }
628 
629 void
emitComposeSubRegIndices(raw_ostream & OS,CodeGenRegBank & RegBank,const std::string & ClName)630 RegisterInfoEmitter::emitComposeSubRegIndices(raw_ostream &OS,
631                                               CodeGenRegBank &RegBank,
632                                               const std::string &ClName) {
633   const auto &SubRegIndices = RegBank.getSubRegIndices();
634   OS << "unsigned " << ClName
635      << "::composeSubRegIndicesImpl(unsigned IdxA, unsigned IdxB) const {\n";
636 
637   // Many sub-register indexes are composition-compatible, meaning that
638   //
639   //   compose(IdxA, IdxB) == compose(IdxA', IdxB)
640   //
641   // for many IdxA, IdxA' pairs. Not all sub-register indexes can be composed.
642   // The illegal entries can be use as wildcards to compress the table further.
643 
644   // Map each Sub-register index to a compatible table row.
645   SmallVector<unsigned, 4> RowMap;
646   SmallVector<SmallVector<CodeGenSubRegIndex*, 4>, 4> Rows;
647 
648   auto SubRegIndicesSize =
649       std::distance(SubRegIndices.begin(), SubRegIndices.end());
650   for (const auto &Idx : SubRegIndices) {
651     unsigned Found = ~0u;
652     for (unsigned r = 0, re = Rows.size(); r != re; ++r) {
653       if (combine(&Idx, Rows[r])) {
654         Found = r;
655         break;
656       }
657     }
658     if (Found == ~0u) {
659       Found = Rows.size();
660       Rows.resize(Found + 1);
661       Rows.back().resize(SubRegIndicesSize);
662       combine(&Idx, Rows.back());
663     }
664     RowMap.push_back(Found);
665   }
666 
667   // Output the row map if there is multiple rows.
668   if (Rows.size() > 1) {
669     OS << "  static const " << getMinimalTypeForRange(Rows.size()) << " RowMap["
670        << SubRegIndicesSize << "] = {\n    ";
671     for (unsigned i = 0, e = SubRegIndicesSize; i != e; ++i)
672       OS << RowMap[i] << ", ";
673     OS << "\n  };\n";
674   }
675 
676   // Output the rows.
677   OS << "  static const " << getMinimalTypeForRange(SubRegIndicesSize + 1)
678      << " Rows[" << Rows.size() << "][" << SubRegIndicesSize << "] = {\n";
679   for (unsigned r = 0, re = Rows.size(); r != re; ++r) {
680     OS << "    { ";
681     for (unsigned i = 0, e = SubRegIndicesSize; i != e; ++i)
682       if (Rows[r][i])
683         OS << Rows[r][i]->EnumValue << ", ";
684       else
685         OS << "0, ";
686     OS << "},\n";
687   }
688   OS << "  };\n\n";
689 
690   OS << "  --IdxA; assert(IdxA < " << SubRegIndicesSize << ");\n"
691      << "  --IdxB; assert(IdxB < " << SubRegIndicesSize << ");\n";
692   if (Rows.size() > 1)
693     OS << "  return Rows[RowMap[IdxA]][IdxB];\n";
694   else
695     OS << "  return Rows[0][IdxB];\n";
696   OS << "}\n\n";
697 }
698 
699 void
emitComposeSubRegIndexLaneMask(raw_ostream & OS,CodeGenRegBank & RegBank,const std::string & ClName)700 RegisterInfoEmitter::emitComposeSubRegIndexLaneMask(raw_ostream &OS,
701                                                     CodeGenRegBank &RegBank,
702                                                     const std::string &ClName) {
703   // See the comments in computeSubRegLaneMasks() for our goal here.
704   const auto &SubRegIndices = RegBank.getSubRegIndices();
705 
706   // Create a list of Mask+Rotate operations, with equivalent entries merged.
707   SmallVector<unsigned, 4> SubReg2SequenceIndexMap;
708   SmallVector<SmallVector<MaskRolPair, 1>, 4> Sequences;
709   for (const auto &Idx : SubRegIndices) {
710     const SmallVector<MaskRolPair, 1> &IdxSequence
711       = Idx.CompositionLaneMaskTransform;
712 
713     unsigned Found = ~0u;
714     unsigned SIdx = 0;
715     unsigned NextSIdx;
716     for (size_t s = 0, se = Sequences.size(); s != se; ++s, SIdx = NextSIdx) {
717       SmallVectorImpl<MaskRolPair> &Sequence = Sequences[s];
718       NextSIdx = SIdx + Sequence.size() + 1;
719       if (Sequence == IdxSequence) {
720         Found = SIdx;
721         break;
722       }
723     }
724     if (Found == ~0u) {
725       Sequences.push_back(IdxSequence);
726       Found = SIdx;
727     }
728     SubReg2SequenceIndexMap.push_back(Found);
729   }
730 
731   OS << "unsigned " << ClName
732      << "::composeSubRegIndexLaneMaskImpl(unsigned IdxA, unsigned LaneMask)"
733         " const {\n";
734 
735   OS << "  struct MaskRolOp {\n"
736         "    unsigned Mask;\n"
737         "    uint8_t  RotateLeft;\n"
738         "  };\n"
739         "  static const MaskRolOp Seqs[] = {\n";
740   unsigned Idx = 0;
741   for (size_t s = 0, se = Sequences.size(); s != se; ++s) {
742     OS << "    ";
743     const SmallVectorImpl<MaskRolPair> &Sequence = Sequences[s];
744     for (size_t p = 0, pe = Sequence.size(); p != pe; ++p) {
745       const MaskRolPair &P = Sequence[p];
746       OS << format("{ 0x%08X, %2u }, ", P.Mask, P.RotateLeft);
747     }
748     OS << "{ 0, 0 }";
749     if (s+1 != se)
750       OS << ", ";
751     OS << "  // Sequence " << Idx << "\n";
752     Idx += Sequence.size() + 1;
753   }
754   OS << "  };\n"
755         "  static const MaskRolOp *const CompositeSequences[] = {\n";
756   for (size_t i = 0, e = SubRegIndices.size(); i != e; ++i) {
757     OS << "    ";
758     unsigned Idx = SubReg2SequenceIndexMap[i];
759     OS << format("&Seqs[%u]", Idx);
760     if (i+1 != e)
761       OS << ",";
762     OS << " // to " << SubRegIndices[i].getName() << "\n";
763   }
764   OS << "  };\n\n";
765 
766   OS << "  --IdxA; assert(IdxA < " << SubRegIndices.size()
767      << " && \"Subregister index out of bounds\");\n"
768         "  unsigned Result = 0;\n"
769         "  for (const MaskRolOp *Ops = CompositeSequences[IdxA]; Ops->Mask != 0; ++Ops)"
770         " {\n"
771         "    unsigned Masked = LaneMask & Ops->Mask;\n"
772         "    Result |= (Masked << Ops->RotateLeft) & 0xFFFFFFFF;\n"
773         "    Result |= (Masked >> ((32 - Ops->RotateLeft) & 0x1F));\n"
774         "  }\n"
775         "  return Result;\n"
776         "}\n";
777 }
778 
779 //
780 // runMCDesc - Print out MC register descriptions.
781 //
782 void
runMCDesc(raw_ostream & OS,CodeGenTarget & Target,CodeGenRegBank & RegBank)783 RegisterInfoEmitter::runMCDesc(raw_ostream &OS, CodeGenTarget &Target,
784                                CodeGenRegBank &RegBank) {
785   emitSourceFileHeader("MC Register Information", OS);
786 
787   OS << "\n#ifdef GET_REGINFO_MC_DESC\n";
788   OS << "#undef GET_REGINFO_MC_DESC\n";
789 
790   const auto &Regs = RegBank.getRegisters();
791 
792   auto &SubRegIndices = RegBank.getSubRegIndices();
793   // The lists of sub-registers and super-registers go in the same array.  That
794   // allows us to share suffixes.
795   typedef std::vector<const CodeGenRegister*> RegVec;
796 
797   // Differentially encoded lists.
798   SequenceToOffsetTable<DiffVec> DiffSeqs;
799   SmallVector<DiffVec, 4> SubRegLists(Regs.size());
800   SmallVector<DiffVec, 4> SuperRegLists(Regs.size());
801   SmallVector<DiffVec, 4> RegUnitLists(Regs.size());
802   SmallVector<unsigned, 4> RegUnitInitScale(Regs.size());
803 
804   // List of lane masks accompanying register unit sequences.
805   SequenceToOffsetTable<MaskVec> LaneMaskSeqs;
806   SmallVector<MaskVec, 4> RegUnitLaneMasks(Regs.size());
807 
808   // Keep track of sub-register names as well. These are not differentially
809   // encoded.
810   typedef SmallVector<const CodeGenSubRegIndex*, 4> SubRegIdxVec;
811   SequenceToOffsetTable<SubRegIdxVec, deref<llvm::less>> SubRegIdxSeqs;
812   SmallVector<SubRegIdxVec, 4> SubRegIdxLists(Regs.size());
813 
814   SequenceToOffsetTable<std::string> RegStrings;
815 
816   // Precompute register lists for the SequenceToOffsetTable.
817   unsigned i = 0;
818   for (auto I = Regs.begin(), E = Regs.end(); I != E; ++I, ++i) {
819     const auto &Reg = *I;
820     RegStrings.add(Reg.getName());
821 
822     // Compute the ordered sub-register list.
823     SetVector<const CodeGenRegister*> SR;
824     Reg.addSubRegsPreOrder(SR, RegBank);
825     diffEncode(SubRegLists[i], Reg.EnumValue, SR.begin(), SR.end());
826     DiffSeqs.add(SubRegLists[i]);
827 
828     // Compute the corresponding sub-register indexes.
829     SubRegIdxVec &SRIs = SubRegIdxLists[i];
830     for (unsigned j = 0, je = SR.size(); j != je; ++j)
831       SRIs.push_back(Reg.getSubRegIndex(SR[j]));
832     SubRegIdxSeqs.add(SRIs);
833 
834     // Super-registers are already computed.
835     const RegVec &SuperRegList = Reg.getSuperRegs();
836     diffEncode(SuperRegLists[i], Reg.EnumValue, SuperRegList.begin(),
837                SuperRegList.end());
838     DiffSeqs.add(SuperRegLists[i]);
839 
840     // Differentially encode the register unit list, seeded by register number.
841     // First compute a scale factor that allows more diff-lists to be reused:
842     //
843     //   D0 -> (S0, S1)
844     //   D1 -> (S2, S3)
845     //
846     // A scale factor of 2 allows D0 and D1 to share a diff-list. The initial
847     // value for the differential decoder is the register number multiplied by
848     // the scale.
849     //
850     // Check the neighboring registers for arithmetic progressions.
851     unsigned ScaleA = ~0u, ScaleB = ~0u;
852     SparseBitVector<> RUs = Reg.getNativeRegUnits();
853     if (I != Regs.begin() &&
854         std::prev(I)->getNativeRegUnits().count() == RUs.count())
855       ScaleB = *RUs.begin() - *std::prev(I)->getNativeRegUnits().begin();
856     if (std::next(I) != Regs.end() &&
857         std::next(I)->getNativeRegUnits().count() == RUs.count())
858       ScaleA = *std::next(I)->getNativeRegUnits().begin() - *RUs.begin();
859     unsigned Scale = std::min(ScaleB, ScaleA);
860     // Default the scale to 0 if it can't be encoded in 4 bits.
861     if (Scale >= 16)
862       Scale = 0;
863     RegUnitInitScale[i] = Scale;
864     DiffSeqs.add(diffEncode(RegUnitLists[i], Scale * Reg.EnumValue, RUs));
865 
866     const auto &RUMasks = Reg.getRegUnitLaneMasks();
867     MaskVec &LaneMaskVec = RegUnitLaneMasks[i];
868     assert(LaneMaskVec.empty());
869     LaneMaskVec.insert(LaneMaskVec.begin(), RUMasks.begin(), RUMasks.end());
870     // Terminator mask should not be used inside of the list.
871 #ifndef NDEBUG
872     for (unsigned M : LaneMaskVec) {
873       assert(M != ~0u && "terminator mask should not be part of the list");
874     }
875 #endif
876     LaneMaskSeqs.add(LaneMaskVec);
877   }
878 
879   // Compute the final layout of the sequence table.
880   DiffSeqs.layout();
881   LaneMaskSeqs.layout();
882   SubRegIdxSeqs.layout();
883 
884   OS << "namespace llvm {\n\n";
885 
886   const std::string &TargetName = Target.getName();
887 
888   // Emit the shared table of differential lists.
889   OS << "extern const MCPhysReg " << TargetName << "RegDiffLists[] = {\n";
890   DiffSeqs.emit(OS, printDiff16);
891   OS << "};\n\n";
892 
893   // Emit the shared table of regunit lane mask sequences.
894   OS << "extern const unsigned " << TargetName << "LaneMaskLists[] = {\n";
895   LaneMaskSeqs.emit(OS, printMask, "~0u");
896   OS << "};\n\n";
897 
898   // Emit the table of sub-register indexes.
899   OS << "extern const uint16_t " << TargetName << "SubRegIdxLists[] = {\n";
900   SubRegIdxSeqs.emit(OS, printSubRegIndex);
901   OS << "};\n\n";
902 
903   // Emit the table of sub-register index sizes.
904   OS << "extern const MCRegisterInfo::SubRegCoveredBits "
905      << TargetName << "SubRegIdxRanges[] = {\n";
906   OS << "  { " << (uint16_t)-1 << ", " << (uint16_t)-1 << " },\n";
907   for (const auto &Idx : SubRegIndices) {
908     OS << "  { " << Idx.Offset << ", " << Idx.Size << " },\t// "
909        << Idx.getName() << "\n";
910   }
911   OS << "};\n\n";
912 
913   // Emit the string table.
914   RegStrings.layout();
915   OS << "extern const char " << TargetName << "RegStrings[] = {\n";
916   RegStrings.emit(OS, printChar);
917   OS << "};\n\n";
918 
919   OS << "extern const MCRegisterDesc " << TargetName
920      << "RegDesc[] = { // Descriptors\n";
921   OS << "  { " << RegStrings.get("") << ", 0, 0, 0, 0, 0 },\n";
922 
923   // Emit the register descriptors now.
924   i = 0;
925   for (const auto &Reg : Regs) {
926     OS << "  { " << RegStrings.get(Reg.getName()) << ", "
927        << DiffSeqs.get(SubRegLists[i]) << ", " << DiffSeqs.get(SuperRegLists[i])
928        << ", " << SubRegIdxSeqs.get(SubRegIdxLists[i]) << ", "
929        << (DiffSeqs.get(RegUnitLists[i]) * 16 + RegUnitInitScale[i]) << ", "
930        << LaneMaskSeqs.get(RegUnitLaneMasks[i]) << " },\n";
931     ++i;
932   }
933   OS << "};\n\n";      // End of register descriptors...
934 
935   // Emit the table of register unit roots. Each regunit has one or two root
936   // registers.
937   OS << "extern const MCPhysReg " << TargetName << "RegUnitRoots[][2] = {\n";
938   for (unsigned i = 0, e = RegBank.getNumNativeRegUnits(); i != e; ++i) {
939     ArrayRef<const CodeGenRegister*> Roots = RegBank.getRegUnit(i).getRoots();
940     assert(!Roots.empty() && "All regunits must have a root register.");
941     assert(Roots.size() <= 2 && "More than two roots not supported yet.");
942     OS << "  { " << getQualifiedName(Roots.front()->TheDef);
943     for (unsigned r = 1; r != Roots.size(); ++r)
944       OS << ", " << getQualifiedName(Roots[r]->TheDef);
945     OS << " },\n";
946   }
947   OS << "};\n\n";
948 
949   const auto &RegisterClasses = RegBank.getRegClasses();
950 
951   // Loop over all of the register classes... emitting each one.
952   OS << "namespace {     // Register classes...\n";
953 
954   SequenceToOffsetTable<std::string> RegClassStrings;
955 
956   // Emit the register enum value arrays for each RegisterClass
957   for (const auto &RC : RegisterClasses) {
958     ArrayRef<Record*> Order = RC.getOrder();
959 
960     // Give the register class a legal C name if it's anonymous.
961     std::string Name = RC.getName();
962 
963     RegClassStrings.add(Name);
964 
965     // Emit the register list now.
966     OS << "  // " << Name << " Register Class...\n"
967        << "  const MCPhysReg " << Name
968        << "[] = {\n    ";
969     for (unsigned i = 0, e = Order.size(); i != e; ++i) {
970       Record *Reg = Order[i];
971       OS << getQualifiedName(Reg) << ", ";
972     }
973     OS << "\n  };\n\n";
974 
975     OS << "  // " << Name << " Bit set.\n"
976        << "  const uint8_t " << Name
977        << "Bits[] = {\n    ";
978     BitVectorEmitter BVE;
979     for (unsigned i = 0, e = Order.size(); i != e; ++i) {
980       Record *Reg = Order[i];
981       BVE.add(Target.getRegBank().getReg(Reg)->EnumValue);
982     }
983     BVE.print(OS);
984     OS << "\n  };\n\n";
985 
986   }
987   OS << "}\n\n";
988 
989   RegClassStrings.layout();
990   OS << "extern const char " << TargetName << "RegClassStrings[] = {\n";
991   RegClassStrings.emit(OS, printChar);
992   OS << "};\n\n";
993 
994   OS << "extern const MCRegisterClass " << TargetName
995      << "MCRegisterClasses[] = {\n";
996 
997   for (const auto &RC : RegisterClasses) {
998     // Asserts to make sure values will fit in table assuming types from
999     // MCRegisterInfo.h
1000     assert((RC.SpillSize/8) <= 0xffff && "SpillSize too large.");
1001     assert((RC.SpillAlignment/8) <= 0xffff && "SpillAlignment too large.");
1002     assert(RC.CopyCost >= -128 && RC.CopyCost <= 127 && "Copy cost too large.");
1003 
1004     OS << "  { " << RC.getName() << ", " << RC.getName() << "Bits, "
1005        << RegClassStrings.get(RC.getName()) << ", "
1006        << RC.getOrder().size() << ", sizeof(" << RC.getName() << "Bits), "
1007        << RC.getQualifiedName() + "RegClassID" << ", "
1008        << RC.SpillSize/8 << ", "
1009        << RC.SpillAlignment/8 << ", "
1010        << RC.CopyCost << ", "
1011        << RC.Allocatable << " },\n";
1012   }
1013 
1014   OS << "};\n\n";
1015 
1016   EmitRegMappingTables(OS, Regs, false);
1017 
1018   // Emit Reg encoding table
1019   OS << "extern const uint16_t " << TargetName;
1020   OS << "RegEncodingTable[] = {\n";
1021   // Add entry for NoRegister
1022   OS << "  0,\n";
1023   for (const auto &RE : Regs) {
1024     Record *Reg = RE.TheDef;
1025     BitsInit *BI = Reg->getValueAsBitsInit("HWEncoding");
1026     uint64_t Value = 0;
1027     for (unsigned b = 0, be = BI->getNumBits(); b != be; ++b) {
1028       if (BitInit *B = dyn_cast<BitInit>(BI->getBit(b)))
1029         Value |= (uint64_t)B->getValue() << b;
1030     }
1031     OS << "  " << Value << ",\n";
1032   }
1033   OS << "};\n";       // End of HW encoding table
1034 
1035   // MCRegisterInfo initialization routine.
1036   OS << "static inline void Init" << TargetName
1037      << "MCRegisterInfo(MCRegisterInfo *RI, unsigned RA, "
1038      << "unsigned DwarfFlavour = 0, unsigned EHFlavour = 0, unsigned PC = 0) "
1039         "{\n"
1040      << "  RI->InitMCRegisterInfo(" << TargetName << "RegDesc, "
1041      << Regs.size() + 1 << ", RA, PC, " << TargetName << "MCRegisterClasses, "
1042      << RegisterClasses.size() << ", " << TargetName << "RegUnitRoots, "
1043      << RegBank.getNumNativeRegUnits() << ", " << TargetName << "RegDiffLists, "
1044      << TargetName << "LaneMaskLists, " << TargetName << "RegStrings, "
1045      << TargetName << "RegClassStrings, " << TargetName << "SubRegIdxLists, "
1046      << (std::distance(SubRegIndices.begin(), SubRegIndices.end()) + 1) << ",\n"
1047      << TargetName << "SubRegIdxRanges, " << TargetName
1048      << "RegEncodingTable);\n\n";
1049 
1050   EmitRegMapping(OS, Regs, false);
1051 
1052   OS << "}\n\n";
1053 
1054   OS << "} // End llvm namespace\n";
1055   OS << "#endif // GET_REGINFO_MC_DESC\n\n";
1056 }
1057 
1058 void
runTargetHeader(raw_ostream & OS,CodeGenTarget & Target,CodeGenRegBank & RegBank)1059 RegisterInfoEmitter::runTargetHeader(raw_ostream &OS, CodeGenTarget &Target,
1060                                      CodeGenRegBank &RegBank) {
1061   emitSourceFileHeader("Register Information Header Fragment", OS);
1062 
1063   OS << "\n#ifdef GET_REGINFO_HEADER\n";
1064   OS << "#undef GET_REGINFO_HEADER\n";
1065 
1066   const std::string &TargetName = Target.getName();
1067   std::string ClassName = TargetName + "GenRegisterInfo";
1068 
1069   OS << "#include \"llvm/Target/TargetRegisterInfo.h\"\n\n";
1070 
1071   OS << "namespace llvm {\n\n";
1072 
1073   OS << "struct " << ClassName << " : public TargetRegisterInfo {\n"
1074      << "  explicit " << ClassName
1075      << "(unsigned RA, unsigned D = 0, unsigned E = 0, unsigned PC = 0);\n"
1076      << "  bool needsStackRealignment(const MachineFunction &) const override\n"
1077      << "     { return false; }\n";
1078   if (!RegBank.getSubRegIndices().empty()) {
1079     OS << "  unsigned composeSubRegIndicesImpl"
1080        << "(unsigned, unsigned) const override;\n"
1081        << "  unsigned composeSubRegIndexLaneMaskImpl"
1082        << "(unsigned, unsigned) const override;\n"
1083        << "  const TargetRegisterClass *getSubClassWithSubReg"
1084        << "(const TargetRegisterClass*, unsigned) const override;\n";
1085   }
1086   OS << "  const RegClassWeight &getRegClassWeight("
1087      << "const TargetRegisterClass *RC) const override;\n"
1088      << "  unsigned getRegUnitWeight(unsigned RegUnit) const override;\n"
1089      << "  unsigned getNumRegPressureSets() const override;\n"
1090      << "  const char *getRegPressureSetName(unsigned Idx) const override;\n"
1091      << "  unsigned getRegPressureSetLimit(const MachineFunction &MF, unsigned "
1092         "Idx) const override;\n"
1093      << "  const int *getRegClassPressureSets("
1094      << "const TargetRegisterClass *RC) const override;\n"
1095      << "  const int *getRegUnitPressureSets("
1096      << "unsigned RegUnit) const override;\n"
1097      << "};\n\n";
1098 
1099   const auto &RegisterClasses = RegBank.getRegClasses();
1100 
1101   if (!RegisterClasses.empty()) {
1102     OS << "namespace " << RegisterClasses.front().Namespace
1103        << " { // Register classes\n";
1104 
1105     for (const auto &RC : RegisterClasses) {
1106       const std::string &Name = RC.getName();
1107 
1108       // Output the extern for the instance.
1109       OS << "  extern const TargetRegisterClass " << Name << "RegClass;\n";
1110     }
1111     OS << "} // end of namespace " << TargetName << "\n\n";
1112   }
1113   OS << "} // End llvm namespace\n";
1114   OS << "#endif // GET_REGINFO_HEADER\n\n";
1115 }
1116 
1117 //
1118 // runTargetDesc - Output the target register and register file descriptions.
1119 //
1120 void
runTargetDesc(raw_ostream & OS,CodeGenTarget & Target,CodeGenRegBank & RegBank)1121 RegisterInfoEmitter::runTargetDesc(raw_ostream &OS, CodeGenTarget &Target,
1122                                    CodeGenRegBank &RegBank){
1123   emitSourceFileHeader("Target Register and Register Classes Information", OS);
1124 
1125   OS << "\n#ifdef GET_REGINFO_TARGET_DESC\n";
1126   OS << "#undef GET_REGINFO_TARGET_DESC\n";
1127 
1128   OS << "namespace llvm {\n\n";
1129 
1130   // Get access to MCRegisterClass data.
1131   OS << "extern const MCRegisterClass " << Target.getName()
1132      << "MCRegisterClasses[];\n";
1133 
1134   // Start out by emitting each of the register classes.
1135   const auto &RegisterClasses = RegBank.getRegClasses();
1136   const auto &SubRegIndices = RegBank.getSubRegIndices();
1137 
1138   // Collect all registers belonging to any allocatable class.
1139   std::set<Record*> AllocatableRegs;
1140 
1141   // Collect allocatable registers.
1142   for (const auto &RC : RegisterClasses) {
1143     ArrayRef<Record*> Order = RC.getOrder();
1144 
1145     if (RC.Allocatable)
1146       AllocatableRegs.insert(Order.begin(), Order.end());
1147   }
1148 
1149   // Build a shared array of value types.
1150   SequenceToOffsetTable<SmallVector<MVT::SimpleValueType, 4> > VTSeqs;
1151   for (const auto &RC : RegisterClasses)
1152     VTSeqs.add(RC.VTs);
1153   VTSeqs.layout();
1154   OS << "\nstatic const MVT::SimpleValueType VTLists[] = {\n";
1155   VTSeqs.emit(OS, printSimpleValueType, "MVT::Other");
1156   OS << "};\n";
1157 
1158   // Emit SubRegIndex names, skipping 0.
1159   OS << "\nstatic const char *const SubRegIndexNameTable[] = { \"";
1160 
1161   for (const auto &Idx : SubRegIndices) {
1162     OS << Idx.getName();
1163     OS << "\", \"";
1164   }
1165   OS << "\" };\n\n";
1166 
1167   // Emit SubRegIndex lane masks, including 0.
1168   OS << "\nstatic const unsigned SubRegIndexLaneMaskTable[] = {\n  ~0u,\n";
1169   for (const auto &Idx : SubRegIndices) {
1170     OS << format("  0x%08x, // ", Idx.LaneMask) << Idx.getName() << '\n';
1171   }
1172   OS << " };\n\n";
1173 
1174   OS << "\n";
1175 
1176   // Now that all of the structs have been emitted, emit the instances.
1177   if (!RegisterClasses.empty()) {
1178     OS << "\nstatic const TargetRegisterClass *const "
1179        << "NullRegClasses[] = { nullptr };\n\n";
1180 
1181     // Emit register class bit mask tables. The first bit mask emitted for a
1182     // register class, RC, is the set of sub-classes, including RC itself.
1183     //
1184     // If RC has super-registers, also create a list of subreg indices and bit
1185     // masks, (Idx, Mask). The bit mask has a bit for every superreg regclass,
1186     // SuperRC, that satisfies:
1187     //
1188     //   For all SuperReg in SuperRC: SuperReg:Idx in RC
1189     //
1190     // The 0-terminated list of subreg indices starts at:
1191     //
1192     //   RC->getSuperRegIndices() = SuperRegIdxSeqs + ...
1193     //
1194     // The corresponding bitmasks follow the sub-class mask in memory. Each
1195     // mask has RCMaskWords uint32_t entries.
1196     //
1197     // Every bit mask present in the list has at least one bit set.
1198 
1199     // Compress the sub-reg index lists.
1200     typedef std::vector<const CodeGenSubRegIndex*> IdxList;
1201     SmallVector<IdxList, 8> SuperRegIdxLists(RegisterClasses.size());
1202     SequenceToOffsetTable<IdxList, deref<llvm::less>> SuperRegIdxSeqs;
1203     BitVector MaskBV(RegisterClasses.size());
1204 
1205     for (const auto &RC : RegisterClasses) {
1206       OS << "static const uint32_t " << RC.getName() << "SubClassMask[] = {\n  ";
1207       printBitVectorAsHex(OS, RC.getSubClasses(), 32);
1208 
1209       // Emit super-reg class masks for any relevant SubRegIndices that can
1210       // project into RC.
1211       IdxList &SRIList = SuperRegIdxLists[RC.EnumValue];
1212       for (auto &Idx : SubRegIndices) {
1213         MaskBV.reset();
1214         RC.getSuperRegClasses(&Idx, MaskBV);
1215         if (MaskBV.none())
1216           continue;
1217         SRIList.push_back(&Idx);
1218         OS << "\n  ";
1219         printBitVectorAsHex(OS, MaskBV, 32);
1220         OS << "// " << Idx.getName();
1221       }
1222       SuperRegIdxSeqs.add(SRIList);
1223       OS << "\n};\n\n";
1224     }
1225 
1226     OS << "static const uint16_t SuperRegIdxSeqs[] = {\n";
1227     SuperRegIdxSeqs.layout();
1228     SuperRegIdxSeqs.emit(OS, printSubRegIndex);
1229     OS << "};\n\n";
1230 
1231     // Emit NULL terminated super-class lists.
1232     for (const auto &RC : RegisterClasses) {
1233       ArrayRef<CodeGenRegisterClass*> Supers = RC.getSuperClasses();
1234 
1235       // Skip classes without supers.  We can reuse NullRegClasses.
1236       if (Supers.empty())
1237         continue;
1238 
1239       OS << "static const TargetRegisterClass *const "
1240          << RC.getName() << "Superclasses[] = {\n";
1241       for (const auto *Super : Supers)
1242         OS << "  &" << Super->getQualifiedName() << "RegClass,\n";
1243       OS << "  nullptr\n};\n\n";
1244     }
1245 
1246     // Emit methods.
1247     for (const auto &RC : RegisterClasses) {
1248       if (!RC.AltOrderSelect.empty()) {
1249         OS << "\nstatic inline unsigned " << RC.getName()
1250            << "AltOrderSelect(const MachineFunction &MF) {"
1251            << RC.AltOrderSelect << "}\n\n"
1252            << "static ArrayRef<MCPhysReg> " << RC.getName()
1253            << "GetRawAllocationOrder(const MachineFunction &MF) {\n";
1254         for (unsigned oi = 1 , oe = RC.getNumOrders(); oi != oe; ++oi) {
1255           ArrayRef<Record*> Elems = RC.getOrder(oi);
1256           if (!Elems.empty()) {
1257             OS << "  static const MCPhysReg AltOrder" << oi << "[] = {";
1258             for (unsigned elem = 0; elem != Elems.size(); ++elem)
1259               OS << (elem ? ", " : " ") << getQualifiedName(Elems[elem]);
1260             OS << " };\n";
1261           }
1262         }
1263         OS << "  const MCRegisterClass &MCR = " << Target.getName()
1264            << "MCRegisterClasses[" << RC.getQualifiedName() + "RegClassID];\n"
1265            << "  const ArrayRef<MCPhysReg> Order[] = {\n"
1266            << "    makeArrayRef(MCR.begin(), MCR.getNumRegs()";
1267         for (unsigned oi = 1, oe = RC.getNumOrders(); oi != oe; ++oi)
1268           if (RC.getOrder(oi).empty())
1269             OS << "),\n    ArrayRef<MCPhysReg>(";
1270           else
1271             OS << "),\n    makeArrayRef(AltOrder" << oi;
1272         OS << ")\n  };\n  const unsigned Select = " << RC.getName()
1273            << "AltOrderSelect(MF);\n  assert(Select < " << RC.getNumOrders()
1274            << ");\n  return Order[Select];\n}\n";
1275       }
1276     }
1277 
1278     // Now emit the actual value-initialized register class instances.
1279     OS << "\nnamespace " << RegisterClasses.front().Namespace
1280        << " {   // Register class instances\n";
1281 
1282     for (const auto &RC : RegisterClasses) {
1283       OS << "  extern const TargetRegisterClass " << RC.getName()
1284          << "RegClass = {\n    " << '&' << Target.getName()
1285          << "MCRegisterClasses[" << RC.getName() << "RegClassID],\n    "
1286          << "VTLists + " << VTSeqs.get(RC.VTs) << ",\n    " << RC.getName()
1287          << "SubClassMask,\n    SuperRegIdxSeqs + "
1288          << SuperRegIdxSeqs.get(SuperRegIdxLists[RC.EnumValue]) << ",\n    "
1289          << format("0x%08x,\n    ", RC.LaneMask)
1290          << (unsigned)RC.AllocationPriority << ",\n    "
1291          << (RC.HasDisjunctSubRegs?"true":"false")
1292          << ", /* HasDisjunctSubRegs */\n    ";
1293       if (RC.getSuperClasses().empty())
1294         OS << "NullRegClasses,\n    ";
1295       else
1296         OS << RC.getName() << "Superclasses,\n    ";
1297       if (RC.AltOrderSelect.empty())
1298         OS << "nullptr\n";
1299       else
1300         OS << RC.getName() << "GetRawAllocationOrder\n";
1301       OS << "  };\n\n";
1302     }
1303 
1304     OS << "}\n";
1305   }
1306 
1307   OS << "\nnamespace {\n";
1308   OS << "  const TargetRegisterClass* const RegisterClasses[] = {\n";
1309   for (const auto &RC : RegisterClasses)
1310     OS << "    &" << RC.getQualifiedName() << "RegClass,\n";
1311   OS << "  };\n";
1312   OS << "}\n";       // End of anonymous namespace...
1313 
1314   // Emit extra information about registers.
1315   const std::string &TargetName = Target.getName();
1316   OS << "\nstatic const TargetRegisterInfoDesc "
1317      << TargetName << "RegInfoDesc[] = { // Extra Descriptors\n";
1318   OS << "  { 0, 0 },\n";
1319 
1320   const auto &Regs = RegBank.getRegisters();
1321   for (const auto &Reg : Regs) {
1322     OS << "  { ";
1323     OS << Reg.CostPerUse << ", "
1324        << int(AllocatableRegs.count(Reg.TheDef)) << " },\n";
1325   }
1326   OS << "};\n";      // End of register descriptors...
1327 
1328 
1329   std::string ClassName = Target.getName() + "GenRegisterInfo";
1330 
1331   auto SubRegIndicesSize =
1332       std::distance(SubRegIndices.begin(), SubRegIndices.end());
1333 
1334   if (!SubRegIndices.empty()) {
1335     emitComposeSubRegIndices(OS, RegBank, ClassName);
1336     emitComposeSubRegIndexLaneMask(OS, RegBank, ClassName);
1337   }
1338 
1339   // Emit getSubClassWithSubReg.
1340   if (!SubRegIndices.empty()) {
1341     OS << "const TargetRegisterClass *" << ClassName
1342        << "::getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx)"
1343        << " const {\n";
1344     // Use the smallest type that can hold a regclass ID with room for a
1345     // sentinel.
1346     if (RegisterClasses.size() < UINT8_MAX)
1347       OS << "  static const uint8_t Table[";
1348     else if (RegisterClasses.size() < UINT16_MAX)
1349       OS << "  static const uint16_t Table[";
1350     else
1351       PrintFatalError("Too many register classes.");
1352     OS << RegisterClasses.size() << "][" << SubRegIndicesSize << "] = {\n";
1353     for (const auto &RC : RegisterClasses) {
1354       OS << "    {\t// " << RC.getName() << "\n";
1355       for (auto &Idx : SubRegIndices) {
1356         if (CodeGenRegisterClass *SRC = RC.getSubClassWithSubReg(&Idx))
1357           OS << "      " << SRC->EnumValue + 1 << ",\t// " << Idx.getName()
1358              << " -> " << SRC->getName() << "\n";
1359         else
1360           OS << "      0,\t// " << Idx.getName() << "\n";
1361       }
1362       OS << "    },\n";
1363     }
1364     OS << "  };\n  assert(RC && \"Missing regclass\");\n"
1365        << "  if (!Idx) return RC;\n  --Idx;\n"
1366        << "  assert(Idx < " << SubRegIndicesSize << " && \"Bad subreg\");\n"
1367        << "  unsigned TV = Table[RC->getID()][Idx];\n"
1368        << "  return TV ? getRegClass(TV - 1) : nullptr;\n}\n\n";
1369   }
1370 
1371   EmitRegUnitPressure(OS, RegBank, ClassName);
1372 
1373   // Emit the constructor of the class...
1374   OS << "extern const MCRegisterDesc " << TargetName << "RegDesc[];\n";
1375   OS << "extern const MCPhysReg " << TargetName << "RegDiffLists[];\n";
1376   OS << "extern const unsigned " << TargetName << "LaneMaskLists[];\n";
1377   OS << "extern const char " << TargetName << "RegStrings[];\n";
1378   OS << "extern const char " << TargetName << "RegClassStrings[];\n";
1379   OS << "extern const MCPhysReg " << TargetName << "RegUnitRoots[][2];\n";
1380   OS << "extern const uint16_t " << TargetName << "SubRegIdxLists[];\n";
1381   OS << "extern const MCRegisterInfo::SubRegCoveredBits "
1382      << TargetName << "SubRegIdxRanges[];\n";
1383   OS << "extern const uint16_t " << TargetName << "RegEncodingTable[];\n";
1384 
1385   EmitRegMappingTables(OS, Regs, true);
1386 
1387   OS << ClassName << "::\n" << ClassName
1388      << "(unsigned RA, unsigned DwarfFlavour, unsigned EHFlavour, unsigned PC)\n"
1389      << "  : TargetRegisterInfo(" << TargetName << "RegInfoDesc"
1390      << ", RegisterClasses, RegisterClasses+" << RegisterClasses.size() <<",\n"
1391      << "             SubRegIndexNameTable, SubRegIndexLaneMaskTable, 0x";
1392   OS.write_hex(RegBank.CoveringLanes);
1393   OS << ") {\n"
1394      << "  InitMCRegisterInfo(" << TargetName << "RegDesc, " << Regs.size() + 1
1395      << ", RA, PC,\n                     " << TargetName
1396      << "MCRegisterClasses, " << RegisterClasses.size() << ",\n"
1397      << "                     " << TargetName << "RegUnitRoots,\n"
1398      << "                     " << RegBank.getNumNativeRegUnits() << ",\n"
1399      << "                     " << TargetName << "RegDiffLists,\n"
1400      << "                     " << TargetName << "LaneMaskLists,\n"
1401      << "                     " << TargetName << "RegStrings,\n"
1402      << "                     " << TargetName << "RegClassStrings,\n"
1403      << "                     " << TargetName << "SubRegIdxLists,\n"
1404      << "                     " << SubRegIndicesSize + 1 << ",\n"
1405      << "                     " << TargetName << "SubRegIdxRanges,\n"
1406      << "                     " << TargetName << "RegEncodingTable);\n\n";
1407 
1408   EmitRegMapping(OS, Regs, true);
1409 
1410   OS << "}\n\n";
1411 
1412 
1413   // Emit CalleeSavedRegs information.
1414   std::vector<Record*> CSRSets =
1415     Records.getAllDerivedDefinitions("CalleeSavedRegs");
1416   for (unsigned i = 0, e = CSRSets.size(); i != e; ++i) {
1417     Record *CSRSet = CSRSets[i];
1418     const SetTheory::RecVec *Regs = RegBank.getSets().expand(CSRSet);
1419     assert(Regs && "Cannot expand CalleeSavedRegs instance");
1420 
1421     // Emit the *_SaveList list of callee-saved registers.
1422     OS << "static const MCPhysReg " << CSRSet->getName()
1423        << "_SaveList[] = { ";
1424     for (unsigned r = 0, re = Regs->size(); r != re; ++r)
1425       OS << getQualifiedName((*Regs)[r]) << ", ";
1426     OS << "0 };\n";
1427 
1428     // Emit the *_RegMask bit mask of call-preserved registers.
1429     BitVector Covered = RegBank.computeCoveredRegisters(*Regs);
1430 
1431     // Check for an optional OtherPreserved set.
1432     // Add those registers to RegMask, but not to SaveList.
1433     if (DagInit *OPDag =
1434         dyn_cast<DagInit>(CSRSet->getValueInit("OtherPreserved"))) {
1435       SetTheory::RecSet OPSet;
1436       RegBank.getSets().evaluate(OPDag, OPSet, CSRSet->getLoc());
1437       Covered |= RegBank.computeCoveredRegisters(
1438         ArrayRef<Record*>(OPSet.begin(), OPSet.end()));
1439     }
1440 
1441     OS << "static const uint32_t " << CSRSet->getName()
1442        << "_RegMask[] = { ";
1443     printBitVectorAsHex(OS, Covered, 32);
1444     OS << "};\n";
1445   }
1446   OS << "\n\n";
1447 
1448   OS << "} // End llvm namespace\n";
1449   OS << "#endif // GET_REGINFO_TARGET_DESC\n\n";
1450 }
1451 
run(raw_ostream & OS)1452 void RegisterInfoEmitter::run(raw_ostream &OS) {
1453   CodeGenTarget Target(Records);
1454   CodeGenRegBank &RegBank = Target.getRegBank();
1455   RegBank.computeDerivedInfo();
1456 
1457   runEnums(OS, Target, RegBank);
1458   runMCDesc(OS, Target, RegBank);
1459   runTargetHeader(OS, Target, RegBank);
1460   runTargetDesc(OS, Target, RegBank);
1461 }
1462 
1463 namespace llvm {
1464 
EmitRegisterInfo(RecordKeeper & RK,raw_ostream & OS)1465 void EmitRegisterInfo(RecordKeeper &RK, raw_ostream &OS) {
1466   RegisterInfoEmitter(RK).run(OS);
1467 }
1468 
1469 } // End llvm namespace
1470