Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / llvm / utils / TableGen / RegisterInfoEmitter.cpp
blob92ef9199cc4702011d71a653fb45a0a84d3ad833
1 //===- RegisterInfoEmitter.cpp - Generate a Register File Desc. -*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This tablegen backend is responsible for emitting a description of a target
10 // register file for a code generator. It uses instances of the Register,
11 // RegisterAliases, and RegisterClass classes to gather this information.
13 //===----------------------------------------------------------------------===//
15 #include "CodeGenHwModes.h"
16 #include "CodeGenRegisters.h"
17 #include "CodeGenTarget.h"
18 #include "InfoByHwMode.h"
19 #include "SequenceToOffsetTable.h"
20 #include "Types.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/BitVector.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/SparseBitVector.h"
27 #include "llvm/ADT/Twine.h"
28 #include "llvm/CodeGen/MachineValueType.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Format.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/TableGen/Error.h"
34 #include "llvm/TableGen/Record.h"
35 #include "llvm/TableGen/SetTheory.h"
36 #include "llvm/TableGen/TableGenBackend.h"
37 #include <algorithm>
38 #include <cassert>
39 #include <cstddef>
40 #include <cstdint>
41 #include <deque>
42 #include <iterator>
43 #include <set>
44 #include <string>
45 #include <vector>
47 using namespace llvm;
49 cl::OptionCategory RegisterInfoCat("Options for -gen-register-info");
51 static cl::opt<bool>
52 RegisterInfoDebug("register-info-debug", cl::init(false),
53 cl::desc("Dump register information to help debugging"),
54 cl::cat(RegisterInfoCat));
56 namespace {
58 class RegisterInfoEmitter {
59 CodeGenTarget Target;
60 RecordKeeper &Records;
62 public:
63 RegisterInfoEmitter(RecordKeeper &R) : Target(R), Records(R) {
64 CodeGenRegBank &RegBank = Target.getRegBank();
65 RegBank.computeDerivedInfo();
68 // runEnums - Print out enum values for all of the registers.
69 void runEnums(raw_ostream &o, CodeGenTarget &Target, CodeGenRegBank &Bank);
71 // runMCDesc - Print out MC register descriptions.
72 void runMCDesc(raw_ostream &o, CodeGenTarget &Target, CodeGenRegBank &Bank);
74 // runTargetHeader - Emit a header fragment for the register info emitter.
75 void runTargetHeader(raw_ostream &o, CodeGenTarget &Target,
76 CodeGenRegBank &Bank);
78 // runTargetDesc - Output the target register and register file descriptions.
79 void runTargetDesc(raw_ostream &o, CodeGenTarget &Target,
80 CodeGenRegBank &Bank);
82 // run - Output the register file description.
83 void run(raw_ostream &o);
85 void debugDump(raw_ostream &OS);
87 private:
88 void EmitRegMapping(raw_ostream &o, const std::deque<CodeGenRegister> &Regs,
89 bool isCtor);
90 void EmitRegMappingTables(raw_ostream &o,
91 const std::deque<CodeGenRegister> &Regs,
92 bool isCtor);
93 void EmitRegUnitPressure(raw_ostream &OS, const CodeGenRegBank &RegBank,
94 const std::string &ClassName);
95 void emitComposeSubRegIndices(raw_ostream &OS, CodeGenRegBank &RegBank,
96 const std::string &ClassName);
97 void emitComposeSubRegIndexLaneMask(raw_ostream &OS, CodeGenRegBank &RegBank,
98 const std::string &ClassName);
101 } // end anonymous namespace
103 // runEnums - Print out enum values for all of the registers.
104 void RegisterInfoEmitter::runEnums(raw_ostream &OS,
105 CodeGenTarget &Target, CodeGenRegBank &Bank) {
106 const auto &Registers = Bank.getRegisters();
108 // Register enums are stored as uint16_t in the tables. Make sure we'll fit.
109 assert(Registers.size() <= 0xffff && "Too many regs to fit in tables");
111 StringRef Namespace = Registers.front().TheDef->getValueAsString("Namespace");
113 emitSourceFileHeader("Target Register Enum Values", OS);
115 OS << "\n#ifdef GET_REGINFO_ENUM\n";
116 OS << "#undef GET_REGINFO_ENUM\n\n";
118 OS << "namespace llvm {\n\n";
120 OS << "class MCRegisterClass;\n"
121 << "extern const MCRegisterClass " << Target.getName()
122 << "MCRegisterClasses[];\n\n";
124 if (!Namespace.empty())
125 OS << "namespace " << Namespace << " {\n";
126 OS << "enum {\n NoRegister,\n";
128 for (const auto &Reg : Registers)
129 OS << " " << Reg.getName() << " = " << Reg.EnumValue << ",\n";
130 assert(Registers.size() == Registers.back().EnumValue &&
131 "Register enum value mismatch!");
132 OS << " NUM_TARGET_REGS // " << Registers.size()+1 << "\n";
133 OS << "};\n";
134 if (!Namespace.empty())
135 OS << "} // end namespace " << Namespace << "\n";
137 const auto &RegisterClasses = Bank.getRegClasses();
138 if (!RegisterClasses.empty()) {
140 // RegisterClass enums are stored as uint16_t in the tables.
141 assert(RegisterClasses.size() <= 0xffff &&
142 "Too many register classes to fit in tables");
144 OS << "\n// Register classes\n\n";
145 if (!Namespace.empty())
146 OS << "namespace " << Namespace << " {\n";
147 OS << "enum {\n";
148 for (const auto &RC : RegisterClasses)
149 OS << " " << RC.getIdName() << " = " << RC.EnumValue << ",\n";
150 OS << "\n};\n";
151 if (!Namespace.empty())
152 OS << "} // end namespace " << Namespace << "\n\n";
155 const std::vector<Record*> &RegAltNameIndices = Target.getRegAltNameIndices();
156 // If the only definition is the default NoRegAltName, we don't need to
157 // emit anything.
158 if (RegAltNameIndices.size() > 1) {
159 OS << "\n// Register alternate name indices\n\n";
160 if (!Namespace.empty())
161 OS << "namespace " << Namespace << " {\n";
162 OS << "enum {\n";
163 for (unsigned i = 0, e = RegAltNameIndices.size(); i != e; ++i)
164 OS << " " << RegAltNameIndices[i]->getName() << ",\t// " << i << "\n";
165 OS << " NUM_TARGET_REG_ALT_NAMES = " << RegAltNameIndices.size() << "\n";
166 OS << "};\n";
167 if (!Namespace.empty())
168 OS << "} // end namespace " << Namespace << "\n\n";
171 auto &SubRegIndices = Bank.getSubRegIndices();
172 if (!SubRegIndices.empty()) {
173 OS << "\n// Subregister indices\n\n";
174 std::string Namespace = SubRegIndices.front().getNamespace();
175 if (!Namespace.empty())
176 OS << "namespace " << Namespace << " {\n";
177 OS << "enum : uint16_t {\n NoSubRegister,\n";
178 unsigned i = 0;
179 for (const auto &Idx : SubRegIndices)
180 OS << " " << Idx.getName() << ",\t// " << ++i << "\n";
181 OS << " NUM_TARGET_SUBREGS\n};\n";
182 if (!Namespace.empty())
183 OS << "} // end namespace " << Namespace << "\n\n";
186 OS << "// Register pressure sets enum.\n";
187 if (!Namespace.empty())
188 OS << "namespace " << Namespace << " {\n";
189 OS << "enum RegisterPressureSets {\n";
190 unsigned NumSets = Bank.getNumRegPressureSets();
191 for (unsigned i = 0; i < NumSets; ++i ) {
192 const RegUnitSet &RegUnits = Bank.getRegSetAt(i);
193 OS << " " << RegUnits.Name << " = " << i << ",\n";
195 OS << "};\n";
196 if (!Namespace.empty())
197 OS << "} // end namespace " << Namespace << '\n';
198 OS << '\n';
200 OS << "} // end namespace llvm\n\n";
201 OS << "#endif // GET_REGINFO_ENUM\n\n";
204 static void printInt(raw_ostream &OS, int Val) {
205 OS << Val;
208 void RegisterInfoEmitter::
209 EmitRegUnitPressure(raw_ostream &OS, const CodeGenRegBank &RegBank,
210 const std::string &ClassName) {
211 unsigned NumRCs = RegBank.getRegClasses().size();
212 unsigned NumSets = RegBank.getNumRegPressureSets();
214 OS << "/// Get the weight in units of pressure for this register class.\n"
215 << "const RegClassWeight &" << ClassName << "::\n"
216 << "getRegClassWeight(const TargetRegisterClass *RC) const {\n"
217 << " static const RegClassWeight RCWeightTable[] = {\n";
218 for (const auto &RC : RegBank.getRegClasses()) {
219 const CodeGenRegister::Vec &Regs = RC.getMembers();
220 OS << " {" << RC.getWeight(RegBank) << ", ";
221 if (Regs.empty() || RC.Artificial)
222 OS << '0';
223 else {
224 std::vector<unsigned> RegUnits;
225 RC.buildRegUnitSet(RegBank, RegUnits);
226 OS << RegBank.getRegUnitSetWeight(RegUnits);
228 OS << "}, \t// " << RC.getName() << "\n";
230 OS << " };\n"
231 << " return RCWeightTable[RC->getID()];\n"
232 << "}\n\n";
234 // Reasonable targets (not ARMv7) have unit weight for all units, so don't
235 // bother generating a table.
236 bool RegUnitsHaveUnitWeight = true;
237 for (unsigned UnitIdx = 0, UnitEnd = RegBank.getNumNativeRegUnits();
238 UnitIdx < UnitEnd; ++UnitIdx) {
239 if (RegBank.getRegUnit(UnitIdx).Weight > 1)
240 RegUnitsHaveUnitWeight = false;
242 OS << "/// Get the weight in units of pressure for this register unit.\n"
243 << "unsigned " << ClassName << "::\n"
244 << "getRegUnitWeight(unsigned RegUnit) const {\n"
245 << " assert(RegUnit < " << RegBank.getNumNativeRegUnits()
246 << " && \"invalid register unit\");\n";
247 if (!RegUnitsHaveUnitWeight) {
248 OS << " static const uint8_t RUWeightTable[] = {\n ";
249 for (unsigned UnitIdx = 0, UnitEnd = RegBank.getNumNativeRegUnits();
250 UnitIdx < UnitEnd; ++UnitIdx) {
251 const RegUnit &RU = RegBank.getRegUnit(UnitIdx);
252 assert(RU.Weight < 256 && "RegUnit too heavy");
253 OS << RU.Weight << ", ";
255 OS << "};\n"
256 << " return RUWeightTable[RegUnit];\n";
258 else {
259 OS << " // All register units have unit weight.\n"
260 << " return 1;\n";
262 OS << "}\n\n";
264 OS << "\n"
265 << "// Get the number of dimensions of register pressure.\n"
266 << "unsigned " << ClassName << "::getNumRegPressureSets() const {\n"
267 << " return " << NumSets << ";\n}\n\n";
269 OS << "// Get the name of this register unit pressure set.\n"
270 << "const char *" << ClassName << "::\n"
271 << "getRegPressureSetName(unsigned Idx) const {\n"
272 << " static const char *PressureNameTable[] = {\n";
273 unsigned MaxRegUnitWeight = 0;
274 for (unsigned i = 0; i < NumSets; ++i ) {
275 const RegUnitSet &RegUnits = RegBank.getRegSetAt(i);
276 MaxRegUnitWeight = std::max(MaxRegUnitWeight, RegUnits.Weight);
277 OS << " \"" << RegUnits.Name << "\",\n";
279 OS << " };\n"
280 << " return PressureNameTable[Idx];\n"
281 << "}\n\n";
283 OS << "// Get the register unit pressure limit for this dimension.\n"
284 << "// This limit must be adjusted dynamically for reserved registers.\n"
285 << "unsigned " << ClassName << "::\n"
286 << "getRegPressureSetLimit(const MachineFunction &MF, unsigned Idx) const "
287 "{\n"
288 << " static const " << getMinimalTypeForRange(MaxRegUnitWeight, 32)
289 << " PressureLimitTable[] = {\n";
290 for (unsigned i = 0; i < NumSets; ++i ) {
291 const RegUnitSet &RegUnits = RegBank.getRegSetAt(i);
292 OS << " " << RegUnits.Weight << ", \t// " << i << ": "
293 << RegUnits.Name << "\n";
295 OS << " };\n"
296 << " return PressureLimitTable[Idx];\n"
297 << "}\n\n";
299 SequenceToOffsetTable<std::vector<int>> PSetsSeqs;
301 // This table may be larger than NumRCs if some register units needed a list
302 // of unit sets that did not correspond to a register class.
303 unsigned NumRCUnitSets = RegBank.getNumRegClassPressureSetLists();
304 std::vector<std::vector<int>> PSets(NumRCUnitSets);
306 for (unsigned i = 0, e = NumRCUnitSets; i != e; ++i) {
307 ArrayRef<unsigned> PSetIDs = RegBank.getRCPressureSetIDs(i);
308 PSets[i].reserve(PSetIDs.size());
309 for (unsigned PSetID : PSetIDs) {
310 PSets[i].push_back(RegBank.getRegPressureSet(PSetID).Order);
312 llvm::sort(PSets[i]);
313 PSetsSeqs.add(PSets[i]);
316 PSetsSeqs.layout();
318 OS << "/// Table of pressure sets per register class or unit.\n"
319 << "static const int RCSetsTable[] = {\n";
320 PSetsSeqs.emit(OS, printInt, "-1");
321 OS << "};\n\n";
323 OS << "/// Get the dimensions of register pressure impacted by this "
324 << "register class.\n"
325 << "/// Returns a -1 terminated array of pressure set IDs\n"
326 << "const int *" << ClassName << "::\n"
327 << "getRegClassPressureSets(const TargetRegisterClass *RC) const {\n";
328 OS << " static const " << getMinimalTypeForRange(PSetsSeqs.size() - 1, 32)
329 << " RCSetStartTable[] = {\n ";
330 for (unsigned i = 0, e = NumRCs; i != e; ++i) {
331 OS << PSetsSeqs.get(PSets[i]) << ",";
333 OS << "};\n"
334 << " return &RCSetsTable[RCSetStartTable[RC->getID()]];\n"
335 << "}\n\n";
337 OS << "/// Get the dimensions of register pressure impacted by this "
338 << "register unit.\n"
339 << "/// Returns a -1 terminated array of pressure set IDs\n"
340 << "const int *" << ClassName << "::\n"
341 << "getRegUnitPressureSets(unsigned RegUnit) const {\n"
342 << " assert(RegUnit < " << RegBank.getNumNativeRegUnits()
343 << " && \"invalid register unit\");\n";
344 OS << " static const " << getMinimalTypeForRange(PSetsSeqs.size() - 1, 32)
345 << " RUSetStartTable[] = {\n ";
346 for (unsigned UnitIdx = 0, UnitEnd = RegBank.getNumNativeRegUnits();
347 UnitIdx < UnitEnd; ++UnitIdx) {
348 OS << PSetsSeqs.get(PSets[RegBank.getRegUnit(UnitIdx).RegClassUnitSetsIdx])
349 << ",";
351 OS << "};\n"
352 << " return &RCSetsTable[RUSetStartTable[RegUnit]];\n"
353 << "}\n\n";
356 using DwarfRegNumsMapPair = std::pair<Record*, std::vector<int64_t>>;
357 using DwarfRegNumsVecTy = std::vector<DwarfRegNumsMapPair>;
359 static void finalizeDwarfRegNumsKeys(DwarfRegNumsVecTy &DwarfRegNums) {
360 // Sort and unique to get a map-like vector. We want the last assignment to
361 // match previous behaviour.
362 llvm::stable_sort(DwarfRegNums, on_first<LessRecordRegister>());
363 // Warn about duplicate assignments.
364 const Record *LastSeenReg = nullptr;
365 for (const auto &X : DwarfRegNums) {
366 const auto &Reg = X.first;
367 // The only way LessRecordRegister can return equal is if they're the same
368 // string. Use simple equality instead.
369 if (LastSeenReg && Reg->getName() == LastSeenReg->getName())
370 PrintWarning(Reg->getLoc(), Twine("DWARF numbers for register ") +
371 getQualifiedName(Reg) +
372 "specified multiple times");
373 LastSeenReg = Reg;
375 auto Last = std::unique(
376 DwarfRegNums.begin(), DwarfRegNums.end(),
377 [](const DwarfRegNumsMapPair &A, const DwarfRegNumsMapPair &B) {
378 return A.first->getName() == B.first->getName();
380 DwarfRegNums.erase(Last, DwarfRegNums.end());
383 void RegisterInfoEmitter::EmitRegMappingTables(
384 raw_ostream &OS, const std::deque<CodeGenRegister> &Regs, bool isCtor) {
385 // Collect all information about dwarf register numbers
386 DwarfRegNumsVecTy DwarfRegNums;
388 // First, just pull all provided information to the map
389 unsigned maxLength = 0;
390 for (auto &RE : Regs) {
391 Record *Reg = RE.TheDef;
392 std::vector<int64_t> RegNums = Reg->getValueAsListOfInts("DwarfNumbers");
393 maxLength = std::max((size_t)maxLength, RegNums.size());
394 DwarfRegNums.emplace_back(Reg, std::move(RegNums));
396 finalizeDwarfRegNumsKeys(DwarfRegNums);
398 if (!maxLength)
399 return;
401 // Now we know maximal length of number list. Append -1's, where needed
402 for (auto &DwarfRegNum : DwarfRegNums)
403 for (unsigned I = DwarfRegNum.second.size(), E = maxLength; I != E; ++I)
404 DwarfRegNum.second.push_back(-1);
406 StringRef Namespace = Regs.front().TheDef->getValueAsString("Namespace");
408 OS << "// " << Namespace << " Dwarf<->LLVM register mappings.\n";
410 // Emit reverse information about the dwarf register numbers.
411 for (unsigned j = 0; j < 2; ++j) {
412 for (unsigned I = 0, E = maxLength; I != E; ++I) {
413 OS << "extern const MCRegisterInfo::DwarfLLVMRegPair " << Namespace;
414 OS << (j == 0 ? "DwarfFlavour" : "EHFlavour");
415 OS << I << "Dwarf2L[]";
417 if (!isCtor) {
418 OS << " = {\n";
420 // Store the mapping sorted by the LLVM reg num so lookup can be done
421 // with a binary search.
422 std::map<uint64_t, Record*> Dwarf2LMap;
423 for (auto &DwarfRegNum : DwarfRegNums) {
424 int DwarfRegNo = DwarfRegNum.second[I];
425 if (DwarfRegNo < 0)
426 continue;
427 Dwarf2LMap[DwarfRegNo] = DwarfRegNum.first;
430 for (auto &I : Dwarf2LMap)
431 OS << " { " << I.first << "U, " << getQualifiedName(I.second)
432 << " },\n";
434 OS << "};\n";
435 } else {
436 OS << ";\n";
439 // We have to store the size in a const global, it's used in multiple
440 // places.
441 OS << "extern const unsigned " << Namespace
442 << (j == 0 ? "DwarfFlavour" : "EHFlavour") << I << "Dwarf2LSize";
443 if (!isCtor)
444 OS << " = std::size(" << Namespace
445 << (j == 0 ? "DwarfFlavour" : "EHFlavour") << I << "Dwarf2L);\n\n";
446 else
447 OS << ";\n\n";
451 for (auto &RE : Regs) {
452 Record *Reg = RE.TheDef;
453 const RecordVal *V = Reg->getValue("DwarfAlias");
454 if (!V || !V->getValue())
455 continue;
457 DefInit *DI = cast<DefInit>(V->getValue());
458 Record *Alias = DI->getDef();
459 const auto &AliasIter = llvm::lower_bound(
460 DwarfRegNums, Alias, [](const DwarfRegNumsMapPair &A, const Record *B) {
461 return LessRecordRegister()(A.first, B);
463 assert(AliasIter != DwarfRegNums.end() && AliasIter->first == Alias &&
464 "Expected Alias to be present in map");
465 const auto &RegIter = llvm::lower_bound(
466 DwarfRegNums, Reg, [](const DwarfRegNumsMapPair &A, const Record *B) {
467 return LessRecordRegister()(A.first, B);
469 assert(RegIter != DwarfRegNums.end() && RegIter->first == Reg &&
470 "Expected Reg to be present in map");
471 RegIter->second = AliasIter->second;
474 // Emit information about the dwarf register numbers.
475 for (unsigned j = 0; j < 2; ++j) {
476 for (unsigned i = 0, e = maxLength; i != e; ++i) {
477 OS << "extern const MCRegisterInfo::DwarfLLVMRegPair " << Namespace;
478 OS << (j == 0 ? "DwarfFlavour" : "EHFlavour");
479 OS << i << "L2Dwarf[]";
480 if (!isCtor) {
481 OS << " = {\n";
482 // Store the mapping sorted by the Dwarf reg num so lookup can be done
483 // with a binary search.
484 for (auto &DwarfRegNum : DwarfRegNums) {
485 int RegNo = DwarfRegNum.second[i];
486 if (RegNo == -1) // -1 is the default value, don't emit a mapping.
487 continue;
489 OS << " { " << getQualifiedName(DwarfRegNum.first) << ", " << RegNo
490 << "U },\n";
492 OS << "};\n";
493 } else {
494 OS << ";\n";
497 // We have to store the size in a const global, it's used in multiple
498 // places.
499 OS << "extern const unsigned " << Namespace
500 << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i << "L2DwarfSize";
501 if (!isCtor)
502 OS << " = std::size(" << Namespace
503 << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i << "L2Dwarf);\n\n";
504 else
505 OS << ";\n\n";
510 void RegisterInfoEmitter::EmitRegMapping(
511 raw_ostream &OS, const std::deque<CodeGenRegister> &Regs, bool isCtor) {
512 // Emit the initializer so the tables from EmitRegMappingTables get wired up
513 // to the MCRegisterInfo object.
514 unsigned maxLength = 0;
515 for (auto &RE : Regs) {
516 Record *Reg = RE.TheDef;
517 maxLength = std::max((size_t)maxLength,
518 Reg->getValueAsListOfInts("DwarfNumbers").size());
521 if (!maxLength)
522 return;
524 StringRef Namespace = Regs.front().TheDef->getValueAsString("Namespace");
526 // Emit reverse information about the dwarf register numbers.
527 for (unsigned j = 0; j < 2; ++j) {
528 OS << " switch (";
529 if (j == 0)
530 OS << "DwarfFlavour";
531 else
532 OS << "EHFlavour";
533 OS << ") {\n"
534 << " default:\n"
535 << " llvm_unreachable(\"Unknown DWARF flavour\");\n";
537 for (unsigned i = 0, e = maxLength; i != e; ++i) {
538 OS << " case " << i << ":\n";
539 OS << " ";
540 if (!isCtor)
541 OS << "RI->";
542 std::string Tmp;
543 raw_string_ostream(Tmp) << Namespace
544 << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i
545 << "Dwarf2L";
546 OS << "mapDwarfRegsToLLVMRegs(" << Tmp << ", " << Tmp << "Size, ";
547 if (j == 0)
548 OS << "false";
549 else
550 OS << "true";
551 OS << ");\n";
552 OS << " break;\n";
554 OS << " }\n";
557 // Emit information about the dwarf register numbers.
558 for (unsigned j = 0; j < 2; ++j) {
559 OS << " switch (";
560 if (j == 0)
561 OS << "DwarfFlavour";
562 else
563 OS << "EHFlavour";
564 OS << ") {\n"
565 << " default:\n"
566 << " llvm_unreachable(\"Unknown DWARF flavour\");\n";
568 for (unsigned i = 0, e = maxLength; i != e; ++i) {
569 OS << " case " << i << ":\n";
570 OS << " ";
571 if (!isCtor)
572 OS << "RI->";
573 std::string Tmp;
574 raw_string_ostream(Tmp) << Namespace
575 << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i
576 << "L2Dwarf";
577 OS << "mapLLVMRegsToDwarfRegs(" << Tmp << ", " << Tmp << "Size, ";
578 if (j == 0)
579 OS << "false";
580 else
581 OS << "true";
582 OS << ");\n";
583 OS << " break;\n";
585 OS << " }\n";
589 // Print a BitVector as a sequence of hex numbers using a little-endian mapping.
590 // Width is the number of bits per hex number.
591 static void printBitVectorAsHex(raw_ostream &OS,
592 const BitVector &Bits,
593 unsigned Width) {
594 assert(Width <= 32 && "Width too large");
595 unsigned Digits = (Width + 3) / 4;
596 for (unsigned i = 0, e = Bits.size(); i < e; i += Width) {
597 unsigned Value = 0;
598 for (unsigned j = 0; j != Width && i + j != e; ++j)
599 Value |= Bits.test(i + j) << j;
600 OS << format("0x%0*x, ", Digits, Value);
604 // Helper to emit a set of bits into a constant byte array.
605 class BitVectorEmitter {
606 BitVector Values;
607 public:
608 void add(unsigned v) {
609 if (v >= Values.size())
610 Values.resize(((v/8)+1)*8); // Round up to the next byte.
611 Values[v] = true;
614 void print(raw_ostream &OS) {
615 printBitVectorAsHex(OS, Values, 8);
619 static void printSimpleValueType(raw_ostream &OS, MVT::SimpleValueType VT) {
620 OS << getEnumName(VT);
623 static void printSubRegIndex(raw_ostream &OS, const CodeGenSubRegIndex *Idx) {
624 OS << Idx->EnumValue;
627 // Differentially encoded register and regunit lists allow for better
628 // compression on regular register banks. The sequence is computed from the
629 // differential list as:
631 // out[0] = InitVal;
632 // out[n+1] = out[n] + diff[n]; // n = 0, 1, ...
634 // The initial value depends on the specific list. The list is terminated by a
635 // 0 differential which means we can't encode repeated elements.
637 typedef SmallVector<int16_t, 4> DiffVec;
638 typedef SmallVector<LaneBitmask, 4> MaskVec;
640 // Fills V with differentials between every two consecutive elements of List.
641 static DiffVec &diffEncode(DiffVec &V, SparseBitVector<> List) {
642 assert(V.empty() && "Clear DiffVec before diffEncode.");
643 SparseBitVector<>::iterator I = List.begin(), E = List.end();
644 unsigned Val = *I;
645 while (++I != E) {
646 unsigned Cur = *I;
647 V.push_back(Cur - Val);
648 Val = Cur;
650 return V;
653 template<typename Iter>
654 static
655 DiffVec &diffEncode(DiffVec &V, unsigned InitVal, Iter Begin, Iter End) {
656 assert(V.empty() && "Clear DiffVec before diffEncode.");
657 unsigned Val = InitVal;
658 for (Iter I = Begin; I != End; ++I) {
659 unsigned Cur = (*I)->EnumValue;
660 V.push_back(Cur - Val);
661 Val = Cur;
663 return V;
666 static void printDiff16(raw_ostream &OS, int16_t Val) { OS << Val; }
668 static void printMask(raw_ostream &OS, LaneBitmask Val) {
669 OS << "LaneBitmask(0x" << PrintLaneMask(Val) << ')';
672 // Try to combine Idx's compose map into Vec if it is compatible.
673 // Return false if it's not possible.
674 static bool combine(const CodeGenSubRegIndex *Idx,
675 SmallVectorImpl<CodeGenSubRegIndex*> &Vec) {
676 const CodeGenSubRegIndex::CompMap &Map = Idx->getComposites();
677 for (const auto &I : Map) {
678 CodeGenSubRegIndex *&Entry = Vec[I.first->EnumValue - 1];
679 if (Entry && Entry != I.second)
680 return false;
683 // All entries are compatible. Make it so.
684 for (const auto &I : Map) {
685 auto *&Entry = Vec[I.first->EnumValue - 1];
686 assert((!Entry || Entry == I.second) &&
687 "Expected EnumValue to be unique");
688 Entry = I.second;
690 return true;
693 void
694 RegisterInfoEmitter::emitComposeSubRegIndices(raw_ostream &OS,
695 CodeGenRegBank &RegBank,
696 const std::string &ClName) {
697 const auto &SubRegIndices = RegBank.getSubRegIndices();
698 OS << "unsigned " << ClName
699 << "::composeSubRegIndicesImpl(unsigned IdxA, unsigned IdxB) const {\n";
701 // Many sub-register indexes are composition-compatible, meaning that
703 // compose(IdxA, IdxB) == compose(IdxA', IdxB)
705 // for many IdxA, IdxA' pairs. Not all sub-register indexes can be composed.
706 // The illegal entries can be use as wildcards to compress the table further.
708 // Map each Sub-register index to a compatible table row.
709 SmallVector<unsigned, 4> RowMap;
710 SmallVector<SmallVector<CodeGenSubRegIndex*, 4>, 4> Rows;
712 auto SubRegIndicesSize =
713 std::distance(SubRegIndices.begin(), SubRegIndices.end());
714 for (const auto &Idx : SubRegIndices) {
715 unsigned Found = ~0u;
716 for (unsigned r = 0, re = Rows.size(); r != re; ++r) {
717 if (combine(&Idx, Rows[r])) {
718 Found = r;
719 break;
722 if (Found == ~0u) {
723 Found = Rows.size();
724 Rows.resize(Found + 1);
725 Rows.back().resize(SubRegIndicesSize);
726 combine(&Idx, Rows.back());
728 RowMap.push_back(Found);
731 // Output the row map if there is multiple rows.
732 if (Rows.size() > 1) {
733 OS << " static const " << getMinimalTypeForRange(Rows.size(), 32)
734 << " RowMap[" << SubRegIndicesSize << "] = {\n ";
735 for (unsigned i = 0, e = SubRegIndicesSize; i != e; ++i)
736 OS << RowMap[i] << ", ";
737 OS << "\n };\n";
740 // Output the rows.
741 OS << " static const " << getMinimalTypeForRange(SubRegIndicesSize + 1, 32)
742 << " Rows[" << Rows.size() << "][" << SubRegIndicesSize << "] = {\n";
743 for (unsigned r = 0, re = Rows.size(); r != re; ++r) {
744 OS << " { ";
745 for (unsigned i = 0, e = SubRegIndicesSize; i != e; ++i)
746 if (Rows[r][i])
747 OS << Rows[r][i]->getQualifiedName() << ", ";
748 else
749 OS << "0, ";
750 OS << "},\n";
752 OS << " };\n\n";
754 OS << " --IdxA; assert(IdxA < " << SubRegIndicesSize << "); (void) IdxA;\n"
755 << " --IdxB; assert(IdxB < " << SubRegIndicesSize << ");\n";
756 if (Rows.size() > 1)
757 OS << " return Rows[RowMap[IdxA]][IdxB];\n";
758 else
759 OS << " return Rows[0][IdxB];\n";
760 OS << "}\n\n";
763 void
764 RegisterInfoEmitter::emitComposeSubRegIndexLaneMask(raw_ostream &OS,
765 CodeGenRegBank &RegBank,
766 const std::string &ClName) {
767 // See the comments in computeSubRegLaneMasks() for our goal here.
768 const auto &SubRegIndices = RegBank.getSubRegIndices();
770 // Create a list of Mask+Rotate operations, with equivalent entries merged.
771 SmallVector<unsigned, 4> SubReg2SequenceIndexMap;
772 SmallVector<SmallVector<MaskRolPair, 1>, 4> Sequences;
773 for (const auto &Idx : SubRegIndices) {
774 const SmallVector<MaskRolPair, 1> &IdxSequence
775 = Idx.CompositionLaneMaskTransform;
777 unsigned Found = ~0u;
778 unsigned SIdx = 0;
779 unsigned NextSIdx;
780 for (size_t s = 0, se = Sequences.size(); s != se; ++s, SIdx = NextSIdx) {
781 SmallVectorImpl<MaskRolPair> &Sequence = Sequences[s];
782 NextSIdx = SIdx + Sequence.size() + 1;
783 if (Sequence == IdxSequence) {
784 Found = SIdx;
785 break;
788 if (Found == ~0u) {
789 Sequences.push_back(IdxSequence);
790 Found = SIdx;
792 SubReg2SequenceIndexMap.push_back(Found);
795 OS << " struct MaskRolOp {\n"
796 " LaneBitmask Mask;\n"
797 " uint8_t RotateLeft;\n"
798 " };\n"
799 " static const MaskRolOp LaneMaskComposeSequences[] = {\n";
800 unsigned Idx = 0;
801 for (size_t s = 0, se = Sequences.size(); s != se; ++s) {
802 OS << " ";
803 const SmallVectorImpl<MaskRolPair> &Sequence = Sequences[s];
804 for (size_t p = 0, pe = Sequence.size(); p != pe; ++p) {
805 const MaskRolPair &P = Sequence[p];
806 printMask(OS << "{ ", P.Mask);
807 OS << format(", %2u }, ", P.RotateLeft);
809 OS << "{ LaneBitmask::getNone(), 0 }";
810 if (s+1 != se)
811 OS << ", ";
812 OS << " // Sequence " << Idx << "\n";
813 Idx += Sequence.size() + 1;
815 auto *IntType = getMinimalTypeForRange(*std::max_element(
816 SubReg2SequenceIndexMap.begin(), SubReg2SequenceIndexMap.end()));
817 OS << " };\n"
818 " static const "
819 << IntType << " CompositeSequences[] = {\n";
820 for (size_t i = 0, e = SubRegIndices.size(); i != e; ++i) {
821 OS << " ";
822 OS << SubReg2SequenceIndexMap[i];
823 if (i+1 != e)
824 OS << ",";
825 OS << " // to " << SubRegIndices[i].getName() << "\n";
827 OS << " };\n\n";
829 OS << "LaneBitmask " << ClName
830 << "::composeSubRegIndexLaneMaskImpl(unsigned IdxA, LaneBitmask LaneMask)"
831 " const {\n"
832 " --IdxA; assert(IdxA < " << SubRegIndices.size()
833 << " && \"Subregister index out of bounds\");\n"
834 " LaneBitmask Result;\n"
835 " for (const MaskRolOp *Ops =\n"
836 " &LaneMaskComposeSequences[CompositeSequences[IdxA]];\n"
837 " Ops->Mask.any(); ++Ops) {\n"
838 " LaneBitmask::Type M = LaneMask.getAsInteger() & Ops->Mask.getAsInteger();\n"
839 " if (unsigned S = Ops->RotateLeft)\n"
840 " Result |= LaneBitmask((M << S) | (M >> (LaneBitmask::BitWidth - S)));\n"
841 " else\n"
842 " Result |= LaneBitmask(M);\n"
843 " }\n"
844 " return Result;\n"
845 "}\n\n";
847 OS << "LaneBitmask " << ClName
848 << "::reverseComposeSubRegIndexLaneMaskImpl(unsigned IdxA, "
849 " LaneBitmask LaneMask) const {\n"
850 " LaneMask &= getSubRegIndexLaneMask(IdxA);\n"
851 " --IdxA; assert(IdxA < " << SubRegIndices.size()
852 << " && \"Subregister index out of bounds\");\n"
853 " LaneBitmask Result;\n"
854 " for (const MaskRolOp *Ops =\n"
855 " &LaneMaskComposeSequences[CompositeSequences[IdxA]];\n"
856 " Ops->Mask.any(); ++Ops) {\n"
857 " LaneBitmask::Type M = LaneMask.getAsInteger();\n"
858 " if (unsigned S = Ops->RotateLeft)\n"
859 " Result |= LaneBitmask((M >> S) | (M << (LaneBitmask::BitWidth - S)));\n"
860 " else\n"
861 " Result |= LaneBitmask(M);\n"
862 " }\n"
863 " return Result;\n"
864 "}\n\n";
868 // runMCDesc - Print out MC register descriptions.
870 void
871 RegisterInfoEmitter::runMCDesc(raw_ostream &OS, CodeGenTarget &Target,
872 CodeGenRegBank &RegBank) {
873 emitSourceFileHeader("MC Register Information", OS);
875 OS << "\n#ifdef GET_REGINFO_MC_DESC\n";
876 OS << "#undef GET_REGINFO_MC_DESC\n\n";
878 const auto &Regs = RegBank.getRegisters();
880 auto &SubRegIndices = RegBank.getSubRegIndices();
881 // The lists of sub-registers and super-registers go in the same array. That
882 // allows us to share suffixes.
883 typedef std::vector<const CodeGenRegister*> RegVec;
885 // Differentially encoded lists.
886 SequenceToOffsetTable<DiffVec> DiffSeqs;
887 SmallVector<DiffVec, 4> SubRegLists(Regs.size());
888 SmallVector<DiffVec, 4> SuperRegLists(Regs.size());
889 SmallVector<DiffVec, 4> RegUnitLists(Regs.size());
891 // List of lane masks accompanying register unit sequences.
892 SequenceToOffsetTable<MaskVec> LaneMaskSeqs;
893 SmallVector<MaskVec, 4> RegUnitLaneMasks(Regs.size());
895 // Keep track of sub-register names as well. These are not differentially
896 // encoded.
897 typedef SmallVector<const CodeGenSubRegIndex*, 4> SubRegIdxVec;
898 SequenceToOffsetTable<SubRegIdxVec, deref<std::less<>>> SubRegIdxSeqs;
899 SmallVector<SubRegIdxVec, 4> SubRegIdxLists(Regs.size());
901 SequenceToOffsetTable<std::string> RegStrings;
903 // Precompute register lists for the SequenceToOffsetTable.
904 unsigned i = 0;
905 for (auto I = Regs.begin(), E = Regs.end(); I != E; ++I, ++i) {
906 const auto &Reg = *I;
907 RegStrings.add(std::string(Reg.getName()));
909 // Compute the ordered sub-register list.
910 SetVector<const CodeGenRegister*> SR;
911 Reg.addSubRegsPreOrder(SR, RegBank);
912 diffEncode(SubRegLists[i], Reg.EnumValue, SR.begin(), SR.end());
913 DiffSeqs.add(SubRegLists[i]);
915 // Compute the corresponding sub-register indexes.
916 SubRegIdxVec &SRIs = SubRegIdxLists[i];
917 for (const CodeGenRegister *S : SR)
918 SRIs.push_back(Reg.getSubRegIndex(S));
919 SubRegIdxSeqs.add(SRIs);
921 // Super-registers are already computed.
922 const RegVec &SuperRegList = Reg.getSuperRegs();
923 diffEncode(SuperRegLists[i], Reg.EnumValue, SuperRegList.begin(),
924 SuperRegList.end());
925 DiffSeqs.add(SuperRegLists[i]);
927 const SparseBitVector<> &RUs = Reg.getNativeRegUnits();
928 DiffSeqs.add(diffEncode(RegUnitLists[i], RUs));
930 const auto &RUMasks = Reg.getRegUnitLaneMasks();
931 MaskVec &LaneMaskVec = RegUnitLaneMasks[i];
932 assert(LaneMaskVec.empty());
933 llvm::append_range(LaneMaskVec, RUMasks);
934 LaneMaskSeqs.add(LaneMaskVec);
937 // Compute the final layout of the sequence table.
938 DiffSeqs.layout();
939 LaneMaskSeqs.layout();
940 SubRegIdxSeqs.layout();
942 OS << "namespace llvm {\n\n";
944 const std::string &TargetName = std::string(Target.getName());
946 // Emit the shared table of differential lists.
947 OS << "extern const int16_t " << TargetName << "RegDiffLists[] = {\n";
948 DiffSeqs.emit(OS, printDiff16);
949 OS << "};\n\n";
951 // Emit the shared table of regunit lane mask sequences.
952 OS << "extern const LaneBitmask " << TargetName << "LaneMaskLists[] = {\n";
953 // TODO: Omit the terminator since it is never used. The length of this list
954 // is known implicitly from the corresponding reg unit list.
955 LaneMaskSeqs.emit(OS, printMask, "LaneBitmask::getAll()");
956 OS << "};\n\n";
958 // Emit the table of sub-register indexes.
959 OS << "extern const uint16_t " << TargetName << "SubRegIdxLists[] = {\n";
960 SubRegIdxSeqs.emit(OS, printSubRegIndex);
961 OS << "};\n\n";
963 // Emit the table of sub-register index sizes.
964 OS << "extern const MCRegisterInfo::SubRegCoveredBits "
965 << TargetName << "SubRegIdxRanges[] = {\n";
966 OS << " { " << (uint16_t)-1 << ", " << (uint16_t)-1 << " },\n";
967 for (const auto &Idx : SubRegIndices) {
968 OS << " { " << Idx.Offset << ", " << Idx.Size << " },\t// "
969 << Idx.getName() << "\n";
971 OS << "};\n\n";
973 // Emit the string table.
974 RegStrings.layout();
975 RegStrings.emitStringLiteralDef(OS, Twine("extern const char ") + TargetName +
976 "RegStrings[]");
978 OS << "extern const MCRegisterDesc " << TargetName
979 << "RegDesc[] = { // Descriptors\n";
980 OS << " { " << RegStrings.get("") << ", 0, 0, 0, 0, 0 },\n";
982 // Emit the register descriptors now.
983 i = 0;
984 for (const auto &Reg : Regs) {
985 unsigned FirstRU = Reg.getNativeRegUnits().find_first();
986 unsigned Offset = DiffSeqs.get(RegUnitLists[i]);
987 // The value must be kept in sync with MCRegisterInfo.h.
988 constexpr unsigned RegUnitBits = 12;
989 assert(isUInt<RegUnitBits>(FirstRU) && "Too many regunits");
990 assert(isUInt<32 - RegUnitBits>(Offset) && "Offset is too big");
991 OS << " { " << RegStrings.get(std::string(Reg.getName())) << ", "
992 << DiffSeqs.get(SubRegLists[i]) << ", " << DiffSeqs.get(SuperRegLists[i])
993 << ", " << SubRegIdxSeqs.get(SubRegIdxLists[i]) << ", "
994 << (Offset << RegUnitBits | FirstRU) << ", "
995 << LaneMaskSeqs.get(RegUnitLaneMasks[i]) << " },\n";
996 ++i;
998 OS << "};\n\n"; // End of register descriptors...
1000 // Emit the table of register unit roots. Each regunit has one or two root
1001 // registers.
1002 OS << "extern const MCPhysReg " << TargetName << "RegUnitRoots[][2] = {\n";
1003 for (unsigned i = 0, e = RegBank.getNumNativeRegUnits(); i != e; ++i) {
1004 ArrayRef<const CodeGenRegister*> Roots = RegBank.getRegUnit(i).getRoots();
1005 assert(!Roots.empty() && "All regunits must have a root register.");
1006 assert(Roots.size() <= 2 && "More than two roots not supported yet.");
1007 OS << " { ";
1008 ListSeparator LS;
1009 for (const CodeGenRegister *R : Roots)
1010 OS << LS << getQualifiedName(R->TheDef);
1011 OS << " },\n";
1013 OS << "};\n\n";
1015 const auto &RegisterClasses = RegBank.getRegClasses();
1017 // Loop over all of the register classes... emitting each one.
1018 OS << "namespace { // Register classes...\n";
1020 SequenceToOffsetTable<std::string> RegClassStrings;
1022 // Emit the register enum value arrays for each RegisterClass
1023 for (const auto &RC : RegisterClasses) {
1024 ArrayRef<Record*> Order = RC.getOrder();
1026 // Give the register class a legal C name if it's anonymous.
1027 const std::string &Name = RC.getName();
1029 RegClassStrings.add(Name);
1031 // Emit the register list now (unless it would be a zero-length array).
1032 if (!Order.empty()) {
1033 OS << " // " << Name << " Register Class...\n"
1034 << " const MCPhysReg " << Name << "[] = {\n ";
1035 for (Record *Reg : Order) {
1036 OS << getQualifiedName(Reg) << ", ";
1038 OS << "\n };\n\n";
1040 OS << " // " << Name << " Bit set.\n"
1041 << " const uint8_t " << Name << "Bits[] = {\n ";
1042 BitVectorEmitter BVE;
1043 for (Record *Reg : Order) {
1044 BVE.add(Target.getRegBank().getReg(Reg)->EnumValue);
1046 BVE.print(OS);
1047 OS << "\n };\n\n";
1050 OS << "} // end anonymous namespace\n\n";
1052 RegClassStrings.layout();
1053 RegClassStrings.emitStringLiteralDef(
1054 OS, Twine("extern const char ") + TargetName + "RegClassStrings[]");
1056 OS << "extern const MCRegisterClass " << TargetName
1057 << "MCRegisterClasses[] = {\n";
1059 for (const auto &RC : RegisterClasses) {
1060 ArrayRef<Record *> Order = RC.getOrder();
1061 std::string RCName = Order.empty() ? "nullptr" : RC.getName();
1062 std::string RCBitsName = Order.empty() ? "nullptr" : RC.getName() + "Bits";
1063 std::string RCBitsSize = Order.empty() ? "0" : "sizeof(" + RCBitsName + ")";
1064 assert(isInt<8>(RC.CopyCost) && "Copy cost too large.");
1065 uint32_t RegSize = 0;
1066 if (RC.RSI.isSimple())
1067 RegSize = RC.RSI.getSimple().RegSize;
1068 OS << " { " << RCName << ", " << RCBitsName << ", "
1069 << RegClassStrings.get(RC.getName()) << ", " << RC.getOrder().size()
1070 << ", " << RCBitsSize << ", " << RC.getQualifiedIdName() << ", "
1071 << RegSize << ", " << RC.CopyCost << ", "
1072 << (RC.Allocatable ? "true" : "false") << " },\n";
1075 OS << "};\n\n";
1077 EmitRegMappingTables(OS, Regs, false);
1079 // Emit Reg encoding table
1080 OS << "extern const uint16_t " << TargetName;
1081 OS << "RegEncodingTable[] = {\n";
1082 // Add entry for NoRegister
1083 OS << " 0,\n";
1084 for (const auto &RE : Regs) {
1085 Record *Reg = RE.TheDef;
1086 BitsInit *BI = Reg->getValueAsBitsInit("HWEncoding");
1087 uint64_t Value = 0;
1088 for (unsigned b = 0, be = BI->getNumBits(); b != be; ++b) {
1089 if (BitInit *B = dyn_cast<BitInit>(BI->getBit(b)))
1090 Value |= (uint64_t)B->getValue() << b;
1092 OS << " " << Value << ",\n";
1094 OS << "};\n"; // End of HW encoding table
1096 // MCRegisterInfo initialization routine.
1097 OS << "static inline void Init" << TargetName
1098 << "MCRegisterInfo(MCRegisterInfo *RI, unsigned RA, "
1099 << "unsigned DwarfFlavour = 0, unsigned EHFlavour = 0, unsigned PC = 0) "
1100 "{\n"
1101 << " RI->InitMCRegisterInfo(" << TargetName << "RegDesc, "
1102 << Regs.size() + 1 << ", RA, PC, " << TargetName << "MCRegisterClasses, "
1103 << RegisterClasses.size() << ", " << TargetName << "RegUnitRoots, "
1104 << RegBank.getNumNativeRegUnits() << ", " << TargetName << "RegDiffLists, "
1105 << TargetName << "LaneMaskLists, " << TargetName << "RegStrings, "
1106 << TargetName << "RegClassStrings, " << TargetName << "SubRegIdxLists, "
1107 << (std::distance(SubRegIndices.begin(), SubRegIndices.end()) + 1) << ",\n"
1108 << TargetName << "SubRegIdxRanges, " << TargetName
1109 << "RegEncodingTable);\n\n";
1111 EmitRegMapping(OS, Regs, false);
1113 OS << "}\n\n";
1115 OS << "} // end namespace llvm\n\n";
1116 OS << "#endif // GET_REGINFO_MC_DESC\n\n";
1119 void
1120 RegisterInfoEmitter::runTargetHeader(raw_ostream &OS, CodeGenTarget &Target,
1121 CodeGenRegBank &RegBank) {
1122 emitSourceFileHeader("Register Information Header Fragment", OS);
1124 OS << "\n#ifdef GET_REGINFO_HEADER\n";
1125 OS << "#undef GET_REGINFO_HEADER\n\n";
1127 const std::string &TargetName = std::string(Target.getName());
1128 std::string ClassName = TargetName + "GenRegisterInfo";
1130 OS << "#include \"llvm/CodeGen/TargetRegisterInfo.h\"\n\n";
1132 OS << "namespace llvm {\n\n";
1134 OS << "class " << TargetName << "FrameLowering;\n\n";
1136 OS << "struct " << ClassName << " : public TargetRegisterInfo {\n"
1137 << " explicit " << ClassName
1138 << "(unsigned RA, unsigned D = 0, unsigned E = 0,\n"
1139 << " unsigned PC = 0, unsigned HwMode = 0);\n";
1140 if (!RegBank.getSubRegIndices().empty()) {
1141 OS << " unsigned composeSubRegIndicesImpl"
1142 << "(unsigned, unsigned) const override;\n"
1143 << " LaneBitmask composeSubRegIndexLaneMaskImpl"
1144 << "(unsigned, LaneBitmask) const override;\n"
1145 << " LaneBitmask reverseComposeSubRegIndexLaneMaskImpl"
1146 << "(unsigned, LaneBitmask) const override;\n"
1147 << " const TargetRegisterClass *getSubClassWithSubReg"
1148 << "(const TargetRegisterClass *, unsigned) const override;\n"
1149 << " const TargetRegisterClass *getSubRegisterClass"
1150 << "(const TargetRegisterClass *, unsigned) const override;\n";
1152 OS << " const RegClassWeight &getRegClassWeight("
1153 << "const TargetRegisterClass *RC) const override;\n"
1154 << " unsigned getRegUnitWeight(unsigned RegUnit) const override;\n"
1155 << " unsigned getNumRegPressureSets() const override;\n"
1156 << " const char *getRegPressureSetName(unsigned Idx) const override;\n"
1157 << " unsigned getRegPressureSetLimit(const MachineFunction &MF, unsigned "
1158 "Idx) const override;\n"
1159 << " const int *getRegClassPressureSets("
1160 << "const TargetRegisterClass *RC) const override;\n"
1161 << " const int *getRegUnitPressureSets("
1162 << "unsigned RegUnit) const override;\n"
1163 << " ArrayRef<const char *> getRegMaskNames() const override;\n"
1164 << " ArrayRef<const uint32_t *> getRegMasks() const override;\n"
1165 << " bool isGeneralPurposeRegister(const MachineFunction &, "
1166 << "MCRegister) const override;\n"
1167 << " bool isFixedRegister(const MachineFunction &, "
1168 << "MCRegister) const override;\n"
1169 << " bool isArgumentRegister(const MachineFunction &, "
1170 << "MCRegister) const override;\n"
1171 << " bool isConstantPhysReg(MCRegister PhysReg) const override final;\n"
1172 << " /// Devirtualized TargetFrameLowering.\n"
1173 << " static const " << TargetName << "FrameLowering *getFrameLowering(\n"
1174 << " const MachineFunction &MF);\n";
1176 const auto &RegisterClasses = RegBank.getRegClasses();
1177 if (llvm::any_of(RegisterClasses, [](const auto &RC) { return RC.getBaseClassOrder(); })) {
1178 OS << " const TargetRegisterClass *getPhysRegBaseClass(MCRegister Reg) const override;\n";
1181 OS << "};\n\n";
1183 if (!RegisterClasses.empty()) {
1184 OS << "namespace " << RegisterClasses.front().Namespace
1185 << " { // Register classes\n";
1187 for (const auto &RC : RegisterClasses) {
1188 const std::string &Name = RC.getName();
1190 // Output the extern for the instance.
1191 OS << " extern const TargetRegisterClass " << Name << "RegClass;\n";
1193 OS << "} // end namespace " << RegisterClasses.front().Namespace << "\n\n";
1195 OS << "} // end namespace llvm\n\n";
1196 OS << "#endif // GET_REGINFO_HEADER\n\n";
1200 // runTargetDesc - Output the target register and register file descriptions.
1202 void
1203 RegisterInfoEmitter::runTargetDesc(raw_ostream &OS, CodeGenTarget &Target,
1204 CodeGenRegBank &RegBank){
1205 emitSourceFileHeader("Target Register and Register Classes Information", OS);
1207 OS << "\n#ifdef GET_REGINFO_TARGET_DESC\n";
1208 OS << "#undef GET_REGINFO_TARGET_DESC\n\n";
1210 OS << "namespace llvm {\n\n";
1212 // Get access to MCRegisterClass data.
1213 OS << "extern const MCRegisterClass " << Target.getName()
1214 << "MCRegisterClasses[];\n";
1216 // Start out by emitting each of the register classes.
1217 const auto &RegisterClasses = RegBank.getRegClasses();
1218 const auto &SubRegIndices = RegBank.getSubRegIndices();
1220 // Collect all registers belonging to any allocatable class.
1221 std::set<Record*> AllocatableRegs;
1223 // Collect allocatable registers.
1224 for (const auto &RC : RegisterClasses) {
1225 ArrayRef<Record*> Order = RC.getOrder();
1227 if (RC.Allocatable)
1228 AllocatableRegs.insert(Order.begin(), Order.end());
1231 const CodeGenHwModes &CGH = Target.getHwModes();
1232 unsigned NumModes = CGH.getNumModeIds();
1234 // Build a shared array of value types.
1235 SequenceToOffsetTable<std::vector<MVT::SimpleValueType>> VTSeqs;
1236 for (unsigned M = 0; M < NumModes; ++M) {
1237 for (const auto &RC : RegisterClasses) {
1238 std::vector<MVT::SimpleValueType> S;
1239 for (const ValueTypeByHwMode &VVT : RC.VTs)
1240 if (VVT.hasDefault() || VVT.hasMode(M))
1241 S.push_back(VVT.get(M).SimpleTy);
1242 VTSeqs.add(S);
1245 VTSeqs.layout();
1246 OS << "\nstatic const MVT::SimpleValueType VTLists[] = {\n";
1247 VTSeqs.emit(OS, printSimpleValueType, "MVT::Other");
1248 OS << "};\n";
1250 // Emit SubRegIndex names, skipping 0.
1251 OS << "\nstatic const char *SubRegIndexNameTable[] = { \"";
1253 for (const auto &Idx : SubRegIndices) {
1254 OS << Idx.getName();
1255 OS << "\", \"";
1257 OS << "\" };\n\n";
1259 // Emit SubRegIndex lane masks, including 0.
1260 OS << "\nstatic const LaneBitmask SubRegIndexLaneMaskTable[] = {\n "
1261 "LaneBitmask::getAll(),\n";
1262 for (const auto &Idx : SubRegIndices) {
1263 printMask(OS << " ", Idx.LaneMask);
1264 OS << ", // " << Idx.getName() << '\n';
1266 OS << " };\n\n";
1268 OS << "\n";
1270 // Now that all of the structs have been emitted, emit the instances.
1271 if (!RegisterClasses.empty()) {
1272 OS << "\nstatic const TargetRegisterInfo::RegClassInfo RegClassInfos[]"
1273 << " = {\n";
1274 for (unsigned M = 0; M < NumModes; ++M) {
1275 unsigned EV = 0;
1276 OS << " // Mode = " << M << " (";
1277 if (M == 0)
1278 OS << "Default";
1279 else
1280 OS << CGH.getMode(M).Name;
1281 OS << ")\n";
1282 for (const auto &RC : RegisterClasses) {
1283 assert(RC.EnumValue == EV && "Unexpected order of register classes");
1284 ++EV;
1285 (void)EV;
1286 const RegSizeInfo &RI = RC.RSI.get(M);
1287 OS << " { " << RI.RegSize << ", " << RI.SpillSize << ", "
1288 << RI.SpillAlignment;
1289 std::vector<MVT::SimpleValueType> VTs;
1290 for (const ValueTypeByHwMode &VVT : RC.VTs)
1291 if (VVT.hasDefault() || VVT.hasMode(M))
1292 VTs.push_back(VVT.get(M).SimpleTy);
1293 OS << ", /*VTLists+*/" << VTSeqs.get(VTs) << " }, // "
1294 << RC.getName() << '\n';
1297 OS << "};\n";
1300 OS << "\nstatic const TargetRegisterClass *const "
1301 << "NullRegClasses[] = { nullptr };\n\n";
1303 // Emit register class bit mask tables. The first bit mask emitted for a
1304 // register class, RC, is the set of sub-classes, including RC itself.
1306 // If RC has super-registers, also create a list of subreg indices and bit
1307 // masks, (Idx, Mask). The bit mask has a bit for every superreg regclass,
1308 // SuperRC, that satisfies:
1310 // For all SuperReg in SuperRC: SuperReg:Idx in RC
1312 // The 0-terminated list of subreg indices starts at:
1314 // RC->getSuperRegIndices() = SuperRegIdxSeqs + ...
1316 // The corresponding bitmasks follow the sub-class mask in memory. Each
1317 // mask has RCMaskWords uint32_t entries.
1319 // Every bit mask present in the list has at least one bit set.
1321 // Compress the sub-reg index lists.
1322 typedef std::vector<const CodeGenSubRegIndex*> IdxList;
1323 SmallVector<IdxList, 8> SuperRegIdxLists(RegisterClasses.size());
1324 SequenceToOffsetTable<IdxList, deref<std::less<>>> SuperRegIdxSeqs;
1325 BitVector MaskBV(RegisterClasses.size());
1327 for (const auto &RC : RegisterClasses) {
1328 OS << "static const uint32_t " << RC.getName()
1329 << "SubClassMask[] = {\n ";
1330 printBitVectorAsHex(OS, RC.getSubClasses(), 32);
1332 // Emit super-reg class masks for any relevant SubRegIndices that can
1333 // project into RC.
1334 IdxList &SRIList = SuperRegIdxLists[RC.EnumValue];
1335 for (auto &Idx : SubRegIndices) {
1336 MaskBV.reset();
1337 RC.getSuperRegClasses(&Idx, MaskBV);
1338 if (MaskBV.none())
1339 continue;
1340 SRIList.push_back(&Idx);
1341 OS << "\n ";
1342 printBitVectorAsHex(OS, MaskBV, 32);
1343 OS << "// " << Idx.getName();
1345 SuperRegIdxSeqs.add(SRIList);
1346 OS << "\n};\n\n";
1349 OS << "static const uint16_t SuperRegIdxSeqs[] = {\n";
1350 SuperRegIdxSeqs.layout();
1351 SuperRegIdxSeqs.emit(OS, printSubRegIndex);
1352 OS << "};\n\n";
1354 // Emit NULL terminated super-class lists.
1355 for (const auto &RC : RegisterClasses) {
1356 ArrayRef<CodeGenRegisterClass*> Supers = RC.getSuperClasses();
1358 // Skip classes without supers. We can reuse NullRegClasses.
1359 if (Supers.empty())
1360 continue;
1362 OS << "static const TargetRegisterClass *const "
1363 << RC.getName() << "Superclasses[] = {\n";
1364 for (const auto *Super : Supers)
1365 OS << " &" << Super->getQualifiedName() << "RegClass,\n";
1366 OS << " nullptr\n};\n\n";
1369 // Emit methods.
1370 for (const auto &RC : RegisterClasses) {
1371 if (!RC.AltOrderSelect.empty()) {
1372 OS << "\nstatic inline unsigned " << RC.getName()
1373 << "AltOrderSelect(const MachineFunction &MF) {"
1374 << RC.AltOrderSelect << "}\n\n"
1375 << "static ArrayRef<MCPhysReg> " << RC.getName()
1376 << "GetRawAllocationOrder(const MachineFunction &MF) {\n";
1377 for (unsigned oi = 1 , oe = RC.getNumOrders(); oi != oe; ++oi) {
1378 ArrayRef<Record*> Elems = RC.getOrder(oi);
1379 if (!Elems.empty()) {
1380 OS << " static const MCPhysReg AltOrder" << oi << "[] = {";
1381 for (unsigned elem = 0; elem != Elems.size(); ++elem)
1382 OS << (elem ? ", " : " ") << getQualifiedName(Elems[elem]);
1383 OS << " };\n";
1386 OS << " const MCRegisterClass &MCR = " << Target.getName()
1387 << "MCRegisterClasses[" << RC.getQualifiedName() + "RegClassID];\n"
1388 << " const ArrayRef<MCPhysReg> Order[] = {\n"
1389 << " ArrayRef(MCR.begin(), MCR.getNumRegs()";
1390 for (unsigned oi = 1, oe = RC.getNumOrders(); oi != oe; ++oi)
1391 if (RC.getOrder(oi).empty())
1392 OS << "),\n ArrayRef<MCPhysReg>(";
1393 else
1394 OS << "),\n ArrayRef(AltOrder" << oi;
1395 OS << ")\n };\n const unsigned Select = " << RC.getName()
1396 << "AltOrderSelect(MF);\n assert(Select < " << RC.getNumOrders()
1397 << ");\n return Order[Select];\n}\n";
1401 // Now emit the actual value-initialized register class instances.
1402 OS << "\nnamespace " << RegisterClasses.front().Namespace
1403 << " { // Register class instances\n";
1405 for (const auto &RC : RegisterClasses) {
1406 OS << " extern const TargetRegisterClass " << RC.getName()
1407 << "RegClass = {\n " << '&' << Target.getName()
1408 << "MCRegisterClasses[" << RC.getName() << "RegClassID],\n "
1409 << RC.getName() << "SubClassMask,\n SuperRegIdxSeqs + "
1410 << SuperRegIdxSeqs.get(SuperRegIdxLists[RC.EnumValue]) << ",\n ";
1411 printMask(OS, RC.LaneMask);
1412 OS << ",\n " << (unsigned)RC.AllocationPriority << ",\n "
1413 << (RC.GlobalPriority ? "true" : "false") << ",\n "
1414 << format("0x%02x", RC.TSFlags) << ", /* TSFlags */\n "
1415 << (RC.HasDisjunctSubRegs ? "true" : "false")
1416 << ", /* HasDisjunctSubRegs */\n "
1417 << (RC.CoveredBySubRegs ? "true" : "false")
1418 << ", /* CoveredBySubRegs */\n ";
1419 if (RC.getSuperClasses().empty())
1420 OS << "NullRegClasses,\n ";
1421 else
1422 OS << RC.getName() << "Superclasses,\n ";
1423 if (RC.AltOrderSelect.empty())
1424 OS << "nullptr\n";
1425 else
1426 OS << RC.getName() << "GetRawAllocationOrder\n";
1427 OS << " };\n\n";
1430 OS << "} // end namespace " << RegisterClasses.front().Namespace << "\n";
1433 OS << "\nnamespace {\n";
1434 OS << " const TargetRegisterClass *const RegisterClasses[] = {\n";
1435 for (const auto &RC : RegisterClasses)
1436 OS << " &" << RC.getQualifiedName() << "RegClass,\n";
1437 OS << " };\n";
1438 OS << "} // end anonymous namespace\n";
1440 // Emit extra information about registers.
1441 const std::string &TargetName = std::string(Target.getName());
1442 const auto &Regs = RegBank.getRegisters();
1443 unsigned NumRegCosts = 1;
1444 for (const auto &Reg : Regs)
1445 NumRegCosts = std::max((size_t)NumRegCosts, Reg.CostPerUse.size());
1447 std::vector<unsigned> AllRegCostPerUse;
1448 llvm::BitVector InAllocClass(Regs.size() + 1, false);
1449 AllRegCostPerUse.insert(AllRegCostPerUse.end(), NumRegCosts, 0);
1451 // Populate the vector RegCosts with the CostPerUse list of the registers
1452 // in the order they are read. Have at most NumRegCosts entries for
1453 // each register. Fill with zero for values which are not explicitly given.
1454 for (const auto &Reg : Regs) {
1455 auto Costs = Reg.CostPerUse;
1456 AllRegCostPerUse.insert(AllRegCostPerUse.end(), Costs.begin(), Costs.end());
1457 if (NumRegCosts > Costs.size())
1458 AllRegCostPerUse.insert(AllRegCostPerUse.end(),
1459 NumRegCosts - Costs.size(), 0);
1461 if (AllocatableRegs.count(Reg.TheDef))
1462 InAllocClass.set(Reg.EnumValue);
1465 // Emit the cost values as a 1D-array after grouping them by their indices,
1466 // i.e. the costs for all registers corresponds to index 0, 1, 2, etc.
1467 // Size of the emitted array should be NumRegCosts * (Regs.size() + 1).
1468 OS << "\nstatic const uint8_t "
1469 << "CostPerUseTable[] = { \n";
1470 for (unsigned int I = 0; I < NumRegCosts; ++I) {
1471 for (unsigned J = I, E = AllRegCostPerUse.size(); J < E; J += NumRegCosts)
1472 OS << AllRegCostPerUse[J] << ", ";
1474 OS << "};\n\n";
1476 OS << "\nstatic const bool "
1477 << "InAllocatableClassTable[] = { \n";
1478 for (unsigned I = 0, E = InAllocClass.size(); I < E; ++I) {
1479 OS << (InAllocClass[I] ? "true" : "false") << ", ";
1481 OS << "};\n\n";
1483 OS << "\nstatic const TargetRegisterInfoDesc " << TargetName
1484 << "RegInfoDesc = { // Extra Descriptors\n";
1485 OS << "CostPerUseTable, " << NumRegCosts << ", "
1486 << "InAllocatableClassTable";
1487 OS << "};\n\n"; // End of register descriptors...
1489 std::string ClassName = Target.getName().str() + "GenRegisterInfo";
1491 auto SubRegIndicesSize =
1492 std::distance(SubRegIndices.begin(), SubRegIndices.end());
1494 if (!SubRegIndices.empty()) {
1495 emitComposeSubRegIndices(OS, RegBank, ClassName);
1496 emitComposeSubRegIndexLaneMask(OS, RegBank, ClassName);
1499 if (!SubRegIndices.empty()) {
1500 // Emit getSubClassWithSubReg.
1501 OS << "const TargetRegisterClass *" << ClassName
1502 << "::getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx)"
1503 << " const {\n";
1504 // Use the smallest type that can hold a regclass ID with room for a
1505 // sentinel.
1506 if (RegisterClasses.size() <= UINT8_MAX)
1507 OS << " static const uint8_t Table[";
1508 else if (RegisterClasses.size() <= UINT16_MAX)
1509 OS << " static const uint16_t Table[";
1510 else
1511 PrintFatalError("Too many register classes.");
1512 OS << RegisterClasses.size() << "][" << SubRegIndicesSize << "] = {\n";
1513 for (const auto &RC : RegisterClasses) {
1514 OS << " {\t// " << RC.getName() << "\n";
1515 for (auto &Idx : SubRegIndices) {
1516 if (CodeGenRegisterClass *SRC = RC.getSubClassWithSubReg(&Idx))
1517 OS << " " << SRC->EnumValue + 1 << ",\t// " << Idx.getName()
1518 << " -> " << SRC->getName() << "\n";
1519 else
1520 OS << " 0,\t// " << Idx.getName() << "\n";
1522 OS << " },\n";
1524 OS << " };\n assert(RC && \"Missing regclass\");\n"
1525 << " if (!Idx) return RC;\n --Idx;\n"
1526 << " assert(Idx < " << SubRegIndicesSize << " && \"Bad subreg\");\n"
1527 << " unsigned TV = Table[RC->getID()][Idx];\n"
1528 << " return TV ? getRegClass(TV - 1) : nullptr;\n}\n\n";
1530 // Emit getSubRegisterClass
1531 OS << "const TargetRegisterClass *" << ClassName
1532 << "::getSubRegisterClass(const TargetRegisterClass *RC, unsigned Idx)"
1533 << " const {\n";
1535 // Use the smallest type that can hold a regclass ID with room for a
1536 // sentinel.
1537 if (RegisterClasses.size() <= UINT8_MAX)
1538 OS << " static const uint8_t Table[";
1539 else if (RegisterClasses.size() <= UINT16_MAX)
1540 OS << " static const uint16_t Table[";
1541 else
1542 PrintFatalError("Too many register classes.");
1544 OS << RegisterClasses.size() << "][" << SubRegIndicesSize << "] = {\n";
1546 for (const auto &RC : RegisterClasses) {
1547 OS << " {\t// " << RC.getName() << '\n';
1548 for (auto &Idx : SubRegIndices) {
1549 std::optional<std::pair<CodeGenRegisterClass *, CodeGenRegisterClass *>>
1550 MatchingSubClass = RC.getMatchingSubClassWithSubRegs(RegBank, &Idx);
1552 unsigned EnumValue = 0;
1553 if (MatchingSubClass) {
1554 CodeGenRegisterClass *SubRegClass = MatchingSubClass->second;
1555 EnumValue = SubRegClass->EnumValue + 1;
1558 OS << " " << EnumValue << ",\t// "
1559 << RC.getName() << ':' << Idx.getName();
1561 if (MatchingSubClass) {
1562 CodeGenRegisterClass *SubRegClass = MatchingSubClass->second;
1563 OS << " -> " << SubRegClass->getName();
1566 OS << '\n';
1569 OS << " },\n";
1571 OS << " };\n assert(RC && \"Missing regclass\");\n"
1572 << " if (!Idx) return RC;\n --Idx;\n"
1573 << " assert(Idx < " << SubRegIndicesSize << " && \"Bad subreg\");\n"
1574 << " unsigned TV = Table[RC->getID()][Idx];\n"
1575 << " return TV ? getRegClass(TV - 1) : nullptr;\n}\n\n";
1578 EmitRegUnitPressure(OS, RegBank, ClassName);
1580 // Emit register base class mapper
1581 if (!RegisterClasses.empty()) {
1582 // Collect base classes
1583 SmallVector<const CodeGenRegisterClass*> BaseClasses;
1584 for (const auto &RC : RegisterClasses) {
1585 if (RC.getBaseClassOrder())
1586 BaseClasses.push_back(&RC);
1588 if (!BaseClasses.empty()) {
1589 assert(BaseClasses.size() < UINT16_MAX &&
1590 "Too many base register classes");
1592 // Apply order
1593 struct BaseClassOrdering {
1594 bool operator()(const CodeGenRegisterClass *LHS, const CodeGenRegisterClass *RHS) const {
1595 return std::pair(*LHS->getBaseClassOrder(), LHS->EnumValue)
1596 < std::pair(*RHS->getBaseClassOrder(), RHS->EnumValue);
1599 llvm::stable_sort(BaseClasses, BaseClassOrdering());
1601 OS << "\n// Register to base register class mapping\n\n";
1602 OS << "\n";
1603 OS << "const TargetRegisterClass *" << ClassName
1604 << "::getPhysRegBaseClass(MCRegister Reg)"
1605 << " const {\n";
1606 OS << " static const uint16_t InvalidRegClassID = UINT16_MAX;\n\n";
1607 OS << " static const uint16_t Mapping[" << Regs.size() + 1 << "] = {\n";
1608 OS << " InvalidRegClassID, // NoRegister\n";
1609 for (const CodeGenRegister &Reg : Regs) {
1610 const CodeGenRegisterClass *BaseRC = nullptr;
1611 for (const CodeGenRegisterClass *RC : BaseClasses) {
1612 if (is_contained(RC->getMembers(), &Reg)) {
1613 BaseRC = RC;
1614 break;
1618 OS << " "
1619 << (BaseRC ? BaseRC->getQualifiedIdName() : "InvalidRegClassID")
1620 << ", // " << Reg.getName() << "\n";
1622 OS << " };\n\n"
1623 " assert(Reg < ArrayRef(Mapping).size());\n"
1624 " unsigned RCID = Mapping[Reg];\n"
1625 " if (RCID == InvalidRegClassID)\n"
1626 " return nullptr;\n"
1627 " return RegisterClasses[RCID];\n"
1628 "}\n";
1632 // Emit the constructor of the class...
1633 OS << "extern const MCRegisterDesc " << TargetName << "RegDesc[];\n";
1634 OS << "extern const int16_t " << TargetName << "RegDiffLists[];\n";
1635 OS << "extern const LaneBitmask " << TargetName << "LaneMaskLists[];\n";
1636 OS << "extern const char " << TargetName << "RegStrings[];\n";
1637 OS << "extern const char " << TargetName << "RegClassStrings[];\n";
1638 OS << "extern const MCPhysReg " << TargetName << "RegUnitRoots[][2];\n";
1639 OS << "extern const uint16_t " << TargetName << "SubRegIdxLists[];\n";
1640 OS << "extern const MCRegisterInfo::SubRegCoveredBits "
1641 << TargetName << "SubRegIdxRanges[];\n";
1642 OS << "extern const uint16_t " << TargetName << "RegEncodingTable[];\n";
1644 EmitRegMappingTables(OS, Regs, true);
1646 OS << ClassName << "::\n"
1647 << ClassName
1648 << "(unsigned RA, unsigned DwarfFlavour, unsigned EHFlavour,\n"
1649 " unsigned PC, unsigned HwMode)\n"
1650 << " : TargetRegisterInfo(&" << TargetName << "RegInfoDesc"
1651 << ", RegisterClasses, RegisterClasses+" << RegisterClasses.size() << ",\n"
1652 << " SubRegIndexNameTable, SubRegIndexLaneMaskTable,\n"
1653 << " ";
1654 printMask(OS, RegBank.CoveringLanes);
1655 OS << ", RegClassInfos, VTLists, HwMode) {\n"
1656 << " InitMCRegisterInfo(" << TargetName << "RegDesc, " << Regs.size() + 1
1657 << ", RA, PC,\n " << TargetName
1658 << "MCRegisterClasses, " << RegisterClasses.size() << ",\n"
1659 << " " << TargetName << "RegUnitRoots,\n"
1660 << " " << RegBank.getNumNativeRegUnits() << ",\n"
1661 << " " << TargetName << "RegDiffLists,\n"
1662 << " " << TargetName << "LaneMaskLists,\n"
1663 << " " << TargetName << "RegStrings,\n"
1664 << " " << TargetName << "RegClassStrings,\n"
1665 << " " << TargetName << "SubRegIdxLists,\n"
1666 << " " << SubRegIndicesSize + 1 << ",\n"
1667 << " " << TargetName << "SubRegIdxRanges,\n"
1668 << " " << TargetName << "RegEncodingTable);\n\n";
1670 EmitRegMapping(OS, Regs, true);
1672 OS << "}\n\n";
1674 // Emit CalleeSavedRegs information.
1675 std::vector<Record*> CSRSets =
1676 Records.getAllDerivedDefinitions("CalleeSavedRegs");
1677 for (unsigned i = 0, e = CSRSets.size(); i != e; ++i) {
1678 Record *CSRSet = CSRSets[i];
1679 const SetTheory::RecVec *Regs = RegBank.getSets().expand(CSRSet);
1680 assert(Regs && "Cannot expand CalleeSavedRegs instance");
1682 // Emit the *_SaveList list of callee-saved registers.
1683 OS << "static const MCPhysReg " << CSRSet->getName()
1684 << "_SaveList[] = { ";
1685 for (unsigned r = 0, re = Regs->size(); r != re; ++r)
1686 OS << getQualifiedName((*Regs)[r]) << ", ";
1687 OS << "0 };\n";
1689 // Emit the *_RegMask bit mask of call-preserved registers.
1690 BitVector Covered = RegBank.computeCoveredRegisters(*Regs);
1692 // Check for an optional OtherPreserved set.
1693 // Add those registers to RegMask, but not to SaveList.
1694 if (DagInit *OPDag =
1695 dyn_cast<DagInit>(CSRSet->getValueInit("OtherPreserved"))) {
1696 SetTheory::RecSet OPSet;
1697 RegBank.getSets().evaluate(OPDag, OPSet, CSRSet->getLoc());
1698 Covered |= RegBank.computeCoveredRegisters(
1699 ArrayRef<Record*>(OPSet.begin(), OPSet.end()));
1702 // Add all constant physical registers to the preserved mask:
1703 SetTheory::RecSet ConstantSet;
1704 for (auto &Reg : RegBank.getRegisters()) {
1705 if (Reg.Constant)
1706 ConstantSet.insert(Reg.TheDef);
1708 Covered |= RegBank.computeCoveredRegisters(
1709 ArrayRef<Record *>(ConstantSet.begin(), ConstantSet.end()));
1711 OS << "static const uint32_t " << CSRSet->getName()
1712 << "_RegMask[] = { ";
1713 printBitVectorAsHex(OS, Covered, 32);
1714 OS << "};\n";
1716 OS << "\n\n";
1718 OS << "ArrayRef<const uint32_t *> " << ClassName
1719 << "::getRegMasks() const {\n";
1720 if (!CSRSets.empty()) {
1721 OS << " static const uint32_t *const Masks[] = {\n";
1722 for (Record *CSRSet : CSRSets)
1723 OS << " " << CSRSet->getName() << "_RegMask,\n";
1724 OS << " };\n";
1725 OS << " return ArrayRef(Masks);\n";
1726 } else {
1727 OS << " return std::nullopt;\n";
1729 OS << "}\n\n";
1731 const std::list<CodeGenRegisterCategory> &RegCategories =
1732 RegBank.getRegCategories();
1733 OS << "bool " << ClassName << "::\n"
1734 << "isGeneralPurposeRegister(const MachineFunction &MF, "
1735 << "MCRegister PhysReg) const {\n"
1736 << " return\n";
1737 for (const CodeGenRegisterCategory &Category : RegCategories)
1738 if (Category.getName() == "GeneralPurposeRegisters") {
1739 for (const CodeGenRegisterClass *RC : Category.getClasses())
1740 OS << " " << RC->getQualifiedName()
1741 << "RegClass.contains(PhysReg) ||\n";
1742 break;
1744 OS << " false;\n";
1745 OS << "}\n\n";
1747 OS << "bool " << ClassName << "::\n"
1748 << "isFixedRegister(const MachineFunction &MF, "
1749 << "MCRegister PhysReg) const {\n"
1750 << " return\n";
1751 for (const CodeGenRegisterCategory &Category : RegCategories)
1752 if (Category.getName() == "FixedRegisters") {
1753 for (const CodeGenRegisterClass *RC : Category.getClasses())
1754 OS << " " << RC->getQualifiedName()
1755 << "RegClass.contains(PhysReg) ||\n";
1756 break;
1758 OS << " false;\n";
1759 OS << "}\n\n";
1761 OS << "bool " << ClassName << "::\n"
1762 << "isArgumentRegister(const MachineFunction &MF, "
1763 << "MCRegister PhysReg) const {\n"
1764 << " return\n";
1765 for (const CodeGenRegisterCategory &Category : RegCategories)
1766 if (Category.getName() == "ArgumentRegisters") {
1767 for (const CodeGenRegisterClass *RC : Category.getClasses())
1768 OS << " " << RC->getQualifiedName()
1769 << "RegClass.contains(PhysReg) ||\n";
1770 break;
1772 OS << " false;\n";
1773 OS << "}\n\n";
1775 OS << "bool " << ClassName << "::\n"
1776 << "isConstantPhysReg(MCRegister PhysReg) const {\n"
1777 << " return\n";
1778 for (const auto &Reg : Regs)
1779 if (Reg.Constant)
1780 OS << " PhysReg == " << getQualifiedName(Reg.TheDef) << " ||\n";
1781 OS << " false;\n";
1782 OS << "}\n\n";
1784 OS << "ArrayRef<const char *> " << ClassName
1785 << "::getRegMaskNames() const {\n";
1786 if (!CSRSets.empty()) {
1787 OS << " static const char *Names[] = {\n";
1788 for (Record *CSRSet : CSRSets)
1789 OS << " " << '"' << CSRSet->getName() << '"' << ",\n";
1790 OS << " };\n";
1791 OS << " return ArrayRef(Names);\n";
1792 } else {
1793 OS << " return std::nullopt;\n";
1795 OS << "}\n\n";
1797 OS << "const " << TargetName << "FrameLowering *\n" << TargetName
1798 << "GenRegisterInfo::getFrameLowering(const MachineFunction &MF) {\n"
1799 << " return static_cast<const " << TargetName << "FrameLowering *>(\n"
1800 << " MF.getSubtarget().getFrameLowering());\n"
1801 << "}\n\n";
1803 OS << "} // end namespace llvm\n\n";
1804 OS << "#endif // GET_REGINFO_TARGET_DESC\n\n";
1807 void RegisterInfoEmitter::run(raw_ostream &OS) {
1808 CodeGenRegBank &RegBank = Target.getRegBank();
1809 Records.startTimer("Print enums");
1810 runEnums(OS, Target, RegBank);
1812 Records.startTimer("Print MC registers");
1813 runMCDesc(OS, Target, RegBank);
1815 Records.startTimer("Print header fragment");
1816 runTargetHeader(OS, Target, RegBank);
1818 Records.startTimer("Print target registers");
1819 runTargetDesc(OS, Target, RegBank);
1821 if (RegisterInfoDebug)
1822 debugDump(errs());
1825 void RegisterInfoEmitter::debugDump(raw_ostream &OS) {
1826 CodeGenRegBank &RegBank = Target.getRegBank();
1827 const CodeGenHwModes &CGH = Target.getHwModes();
1828 unsigned NumModes = CGH.getNumModeIds();
1829 auto getModeName = [CGH] (unsigned M) -> StringRef {
1830 if (M == 0)
1831 return "Default";
1832 return CGH.getMode(M).Name;
1835 for (const CodeGenRegisterClass &RC : RegBank.getRegClasses()) {
1836 OS << "RegisterClass " << RC.getName() << ":\n";
1837 OS << "\tSpillSize: {";
1838 for (unsigned M = 0; M != NumModes; ++M)
1839 OS << ' ' << getModeName(M) << ':' << RC.RSI.get(M).SpillSize;
1840 OS << " }\n\tSpillAlignment: {";
1841 for (unsigned M = 0; M != NumModes; ++M)
1842 OS << ' ' << getModeName(M) << ':' << RC.RSI.get(M).SpillAlignment;
1843 OS << " }\n\tNumRegs: " << RC.getMembers().size() << '\n';
1844 OS << "\tLaneMask: " << PrintLaneMask(RC.LaneMask) << '\n';
1845 OS << "\tHasDisjunctSubRegs: " << RC.HasDisjunctSubRegs << '\n';
1846 OS << "\tCoveredBySubRegs: " << RC.CoveredBySubRegs << '\n';
1847 OS << "\tAllocatable: " << RC.Allocatable << '\n';
1848 OS << "\tAllocationPriority: " << unsigned(RC.AllocationPriority) << '\n';
1849 OS << "\tRegs:";
1850 for (const CodeGenRegister *R : RC.getMembers()) {
1851 OS << " " << R->getName();
1853 OS << '\n';
1854 OS << "\tSubClasses:";
1855 const BitVector &SubClasses = RC.getSubClasses();
1856 for (const CodeGenRegisterClass &SRC : RegBank.getRegClasses()) {
1857 if (!SubClasses.test(SRC.EnumValue))
1858 continue;
1859 OS << " " << SRC.getName();
1861 OS << '\n';
1862 OS << "\tSuperClasses:";
1863 for (const CodeGenRegisterClass *SRC : RC.getSuperClasses()) {
1864 OS << " " << SRC->getName();
1866 OS << '\n';
1869 for (const CodeGenSubRegIndex &SRI : RegBank.getSubRegIndices()) {
1870 OS << "SubRegIndex " << SRI.getName() << ":\n";
1871 OS << "\tLaneMask: " << PrintLaneMask(SRI.LaneMask) << '\n';
1872 OS << "\tAllSuperRegsCovered: " << SRI.AllSuperRegsCovered << '\n';
1873 OS << "\tOffset, Size: " << SRI.Offset << ", " << SRI.Size << '\n';
1876 for (const CodeGenRegister &R : RegBank.getRegisters()) {
1877 OS << "Register " << R.getName() << ":\n";
1878 OS << "\tCostPerUse: ";
1879 for (const auto &Cost : R.CostPerUse)
1880 OS << Cost << " ";
1881 OS << '\n';
1882 OS << "\tCoveredBySubregs: " << R.CoveredBySubRegs << '\n';
1883 OS << "\tHasDisjunctSubRegs: " << R.HasDisjunctSubRegs << '\n';
1884 for (std::pair<CodeGenSubRegIndex*,CodeGenRegister*> P : R.getSubRegs()) {
1885 OS << "\tSubReg " << P.first->getName()
1886 << " = " << P.second->getName() << '\n';
1891 static TableGen::Emitter::OptClass<RegisterInfoEmitter>
1892 X("gen-register-info", "Generate registers and register classes info");