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"
11#include "ToolChains/CommonArgs.h"
12#include "clang/Basic/CharInfo.h"
13#include "clang/Driver/Driver.h"
14#include "clang/Driver/DriverDiagnostic.h"
15#include "clang/Driver/Options.h"
16#include "llvm/Option/ArgList.h"
17#include "llvm/Support/Error.h"
18#include "llvm/Support/RISCVISAInfo.h"
19#include "llvm/Support/raw_ostream.h"
20#include "llvm/TargetParser/Host.h"
21#include "llvm/TargetParser/RISCVTargetParser.h"
22
23using namespace clang::driver;
24using namespace clang::driver::tools;
25using namespace clang;
26using namespace llvm::opt;
27
28// Returns false if an error is diagnosed.
29static bool getArchFeatures(const Driver &D, StringRef Arch,
30                            std::vector<StringRef> &Features,
31                            const ArgList &Args) {
32  bool EnableExperimentalExtensions =
33      Args.hasArg(options::OPT_menable_experimental_extensions);
34  auto ISAInfo =
35      llvm::RISCVISAInfo::parseArchString(Arch, EnableExperimentalExtensions);
36  if (!ISAInfo) {
37    handleAllErrors(ISAInfo.takeError(), [&](llvm::StringError &ErrMsg) {
38      D.Diag(diag::err_drv_invalid_riscv_arch_name)
39          << Arch << ErrMsg.getMessage();
40    });
41
42    return false;
43  }
44
45  for (const std::string &Str : (*ISAInfo)->toFeatures(/*AddAllExtension=*/true,
46                                                       /*IgnoreUnknown=*/false))
47    Features.push_back(Args.MakeArgString(Str));
48
49  if (EnableExperimentalExtensions)
50    Features.push_back(Args.MakeArgString("+experimental"));
51
52  return true;
53}
54
55// Get features except standard extension feature
56static void getRISCFeaturesFromMcpu(const Driver &D, const Arg *A,
57                                    const llvm::Triple &Triple,
58                                    StringRef Mcpu,
59                                    std::vector<StringRef> &Features) {
60  bool Is64Bit = Triple.isRISCV64();
61  if (!llvm::RISCV::parseCPU(Mcpu, Is64Bit)) {
62    // Try inverting Is64Bit in case the CPU is valid, but for the wrong target.
63    if (llvm::RISCV::parseCPU(Mcpu, !Is64Bit))
64      D.Diag(clang::diag::err_drv_invalid_riscv_cpu_name_for_target)
65          << Mcpu << Is64Bit;
66    else
67      D.Diag(clang::diag::err_drv_unsupported_option_argument)
68          << A->getSpelling() << Mcpu;
69  }
70
71  if (llvm::RISCV::hasFastUnalignedAccess(Mcpu))
72    Features.push_back("+fast-unaligned-access");
73}
74
75void riscv::getRISCVTargetFeatures(const Driver &D, const llvm::Triple &Triple,
76                                   const ArgList &Args,
77                                   std::vector<StringRef> &Features) {
78  StringRef MArch = getRISCVArch(Args, Triple);
79
80  if (!getArchFeatures(D, MArch, Features, Args))
81    return;
82
83  // If users give march and mcpu, get std extension feature from MArch
84  // and other features (ex. mirco architecture feature) from mcpu
85  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
86    StringRef CPU = A->getValue();
87    if (CPU == "native")
88      CPU = llvm::sys::getHostCPUName();
89
90    getRISCFeaturesFromMcpu(D, A, Triple, CPU, Features);
91  }
92
93  // Handle features corresponding to "-ffixed-X" options
94  if (Args.hasArg(options::OPT_ffixed_x1))
95    Features.push_back("+reserve-x1");
96  if (Args.hasArg(options::OPT_ffixed_x2))
97    Features.push_back("+reserve-x2");
98  if (Args.hasArg(options::OPT_ffixed_x3))
99    Features.push_back("+reserve-x3");
100  if (Args.hasArg(options::OPT_ffixed_x4))
101    Features.push_back("+reserve-x4");
102  if (Args.hasArg(options::OPT_ffixed_x5))
103    Features.push_back("+reserve-x5");
104  if (Args.hasArg(options::OPT_ffixed_x6))
105    Features.push_back("+reserve-x6");
106  if (Args.hasArg(options::OPT_ffixed_x7))
107    Features.push_back("+reserve-x7");
108  if (Args.hasArg(options::OPT_ffixed_x8))
109    Features.push_back("+reserve-x8");
110  if (Args.hasArg(options::OPT_ffixed_x9))
111    Features.push_back("+reserve-x9");
112  if (Args.hasArg(options::OPT_ffixed_x10))
113    Features.push_back("+reserve-x10");
114  if (Args.hasArg(options::OPT_ffixed_x11))
115    Features.push_back("+reserve-x11");
116  if (Args.hasArg(options::OPT_ffixed_x12))
117    Features.push_back("+reserve-x12");
118  if (Args.hasArg(options::OPT_ffixed_x13))
119    Features.push_back("+reserve-x13");
120  if (Args.hasArg(options::OPT_ffixed_x14))
121    Features.push_back("+reserve-x14");
122  if (Args.hasArg(options::OPT_ffixed_x15))
123    Features.push_back("+reserve-x15");
124  if (Args.hasArg(options::OPT_ffixed_x16))
125    Features.push_back("+reserve-x16");
126  if (Args.hasArg(options::OPT_ffixed_x17))
127    Features.push_back("+reserve-x17");
128  if (Args.hasArg(options::OPT_ffixed_x18))
129    Features.push_back("+reserve-x18");
130  if (Args.hasArg(options::OPT_ffixed_x19))
131    Features.push_back("+reserve-x19");
132  if (Args.hasArg(options::OPT_ffixed_x20))
133    Features.push_back("+reserve-x20");
134  if (Args.hasArg(options::OPT_ffixed_x21))
135    Features.push_back("+reserve-x21");
136  if (Args.hasArg(options::OPT_ffixed_x22))
137    Features.push_back("+reserve-x22");
138  if (Args.hasArg(options::OPT_ffixed_x23))
139    Features.push_back("+reserve-x23");
140  if (Args.hasArg(options::OPT_ffixed_x24))
141    Features.push_back("+reserve-x24");
142  if (Args.hasArg(options::OPT_ffixed_x25))
143    Features.push_back("+reserve-x25");
144  if (Args.hasArg(options::OPT_ffixed_x26))
145    Features.push_back("+reserve-x26");
146  if (Args.hasArg(options::OPT_ffixed_x27))
147    Features.push_back("+reserve-x27");
148  if (Args.hasArg(options::OPT_ffixed_x28))
149    Features.push_back("+reserve-x28");
150  if (Args.hasArg(options::OPT_ffixed_x29))
151    Features.push_back("+reserve-x29");
152  if (Args.hasArg(options::OPT_ffixed_x30))
153    Features.push_back("+reserve-x30");
154  if (Args.hasArg(options::OPT_ffixed_x31))
155    Features.push_back("+reserve-x31");
156
157  // FreeBSD local, because ld.lld doesn't support relaxations
158  // -mno-relax is default, unless -mrelax is specified.
159  if (Args.hasFlag(options::OPT_mrelax, options::OPT_mno_relax, false)) {
160    Features.push_back("+relax");
161    // -gsplit-dwarf -mrelax requires DW_AT_high_pc/DW_AT_ranges/... indexing
162    // into .debug_addr, which is currently not implemented.
163    Arg *A;
164    if (getDebugFissionKind(D, Args, A) != DwarfFissionKind::None)
165      D.Diag(clang::diag::err_drv_riscv_unsupported_with_linker_relaxation)
166          << A->getAsString(Args);
167  } else {
168    Features.push_back("-relax");
169  }
170
171  // -mno-unaligned-access is default, unless -munaligned-access is specified.
172  AddTargetFeature(Args, Features, options::OPT_munaligned_access,
173                   options::OPT_mno_unaligned_access, "fast-unaligned-access");
174
175  // Now add any that the user explicitly requested on the command line,
176  // which may override the defaults.
177  handleTargetFeaturesGroup(D, Triple, Args, Features,
178                            options::OPT_m_riscv_Features_Group);
179}
180
181StringRef riscv::getRISCVABI(const ArgList &Args, const llvm::Triple &Triple) {
182  assert(Triple.isRISCV() && "Unexpected triple");
183
184  // GCC's logic around choosing a default `-mabi=` is complex. If GCC is not
185  // configured using `--with-abi=`, then the logic for the default choice is
186  // defined in config.gcc. This function is based on the logic in GCC 9.2.0.
187  //
188  // The logic used in GCC 9.2.0 is the following, in order:
189  // 1. Explicit choices using `--with-abi=`
190  // 2. A default based on `--with-arch=`, if provided
191  // 3. A default based on the target triple's arch
192  //
193  // The logic in config.gcc is a little circular but it is not inconsistent.
194  //
195  // Clang does not have `--with-arch=` or `--with-abi=`, so we use `-march=`
196  // and `-mabi=` respectively instead.
197  //
198  // In order to make chosing logic more clear, Clang uses the following logic,
199  // in order:
200  // 1. Explicit choices using `-mabi=`
201  // 2. A default based on the architecture as determined by getRISCVArch
202  // 3. Choose a default based on the triple
203
204  // 1. If `-mabi=` is specified, use it.
205  if (const Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
206    return A->getValue();
207
208  // 2. Choose a default based on the target architecture.
209  //
210  // rv32g | rv32*d -> ilp32d
211  // rv32e -> ilp32e
212  // rv32* -> ilp32
213  // rv64g | rv64*d -> lp64d
214  // rv64e -> lp64e
215  // rv64* -> lp64
216  StringRef Arch = getRISCVArch(Args, Triple);
217
218  auto ParseResult = llvm::RISCVISAInfo::parseArchString(
219      Arch, /* EnableExperimentalExtension */ true);
220  // Ignore parsing error, just go 3rd step.
221  if (!llvm::errorToBool(ParseResult.takeError()))
222    return (*ParseResult)->computeDefaultABI();
223
224  // 3. Choose a default based on the triple
225  //
226  // We deviate from GCC's defaults here:
227  // - On `riscv{XLEN}-unknown-elf` we use the integer calling convention only.
228  // - On all other OSs we use the double floating point calling convention.
229  if (Triple.isRISCV32()) {
230    if (Triple.getOS() == llvm::Triple::UnknownOS)
231      return "ilp32";
232    else
233      return "ilp32d";
234  } else {
235    if (Triple.getOS() == llvm::Triple::UnknownOS)
236      return "lp64";
237    else
238      return "lp64d";
239  }
240}
241
242StringRef riscv::getRISCVArch(const llvm::opt::ArgList &Args,
243                              const llvm::Triple &Triple) {
244  assert(Triple.isRISCV() && "Unexpected triple");
245
246  // GCC's logic around choosing a default `-march=` is complex. If GCC is not
247  // configured using `--with-arch=`, then the logic for the default choice is
248  // defined in config.gcc. This function is based on the logic in GCC 9.2.0. We
249  // deviate from GCC's default on additional `-mcpu` option (GCC does not
250  // support `-mcpu`) and baremetal targets (UnknownOS) where neither `-march`
251  // nor `-mabi` is specified.
252  //
253  // The logic used in GCC 9.2.0 is the following, in order:
254  // 1. Explicit choices using `--with-arch=`
255  // 2. A default based on `--with-abi=`, if provided
256  // 3. A default based on the target triple's arch
257  //
258  // The logic in config.gcc is a little circular but it is not inconsistent.
259  //
260  // Clang does not have `--with-arch=` or `--with-abi=`, so we use `-march=`
261  // and `-mabi=` respectively instead.
262  //
263  // Clang uses the following logic, in order:
264  // 1. Explicit choices using `-march=`
265  // 2. Based on `-mcpu` if the target CPU has a default ISA string
266  // 3. A default based on `-mabi`, if provided
267  // 4. A default based on the target triple's arch
268  //
269  // Clang does not yet support MULTILIB_REUSE, so we use `rv{XLEN}imafdc`
270  // instead of `rv{XLEN}gc` though they are (currently) equivalent.
271
272  // 1. If `-march=` is specified, use it.
273  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
274    return A->getValue();
275
276  // 2. Get march (isa string) based on `-mcpu=`
277  if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
278    StringRef CPU = A->getValue();
279    if (CPU == "native")
280      CPU = llvm::sys::getHostCPUName();
281    StringRef MArch = llvm::RISCV::getMArchFromMcpu(CPU);
282    // Bypass if target cpu's default march is empty.
283    if (MArch != "")
284      return MArch;
285  }
286
287  // 3. Choose a default based on `-mabi=`
288  //
289  // ilp32e -> rv32e
290  // lp64e -> rv64e
291  // ilp32 | ilp32f | ilp32d -> rv32imafdc
292  // lp64 | lp64f | lp64d -> rv64imafdc
293  if (const Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
294    StringRef MABI = A->getValue();
295
296    if (MABI.equals_insensitive("ilp32e"))
297      return "rv32e";
298    else if (MABI.equals_insensitive("lp64e"))
299      return "rv64e";
300    else if (MABI.starts_with_insensitive("ilp32"))
301      return "rv32imafdc";
302    else if (MABI.starts_with_insensitive("lp64")) {
303      if (Triple.isAndroid())
304        return "rv64imafdcv_zba_zbb_zbs";
305
306      return "rv64imafdc";
307    }
308  }
309
310  // 4. Choose a default based on the triple
311  //
312  // We deviate from GCC's defaults here:
313  // - On `riscv{XLEN}-unknown-elf` we default to `rv{XLEN}imac`
314  // - On all other OSs we use `rv{XLEN}imafdc` (equivalent to `rv{XLEN}gc`)
315  if (Triple.isRISCV32()) {
316    if (Triple.getOS() == llvm::Triple::UnknownOS)
317      return "rv32imac";
318    else
319      return "rv32imafdc";
320  } else {
321    if (Triple.getOS() == llvm::Triple::UnknownOS)
322      return "rv64imac";
323    else if (Triple.isAndroid())
324      return "rv64imafdcv_zba_zbb_zbs";
325    else
326      return "rv64imafdc";
327  }
328}
329
330std::string riscv::getRISCVTargetCPU(const llvm::opt::ArgList &Args,
331                                     const llvm::Triple &Triple) {
332  std::string CPU;
333  // If we have -mcpu, use that.
334  if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
335    CPU = A->getValue();
336
337  // Handle CPU name is 'native'.
338  if (CPU == "native")
339    CPU = llvm::sys::getHostCPUName();
340
341  if (!CPU.empty())
342    return CPU;
343
344  return Triple.isRISCV64() ? "generic-rv64" : "generic-rv32";
345}
346