1 //===--- RISCV.cpp - RISCV 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/Basic/CharInfo.h"
11 #include "clang/Driver/Driver.h"
12 #include "clang/Driver/DriverDiagnostic.h"
13 #include "clang/Driver/Options.h"
14 #include "llvm/Option/ArgList.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/Support/TargetParser.h"
17 #include "llvm/Support/raw_ostream.h"
18 #include "ToolChains/CommonArgs.h"
19 
20 using namespace clang::driver;
21 using namespace clang::driver::tools;
22 using namespace clang;
23 using namespace llvm::opt;
24 
25 namespace {
26 // Represents the major and version number components of a RISC-V extension
27 struct RISCVExtensionVersion {
28   StringRef Major;
29   StringRef Minor;
30 };
31 } // end anonymous namespace
32 
33 static StringRef getExtensionTypeDesc(StringRef Ext) {
34   if (Ext.startswith("sx"))
35     return "non-standard supervisor-level extension";
36   if (Ext.startswith("s"))
37     return "standard supervisor-level extension";
38   if (Ext.startswith("x"))
39     return "non-standard user-level extension";
40   if (Ext.startswith("z"))
41     return "standard user-level extension";
42   return StringRef();
43 }
44 
45 static StringRef getExtensionType(StringRef Ext) {
46   if (Ext.startswith("sx"))
47     return "sx";
48   if (Ext.startswith("s"))
49     return "s";
50   if (Ext.startswith("x"))
51     return "x";
52   if (Ext.startswith("z"))
53     return "z";
54   return StringRef();
55 }
56 
57 // If the extension is supported as experimental, return the version of that
58 // extension that the compiler currently supports.
59 static Optional<RISCVExtensionVersion>
60 isExperimentalExtension(StringRef Ext) {
61   if (Ext == "b" || Ext == "zba" || Ext == "zbb" || Ext == "zbc" ||
62       Ext == "zbe" || Ext == "zbf" || Ext == "zbm" || Ext == "zbp" ||
63       Ext == "zbr" || Ext == "zbs" || Ext == "zbt" || Ext == "zbproposedc")
64     return RISCVExtensionVersion{"0", "93"};
65   if (Ext == "v" || Ext == "zvamo" || Ext == "zvlsseg")
66     return RISCVExtensionVersion{"0", "10"};
67   if (Ext == "zfh")
68     return RISCVExtensionVersion{"0", "1"};
69   return None;
70 }
71 
72 static bool isSupportedExtension(StringRef Ext) {
73   // LLVM supports "z" extensions which are marked as experimental.
74   if (isExperimentalExtension(Ext))
75     return true;
76 
77   // LLVM does not support "sx", "s" nor "x" extensions.
78   return false;
79 }
80 
81 // Extensions may have a version number, and may be separated by
82 // an underscore '_' e.g.: rv32i2_m2.
83 // Version number is divided into major and minor version numbers,
84 // separated by a 'p'. If the minor version is 0 then 'p0' can be
85 // omitted from the version string. E.g., rv32i2p0, rv32i2, rv32i2p1.
86 static bool getExtensionVersion(const Driver &D, const ArgList &Args,
87                                 StringRef MArch, StringRef Ext, StringRef In,
88                                 std::string &Major, std::string &Minor) {
89   Major = std::string(In.take_while(isDigit));
90   In = In.substr(Major.size());
91 
92   if (Major.size() && In.consume_front("p")) {
93     Minor = std::string(In.take_while(isDigit));
94     In = In.substr(Major.size() + 1);
95 
96     // Expected 'p' to be followed by minor version number.
97     if (Minor.empty()) {
98       std::string Error =
99         "minor version number missing after 'p' for extension";
100       D.Diag(diag::err_drv_invalid_riscv_ext_arch_name)
101         << MArch << Error << Ext;
102       return false;
103     }
104   }
105 
106   // Expected multi-character extension with version number to have no
107   // subsequent characters (i.e. must either end string or be followed by
108   // an underscore).
109   if (Ext.size() > 1 && In.size()) {
110     std::string Error =
111         "multi-character extensions must be separated by underscores";
112     D.Diag(diag::err_drv_invalid_riscv_ext_arch_name) << MArch << Error << In;
113     return false;
114   }
115 
116   // If experimental extension, require use of current version number number
117   if (auto ExperimentalExtension = isExperimentalExtension(Ext)) {
118     if (!Args.hasArg(options::OPT_menable_experimental_extensions)) {
119       std::string Error =
120           "requires '-menable-experimental-extensions' for experimental extension";
121       D.Diag(diag::err_drv_invalid_riscv_ext_arch_name)
122           << MArch << Error << Ext;
123       return false;
124     } else if (Major.empty() && Minor.empty()) {
125       std::string Error =
126           "experimental extension requires explicit version number";
127       D.Diag(diag::err_drv_invalid_riscv_ext_arch_name)
128           << MArch << Error << Ext;
129       return false;
130     }
131     auto SupportedVers = *ExperimentalExtension;
132     if (Major != SupportedVers.Major || Minor != SupportedVers.Minor) {
133       std::string Error =
134           "unsupported version number " + Major;
135       if (!Minor.empty())
136         Error += "." + Minor;
137       Error += " for experimental extension (this compiler supports "
138             + SupportedVers.Major.str() + "."
139             + SupportedVers.Minor.str() + ")";
140 
141       D.Diag(diag::err_drv_invalid_riscv_ext_arch_name)
142           << MArch << Error << Ext;
143       return false;
144     }
145     return true;
146   }
147 
148   // Allow extensions to declare no version number
149   if (Major.empty() && Minor.empty())
150     return true;
151 
152   // TODO: Handle supported extensions with version number.
153   std::string Error = "unsupported version number " + Major;
154   if (!Minor.empty())
155     Error += "." + Minor;
156   Error += " for extension";
157   D.Diag(diag::err_drv_invalid_riscv_ext_arch_name) << MArch << Error << Ext;
158 
159   return false;
160 }
161 
162 // Handle other types of extensions other than the standard
163 // general purpose and standard user-level extensions.
164 // Parse the ISA string containing non-standard user-level
165 // extensions, standard supervisor-level extensions and
166 // non-standard supervisor-level extensions.
167 // These extensions start with 'z', 'x', 's', 'sx' prefixes, follow a
168 // canonical order, might have a version number (major, minor)
169 // and are separated by a single underscore '_'.
170 // Set the hardware features for the extensions that are supported.
171 static void getExtensionFeatures(const Driver &D,
172                                  const ArgList &Args,
173                                  std::vector<StringRef> &Features,
174                                  StringRef &MArch, StringRef &Exts) {
175   if (Exts.empty())
176     return;
177 
178   // Multi-letter extensions are seperated by a single underscore
179   // as described in RISC-V User-Level ISA V2.2.
180   SmallVector<StringRef, 8> Split;
181   Exts.split(Split, StringRef("_"));
182 
183   SmallVector<StringRef, 4> Prefix{"z", "x", "s", "sx"};
184   auto I = Prefix.begin();
185   auto E = Prefix.end();
186 
187   SmallVector<StringRef, 8> AllExts;
188 
189   for (StringRef Ext : Split) {
190     if (Ext.empty()) {
191       D.Diag(diag::err_drv_invalid_riscv_arch_name) << MArch
192         << "extension name missing after separator '_'";
193       return;
194     }
195 
196     StringRef Type = getExtensionType(Ext);
197     StringRef Desc = getExtensionTypeDesc(Ext);
198     auto Pos = Ext.find_if(isDigit);
199     StringRef Name(Ext.substr(0, Pos));
200     StringRef Vers(Ext.substr(Pos));
201 
202     if (Type.empty()) {
203       D.Diag(diag::err_drv_invalid_riscv_ext_arch_name)
204         << MArch << "invalid extension prefix" << Ext;
205       return;
206     }
207 
208     // Check ISA extensions are specified in the canonical order.
209     while (I != E && *I != Type)
210       ++I;
211 
212     if (I == E) {
213       std::string Error = std::string(Desc);
214       Error += " not given in canonical order";
215       D.Diag(diag::err_drv_invalid_riscv_ext_arch_name)
216         << MArch <<  Error << Ext;
217       return;
218     }
219 
220     // The order is OK, do not advance I to the next prefix
221     // to allow repeated extension type, e.g.: rv32ixabc_xdef.
222 
223     if (Name.size() == Type.size()) {
224       std::string Error = std::string(Desc);
225       Error += " name missing after";
226       D.Diag(diag::err_drv_invalid_riscv_ext_arch_name)
227         << MArch << Error << Type;
228       return;
229     }
230 
231     std::string Major, Minor;
232     if (!getExtensionVersion(D, Args, MArch, Name, Vers, Major, Minor))
233       return;
234 
235     // Check if duplicated extension.
236     if (llvm::is_contained(AllExts, Name)) {
237       std::string Error = "duplicated ";
238       Error += Desc;
239       D.Diag(diag::err_drv_invalid_riscv_ext_arch_name)
240         << MArch << Error << Name;
241       return;
242     }
243 
244     // Extension format is correct, keep parsing the extensions.
245     // TODO: Save Type, Name, Major, Minor to avoid parsing them later.
246     AllExts.push_back(Name);
247   }
248 
249   // Set target features.
250   // TODO: Hardware features to be handled in Support/TargetParser.cpp.
251   // TODO: Use version number when setting target features.
252   for (auto Ext : AllExts) {
253     if (!isSupportedExtension(Ext)) {
254       StringRef Desc = getExtensionTypeDesc(getExtensionType(Ext));
255       std::string Error = "unsupported ";
256       Error += Desc;
257       D.Diag(diag::err_drv_invalid_riscv_ext_arch_name)
258         << MArch << Error << Ext;
259       return;
260     }
261     if (Ext == "zvlsseg") {
262       Features.push_back("+experimental-v");
263       Features.push_back("+experimental-zvlsseg");
264     } else if (Ext == "zvamo") {
265       Features.push_back("+experimental-v");
266       Features.push_back("+experimental-zvlsseg");
267       Features.push_back("+experimental-zvamo");
268     } else if (isExperimentalExtension(Ext))
269       Features.push_back(Args.MakeArgString("+experimental-" + Ext));
270     else
271       Features.push_back(Args.MakeArgString("+" + Ext));
272   }
273 }
274 
275 // Returns false if an error is diagnosed.
276 static bool getArchFeatures(const Driver &D, StringRef MArch,
277                             std::vector<StringRef> &Features,
278                             const ArgList &Args) {
279   // RISC-V ISA strings must be lowercase.
280   if (llvm::any_of(MArch, [](char c) { return isupper(c); })) {
281     D.Diag(diag::err_drv_invalid_riscv_arch_name)
282         << MArch << "string must be lowercase";
283     return false;
284   }
285 
286   // ISA string must begin with rv32 or rv64.
287   if (!(MArch.startswith("rv32") || MArch.startswith("rv64")) ||
288       (MArch.size() < 5)) {
289     D.Diag(diag::err_drv_invalid_riscv_arch_name)
290         << MArch << "string must begin with rv32{i,e,g} or rv64{i,g}";
291     return false;
292   }
293 
294   bool HasRV64 = MArch.startswith("rv64");
295 
296   // The canonical order specified in ISA manual.
297   // Ref: Table 22.1 in RISC-V User-Level ISA V2.2
298   StringRef StdExts = "mafdqlcbjtpvn";
299   bool HasF = false, HasD = false;
300   char Baseline = MArch[4];
301 
302   // First letter should be 'e', 'i' or 'g'.
303   switch (Baseline) {
304   default:
305     D.Diag(diag::err_drv_invalid_riscv_arch_name)
306         << MArch << "first letter should be 'e', 'i' or 'g'";
307     return false;
308   case 'e': {
309     StringRef Error;
310     // Currently LLVM does not support 'e'.
311     // Extension 'e' is not allowed in rv64.
312     if (HasRV64)
313       Error = "standard user-level extension 'e' requires 'rv32'";
314     else
315       Error = "unsupported standard user-level extension 'e'";
316     D.Diag(diag::err_drv_invalid_riscv_arch_name) << MArch << Error;
317     return false;
318   }
319   case 'i':
320     break;
321   case 'g':
322     // g = imafd
323     StdExts = StdExts.drop_front(4);
324     Features.push_back("+m");
325     Features.push_back("+a");
326     Features.push_back("+f");
327     Features.push_back("+d");
328     HasF = true;
329     HasD = true;
330     break;
331   }
332 
333   // Skip rvxxx
334   StringRef Exts = MArch.substr(5);
335 
336   // Remove multi-letter standard extensions, non-standard extensions and
337   // supervisor-level extensions. They have 'z', 'x', 's', 'sx' prefixes.
338   // Parse them at the end.
339   // Find the very first occurrence of 's', 'x' or 'z'.
340   StringRef OtherExts;
341   size_t Pos = Exts.find_first_of("zsx");
342   if (Pos != StringRef::npos) {
343     OtherExts = Exts.substr(Pos);
344     Exts = Exts.substr(0, Pos);
345   }
346 
347   std::string Major, Minor;
348   if (!getExtensionVersion(D, Args, MArch, std::string(1, Baseline), Exts,
349                            Major, Minor))
350     return false;
351 
352   // Consume the base ISA version number and any '_' between rvxxx and the
353   // first extension
354   Exts = Exts.drop_front(Major.size());
355   if (!Minor.empty())
356     Exts = Exts.drop_front(Minor.size() + 1 /*'p'*/);
357   Exts.consume_front("_");
358 
359   // TODO: Use version number when setting target features
360 
361   auto StdExtsItr = StdExts.begin();
362   auto StdExtsEnd = StdExts.end();
363 
364   for (auto I = Exts.begin(), E = Exts.end(); I != E; ) {
365     char c = *I;
366 
367     // Check ISA extensions are specified in the canonical order.
368     while (StdExtsItr != StdExtsEnd && *StdExtsItr != c)
369       ++StdExtsItr;
370 
371     if (StdExtsItr == StdExtsEnd) {
372       // Either c contains a valid extension but it was not given in
373       // canonical order or it is an invalid extension.
374       StringRef Error;
375       if (StdExts.contains(c))
376         Error = "standard user-level extension not given in canonical order";
377       else
378         Error = "invalid standard user-level extension";
379       D.Diag(diag::err_drv_invalid_riscv_ext_arch_name)
380           << MArch << Error << std::string(1, c);
381       return false;
382     }
383 
384     // Move to next char to prevent repeated letter.
385     ++StdExtsItr;
386 
387     std::string Next, Major, Minor;
388     if (std::next(I) != E)
389       Next = std::string(std::next(I), E);
390     if (!getExtensionVersion(D, Args, MArch, std::string(1, c), Next, Major,
391                              Minor))
392       return false;
393 
394     // The order is OK, then push it into features.
395     // TODO: Use version number when setting target features
396     switch (c) {
397     default:
398       // Currently LLVM supports only "mafdc".
399       D.Diag(diag::err_drv_invalid_riscv_ext_arch_name)
400           << MArch << "unsupported standard user-level extension"
401           << std::string(1, c);
402       return false;
403     case 'm':
404       Features.push_back("+m");
405       break;
406     case 'a':
407       Features.push_back("+a");
408       break;
409     case 'f':
410       Features.push_back("+f");
411       HasF = true;
412       break;
413     case 'd':
414       Features.push_back("+d");
415       HasD = true;
416       break;
417     case 'c':
418       Features.push_back("+c");
419       break;
420     case 'b':
421       Features.push_back("+experimental-b");
422       Features.push_back("+experimental-zba");
423       Features.push_back("+experimental-zbb");
424       Features.push_back("+experimental-zbc");
425       Features.push_back("+experimental-zbe");
426       Features.push_back("+experimental-zbf");
427       Features.push_back("+experimental-zbm");
428       Features.push_back("+experimental-zbp");
429       Features.push_back("+experimental-zbr");
430       Features.push_back("+experimental-zbs");
431       Features.push_back("+experimental-zbt");
432       break;
433     case 'v':
434       Features.push_back("+experimental-v");
435       Features.push_back("+experimental-zvlsseg");
436       break;
437     }
438 
439     // Consume full extension name and version, including any optional '_'
440     // between this extension and the next
441     ++I;
442     I += Major.size();
443     if (Minor.size())
444       I += Minor.size() + 1 /*'p'*/;
445     if (*I == '_')
446       ++I;
447   }
448 
449   // Dependency check.
450   // It's illegal to specify the 'd' (double-precision floating point)
451   // extension without also specifying the 'f' (single precision
452   // floating-point) extension.
453   if (HasD && !HasF) {
454     D.Diag(diag::err_drv_invalid_riscv_arch_name)
455         << MArch << "d requires f extension to also be specified";
456     return false;
457   }
458 
459   // Additional dependency checks.
460   // TODO: The 'q' extension requires rv64.
461   // TODO: It is illegal to specify 'e' extensions with 'f' and 'd'.
462 
463   // Handle all other types of extensions.
464   getExtensionFeatures(D, Args, Features, MArch, OtherExts);
465 
466   return true;
467 }
468 
469 // Get features except standard extension feature
470 static void getRISCFeaturesFromMcpu(const Driver &D, const llvm::Triple &Triple,
471                                     const llvm::opt::ArgList &Args,
472                                     const llvm::opt::Arg *A, StringRef Mcpu,
473                                     std::vector<StringRef> &Features) {
474   bool Is64Bit = (Triple.getArch() == llvm::Triple::riscv64);
475   llvm::RISCV::CPUKind CPUKind = llvm::RISCV::parseCPUKind(Mcpu);
476   if (!llvm::RISCV::checkCPUKind(CPUKind, Is64Bit) ||
477       !llvm::RISCV::getCPUFeaturesExceptStdExt(CPUKind, Features)) {
478     D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
479   }
480 }
481 
482 void riscv::getRISCVTargetFeatures(const Driver &D, const llvm::Triple &Triple,
483                                    const ArgList &Args,
484                                    std::vector<StringRef> &Features) {
485   StringRef MArch = getRISCVArch(Args, Triple);
486 
487   if (!getArchFeatures(D, MArch, Features, Args))
488     return;
489 
490   // If users give march and mcpu, get std extension feature from MArch
491   // and other features (ex. mirco architecture feature) from mcpu
492   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
493     getRISCFeaturesFromMcpu(D, Triple, Args, A, A->getValue(), Features);
494 
495   // Handle features corresponding to "-ffixed-X" options
496   if (Args.hasArg(options::OPT_ffixed_x1))
497     Features.push_back("+reserve-x1");
498   if (Args.hasArg(options::OPT_ffixed_x2))
499     Features.push_back("+reserve-x2");
500   if (Args.hasArg(options::OPT_ffixed_x3))
501     Features.push_back("+reserve-x3");
502   if (Args.hasArg(options::OPT_ffixed_x4))
503     Features.push_back("+reserve-x4");
504   if (Args.hasArg(options::OPT_ffixed_x5))
505     Features.push_back("+reserve-x5");
506   if (Args.hasArg(options::OPT_ffixed_x6))
507     Features.push_back("+reserve-x6");
508   if (Args.hasArg(options::OPT_ffixed_x7))
509     Features.push_back("+reserve-x7");
510   if (Args.hasArg(options::OPT_ffixed_x8))
511     Features.push_back("+reserve-x8");
512   if (Args.hasArg(options::OPT_ffixed_x9))
513     Features.push_back("+reserve-x9");
514   if (Args.hasArg(options::OPT_ffixed_x10))
515     Features.push_back("+reserve-x10");
516   if (Args.hasArg(options::OPT_ffixed_x11))
517     Features.push_back("+reserve-x11");
518   if (Args.hasArg(options::OPT_ffixed_x12))
519     Features.push_back("+reserve-x12");
520   if (Args.hasArg(options::OPT_ffixed_x13))
521     Features.push_back("+reserve-x13");
522   if (Args.hasArg(options::OPT_ffixed_x14))
523     Features.push_back("+reserve-x14");
524   if (Args.hasArg(options::OPT_ffixed_x15))
525     Features.push_back("+reserve-x15");
526   if (Args.hasArg(options::OPT_ffixed_x16))
527     Features.push_back("+reserve-x16");
528   if (Args.hasArg(options::OPT_ffixed_x17))
529     Features.push_back("+reserve-x17");
530   if (Args.hasArg(options::OPT_ffixed_x18))
531     Features.push_back("+reserve-x18");
532   if (Args.hasArg(options::OPT_ffixed_x19))
533     Features.push_back("+reserve-x19");
534   if (Args.hasArg(options::OPT_ffixed_x20))
535     Features.push_back("+reserve-x20");
536   if (Args.hasArg(options::OPT_ffixed_x21))
537     Features.push_back("+reserve-x21");
538   if (Args.hasArg(options::OPT_ffixed_x22))
539     Features.push_back("+reserve-x22");
540   if (Args.hasArg(options::OPT_ffixed_x23))
541     Features.push_back("+reserve-x23");
542   if (Args.hasArg(options::OPT_ffixed_x24))
543     Features.push_back("+reserve-x24");
544   if (Args.hasArg(options::OPT_ffixed_x25))
545     Features.push_back("+reserve-x25");
546   if (Args.hasArg(options::OPT_ffixed_x26))
547     Features.push_back("+reserve-x26");
548   if (Args.hasArg(options::OPT_ffixed_x27))
549     Features.push_back("+reserve-x27");
550   if (Args.hasArg(options::OPT_ffixed_x28))
551     Features.push_back("+reserve-x28");
552   if (Args.hasArg(options::OPT_ffixed_x29))
553     Features.push_back("+reserve-x29");
554   if (Args.hasArg(options::OPT_ffixed_x30))
555     Features.push_back("+reserve-x30");
556   if (Args.hasArg(options::OPT_ffixed_x31))
557     Features.push_back("+reserve-x31");
558 
559 #ifdef __OpenBSD__
560   // -mno-relax is default, unless -mrelax is specified.
561   if (Args.hasFlag(options::OPT_mrelax, options::OPT_mno_relax, false))
562     Features.push_back("+relax");
563   else
564     Features.push_back("-relax");
565 #else
566   // -mrelax is default, unless -mno-relax is specified.
567   if (Args.hasFlag(options::OPT_mrelax, options::OPT_mno_relax, true))
568     Features.push_back("+relax");
569   else
570     Features.push_back("-relax");
571 #endif
572 
573   // GCC Compatibility: -mno-save-restore is default, unless -msave-restore is
574   // specified.
575   if (Args.hasFlag(options::OPT_msave_restore, options::OPT_mno_save_restore, false))
576     Features.push_back("+save-restore");
577   else
578     Features.push_back("-save-restore");
579 
580   // Now add any that the user explicitly requested on the command line,
581   // which may override the defaults.
582   handleTargetFeaturesGroup(Args, Features, options::OPT_m_riscv_Features_Group);
583 }
584 
585 StringRef riscv::getRISCVABI(const ArgList &Args, const llvm::Triple &Triple) {
586   assert((Triple.getArch() == llvm::Triple::riscv32 ||
587           Triple.getArch() == llvm::Triple::riscv64) &&
588          "Unexpected triple");
589 
590   // GCC's logic around choosing a default `-mabi=` is complex. If GCC is not
591   // configured using `--with-abi=`, then the logic for the default choice is
592   // defined in config.gcc. This function is based on the logic in GCC 9.2.0.
593   //
594   // The logic used in GCC 9.2.0 is the following, in order:
595   // 1. Explicit choices using `--with-abi=`
596   // 2. A default based on `--with-arch=`, if provided
597   // 3. A default based on the target triple's arch
598   //
599   // The logic in config.gcc is a little circular but it is not inconsistent.
600   //
601   // Clang does not have `--with-arch=` or `--with-abi=`, so we use `-march=`
602   // and `-mabi=` respectively instead.
603   //
604   // In order to make chosing logic more clear, Clang uses the following logic,
605   // in order:
606   // 1. Explicit choices using `-mabi=`
607   // 2. A default based on the architecture as determined by getRISCVArch
608   // 3. Choose a default based on the triple
609 
610   // 1. If `-mabi=` is specified, use it.
611   if (const Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
612     return A->getValue();
613 
614   // 2. Choose a default based on the target architecture.
615   //
616   // rv32g | rv32*d -> ilp32d
617   // rv32e -> ilp32e
618   // rv32* -> ilp32
619   // rv64g | rv64*d -> lp64d
620   // rv64* -> lp64
621   StringRef MArch = getRISCVArch(Args, Triple);
622 
623   if (MArch.startswith_insensitive("rv32")) {
624     // FIXME: parse `March` to find `D` extension properly
625     if (MArch.substr(4).contains_insensitive("d") ||
626         MArch.startswith_insensitive("rv32g"))
627       return "ilp32d";
628     else if (MArch.startswith_insensitive("rv32e"))
629       return "ilp32e";
630     else
631       return "ilp32";
632   } else if (MArch.startswith_insensitive("rv64")) {
633     // FIXME: parse `March` to find `D` extension properly
634     if (MArch.substr(4).contains_insensitive("d") ||
635         MArch.startswith_insensitive("rv64g"))
636       return "lp64d";
637     else
638       return "lp64";
639   }
640 
641   // 3. Choose a default based on the triple
642   //
643   // We deviate from GCC's defaults here:
644   // - On `riscv{XLEN}-unknown-elf` we use the integer calling convention only.
645   // - On all other OSs we use the double floating point calling convention.
646   if (Triple.getArch() == llvm::Triple::riscv32) {
647     if (Triple.getOS() == llvm::Triple::UnknownOS)
648       return "ilp32";
649     else
650       return "ilp32d";
651   } else {
652     if (Triple.getOS() == llvm::Triple::UnknownOS)
653       return "lp64";
654     else
655       return "lp64d";
656   }
657 }
658 
659 StringRef riscv::getRISCVArch(const llvm::opt::ArgList &Args,
660                               const llvm::Triple &Triple) {
661   assert((Triple.getArch() == llvm::Triple::riscv32 ||
662           Triple.getArch() == llvm::Triple::riscv64) &&
663          "Unexpected triple");
664 
665   // GCC's logic around choosing a default `-march=` is complex. If GCC is not
666   // configured using `--with-arch=`, then the logic for the default choice is
667   // defined in config.gcc. This function is based on the logic in GCC 9.2.0. We
668   // deviate from GCC's default on additional `-mcpu` option (GCC does not
669   // support `-mcpu`) and baremetal targets (UnknownOS) where neither `-march`
670   // nor `-mabi` is specified.
671   //
672   // The logic used in GCC 9.2.0 is the following, in order:
673   // 1. Explicit choices using `--with-arch=`
674   // 2. A default based on `--with-abi=`, if provided
675   // 3. A default based on the target triple's arch
676   //
677   // The logic in config.gcc is a little circular but it is not inconsistent.
678   //
679   // Clang does not have `--with-arch=` or `--with-abi=`, so we use `-march=`
680   // and `-mabi=` respectively instead.
681   //
682   // Clang uses the following logic, in order:
683   // 1. Explicit choices using `-march=`
684   // 2. Based on `-mcpu` if the target CPU has a default ISA string
685   // 3. A default based on `-mabi`, if provided
686   // 4. A default based on the target triple's arch
687   //
688   // Clang does not yet support MULTILIB_REUSE, so we use `rv{XLEN}imafdc`
689   // instead of `rv{XLEN}gc` though they are (currently) equivalent.
690 
691   // 1. If `-march=` is specified, use it.
692   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
693     return A->getValue();
694 
695   // 2. Get march (isa string) based on `-mcpu=`
696   if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
697     StringRef MArch = llvm::RISCV::getMArchFromMcpu(A->getValue());
698     // Bypass if target cpu's default march is empty.
699     if (MArch != "")
700       return MArch;
701   }
702 
703   // 3. Choose a default based on `-mabi=`
704   //
705   // ilp32e -> rv32e
706   // ilp32 | ilp32f | ilp32d -> rv32imafdc
707   // lp64 | lp64f | lp64d -> rv64imafdc
708   if (const Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
709     StringRef MABI = A->getValue();
710 
711     if (MABI.equals_insensitive("ilp32e"))
712       return "rv32e";
713     else if (MABI.startswith_insensitive("ilp32"))
714       return "rv32imafdc";
715     else if (MABI.startswith_insensitive("lp64"))
716       return "rv64imafdc";
717   }
718 
719   // 4. Choose a default based on the triple
720   //
721   // We deviate from GCC's defaults here:
722   // - On `riscv{XLEN}-unknown-elf` we default to `rv{XLEN}imac`
723   // - On all other OSs we use `rv{XLEN}imafdc` (equivalent to `rv{XLEN}gc`)
724   if (Triple.getArch() == llvm::Triple::riscv32) {
725     if (Triple.getOS() == llvm::Triple::UnknownOS)
726       return "rv32imac";
727     else
728       return "rv32imafdc";
729   } else {
730     if (Triple.getOS() == llvm::Triple::UnknownOS)
731       return "rv64imac";
732     else
733       return "rv64imafdc";
734   }
735 }
736