]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/utils/TableGen/RegisterBankEmitter.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304460, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / utils / TableGen / RegisterBankEmitter.cpp
1 //===- RegisterBankEmitter.cpp - Generate a Register Bank Desc. -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend is responsible for emitting a description of a target
11 // register bank for a code generator.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/Support/Debug.h"
17 #include "llvm/TableGen/Error.h"
18 #include "llvm/TableGen/Record.h"
19 #include "llvm/TableGen/TableGenBackend.h"
20
21 #include "CodeGenRegisters.h"
22
23 #define DEBUG_TYPE "register-bank-emitter"
24
25 using namespace llvm;
26
27 namespace {
28 class RegisterBank {
29
30   /// A vector of register classes that are included in the register bank.
31   typedef std::vector<const CodeGenRegisterClass *> RegisterClassesTy;
32
33 private:
34   const Record &TheDef;
35
36   /// The register classes that are covered by the register bank.
37   RegisterClassesTy RCs;
38
39   /// The register class with the largest register size.
40   const CodeGenRegisterClass *RCWithLargestRegsSize;
41
42 public:
43   RegisterBank(const Record &TheDef)
44       : TheDef(TheDef), RCs(), RCWithLargestRegsSize(nullptr) {}
45
46   /// Get the human-readable name for the bank.
47   StringRef getName() const { return TheDef.getValueAsString("Name"); }
48   /// Get the name of the enumerator in the ID enumeration.
49   std::string getEnumeratorName() const { return (TheDef.getName() + "ID").str(); }
50
51   /// Get the name of the array holding the register class coverage data;
52   std::string getCoverageArrayName() const {
53     return (TheDef.getName() + "CoverageData").str();
54   }
55
56   /// Get the name of the global instance variable.
57   StringRef getInstanceVarName() const { return TheDef.getName(); }
58
59   const Record &getDef() const { return TheDef; }
60
61   /// Get the register classes listed in the RegisterBank.RegisterClasses field.
62   std::vector<const CodeGenRegisterClass *>
63   getExplictlySpecifiedRegisterClasses(
64       CodeGenRegBank &RegisterClassHierarchy) const {
65     std::vector<const CodeGenRegisterClass *> RCs;
66     for (const auto &RCDef : getDef().getValueAsListOfDefs("RegisterClasses"))
67       RCs.push_back(RegisterClassHierarchy.getRegClass(RCDef));
68     return RCs;
69   }
70
71   /// Add a register class to the bank without duplicates.
72   void addRegisterClass(const CodeGenRegisterClass *RC) {
73     if (std::find_if(RCs.begin(), RCs.end(),
74                      [&RC](const CodeGenRegisterClass *X) {
75                        return X == RC;
76                      }) != RCs.end())
77       return;
78
79     // FIXME? We really want the register size rather than the spill size
80     //        since the spill size may be bigger on some targets with
81     //        limited load/store instructions. However, we don't store the
82     //        register size anywhere (we could sum the sizes of the subregisters
83     //        but there may be additional bits too) and we can't derive it from
84     //        the VT's reliably due to Untyped.
85     if (RCWithLargestRegsSize == nullptr)
86       RCWithLargestRegsSize = RC;
87     else if (RCWithLargestRegsSize->SpillSize < RC->SpillSize)
88       RCWithLargestRegsSize = RC;
89     assert(RCWithLargestRegsSize && "RC was nullptr?");
90
91     RCs.emplace_back(RC);
92   }
93
94   const CodeGenRegisterClass *getRCWithLargestRegsSize() const {
95     return RCWithLargestRegsSize;
96   }
97
98   iterator_range<typename RegisterClassesTy::const_iterator>
99   register_classes() const {
100     return llvm::make_range(RCs.begin(), RCs.end());
101   }
102 };
103
104 class RegisterBankEmitter {
105 private:
106   RecordKeeper &Records;
107   CodeGenRegBank RegisterClassHierarchy;
108
109   void emitHeader(raw_ostream &OS, const StringRef TargetName,
110                   const std::vector<RegisterBank> &Banks);
111   void emitBaseClassDefinition(raw_ostream &OS, const StringRef TargetName,
112                                const std::vector<RegisterBank> &Banks);
113   void emitBaseClassImplementation(raw_ostream &OS, const StringRef TargetName,
114                                    std::vector<RegisterBank> &Banks);
115
116 public:
117   RegisterBankEmitter(RecordKeeper &R)
118       : Records(R), RegisterClassHierarchy(Records) {}
119
120   void run(raw_ostream &OS);
121 };
122
123 } // end anonymous namespace
124
125 /// Emit code to declare the ID enumeration and external global instance
126 /// variables.
127 void RegisterBankEmitter::emitHeader(raw_ostream &OS,
128                                      const StringRef TargetName,
129                                      const std::vector<RegisterBank> &Banks) {
130   // <Target>RegisterBankInfo.h
131   OS << "namespace llvm {\n"
132      << "namespace " << TargetName << " {\n"
133      << "enum {\n";
134   for (const auto &Bank : Banks)
135     OS << "  " << Bank.getEnumeratorName() << ",\n";
136   OS << "  NumRegisterBanks,\n"
137      << "};\n"
138      << "} // end namespace " << TargetName << "\n"
139      << "} // end namespace llvm\n";
140 }
141
142 /// Emit declarations of the <Target>GenRegisterBankInfo class.
143 void RegisterBankEmitter::emitBaseClassDefinition(
144     raw_ostream &OS, const StringRef TargetName,
145     const std::vector<RegisterBank> &Banks) {
146   OS << "private:\n"
147      << "  static RegisterBank *RegBanks[];\n\n"
148      << "protected:\n"
149      << "  " << TargetName << "GenRegisterBankInfo();\n"
150      << "\n";
151 }
152
153 /// Visit each register class belonging to the given register bank.
154 ///
155 /// A class belongs to the bank iff any of these apply:
156 /// * It is explicitly specified
157 /// * It is a subclass of a class that is a member.
158 /// * It is a class containing subregisters of the registers of a class that
159 ///   is a member. This is known as a subreg-class.
160 ///
161 /// This function must be called for each explicitly specified register class.
162 ///
163 /// \param RC The register class to search.
164 /// \param Kind A debug string containing the path the visitor took to reach RC.
165 /// \param VisitFn The action to take for each class visited. It may be called
166 ///                multiple times for a given class if there are multiple paths
167 ///                to the class.
168 static void visitRegisterBankClasses(
169     CodeGenRegBank &RegisterClassHierarchy, const CodeGenRegisterClass *RC,
170     const Twine Kind,
171     std::function<void(const CodeGenRegisterClass *, StringRef)> VisitFn,
172     SmallPtrSetImpl<const CodeGenRegisterClass *> &VisitedRCs) {
173
174   // Make sure we only visit each class once to avoid infinite loops.
175   if (VisitedRCs.count(RC))
176     return;
177   VisitedRCs.insert(RC);
178
179   // Visit each explicitly named class.
180   VisitFn(RC, Kind.str());
181
182   for (const auto &PossibleSubclass : RegisterClassHierarchy.getRegClasses()) {
183     std::string TmpKind =
184         (Twine(Kind) + " (" + PossibleSubclass.getName() + ")").str();
185
186     // Visit each subclass of an explicitly named class.
187     if (RC != &PossibleSubclass && RC->hasSubClass(&PossibleSubclass))
188       visitRegisterBankClasses(RegisterClassHierarchy, &PossibleSubclass,
189                                TmpKind + " " + RC->getName() + " subclass",
190                                VisitFn, VisitedRCs);
191
192     // Visit each class that contains only subregisters of RC with a common
193     // subregister-index.
194     //
195     // More precisely, PossibleSubclass is a subreg-class iff Reg:SubIdx is in
196     // PossibleSubclass for all registers Reg from RC using any
197     // subregister-index SubReg
198     for (const auto &SubIdx : RegisterClassHierarchy.getSubRegIndices()) {
199       BitVector BV(RegisterClassHierarchy.getRegClasses().size());
200       PossibleSubclass.getSuperRegClasses(&SubIdx, BV);
201       if (BV.test(RC->EnumValue)) {
202         std::string TmpKind2 = (Twine(TmpKind) + " " + RC->getName() +
203                                 " class-with-subregs: " + RC->getName())
204                                    .str();
205         VisitFn(&PossibleSubclass, TmpKind2);
206       }
207     }
208   }
209 }
210
211 void RegisterBankEmitter::emitBaseClassImplementation(
212     raw_ostream &OS, StringRef TargetName,
213     std::vector<RegisterBank> &Banks) {
214
215   OS << "namespace llvm {\n"
216      << "namespace " << TargetName << " {\n";
217   for (const auto &Bank : Banks) {
218     std::vector<std::vector<const CodeGenRegisterClass *>> RCsGroupedByWord(
219         (RegisterClassHierarchy.getRegClasses().size() + 31) / 32);
220
221     for (const auto &RC : Bank.register_classes())
222       RCsGroupedByWord[RC->EnumValue / 32].push_back(RC);
223
224     OS << "const uint32_t " << Bank.getCoverageArrayName() << "[] = {\n";
225     unsigned LowestIdxInWord = 0;
226     for (const auto &RCs : RCsGroupedByWord) {
227       OS << "    // " << LowestIdxInWord << "-" << (LowestIdxInWord + 31) << "\n";
228       for (const auto &RC : RCs) {
229         std::string QualifiedRegClassID =
230             (Twine(TargetName) + "::" + RC->getName() + "RegClassID").str();
231         OS << "    (1u << (" << QualifiedRegClassID << " - "
232            << LowestIdxInWord << ")) |\n";
233       }
234       OS << "    0,\n";
235       LowestIdxInWord += 32;
236     }
237     OS << "};\n";
238   }
239   OS << "\n";
240
241   for (const auto &Bank : Banks) {
242     std::string QualifiedBankID =
243         (TargetName + "::" + Bank.getEnumeratorName()).str();
244     unsigned Size = Bank.getRCWithLargestRegsSize()->SpillSize;
245     OS << "RegisterBank " << Bank.getInstanceVarName() << "(/* ID */ "
246        << QualifiedBankID << ", /* Name */ \"" << Bank.getName()
247        << "\", /* Size */ " << Size << ", "
248        << "/* CoveredRegClasses */ " << Bank.getCoverageArrayName()
249        << ", /* NumRegClasses */ "
250        << RegisterClassHierarchy.getRegClasses().size() << ");\n";
251   }
252   OS << "} // end namespace " << TargetName << "\n"
253      << "\n";
254
255   OS << "RegisterBank *" << TargetName
256      << "GenRegisterBankInfo::RegBanks[] = {\n";
257   for (const auto &Bank : Banks)
258     OS << "    &" << TargetName << "::" << Bank.getInstanceVarName() << ",\n";
259   OS << "};\n\n";
260
261   OS << TargetName << "GenRegisterBankInfo::" << TargetName
262      << "GenRegisterBankInfo()\n"
263      << "    : RegisterBankInfo(RegBanks, " << TargetName
264      << "::NumRegisterBanks) {\n"
265      << "  // Assert that RegBank indices match their ID's\n"
266      << "#ifndef NDEBUG\n"
267      << "  unsigned Index = 0;\n"
268      << "  for (const auto &RB : RegBanks)\n"
269      << "    assert(Index++ == RB->getID() && \"Index != ID\");\n"
270      << "#endif // NDEBUG\n"
271      << "}\n"
272      << "} // end namespace llvm\n";
273 }
274
275 void RegisterBankEmitter::run(raw_ostream &OS) {
276   std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
277   if (Targets.size() != 1)
278     PrintFatalError("ERROR: Too many or too few subclasses of Target defined!");
279   StringRef TargetName = Targets[0]->getName();
280
281   std::vector<RegisterBank> Banks;
282   for (const auto &V : Records.getAllDerivedDefinitions("RegisterBank")) {
283     SmallPtrSet<const CodeGenRegisterClass *, 8> VisitedRCs;
284     RegisterBank Bank(*V);
285
286     for (const CodeGenRegisterClass *RC :
287          Bank.getExplictlySpecifiedRegisterClasses(RegisterClassHierarchy)) {
288       visitRegisterBankClasses(
289           RegisterClassHierarchy, RC, "explicit",
290           [&Bank](const CodeGenRegisterClass *RC, StringRef Kind) {
291             DEBUG(dbgs() << "Added " << RC->getName() << "(" << Kind << ")\n");
292             Bank.addRegisterClass(RC);
293           }, VisitedRCs);
294     }
295
296     Banks.push_back(Bank);
297   }
298
299   emitSourceFileHeader("Register Bank Source Fragments", OS);
300   OS << "#ifdef GET_REGBANK_DECLARATIONS\n"
301      << "#undef GET_REGBANK_DECLARATIONS\n";
302   emitHeader(OS, TargetName, Banks);
303   OS << "#endif // GET_REGBANK_DECLARATIONS\n\n"
304      << "#ifdef GET_TARGET_REGBANK_CLASS\n"
305      << "#undef GET_TARGET_REGBANK_CLASS\n";
306   emitBaseClassDefinition(OS, TargetName, Banks);
307   OS << "#endif // GET_TARGET_REGBANK_CLASS\n\n"
308      << "#ifdef GET_TARGET_REGBANK_IMPL\n"
309      << "#undef GET_TARGET_REGBANK_IMPL\n";
310   emitBaseClassImplementation(OS, TargetName, Banks);
311   OS << "#endif // GET_TARGET_REGBANK_IMPL\n";
312 }
313
314 namespace llvm {
315
316 void EmitRegisterBank(RecordKeeper &RK, raw_ostream &OS) {
317   RegisterBankEmitter(RK).run(OS);
318 }
319
320 } // end namespace llvm