LLVM 19.0.0git
RISCVISAInfo.cpp
Go to the documentation of this file.
1//===-- RISCVISAInfo.cpp - RISC-V Arch String Parser ----------------------===//
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
10#include "llvm/ADT/MapVector.h"
11#include "llvm/ADT/STLExtras.h"
12#include "llvm/ADT/SetVector.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/Support/Errc.h"
16#include "llvm/Support/Error.h"
18
19#include <array>
20#include <atomic>
21#include <optional>
22#include <string>
23#include <vector>
24
25using namespace llvm;
26
27namespace {
28
29struct RISCVSupportedExtension {
30 const char *Name;
31 /// Supported version.
33
34 bool operator<(const RISCVSupportedExtension &RHS) const {
35 return StringRef(Name) < StringRef(RHS.Name);
36 }
37};
38
39struct RISCVProfile {
41 StringLiteral MArch;
42};
43
44} // end anonymous namespace
45
46static const char *RISCVGImplications[] = {
47 "i", "m", "a", "f", "d", "zicsr", "zifencei"
48};
49
50#define GET_SUPPORTED_EXTENSIONS
51#include "llvm/TargetParser/RISCVTargetParserDef.inc"
52
53#define GET_SUPPORTED_PROFILES
54#include "llvm/TargetParser/RISCVTargetParserDef.inc"
55
56static void verifyTables() {
57#ifndef NDEBUG
58 static std::atomic<bool> TableChecked(false);
59 if (!TableChecked.load(std::memory_order_relaxed)) {
60 assert(llvm::is_sorted(SupportedExtensions) &&
61 "Extensions are not sorted by name");
62 assert(llvm::is_sorted(SupportedExperimentalExtensions) &&
63 "Experimental extensions are not sorted by name");
64 TableChecked.store(true, std::memory_order_relaxed);
65 }
66#endif
67}
68
70 StringRef Description) {
71 outs().indent(4);
72 unsigned VersionWidth = Description.empty() ? 0 : 10;
73 outs() << left_justify(Name, 21) << left_justify(Version, VersionWidth)
74 << Description << "\n";
75}
76
78
79 outs() << "All available -march extensions for RISC-V\n\n";
80 PrintExtension("Name", "Version", (DescMap.empty() ? "" : "Description"));
81
83 for (const auto &E : SupportedExtensions)
84 ExtMap[E.Name] = {E.Version.Major, E.Version.Minor};
85 for (const auto &E : ExtMap) {
86 std::string Version =
87 std::to_string(E.second.Major) + "." + std::to_string(E.second.Minor);
88 PrintExtension(E.first, Version, DescMap[E.first]);
89 }
90
91 outs() << "\nExperimental extensions\n";
92 ExtMap.clear();
93 for (const auto &E : SupportedExperimentalExtensions)
94 ExtMap[E.Name] = {E.Version.Major, E.Version.Minor};
95 for (const auto &E : ExtMap) {
96 std::string Version =
97 std::to_string(E.second.Major) + "." + std::to_string(E.second.Minor);
98 PrintExtension(E.first, Version, DescMap["experimental-" + E.first]);
99 }
100
101 outs() << "\nUse -march to specify the target's extension.\n"
102 "For example, clang -march=rv32i_v1p0\n";
103}
104
106 return Ext.consume_front("experimental-");
107}
108
109// This function finds the last character that doesn't belong to a version
110// (e.g. zba1p0 is extension 'zba' of version '1p0'). So the function will
111// consume [0-9]*p[0-9]* starting from the backward. An extension name will not
112// end with a digit or the letter 'p', so this function will parse correctly.
113// NOTE: This function is NOT able to take empty strings or strings that only
114// have version numbers and no extension name. It assumes the extension name
115// will be at least more than one character.
117 assert(!Ext.empty() &&
118 "Already guarded by if-statement in ::parseArchString");
119
120 int Pos = Ext.size() - 1;
121 while (Pos > 0 && isDigit(Ext[Pos]))
122 Pos--;
123 if (Pos > 0 && Ext[Pos] == 'p' && isDigit(Ext[Pos - 1])) {
124 Pos--;
125 while (Pos > 0 && isDigit(Ext[Pos]))
126 Pos--;
127 }
128 return Pos;
129}
130
131namespace {
132struct LessExtName {
133 bool operator()(const RISCVSupportedExtension &LHS, StringRef RHS) {
134 return StringRef(LHS.Name) < RHS;
135 }
136 bool operator()(StringRef LHS, const RISCVSupportedExtension &RHS) {
137 return LHS < StringRef(RHS.Name);
138 }
139};
140} // namespace
141
142static std::optional<RISCVISAUtils::ExtensionVersion>
144 // Find default version of an extension.
145 // TODO: We might set default version based on profile or ISA spec.
146 for (auto &ExtInfo : {ArrayRef(SupportedExtensions),
147 ArrayRef(SupportedExperimentalExtensions)}) {
148 auto I = llvm::lower_bound(ExtInfo, ExtName, LessExtName());
149
150 if (I == ExtInfo.end() || I->Name != ExtName)
151 continue;
152
153 return I->Version;
154 }
155 return std::nullopt;
156}
157
158void RISCVISAInfo::addExtension(StringRef ExtName,
160 Exts[ExtName.str()] = Version;
161}
162
164 if (Ext.starts_with("s"))
165 return "standard supervisor-level extension";
166 if (Ext.starts_with("x"))
167 return "non-standard user-level extension";
168 if (Ext.starts_with("z"))
169 return "standard user-level extension";
170 return StringRef();
171}
172
174 if (Ext.starts_with("s"))
175 return "s";
176 if (Ext.starts_with("x"))
177 return "x";
178 if (Ext.starts_with("z"))
179 return "z";
180 return StringRef();
181}
182
183static std::optional<RISCVISAUtils::ExtensionVersion>
185 auto I =
186 llvm::lower_bound(SupportedExperimentalExtensions, Ext, LessExtName());
187 if (I == std::end(SupportedExperimentalExtensions) || I->Name != Ext)
188 return std::nullopt;
189
190 return I->Version;
191}
192
194 bool IsExperimental = stripExperimentalPrefix(Ext);
195
197 IsExperimental ? ArrayRef(SupportedExperimentalExtensions)
198 : ArrayRef(SupportedExtensions);
199
200 auto I = llvm::lower_bound(ExtInfo, Ext, LessExtName());
201 return I != ExtInfo.end() && I->Name == Ext;
202}
203
205 verifyTables();
206
207 for (auto ExtInfo : {ArrayRef(SupportedExtensions),
208 ArrayRef(SupportedExperimentalExtensions)}) {
209 auto I = llvm::lower_bound(ExtInfo, Ext, LessExtName());
210 if (I != ExtInfo.end() && I->Name == Ext)
211 return true;
212 }
213
214 return false;
215}
216
217bool RISCVISAInfo::isSupportedExtension(StringRef Ext, unsigned MajorVersion,
218 unsigned MinorVersion) {
219 for (auto ExtInfo : {ArrayRef(SupportedExtensions),
220 ArrayRef(SupportedExperimentalExtensions)}) {
221 auto Range =
222 std::equal_range(ExtInfo.begin(), ExtInfo.end(), Ext, LessExtName());
223 for (auto I = Range.first, E = Range.second; I != E; ++I)
224 if (I->Version.Major == MajorVersion && I->Version.Minor == MinorVersion)
225 return true;
226 }
227
228 return false;
229}
230
233
234 if (!isSupportedExtension(Ext))
235 return false;
236
237 return Exts.count(Ext.str()) != 0;
238}
239
240std::vector<std::string> RISCVISAInfo::toFeatures(bool AddAllExtensions,
241 bool IgnoreUnknown) const {
242 std::vector<std::string> Features;
243 for (const auto &[ExtName, _] : Exts) {
244 // i is a base instruction set, not an extension (see
245 // https://github.com/riscv/riscv-isa-manual/blob/main/src/naming.adoc#base-integer-isa)
246 // and is not recognized in clang -cc1
247 if (ExtName == "i")
248 continue;
249 if (IgnoreUnknown && !isSupportedExtension(ExtName))
250 continue;
251
252 if (isExperimentalExtension(ExtName)) {
253 Features.push_back((llvm::Twine("+experimental-") + ExtName).str());
254 } else {
255 Features.push_back((llvm::Twine("+") + ExtName).str());
256 }
257 }
258 if (AddAllExtensions) {
259 for (const RISCVSupportedExtension &Ext : SupportedExtensions) {
260 if (Exts.count(Ext.Name))
261 continue;
262 Features.push_back((llvm::Twine("-") + Ext.Name).str());
263 }
264
265 for (const RISCVSupportedExtension &Ext : SupportedExperimentalExtensions) {
266 if (Exts.count(Ext.Name))
267 continue;
268 Features.push_back((llvm::Twine("-experimental-") + Ext.Name).str());
269 }
270 }
271 return Features;
272}
273
274static Error getStringErrorForInvalidExt(std::string_view ExtName) {
275 if (ExtName.size() == 1) {
277 "unsupported standard user-level extension '" +
278 ExtName + "'");
279 }
281 "unsupported " + getExtensionTypeDesc(ExtName) +
282 " '" + ExtName + "'");
283}
284
285// Extensions may have a version number, and may be separated by
286// an underscore '_' e.g.: rv32i2_m2.
287// Version number is divided into major and minor version numbers,
288// separated by a 'p'. If the minor version is 0 then 'p0' can be
289// omitted from the version string. E.g., rv32i2p0, rv32i2, rv32i2p1.
290static Error getExtensionVersion(StringRef Ext, StringRef In, unsigned &Major,
291 unsigned &Minor, unsigned &ConsumeLength,
292 bool EnableExperimentalExtension,
293 bool ExperimentalExtensionVersionCheck) {
294 StringRef MajorStr, MinorStr;
295 Major = 0;
296 Minor = 0;
297 ConsumeLength = 0;
298 MajorStr = In.take_while(isDigit);
299 In = In.substr(MajorStr.size());
300
301 if (!MajorStr.empty() && In.consume_front("p")) {
302 MinorStr = In.take_while(isDigit);
303 In = In.substr(MajorStr.size() + MinorStr.size() - 1);
304
305 // Expected 'p' to be followed by minor version number.
306 if (MinorStr.empty()) {
307 return createStringError(
309 "minor version number missing after 'p' for extension '" + Ext + "'");
310 }
311 }
312
313 if (!MajorStr.empty() && MajorStr.getAsInteger(10, Major))
314 return createStringError(
316 "Failed to parse major version number for extension '" + Ext + "'");
317
318 if (!MinorStr.empty() && MinorStr.getAsInteger(10, Minor))
319 return createStringError(
321 "Failed to parse minor version number for extension '" + Ext + "'");
322
323 ConsumeLength = MajorStr.size();
324
325 if (!MinorStr.empty())
326 ConsumeLength += MinorStr.size() + 1 /*'p'*/;
327
328 // Expected multi-character extension with version number to have no
329 // subsequent characters (i.e. must either end string or be followed by
330 // an underscore).
331 if (Ext.size() > 1 && In.size())
332 return createStringError(
334 "multi-character extensions must be separated by underscores");
335
336 // If experimental extension, require use of current version number
337 if (auto ExperimentalExtension = isExperimentalExtension(Ext)) {
338 if (!EnableExperimentalExtension)
340 "requires '-menable-experimental-extensions' "
341 "for experimental extension '" +
342 Ext + "'");
343
344 if (ExperimentalExtensionVersionCheck &&
345 (MajorStr.empty() && MinorStr.empty()))
346 return createStringError(
348 "experimental extension requires explicit version number `" + Ext +
349 "`");
350
351 auto SupportedVers = *ExperimentalExtension;
352 if (ExperimentalExtensionVersionCheck &&
353 (Major != SupportedVers.Major || Minor != SupportedVers.Minor)) {
354 std::string Error = "unsupported version number " + MajorStr.str();
355 if (!MinorStr.empty())
356 Error += "." + MinorStr.str();
357 Error += " for experimental extension '" + Ext.str() +
358 "' (this compiler supports " + utostr(SupportedVers.Major) +
359 "." + utostr(SupportedVers.Minor) + ")";
361 }
362 return Error::success();
363 }
364
365 // Exception rule for `g`, we don't have clear version scheme for that on
366 // ISA spec.
367 if (Ext == "g")
368 return Error::success();
369
370 if (MajorStr.empty() && MinorStr.empty()) {
371 if (auto DefaultVersion = findDefaultVersion(Ext)) {
372 Major = DefaultVersion->Major;
373 Minor = DefaultVersion->Minor;
374 }
375 // No matter found or not, return success, assume other place will
376 // verify.
377 return Error::success();
378 }
379
380 if (RISCVISAInfo::isSupportedExtension(Ext, Major, Minor))
381 return Error::success();
382
384 return getStringErrorForInvalidExt(Ext);
385
386 std::string Error = "unsupported version number " + std::string(MajorStr);
387 if (!MinorStr.empty())
388 Error += "." + MinorStr.str();
389 Error += " for extension '" + Ext.str() + "'";
391}
392
395 const std::vector<std::string> &Features) {
396 assert(XLen == 32 || XLen == 64);
397 std::unique_ptr<RISCVISAInfo> ISAInfo(new RISCVISAInfo(XLen));
398
399 for (auto &Feature : Features) {
400 StringRef ExtName = Feature;
401 assert(ExtName.size() > 1 && (ExtName[0] == '+' || ExtName[0] == '-'));
402 bool Add = ExtName[0] == '+';
403 ExtName = ExtName.drop_front(1); // Drop '+' or '-'
404 bool Experimental = stripExperimentalPrefix(ExtName);
405 auto ExtensionInfos = Experimental
406 ? ArrayRef(SupportedExperimentalExtensions)
407 : ArrayRef(SupportedExtensions);
408 auto ExtensionInfoIterator =
409 llvm::lower_bound(ExtensionInfos, ExtName, LessExtName());
410
411 // Not all features is related to ISA extension, like `relax` or
412 // `save-restore`, skip those feature.
413 if (ExtensionInfoIterator == ExtensionInfos.end() ||
414 ExtensionInfoIterator->Name != ExtName)
415 continue;
416
417 if (Add)
418 ISAInfo->addExtension(ExtName, ExtensionInfoIterator->Version);
419 else
420 ISAInfo->Exts.erase(ExtName.str());
421 }
422
423 return RISCVISAInfo::postProcessAndChecking(std::move(ISAInfo));
424}
425
428 if (llvm::any_of(Arch, isupper))
430 "string must be lowercase");
431
432 // Must start with a valid base ISA name.
433 unsigned XLen = 0;
434 if (Arch.consume_front("rv32"))
435 XLen = 32;
436 else if (Arch.consume_front("rv64"))
437 XLen = 64;
438
439 if (XLen == 0 || Arch.empty() || (Arch[0] != 'i' && Arch[0] != 'e'))
441 "arch string must begin with valid base ISA");
442
443 std::unique_ptr<RISCVISAInfo> ISAInfo(new RISCVISAInfo(XLen));
444
445 // Each extension is of the form ${name}${major_version}p${minor_version}
446 // and separated by _. Split by _ and then extract the name and version
447 // information for each extension.
449 Arch.split(Split, '_');
450 for (StringRef Ext : Split) {
451 StringRef Prefix, MinorVersionStr;
452 std::tie(Prefix, MinorVersionStr) = Ext.rsplit('p');
453 if (MinorVersionStr.empty())
455 "extension lacks version in expected format");
456 unsigned MajorVersion, MinorVersion;
457 if (MinorVersionStr.getAsInteger(10, MinorVersion))
459 "failed to parse minor version number");
460
461 // Split Prefix into the extension name and the major version number
462 // (the trailing digits of Prefix).
463 int TrailingDigits = 0;
464 StringRef ExtName = Prefix;
465 while (!ExtName.empty()) {
466 if (!isDigit(ExtName.back()))
467 break;
468 ExtName = ExtName.drop_back(1);
469 TrailingDigits++;
470 }
471 if (!TrailingDigits)
473 "extension lacks version in expected format");
474
475 StringRef MajorVersionStr = Prefix.take_back(TrailingDigits);
476 if (MajorVersionStr.getAsInteger(10, MajorVersion))
478 "failed to parse major version number");
479 ISAInfo->addExtension(ExtName, {MajorVersion, MinorVersion});
480 }
481 ISAInfo->updateFLen();
482 ISAInfo->updateMinVLen();
483 ISAInfo->updateMaxELen();
484 return std::move(ISAInfo);
485}
486
488 std::vector<std::string> &SplitExts) {
490 if (Exts.empty())
491 return Error::success();
492
493 Exts.split(Split, "_");
494
495 for (auto Ext : Split) {
496 if (Ext.empty())
498 "extension name missing after separator '_'");
499
500 SplitExts.push_back(Ext.str());
501 }
502 return Error::success();
503}
504
506 StringRef RawExt,
508 std::map<std::string, unsigned>> &SeenExtMap,
509 bool IgnoreUnknown, bool EnableExperimentalExtension,
510 bool ExperimentalExtensionVersionCheck) {
513 auto Pos = findLastNonVersionCharacter(RawExt) + 1;
514 StringRef Name(RawExt.substr(0, Pos));
515 StringRef Vers(RawExt.substr(Pos));
516
517 if (Type.empty()) {
518 if (IgnoreUnknown)
519 return Error::success();
521 "invalid extension prefix '" + RawExt + "'");
522 }
523
524 if (!IgnoreUnknown && Name.size() == Type.size())
526 Desc + " name missing after '" + Type + "'");
527
528 unsigned Major, Minor, ConsumeLength;
529 if (auto E = getExtensionVersion(Name, Vers, Major, Minor, ConsumeLength,
530 EnableExperimentalExtension,
531 ExperimentalExtensionVersionCheck)) {
532 if (IgnoreUnknown) {
533 consumeError(std::move(E));
534 return Error::success();
535 }
536 return E;
537 }
538
539 // Check if duplicated extension.
540 if (!IgnoreUnknown && SeenExtMap.contains(Name.str()))
542 "duplicated " + Desc + " '" + Name + "'");
543
544 if (IgnoreUnknown && !RISCVISAInfo::isSupportedExtension(Name))
545 return Error::success();
546
547 SeenExtMap[Name.str()] = {Major, Minor};
548 return Error::success();
549}
550
552 StringRef &RawExt,
554 std::map<std::string, unsigned>> &SeenExtMap,
555 bool IgnoreUnknown, bool EnableExperimentalExtension,
556 bool ExperimentalExtensionVersionCheck) {
557 unsigned Major, Minor, ConsumeLength;
558 StringRef Name = RawExt.take_front(1);
559 RawExt.consume_front(Name);
560 if (auto E = getExtensionVersion(Name, RawExt, Major, Minor, ConsumeLength,
561 EnableExperimentalExtension,
562 ExperimentalExtensionVersionCheck)) {
563 if (IgnoreUnknown) {
564 consumeError(std::move(E));
565 RawExt = RawExt.substr(ConsumeLength);
566 return Error::success();
567 }
568 return E;
569 }
570
571 RawExt = RawExt.substr(ConsumeLength);
572
573 // Check if duplicated extension.
574 if (!IgnoreUnknown && SeenExtMap.contains(Name.str()))
576 "duplicated standard user-level extension '" +
577 Name + "'");
578
579 if (IgnoreUnknown && !RISCVISAInfo::isSupportedExtension(Name))
580 return Error::success();
581
582 SeenExtMap[Name.str()] = {Major, Minor};
583 return Error::success();
584}
585
587RISCVISAInfo::parseArchString(StringRef Arch, bool EnableExperimentalExtension,
588 bool ExperimentalExtensionVersionCheck,
589 bool IgnoreUnknown) {
590 // RISC-V ISA strings must be lowercase.
591 if (llvm::any_of(Arch, isupper))
593 "string must be lowercase");
594
595 if (Arch.starts_with("rvi") || Arch.starts_with("rva") ||
596 Arch.starts_with("rvb") || Arch.starts_with("rvm")) {
597 const auto *FoundProfile =
598 llvm::find_if(SupportedProfiles, [Arch](const RISCVProfile &Profile) {
599 return Arch.starts_with(Profile.Name);
600 });
601
602 if (FoundProfile == std::end(SupportedProfiles))
603 return createStringError(errc::invalid_argument, "unsupported profile");
604
605 std::string NewArch = FoundProfile->MArch.str();
606 StringRef ArchWithoutProfile = Arch.substr(FoundProfile->Name.size());
607 if (!ArchWithoutProfile.empty()) {
608 if (!ArchWithoutProfile.starts_with("_"))
609 return createStringError(
611 "additional extensions must be after separator '_'");
612 NewArch += ArchWithoutProfile.str();
613 }
614 return parseArchString(NewArch, EnableExperimentalExtension,
615 ExperimentalExtensionVersionCheck, IgnoreUnknown);
616 }
617
618 // ISA string must begin with rv32 or rv64.
619 unsigned XLen = 0;
620 if (Arch.consume_front("rv32"))
621 XLen = 32;
622 else if (Arch.consume_front("rv64"))
623 XLen = 64;
624
625 if (XLen == 0 || Arch.empty())
626 return createStringError(
628 "string must begin with rv32{i,e,g} or rv64{i,e,g}");
629
630 std::unique_ptr<RISCVISAInfo> ISAInfo(new RISCVISAInfo(XLen));
632 std::map<std::string, unsigned>>
633 SeenExtMap;
634
635 // The canonical order specified in ISA manual.
636 // Ref: Table 22.1 in RISC-V User-Level ISA V2.2
637 char Baseline = Arch.front();
638
639 // First letter should be 'e', 'i' or 'g'.
640 switch (Baseline) {
641 default:
643 "first letter after \'rv" + Twine(XLen) +
644 "\' should be 'e', 'i' or 'g'");
645 case 'e':
646 case 'i':
647 break;
648 case 'g':
649 // g expands to extensions in RISCVGImplications.
650 if (Arch.size() > 1 && isDigit(Arch[1]))
652 "version not supported for 'g'");
653 break;
654 }
655
656 if (Arch.back() == '_')
658 "extension name missing after separator '_'");
659
660 // Skip baseline.
661 StringRef Exts = Arch.drop_front(1);
662
663 unsigned Major, Minor, ConsumeLength;
664 if (Baseline == 'g') {
665 // Versions for g are disallowed, and this was checked for previously.
666 ConsumeLength = 0;
667
668 // No matter which version is given to `g`, we always set imafd to default
669 // version since the we don't have clear version scheme for that on
670 // ISA spec.
671 for (const auto *Ext : RISCVGImplications) {
672 auto Version = findDefaultVersion(Ext);
673 assert(Version && "Default extension version not found?");
674 // Postpone AddExtension until end of this function
675 SeenExtMap[Ext] = {Version->Major, Version->Minor};
676 }
677 } else {
678 // Baseline is `i` or `e`
679 if (auto E = getExtensionVersion(
680 StringRef(&Baseline, 1), Exts, Major, Minor, ConsumeLength,
681 EnableExperimentalExtension, ExperimentalExtensionVersionCheck)) {
682 if (!IgnoreUnknown)
683 return std::move(E);
684 // If IgnoreUnknown, then ignore an unrecognised version of the baseline
685 // ISA and just use the default supported version.
686 consumeError(std::move(E));
687 auto Version = findDefaultVersion(StringRef(&Baseline, 1));
688 Major = Version->Major;
689 Minor = Version->Minor;
690 }
691
692 // Postpone AddExtension until end of this function
693 SeenExtMap[StringRef(&Baseline, 1).str()] = {Major, Minor};
694 }
695
696 // Consume the base ISA version number and any '_' between rvxxx and the
697 // first extension
698 Exts = Exts.drop_front(ConsumeLength);
699 Exts.consume_front("_");
700
701 std::vector<std::string> SplitExts;
702 if (auto E = splitExtsByUnderscore(Exts, SplitExts))
703 return std::move(E);
704
705 for (auto &Ext : SplitExts) {
706 StringRef CurrExt = Ext;
707 while (!CurrExt.empty()) {
709 if (auto E = processSingleLetterExtension(
710 CurrExt, SeenExtMap, IgnoreUnknown, EnableExperimentalExtension,
711 ExperimentalExtensionVersionCheck))
712 return std::move(E);
713 } else if (CurrExt.front() == 'z' || CurrExt.front() == 's' ||
714 CurrExt.front() == 'x') {
715 // Handle other types of extensions other than the standard
716 // general purpose and standard user-level extensions.
717 // Parse the ISA string containing non-standard user-level
718 // extensions, standard supervisor-level extensions and
719 // non-standard supervisor-level extensions.
720 // These extensions start with 'z', 's', 'x' prefixes, might have a
721 // version number (major, minor) and are separated by a single
722 // underscore '_'. We do not enforce a canonical order for them.
723 if (auto E = processMultiLetterExtension(
724 CurrExt, SeenExtMap, IgnoreUnknown, EnableExperimentalExtension,
725 ExperimentalExtensionVersionCheck))
726 return std::move(E);
727 // Multi-letter extension must be seperate following extension with
728 // underscore
729 break;
730 } else {
731 // FIXME: Could it be ignored by IgnoreUnknown?
733 "invalid standard user-level extension '" +
734 Twine(CurrExt.front()) + "'");
735 }
736 }
737 }
738
739 // Check all Extensions are supported.
740 for (auto &SeenExtAndVers : SeenExtMap) {
741 const std::string &ExtName = SeenExtAndVers.first;
742 RISCVISAUtils::ExtensionVersion ExtVers = SeenExtAndVers.second;
743
745 return getStringErrorForInvalidExt(ExtName);
746 ISAInfo->addExtension(ExtName, ExtVers);
747 }
748
749 return RISCVISAInfo::postProcessAndChecking(std::move(ISAInfo));
750}
751
752Error RISCVISAInfo::checkDependency() {
753 bool HasC = Exts.count("c") != 0;
754 bool HasF = Exts.count("f") != 0;
755 bool HasZfinx = Exts.count("zfinx") != 0;
756 bool HasVector = Exts.count("zve32x") != 0;
757 bool HasZvl = MinVLen != 0;
758 bool HasZcmt = Exts.count("zcmt") != 0;
759
760 if (HasF && HasZfinx)
762 "'f' and 'zfinx' extensions are incompatible");
763
764 if (HasZvl && !HasVector)
765 return createStringError(
767 "'zvl*b' requires 'v' or 'zve*' extension to also be specified");
768
769 if (Exts.count("zvbb") && !HasVector)
770 return createStringError(
772 "'zvbb' requires 'v' or 'zve*' extension to also be specified");
773
774 if (Exts.count("zvbc") && !Exts.count("zve64x"))
775 return createStringError(
777 "'zvbc' requires 'v' or 'zve64*' extension to also be specified");
778
779 if ((Exts.count("zvkb") || Exts.count("zvkg") || Exts.count("zvkned") ||
780 Exts.count("zvknha") || Exts.count("zvksed") || Exts.count("zvksh")) &&
781 !HasVector)
782 return createStringError(
784 "'zvk*' requires 'v' or 'zve*' extension to also be specified");
785
786 if (Exts.count("zvknhb") && !Exts.count("zve64x"))
787 return createStringError(
789 "'zvknhb' requires 'v' or 'zve64*' extension to also be specified");
790
791 if ((HasZcmt || Exts.count("zcmp")) && Exts.count("d") &&
792 (HasC || Exts.count("zcd")))
793 return createStringError(
795 Twine("'") + (HasZcmt ? "zcmt" : "zcmp") +
796 "' extension is incompatible with '" + (HasC ? "c" : "zcd") +
797 "' extension when 'd' extension is enabled");
798
799 if (XLen != 32 && Exts.count("zcf"))
801 "'zcf' is only supported for 'rv32'");
802
803 if (Exts.count("zacas") && !(Exts.count("a") || Exts.count("zamo")))
804 return createStringError(
806 "'zacas' requires 'a' or 'zaamo' extension to also be specified");
807
808 if (Exts.count("zabha") && !(Exts.count("a") || Exts.count("zamo")))
809 return createStringError(
811 "'zabha' requires 'a' or 'zaamo' extension to also be specified");
812
813 return Error::success();
814}
815
818 const char *ImpliedExt;
819
820 bool operator<(const ImpliedExtsEntry &Other) const {
821 return Name < Other.Name;
822 }
823};
824
825static bool operator<(const ImpliedExtsEntry &LHS, StringRef RHS) {
826 return LHS.Name < RHS;
827}
828
829static bool operator<(StringRef LHS, const ImpliedExtsEntry &RHS) {
830 return LHS < RHS.Name;
831}
832
833#define GET_IMPLIED_EXTENSIONS
834#include "llvm/TargetParser/RISCVTargetParserDef.inc"
835
836void RISCVISAInfo::updateImplication() {
837 bool HasE = Exts.count("e") != 0;
838 bool HasI = Exts.count("i") != 0;
839
840 // If not in e extension and i extension does not exist, i extension is
841 // implied
842 if (!HasE && !HasI) {
843 auto Version = findDefaultVersion("i");
844 addExtension("i", Version.value());
845 }
846
847 assert(llvm::is_sorted(ImpliedExts) && "Table not sorted by Name");
848
849 // This loop may execute over 1 iteration since implication can be layered
850 // Exits loop if no more implication is applied
852 for (auto const &Ext : Exts)
853 WorkList.insert(Ext.first);
854
855 while (!WorkList.empty()) {
856 StringRef ExtName = WorkList.pop_back_val();
857 auto Range = std::equal_range(std::begin(ImpliedExts),
858 std::end(ImpliedExts), ExtName);
859 std::for_each(Range.first, Range.second,
860 [&](const ImpliedExtsEntry &Implied) {
861 const char *ImpliedExt = Implied.ImpliedExt;
862 if (WorkList.count(ImpliedExt))
863 return;
864 if (Exts.count(ImpliedExt))
865 return;
866 auto Version = findDefaultVersion(ImpliedExt);
867 addExtension(ImpliedExt, Version.value());
868 WorkList.insert(ImpliedExt);
869 });
870 }
871
872 // Add Zcf if Zce and F are enabled on RV32.
873 if (XLen == 32 && Exts.count("zce") && Exts.count("f") &&
874 !Exts.count("zcf")) {
875 auto Version = findDefaultVersion("zcf");
876 addExtension("zcf", Version.value());
877 }
878}
879
880static constexpr StringLiteral CombineIntoExts[] = {
881 {"zk"}, {"zkn"}, {"zks"}, {"zvkn"}, {"zvknc"},
882 {"zvkng"}, {"zvks"}, {"zvksc"}, {"zvksg"},
883};
884
885void RISCVISAInfo::updateCombination() {
886 bool MadeChange = false;
887 do {
888 MadeChange = false;
889 for (StringRef CombineExt : CombineIntoExts) {
890 if (hasExtension(CombineExt))
891 continue;
892
893 // Look up the extension in the ImpliesExt table to find everything it
894 // depends on.
895 auto Range = std::equal_range(std::begin(ImpliedExts),
896 std::end(ImpliedExts), CombineExt);
897 bool HasAllRequiredFeatures = std::all_of(
898 Range.first, Range.second, [&](const ImpliedExtsEntry &Implied) {
899 return hasExtension(Implied.ImpliedExt);
900 });
901 if (HasAllRequiredFeatures) {
902 auto Version = findDefaultVersion(CombineExt);
903 addExtension(CombineExt, Version.value());
904 MadeChange = true;
905 }
906 }
907 } while (MadeChange);
908}
909
910void RISCVISAInfo::updateFLen() {
911 FLen = 0;
912 // TODO: Handle q extension.
913 if (Exts.count("d"))
914 FLen = 64;
915 else if (Exts.count("f"))
916 FLen = 32;
917}
918
919void RISCVISAInfo::updateMinVLen() {
920 for (auto const &Ext : Exts) {
921 StringRef ExtName = Ext.first;
922 bool IsZvlExt = ExtName.consume_front("zvl") && ExtName.consume_back("b");
923 if (IsZvlExt) {
924 unsigned ZvlLen;
925 if (!ExtName.getAsInteger(10, ZvlLen))
926 MinVLen = std::max(MinVLen, ZvlLen);
927 }
928 }
929}
930
931void RISCVISAInfo::updateMaxELen() {
932 assert(MaxELenFp == 0 && MaxELen == 0);
933 if (Exts.count("v")) {
934 MaxELenFp = std::max(MaxELenFp, 64u);
935 MaxELen = std::max(MaxELen, 64u);
936 }
937
938 // handles EEW restriction by sub-extension zve
939 for (auto const &Ext : Exts) {
940 StringRef ExtName = Ext.first;
941 bool IsZveExt = ExtName.consume_front("zve");
942 if (IsZveExt) {
943 if (ExtName.back() == 'f')
944 MaxELenFp = std::max(MaxELenFp, 32u);
945 else if (ExtName.back() == 'd')
946 MaxELenFp = std::max(MaxELenFp, 64u);
947 else if (ExtName.back() != 'x')
948 continue;
949
950 ExtName = ExtName.drop_back();
951 unsigned ZveELen;
952 if (!ExtName.getAsInteger(10, ZveELen))
953 MaxELen = std::max(MaxELen, ZveELen);
954 }
955 }
956}
957
958std::string RISCVISAInfo::toString() const {
959 std::string Buffer;
960 raw_string_ostream Arch(Buffer);
961
962 Arch << "rv" << XLen;
963
964 ListSeparator LS("_");
965 for (auto const &Ext : Exts) {
966 StringRef ExtName = Ext.first;
967 auto ExtInfo = Ext.second;
968 Arch << LS << ExtName;
969 Arch << ExtInfo.Major << "p" << ExtInfo.Minor;
970 }
971
972 return Arch.str();
973}
974
976RISCVISAInfo::postProcessAndChecking(std::unique_ptr<RISCVISAInfo> &&ISAInfo) {
977 ISAInfo->updateImplication();
978 ISAInfo->updateCombination();
979 ISAInfo->updateFLen();
980 ISAInfo->updateMinVLen();
981 ISAInfo->updateMaxELen();
982
983 if (Error Result = ISAInfo->checkDependency())
984 return std::move(Result);
985 return std::move(ISAInfo);
986}
987
989 if (XLen == 32) {
990 if (hasExtension("e"))
991 return "ilp32e";
992 if (hasExtension("d"))
993 return "ilp32d";
994 if (hasExtension("f"))
995 return "ilp32f";
996 return "ilp32";
997 } else if (XLen == 64) {
998 if (hasExtension("e"))
999 return "lp64e";
1000 if (hasExtension("d"))
1001 return "lp64d";
1002 if (hasExtension("f"))
1003 return "lp64f";
1004 return "lp64";
1005 }
1006 llvm_unreachable("Invalid XLEN");
1007}
1008
1010 if (Ext.empty())
1011 return false;
1012
1013 auto Pos = findLastNonVersionCharacter(Ext) + 1;
1014 StringRef Name = Ext.substr(0, Pos);
1015 StringRef Vers = Ext.substr(Pos);
1016 if (Vers.empty())
1017 return false;
1018
1019 unsigned Major, Minor, ConsumeLength;
1020 if (auto E = getExtensionVersion(Name, Vers, Major, Minor, ConsumeLength,
1021 true, true)) {
1022 consumeError(std::move(E));
1023 return false;
1024 }
1025
1026 return true;
1027}
1028
1030 if (Ext.empty())
1031 return std::string();
1032
1033 auto Pos = findLastNonVersionCharacter(Ext) + 1;
1034 StringRef Name = Ext.substr(0, Pos);
1035
1036 if (Pos != Ext.size() && !isSupportedExtensionWithVersion(Ext))
1037 return std::string();
1038
1040 return std::string();
1041
1042 return isExperimentalExtension(Name) ? "experimental-" + Name.str()
1043 : Name.str();
1044}
std::string Name
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1291
#define _
#define I(x, y, z)
Definition: MD5.cpp:58
Load MIR Sample Profile
This file implements a map that provides insertion order iteration.
static void verifyTables()
static StringRef getExtensionTypeDesc(StringRef Ext)
static Error processSingleLetterExtension(StringRef &RawExt, MapVector< std::string, RISCVISAUtils::ExtensionVersion, std::map< std::string, unsigned > > &SeenExtMap, bool IgnoreUnknown, bool EnableExperimentalExtension, bool ExperimentalExtensionVersionCheck)
static std::optional< RISCVISAUtils::ExtensionVersion > findDefaultVersion(StringRef ExtName)
static size_t findLastNonVersionCharacter(StringRef Ext)
static StringRef getExtensionType(StringRef Ext)
static constexpr StringLiteral CombineIntoExts[]
static bool stripExperimentalPrefix(StringRef &Ext)
static Error processMultiLetterExtension(StringRef RawExt, MapVector< std::string, RISCVISAUtils::ExtensionVersion, std::map< std::string, unsigned > > &SeenExtMap, bool IgnoreUnknown, bool EnableExperimentalExtension, bool ExperimentalExtensionVersionCheck)
static std::optional< RISCVISAUtils::ExtensionVersion > isExperimentalExtension(StringRef Ext)
static void PrintExtension(StringRef Name, StringRef Version, StringRef Description)
static bool operator<(const ImpliedExtsEntry &LHS, StringRef RHS)
static Error getExtensionVersion(StringRef Ext, StringRef In, unsigned &Major, unsigned &Minor, unsigned &ConsumeLength, bool EnableExperimentalExtension, bool ExperimentalExtensionVersionCheck)
static const char * RISCVGImplications[]
static Error getStringErrorForInvalidExt(std::string_view ExtName)
static Error splitExtsByUnderscore(StringRef Exts, std::vector< std::string > &SplitExts)
static bool isDigit(const char C)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file contains some functions that are useful when dealing with strings.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition: Value.cpp:469
static void verifyTables()
Value * RHS
Value * LHS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:154
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:334
Tagged union holding either a T or a Error.
Definition: Error.h:474
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
static bool isSupportedExtensionFeature(StringRef Ext)
static std::string getTargetFeatureForExtension(StringRef Ext)
static llvm::Expected< std::unique_ptr< RISCVISAInfo > > parseNormalizedArchString(StringRef Arch)
Parse RISC-V ISA info from an arch string that is already in normalized form (as defined in the psABI...
bool hasExtension(StringRef Ext) const
std::string toString() const
static llvm::Expected< std::unique_ptr< RISCVISAInfo > > postProcessAndChecking(std::unique_ptr< RISCVISAInfo > &&ISAInfo)
StringRef computeDefaultABI() const
static bool isSupportedExtension(StringRef Ext)
static llvm::Expected< std::unique_ptr< RISCVISAInfo > > parseFeatures(unsigned XLen, const std::vector< std::string > &Features)
Parse RISC-V ISA info from feature vector.
std::vector< std::string > toFeatures(bool AddAllExtensions=false, bool IgnoreUnknown=true) const
Convert RISC-V ISA info to a feature vector.
static llvm::Expected< std::unique_ptr< RISCVISAInfo > > parseArchString(StringRef Arch, bool EnableExperimentalExtension, bool ExperimentalExtensionVersionCheck=true, bool IgnoreUnknown=false)
Parse RISC-V ISA info from arch string.
static bool isSupportedExtensionWithVersion(StringRef Ext)
bool empty() const
Determine if the SetVector is empty or not.
Definition: SetVector.h:93
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:162
value_type pop_back_val()
Definition: SetVector.h:285
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition: StringRef.h:845
bool empty() const
Definition: StringMap.h:102
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:127
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:692
bool consume_back(StringRef Suffix)
Returns true if this StringRef has the given suffix and removes that suffix.
Definition: StringRef.h:647
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:462
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:222
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:563
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:257
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition: StringRef.h:601
char back() const
back - Get the last character in the string.
Definition: StringRef.h:146
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:137
char front() const
front - Get the first character in the string.
Definition: StringRef.h:140
bool consume_front(StringRef Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition: StringRef.h:627
StringRef take_front(size_t N=1) const
Return a StringRef equal to 'this' but with only the first N elements remaining.
Definition: StringRef.h:572
StringRef drop_back(size_t N=1) const
Return a StringRef equal to 'this' but with the last N elements dropped.
Definition: StringRef.h:608
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:660
std::string & str()
Returns the string's reference.
Definition: raw_ostream.h:678
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const uint64_t Version
Definition: InstrProf.h:1153
constexpr StringLiteral AllStdExts
Definition: RISCVISAUtils.h:23
std::map< std::string, ExtensionVersion, ExtensionComparator > OrderedExtensionMap
OrderedExtensionMap is std::map, it's specialized to keep entries in canonical order of extension.
Definition: RISCVISAUtils.h:43
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool operator<(int64_t V1, const APSInt &V2)
Definition: APSInt.h:361
raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1258
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1729
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition: STLExtras.h:1902
void riscvExtensionsHelp(StringMap< StringRef > DescMap)
FormattedString left_justify(StringRef Str, unsigned Width)
left_justify - append spaces after string so total output is Width characters.
Definition: Format.h:146
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1954
@ Add
Sum of integers.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1749
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1041
StringLiteral Name
bool operator<(const ImpliedExtsEntry &Other) const
const char * ImpliedExt
Description of the encoding of one expression Op.
Represents the major and version number components of a RISC-V extension.
Definition: RISCVISAUtils.h:26