clang 23.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 // If users give march and mcpu, get std extension feature from MArch
81 // and other features (ex. mirco architecture feature) from mcpu
82 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
83 StringRef CPU = A->getValue();
84 if (CPU == "native")
85 CPU = llvm::sys::getHostCPUName();
86
87 if (!isValidRISCVCPU(D, A, Triple, CPU))
88 return;
89
90 if (llvm::RISCV::hasFastScalarUnalignedAccess(CPU))
91 CPUFastScalarUnaligned = true;
92 if (llvm::RISCV::hasFastVectorUnalignedAccess(CPU))
93 CPUFastVectorUnaligned = true;
94 }
95
96// Handle features corresponding to "-ffixed-X" options
97#define RESERVE_REG(REG) \
98 if (Args.hasArg(options::OPT_ffixed_##REG)) \
99 Features.push_back("+reserve-" #REG);
100 RESERVE_REG(x1)
101 RESERVE_REG(x2)
102 RESERVE_REG(x3)
103 RESERVE_REG(x4)
104 RESERVE_REG(x5)
105 RESERVE_REG(x6)
106 RESERVE_REG(x7)
107 RESERVE_REG(x8)
108 RESERVE_REG(x9)
109 RESERVE_REG(x10)
110 RESERVE_REG(x11)
111 RESERVE_REG(x12)
112 RESERVE_REG(x13)
113 RESERVE_REG(x14)
114 RESERVE_REG(x15)
115 RESERVE_REG(x16)
116 RESERVE_REG(x17)
117 RESERVE_REG(x18)
118 RESERVE_REG(x19)
119 RESERVE_REG(x20)
120 RESERVE_REG(x21)
121 RESERVE_REG(x22)
122 RESERVE_REG(x23)
123 RESERVE_REG(x24)
124 RESERVE_REG(x25)
125 RESERVE_REG(x26)
126 RESERVE_REG(x27)
127 RESERVE_REG(x28)
128 RESERVE_REG(x29)
129 RESERVE_REG(x30)
130 RESERVE_REG(x31)
131#undef RESERVE_REG
132
133 // -mrelax is default, unless -mno-relax is specified.
134 if (Args.hasFlag(options::OPT_mrelax, options::OPT_mno_relax, true))
135 Features.push_back("+relax");
136 else
137 Features.push_back("-relax");
138
139 // If -mstrict-align, -mno-strict-align, -mscalar-strict-align, or
140 // -mno-scalar-strict-align is passed, use it. Otherwise, the
141 // unaligned-scalar-mem is enabled if the CPU supports it or the target is
142 // Android.
143 if (const Arg *A = Args.getLastArg(
144 options::OPT_mno_strict_align, options::OPT_mscalar_strict_align,
145 options::OPT_mstrict_align, options::OPT_mno_scalar_strict_align)) {
146 if (A->getOption().matches(options::OPT_mno_strict_align) ||
147 A->getOption().matches(options::OPT_mno_scalar_strict_align)) {
148 Features.push_back("+unaligned-scalar-mem");
149 } else {
150 Features.push_back("-unaligned-scalar-mem");
151 }
152 } else if (CPUFastScalarUnaligned || Triple.isAndroid()) {
153 Features.push_back("+unaligned-scalar-mem");
154 }
155
156 // If -mstrict-align, -mno-strict-align, -mvector-strict-align, or
157 // -mno-vector-strict-align is passed, use it. Otherwise, the
158 // unaligned-vector-mem is enabled if the CPU supports it or the target is
159 // Android.
160 if (const Arg *A = Args.getLastArg(
161 options::OPT_mno_strict_align, options::OPT_mvector_strict_align,
162 options::OPT_mstrict_align, options::OPT_mno_vector_strict_align)) {
163 if (A->getOption().matches(options::OPT_mno_strict_align) ||
164 A->getOption().matches(options::OPT_mno_vector_strict_align)) {
165 Features.push_back("+unaligned-vector-mem");
166 } else {
167 Features.push_back("-unaligned-vector-mem");
168 }
169 } else if (CPUFastVectorUnaligned || Triple.isAndroid()) {
170 Features.push_back("+unaligned-vector-mem");
171 }
172
173 if (Triple.isRISCV32()) {
174 // Handle `-mzilsd-word-align` and `-mzilsd-strict-align` on rv32. These
175 // interact with the scalar alignment options - if unaligned scalar memory
176 // is allowed then that takes precedence over this option, as zilsd accesses
177 // can be 1-byte aligned in this case. Otherwise, the option
178 // `-mzilsd-word-align` option allows zilsd accesses to be 4-byte aligned
179 // rather than the usual 8-byte aligned (`-mzilsd-strict-align`).
180 if (const Arg *A = Args.getLastArg(
181 options::OPT_mstrict_align, options::OPT_mscalar_strict_align,
182 options::OPT_mzilsd_word_align, options::OPT_mno_strict_align,
183 options::OPT_mno_scalar_strict_align,
184 options::OPT_mzilsd_strict_align)) {
185 if (A->getOption().matches(options::OPT_mno_strict_align) ||
186 A->getOption().matches(options::OPT_mno_scalar_strict_align) ||
187 A->getOption().matches(options::OPT_mzilsd_word_align)) {
188 Features.push_back("+zilsd-word-align");
189 } else {
190 Features.push_back("-zilsd-word-align");
191 }
192 }
193 } else {
194 // Zilsd is not available on RV64, so report an error for these options.
195 if (const Arg *A = Args.getLastArg(options::OPT_mzilsd_word_align,
196 options::OPT_mzilsd_strict_align)) {
197 D.Diag(clang::diag::err_drv_unsupported_opt_for_target)
198 << A->getSpelling() << Triple.getTriple();
199 }
200 }
201
202 // Now add any that the user explicitly requested on the command line,
203 // which may override the defaults.
204 handleTargetFeaturesGroup(D, Triple, Args, Features,
205 options::OPT_m_riscv_Features_Group);
206}
207
208StringRef riscv::getRISCVABI(const ArgList &Args, const llvm::Triple &Triple) {
209 assert(Triple.isRISCV() && "Unexpected triple");
210
211 // GCC's logic around choosing a default `-mabi=` is complex. If GCC is not
212 // configured using `--with-abi=`, then the logic for the default choice is
213 // defined in config.gcc. This function is based on the logic in GCC 9.2.0.
214 //
215 // The logic used in GCC 9.2.0 is the following, in order:
216 // 1. Explicit choices using `--with-abi=`
217 // 2. A default based on `--with-arch=`, if provided
218 // 3. A default based on the target triple's arch
219 //
220 // The logic in config.gcc is a little circular but it is not inconsistent.
221 //
222 // Clang does not have `--with-arch=` or `--with-abi=`, so we use `-march=`
223 // and `-mabi=` respectively instead.
224 //
225 // In order to make chosing logic more clear, Clang uses the following logic,
226 // in order:
227 // 1. Explicit choices using `-mabi=`
228 // 2. A default based on the architecture as determined by getRISCVArch
229 // 3. Choose a default based on the triple
230
231 // 1. If `-mabi=` is specified, use it.
232 if (const Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
233 return A->getValue();
234
235 // 2. Choose a default based on the target architecture.
236 //
237 // rv32g | rv32*d -> ilp32d
238 // rv32e -> ilp32e
239 // rv32* -> ilp32
240 // rv64g | rv64*d -> lp64d
241 // rv64e -> lp64e
242 // rv64* -> lp64
243 std::string Arch = getRISCVArch(Args, Triple);
244
245 auto ParseResult = llvm::RISCVISAInfo::parseArchString(
246 Arch, /* EnableExperimentalExtension */ true);
247 // Ignore parsing error, just go 3rd step.
248 if (!llvm::errorToBool(ParseResult.takeError()))
249 return (*ParseResult)->computeDefaultABI();
250
251 // 3. Choose a default based on the triple
252 //
253 // We deviate from GCC's defaults here:
254 // - On `riscv{XLEN}-unknown-elf` we use the integer calling convention only.
255 // - On all other OSs we use the double floating point calling convention.
256 if (Triple.isRISCV32()) {
257 if (Triple.getOS() == llvm::Triple::UnknownOS)
258 return "ilp32";
259 else
260 return "ilp32d";
261 } else {
262 if (Triple.getOS() == llvm::Triple::UnknownOS)
263 return "lp64";
264 else
265 return "lp64d";
266 }
267}
268
269std::string riscv::getRISCVArch(const llvm::opt::ArgList &Args,
270 const llvm::Triple &Triple) {
271 assert(Triple.isRISCV() && "Unexpected triple");
272
273 // GCC's logic around choosing a default `-march=` is complex. If GCC is not
274 // configured using `--with-arch=`, then the logic for the default choice is
275 // defined in config.gcc. This function is based on the logic in GCC 9.2.0. We
276 // deviate from GCC's default on additional `-mcpu` option (GCC does not
277 // support `-mcpu`) and baremetal targets (UnknownOS) where neither `-march`
278 // nor `-mabi` is specified.
279 //
280 // The logic used in GCC 9.2.0 is the following, in order:
281 // 1. Explicit choices using `--with-arch=`
282 // 2. A default based on `--with-abi=`, if provided
283 // 3. A default based on the target triple's arch
284 //
285 // The logic in config.gcc is a little circular but it is not inconsistent.
286 //
287 // Clang does not have `--with-arch=` or `--with-abi=`, so we use `-march=`
288 // and `-mabi=` respectively instead.
289 //
290 // Clang uses the following logic, in order:
291 // 1. Explicit choices using `-march=`
292 // 2. Based on `-mcpu` if the target CPU has a default ISA string
293 // 3. A default based on `-mabi`, if provided
294 // 4. A default based on the target triple's arch
295 //
296 // Clang does not yet support MULTILIB_REUSE, so we use `rv{XLEN}imafdc`
297 // instead of `rv{XLEN}gc` though they are (currently) equivalent.
298
299 // 1. If `-march=` is specified, use it unless the value is "unset".
300 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
301 StringRef MArch = A->getValue();
302 if (MArch != "unset")
303 return MArch.str();
304 }
305
306 // 2. Get march (isa string) based on `-mcpu=`
307 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
308 StringRef CPU = A->getValue();
309 if (CPU == "native") {
310 CPU = llvm::sys::getHostCPUName();
311 // If the target cpu is unrecognized, use target features.
312 if (CPU.starts_with("generic")) {
313 auto FeatureMap = llvm::sys::getHostCPUFeatures();
314 // hwprobe may be unavailable on older Linux versions.
315 if (!FeatureMap.empty()) {
316 std::vector<std::string> Features;
317 for (auto &F : FeatureMap)
318 Features.push_back(((F.second ? "+" : "-") + F.first()).str());
319 auto ParseResult = llvm::RISCVISAInfo::parseFeatures(
320 Triple.isRISCV32() ? 32 : 64, Features);
321 if (ParseResult)
322 return (*ParseResult)->toString();
323 }
324 }
325 }
326
327 StringRef MArch = llvm::RISCV::getMArchFromMcpu(CPU);
328 // Bypass if target cpu's default march is empty.
329 if (!MArch.empty())
330 return MArch.str();
331 }
332
333 // 3. Choose a default based on `-mabi=`
334 //
335 // ilp32e -> rv32e
336 // lp64e -> rv64e
337 // ilp32 | ilp32f | ilp32d -> rv32imafdc
338 // lp64 | lp64f | lp64d -> rv64imafdc
339 if (const Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
340 StringRef MABI = A->getValue();
341
342 if (MABI.equals_insensitive("ilp32e"))
343 return "rv32e";
344 if (MABI.equals_insensitive("lp64e"))
345 return "rv64e";
346 if (MABI.starts_with_insensitive("ilp32"))
347 return "rv32imafdc";
348 if (MABI.starts_with_insensitive("lp64")) {
349 if (Triple.isAndroid())
350 return "rv64imafdcv_zba_zbb_zbs";
351 if (Triple.isOSFuchsia())
352 return "rva22u64_v";
353 return "rv64imafdc";
354 }
355 }
356
357 // 4. Choose a default based on the triple
358 //
359 // We deviate from GCC's defaults here:
360 // - On `riscv{XLEN}-unknown-elf` we default to `rv{XLEN}imac`
361 // - On all other OSs we use `rv{XLEN}imafdc` (equivalent to `rv{XLEN}gc`)
362 if (Triple.isRISCV32()) {
363 if (Triple.getOS() == llvm::Triple::UnknownOS)
364 return "rv32imac";
365 return "rv32imafdc";
366 }
367
368 if (Triple.getOS() == llvm::Triple::UnknownOS)
369 return "rv64imac";
370 if (Triple.isAndroid())
371 return "rv64imafdcv_zba_zbb_zbs";
372 if (Triple.isOSFuchsia())
373 return "rva22u64_v";
374 return "rv64imafdc";
375}
376
377std::string riscv::getRISCVTargetCPU(const llvm::opt::ArgList &Args,
378 const llvm::Triple &Triple) {
379 std::string CPU;
380 // If we have -mcpu, use that.
381 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
382 CPU = A->getValue();
383
384 // Handle CPU name is 'native'.
385 if (CPU == "native")
386 CPU = llvm::sys::getHostCPUName();
387
388 if (!CPU.empty())
389 return CPU;
390
391 return Triple.isRISCV64() ? "generic-rv64" : "generic-rv32";
392}
static bool isValidRISCVCPU(const Driver &D, const Arg *A, const llvm::Triple &Triple, StringRef Mcpu)
Definition RISCV.cpp:53
#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:94
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:158
std::string getRISCVArch(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition RISCV.cpp:269
std::string getRISCVTargetCPU(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition RISCV.cpp:377
StringRef getRISCVABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
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.
The JSON file list parser is used to communicate input to InstallAPI.