RegisterInfoEmitter.cpp 63 KB

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