clang 24.0.0git
RISCV.cpp
Go to the documentation of this file.
1//===--- RISCV.cpp - RISC-V Helpers for Tools -------------------*- 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#include "RISCV.h"
10#include "../Clang.h"
13#include "clang/Driver/Driver.h"
15#include "llvm/Option/ArgList.h"
16#include "llvm/Support/Error.h"
17#include "llvm/TargetParser/Host.h"
18#include "llvm/TargetParser/RISCVISAInfo.h"
19#include "llvm/TargetParser/RISCVTargetParser.h"
20
21using namespace clang::driver;
22using namespace clang::driver::tools;
23using namespace clang;
24using namespace llvm::opt;
25
26// Returns false if an error is diagnosed.
27static bool getArchFeatures(const Driver &D, StringRef Arch,
28 std::vector<StringRef> &Features,
29 const ArgList &Args) {
30 bool EnableExperimentalExtensions =
31 Args.hasArg(options::OPT_menable_experimental_extensions);
32 auto ISAInfo =
33 llvm::RISCVISAInfo::parseArchString(Arch, EnableExperimentalExtensions);
34 if (!ISAInfo) {
35 handleAllErrors(ISAInfo.takeError(), [&](llvm::StringError &ErrMsg) {
36 D.Diag(diag::err_drv_invalid_riscv_arch_name)
37 << Arch << ErrMsg.getMessage();
38 });
39
40 return false;
41 }
42
43 for (const std::string &Str : (*ISAInfo)->toFeatures(/*AddAllExtension=*/true,
44 /*IgnoreUnknown=*/false))
45 Features.push_back(Args.MakeArgString(Str));
46
47 if (EnableExperimentalExtensions)
48 Features.push_back(Args.MakeArgString("+experimental"));
49
50 return true;
51}
52
53static bool isValidRISCVCPU(const Driver &D, const Arg *A,
54 const llvm::Triple &Triple, StringRef Mcpu) {
55 bool Is64Bit = Triple.isRISCV64();
56 if (!llvm::RISCV::parseCPU(Mcpu, Is64Bit)) {
57 // Try inverting Is64Bit in case the CPU is valid, but for the wrong target.
58 if (llvm::RISCV::parseCPU(Mcpu, !Is64Bit))
59 D.Diag(clang::diag::err_drv_invalid_riscv_cpu_name_for_target)
60 << Mcpu << Is64Bit;
61 else
62 D.Diag(clang::diag::err_drv_unsupported_option_argument)
63 << A->getSpelling() << Mcpu;
64 return false;
65 }
66 return true;
67}
68
69void riscv::getRISCVTargetFeatures(const Driver &D, const llvm::Triple &Triple,
70 const ArgList &Args,
71 std::vector<StringRef> &Features) {
72 std::string MArch = getRISCVArch(Args, Triple);
73
74 if (!getArchFeatures(D, MArch, Features, Args))
75 return;
76
77 bool CPUFastScalarUnaligned = false;
78 bool CPUFastVectorUnaligned = false;
79
80 StringRef CPU;
81 Arg *CPUArg = nullptr;
82
83 if ((CPUArg = Args.getLastArg(options::OPT_mcpu_EQ))) {
84 CPU = CPUArg->getValue();
85 } else if ((CPUArg = Args.getLastArg(options::OPT_march_EQ))) {
86 StringRef MArchValue = CPUArg->getValue();
87 if (MArchValue == "native")
88 CPU = "native";
89 }
90
91 if (!CPU.empty()) {
92 if (CPU == "native")
93 CPU = llvm::sys::getHostCPUName();
94
95 if (!isValidRISCVCPU(D, CPUArg, Triple, CPU))
96 return;
97
98 if (llvm::RISCV::hasFastScalarUnalignedAccess(CPU))
99 CPUFastScalarUnaligned = true;
100 if (llvm::RISCV::hasFastVectorUnalignedAccess(CPU))
101 CPUFastVectorUnaligned = true;
102 }
103
104// Handle features corresponding to "-ffixed-X" options
105#define RESERVE_REG(REG) \
106 if (Args.hasArg(options::OPT_ffixed_##REG)) \
107 Features.push_back("+reserve-" #REG);
108 RESERVE_REG(x1)
109 RESERVE_REG(x2)
110 RESERVE_REG(x3)
111 RESERVE_REG(x4)
112 RESERVE_REG(x5)
113 RESERVE_REG(x6)
114 RESERVE_REG(x7)
115 RESERVE_REG(x8)
116 RESERVE_REG(x9)
117 RESERVE_REG(x10)
118 RESERVE_REG(x11)
119 RESERVE_REG(x12)
120 RESERVE_REG(x13)
121 RESERVE_REG(x14)
122 RESERVE_REG(x15)
123 RESERVE_REG(x16)
124 RESERVE_REG(x17)
125 RESERVE_REG(x18)
126 RESERVE_REG(x19)
127 RESERVE_REG(x20)
128 RESERVE_REG(x21)
129 RESERVE_REG(x22)
130 RESERVE_REG(x23)
131 RESERVE_REG(x24)
132 RESERVE_REG(x25)
133 RESERVE_REG(x26)
134 RESERVE_REG(x27)
135 RESERVE_REG(x28)
136 RESERVE_REG(x29)
137 RESERVE_REG(x30)
138 RESERVE_REG(x31)
139#undef RESERVE_REG
140
141 // -mrelax is default, unless -mno-relax is specified.
142 if (Args.hasFlag(options::OPT_mrelax, options::OPT_mno_relax, true))
143 Features.push_back("+relax");
144 else
145 Features.push_back("-relax");
146
147 // If -mstrict-align, -mno-strict-align, -mscalar-strict-align, or
148 // -mno-scalar-strict-align is passed, use it. Otherwise, the
149 // unaligned-scalar-mem is enabled if the CPU supports it or the target is
150 // Android.
151 if (const Arg *A = Args.getLastArg(
152 options::OPT_mno_strict_align, options::OPT_mscalar_strict_align,
153 options::OPT_mstrict_align, options::OPT_mno_scalar_strict_align)) {
154 if (A->getOption().matches(options::OPT_mno_strict_align) ||
155 A->getOption().matches(options::OPT_mno_scalar_strict_align)) {
156 Features.push_back("+unaligned-scalar-mem");
157 } else {
158 Features.push_back("-unaligned-scalar-mem");
159 }
160 } else if (CPUFastScalarUnaligned || Triple.isAndroid()) {
161 Features.push_back("+unaligned-scalar-mem");
162 }
163
164 // If -mstrict-align, -mno-strict-align, -mvector-strict-align, or
165 // -mno-vector-strict-align is passed, use it. Otherwise, the
166 // unaligned-vector-mem is enabled if the CPU supports it or the target is
167 // Android.
168 if (const Arg *A = Args.getLastArg(
169 options::OPT_mno_strict_align, options::OPT_mvector_strict_align,
170 options::OPT_mstrict_align, options::OPT_mno_vector_strict_align)) {
171 if (A->getOption().matches(options::OPT_mno_strict_align) ||
172 A->getOption().matches(options::OPT_mno_vector_strict_align)) {
173 Features.push_back("+unaligned-vector-mem");
174 } else {
175 Features.push_back("-unaligned-vector-mem");
176 }
177 } else if (CPUFastVectorUnaligned || Triple.isAndroid()) {
178 Features.push_back("+unaligned-vector-mem");
179 }
180
181 if (Triple.isRISCV32()) {
182 // Handle `-mzilsd-word-align` and `-mzilsd-strict-align` on rv32. These
183 // interact with the scalar alignment options - if unaligned scalar memory
184 // is allowed then that takes precedence over this option, as zilsd accesses
185 // can be 1-byte aligned in this case. Otherwise, the option
186 // `-mzilsd-word-align` option allows zilsd accesses to be 4-byte aligned
187 // rather than the usual 8-byte aligned (`-mzilsd-strict-align`).
188 if (const Arg *A = Args.getLastArg(
189 options::OPT_mstrict_align, options::OPT_mscalar_strict_align,
190 options::OPT_mzilsd_word_align, options::OPT_mno_strict_align,
191 options::OPT_mno_scalar_strict_align,
192 options::OPT_mzilsd_strict_align)) {
193 if (A->getOption().matches(options::OPT_mno_strict_align) ||
194 A->getOption().matches(options::OPT_mno_scalar_strict_align) ||
195 A->getOption().matches(options::OPT_mzilsd_word_align)) {
196 Features.push_back("+zilsd-word-align");
197 } else {
198 Features.push_back("-zilsd-word-align");
199 }
200 }
201 } else {
202 // Zilsd is not available on RV64, so report an error for these options.
203 if (const Arg *A = Args.getLastArg(options::OPT_mzilsd_word_align,
204 options::OPT_mzilsd_strict_align)) {
205 D.Diag(clang::diag::err_drv_unsupported_opt_for_target)
206 << A->getSpelling() << Triple.getTriple();
207 }
208 }
209
210 SmallVector<std::string, 4> TuneFeatures;
211 if (!riscv::getRISCVTuneCPU(D, Args, &TuneFeatures))
212 return;
213 for (const std::string &TF : TuneFeatures)
214 Features.push_back(Args.MakeArgString(TF));
215
216 // Now add any that the user explicitly requested on the command line,
217 // which may override the defaults.
218 handleTargetFeaturesGroup(D, Triple, Args, Features,
219 options::OPT_m_riscv_Features_Group);
220}
221
222StringRef riscv::getRISCVABI(const ArgList &Args, const llvm::Triple &Triple) {
223 assert(Triple.isRISCV() && "Unexpected triple");
224
225 // GCC's logic around choosing a default `-mabi=` is complex. If GCC is not
226 // configured using `--with-abi=`, then the logic for the default choice is
227 // defined in config.gcc. This function is based on the logic in GCC 9.2.0.
228 //
229 // The logic used in GCC 9.2.0 is the following, in order:
230 // 1. Explicit choices using `--with-abi=`
231 // 2. A default based on `--with-arch=`, if provided
232 // 3. A default based on the target triple's arch
233 //
234 // The logic in config.gcc is a little circular but it is not inconsistent.
235 //
236 // Clang does not have `--with-arch=` or `--with-abi=`, so we use `-march=`
237 // and `-mabi=` respectively instead.
238 //
239 // In order to make chosing logic more clear, Clang uses the following logic,
240 // in order:
241 // 1. Explicit choices using `-mabi=`
242 // 2. A default based on the architecture as determined by getRISCVArch
243 // 3. Choose a default based on the triple
244
245 // 1. If `-mabi=` is specified, use it.
246 if (const Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
247 return A->getValue();
248
249 // 2. Choose a default based on the target architecture.
250 //
251 // rv32g | rv32*d -> ilp32d
252 // rv32e -> ilp32e
253 // rv32* -> ilp32
254 // rv64g | rv64*d -> lp64d
255 // rv64e -> lp64e
256 // rv64* -> lp64
257 std::string Arch = getRISCVArch(Args, Triple);
258
259 auto ParseResult = llvm::RISCVISAInfo::parseArchString(
260 Arch, /* EnableExperimentalExtension */ true);
261 // Ignore parsing error, just go 3rd step.
262 if (!llvm::errorToBool(ParseResult.takeError()))
263 return (*ParseResult)->computeDefaultABI();
264
265 // 3. Choose a default based on the triple
266 //
267 // We deviate from GCC's defaults here:
268 // - On `riscv{XLEN}-unknown-elf` we use the integer calling convention only.
269 // - On all other OSs we use the double floating point calling convention.
270 if (Triple.isRISCV32()) {
271 if (Triple.getOS() == llvm::Triple::UnknownOS)
272 return "ilp32";
273 else
274 return "ilp32d";
275 } else {
276 if (Triple.getOS() == llvm::Triple::UnknownOS)
277 return "lp64";
278 else
279 return "lp64d";
280 }
281}
282
283static std::string getMArchFromMcpu(StringRef CPU, const llvm::Triple &Triple) {
284 if (CPU == "native") {
285 CPU = llvm::sys::getHostCPUName();
286 // If the target cpu is unrecognized, use target features.
287 if (CPU.starts_with("generic")) {
288 auto FeatureMap = llvm::sys::getHostCPUFeatures();
289 // hwprobe may be unavailable on older Linux versions.
290 if (!FeatureMap.empty()) {
291 std::vector<std::string> Features;
292 for (auto &F : FeatureMap)
293 Features.push_back(((F.second ? "+" : "-") + F.first()).str());
294 auto ParseResult = llvm::RISCVISAInfo::parseFeatures(
295 Triple.isRISCV32() ? 32 : 64, Features);
296 if (ParseResult)
297 return (*ParseResult)->toString();
298 }
299 }
300 }
301
302 return llvm::RISCV::getMArchFromMcpu(CPU).str();
303}
304
305std::string riscv::getRISCVArch(const llvm::opt::ArgList &Args,
306 const llvm::Triple &Triple) {
307 assert(Triple.isRISCV() && "Unexpected triple");
308
309 // GCC's logic around choosing a default `-march=` is complex. If GCC is not
310 // configured using `--with-arch=`, then the logic for the default choice is
311 // defined in config.gcc. This function is based on the logic in GCC 9.2.0. We
312 // deviate from GCC's default on additional `-mcpu` option (GCC does not
313 // support `-mcpu`) and baremetal targets (UnknownOS) where neither `-march`
314 // nor `-mabi` is specified.
315 //
316 // The logic used in GCC 9.2.0 is the following, in order:
317 // 1. Explicit choices using `--with-arch=`
318 // 2. A default based on `--with-abi=`, if provided
319 // 3. A default based on the target triple's arch
320 //
321 // The logic in config.gcc is a little circular but it is not inconsistent.
322 //
323 // Clang does not have `--with-arch=` or `--with-abi=`, so we use `-march=`
324 // and `-mabi=` respectively instead.
325 //
326 // Clang uses the following logic, in order:
327 // 1. Explicit choices using `-march=` (`-march=native` means the host CPU)
328 // 2. Based on `-mcpu` if `-march=` is not specified and the target CPU has a
329 // default ISA string
330 // 3. A default based on `-mabi`, if provided
331 // 4. A default based on the target triple's arch
332 //
333 // Clang does not yet support MULTILIB_REUSE, so we use `rv{XLEN}imafdc`
334 // instead of `rv{XLEN}gc` though they are (currently) equivalent.
335
336 // 1. If `-march=` is specified, use it unless the value is "unset". A value
337 // of "native" is an alias for `-mcpu=native` and selects the ISA string of
338 // the host CPU.
339 bool HasMArch = false;
340 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
341 StringRef MArchValue = A->getValue();
342 if (MArchValue != "unset") {
343 HasMArch = true;
344 if (MArchValue != "native")
345 return MArchValue.str();
346
347 std::string MArch = getMArchFromMcpu(MArchValue, Triple);
348 if (!MArch.empty())
349 return MArch;
350 }
351 }
352
353 // 2. Get march (isa string) based on `-mcpu=`. This is only used if `-march=`
354 // was not specified, so a `-march=native` that failed to determine the host
355 // ISA string above does not fall back to `-mcpu=`.
356 if (!HasMArch) {
357 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
358 std::string MArch = getMArchFromMcpu(A->getValue(), Triple);
359 // Bypass if target cpu's default march is empty.
360 if (!MArch.empty())
361 return MArch;
362 }
363 }
364
365 // 3. Choose a default based on `-mabi=`
366 //
367 // ilp32e -> rv32e
368 // lp64e -> rv64e
369 // ilp32 | ilp32f | ilp32d -> rv32imafdc
370 // lp64 | lp64f | lp64d -> rv64imafdc
371 if (const Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
372 StringRef MABI = A->getValue();
373
374 if (MABI.equals_insensitive("ilp32e"))
375 return "rv32e";
376 if (MABI.equals_insensitive("lp64e"))
377 return "rv64e";
378 if (MABI.starts_with_insensitive("ilp32"))
379 return "rv32imafdc";
380 if (MABI.starts_with_insensitive("lp64")) {
381 if (Triple.isAndroid())
382 return "rv64imafdcv_zba_zbb_zbs";
383 if (Triple.isOSFuchsia())
384 return "rva22u64_v";
385 return "rv64imafdc";
386 }
387 }
388
389 // 4. Choose a default based on the triple
390 //
391 // We deviate from GCC's defaults here:
392 // - On `riscv{XLEN}-unknown-elf` we default to `rv{XLEN}imac`
393 // - On all other OSs we use `rv{XLEN}imafdc` (equivalent to `rv{XLEN}gc`)
394 if (Triple.isRISCV32()) {
395 if (Triple.getOS() == llvm::Triple::UnknownOS)
396 return "rv32imac";
397 return "rv32imafdc";
398 }
399
400 if (Triple.getOS() == llvm::Triple::UnknownOS)
401 return "rv64imac";
402 if (Triple.isAndroid())
403 return "rv64imafdcv_zba_zbb_zbs";
404 if (Triple.isOSFuchsia())
405 return "rva22u64_v";
406 return "rv64imafdc";
407}
408
409std::string riscv::getRISCVTargetCPU(const llvm::opt::ArgList &Args,
410 const llvm::Triple &Triple) {
411 std::string CPU;
412 // If we have -mcpu, use that. Otherwise, check for -march=native.
413 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
414 CPU = A->getValue();
415 } else if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
416 // `-march=native` is an alias for `-mcpu=native`.
417 StringRef MArchValue = A->getValue();
418 if (MArchValue == "native")
419 CPU = "native";
420 }
421
422 // Handle CPU name is 'native'.
423 if (CPU == "native")
424 CPU = llvm::sys::getHostCPUName();
425
426 if (!CPU.empty())
427 return CPU;
428
429 return Triple.isRISCV64() ? "generic-rv64" : "generic-rv32";
430}
431
432std::optional<StringRef>
433riscv::getRISCVTuneCPU(const Driver &D, const llvm::opt::ArgList &Args,
434 SmallVectorImpl<std::string> *TuneFeatures) {
435 const Arg *MTuneArg = Args.getLastArg(options::OPT_mtune_EQ);
436 if (!MTuneArg)
437 return "";
438
439 StringRef TuneCPU = MTuneArg->getValue();
440 StringRef TFString;
441
442 auto Idx = TuneCPU.find(':');
443 if (Idx != StringRef::npos) {
444 if (!Args.hasFlag(options::OPT_mexperimental_mtune_syntax,
445 options::OPT_mno_experimental_mtune_syntax, false)) {
446 // Only print this diagnostics if it's used for retrieving tune features
447 // to avoid printing the same error message multiple times.
448 if (TuneFeatures)
449 D.Diag(diag::err_drv_invalid_riscv_mtune_string)
450 << 0 << TuneCPU
451 << "require '-mexperimental-mtune-syntax' to use with tune feature "
452 "string";
453 return std::nullopt;
454 }
455
456 TFString = TuneCPU.substr(Idx + 1);
457 TuneCPU = TuneCPU.slice(0, Idx);
458 }
459
460 if (TuneFeatures && !TFString.empty()) {
461 if (auto E = llvm::RISCV::parseTuneFeatureString(TuneCPU, TFString,
462 *TuneFeatures)) {
463 D.Diag(diag::err_drv_invalid_riscv_mtune_string)
464 << 1 << TFString << llvm::toString(std::move(E));
465 return std::nullopt;
466 }
467 }
468
469 // Apply -mtune=native after applying features. Not all features apply to
470 // all CPUs so an -mtune=native:<feature> may fail depending on what the
471 // native was expanded to.
472 if (TuneCPU == "native")
473 TuneCPU = llvm::sys::getHostCPUName();
474
475 return TuneCPU;
476}
static bool isValidRISCVCPU(const Driver &D, const Arg *A, const llvm::Triple &Triple, StringRef Mcpu)
Definition RISCV.cpp:53
static std::string getMArchFromMcpu(StringRef CPU, const llvm::Triple &Triple)
Definition RISCV.cpp:283
#define RESERVE_REG(REG)
static bool getArchFeatures(const Driver &D, StringRef Arch, std::vector< StringRef > &Features, const ArgList &Args)
Definition RISCV.cpp:27
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:95
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:159
std::string getRISCVArch(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition RISCV.cpp:305
std::string getRISCVTargetCPU(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition RISCV.cpp:409
StringRef getRISCVABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
std::optional< StringRef > getRISCVTuneCPU(const Driver &D, const llvm::opt::ArgList &Args, SmallVectorImpl< std::string > *TuneFeatures=nullptr)
Return the tune CPU and optionally, the tune features.
Definition RISCV.cpp:433
void getRISCVTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< llvm::StringRef > &Features)
void handleTargetFeaturesGroup(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< StringRef > &Features, llvm::opt::OptSpecifier Group)
Iterate Args and convert -mxxx to +xxx and -mno-xxx to -xxx and append it to Features.
Top level wrappers for InstallAPI frontend operations.