1//===- ARMTargetDefEmitter.cpp - Generate data about ARM Architectures ----===//
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 exports information about CPUs, FPUs, architectures,
10// and features into a common format that can be used by both TargetParser and
11// the ARM and AArch64 backends.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/StringSet.h"
17#include "llvm/Support/Format.h"
18#include "llvm/TableGen/Error.h"
19#include "llvm/TableGen/Record.h"
20#include "llvm/TableGen/StringToOffsetTable.h"
21#include "llvm/TableGen/TableGenBackend.h"
22#include <set>
23#include <string>
24
25using namespace llvm;
26
27/// Collect the full set of implied features for a SubtargetFeature.
28static void collectImpliedFeatures(std::set<const Record *> &SeenFeats,
29 const Record *Rec) {
30 assert(Rec->isSubClassOf("SubtargetFeature") &&
31 "Rec is not a SubtargetFeature");
32
33 SeenFeats.insert(x: Rec);
34 for (const Record *Implied : Rec->getValueAsListOfDefs(FieldName: "Implies"))
35 collectImpliedFeatures(SeenFeats, Rec: Implied);
36}
37
38static void checkFeatureTree(const Record *Root) {
39 std::set<const Record *> SeenFeats;
40 collectImpliedFeatures(SeenFeats, Rec: Root);
41
42 // Check that each of the mandatory (implied) features which is an
43 // ExtensionWithMArch is also enabled by default.
44 auto DefaultExtsVec = Root->getValueAsListOfDefs(FieldName: "DefaultExts");
45 std::set<const Record *> DefaultExts{DefaultExtsVec.begin(),
46 DefaultExtsVec.end()};
47 for (const Record *Feat : SeenFeats) {
48 if (Feat->isSubClassOf(Name: "ExtensionWithMArch") && !DefaultExts.count(x: Feat))
49 PrintFatalError(ErrorLoc: Root->getLoc(),
50 Msg: "ExtensionWithMArch " + Feat->getName() +
51 " is implied (mandatory) as a SubtargetFeature, but "
52 "is not present in DefaultExts");
53 }
54}
55
56static void emitARMTargetDef(const RecordKeeper &RK, raw_ostream &OS) {
57 OS << "// Autogenerated by ARMTargetDefEmitter.cpp\n\n";
58
59 // Look through all SubtargetFeature defs with the given FieldName, and
60 // collect the set of all Values that that FieldName is set to.
61 auto GatherSubtargetFeatureFieldValues = [&RK](StringRef FieldName) {
62 llvm::StringSet<> Set;
63 for (const Record *Rec : RK.getAllDerivedDefinitions(ClassName: "SubtargetFeature")) {
64 if (Rec->getValueAsString(FieldName: "FieldName") == FieldName) {
65 Set.insert(key: Rec->getValueAsString(FieldName: "Value"));
66 }
67 }
68 return Set;
69 };
70
71 // Sort the extensions alphabetically, so they don't appear in tablegen order.
72 std::vector<const Record *> SortedExtensions =
73 RK.getAllDerivedDefinitions(ClassName: "Extension");
74 auto Alphabetical = [](const Record *A, const Record *B) -> bool {
75 const auto NameA = A->getValueAsString(FieldName: "Name");
76 const auto NameB = B->getValueAsString(FieldName: "Name");
77 return NameA.compare(RHS: NameB) < 0; // A lexographically less than B
78 };
79 sort(C&: SortedExtensions, Comp: Alphabetical);
80
81 // Cache Extension records for quick lookup.
82 DenseMap<StringRef, const Record *> ExtensionMap;
83 for (const Record *Rec : SortedExtensions) {
84 auto Name = Rec->getValueAsString(FieldName: "UserVisibleName");
85 if (Name.empty())
86 Name = Rec->getValueAsString(FieldName: "Name");
87 ExtensionMap[Name] = Rec;
88 }
89
90 // The ARMProcFamilyEnum values are initialised by SubtargetFeature defs
91 // which set the ARMProcFamily field. We can generate the enum from these defs
92 // which look like this:
93 //
94 // def ProcA5 : SubtargetFeature<"a5", "ARMProcFamily", "CortexA5",
95 // "Cortex-A5 ARM processors", []>;
96 OS << "#ifndef ARM_PROCESSOR_FAMILY\n"
97 << "#define ARM_PROCESSOR_FAMILY(ENUM)\n"
98 << "#endif\n\n";
99 const StringSet<> ARMProcFamilyVals =
100 GatherSubtargetFeatureFieldValues("ARMProcFamily");
101 for (const StringRef &Family : ARMProcFamilyVals.keys())
102 OS << "ARM_PROCESSOR_FAMILY(" << Family << ")\n";
103 OS << "\n#undef ARM_PROCESSOR_FAMILY\n\n";
104
105 OS << "#ifndef ARM_ARCHITECTURE\n"
106 << "#define ARM_ARCHITECTURE(ENUM)\n"
107 << "#endif\n\n";
108 // This should correspond to instances of the Architecture tablegen class.
109 const StringSet<> ARMArchVals = GatherSubtargetFeatureFieldValues("ARMArch");
110 for (const StringRef &Arch : ARMArchVals.keys())
111 OS << "ARM_ARCHITECTURE(" << Arch << ")\n";
112 OS << "\n#undef ARM_ARCHITECTURE\n\n";
113
114 // Currently only AArch64 (not ARM) is handled beyond this point.
115 if (!RK.getClass(Name: "Architecture64"))
116 return;
117
118 StringToOffsetTable StrTab;
119
120 // Emit the ArchExtKind enum
121 OS << "#ifdef EMIT_ARCHEXTKIND_ENUM\n"
122 << "enum ArchExtKind : unsigned {\n";
123 for (const Record *Rec : SortedExtensions) {
124 auto AEK = Rec->getValueAsString(FieldName: "ArchExtKindSpelling").upper();
125 OS << " " << AEK << ",\n";
126 }
127 OS << " AEK_NUM_EXTENSIONS\n"
128 << "};\n"
129 << "#undef EMIT_ARCHEXTKIND_ENUM\n"
130 << "#endif // EMIT_ARCHEXTKIND_ENUM\n";
131
132 // Emit information for each defined Extension; used to build ArmExtKind.
133 OS << "#ifdef EMIT_EXTENSIONS\n"
134 << "inline constexpr ExtensionInfo Extensions[] = {\n";
135 for (const Record *Rec : SortedExtensions) {
136 auto AEK = Rec->getValueAsString(FieldName: "ArchExtKindSpelling").upper();
137 OS << " ";
138 OS << "{"
139 << StrTab.GetOrAddStringOffset(Str: Rec->getValueAsString(FieldName: "UserVisibleName"));
140 // Empty string implies no alias.
141 OS << ", "
142 << StrTab.GetOrAddStringOffset(
143 Str: Rec->getValueAsString(FieldName: "UserVisibleAlias"));
144 OS << ", AArch64::" << AEK;
145 OS << ", "
146 << StrTab.GetOrAddStringOffset(Str: Rec->getValueAsString(FieldName: "ArchFeatureName"));
147 OS << ", " << StrTab.GetOrAddStringOffset(Str: Rec->getValueAsString(FieldName: "Desc"));
148 OS << ", "
149 << StrTab.GetOrAddStringOffset(
150 Str: std::string("+") +
151 Rec->getValueAsString(FieldName: "Name").str()); // posfeature
152 OS << ", "
153 << StrTab.GetOrAddStringOffset(
154 Str: std::string("-") +
155 Rec->getValueAsString(FieldName: "Name").str()); // negfeature
156 OS << "},\n";
157 };
158 OS << "};\n";
159 OS << "#undef EMIT_EXTENSIONS\n"
160 << "#endif // EMIT_EXTENSIONS\n"
161 << "\n";
162
163 // Emit FMV information
164 auto FMVExts = RK.getAllDerivedDefinitionsIfDefined(ClassName: "FMVExtension");
165 OS << "#ifdef EMIT_FMV_INFO\n"
166 << "const std::vector<llvm::AArch64::FMVInfo>& "
167 "llvm::AArch64::getFMVInfo() {\n"
168 << " static std::vector<FMVInfo> I;\n"
169 << " if(I.size()) return I;\n"
170 << " I.reserve(" << FMVExts.size() << ");\n";
171 for (const Record *Rec : FMVExts) {
172 auto FeatName = Rec->getValueAsString(FieldName: "BackendFeature");
173 const Record *FeatRec = ExtensionMap[FeatName];
174 OS << " I.emplace_back(";
175 OS << "\"" << Rec->getValueAsString(FieldName: "Name") << "\"";
176 if (FeatRec)
177 OS << ", " << Rec->getValueAsString(FieldName: "FeatureBit");
178 else
179 OS << ", std::nullopt";
180 OS << ", " << Rec->getValueAsString(FieldName: "PriorityBit");
181 if (FeatRec)
182 OS << ", " << FeatRec->getValueAsString(FieldName: "ArchExtKindSpelling").upper();
183 else
184 OS << ", std::nullopt";
185 OS << ");\n";
186 };
187 OS << " return I;\n"
188 << "}\n"
189 << "#undef EMIT_FMV_INFO\n"
190 << "#endif // EMIT_FMV_INFO\n"
191 << "\n";
192
193 // Emit extension dependencies
194 OS << "#ifdef EMIT_EXTENSION_DEPENDENCIES\n"
195 << "inline constexpr ExtensionDependency ExtensionDependencies[] = {\n";
196 for (const Record *Rec : SortedExtensions) {
197 auto LaterAEK = Rec->getValueAsString(FieldName: "ArchExtKindSpelling").upper();
198 for (const Record *I : Rec->getValueAsListOfDefs(FieldName: "Implies"))
199 if (auto EarlierAEK = I->getValueAsOptionalString(FieldName: "ArchExtKindSpelling"))
200 OS << " {" << EarlierAEK->upper() << ", " << LaterAEK << "},\n";
201 }
202 // FIXME: Tablegen has the Subtarget Feature FeatureRCPC_IMMO which is implied
203 // by FeatureRCPC3 and in turn implies FeatureRCPC. The proper fix is to make
204 // FeatureRCPC_IMMO an Extension but that will expose it to the command line.
205 OS << " {AEK_RCPC, AEK_RCPC3},\n";
206 OS << "};\n"
207 << "#undef EMIT_EXTENSION_DEPENDENCIES\n"
208 << "#endif // EMIT_EXTENSION_DEPENDENCIES\n"
209 << "\n";
210
211 // Emit architecture information
212 OS << "#ifdef EMIT_ARCHITECTURES\n";
213
214 // Return the C++ name of the of an ArchInfo object
215 auto ArchInfoName = [](int Major, int Minor,
216 StringRef Profile) -> std::string {
217 return Minor == 0 ? "ARMV" + std::to_string(val: Major) + Profile.upper()
218 : "ARMV" + std::to_string(val: Major) + "_" +
219 std::to_string(val: Minor) + Profile.upper();
220 };
221
222 auto Architectures = RK.getAllDerivedDefinitionsIfDefined(ClassName: "Architecture64");
223 OS << "\n"
224 << "/// The set of all architectures\n"
225 << "inline constexpr std::array<ArchInfo, " << Architectures.size()
226 << "> ArchInfos = {{\n";
227 std::vector<std::string> CppSpellings;
228 for (const Record *Rec : Architectures) {
229 const int Major = Rec->getValueAsInt(FieldName: "Major");
230 const int Minor = Rec->getValueAsInt(FieldName: "Minor");
231 const std::string ProfileLower = Rec->getValueAsString(FieldName: "Profile").str();
232 const std::string ProfileUpper = Rec->getValueAsString(FieldName: "Profile").upper();
233
234 if (ProfileLower != "a" && ProfileLower != "r")
235 PrintFatalError(ErrorLoc: Rec->getLoc(),
236 Msg: "error: Profile must be one of 'a' or 'r', got '" +
237 ProfileLower + "'");
238
239 // Name of the object in C++
240 std::string CppSpelling = ArchInfoName(Major, Minor, ProfileUpper);
241 OS << " {\n";
242 CppSpellings.push_back(x: std::move(CppSpelling));
243
244 OS << llvm::format(Fmt: " VersionTuple{%d, %d},\n", Vals: Major, Vals: Minor);
245 OS << llvm::format(Fmt: " %sProfile,\n", Vals: ProfileUpper.c_str());
246
247 // Name as spelled for -march.
248 std::string ArchStr;
249 llvm::raw_string_ostream AS(ArchStr);
250 if (Minor == 0)
251 AS << llvm::format(Fmt: "armv%d-%s", Vals: Major, Vals: ProfileLower.c_str());
252 else
253 AS << llvm::format(Fmt: "armv%d.%d-%s", Vals: Major, Vals: Minor, Vals: ProfileLower.c_str());
254 OS << " " << StrTab.GetOrAddStringOffset(Str: ArchStr) << ",\n";
255
256 // SubtargetFeature::Name, used for -target-feature. Here the "+" is added.
257 std::string TargetFeatureName =
258 (Twine("+") + Rec->getValueAsString(FieldName: "Name")).str();
259 OS << " " << StrTab.GetOrAddStringOffset(Str: TargetFeatureName) << ",\n";
260
261 // Construct the list of default extensions
262 OS << " (AArch64::ExtensionBitset({";
263 for (auto *E : Rec->getValueAsListOfDefs(FieldName: "DefaultExts")) {
264 OS << "AArch64::" << E->getValueAsString(FieldName: "ArchExtKindSpelling").upper()
265 << ", ";
266 }
267 OS << "}))\n";
268
269 OS << " },\n";
270 }
271 OS << "}};\n";
272
273 for (auto [Idx, CppSpelling] : enumerate(First&: CppSpellings))
274 OS << "static constexpr const ArchInfo &" << CppSpelling << " = ArchInfos["
275 << Idx << "];\n";
276
277 OS << "#undef EMIT_ARCHITECTURES\n"
278 << "#endif // EMIT_ARCHITECTURES\n"
279 << "\n";
280
281 // Emit CPU Aliases
282 OS << "#ifdef EMIT_CPU_ALIAS\n"
283 << "inline constexpr Alias CpuAliases[] = {\n";
284
285 llvm::StringSet<> Processors;
286 for (const Record *Rec : RK.getAllDerivedDefinitions(ClassName: "ProcessorModel"))
287 Processors.insert(key: Rec->getValueAsString(FieldName: "Name"));
288
289 llvm::StringSet<> Aliases;
290 for (const Record *Rec : RK.getAllDerivedDefinitions(ClassName: "ProcessorAlias")) {
291 auto Name = Rec->getValueAsString(FieldName: "Name");
292 auto Alias = Rec->getValueAsString(FieldName: "Alias");
293 if (!Processors.contains(key: Alias))
294 PrintFatalError(
295 Rec, Msg: "Alias '" + Name + "' references a non-existent ProcessorModel '" + Alias + "'");
296 if (Processors.contains(key: Name))
297 PrintFatalError(
298 Rec, Msg: "Alias '" + Name + "' duplicates an existing ProcessorModel");
299 if (!Aliases.insert(key: Name).second)
300 PrintFatalError(
301 Rec, Msg: "Alias '" + Name + "' duplicates an existing ProcessorAlias");
302
303 OS << " {" << StrTab.GetOrAddStringOffset(Str: Name) << ", "
304 << StrTab.GetOrAddStringOffset(Str: Alias) << "},\n";
305 }
306
307 OS << "};\n"
308 << "#undef EMIT_CPU_ALIAS\n"
309 << "#endif // EMIT_CPU_ALIAS\n"
310 << "\n";
311
312 // Emit CPU information
313 OS << "#ifdef EMIT_CPU_INFO\n"
314 << "inline constexpr CpuInfo CpuInfos[] = {\n";
315
316 for (const Record *Rec : RK.getAllDerivedDefinitions(ClassName: "ProcessorModel")) {
317 auto Name = Rec->getValueAsString(FieldName: "Name");
318 auto Features = Rec->getValueAsListOfDefs(FieldName: "Features");
319
320 // "apple-latest" is backend-only, should not be accepted by TargetParser.
321 if (Name == "apple-latest")
322 continue;
323
324 const Record *Arch;
325 if (Name == "generic") {
326 // "generic" is an exception. It does not have an architecture, and there
327 // are tests that depend on e.g. -mattr=-v8.4a meaning HasV8_0aOps==false.
328 // However, in TargetParser CPUInfo, it is written as 8.0-A.
329 Arch = RK.getDef(Name: "HasV8_0aOps");
330 } else {
331 // Search for an Architecture64 in the list of features.
332 auto IsArch = [](const Record *F) {
333 return F->isSubClassOf(Name: "Architecture64");
334 };
335 auto ArchIter = llvm::find_if(Range&: Features, P: IsArch);
336 if (ArchIter == Features.end())
337 PrintFatalError(Rec, Msg: "Features must include an Architecture64.");
338 Arch = *ArchIter;
339
340 // Check there is only one Architecture in the list.
341 if (llvm::count_if(Range&: Features, P: IsArch) > 1)
342 PrintFatalError(Rec, Msg: "Features has multiple Architecture64 entries");
343 }
344
345 auto Major = Arch->getValueAsInt(FieldName: "Major");
346 auto Minor = Arch->getValueAsInt(FieldName: "Minor");
347 auto Profile = Arch->getValueAsString(FieldName: "Profile");
348 auto ArchInfo = ArchInfoName(Major, Minor, Profile);
349 unsigned ArchIdx =
350 llvm::find(Range&: CppSpellings, Val: ArchInfo) - CppSpellings.begin();
351
352 checkFeatureTree(Root: Arch);
353
354 OS << " {\n"
355 << " " << StrTab.GetOrAddStringOffset(Str: Name) << ",\n"
356 << " " << ArchIdx << " /* " << ArchInfo << " */,\n"
357 << " AArch64::ExtensionBitset({\n";
358
359 // Keep track of extensions we have seen
360 StringSet<> SeenExts;
361 for (const Record *E : Rec->getValueAsListOfDefs(FieldName: "Features"))
362 // Only process subclasses of Extension
363 if (E->isSubClassOf(Name: "Extension")) {
364 const auto AEK = E->getValueAsString(FieldName: "ArchExtKindSpelling").upper();
365 if (!SeenExts.insert(key: AEK).second)
366 PrintFatalError(Rec, Msg: "feature already added: " + E->getName());
367 OS << " AArch64::" << AEK << ",\n";
368 }
369 OS << " })\n"
370 << " },\n";
371 }
372 OS << "};\n";
373
374 OS << "#undef EMIT_CPU_INFO\n"
375 << "#endif // EMIT_CPU_INFO\n"
376 << "\n";
377
378 // Emit string table.
379 OS << "#ifdef EMIT_STRTAB\n";
380 StrTab.EmitStringTableDef(OS, Name: "StrTab");
381 OS << "#undef EMIT_STRTAB\n"
382 << "#endif // EMIT_STRTAB\n"
383 << "\n";
384}
385
386static TableGen::Emitter::Opt
387 X("gen-arm-target-def", emitARMTargetDef,
388 "Generate the ARM or AArch64 Architecture information header.");
389