1//===- MCSubtargetInfo.cpp - Subtarget Information ------------------------===//
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#include "llvm/MC/MCSubtargetInfo.h"
10#include "llvm/ADT/ArrayRef.h"
11#include "llvm/ADT/StringRef.h"
12#include "llvm/ADT/Twine.h"
13#include "llvm/MC/MCInstrItineraries.h"
14#include "llvm/MC/MCSchedule.h"
15#include "llvm/Support/Format.h"
16#include "llvm/Support/raw_ostream.h"
17#include "llvm/TargetParser/SubtargetFeature.h"
18#include <algorithm>
19#include <cassert>
20#include <cstring>
21#include <optional>
22
23using namespace llvm;
24
25/// Find KV in array using binary search.
26template <typename T>
27static const T *Find(StringRef S, ArrayRef<T> A) {
28 // Binary search the array
29 auto F = llvm::lower_bound(A, S);
30 // If not found then return NULL
31 if (F == A.end() || StringRef(F->key()) != S)
32 return nullptr;
33 // Return the found array item
34 return F;
35}
36
37/// For each feature that is (transitively) implied by this feature, set it.
38static void SetImpliedBits(FeatureBitset &Bits, FeatureBitset Implies,
39 ArrayRef<SubtargetFeatureKV> FeatureTable) {
40 // Transitively set all features implied. We don't assume that the features in
41 // Bits have already had their implied features set.
42 FeatureBitset NewBits = Implies;
43 while (Implies.any()) {
44 FeatureBitset Implied;
45 for (const SubtargetFeatureKV &FE : FeatureTable) {
46 if (Implies.test(I: FE.Value))
47 Implied |= FE.Implies.getAsBitset();
48 }
49
50 // Only continue for bits that haven't been set yet.
51 Implies = Implied & ~NewBits;
52 NewBits |= Implies;
53 }
54 Bits |= NewBits;
55}
56
57/// For each feature that (transitively) implies this feature, clear it.
58static
59void ClearImpliedBits(FeatureBitset &Bits, unsigned Value,
60 ArrayRef<SubtargetFeatureKV> FeatureTable) {
61 for (const SubtargetFeatureKV &FE : FeatureTable) {
62 if (FE.Implies.getAsBitset().test(I: Value)) {
63 Bits.reset(I: FE.Value);
64 ClearImpliedBits(Bits, Value: FE.Value, FeatureTable);
65 }
66 }
67}
68
69static void ApplyFeatureFlag(FeatureBitset &Bits, StringRef Feature,
70 ArrayRef<SubtargetFeatureKV> FeatureTable) {
71 assert(SubtargetFeatures::hasFlag(Feature) &&
72 "Feature flags should start with '+' or '-'");
73
74 // Find feature in table.
75 const SubtargetFeatureKV *FeatureEntry =
76 Find(S: SubtargetFeatures::StripFlag(Feature), A: FeatureTable);
77 // If there is a match
78 if (FeatureEntry) {
79 // Enable/disable feature in bits
80 if (SubtargetFeatures::isEnabled(Feature)) {
81 Bits.set(FeatureEntry->Value);
82
83 // For each feature that this implies, set it.
84 SetImpliedBits(Bits, Implies: FeatureEntry->Implies.getAsBitset(), FeatureTable);
85 } else {
86 Bits.reset(I: FeatureEntry->Value);
87
88 // For each feature that implies this, clear it.
89 ClearImpliedBits(Bits, Value: FeatureEntry->Value, FeatureTable);
90 }
91 } else {
92 errs() << "'" << Feature << "' is not a recognized feature for this target"
93 << " (ignoring feature)\n";
94 }
95}
96
97/// Return the length of the longest entry in the table.
98static size_t getLongestEntryLength(ArrayRef<SubtargetFeatureKV> Table) {
99 size_t MaxLen = 0;
100 for (auto &I : Table)
101 MaxLen = std::max(a: MaxLen, b: std::strlen(s: I.key()));
102 return MaxLen;
103}
104
105static size_t getLongestEntryLength(StringTable Table) {
106 size_t MaxLen = 0;
107 for (StringRef I : Table)
108 MaxLen = std::max(a: MaxLen, b: I.size());
109 return MaxLen;
110}
111
112/// Display help for feature and mcpu choices.
113static void Help(StringTable CPUNames, ArrayRef<SubtargetFeatureKV> FeatTable) {
114 // the static variable ensures that the help information only gets
115 // printed once even though a target machine creates multiple subtargets
116 static bool PrintOnce = false;
117 if (PrintOnce) {
118 return;
119 }
120
121 // Determine the length of the longest CPU and Feature entries.
122 unsigned MaxCPULen = getLongestEntryLength(Table: CPUNames);
123 unsigned MaxFeatLen = getLongestEntryLength(Table: FeatTable);
124
125 // Print the CPU table.
126 errs() << "Available CPUs for this target:\n\n";
127 for (auto &CPUName : CPUNames) {
128 // Skip apple-latest, as that's only meant to be used in
129 // disassemblers/debuggers, and we don't want normal code to be built with
130 // it as an -mcpu=
131 if (CPUName == "apple-latest")
132 continue;
133 errs() << format(Fmt: " %-*s - Select the %s processor.\n", Vals: MaxCPULen,
134 Vals: CPUName.str().c_str(), Vals: CPUName.str().c_str());
135 }
136 errs() << '\n';
137
138 // Print the Feature table.
139 errs() << "Available features for this target:\n\n";
140 for (auto &Feature : FeatTable)
141 errs() << format(Fmt: " %-*s - %s.\n", Vals: MaxFeatLen, Vals: Feature.key(),
142 Vals: Feature.desc());
143 errs() << '\n';
144
145 errs() << "Use +feature to enable a feature, or -feature to disable it.\n"
146 "For example, llc -mcpu=mycpu -mattr=+feature1,-feature2\n";
147
148 PrintOnce = true;
149}
150
151/// Display help for mcpu choices only
152static void cpuHelp(StringTable CPUNames) {
153 // the static variable ensures that the help information only gets
154 // printed once even though a target machine creates multiple subtargets
155 static bool PrintOnce = false;
156 if (PrintOnce) {
157 return;
158 }
159
160 // Print the CPU table.
161 errs() << "Available CPUs for this target:\n\n";
162 for (auto &CPU : CPUNames) {
163 // Skip apple-latest, as that's only meant to be used in
164 // disassemblers/debuggers, and we don't want normal code to be built with
165 // it as an -mcpu=
166 if (CPU == "apple-latest")
167 continue;
168 errs() << "\t" << CPU << "\n";
169 }
170 errs() << '\n';
171
172 errs() << "Use -mcpu or -mtune to specify the target's processor.\n"
173 "For example, clang --target=aarch64-unknown-linux-gnu "
174 "-mcpu=cortex-a35\n";
175
176 PrintOnce = true;
177}
178
179static FeatureBitset getFeatures(MCSubtargetInfo &STI, StringRef CPU,
180 StringRef TuneCPU, StringRef FS,
181 StringTable ProcNames,
182 ArrayRef<SubtargetSubTypeKV> ProcDesc,
183 ArrayRef<SubtargetFeatureKV> ProcFeatures) {
184 SubtargetFeatures Features(FS);
185
186 if (ProcDesc.empty() || ProcFeatures.empty())
187 return FeatureBitset();
188
189 assert(llvm::is_sorted(ProcDesc) && "CPU table is not sorted");
190 assert(llvm::is_sorted(ProcFeatures) && "CPU features table is not sorted");
191 // Resulting bits
192 FeatureBitset Bits;
193
194 // Check if help is needed
195 if (CPU == "help")
196 Help(CPUNames: ProcNames, FeatTable: ProcFeatures);
197
198 // Find CPU entry if CPU name is specified.
199 else if (!CPU.empty()) {
200 const SubtargetSubTypeKV *CPUEntry = STI.resolveCPU(CPU);
201
202 // If there is a match
203 if (CPUEntry) {
204 // Set the features implied by this CPU feature, if any.
205 SetImpliedBits(Bits, Implies: CPUEntry->Implies.getAsBitset(), FeatureTable: ProcFeatures);
206 } else {
207 errs() << "'" << CPU << "' is not a recognized processor for this target"
208 << " (ignoring processor)\n";
209 }
210 }
211
212 if (!TuneCPU.empty()) {
213 const SubtargetSubTypeKV *CPUEntry = STI.resolveCPU(CPU: TuneCPU);
214
215 // If there is a match
216 if (CPUEntry) {
217 // Set the features implied by this CPU feature, if any.
218 SetImpliedBits(Bits, Implies: CPUEntry->TuneImplies.getAsBitset(), FeatureTable: ProcFeatures);
219 } else if (TuneCPU != CPU) {
220 errs() << "'" << TuneCPU << "' is not a recognized processor for this "
221 << "target (ignoring processor)\n";
222 }
223 }
224
225 // Iterate through each feature
226 for (const std::string &Feature : Features.getFeatures()) {
227 // Check for help
228 if (Feature == "+help")
229 Help(CPUNames: ProcNames, FeatTable: ProcFeatures);
230 else if (Feature == "+cpuhelp")
231 cpuHelp(CPUNames: ProcNames);
232 else
233 ApplyFeatureFlag(Bits, Feature, FeatureTable: ProcFeatures);
234 }
235
236 return Bits;
237}
238
239void MCSubtargetInfo::InitMCProcessorInfo(StringRef CPU, StringRef TuneCPU,
240 StringRef FS) {
241 FeatureBits =
242 getFeatures(STI&: *this, CPU, TuneCPU, FS, ProcNames, ProcDesc, ProcFeatures);
243 FeatureString = std::string(FS);
244
245 if (!TuneCPU.empty())
246 CPUSchedModel = &getSchedModelForCPU(CPU: TuneCPU);
247 else
248 CPUSchedModel = &MCSchedModel::Default;
249}
250
251void MCSubtargetInfo::setDefaultFeatures(StringRef CPU, StringRef TuneCPU,
252 StringRef FS) {
253 FeatureBits =
254 getFeatures(STI&: *this, CPU, TuneCPU, FS, ProcNames, ProcDesc, ProcFeatures);
255 FeatureString = std::string(FS);
256}
257
258MCSubtargetInfo::MCSubtargetInfo(
259 const Triple &TT, StringRef C, StringRef TC, StringRef FS, StringTable PN,
260 ArrayRef<SubtargetFeatureKV> PF, ArrayRef<SubtargetSubTypeKV> PD,
261 ArrayRef<SubtargetSubTypeAliasKV> PA, const MCSchedModel *PSM,
262 const MCWriteProcResEntry *WPR, const MCWriteLatencyEntry *WL,
263 const MCReadAdvanceEntry *RA, const InstrStage *IS, const unsigned *OC,
264 const unsigned *FP)
265 : TargetTriple(TT), CPU(std::string(C)), TuneCPU(std::string(TC)),
266 ProcNames(PN), ProcFeatures(PF), ProcDesc(PD), ProcAliases(PA),
267 ProcSchedModels(PSM), WriteProcResTable(WPR), WriteLatencyTable(WL),
268 ReadAdvanceTable(RA), Stages(IS), OperandCycles(OC), ForwardingPaths(FP) {
269 InitMCProcessorInfo(CPU, TuneCPU, FS);
270}
271
272const FeatureBitset &MCSubtargetInfo::ToggleFeature(uint64_t FB) {
273 FeatureBits.flip(I: FB);
274 return FeatureBits;
275}
276
277const FeatureBitset &MCSubtargetInfo::ToggleFeature(const FeatureBitset &FB) {
278 FeatureBits ^= FB;
279 return FeatureBits;
280}
281
282const FeatureBitset &
283MCSubtargetInfo::SetFeatureBitsTransitively(const FeatureBitset &FB) {
284 SetImpliedBits(Bits&: FeatureBits, Implies: FB, FeatureTable: ProcFeatures);
285 return FeatureBits;
286}
287
288const FeatureBitset &
289MCSubtargetInfo::ClearFeatureBitsTransitively(const FeatureBitset &FB) {
290 for (unsigned I = 0, E = FB.size(); I < E; I++) {
291 if (FB[I]) {
292 FeatureBits.reset(I);
293 ClearImpliedBits(Bits&: FeatureBits, Value: I, FeatureTable: ProcFeatures);
294 }
295 }
296 return FeatureBits;
297}
298
299const FeatureBitset &MCSubtargetInfo::ToggleFeature(StringRef Feature) {
300 // Find feature in table.
301 const SubtargetFeatureKV *FeatureEntry =
302 Find(S: SubtargetFeatures::StripFlag(Feature), A: ProcFeatures);
303 // If there is a match
304 if (FeatureEntry) {
305 if (FeatureBits.test(I: FeatureEntry->Value)) {
306 FeatureBits.reset(I: FeatureEntry->Value);
307 // For each feature that implies this, clear it.
308 ClearImpliedBits(Bits&: FeatureBits, Value: FeatureEntry->Value, FeatureTable: ProcFeatures);
309 } else {
310 FeatureBits.set(FeatureEntry->Value);
311
312 // For each feature that this implies, set it.
313 SetImpliedBits(Bits&: FeatureBits, Implies: FeatureEntry->Implies.getAsBitset(),
314 FeatureTable: ProcFeatures);
315 }
316 } else {
317 errs() << "'" << Feature << "' is not a recognized feature for this target"
318 << " (ignoring feature)\n";
319 }
320
321 return FeatureBits;
322}
323
324const FeatureBitset &MCSubtargetInfo::ApplyFeatureFlag(StringRef FS) {
325 ::ApplyFeatureFlag(Bits&: FeatureBits, Feature: FS, FeatureTable: ProcFeatures);
326 return FeatureBits;
327}
328
329bool MCSubtargetInfo::checkFeatures(StringRef FS) const {
330 SubtargetFeatures T(FS);
331 return all_of(Range: T.getFeatures(), P: [this](const std::string &F) {
332 assert(SubtargetFeatures::hasFlag(F) &&
333 "Feature flags should start with '+' or '-'");
334 const SubtargetFeatureKV *FeatureEntry =
335 Find(S: SubtargetFeatures::StripFlag(Feature: F), A: ProcFeatures);
336 if (!FeatureEntry) {
337 reportFatalInternalError(reason: Twine("'") + F +
338 "' is not a recognized feature for this target");
339 }
340
341 return FeatureBits.test(I: FeatureEntry->Value) ==
342 SubtargetFeatures::isEnabled(Feature: F);
343 });
344}
345
346static bool hasFeature(StringRef Feature, const FeatureBitset &FeatureBits,
347 ArrayRef<SubtargetFeatureKV> ProcFeatures) {
348 bool ShouldBeEnabled = true;
349 if (!Feature.consume_front(Prefix: "+") && Feature.consume_front(Prefix: "-"))
350 ShouldBeEnabled = false;
351
352 const SubtargetFeatureKV *FeatureEntry = Find(S: Feature, A: ProcFeatures);
353 if (!FeatureEntry) {
354 reportFatalInternalError(reason: Twine("'") + Feature +
355 "' is not a recognized feature for this target");
356 }
357
358 return FeatureBits.test(I: FeatureEntry->Value) == ShouldBeEnabled;
359}
360
361namespace {
362class FeatureExpressionParser {
363 StringRef Expr;
364 const FeatureBitset &FeatureBits;
365 ArrayRef<SubtargetFeatureKV> ProcFeatures;
366 size_t Pos = 0;
367
368public:
369 FeatureExpressionParser(StringRef Expr, const FeatureBitset &FeatureBits,
370 ArrayRef<SubtargetFeatureKV> ProcFeatures)
371 : Expr(Expr), FeatureBits(FeatureBits), ProcFeatures(ProcFeatures) {}
372
373 bool parse() {
374 bool Result = parseOr();
375 if (Pos != Expr.size())
376 reportFatalInternalError(reason: "malformed target feature expression");
377 return Result;
378 }
379
380private:
381 bool consume(char C) {
382 if (Pos == Expr.size() || Expr[Pos] != C)
383 return false;
384 ++Pos;
385 return true;
386 }
387
388 bool parseOr() {
389 bool Result = parseAnd();
390 while (consume(C: '|')) {
391 bool RHS = parseAnd();
392 Result |= RHS;
393 }
394 return Result;
395 }
396
397 bool parseAnd() {
398 bool Result = parsePrimary();
399 while (consume(C: ',')) {
400 bool RHS = parsePrimary();
401 Result &= RHS;
402 }
403 return Result;
404 }
405
406 bool parsePrimary() {
407 if (consume(C: '(')) {
408 bool Result = parseOr();
409 if (!consume(C: ')'))
410 reportFatalInternalError(reason: "malformed target feature expression");
411 return Result;
412 }
413
414 size_t Start = Pos;
415 Pos = Expr.find_first_of(Chars: ",|()", From: Pos);
416 if (Pos == StringRef::npos)
417 Pos = Expr.size();
418
419 if (Start == Pos)
420 reportFatalInternalError(reason: "malformed target feature expression");
421
422 return hasFeature(Feature: Expr.slice(Start, End: Pos), FeatureBits, ProcFeatures);
423 }
424};
425} // namespace
426
427bool MCSubtargetInfo::checkFeatureExpression(StringRef FeatureExpr) const {
428 if (FeatureExpr.empty())
429 return true;
430 if (FeatureExpr.contains(C: ' ')) {
431 reportFatalInternalError(
432 reason: "spaces are not allowed in target feature expressions");
433 }
434 FeatureExpressionParser Parser(FeatureExpr, FeatureBits, ProcFeatures);
435 return Parser.parse();
436}
437
438const SubtargetSubTypeKV *MCSubtargetInfo::resolveCPU(StringRef CPU) const {
439 if (const SubtargetSubTypeKV *CPUEntry = Find(S: CPU, A: ProcDesc))
440 return CPUEntry;
441
442 // Not a canonical processor name; check whether it is a known alias.
443 if (const SubtargetSubTypeAliasKV *Alias = Find(S: CPU, A: ProcAliases))
444 return &ProcDesc[Alias->SubTypeIdx];
445
446 return nullptr;
447}
448
449const MCSchedModel &MCSubtargetInfo::getSchedModelForCPU(StringRef CPU) const {
450 assert(llvm::is_sorted(ProcDesc) &&
451 "Processor machine model table is not sorted");
452
453 // Find entry
454 const SubtargetSubTypeKV *CPUEntry = resolveCPU(CPU);
455
456 if (!CPUEntry) {
457 if (CPU != "help") // Don't error if the user asked for help.
458 errs() << "'" << CPU
459 << "' is not a recognized processor for this target"
460 << " (ignoring processor)\n";
461 return MCSchedModel::Default;
462 }
463 return ProcSchedModels[CPUEntry->SchedModelIdx];
464}
465
466InstrItineraryData
467MCSubtargetInfo::getInstrItineraryForCPU(StringRef CPU) const {
468 const MCSchedModel &SchedModel = getSchedModelForCPU(CPU);
469 return InstrItineraryData(SchedModel, Stages, OperandCycles, ForwardingPaths);
470}
471
472void MCSubtargetInfo::initInstrItins(InstrItineraryData &InstrItins) const {
473 InstrItins = InstrItineraryData(getSchedModel(), Stages, OperandCycles,
474 ForwardingPaths);
475}
476
477std::vector<const SubtargetFeatureKV *>
478MCSubtargetInfo::getEnabledProcessorFeatures() const {
479 std::vector<const SubtargetFeatureKV *> EnabledFeatures;
480 for (const SubtargetFeatureKV &FeatureKV : ProcFeatures)
481 if (FeatureBits.test(I: FeatureKV.Value))
482 EnabledFeatures.push_back(x: &FeatureKV);
483 return EnabledFeatures;
484}
485
486std::optional<unsigned> MCSubtargetInfo::getCacheSize(unsigned Level) const {
487 return std::nullopt;
488}
489
490std::optional<unsigned>
491MCSubtargetInfo::getCacheAssociativity(unsigned Level) const {
492 return std::nullopt;
493}
494
495std::optional<unsigned>
496MCSubtargetInfo::getCacheLineSize(unsigned Level) const {
497 return std::nullopt;
498}
499
500unsigned MCSubtargetInfo::getPrefetchDistance() const {
501 return 0;
502}
503
504unsigned MCSubtargetInfo::getMaxPrefetchIterationsAhead() const {
505 return UINT_MAX;
506}
507
508bool MCSubtargetInfo::enableWritePrefetching() const {
509 return false;
510}
511
512unsigned MCSubtargetInfo::getMinPrefetchStride(unsigned NumMemAccesses,
513 unsigned NumStridedMemAccesses,
514 unsigned NumPrefetches,
515 bool HasCall) const {
516 return 1;
517}
518
519bool MCSubtargetInfo::shouldPrefetchAddressSpace(unsigned AS) const {
520 return !AS;
521}
522