[Frontend] Remove unused includes (NFC) (#116927)
[llvm-project.git] / llvm / utils / TableGen / RegisterInfoEmitter.cpp
bloba6f87119aca5babbe48c423dd6caff41911339ce
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 "Basic/SequenceToOffsetTable.h"
16 #include "Common/CodeGenHwModes.h"
17 #include "Common/CodeGenRegisters.h"
18 #include "Common/CodeGenTarget.h"
19 #include "Common/InfoByHwMode.h"
20 #include "Common/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/CodeGenTypes/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/TGTimer.h"
37 #include "llvm/TableGen/TableGenBackend.h"
38 #include <algorithm>
39 #include <cassert>
40 #include <cstddef>
41 #include <cstdint>
42 #include <deque>
43 #include <iterator>
44 #include <set>
45 #include <string>
46 #include <vector>
48 using namespace llvm;
50 cl::OptionCategory RegisterInfoCat("Options for -gen-register-info");
52 static cl::opt<bool>
53 RegisterInfoDebug("register-info-debug", cl::init(false),
54 cl::desc("Dump register information to help debugging"),
55 cl::cat(RegisterInfoCat));
57 namespace {
59 class RegisterInfoEmitter {
60 const RecordKeeper &Records;
61 const CodeGenTarget Target;
62 CodeGenRegBank &RegBank;
64 public:
65 RegisterInfoEmitter(const RecordKeeper &R)
66 : Records(R), Target(R), RegBank(Target.getRegBank()) {
67 RegBank.computeDerivedInfo();
70 // runEnums - Print out enum values for all of the registers.
71 void runEnums(raw_ostream &OS);
73 // runMCDesc - Print out MC register descriptions.
74 void runMCDesc(raw_ostream &OS);
76 // runTargetHeader - Emit a header fragment for the register info emitter.
77 void runTargetHeader(raw_ostream &OS);
79 // runTargetDesc - Output the target register and register file descriptions.
80 void runTargetDesc(raw_ostream &OS);
82 // run - Output the register file description.
83 void run(raw_ostream &OS);
85 void debugDump(raw_ostream &OS);
87 private:
88 void EmitRegMapping(raw_ostream &OS, const std::deque<CodeGenRegister> &Regs,
89 bool isCtor);
90 void EmitRegMappingTables(raw_ostream &OS,
91 const std::deque<CodeGenRegister> &Regs,
92 bool isCtor);
93 void EmitRegUnitPressure(raw_ostream &OS, StringRef ClassName);
94 void emitComposeSubRegIndices(raw_ostream &OS, StringRef ClassName);
95 void emitComposeSubRegIndexLaneMask(raw_ostream &OS, StringRef ClassName);
98 } // end anonymous namespace
100 // runEnums - Print out enum values for all of the registers.
101 void RegisterInfoEmitter::runEnums(raw_ostream &OS) {
102 const auto &Registers = RegBank.getRegisters();
104 // Register enums are stored as uint16_t in the tables. Make sure we'll fit.
105 assert(Registers.size() <= 0xffff && "Too many regs to fit in tables");
107 StringRef Namespace = Registers.front().TheDef->getValueAsString("Namespace");
109 emitSourceFileHeader("Target Register Enum Values", OS);
111 OS << "\n#ifdef GET_REGINFO_ENUM\n";
112 OS << "#undef GET_REGINFO_ENUM\n\n";
114 OS << "namespace llvm {\n\n";
116 OS << "class MCRegisterClass;\n"
117 << "extern const MCRegisterClass " << Target.getName()
118 << "MCRegisterClasses[];\n\n";
120 if (!Namespace.empty())
121 OS << "namespace " << Namespace << " {\n";
122 OS << "enum : unsigned {\n NoRegister,\n";
124 for (const auto &Reg : Registers)
125 OS << " " << Reg.getName() << " = " << Reg.EnumValue << ",\n";
126 assert(Registers.size() == Registers.back().EnumValue &&
127 "Register enum value mismatch!");
128 OS << " NUM_TARGET_REGS // " << Registers.size() + 1 << "\n";
129 OS << "};\n";
130 if (!Namespace.empty())
131 OS << "} // end namespace " << Namespace << "\n";
133 const auto &RegisterClasses = RegBank.getRegClasses();
134 if (!RegisterClasses.empty()) {
136 // RegisterClass enums are stored as uint16_t in the tables.
137 assert(RegisterClasses.size() <= 0xffff &&
138 "Too many register classes to fit in tables");
140 OS << "\n// Register classes\n\n";
141 if (!Namespace.empty())
142 OS << "namespace " << Namespace << " {\n";
143 OS << "enum {\n";
144 for (const auto &RC : RegisterClasses)
145 OS << " " << RC.getIdName() << " = " << RC.EnumValue << ",\n";
146 OS << "\n};\n";
147 if (!Namespace.empty())
148 OS << "} // end namespace " << Namespace << "\n\n";
151 ArrayRef<const Record *> RegAltNameIndices = Target.getRegAltNameIndices();
152 // If the only definition is the default NoRegAltName, we don't need to
153 // emit anything.
154 if (RegAltNameIndices.size() > 1) {
155 OS << "\n// Register alternate name indices\n\n";
156 if (!Namespace.empty())
157 OS << "namespace " << Namespace << " {\n";
158 OS << "enum {\n";
159 for (unsigned i = 0, e = RegAltNameIndices.size(); i != e; ++i)
160 OS << " " << RegAltNameIndices[i]->getName() << ",\t// " << i << "\n";
161 OS << " NUM_TARGET_REG_ALT_NAMES = " << RegAltNameIndices.size() << "\n";
162 OS << "};\n";
163 if (!Namespace.empty())
164 OS << "} // end namespace " << Namespace << "\n\n";
167 auto &SubRegIndices = RegBank.getSubRegIndices();
168 if (!SubRegIndices.empty()) {
169 OS << "\n// Subregister indices\n\n";
170 std::string Namespace = SubRegIndices.front().getNamespace();
171 if (!Namespace.empty())
172 OS << "namespace " << Namespace << " {\n";
173 OS << "enum : uint16_t {\n NoSubRegister,\n";
174 unsigned i = 0;
175 for (const auto &Idx : SubRegIndices)
176 OS << " " << Idx.getName() << ",\t// " << ++i << "\n";
177 OS << " NUM_TARGET_SUBREGS\n};\n";
178 if (!Namespace.empty())
179 OS << "} // end namespace " << Namespace << "\n\n";
182 OS << "// Register pressure sets enum.\n";
183 if (!Namespace.empty())
184 OS << "namespace " << Namespace << " {\n";
185 OS << "enum RegisterPressureSets {\n";
186 unsigned NumSets = RegBank.getNumRegPressureSets();
187 for (unsigned i = 0; i < NumSets; ++i) {
188 const RegUnitSet &RegUnits = RegBank.getRegSetAt(i);
189 OS << " " << RegUnits.Name << " = " << i << ",\n";
191 OS << "};\n";
192 if (!Namespace.empty())
193 OS << "} // end namespace " << Namespace << '\n';
194 OS << '\n';
196 OS << "} // end namespace llvm\n\n";
197 OS << "#endif // GET_REGINFO_ENUM\n\n";
200 static void printInt(raw_ostream &OS, int Val) { OS << Val; }
202 void RegisterInfoEmitter::EmitRegUnitPressure(raw_ostream &OS,
203 StringRef ClassName) {
204 unsigned NumRCs = RegBank.getRegClasses().size();
205 unsigned NumSets = RegBank.getNumRegPressureSets();
207 OS << "/// Get the weight in units of pressure for this register class.\n"
208 << "const RegClassWeight &" << ClassName << "::\n"
209 << "getRegClassWeight(const TargetRegisterClass *RC) const {\n"
210 << " static const RegClassWeight RCWeightTable[] = {\n";
211 for (const auto &RC : RegBank.getRegClasses()) {
212 const CodeGenRegister::Vec &Regs = RC.getMembers();
213 OS << " {" << RC.getWeight(RegBank) << ", ";
214 if (Regs.empty() || RC.Artificial)
215 OS << '0';
216 else {
217 std::vector<unsigned> RegUnits;
218 RC.buildRegUnitSet(RegBank, RegUnits);
219 OS << RegBank.getRegUnitSetWeight(RegUnits);
221 OS << "}, \t// " << RC.getName() << "\n";
223 OS << " };\n"
224 << " return RCWeightTable[RC->getID()];\n"
225 << "}\n\n";
227 // Reasonable targets (not ARMv7) have unit weight for all units, so don't
228 // bother generating a table.
229 bool RegUnitsHaveUnitWeight = true;
230 for (unsigned UnitIdx = 0, UnitEnd = RegBank.getNumNativeRegUnits();
231 UnitIdx < UnitEnd; ++UnitIdx) {
232 if (RegBank.getRegUnit(UnitIdx).Weight > 1)
233 RegUnitsHaveUnitWeight = false;
235 OS << "/// Get the weight in units of pressure for this register unit.\n"
236 << "unsigned " << ClassName << "::\n"
237 << "getRegUnitWeight(unsigned RegUnit) const {\n"
238 << " assert(RegUnit < " << RegBank.getNumNativeRegUnits()
239 << " && \"invalid register unit\");\n";
240 if (!RegUnitsHaveUnitWeight) {
241 OS << " static const uint8_t RUWeightTable[] = {\n ";
242 for (unsigned UnitIdx = 0, UnitEnd = RegBank.getNumNativeRegUnits();
243 UnitIdx < UnitEnd; ++UnitIdx) {
244 const RegUnit &RU = RegBank.getRegUnit(UnitIdx);
245 assert(RU.Weight < 256 && "RegUnit too heavy");
246 OS << RU.Weight << ", ";
248 OS << "};\n"
249 << " return RUWeightTable[RegUnit];\n";
250 } else {
251 OS << " // All register units have unit weight.\n"
252 << " return 1;\n";
254 OS << "}\n\n";
256 OS << "\n"
257 << "// Get the number of dimensions of register pressure.\n"
258 << "unsigned " << ClassName << "::getNumRegPressureSets() const {\n"
259 << " return " << NumSets << ";\n}\n\n";
261 OS << "// Get the name of this register unit pressure set.\n"
262 << "const char *" << ClassName << "::\n"
263 << "getRegPressureSetName(unsigned Idx) const {\n"
264 << " static const char *PressureNameTable[] = {\n";
265 unsigned MaxRegUnitWeight = 0;
266 for (unsigned i = 0; i < NumSets; ++i) {
267 const RegUnitSet &RegUnits = RegBank.getRegSetAt(i);
268 MaxRegUnitWeight = std::max(MaxRegUnitWeight, RegUnits.Weight);
269 OS << " \"" << RegUnits.Name << "\",\n";
271 OS << " };\n"
272 << " return PressureNameTable[Idx];\n"
273 << "}\n\n";
275 OS << "// Get the register unit pressure limit for this dimension.\n"
276 << "// This limit must be adjusted dynamically for reserved registers.\n"
277 << "unsigned " << ClassName << "::\n"
278 << "getRegPressureSetLimit(const MachineFunction &MF, unsigned Idx) const "
279 "{\n"
280 << " static const " << getMinimalTypeForRange(MaxRegUnitWeight, 32)
281 << " PressureLimitTable[] = {\n";
282 for (unsigned i = 0; i < NumSets; ++i) {
283 const RegUnitSet &RegUnits = RegBank.getRegSetAt(i);
284 OS << " " << RegUnits.Weight << ", \t// " << i << ": " << RegUnits.Name
285 << "\n";
287 OS << " };\n"
288 << " return PressureLimitTable[Idx];\n"
289 << "}\n\n";
291 SequenceToOffsetTable<std::vector<int>> PSetsSeqs;
293 // This table may be larger than NumRCs if some register units needed a list
294 // of unit sets that did not correspond to a register class.
295 unsigned NumRCUnitSets = RegBank.getNumRegClassPressureSetLists();
296 std::vector<std::vector<int>> PSets(NumRCUnitSets);
298 for (unsigned i = 0, e = NumRCUnitSets; i != e; ++i) {
299 ArrayRef<unsigned> PSetIDs = RegBank.getRCPressureSetIDs(i);
300 PSets[i].reserve(PSetIDs.size());
301 for (unsigned PSetID : PSetIDs) {
302 PSets[i].push_back(RegBank.getRegPressureSet(PSetID).Order);
304 llvm::sort(PSets[i]);
305 PSetsSeqs.add(PSets[i]);
308 PSetsSeqs.layout();
310 OS << "/// Table of pressure sets per register class or unit.\n"
311 << "static const int RCSetsTable[] = {\n";
312 PSetsSeqs.emit(OS, printInt, "-1");
313 OS << "};\n\n";
315 OS << "/// Get the dimensions of register pressure impacted by this "
316 << "register class.\n"
317 << "/// Returns a -1 terminated array of pressure set IDs\n"
318 << "const int *" << ClassName << "::\n"
319 << "getRegClassPressureSets(const TargetRegisterClass *RC) const {\n";
320 OS << " static const " << getMinimalTypeForRange(PSetsSeqs.size() - 1, 32)
321 << " RCSetStartTable[] = {\n ";
322 for (unsigned i = 0, e = NumRCs; i != e; ++i) {
323 OS << PSetsSeqs.get(PSets[i]) << ",";
325 OS << "};\n"
326 << " return &RCSetsTable[RCSetStartTable[RC->getID()]];\n"
327 << "}\n\n";
329 OS << "/// Get the dimensions of register pressure impacted by this "
330 << "register unit.\n"
331 << "/// Returns a -1 terminated array of pressure set IDs\n"
332 << "const int *" << ClassName << "::\n"
333 << "getRegUnitPressureSets(unsigned RegUnit) const {\n"
334 << " assert(RegUnit < " << RegBank.getNumNativeRegUnits()
335 << " && \"invalid register unit\");\n";
336 OS << " static const " << getMinimalTypeForRange(PSetsSeqs.size() - 1, 32)
337 << " RUSetStartTable[] = {\n ";
338 for (unsigned UnitIdx = 0, UnitEnd = RegBank.getNumNativeRegUnits();
339 UnitIdx < UnitEnd; ++UnitIdx) {
340 OS << PSetsSeqs.get(PSets[RegBank.getRegUnit(UnitIdx).RegClassUnitSetsIdx])
341 << ",";
343 OS << "};\n"
344 << " return &RCSetsTable[RUSetStartTable[RegUnit]];\n"
345 << "}\n\n";
348 using DwarfRegNumsMapPair = std::pair<const Record *, std::vector<int64_t>>;
349 using DwarfRegNumsVecTy = std::vector<DwarfRegNumsMapPair>;
351 static void finalizeDwarfRegNumsKeys(DwarfRegNumsVecTy &DwarfRegNums) {
352 // Sort and unique to get a map-like vector. We want the last assignment to
353 // match previous behaviour.
354 llvm::stable_sort(DwarfRegNums, on_first<LessRecordRegister>());
355 // Warn about duplicate assignments.
356 const Record *LastSeenReg = nullptr;
357 for (const auto &X : DwarfRegNums) {
358 const auto &Reg = X.first;
359 // The only way LessRecordRegister can return equal is if they're the same
360 // string. Use simple equality instead.
361 if (LastSeenReg && Reg->getName() == LastSeenReg->getName())
362 PrintWarning(Reg->getLoc(), Twine("DWARF numbers for register ") +
363 getQualifiedName(Reg) +
364 "specified multiple times");
365 LastSeenReg = Reg;
367 auto Last = llvm::unique(DwarfRegNums, [](const DwarfRegNumsMapPair &A,
368 const DwarfRegNumsMapPair &B) {
369 return A.first->getName() == B.first->getName();
371 DwarfRegNums.erase(Last, DwarfRegNums.end());
374 void RegisterInfoEmitter::EmitRegMappingTables(
375 raw_ostream &OS, const std::deque<CodeGenRegister> &Regs, bool isCtor) {
376 // Collect all information about dwarf register numbers
377 DwarfRegNumsVecTy DwarfRegNums;
379 // First, just pull all provided information to the map
380 unsigned maxLength = 0;
381 for (auto &RE : Regs) {
382 const Record *Reg = RE.TheDef;
383 std::vector<int64_t> RegNums = Reg->getValueAsListOfInts("DwarfNumbers");
384 maxLength = std::max((size_t)maxLength, RegNums.size());
385 DwarfRegNums.emplace_back(Reg, std::move(RegNums));
387 finalizeDwarfRegNumsKeys(DwarfRegNums);
389 if (!maxLength)
390 return;
392 // Now we know maximal length of number list. Append -1's, where needed
393 for (auto &DwarfRegNum : DwarfRegNums)
394 for (unsigned I = DwarfRegNum.second.size(), E = maxLength; I != E; ++I)
395 DwarfRegNum.second.push_back(-1);
397 StringRef Namespace = Regs.front().TheDef->getValueAsString("Namespace");
399 OS << "// " << Namespace << " Dwarf<->LLVM register mappings.\n";
401 // Emit reverse information about the dwarf register numbers.
402 for (unsigned j = 0; j < 2; ++j) {
403 for (unsigned I = 0, E = maxLength; I != E; ++I) {
404 OS << "extern const MCRegisterInfo::DwarfLLVMRegPair " << Namespace;
405 OS << (j == 0 ? "DwarfFlavour" : "EHFlavour");
406 OS << I << "Dwarf2L[]";
408 if (!isCtor) {
409 OS << " = {\n";
411 // Store the mapping sorted by the LLVM reg num so lookup can be done
412 // with a binary search.
413 std::map<uint64_t, const Record *> Dwarf2LMap;
414 for (auto &DwarfRegNum : DwarfRegNums) {
415 int DwarfRegNo = DwarfRegNum.second[I];
416 if (DwarfRegNo < 0)
417 continue;
418 Dwarf2LMap[DwarfRegNo] = DwarfRegNum.first;
421 for (auto &I : Dwarf2LMap)
422 OS << " { " << I.first << "U, " << getQualifiedName(I.second)
423 << " },\n";
425 OS << "};\n";
426 } else {
427 OS << ";\n";
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 << "Dwarf2LSize";
434 if (!isCtor)
435 OS << " = std::size(" << Namespace
436 << (j == 0 ? "DwarfFlavour" : "EHFlavour") << I << "Dwarf2L);\n\n";
437 else
438 OS << ";\n\n";
442 for (auto &RE : Regs) {
443 const Record *Reg = RE.TheDef;
444 const RecordVal *V = Reg->getValue("DwarfAlias");
445 if (!V || !V->getValue())
446 continue;
448 const DefInit *DI = cast<DefInit>(V->getValue());
449 const Record *Alias = DI->getDef();
450 const auto &AliasIter = llvm::lower_bound(
451 DwarfRegNums, Alias, [](const DwarfRegNumsMapPair &A, const Record *B) {
452 return LessRecordRegister()(A.first, B);
454 assert(AliasIter != DwarfRegNums.end() && AliasIter->first == Alias &&
455 "Expected Alias to be present in map");
456 const auto &RegIter = llvm::lower_bound(
457 DwarfRegNums, Reg, [](const DwarfRegNumsMapPair &A, const Record *B) {
458 return LessRecordRegister()(A.first, B);
460 assert(RegIter != DwarfRegNums.end() && RegIter->first == Reg &&
461 "Expected Reg to be present in map");
462 RegIter->second = AliasIter->second;
465 // Emit information about the dwarf register numbers.
466 for (unsigned j = 0; j < 2; ++j) {
467 for (unsigned i = 0, e = maxLength; i != e; ++i) {
468 OS << "extern const MCRegisterInfo::DwarfLLVMRegPair " << Namespace;
469 OS << (j == 0 ? "DwarfFlavour" : "EHFlavour");
470 OS << i << "L2Dwarf[]";
471 if (!isCtor) {
472 OS << " = {\n";
473 // Store the mapping sorted by the Dwarf reg num so lookup can be done
474 // with a binary search.
475 for (auto &DwarfRegNum : DwarfRegNums) {
476 int RegNo = DwarfRegNum.second[i];
477 if (RegNo == -1) // -1 is the default value, don't emit a mapping.
478 continue;
480 OS << " { " << getQualifiedName(DwarfRegNum.first) << ", " << RegNo
481 << "U },\n";
483 OS << "};\n";
484 } else {
485 OS << ";\n";
488 // We have to store the size in a const global, it's used in multiple
489 // places.
490 OS << "extern const unsigned " << Namespace
491 << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i << "L2DwarfSize";
492 if (!isCtor)
493 OS << " = std::size(" << Namespace
494 << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i << "L2Dwarf);\n\n";
495 else
496 OS << ";\n\n";
501 void RegisterInfoEmitter::EmitRegMapping(
502 raw_ostream &OS, const std::deque<CodeGenRegister> &Regs, bool isCtor) {
503 // Emit the initializer so the tables from EmitRegMappingTables get wired up
504 // to the MCRegisterInfo object.
505 unsigned maxLength = 0;
506 for (auto &RE : Regs) {
507 const Record *Reg = RE.TheDef;
508 maxLength = std::max((size_t)maxLength,
509 Reg->getValueAsListOfInts("DwarfNumbers").size());
512 if (!maxLength)
513 return;
515 StringRef Namespace = Regs.front().TheDef->getValueAsString("Namespace");
517 // Emit reverse information about the dwarf register numbers.
518 for (unsigned j = 0; j < 2; ++j) {
519 OS << " switch (";
520 if (j == 0)
521 OS << "DwarfFlavour";
522 else
523 OS << "EHFlavour";
524 OS << ") {\n"
525 << " default:\n"
526 << " llvm_unreachable(\"Unknown DWARF flavour\");\n";
528 for (unsigned i = 0, e = maxLength; i != e; ++i) {
529 OS << " case " << i << ":\n";
530 OS << " ";
531 if (!isCtor)
532 OS << "RI->";
533 std::string Tmp;
534 raw_string_ostream(Tmp)
535 << Namespace << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i
536 << "Dwarf2L";
537 OS << "mapDwarfRegsToLLVMRegs(" << Tmp << ", " << Tmp << "Size, ";
538 if (j == 0)
539 OS << "false";
540 else
541 OS << "true";
542 OS << ");\n";
543 OS << " break;\n";
545 OS << " }\n";
548 // Emit information about the dwarf register numbers.
549 for (unsigned j = 0; j < 2; ++j) {
550 OS << " switch (";
551 if (j == 0)
552 OS << "DwarfFlavour";
553 else
554 OS << "EHFlavour";
555 OS << ") {\n"
556 << " default:\n"
557 << " llvm_unreachable(\"Unknown DWARF flavour\");\n";
559 for (unsigned i = 0, e = maxLength; i != e; ++i) {
560 OS << " case " << i << ":\n";
561 OS << " ";
562 if (!isCtor)
563 OS << "RI->";
564 std::string Tmp;
565 raw_string_ostream(Tmp)
566 << Namespace << (j == 0 ? "DwarfFlavour" : "EHFlavour") << i
567 << "L2Dwarf";
568 OS << "mapLLVMRegsToDwarfRegs(" << Tmp << ", " << Tmp << "Size, ";
569 if (j == 0)
570 OS << "false";
571 else
572 OS << "true";
573 OS << ");\n";
574 OS << " break;\n";
576 OS << " }\n";
580 // Print a BitVector as a sequence of hex numbers using a little-endian mapping.
581 // Width is the number of bits per hex number.
582 static void printBitVectorAsHex(raw_ostream &OS, const BitVector &Bits,
583 unsigned Width) {
584 assert(Width <= 32 && "Width too large");
585 unsigned Digits = (Width + 3) / 4;
586 for (unsigned i = 0, e = Bits.size(); i < e; i += Width) {
587 unsigned Value = 0;
588 for (unsigned j = 0; j != Width && i + j != e; ++j)
589 Value |= Bits.test(i + j) << j;
590 OS << format("0x%0*x, ", Digits, Value);
594 // Helper to emit a set of bits into a constant byte array.
595 class BitVectorEmitter {
596 BitVector Values;
598 public:
599 void add(unsigned v) {
600 if (v >= Values.size())
601 Values.resize(((v / 8) + 1) * 8); // Round up to the next byte.
602 Values[v] = true;
605 void print(raw_ostream &OS) { printBitVectorAsHex(OS, Values, 8); }
608 static void printSimpleValueType(raw_ostream &OS, MVT::SimpleValueType VT) {
609 OS << getEnumName(VT);
612 static void printSubRegIndex(raw_ostream &OS, const CodeGenSubRegIndex *Idx) {
613 OS << Idx->EnumValue;
616 // Differentially encoded register and regunit lists allow for better
617 // compression on regular register banks. The sequence is computed from the
618 // differential list as:
620 // out[0] = InitVal;
621 // out[n+1] = out[n] + diff[n]; // n = 0, 1, ...
623 // The initial value depends on the specific list. The list is terminated by a
624 // 0 differential which means we can't encode repeated elements.
626 typedef SmallVector<int16_t, 4> DiffVec;
627 typedef SmallVector<LaneBitmask, 4> MaskVec;
629 // Fills V with differentials between every two consecutive elements of List.
630 static DiffVec &diffEncode(DiffVec &V, SparseBitVector<> List) {
631 assert(V.empty() && "Clear DiffVec before diffEncode.");
632 SparseBitVector<>::iterator I = List.begin(), E = List.end();
633 unsigned Val = *I;
634 while (++I != E) {
635 unsigned Cur = *I;
636 V.push_back(Cur - Val);
637 Val = Cur;
639 return V;
642 template <typename Iter>
643 static DiffVec &diffEncode(DiffVec &V, unsigned InitVal, Iter Begin, Iter End) {
644 assert(V.empty() && "Clear DiffVec before diffEncode.");
645 unsigned Val = InitVal;
646 for (Iter I = Begin; I != End; ++I) {
647 unsigned Cur = (*I)->EnumValue;
648 V.push_back(Cur - Val);
649 Val = Cur;
651 return V;
654 static void printDiff16(raw_ostream &OS, int16_t Val) { OS << Val; }
656 static void printMask(raw_ostream &OS, LaneBitmask Val) {
657 OS << "LaneBitmask(0x" << PrintLaneMask(Val) << ')';
660 // Try to combine Idx's compose map into Vec if it is compatible.
661 // Return false if it's not possible.
662 static bool combine(const CodeGenSubRegIndex *Idx,
663 SmallVectorImpl<CodeGenSubRegIndex *> &Vec) {
664 const CodeGenSubRegIndex::CompMap &Map = Idx->getComposites();
665 for (const auto &I : Map) {
666 CodeGenSubRegIndex *&Entry = Vec[I.first->EnumValue - 1];
667 if (Entry && Entry != I.second)
668 return false;
671 // All entries are compatible. Make it so.
672 for (const auto &I : Map) {
673 auto *&Entry = Vec[I.first->EnumValue - 1];
674 assert((!Entry || Entry == I.second) && "Expected EnumValue to be unique");
675 Entry = I.second;
677 return true;
680 void RegisterInfoEmitter::emitComposeSubRegIndices(raw_ostream &OS,
681 StringRef ClassName) {
682 const auto &SubRegIndices = RegBank.getSubRegIndices();
683 OS << "unsigned " << ClassName
684 << "::composeSubRegIndicesImpl(unsigned IdxA, unsigned IdxB) const {\n";
686 // Many sub-register indexes are composition-compatible, meaning that
688 // compose(IdxA, IdxB) == compose(IdxA', IdxB)
690 // for many IdxA, IdxA' pairs. Not all sub-register indexes can be composed.
691 // The illegal entries can be use as wildcards to compress the table further.
693 // Map each Sub-register index to a compatible table row.
694 SmallVector<unsigned, 4> RowMap;
695 SmallVector<SmallVector<CodeGenSubRegIndex *, 4>, 4> Rows;
697 auto SubRegIndicesSize =
698 std::distance(SubRegIndices.begin(), SubRegIndices.end());
699 for (const auto &Idx : SubRegIndices) {
700 unsigned Found = ~0u;
701 for (unsigned r = 0, re = Rows.size(); r != re; ++r) {
702 if (combine(&Idx, Rows[r])) {
703 Found = r;
704 break;
707 if (Found == ~0u) {
708 Found = Rows.size();
709 Rows.resize(Found + 1);
710 Rows.back().resize(SubRegIndicesSize);
711 combine(&Idx, Rows.back());
713 RowMap.push_back(Found);
716 // Output the row map if there is multiple rows.
717 if (Rows.size() > 1) {
718 OS << " static const " << getMinimalTypeForRange(Rows.size(), 32)
719 << " RowMap[" << SubRegIndicesSize << "] = {\n ";
720 for (unsigned i = 0, e = SubRegIndicesSize; i != e; ++i)
721 OS << RowMap[i] << ", ";
722 OS << "\n };\n";
725 // Output the rows.
726 OS << " static const " << getMinimalTypeForRange(SubRegIndicesSize + 1, 32)
727 << " Rows[" << Rows.size() << "][" << SubRegIndicesSize << "] = {\n";
728 for (unsigned r = 0, re = Rows.size(); r != re; ++r) {
729 OS << " { ";
730 for (unsigned i = 0, e = SubRegIndicesSize; i != e; ++i)
731 if (Rows[r][i])
732 OS << Rows[r][i]->getQualifiedName() << ", ";
733 else
734 OS << "0, ";
735 OS << "},\n";
737 OS << " };\n\n";
739 OS << " --IdxA; assert(IdxA < " << SubRegIndicesSize << "); (void) IdxA;\n"
740 << " --IdxB; assert(IdxB < " << SubRegIndicesSize << ");\n";
741 if (Rows.size() > 1)
742 OS << " return Rows[RowMap[IdxA]][IdxB];\n";
743 else
744 OS << " return Rows[0][IdxB];\n";
745 OS << "}\n\n";
748 void RegisterInfoEmitter::emitComposeSubRegIndexLaneMask(raw_ostream &OS,
749 StringRef ClassName) {
750 // See the comments in computeSubRegLaneMasks() for our goal here.
751 const auto &SubRegIndices = RegBank.getSubRegIndices();
753 // Create a list of Mask+Rotate operations, with equivalent entries merged.
754 SmallVector<unsigned, 4> SubReg2SequenceIndexMap;
755 SmallVector<SmallVector<MaskRolPair, 1>, 4> Sequences;
756 for (const auto &Idx : SubRegIndices) {
757 const SmallVector<MaskRolPair, 1> &IdxSequence =
758 Idx.CompositionLaneMaskTransform;
760 unsigned Found = ~0u;
761 unsigned SIdx = 0;
762 unsigned NextSIdx;
763 for (size_t s = 0, se = Sequences.size(); s != se; ++s, SIdx = NextSIdx) {
764 SmallVectorImpl<MaskRolPair> &Sequence = Sequences[s];
765 NextSIdx = SIdx + Sequence.size() + 1;
766 if (Sequence == IdxSequence) {
767 Found = SIdx;
768 break;
771 if (Found == ~0u) {
772 Sequences.push_back(IdxSequence);
773 Found = SIdx;
775 SubReg2SequenceIndexMap.push_back(Found);
778 OS << " struct MaskRolOp {\n"
779 " LaneBitmask Mask;\n"
780 " uint8_t RotateLeft;\n"
781 " };\n"
782 " static const MaskRolOp LaneMaskComposeSequences[] = {\n";
783 unsigned Idx = 0;
784 for (size_t s = 0, se = Sequences.size(); s != se; ++s) {
785 OS << " ";
786 const SmallVectorImpl<MaskRolPair> &Sequence = Sequences[s];
787 for (size_t p = 0, pe = Sequence.size(); p != pe; ++p) {
788 const MaskRolPair &P = Sequence[p];
789 printMask(OS << "{ ", P.Mask);
790 OS << format(", %2u }, ", P.RotateLeft);
792 OS << "{ LaneBitmask::getNone(), 0 }";
793 if (s + 1 != se)
794 OS << ", ";
795 OS << " // Sequence " << Idx << "\n";
796 Idx += Sequence.size() + 1;
798 auto *IntType =
799 getMinimalTypeForRange(*llvm::max_element(SubReg2SequenceIndexMap));
800 OS << " };\n"
801 " static const "
802 << IntType << " CompositeSequences[] = {\n";
803 for (size_t i = 0, e = SubRegIndices.size(); i != e; ++i) {
804 OS << " ";
805 OS << SubReg2SequenceIndexMap[i];
806 if (i + 1 != e)
807 OS << ",";
808 OS << " // to " << SubRegIndices[i].getName() << "\n";
810 OS << " };\n\n";
812 OS << "LaneBitmask " << ClassName
813 << "::composeSubRegIndexLaneMaskImpl(unsigned IdxA, LaneBitmask LaneMask)"
814 " const {\n"
815 " --IdxA; assert(IdxA < "
816 << SubRegIndices.size()
817 << " && \"Subregister index out of bounds\");\n"
818 " LaneBitmask Result;\n"
819 " for (const MaskRolOp *Ops =\n"
820 " &LaneMaskComposeSequences[CompositeSequences[IdxA]];\n"
821 " Ops->Mask.any(); ++Ops) {\n"
822 " LaneBitmask::Type M = LaneMask.getAsInteger() & "
823 "Ops->Mask.getAsInteger();\n"
824 " if (unsigned S = Ops->RotateLeft)\n"
825 " Result |= LaneBitmask((M << S) | (M >> (LaneBitmask::BitWidth - "
826 "S)));\n"
827 " else\n"
828 " Result |= LaneBitmask(M);\n"
829 " }\n"
830 " return Result;\n"
831 "}\n\n";
833 OS << "LaneBitmask " << ClassName
834 << "::reverseComposeSubRegIndexLaneMaskImpl(unsigned IdxA, "
835 " LaneBitmask LaneMask) const {\n"
836 " LaneMask &= getSubRegIndexLaneMask(IdxA);\n"
837 " --IdxA; assert(IdxA < "
838 << SubRegIndices.size()
839 << " && \"Subregister index out of bounds\");\n"
840 " LaneBitmask Result;\n"
841 " for (const MaskRolOp *Ops =\n"
842 " &LaneMaskComposeSequences[CompositeSequences[IdxA]];\n"
843 " Ops->Mask.any(); ++Ops) {\n"
844 " LaneBitmask::Type M = LaneMask.getAsInteger();\n"
845 " if (unsigned S = Ops->RotateLeft)\n"
846 " Result |= LaneBitmask((M >> S) | (M << (LaneBitmask::BitWidth - "
847 "S)));\n"
848 " else\n"
849 " Result |= LaneBitmask(M);\n"
850 " }\n"
851 " return Result;\n"
852 "}\n\n";
856 // runMCDesc - Print out MC register descriptions.
858 void RegisterInfoEmitter::runMCDesc(raw_ostream &OS) {
859 emitSourceFileHeader("MC Register Information", OS);
861 OS << "\n#ifdef GET_REGINFO_MC_DESC\n";
862 OS << "#undef GET_REGINFO_MC_DESC\n\n";
864 const auto &Regs = RegBank.getRegisters();
866 auto &SubRegIndices = RegBank.getSubRegIndices();
867 // The lists of sub-registers and super-registers go in the same array. That
868 // allows us to share suffixes.
869 typedef std::vector<const CodeGenRegister *> RegVec;
871 // Differentially encoded lists.
872 SequenceToOffsetTable<DiffVec> DiffSeqs;
873 SmallVector<DiffVec, 4> SubRegLists(Regs.size());
874 SmallVector<DiffVec, 4> SuperRegLists(Regs.size());
875 SmallVector<DiffVec, 4> RegUnitLists(Regs.size());
877 // List of lane masks accompanying register unit sequences.
878 SequenceToOffsetTable<MaskVec> LaneMaskSeqs;
879 SmallVector<MaskVec, 4> RegUnitLaneMasks(Regs.size());
881 // Keep track of sub-register names as well. These are not differentially
882 // encoded.
883 typedef SmallVector<const CodeGenSubRegIndex *, 4> SubRegIdxVec;
884 SequenceToOffsetTable<SubRegIdxVec, deref<std::less<>>> SubRegIdxSeqs;
885 SmallVector<SubRegIdxVec, 4> SubRegIdxLists(Regs.size());
887 SequenceToOffsetTable<std::string> RegStrings;
889 // Precompute register lists for the SequenceToOffsetTable.
890 unsigned i = 0;
891 for (auto I = Regs.begin(), E = Regs.end(); I != E; ++I, ++i) {
892 const auto &Reg = *I;
893 RegStrings.add(std::string(Reg.getName()));
895 // Compute the ordered sub-register list.
896 SetVector<const CodeGenRegister *> SR;
897 Reg.addSubRegsPreOrder(SR, RegBank);
898 diffEncode(SubRegLists[i], Reg.EnumValue, SR.begin(), SR.end());
899 DiffSeqs.add(SubRegLists[i]);
901 // Compute the corresponding sub-register indexes.
902 SubRegIdxVec &SRIs = SubRegIdxLists[i];
903 for (const CodeGenRegister *S : SR)
904 SRIs.push_back(Reg.getSubRegIndex(S));
905 SubRegIdxSeqs.add(SRIs);
907 // Super-registers are already computed.
908 const RegVec &SuperRegList = Reg.getSuperRegs();
909 diffEncode(SuperRegLists[i], Reg.EnumValue, SuperRegList.begin(),
910 SuperRegList.end());
911 DiffSeqs.add(SuperRegLists[i]);
913 const SparseBitVector<> &RUs = Reg.getNativeRegUnits();
914 DiffSeqs.add(diffEncode(RegUnitLists[i], RUs));
916 const auto &RUMasks = Reg.getRegUnitLaneMasks();
917 MaskVec &LaneMaskVec = RegUnitLaneMasks[i];
918 assert(LaneMaskVec.empty());
919 llvm::append_range(LaneMaskVec, RUMasks);
920 LaneMaskSeqs.add(LaneMaskVec);
923 // Compute the final layout of the sequence table.
924 DiffSeqs.layout();
925 LaneMaskSeqs.layout();
926 SubRegIdxSeqs.layout();
928 OS << "namespace llvm {\n\n";
930 const std::string &TargetName = std::string(Target.getName());
932 // Emit the shared table of differential lists.
933 OS << "extern const int16_t " << TargetName << "RegDiffLists[] = {\n";
934 DiffSeqs.emit(OS, printDiff16);
935 OS << "};\n\n";
937 // Emit the shared table of regunit lane mask sequences.
938 OS << "extern const LaneBitmask " << TargetName << "LaneMaskLists[] = {\n";
939 // TODO: Omit the terminator since it is never used. The length of this list
940 // is known implicitly from the corresponding reg unit list.
941 LaneMaskSeqs.emit(OS, printMask, "LaneBitmask::getAll()");
942 OS << "};\n\n";
944 // Emit the table of sub-register indexes.
945 OS << "extern const uint16_t " << TargetName << "SubRegIdxLists[] = {\n";
946 SubRegIdxSeqs.emit(OS, printSubRegIndex);
947 OS << "};\n\n";
949 // Emit the string table.
950 RegStrings.layout();
951 RegStrings.emitStringLiteralDef(OS, Twine("extern const char ") + TargetName +
952 "RegStrings[]");
954 OS << "extern const MCRegisterDesc " << TargetName
955 << "RegDesc[] = { // Descriptors\n";
956 OS << " { " << RegStrings.get("") << ", 0, 0, 0, 0, 0, 0, 0 },\n";
958 // Emit the register descriptors now.
959 i = 0;
960 for (const auto &Reg : Regs) {
961 unsigned FirstRU = Reg.getNativeRegUnits().find_first();
962 unsigned Offset = DiffSeqs.get(RegUnitLists[i]);
963 // The value must be kept in sync with MCRegisterInfo.h.
964 constexpr unsigned RegUnitBits = 12;
965 assert(isUInt<RegUnitBits>(FirstRU) && "Too many regunits");
966 assert(isUInt<32 - RegUnitBits>(Offset) && "Offset is too big");
967 OS << " { " << RegStrings.get(std::string(Reg.getName())) << ", "
968 << DiffSeqs.get(SubRegLists[i]) << ", " << DiffSeqs.get(SuperRegLists[i])
969 << ", " << SubRegIdxSeqs.get(SubRegIdxLists[i]) << ", "
970 << (Offset << RegUnitBits | FirstRU) << ", "
971 << LaneMaskSeqs.get(RegUnitLaneMasks[i]) << ", " << Reg.Constant << ", "
972 << Reg.Artificial << " },\n";
973 ++i;
975 OS << "};\n\n"; // End of register descriptors...
977 // Emit the table of register unit roots. Each regunit has one or two root
978 // registers.
979 OS << "extern const MCPhysReg " << TargetName << "RegUnitRoots[][2] = {\n";
980 for (unsigned i = 0, e = RegBank.getNumNativeRegUnits(); i != e; ++i) {
981 ArrayRef<const CodeGenRegister *> Roots = RegBank.getRegUnit(i).getRoots();
982 assert(!Roots.empty() && "All regunits must have a root register.");
983 assert(Roots.size() <= 2 && "More than two roots not supported yet.");
984 OS << " { ";
985 ListSeparator LS;
986 for (const CodeGenRegister *R : Roots)
987 OS << LS << getQualifiedName(R->TheDef);
988 OS << " },\n";
990 OS << "};\n\n";
992 const auto &RegisterClasses = RegBank.getRegClasses();
994 // Loop over all of the register classes... emitting each one.
995 OS << "namespace { // Register classes...\n";
997 SequenceToOffsetTable<std::string> RegClassStrings;
999 // Emit the register enum value arrays for each RegisterClass
1000 for (const auto &RC : RegisterClasses) {
1001 ArrayRef<const Record *> Order = RC.getOrder();
1003 // Give the register class a legal C name if it's anonymous.
1004 const std::string &Name = RC.getName();
1006 RegClassStrings.add(Name);
1008 // Emit the register list now (unless it would be a zero-length array).
1009 if (!Order.empty()) {
1010 OS << " // " << Name << " Register Class...\n"
1011 << " const MCPhysReg " << Name << "[] = {\n ";
1012 for (const Record *Reg : Order) {
1013 OS << getQualifiedName(Reg) << ", ";
1015 OS << "\n };\n\n";
1017 OS << " // " << Name << " Bit set.\n"
1018 << " const uint8_t " << Name << "Bits[] = {\n ";
1019 BitVectorEmitter BVE;
1020 for (const Record *Reg : Order) {
1021 BVE.add(RegBank.getReg(Reg)->EnumValue);
1023 BVE.print(OS);
1024 OS << "\n };\n\n";
1027 OS << "} // end anonymous namespace\n\n";
1029 RegClassStrings.layout();
1030 RegClassStrings.emitStringLiteralDef(
1031 OS, Twine("extern const char ") + TargetName + "RegClassStrings[]");
1033 OS << "extern const MCRegisterClass " << TargetName
1034 << "MCRegisterClasses[] = {\n";
1036 for (const auto &RC : RegisterClasses) {
1037 ArrayRef<const Record *> Order = RC.getOrder();
1038 std::string RCName = Order.empty() ? "nullptr" : RC.getName();
1039 std::string RCBitsName = Order.empty() ? "nullptr" : RC.getName() + "Bits";
1040 std::string RCBitsSize = Order.empty() ? "0" : "sizeof(" + RCBitsName + ")";
1041 assert(isInt<8>(RC.CopyCost) && "Copy cost too large.");
1042 uint32_t RegSize = 0;
1043 if (RC.RSI.isSimple())
1044 RegSize = RC.RSI.getSimple().RegSize;
1045 OS << " { " << RCName << ", " << RCBitsName << ", "
1046 << RegClassStrings.get(RC.getName()) << ", " << RC.getOrder().size()
1047 << ", " << RCBitsSize << ", " << RC.getQualifiedIdName() << ", "
1048 << RegSize << ", " << RC.CopyCost << ", "
1049 << (RC.Allocatable ? "true" : "false") << ", "
1050 << (RC.getBaseClassOrder() ? "true" : "false") << " },\n";
1053 OS << "};\n\n";
1055 EmitRegMappingTables(OS, Regs, false);
1057 // Emit Reg encoding table
1058 OS << "extern const uint16_t " << TargetName;
1059 OS << "RegEncodingTable[] = {\n";
1060 // Add entry for NoRegister
1061 OS << " 0,\n";
1062 for (const auto &RE : Regs) {
1063 const Record *Reg = RE.TheDef;
1064 const BitsInit *BI = Reg->getValueAsBitsInit("HWEncoding");
1065 uint64_t Value = 0;
1066 for (unsigned b = 0, be = BI->getNumBits(); b != be; ++b) {
1067 if (const BitInit *B = dyn_cast<BitInit>(BI->getBit(b)))
1068 Value |= (uint64_t)B->getValue() << b;
1070 OS << " " << Value << ",\n";
1072 OS << "};\n"; // End of HW encoding table
1074 // MCRegisterInfo initialization routine.
1075 OS << "static inline void Init" << TargetName
1076 << "MCRegisterInfo(MCRegisterInfo *RI, unsigned RA, "
1077 << "unsigned DwarfFlavour = 0, unsigned EHFlavour = 0, unsigned PC = 0) "
1078 "{\n"
1079 << " RI->InitMCRegisterInfo(" << TargetName << "RegDesc, "
1080 << Regs.size() + 1 << ", RA, PC, " << TargetName << "MCRegisterClasses, "
1081 << RegisterClasses.size() << ", " << TargetName << "RegUnitRoots, "
1082 << RegBank.getNumNativeRegUnits() << ", " << TargetName << "RegDiffLists, "
1083 << TargetName << "LaneMaskLists, " << TargetName << "RegStrings, "
1084 << TargetName << "RegClassStrings, " << TargetName << "SubRegIdxLists, "
1085 << (std::distance(SubRegIndices.begin(), SubRegIndices.end()) + 1) << ",\n"
1086 << TargetName << "RegEncodingTable);\n\n";
1088 EmitRegMapping(OS, Regs, false);
1090 OS << "}\n\n";
1092 OS << "} // end namespace llvm\n\n";
1093 OS << "#endif // GET_REGINFO_MC_DESC\n\n";
1096 void RegisterInfoEmitter::runTargetHeader(raw_ostream &OS) {
1097 emitSourceFileHeader("Register Information Header Fragment", OS);
1099 OS << "\n#ifdef GET_REGINFO_HEADER\n";
1100 OS << "#undef GET_REGINFO_HEADER\n\n";
1102 const std::string &TargetName = std::string(Target.getName());
1103 std::string ClassName = TargetName + "GenRegisterInfo";
1105 OS << "#include \"llvm/CodeGen/TargetRegisterInfo.h\"\n\n";
1107 OS << "namespace llvm {\n\n";
1109 OS << "class " << TargetName << "FrameLowering;\n\n";
1111 OS << "struct " << ClassName << " : public TargetRegisterInfo {\n"
1112 << " explicit " << ClassName
1113 << "(unsigned RA, unsigned D = 0, unsigned E = 0,\n"
1114 << " unsigned PC = 0, unsigned HwMode = 0);\n";
1115 if (!RegBank.getSubRegIndices().empty()) {
1116 OS << " unsigned composeSubRegIndicesImpl"
1117 << "(unsigned, unsigned) const override;\n"
1118 << " LaneBitmask composeSubRegIndexLaneMaskImpl"
1119 << "(unsigned, LaneBitmask) const override;\n"
1120 << " LaneBitmask reverseComposeSubRegIndexLaneMaskImpl"
1121 << "(unsigned, LaneBitmask) const override;\n"
1122 << " const TargetRegisterClass *getSubClassWithSubReg"
1123 << "(const TargetRegisterClass *, unsigned) const override;\n"
1124 << " const TargetRegisterClass *getSubRegisterClass"
1125 << "(const TargetRegisterClass *, unsigned) const override;\n";
1127 OS << " const RegClassWeight &getRegClassWeight("
1128 << "const TargetRegisterClass *RC) const override;\n"
1129 << " unsigned getRegUnitWeight(unsigned RegUnit) const override;\n"
1130 << " unsigned getNumRegPressureSets() const override;\n"
1131 << " const char *getRegPressureSetName(unsigned Idx) const override;\n"
1132 << " unsigned getRegPressureSetLimit(const MachineFunction &MF, unsigned "
1133 "Idx) const override;\n"
1134 << " const int *getRegClassPressureSets("
1135 << "const TargetRegisterClass *RC) const override;\n"
1136 << " const int *getRegUnitPressureSets("
1137 << "unsigned RegUnit) const override;\n"
1138 << " ArrayRef<const char *> getRegMaskNames() const override;\n"
1139 << " ArrayRef<const uint32_t *> getRegMasks() const override;\n"
1140 << " bool isGeneralPurposeRegister(const MachineFunction &, "
1141 << "MCRegister) const override;\n"
1142 << " bool isGeneralPurposeRegisterClass(const TargetRegisterClass *RC)"
1143 << " const override;\n"
1144 << " bool isFixedRegister(const MachineFunction &, "
1145 << "MCRegister) const override;\n"
1146 << " bool isArgumentRegister(const MachineFunction &, "
1147 << "MCRegister) const override;\n"
1148 << " bool isConstantPhysReg(MCRegister PhysReg) const override final;\n"
1149 << " /// Devirtualized TargetFrameLowering.\n"
1150 << " static const " << TargetName << "FrameLowering *getFrameLowering(\n"
1151 << " const MachineFunction &MF);\n";
1153 const auto &RegisterClasses = RegBank.getRegClasses();
1154 if (llvm::any_of(RegisterClasses,
1155 [](const auto &RC) { return RC.getBaseClassOrder(); })) {
1156 OS << " const TargetRegisterClass *getPhysRegBaseClass(MCRegister Reg) "
1157 "const override;\n";
1160 OS << "};\n\n";
1162 if (!RegisterClasses.empty()) {
1163 OS << "namespace " << RegisterClasses.front().Namespace
1164 << " { // Register classes\n";
1166 for (const auto &RC : RegisterClasses) {
1167 const std::string &Name = RC.getName();
1169 // Output the extern for the instance.
1170 OS << " extern const TargetRegisterClass " << Name << "RegClass;\n";
1172 OS << "} // end namespace " << RegisterClasses.front().Namespace << "\n\n";
1174 OS << "} // end namespace llvm\n\n";
1175 OS << "#endif // GET_REGINFO_HEADER\n\n";
1179 // runTargetDesc - Output the target register and register file descriptions.
1181 void RegisterInfoEmitter::runTargetDesc(raw_ostream &OS) {
1182 emitSourceFileHeader("Target Register and Register Classes Information", OS);
1184 OS << "\n#ifdef GET_REGINFO_TARGET_DESC\n";
1185 OS << "#undef GET_REGINFO_TARGET_DESC\n\n";
1187 OS << "namespace llvm {\n\n";
1189 // Get access to MCRegisterClass data.
1190 OS << "extern const MCRegisterClass " << Target.getName()
1191 << "MCRegisterClasses[];\n";
1193 // Start out by emitting each of the register classes.
1194 const auto &RegisterClasses = RegBank.getRegClasses();
1195 const auto &SubRegIndices = RegBank.getSubRegIndices();
1197 // Collect all registers belonging to any allocatable class.
1198 std::set<const Record *> AllocatableRegs;
1200 // Collect allocatable registers.
1201 for (const auto &RC : RegisterClasses) {
1202 ArrayRef<const Record *> Order = RC.getOrder();
1204 if (RC.Allocatable)
1205 AllocatableRegs.insert(Order.begin(), Order.end());
1208 const CodeGenHwModes &CGH = Target.getHwModes();
1209 unsigned NumModes = CGH.getNumModeIds();
1211 // Build a shared array of value types.
1212 SequenceToOffsetTable<std::vector<MVT::SimpleValueType>> VTSeqs;
1213 for (unsigned M = 0; M < NumModes; ++M) {
1214 for (const auto &RC : RegisterClasses) {
1215 std::vector<MVT::SimpleValueType> S;
1216 for (const ValueTypeByHwMode &VVT : RC.VTs)
1217 if (VVT.hasDefault() || VVT.hasMode(M))
1218 S.push_back(VVT.get(M).SimpleTy);
1219 VTSeqs.add(S);
1222 VTSeqs.layout();
1223 OS << "\nstatic const MVT::SimpleValueType VTLists[] = {\n";
1224 VTSeqs.emit(OS, printSimpleValueType, "MVT::Other");
1225 OS << "};\n";
1227 // Emit SubRegIndex names, skipping 0.
1228 OS << "\nstatic const char *SubRegIndexNameTable[] = { \"";
1230 for (const auto &Idx : SubRegIndices) {
1231 OS << Idx.getName();
1232 OS << "\", \"";
1234 OS << "\" };\n\n";
1236 // Emit the table of sub-register index sizes.
1237 OS << "static const TargetRegisterInfo::SubRegCoveredBits "
1238 "SubRegIdxRangeTable[] = {\n";
1239 for (unsigned M = 0; M < NumModes; ++M) {
1240 OS << " { " << (uint16_t)-1 << ", " << (uint16_t)-1 << " },\n";
1241 for (const auto &Idx : SubRegIndices) {
1242 const SubRegRange &Range = Idx.Range.get(M);
1243 OS << " { " << Range.Offset << ", " << Range.Size << " },\t// "
1244 << Idx.getName() << "\n";
1247 OS << "};\n\n";
1249 // Emit SubRegIndex lane masks, including 0.
1250 OS << "\nstatic const LaneBitmask SubRegIndexLaneMaskTable[] = {\n "
1251 "LaneBitmask::getAll(),\n";
1252 for (const auto &Idx : SubRegIndices) {
1253 printMask(OS << " ", Idx.LaneMask);
1254 OS << ", // " << Idx.getName() << '\n';
1256 OS << " };\n\n";
1258 OS << "\n";
1260 // Now that all of the structs have been emitted, emit the instances.
1261 if (!RegisterClasses.empty()) {
1262 OS << "\nstatic const TargetRegisterInfo::RegClassInfo RegClassInfos[]"
1263 << " = {\n";
1264 for (unsigned M = 0; M < NumModes; ++M) {
1265 unsigned EV = 0;
1266 OS << " // Mode = " << M << " (";
1267 if (M == 0)
1268 OS << "Default";
1269 else
1270 OS << CGH.getMode(M).Name;
1271 OS << ")\n";
1272 for (const auto &RC : RegisterClasses) {
1273 assert(RC.EnumValue == EV && "Unexpected order of register classes");
1274 ++EV;
1275 (void)EV;
1276 const RegSizeInfo &RI = RC.RSI.get(M);
1277 OS << " { " << RI.RegSize << ", " << RI.SpillSize << ", "
1278 << RI.SpillAlignment;
1279 std::vector<MVT::SimpleValueType> VTs;
1280 for (const ValueTypeByHwMode &VVT : RC.VTs)
1281 if (VVT.hasDefault() || VVT.hasMode(M))
1282 VTs.push_back(VVT.get(M).SimpleTy);
1283 OS << ", /*VTLists+*/" << VTSeqs.get(VTs) << " }, // "
1284 << RC.getName() << '\n';
1287 OS << "};\n";
1289 OS << "\nstatic const TargetRegisterClass *const "
1290 << "NullRegClasses[] = { nullptr };\n\n";
1292 // Emit register class bit mask tables. The first bit mask emitted for a
1293 // register class, RC, is the set of sub-classes, including RC itself.
1295 // If RC has super-registers, also create a list of subreg indices and bit
1296 // masks, (Idx, Mask). The bit mask has a bit for every superreg regclass,
1297 // SuperRC, that satisfies:
1299 // For all SuperReg in SuperRC: SuperReg:Idx in RC
1301 // The 0-terminated list of subreg indices starts at:
1303 // RC->getSuperRegIndices() = SuperRegIdxSeqs + ...
1305 // The corresponding bitmasks follow the sub-class mask in memory. Each
1306 // mask has RCMaskWords uint32_t entries.
1308 // Every bit mask present in the list has at least one bit set.
1310 // Compress the sub-reg index lists.
1311 typedef std::vector<const CodeGenSubRegIndex *> IdxList;
1312 SmallVector<IdxList, 8> SuperRegIdxLists(RegisterClasses.size());
1313 SequenceToOffsetTable<IdxList, deref<std::less<>>> SuperRegIdxSeqs;
1314 BitVector MaskBV(RegisterClasses.size());
1316 for (const auto &RC : RegisterClasses) {
1317 OS << "static const uint32_t " << RC.getName()
1318 << "SubClassMask[] = {\n ";
1319 printBitVectorAsHex(OS, RC.getSubClasses(), 32);
1321 // Emit super-reg class masks for any relevant SubRegIndices that can
1322 // project into RC.
1323 IdxList &SRIList = SuperRegIdxLists[RC.EnumValue];
1324 for (auto &Idx : SubRegIndices) {
1325 MaskBV.reset();
1326 RC.getSuperRegClasses(&Idx, MaskBV);
1327 if (MaskBV.none())
1328 continue;
1329 SRIList.push_back(&Idx);
1330 OS << "\n ";
1331 printBitVectorAsHex(OS, MaskBV, 32);
1332 OS << "// " << Idx.getName();
1334 SuperRegIdxSeqs.add(SRIList);
1335 OS << "\n};\n\n";
1338 OS << "static const uint16_t SuperRegIdxSeqs[] = {\n";
1339 SuperRegIdxSeqs.layout();
1340 SuperRegIdxSeqs.emit(OS, printSubRegIndex);
1341 OS << "};\n\n";
1343 // Emit NULL terminated super-class lists.
1344 for (const auto &RC : RegisterClasses) {
1345 ArrayRef<CodeGenRegisterClass *> Supers = RC.getSuperClasses();
1347 // Skip classes without supers. We can reuse NullRegClasses.
1348 if (Supers.empty())
1349 continue;
1351 OS << "static const TargetRegisterClass *const " << RC.getName()
1352 << "Superclasses[] = {\n";
1353 for (const auto *Super : Supers)
1354 OS << " &" << Super->getQualifiedName() << "RegClass,\n";
1355 OS << " nullptr\n};\n\n";
1358 // Emit methods.
1359 for (const auto &RC : RegisterClasses) {
1360 if (!RC.AltOrderSelect.empty()) {
1361 OS << "\nstatic inline unsigned " << RC.getName()
1362 << "AltOrderSelect(const MachineFunction &MF) {" << RC.AltOrderSelect
1363 << "}\n\n"
1364 << "static ArrayRef<MCPhysReg> " << RC.getName()
1365 << "GetRawAllocationOrder(const MachineFunction &MF) {\n";
1366 for (unsigned oi = 1, oe = RC.getNumOrders(); oi != oe; ++oi) {
1367 ArrayRef<const Record *> Elems = RC.getOrder(oi);
1368 if (!Elems.empty()) {
1369 OS << " static const MCPhysReg AltOrder" << oi << "[] = {";
1370 for (unsigned elem = 0; elem != Elems.size(); ++elem)
1371 OS << (elem ? ", " : " ") << getQualifiedName(Elems[elem]);
1372 OS << " };\n";
1375 OS << " const MCRegisterClass &MCR = " << Target.getName()
1376 << "MCRegisterClasses[" << RC.getQualifiedName() + "RegClassID];\n"
1377 << " const ArrayRef<MCPhysReg> Order[] = {\n"
1378 << " ArrayRef(MCR.begin(), MCR.getNumRegs()";
1379 for (unsigned oi = 1, oe = RC.getNumOrders(); oi != oe; ++oi)
1380 if (RC.getOrder(oi).empty())
1381 OS << "),\n ArrayRef<MCPhysReg>(";
1382 else
1383 OS << "),\n ArrayRef(AltOrder" << oi;
1384 OS << ")\n };\n const unsigned Select = " << RC.getName()
1385 << "AltOrderSelect(MF);\n assert(Select < " << RC.getNumOrders()
1386 << ");\n return Order[Select];\n}\n";
1390 // Now emit the actual value-initialized register class instances.
1391 OS << "\nnamespace " << RegisterClasses.front().Namespace
1392 << " { // Register class instances\n";
1394 for (const auto &RC : RegisterClasses) {
1395 OS << " extern const TargetRegisterClass " << RC.getName()
1396 << "RegClass = {\n " << '&' << Target.getName()
1397 << "MCRegisterClasses[" << RC.getName() << "RegClassID],\n "
1398 << RC.getName() << "SubClassMask,\n SuperRegIdxSeqs + "
1399 << SuperRegIdxSeqs.get(SuperRegIdxLists[RC.EnumValue]) << ",\n ";
1400 printMask(OS, RC.LaneMask);
1401 OS << ",\n " << (unsigned)RC.AllocationPriority << ",\n "
1402 << (RC.GlobalPriority ? "true" : "false") << ",\n "
1403 << format("0x%02x", RC.TSFlags) << ", /* TSFlags */\n "
1404 << (RC.HasDisjunctSubRegs ? "true" : "false")
1405 << ", /* HasDisjunctSubRegs */\n "
1406 << (RC.CoveredBySubRegs ? "true" : "false")
1407 << ", /* CoveredBySubRegs */\n ";
1408 if (RC.getSuperClasses().empty())
1409 OS << "NullRegClasses,\n ";
1410 else
1411 OS << RC.getName() << "Superclasses,\n ";
1412 if (RC.AltOrderSelect.empty())
1413 OS << "nullptr\n";
1414 else
1415 OS << RC.getName() << "GetRawAllocationOrder\n";
1416 OS << " };\n\n";
1419 OS << "} // end namespace " << RegisterClasses.front().Namespace << "\n";
1422 OS << "\nnamespace {\n";
1423 OS << " const TargetRegisterClass *const RegisterClasses[] = {\n";
1424 for (const auto &RC : RegisterClasses)
1425 OS << " &" << RC.getQualifiedName() << "RegClass,\n";
1426 OS << " };\n";
1427 OS << "} // end anonymous namespace\n";
1429 // Emit extra information about registers.
1430 const std::string &TargetName = std::string(Target.getName());
1431 const auto &Regs = RegBank.getRegisters();
1432 unsigned NumRegCosts = 1;
1433 for (const auto &Reg : Regs)
1434 NumRegCosts = std::max((size_t)NumRegCosts, Reg.CostPerUse.size());
1436 std::vector<unsigned> AllRegCostPerUse;
1437 llvm::BitVector InAllocClass(Regs.size() + 1, false);
1438 AllRegCostPerUse.insert(AllRegCostPerUse.end(), NumRegCosts, 0);
1440 // Populate the vector RegCosts with the CostPerUse list of the registers
1441 // in the order they are read. Have at most NumRegCosts entries for
1442 // each register. Fill with zero for values which are not explicitly given.
1443 for (const auto &Reg : Regs) {
1444 auto Costs = Reg.CostPerUse;
1445 AllRegCostPerUse.insert(AllRegCostPerUse.end(), Costs.begin(), Costs.end());
1446 if (NumRegCosts > Costs.size())
1447 AllRegCostPerUse.insert(AllRegCostPerUse.end(),
1448 NumRegCosts - Costs.size(), 0);
1450 if (AllocatableRegs.count(Reg.TheDef))
1451 InAllocClass.set(Reg.EnumValue);
1454 // Emit the cost values as a 1D-array after grouping them by their indices,
1455 // i.e. the costs for all registers corresponds to index 0, 1, 2, etc.
1456 // Size of the emitted array should be NumRegCosts * (Regs.size() + 1).
1457 OS << "\nstatic const uint8_t "
1458 << "CostPerUseTable[] = { \n";
1459 for (unsigned int I = 0; I < NumRegCosts; ++I) {
1460 for (unsigned J = I, E = AllRegCostPerUse.size(); J < E; J += NumRegCosts)
1461 OS << AllRegCostPerUse[J] << ", ";
1463 OS << "};\n\n";
1465 OS << "\nstatic const bool "
1466 << "InAllocatableClassTable[] = { \n";
1467 for (unsigned I = 0, E = InAllocClass.size(); I < E; ++I) {
1468 OS << (InAllocClass[I] ? "true" : "false") << ", ";
1470 OS << "};\n\n";
1472 OS << "\nstatic const TargetRegisterInfoDesc " << TargetName
1473 << "RegInfoDesc = { // Extra Descriptors\n";
1474 OS << "CostPerUseTable, " << NumRegCosts << ", "
1475 << "InAllocatableClassTable";
1476 OS << "};\n\n"; // End of register descriptors...
1478 std::string ClassName = Target.getName().str() + "GenRegisterInfo";
1480 auto SubRegIndicesSize =
1481 std::distance(SubRegIndices.begin(), SubRegIndices.end());
1483 if (!SubRegIndices.empty()) {
1484 emitComposeSubRegIndices(OS, ClassName);
1485 emitComposeSubRegIndexLaneMask(OS, ClassName);
1488 if (!SubRegIndices.empty()) {
1489 // Emit getSubClassWithSubReg.
1490 OS << "const TargetRegisterClass *" << ClassName
1491 << "::getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx)"
1492 << " const {\n";
1493 // Use the smallest type that can hold a regclass ID with room for a
1494 // sentinel.
1495 if (RegisterClasses.size() <= UINT8_MAX)
1496 OS << " static const uint8_t Table[";
1497 else if (RegisterClasses.size() <= UINT16_MAX)
1498 OS << " static const uint16_t Table[";
1499 else
1500 PrintFatalError("Too many register classes.");
1501 OS << RegisterClasses.size() << "][" << SubRegIndicesSize << "] = {\n";
1502 for (const auto &RC : RegisterClasses) {
1503 OS << " {\t// " << RC.getName() << "\n";
1504 for (auto &Idx : SubRegIndices) {
1505 if (CodeGenRegisterClass *SRC = RC.getSubClassWithSubReg(&Idx))
1506 OS << " " << SRC->EnumValue + 1 << ",\t// " << Idx.getName()
1507 << " -> " << SRC->getName() << "\n";
1508 else
1509 OS << " 0,\t// " << Idx.getName() << "\n";
1511 OS << " },\n";
1513 OS << " };\n assert(RC && \"Missing regclass\");\n"
1514 << " if (!Idx) return RC;\n --Idx;\n"
1515 << " assert(Idx < " << SubRegIndicesSize << " && \"Bad subreg\");\n"
1516 << " unsigned TV = Table[RC->getID()][Idx];\n"
1517 << " return TV ? getRegClass(TV - 1) : nullptr;\n}\n\n";
1519 // Emit getSubRegisterClass
1520 OS << "const TargetRegisterClass *" << ClassName
1521 << "::getSubRegisterClass(const TargetRegisterClass *RC, unsigned Idx)"
1522 << " const {\n";
1524 // Use the smallest type that can hold a regclass ID with room for a
1525 // sentinel.
1526 if (RegisterClasses.size() <= UINT8_MAX)
1527 OS << " static const uint8_t Table[";
1528 else if (RegisterClasses.size() <= UINT16_MAX)
1529 OS << " static const uint16_t Table[";
1530 else
1531 PrintFatalError("Too many register classes.");
1533 OS << RegisterClasses.size() << "][" << SubRegIndicesSize << "] = {\n";
1535 for (const auto &RC : RegisterClasses) {
1536 OS << " {\t// " << RC.getName() << '\n';
1537 for (auto &Idx : SubRegIndices) {
1538 std::optional<std::pair<CodeGenRegisterClass *, CodeGenRegisterClass *>>
1539 MatchingSubClass = RC.getMatchingSubClassWithSubRegs(RegBank, &Idx);
1541 unsigned EnumValue = 0;
1542 if (MatchingSubClass) {
1543 CodeGenRegisterClass *SubRegClass = MatchingSubClass->second;
1544 EnumValue = SubRegClass->EnumValue + 1;
1547 OS << " " << EnumValue << ",\t// " << RC.getName() << ':'
1548 << Idx.getName();
1550 if (MatchingSubClass) {
1551 CodeGenRegisterClass *SubRegClass = MatchingSubClass->second;
1552 OS << " -> " << SubRegClass->getName();
1555 OS << '\n';
1558 OS << " },\n";
1560 OS << " };\n assert(RC && \"Missing regclass\");\n"
1561 << " if (!Idx) return RC;\n --Idx;\n"
1562 << " assert(Idx < " << SubRegIndicesSize << " && \"Bad subreg\");\n"
1563 << " unsigned TV = Table[RC->getID()][Idx];\n"
1564 << " return TV ? getRegClass(TV - 1) : nullptr;\n}\n\n";
1567 EmitRegUnitPressure(OS, ClassName);
1569 // Emit register base class mapper
1570 if (!RegisterClasses.empty()) {
1571 // Collect base classes
1572 SmallVector<const CodeGenRegisterClass *> BaseClasses;
1573 for (const auto &RC : RegisterClasses) {
1574 if (RC.getBaseClassOrder())
1575 BaseClasses.push_back(&RC);
1577 if (!BaseClasses.empty()) {
1578 assert(BaseClasses.size() < UINT16_MAX &&
1579 "Too many base register classes");
1581 // Apply order
1582 struct BaseClassOrdering {
1583 bool operator()(const CodeGenRegisterClass *LHS,
1584 const CodeGenRegisterClass *RHS) const {
1585 return std::pair(*LHS->getBaseClassOrder(), LHS->EnumValue) <
1586 std::pair(*RHS->getBaseClassOrder(), RHS->EnumValue);
1589 llvm::stable_sort(BaseClasses, BaseClassOrdering());
1591 OS << "\n// Register to base register class mapping\n\n";
1592 OS << "\n";
1593 OS << "const TargetRegisterClass *" << ClassName
1594 << "::getPhysRegBaseClass(MCRegister Reg)"
1595 << " const {\n";
1596 OS << " static const uint16_t InvalidRegClassID = UINT16_MAX;\n\n";
1597 OS << " static const uint16_t Mapping[" << Regs.size() + 1 << "] = {\n";
1598 OS << " InvalidRegClassID, // NoRegister\n";
1599 for (const CodeGenRegister &Reg : Regs) {
1600 const CodeGenRegisterClass *BaseRC = nullptr;
1601 for (const CodeGenRegisterClass *RC : BaseClasses) {
1602 if (is_contained(RC->getMembers(), &Reg)) {
1603 BaseRC = RC;
1604 break;
1608 OS << " "
1609 << (BaseRC ? BaseRC->getQualifiedIdName() : "InvalidRegClassID")
1610 << ", // " << Reg.getName() << "\n";
1612 OS << " };\n\n"
1613 " assert(Reg < ArrayRef(Mapping).size());\n"
1614 " unsigned RCID = Mapping[Reg];\n"
1615 " if (RCID == InvalidRegClassID)\n"
1616 " return nullptr;\n"
1617 " return RegisterClasses[RCID];\n"
1618 "}\n";
1622 // Emit the constructor of the class...
1623 OS << "extern const MCRegisterDesc " << TargetName << "RegDesc[];\n";
1624 OS << "extern const int16_t " << TargetName << "RegDiffLists[];\n";
1625 OS << "extern const LaneBitmask " << TargetName << "LaneMaskLists[];\n";
1626 OS << "extern const char " << TargetName << "RegStrings[];\n";
1627 OS << "extern const char " << TargetName << "RegClassStrings[];\n";
1628 OS << "extern const MCPhysReg " << TargetName << "RegUnitRoots[][2];\n";
1629 OS << "extern const uint16_t " << TargetName << "SubRegIdxLists[];\n";
1630 OS << "extern const uint16_t " << TargetName << "RegEncodingTable[];\n";
1632 EmitRegMappingTables(OS, Regs, true);
1634 OS << ClassName << "::\n"
1635 << ClassName
1636 << "(unsigned RA, unsigned DwarfFlavour, unsigned EHFlavour,\n"
1637 " unsigned PC, unsigned HwMode)\n"
1638 << " : TargetRegisterInfo(&" << TargetName << "RegInfoDesc"
1639 << ", RegisterClasses, RegisterClasses+" << RegisterClasses.size() << ",\n"
1640 << " SubRegIndexNameTable, SubRegIdxRangeTable, "
1641 "SubRegIndexLaneMaskTable,\n"
1642 << " ";
1643 printMask(OS, RegBank.CoveringLanes);
1644 OS << ", RegClassInfos, VTLists, HwMode) {\n"
1645 << " InitMCRegisterInfo(" << TargetName << "RegDesc, " << Regs.size() + 1
1646 << ", RA, PC,\n " << TargetName
1647 << "MCRegisterClasses, " << RegisterClasses.size() << ",\n"
1648 << " " << TargetName << "RegUnitRoots,\n"
1649 << " " << RegBank.getNumNativeRegUnits() << ",\n"
1650 << " " << TargetName << "RegDiffLists,\n"
1651 << " " << TargetName << "LaneMaskLists,\n"
1652 << " " << TargetName << "RegStrings,\n"
1653 << " " << TargetName << "RegClassStrings,\n"
1654 << " " << TargetName << "SubRegIdxLists,\n"
1655 << " " << SubRegIndicesSize + 1 << ",\n"
1656 << " " << TargetName << "RegEncodingTable);\n\n";
1658 EmitRegMapping(OS, Regs, true);
1660 OS << "}\n\n";
1662 // Emit CalleeSavedRegs information.
1663 ArrayRef<const Record *> CSRSets =
1664 Records.getAllDerivedDefinitions("CalleeSavedRegs");
1665 for (const Record *CSRSet : CSRSets) {
1666 const SetTheory::RecVec *Regs = RegBank.getSets().expand(CSRSet);
1667 assert(Regs && "Cannot expand CalleeSavedRegs instance");
1669 // Emit the *_SaveList list of callee-saved registers.
1670 OS << "static const MCPhysReg " << CSRSet->getName() << "_SaveList[] = { ";
1671 for (const Record *Reg : *Regs)
1672 OS << getQualifiedName(Reg) << ", ";
1673 OS << "0 };\n";
1675 // Emit the *_RegMask bit mask of call-preserved registers.
1676 BitVector Covered = RegBank.computeCoveredRegisters(*Regs);
1678 // Check for an optional OtherPreserved set.
1679 // Add those registers to RegMask, but not to SaveList.
1680 if (const DagInit *OPDag =
1681 dyn_cast<DagInit>(CSRSet->getValueInit("OtherPreserved"))) {
1682 SetTheory::RecSet OPSet;
1683 RegBank.getSets().evaluate(OPDag, OPSet, CSRSet->getLoc());
1684 Covered |= RegBank.computeCoveredRegisters(OPSet.getArrayRef());
1687 // Add all constant physical registers to the preserved mask:
1688 SetTheory::RecSet ConstantSet;
1689 for (const auto &Reg : RegBank.getRegisters()) {
1690 if (Reg.Constant)
1691 ConstantSet.insert(Reg.TheDef);
1693 Covered |= RegBank.computeCoveredRegisters(ConstantSet.getArrayRef());
1695 OS << "static const uint32_t " << CSRSet->getName() << "_RegMask[] = { ";
1696 printBitVectorAsHex(OS, Covered, 32);
1697 OS << "};\n";
1699 OS << "\n\n";
1701 OS << "ArrayRef<const uint32_t *> " << ClassName
1702 << "::getRegMasks() const {\n";
1703 if (!CSRSets.empty()) {
1704 OS << " static const uint32_t *const Masks[] = {\n";
1705 for (const Record *CSRSet : CSRSets)
1706 OS << " " << CSRSet->getName() << "_RegMask,\n";
1707 OS << " };\n";
1708 OS << " return ArrayRef(Masks);\n";
1709 } else {
1710 OS << " return {};\n";
1712 OS << "}\n\n";
1714 const std::list<CodeGenRegisterCategory> &RegCategories =
1715 RegBank.getRegCategories();
1716 OS << "bool " << ClassName << "::\n"
1717 << "isGeneralPurposeRegister(const MachineFunction &MF, "
1718 << "MCRegister PhysReg) const {\n"
1719 << " return\n";
1720 for (const CodeGenRegisterCategory &Category : RegCategories)
1721 if (Category.getName() == "GeneralPurposeRegisters") {
1722 for (const CodeGenRegisterClass *RC : Category.getClasses())
1723 OS << " " << RC->getQualifiedName()
1724 << "RegClass.contains(PhysReg) ||\n";
1725 break;
1727 OS << " false;\n";
1728 OS << "}\n\n";
1730 OS << "bool " << ClassName << "::\n"
1731 << "isGeneralPurposeRegisterClass(const TargetRegisterClass *RC)"
1732 << " const {\n"
1733 << " return\n";
1734 for (const CodeGenRegisterCategory &Category : RegCategories)
1735 if (Category.getName() == "GeneralPurposeRegisters") {
1736 for (const CodeGenRegisterClass *RC : Category.getClasses())
1737 OS << " " << RC->getQualifiedName()
1738 << "RegClass.hasSubClassEq(RC) ||\n";
1739 break;
1741 OS << " false;\n";
1742 OS << "}\n\n";
1744 OS << "bool " << ClassName << "::\n"
1745 << "isFixedRegister(const MachineFunction &MF, "
1746 << "MCRegister PhysReg) const {\n"
1747 << " return\n";
1748 for (const CodeGenRegisterCategory &Category : RegCategories)
1749 if (Category.getName() == "FixedRegisters") {
1750 for (const CodeGenRegisterClass *RC : Category.getClasses())
1751 OS << " " << RC->getQualifiedName()
1752 << "RegClass.contains(PhysReg) ||\n";
1753 break;
1755 OS << " false;\n";
1756 OS << "}\n\n";
1758 OS << "bool " << ClassName << "::\n"
1759 << "isArgumentRegister(const MachineFunction &MF, "
1760 << "MCRegister PhysReg) const {\n"
1761 << " return\n";
1762 for (const CodeGenRegisterCategory &Category : RegCategories)
1763 if (Category.getName() == "ArgumentRegisters") {
1764 for (const CodeGenRegisterClass *RC : Category.getClasses())
1765 OS << " " << RC->getQualifiedName()
1766 << "RegClass.contains(PhysReg) ||\n";
1767 break;
1769 OS << " false;\n";
1770 OS << "}\n\n";
1772 OS << "bool " << ClassName << "::\n"
1773 << "isConstantPhysReg(MCRegister PhysReg) const {\n"
1774 << " return\n";
1775 for (const auto &Reg : Regs)
1776 if (Reg.Constant)
1777 OS << " PhysReg == " << getQualifiedName(Reg.TheDef) << " ||\n";
1778 OS << " false;\n";
1779 OS << "}\n\n";
1781 OS << "ArrayRef<const char *> " << ClassName
1782 << "::getRegMaskNames() const {\n";
1783 if (!CSRSets.empty()) {
1784 OS << " static const char *Names[] = {\n";
1785 for (const Record *CSRSet : CSRSets)
1786 OS << " " << '"' << CSRSet->getName() << '"' << ",\n";
1787 OS << " };\n";
1788 OS << " return ArrayRef(Names);\n";
1789 } else {
1790 OS << " return {};\n";
1792 OS << "}\n\n";
1794 OS << "const " << TargetName << "FrameLowering *\n"
1795 << TargetName
1796 << "GenRegisterInfo::getFrameLowering(const MachineFunction &MF) {\n"
1797 << " return static_cast<const " << TargetName << "FrameLowering *>(\n"
1798 << " MF.getSubtarget().getFrameLowering());\n"
1799 << "}\n\n";
1801 OS << "} // end namespace llvm\n\n";
1802 OS << "#endif // GET_REGINFO_TARGET_DESC\n\n";
1805 void RegisterInfoEmitter::run(raw_ostream &OS) {
1806 TGTimer &Timer = Records.getTimer();
1807 Timer.startTimer("Print enums");
1808 runEnums(OS);
1810 Timer.startTimer("Print MC registers");
1811 runMCDesc(OS);
1813 Timer.startTimer("Print header fragment");
1814 runTargetHeader(OS);
1816 Timer.startTimer("Print target registers");
1817 runTargetDesc(OS);
1819 if (RegisterInfoDebug)
1820 debugDump(errs());
1823 void RegisterInfoEmitter::debugDump(raw_ostream &OS) {
1824 const CodeGenHwModes &CGH = Target.getHwModes();
1825 unsigned NumModes = CGH.getNumModeIds();
1826 auto getModeName = [CGH](unsigned M) -> StringRef {
1827 if (M == 0)
1828 return "Default";
1829 return CGH.getMode(M).Name;
1832 for (const CodeGenRegisterClass &RC : RegBank.getRegClasses()) {
1833 OS << "RegisterClass " << RC.getName() << ":\n";
1834 OS << "\tSpillSize: {";
1835 for (unsigned M = 0; M != NumModes; ++M)
1836 OS << ' ' << getModeName(M) << ':' << RC.RSI.get(M).SpillSize;
1837 OS << " }\n\tSpillAlignment: {";
1838 for (unsigned M = 0; M != NumModes; ++M)
1839 OS << ' ' << getModeName(M) << ':' << RC.RSI.get(M).SpillAlignment;
1840 OS << " }\n\tNumRegs: " << RC.getMembers().size() << '\n';
1841 OS << "\tLaneMask: " << PrintLaneMask(RC.LaneMask) << '\n';
1842 OS << "\tHasDisjunctSubRegs: " << RC.HasDisjunctSubRegs << '\n';
1843 OS << "\tCoveredBySubRegs: " << RC.CoveredBySubRegs << '\n';
1844 OS << "\tAllocatable: " << RC.Allocatable << '\n';
1845 OS << "\tAllocationPriority: " << unsigned(RC.AllocationPriority) << '\n';
1846 OS << "\tBaseClassOrder: " << RC.getBaseClassOrder() << '\n';
1847 OS << "\tRegs:";
1848 for (const CodeGenRegister *R : RC.getMembers()) {
1849 OS << " " << R->getName();
1851 OS << '\n';
1852 OS << "\tSubClasses:";
1853 const BitVector &SubClasses = RC.getSubClasses();
1854 for (const CodeGenRegisterClass &SRC : RegBank.getRegClasses()) {
1855 if (!SubClasses.test(SRC.EnumValue))
1856 continue;
1857 OS << " " << SRC.getName();
1859 OS << '\n';
1860 OS << "\tSuperClasses:";
1861 for (const CodeGenRegisterClass *SRC : RC.getSuperClasses()) {
1862 OS << " " << SRC->getName();
1864 OS << '\n';
1867 for (const CodeGenSubRegIndex &SRI : RegBank.getSubRegIndices()) {
1868 OS << "SubRegIndex " << SRI.getName() << ":\n";
1869 OS << "\tLaneMask: " << PrintLaneMask(SRI.LaneMask) << '\n';
1870 OS << "\tAllSuperRegsCovered: " << SRI.AllSuperRegsCovered << '\n';
1871 OS << "\tOffset: {";
1872 for (unsigned M = 0; M != NumModes; ++M)
1873 OS << ' ' << getModeName(M) << ':' << SRI.Range.get(M).Offset;
1874 OS << " }\n\tSize: {";
1875 for (unsigned M = 0; M != NumModes; ++M)
1876 OS << ' ' << getModeName(M) << ':' << SRI.Range.get(M).Size;
1877 OS << " }\n";
1880 for (const CodeGenRegister &R : RegBank.getRegisters()) {
1881 OS << "Register " << R.getName() << ":\n";
1882 OS << "\tCostPerUse: ";
1883 for (const auto &Cost : R.CostPerUse)
1884 OS << Cost << " ";
1885 OS << '\n';
1886 OS << "\tCoveredBySubregs: " << R.CoveredBySubRegs << '\n';
1887 OS << "\tHasDisjunctSubRegs: " << R.HasDisjunctSubRegs << '\n';
1888 for (std::pair<CodeGenSubRegIndex *, CodeGenRegister *> P :
1889 R.getSubRegs()) {
1890 OS << "\tSubReg " << P.first->getName() << " = " << P.second->getName()
1891 << '\n';
1896 static TableGen::Emitter::OptClass<RegisterInfoEmitter>
1897 X("gen-register-info", "Generate registers and register classes info");