[docs] Fix build-docs.sh
[llvm-project.git] / clang / lib / Driver / ToolChains / Gnu.cpp
blobe153f86334aaed812434e0c8653da46da347ce0a
1 //===--- Gnu.cpp - Gnu Tool and ToolChain Implementations -------*- 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 //===----------------------------------------------------------------------===//
9 #include "Gnu.h"
10 #include "Arch/ARM.h"
11 #include "Arch/CSKY.h"
12 #include "Arch/Mips.h"
13 #include "Arch/PPC.h"
14 #include "Arch/RISCV.h"
15 #include "Arch/Sparc.h"
16 #include "Arch/SystemZ.h"
17 #include "CommonArgs.h"
18 #include "Linux.h"
19 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
20 #include "clang/Driver/Compilation.h"
21 #include "clang/Driver/Driver.h"
22 #include "clang/Driver/DriverDiagnostic.h"
23 #include "clang/Driver/Options.h"
24 #include "clang/Driver/Tool.h"
25 #include "clang/Driver/ToolChain.h"
26 #include "llvm/Option/ArgList.h"
27 #include "llvm/Support/CodeGen.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/TargetParser.h"
30 #include "llvm/Support/VirtualFileSystem.h"
31 #include <system_error>
33 using namespace clang::driver;
34 using namespace clang::driver::toolchains;
35 using namespace clang;
36 using namespace llvm::opt;
38 using tools::addMultilibFlag;
39 using tools::addPathIfExists;
41 static bool forwardToGCC(const Option &O) {
42 // LinkerInput options have been forwarded. Don't duplicate.
43 if (O.hasFlag(options::LinkerInput))
44 return false;
45 return O.matches(options::OPT_Link_Group) || O.hasFlag(options::LinkOption);
48 // Switch CPU names not recognized by GNU assembler to a close CPU that it does
49 // recognize, instead of a lower march from being picked in the absence of a cpu
50 // flag.
51 static void normalizeCPUNamesForAssembler(const ArgList &Args,
52 ArgStringList &CmdArgs) {
53 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
54 StringRef CPUArg(A->getValue());
55 if (CPUArg.equals_insensitive("krait"))
56 CmdArgs.push_back("-mcpu=cortex-a15");
57 else if (CPUArg.equals_insensitive("kryo"))
58 CmdArgs.push_back("-mcpu=cortex-a57");
59 else
60 Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
64 void tools::gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
65 const InputInfo &Output,
66 const InputInfoList &Inputs,
67 const ArgList &Args,
68 const char *LinkingOutput) const {
69 const Driver &D = getToolChain().getDriver();
70 ArgStringList CmdArgs;
72 for (const auto &A : Args) {
73 if (forwardToGCC(A->getOption())) {
74 // It is unfortunate that we have to claim here, as this means
75 // we will basically never report anything interesting for
76 // platforms using a generic gcc, even if we are just using gcc
77 // to get to the assembler.
78 A->claim();
80 A->render(Args, CmdArgs);
84 RenderExtraToolArgs(JA, CmdArgs);
86 // If using a driver driver, force the arch.
87 if (getToolChain().getTriple().isOSDarwin()) {
88 CmdArgs.push_back("-arch");
89 CmdArgs.push_back(
90 Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
93 // Try to force gcc to match the tool chain we want, if we recognize
94 // the arch.
96 // FIXME: The triple class should directly provide the information we want
97 // here.
98 switch (getToolChain().getArch()) {
99 default:
100 break;
101 case llvm::Triple::x86:
102 case llvm::Triple::ppc:
103 case llvm::Triple::ppcle:
104 CmdArgs.push_back("-m32");
105 break;
106 case llvm::Triple::x86_64:
107 case llvm::Triple::ppc64:
108 case llvm::Triple::ppc64le:
109 CmdArgs.push_back("-m64");
110 break;
111 case llvm::Triple::sparcel:
112 CmdArgs.push_back("-EL");
113 break;
116 if (Output.isFilename()) {
117 CmdArgs.push_back("-o");
118 CmdArgs.push_back(Output.getFilename());
119 } else {
120 assert(Output.isNothing() && "Unexpected output");
121 CmdArgs.push_back("-fsyntax-only");
124 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
126 // Only pass -x if gcc will understand it; otherwise hope gcc
127 // understands the suffix correctly. The main use case this would go
128 // wrong in is for linker inputs if they happened to have an odd
129 // suffix; really the only way to get this to happen is a command
130 // like '-x foobar a.c' which will treat a.c like a linker input.
132 // FIXME: For the linker case specifically, can we safely convert
133 // inputs into '-Wl,' options?
134 for (const auto &II : Inputs) {
135 // Don't try to pass LLVM or AST inputs to a generic gcc.
136 if (types::isLLVMIR(II.getType()))
137 D.Diag(clang::diag::err_drv_no_linker_llvm_support)
138 << getToolChain().getTripleString();
139 else if (II.getType() == types::TY_AST)
140 D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
141 else if (II.getType() == types::TY_ModuleFile)
142 D.Diag(diag::err_drv_no_module_support)
143 << getToolChain().getTripleString();
145 if (types::canTypeBeUserSpecified(II.getType())) {
146 CmdArgs.push_back("-x");
147 CmdArgs.push_back(types::getTypeName(II.getType()));
150 if (II.isFilename())
151 CmdArgs.push_back(II.getFilename());
152 else {
153 const Arg &A = II.getInputArg();
155 // Reverse translate some rewritten options.
156 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
157 CmdArgs.push_back("-lstdc++");
158 continue;
161 // Don't render as input, we need gcc to do the translations.
162 A.render(Args, CmdArgs);
166 const std::string &customGCCName = D.getCCCGenericGCCName();
167 const char *GCCName;
168 if (!customGCCName.empty())
169 GCCName = customGCCName.c_str();
170 else if (D.CCCIsCXX()) {
171 GCCName = "g++";
172 } else
173 GCCName = "gcc";
175 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
176 C.addCommand(std::make_unique<Command>(JA, *this,
177 ResponseFileSupport::AtFileCurCP(),
178 Exec, CmdArgs, Inputs, Output));
181 void tools::gcc::Preprocessor::RenderExtraToolArgs(
182 const JobAction &JA, ArgStringList &CmdArgs) const {
183 CmdArgs.push_back("-E");
186 void tools::gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
187 ArgStringList &CmdArgs) const {
188 const Driver &D = getToolChain().getDriver();
190 switch (JA.getType()) {
191 // If -flto, etc. are present then make sure not to force assembly output.
192 case types::TY_LLVM_IR:
193 case types::TY_LTO_IR:
194 case types::TY_LLVM_BC:
195 case types::TY_LTO_BC:
196 CmdArgs.push_back("-c");
197 break;
198 // We assume we've got an "integrated" assembler in that gcc will produce an
199 // object file itself.
200 case types::TY_Object:
201 CmdArgs.push_back("-c");
202 break;
203 case types::TY_PP_Asm:
204 CmdArgs.push_back("-S");
205 break;
206 case types::TY_Nothing:
207 CmdArgs.push_back("-fsyntax-only");
208 break;
209 default:
210 D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
214 void tools::gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
215 ArgStringList &CmdArgs) const {
216 // The types are (hopefully) good enough.
219 // On Arm the endianness of the output file is determined by the target and
220 // can be overridden by the pseudo-target flags '-mlittle-endian'/'-EL' and
221 // '-mbig-endian'/'-EB'. Unlike other targets the flag does not result in a
222 // normalized triple so we must handle the flag here.
223 static bool isArmBigEndian(const llvm::Triple &Triple,
224 const ArgList &Args) {
225 bool IsBigEndian = false;
226 switch (Triple.getArch()) {
227 case llvm::Triple::armeb:
228 case llvm::Triple::thumbeb:
229 IsBigEndian = true;
230 [[fallthrough]];
231 case llvm::Triple::arm:
232 case llvm::Triple::thumb:
233 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
234 options::OPT_mbig_endian))
235 IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
236 break;
237 default:
238 break;
240 return IsBigEndian;
243 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
244 switch (T.getArch()) {
245 case llvm::Triple::x86:
246 if (T.isOSIAMCU())
247 return "elf_iamcu";
248 return "elf_i386";
249 case llvm::Triple::aarch64:
250 return "aarch64linux";
251 case llvm::Triple::aarch64_be:
252 return "aarch64linuxb";
253 case llvm::Triple::arm:
254 case llvm::Triple::thumb:
255 case llvm::Triple::armeb:
256 case llvm::Triple::thumbeb:
257 return isArmBigEndian(T, Args) ? "armelfb_linux_eabi" : "armelf_linux_eabi";
258 case llvm::Triple::m68k:
259 return "m68kelf";
260 case llvm::Triple::ppc:
261 if (T.isOSLinux())
262 return "elf32ppclinux";
263 return "elf32ppc";
264 case llvm::Triple::ppcle:
265 if (T.isOSLinux())
266 return "elf32lppclinux";
267 return "elf32lppc";
268 case llvm::Triple::ppc64:
269 return "elf64ppc";
270 case llvm::Triple::ppc64le:
271 return "elf64lppc";
272 case llvm::Triple::riscv32:
273 return "elf32lriscv";
274 case llvm::Triple::riscv64:
275 return "elf64lriscv";
276 case llvm::Triple::sparc:
277 case llvm::Triple::sparcel:
278 return "elf32_sparc";
279 case llvm::Triple::sparcv9:
280 return "elf64_sparc";
281 case llvm::Triple::loongarch32:
282 return "elf32loongarch";
283 case llvm::Triple::loongarch64:
284 return "elf64loongarch";
285 case llvm::Triple::mips:
286 return "elf32btsmip";
287 case llvm::Triple::mipsel:
288 return "elf32ltsmip";
289 case llvm::Triple::mips64:
290 if (tools::mips::hasMipsAbiArg(Args, "n32") ||
291 T.getEnvironment() == llvm::Triple::GNUABIN32)
292 return "elf32btsmipn32";
293 return "elf64btsmip";
294 case llvm::Triple::mips64el:
295 if (tools::mips::hasMipsAbiArg(Args, "n32") ||
296 T.getEnvironment() == llvm::Triple::GNUABIN32)
297 return "elf32ltsmipn32";
298 return "elf64ltsmip";
299 case llvm::Triple::systemz:
300 return "elf64_s390";
301 case llvm::Triple::x86_64:
302 if (T.isX32())
303 return "elf32_x86_64";
304 return "elf_x86_64";
305 case llvm::Triple::ve:
306 return "elf64ve";
307 case llvm::Triple::csky:
308 return "cskyelf_linux";
309 default:
310 return nullptr;
314 static bool getPIE(const ArgList &Args, const ToolChain &TC) {
315 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_static) ||
316 Args.hasArg(options::OPT_r) || Args.hasArg(options::OPT_static_pie))
317 return false;
319 Arg *A = Args.getLastArg(options::OPT_pie, options::OPT_no_pie,
320 options::OPT_nopie);
321 if (!A)
322 return TC.isPIEDefault(Args);
323 return A->getOption().matches(options::OPT_pie);
326 static bool getStaticPIE(const ArgList &Args, const ToolChain &TC) {
327 bool HasStaticPIE = Args.hasArg(options::OPT_static_pie);
328 // -no-pie is an alias for -nopie. So, handling -nopie takes care of
329 // -no-pie as well.
330 if (HasStaticPIE && Args.hasArg(options::OPT_nopie)) {
331 const Driver &D = TC.getDriver();
332 const llvm::opt::OptTable &Opts = D.getOpts();
333 const char *StaticPIEName = Opts.getOptionName(options::OPT_static_pie);
334 const char *NoPIEName = Opts.getOptionName(options::OPT_nopie);
335 D.Diag(diag::err_drv_cannot_mix_options) << StaticPIEName << NoPIEName;
337 return HasStaticPIE;
340 static bool getStatic(const ArgList &Args) {
341 return Args.hasArg(options::OPT_static) &&
342 !Args.hasArg(options::OPT_static_pie);
345 void tools::gnutools::StaticLibTool::ConstructJob(
346 Compilation &C, const JobAction &JA, const InputInfo &Output,
347 const InputInfoList &Inputs, const ArgList &Args,
348 const char *LinkingOutput) const {
349 const Driver &D = getToolChain().getDriver();
351 // Silence warning for "clang -g foo.o -o foo"
352 Args.ClaimAllArgs(options::OPT_g_Group);
353 // and "clang -emit-llvm foo.o -o foo"
354 Args.ClaimAllArgs(options::OPT_emit_llvm);
355 // and for "clang -w foo.o -o foo". Other warning options are already
356 // handled somewhere else.
357 Args.ClaimAllArgs(options::OPT_w);
358 // Silence warnings when linking C code with a C++ '-stdlib' argument.
359 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
361 // ar tool command "llvm-ar <options> <output_file> <input_files>".
362 ArgStringList CmdArgs;
363 // Create and insert file members with a deterministic index.
364 CmdArgs.push_back("rcsD");
365 CmdArgs.push_back(Output.getFilename());
367 for (const auto &II : Inputs) {
368 if (II.isFilename()) {
369 CmdArgs.push_back(II.getFilename());
373 // Delete old output archive file if it already exists before generating a new
374 // archive file.
375 auto OutputFileName = Output.getFilename();
376 if (Output.isFilename() && llvm::sys::fs::exists(OutputFileName)) {
377 if (std::error_code EC = llvm::sys::fs::remove(OutputFileName)) {
378 D.Diag(diag::err_drv_unable_to_remove_file) << EC.message();
379 return;
383 const char *Exec = Args.MakeArgString(getToolChain().GetStaticLibToolPath());
384 C.addCommand(std::make_unique<Command>(JA, *this,
385 ResponseFileSupport::AtFileCurCP(),
386 Exec, CmdArgs, Inputs, Output));
389 void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
390 const InputInfo &Output,
391 const InputInfoList &Inputs,
392 const ArgList &Args,
393 const char *LinkingOutput) const {
394 // FIXME: The Linker class constructor takes a ToolChain and not a
395 // Generic_ELF, so the static_cast might return a reference to a invalid
396 // instance (see PR45061). Ideally, the Linker constructor needs to take a
397 // Generic_ELF instead.
398 const toolchains::Generic_ELF &ToolChain =
399 static_cast<const toolchains::Generic_ELF &>(getToolChain());
400 const Driver &D = ToolChain.getDriver();
402 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
404 const llvm::Triple::ArchType Arch = ToolChain.getArch();
405 const bool isAndroid = ToolChain.getTriple().isAndroid();
406 const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
407 const bool IsVE = ToolChain.getTriple().isVE();
408 const bool IsPIE = getPIE(Args, ToolChain);
409 const bool IsStaticPIE = getStaticPIE(Args, ToolChain);
410 const bool IsStatic = getStatic(Args);
411 const bool HasCRTBeginEndFiles =
412 ToolChain.getTriple().hasEnvironment() ||
413 (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
415 ArgStringList CmdArgs;
417 // Silence warning for "clang -g foo.o -o foo"
418 Args.ClaimAllArgs(options::OPT_g_Group);
419 // and "clang -emit-llvm foo.o -o foo"
420 Args.ClaimAllArgs(options::OPT_emit_llvm);
421 // and for "clang -w foo.o -o foo". Other warning options are already
422 // handled somewhere else.
423 Args.ClaimAllArgs(options::OPT_w);
425 if (!D.SysRoot.empty())
426 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
428 if (IsPIE)
429 CmdArgs.push_back("-pie");
431 if (IsStaticPIE) {
432 CmdArgs.push_back("-static");
433 CmdArgs.push_back("-pie");
434 CmdArgs.push_back("--no-dynamic-linker");
435 CmdArgs.push_back("-z");
436 CmdArgs.push_back("text");
439 if (Args.hasArg(options::OPT_rdynamic))
440 CmdArgs.push_back("-export-dynamic");
442 if (Args.hasArg(options::OPT_s))
443 CmdArgs.push_back("-s");
445 if (Triple.isARM() || Triple.isThumb() || Triple.isAArch64()) {
446 bool IsBigEndian = isArmBigEndian(Triple, Args);
447 if (IsBigEndian)
448 arm::appendBE8LinkFlag(Args, CmdArgs, Triple);
449 IsBigEndian = IsBigEndian || Arch == llvm::Triple::aarch64_be;
450 CmdArgs.push_back(IsBigEndian ? "-EB" : "-EL");
453 // Most Android ARM64 targets should enable the linker fix for erratum
454 // 843419. Only non-Cortex-A53 devices are allowed to skip this flag.
455 if (Arch == llvm::Triple::aarch64 && isAndroid) {
456 std::string CPU = getCPUName(D, Args, Triple);
457 if (CPU.empty() || CPU == "generic" || CPU == "cortex-a53")
458 CmdArgs.push_back("--fix-cortex-a53-843419");
461 ToolChain.addExtraOpts(CmdArgs);
463 CmdArgs.push_back("--eh-frame-hdr");
465 if (const char *LDMOption = getLDMOption(ToolChain.getTriple(), Args)) {
466 CmdArgs.push_back("-m");
467 CmdArgs.push_back(LDMOption);
468 } else {
469 D.Diag(diag::err_target_unknown_triple) << Triple.str();
470 return;
472 if (Triple.isRISCV())
473 CmdArgs.push_back("-X");
475 if (Args.hasArg(options::OPT_shared))
476 CmdArgs.push_back("-shared");
478 if (IsStatic) {
479 CmdArgs.push_back("-static");
480 } else {
481 if (Args.hasArg(options::OPT_rdynamic))
482 CmdArgs.push_back("-export-dynamic");
484 if (!Args.hasArg(options::OPT_shared) && !IsStaticPIE &&
485 !Args.hasArg(options::OPT_r)) {
486 CmdArgs.push_back("-dynamic-linker");
487 CmdArgs.push_back(Args.MakeArgString(Twine(D.DyldPrefix) +
488 ToolChain.getDynamicLinker(Args)));
492 CmdArgs.push_back("-o");
493 CmdArgs.push_back(Output.getFilename());
495 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
496 options::OPT_r)) {
497 if (!isAndroid && !IsIAMCU) {
498 const char *crt1 = nullptr;
499 if (!Args.hasArg(options::OPT_shared)) {
500 if (Args.hasArg(options::OPT_pg))
501 crt1 = "gcrt1.o";
502 else if (IsPIE)
503 crt1 = "Scrt1.o";
504 else if (IsStaticPIE)
505 crt1 = "rcrt1.o";
506 else
507 crt1 = "crt1.o";
509 if (crt1)
510 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
512 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
515 if (IsVE) {
516 CmdArgs.push_back("-z");
517 CmdArgs.push_back("max-page-size=0x4000000");
520 if (IsIAMCU)
521 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
522 else if (HasCRTBeginEndFiles) {
523 std::string P;
524 if (ToolChain.GetRuntimeLibType(Args) == ToolChain::RLT_CompilerRT &&
525 !isAndroid) {
526 std::string crtbegin = ToolChain.getCompilerRT(Args, "crtbegin",
527 ToolChain::FT_Object);
528 if (ToolChain.getVFS().exists(crtbegin))
529 P = crtbegin;
531 if (P.empty()) {
532 const char *crtbegin;
533 if (Args.hasArg(options::OPT_shared))
534 crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
535 else if (IsStatic)
536 crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
537 else if (IsPIE || IsStaticPIE)
538 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
539 else
540 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
541 P = ToolChain.GetFilePath(crtbegin);
543 CmdArgs.push_back(Args.MakeArgString(P));
546 // Add crtfastmath.o if available and fast math is enabled.
547 ToolChain.addFastMathRuntimeIfAvailable(Args, CmdArgs);
550 Args.AddAllArgs(CmdArgs, options::OPT_L);
551 Args.AddAllArgs(CmdArgs, options::OPT_u);
553 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
555 if (D.isUsingLTO()) {
556 assert(!Inputs.empty() && "Must have at least one input.");
557 addLTOOptions(ToolChain, Args, CmdArgs, Output, Inputs[0],
558 D.getLTOMode() == LTOK_Thin);
561 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
562 CmdArgs.push_back("--no-demangle");
564 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
565 bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
566 addLinkerCompressDebugSectionsOption(ToolChain, Args, CmdArgs);
567 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
569 addHIPRuntimeLibArgs(ToolChain, Args, CmdArgs);
571 // The profile runtime also needs access to system libraries.
572 getToolChain().addProfileRTLibs(Args, CmdArgs);
574 if (D.CCCIsCXX() &&
575 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
576 options::OPT_r)) {
577 if (ToolChain.ShouldLinkCXXStdlib(Args)) {
578 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
579 !Args.hasArg(options::OPT_static);
580 if (OnlyLibstdcxxStatic)
581 CmdArgs.push_back("-Bstatic");
582 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
583 if (OnlyLibstdcxxStatic)
584 CmdArgs.push_back("-Bdynamic");
586 CmdArgs.push_back("-lm");
589 // If we are linking for the device all symbols should be bound locally. The
590 // symbols are already protected which makes this redundant. This is only
591 // necessary to work around a problem in bfd.
592 // TODO: Remove this once 'lld' becomes the only linker for offloading.
593 if (JA.isDeviceOffloading(Action::OFK_OpenMP))
594 CmdArgs.push_back("-Bsymbolic");
596 // Silence warnings when linking C code with a C++ '-stdlib' argument.
597 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
599 // Additional linker set-up and flags for Fortran. This is required in order
600 // to generate executables. As Fortran runtime depends on the C runtime,
601 // these dependencies need to be listed before the C runtime below (i.e.
602 // AddRuntTimeLibs).
603 if (D.IsFlangMode()) {
604 addFortranRuntimeLibraryPath(ToolChain, Args, CmdArgs);
605 addFortranRuntimeLibs(ToolChain, CmdArgs);
606 CmdArgs.push_back("-lm");
609 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_r)) {
610 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
611 if (IsStatic || IsStaticPIE)
612 CmdArgs.push_back("--start-group");
614 if (NeedsSanitizerDeps)
615 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
617 if (NeedsXRayDeps)
618 linkXRayRuntimeDeps(ToolChain, CmdArgs);
620 bool WantPthread = Args.hasArg(options::OPT_pthread) ||
621 Args.hasArg(options::OPT_pthreads);
623 // Use the static OpenMP runtime with -static-openmp
624 bool StaticOpenMP = Args.hasArg(options::OPT_static_openmp) &&
625 !Args.hasArg(options::OPT_static);
627 // FIXME: Only pass GompNeedsRT = true for platforms with libgomp that
628 // require librt. Most modern Linux platforms do, but some may not.
629 if (addOpenMPRuntime(CmdArgs, ToolChain, Args, StaticOpenMP,
630 JA.isHostOffloading(Action::OFK_OpenMP),
631 /* GompNeedsRT= */ true))
632 // OpenMP runtimes implies pthreads when using the GNU toolchain.
633 // FIXME: Does this really make sense for all GNU toolchains?
634 WantPthread = true;
636 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
638 // LLVM support for atomics on 32-bit SPARC V8+ is incomplete, so
639 // forcibly link with libatomic as a workaround.
640 // TODO: Issue #41880 and D118021.
641 if (getToolChain().getTriple().getArch() == llvm::Triple::sparc) {
642 CmdArgs.push_back("--push-state");
643 CmdArgs.push_back("--as-needed");
644 CmdArgs.push_back("-latomic");
645 CmdArgs.push_back("--pop-state");
648 if (WantPthread && !isAndroid)
649 CmdArgs.push_back("-lpthread");
651 if (Args.hasArg(options::OPT_fsplit_stack))
652 CmdArgs.push_back("--wrap=pthread_create");
654 if (!Args.hasArg(options::OPT_nolibc))
655 CmdArgs.push_back("-lc");
657 // Add IAMCU specific libs, if needed.
658 if (IsIAMCU)
659 CmdArgs.push_back("-lgloss");
661 if (IsStatic || IsStaticPIE)
662 CmdArgs.push_back("--end-group");
663 else
664 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
666 // Add IAMCU specific libs (outside the group), if needed.
667 if (IsIAMCU) {
668 CmdArgs.push_back("--as-needed");
669 CmdArgs.push_back("-lsoftfp");
670 CmdArgs.push_back("--no-as-needed");
674 if (!Args.hasArg(options::OPT_nostartfiles) && !IsIAMCU) {
675 if (HasCRTBeginEndFiles) {
676 std::string P;
677 if (ToolChain.GetRuntimeLibType(Args) == ToolChain::RLT_CompilerRT &&
678 !isAndroid) {
679 std::string crtend = ToolChain.getCompilerRT(Args, "crtend",
680 ToolChain::FT_Object);
681 if (ToolChain.getVFS().exists(crtend))
682 P = crtend;
684 if (P.empty()) {
685 const char *crtend;
686 if (Args.hasArg(options::OPT_shared))
687 crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
688 else if (IsPIE || IsStaticPIE)
689 crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
690 else
691 crtend = isAndroid ? "crtend_android.o" : "crtend.o";
692 P = ToolChain.GetFilePath(crtend);
694 CmdArgs.push_back(Args.MakeArgString(P));
696 if (!isAndroid)
697 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
701 Args.AddAllArgs(CmdArgs, options::OPT_T);
703 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
704 C.addCommand(std::make_unique<Command>(JA, *this,
705 ResponseFileSupport::AtFileCurCP(),
706 Exec, CmdArgs, Inputs, Output));
709 void tools::gnutools::Assembler::ConstructJob(Compilation &C,
710 const JobAction &JA,
711 const InputInfo &Output,
712 const InputInfoList &Inputs,
713 const ArgList &Args,
714 const char *LinkingOutput) const {
715 const auto &D = getToolChain().getDriver();
717 claimNoWarnArgs(Args);
719 ArgStringList CmdArgs;
721 llvm::Reloc::Model RelocationModel;
722 unsigned PICLevel;
723 bool IsPIE;
724 const char *DefaultAssembler = "as";
725 std::tie(RelocationModel, PICLevel, IsPIE) =
726 ParsePICArgs(getToolChain(), Args);
728 if (const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ)) {
729 if (A->getOption().getID() == options::OPT_gz) {
730 CmdArgs.push_back("--compress-debug-sections");
731 } else {
732 StringRef Value = A->getValue();
733 if (Value == "none" || Value == "zlib" || Value == "zstd") {
734 CmdArgs.push_back(
735 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
736 } else {
737 D.Diag(diag::err_drv_unsupported_option_argument)
738 << A->getOption().getName() << Value;
743 switch (getToolChain().getArch()) {
744 default:
745 break;
746 // Add --32/--64 to make sure we get the format we want.
747 // This is incomplete
748 case llvm::Triple::x86:
749 CmdArgs.push_back("--32");
750 break;
751 case llvm::Triple::x86_64:
752 if (getToolChain().getTriple().isX32())
753 CmdArgs.push_back("--x32");
754 else
755 CmdArgs.push_back("--64");
756 break;
757 case llvm::Triple::ppc: {
758 CmdArgs.push_back("-a32");
759 CmdArgs.push_back("-mppc");
760 CmdArgs.push_back("-mbig-endian");
761 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
762 getCPUName(D, Args, getToolChain().getTriple())));
763 break;
765 case llvm::Triple::ppcle: {
766 CmdArgs.push_back("-a32");
767 CmdArgs.push_back("-mppc");
768 CmdArgs.push_back("-mlittle-endian");
769 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
770 getCPUName(D, Args, getToolChain().getTriple())));
771 break;
773 case llvm::Triple::ppc64: {
774 CmdArgs.push_back("-a64");
775 CmdArgs.push_back("-mppc64");
776 CmdArgs.push_back("-mbig-endian");
777 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
778 getCPUName(D, Args, getToolChain().getTriple())));
779 break;
781 case llvm::Triple::ppc64le: {
782 CmdArgs.push_back("-a64");
783 CmdArgs.push_back("-mppc64");
784 CmdArgs.push_back("-mlittle-endian");
785 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
786 getCPUName(D, Args, getToolChain().getTriple())));
787 break;
789 case llvm::Triple::riscv32:
790 case llvm::Triple::riscv64: {
791 StringRef ABIName = riscv::getRISCVABI(Args, getToolChain().getTriple());
792 CmdArgs.push_back("-mabi");
793 CmdArgs.push_back(ABIName.data());
794 StringRef MArchName = riscv::getRISCVArch(Args, getToolChain().getTriple());
795 CmdArgs.push_back("-march");
796 CmdArgs.push_back(MArchName.data());
797 if (!Args.hasFlag(options::OPT_mrelax, options::OPT_mno_relax, true))
798 Args.addOptOutFlag(CmdArgs, options::OPT_mrelax, options::OPT_mno_relax);
799 break;
801 case llvm::Triple::sparc:
802 case llvm::Triple::sparcel: {
803 CmdArgs.push_back("-32");
804 std::string CPU = getCPUName(D, Args, getToolChain().getTriple());
805 CmdArgs.push_back(
806 sparc::getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
807 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
808 break;
810 case llvm::Triple::sparcv9: {
811 CmdArgs.push_back("-64");
812 std::string CPU = getCPUName(D, Args, getToolChain().getTriple());
813 CmdArgs.push_back(
814 sparc::getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
815 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
816 break;
818 case llvm::Triple::arm:
819 case llvm::Triple::armeb:
820 case llvm::Triple::thumb:
821 case llvm::Triple::thumbeb: {
822 const llvm::Triple &Triple2 = getToolChain().getTriple();
823 CmdArgs.push_back(isArmBigEndian(Triple2, Args) ? "-EB" : "-EL");
824 switch (Triple2.getSubArch()) {
825 case llvm::Triple::ARMSubArch_v7:
826 CmdArgs.push_back("-mfpu=neon");
827 break;
828 case llvm::Triple::ARMSubArch_v8:
829 CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
830 break;
831 default:
832 break;
835 switch (arm::getARMFloatABI(getToolChain(), Args)) {
836 case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
837 case arm::FloatABI::Soft:
838 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
839 break;
840 case arm::FloatABI::SoftFP:
841 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
842 break;
843 case arm::FloatABI::Hard:
844 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
845 break;
848 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
849 normalizeCPUNamesForAssembler(Args, CmdArgs);
851 Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
852 break;
854 case llvm::Triple::aarch64:
855 case llvm::Triple::aarch64_be: {
856 CmdArgs.push_back(
857 getToolChain().getArch() == llvm::Triple::aarch64_be ? "-EB" : "-EL");
858 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
859 normalizeCPUNamesForAssembler(Args, CmdArgs);
861 break;
863 case llvm::Triple::mips:
864 case llvm::Triple::mipsel:
865 case llvm::Triple::mips64:
866 case llvm::Triple::mips64el: {
867 StringRef CPUName;
868 StringRef ABIName;
869 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
870 ABIName = mips::getGnuCompatibleMipsABIName(ABIName);
872 CmdArgs.push_back("-march");
873 CmdArgs.push_back(CPUName.data());
875 CmdArgs.push_back("-mabi");
876 CmdArgs.push_back(ABIName.data());
878 // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
879 // or -mshared (not implemented) is in effect.
880 if (RelocationModel == llvm::Reloc::Static)
881 CmdArgs.push_back("-mno-shared");
883 // LLVM doesn't support -mplt yet and acts as if it is always given.
884 // However, -mplt has no effect with the N64 ABI.
885 if (ABIName != "64" && !Args.hasArg(options::OPT_mno_abicalls))
886 CmdArgs.push_back("-call_nonpic");
888 if (getToolChain().getTriple().isLittleEndian())
889 CmdArgs.push_back("-EL");
890 else
891 CmdArgs.push_back("-EB");
893 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
894 if (StringRef(A->getValue()) == "2008")
895 CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
898 // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
899 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
900 options::OPT_mfp64)) {
901 A->claim();
902 A->render(Args, CmdArgs);
903 } else if (mips::shouldUseFPXX(
904 Args, getToolChain().getTriple(), CPUName, ABIName,
905 mips::getMipsFloatABI(getToolChain().getDriver(), Args,
906 getToolChain().getTriple())))
907 CmdArgs.push_back("-mfpxx");
909 // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
910 // -mno-mips16 is actually -no-mips16.
911 if (Arg *A =
912 Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
913 if (A->getOption().matches(options::OPT_mips16)) {
914 A->claim();
915 A->render(Args, CmdArgs);
916 } else {
917 A->claim();
918 CmdArgs.push_back("-no-mips16");
922 Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
923 options::OPT_mno_micromips);
924 Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
925 Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
927 if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
928 // Do not use AddLastArg because not all versions of MIPS assembler
929 // support -mmsa / -mno-msa options.
930 if (A->getOption().matches(options::OPT_mmsa))
931 CmdArgs.push_back(Args.MakeArgString("-mmsa"));
934 Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
935 options::OPT_msoft_float);
937 Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
938 options::OPT_msingle_float);
940 Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
941 options::OPT_mno_odd_spreg);
943 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
944 break;
946 case llvm::Triple::systemz: {
947 // Always pass an -march option, since our default of z10 is later
948 // than the GNU assembler's default.
949 std::string CPUName = systemz::getSystemZTargetCPU(Args);
950 CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
951 break;
953 case llvm::Triple::ve:
954 DefaultAssembler = "nas";
957 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
958 options::OPT_fdebug_prefix_map_EQ)) {
959 StringRef Map = A->getValue();
960 if (!Map.contains('='))
961 D.Diag(diag::err_drv_invalid_argument_to_option)
962 << Map << A->getOption().getName();
963 else {
964 CmdArgs.push_back(Args.MakeArgString("--debug-prefix-map"));
965 CmdArgs.push_back(Args.MakeArgString(Map));
967 A->claim();
970 Args.AddAllArgs(CmdArgs, options::OPT_I);
971 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
973 CmdArgs.push_back("-o");
974 CmdArgs.push_back(Output.getFilename());
976 for (const auto &II : Inputs)
977 CmdArgs.push_back(II.getFilename());
979 const char *Exec =
980 Args.MakeArgString(getToolChain().GetProgramPath(DefaultAssembler));
981 C.addCommand(std::make_unique<Command>(JA, *this,
982 ResponseFileSupport::AtFileCurCP(),
983 Exec, CmdArgs, Inputs, Output));
985 // Handle the debug info splitting at object creation time if we're
986 // creating an object.
987 // TODO: Currently only works on linux with newer objcopy.
988 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
989 getToolChain().getTriple().isOSLinux())
990 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
991 SplitDebugName(JA, Args, Inputs[0], Output));
994 namespace {
995 // Filter to remove Multilibs that don't exist as a suffix to Path
996 class FilterNonExistent {
997 StringRef Base, File;
998 llvm::vfs::FileSystem &VFS;
1000 public:
1001 FilterNonExistent(StringRef Base, StringRef File, llvm::vfs::FileSystem &VFS)
1002 : Base(Base), File(File), VFS(VFS) {}
1003 bool operator()(const Multilib &M) {
1004 return !VFS.exists(Base + M.gccSuffix() + File);
1007 } // end anonymous namespace
1009 static bool isSoftFloatABI(const ArgList &Args) {
1010 Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1011 options::OPT_mfloat_abi_EQ);
1012 if (!A)
1013 return false;
1015 return A->getOption().matches(options::OPT_msoft_float) ||
1016 (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
1017 A->getValue() == StringRef("soft"));
1020 static bool isArmOrThumbArch(llvm::Triple::ArchType Arch) {
1021 return Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb;
1024 static bool isMipsEL(llvm::Triple::ArchType Arch) {
1025 return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
1028 static bool isMips16(const ArgList &Args) {
1029 Arg *A = Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16);
1030 return A && A->getOption().matches(options::OPT_mips16);
1033 static bool isMicroMips(const ArgList &Args) {
1034 Arg *A = Args.getLastArg(options::OPT_mmicromips, options::OPT_mno_micromips);
1035 return A && A->getOption().matches(options::OPT_mmicromips);
1038 static bool isMSP430(llvm::Triple::ArchType Arch) {
1039 return Arch == llvm::Triple::msp430;
1042 static Multilib makeMultilib(StringRef commonSuffix) {
1043 return Multilib(commonSuffix, commonSuffix, commonSuffix);
1046 static bool findMipsCsMultilibs(const Multilib::flags_list &Flags,
1047 FilterNonExistent &NonExistent,
1048 DetectedMultilibs &Result) {
1049 // Check for Code Sourcery toolchain multilibs
1050 MultilibSet CSMipsMultilibs;
1052 auto MArchMips16 = makeMultilib("/mips16").flag("+m32").flag("+mips16");
1054 auto MArchMicroMips =
1055 makeMultilib("/micromips").flag("+m32").flag("+mmicromips");
1057 auto MArchDefault = makeMultilib("").flag("-mips16").flag("-mmicromips");
1059 auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
1061 auto SoftFloat = makeMultilib("/soft-float").flag("+msoft-float");
1063 auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
1065 auto DefaultFloat =
1066 makeMultilib("").flag("-msoft-float").flag("-mnan=2008");
1068 auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
1070 auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1072 // Note that this one's osSuffix is ""
1073 auto MAbi64 = makeMultilib("")
1074 .gccSuffix("/64")
1075 .includeSuffix("/64")
1076 .flag("+mabi=n64")
1077 .flag("-mabi=n32")
1078 .flag("-m32");
1080 CSMipsMultilibs =
1081 MultilibSet()
1082 .Either(MArchMips16, MArchMicroMips, MArchDefault)
1083 .Maybe(UCLibc)
1084 .Either(SoftFloat, Nan2008, DefaultFloat)
1085 .FilterOut("/micromips/nan2008")
1086 .FilterOut("/mips16/nan2008")
1087 .Either(BigEndian, LittleEndian)
1088 .Maybe(MAbi64)
1089 .FilterOut("/mips16.*/64")
1090 .FilterOut("/micromips.*/64")
1091 .FilterOut(NonExistent)
1092 .setIncludeDirsCallback([](const Multilib &M) {
1093 std::vector<std::string> Dirs({"/include"});
1094 if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1095 Dirs.push_back(
1096 "/../../../../mips-linux-gnu/libc/uclibc/usr/include");
1097 else
1098 Dirs.push_back("/../../../../mips-linux-gnu/libc/usr/include");
1099 return Dirs;
1103 MultilibSet DebianMipsMultilibs;
1105 Multilib MAbiN32 =
1106 Multilib().gccSuffix("/n32").includeSuffix("/n32").flag("+mabi=n32");
1108 Multilib M64 = Multilib()
1109 .gccSuffix("/64")
1110 .includeSuffix("/64")
1111 .flag("+m64")
1112 .flag("-m32")
1113 .flag("-mabi=n32");
1115 Multilib M32 =
1116 Multilib().gccSuffix("/32").flag("-m64").flag("+m32").flag("-mabi=n32");
1118 DebianMipsMultilibs =
1119 MultilibSet().Either(M32, M64, MAbiN32).FilterOut(NonExistent);
1122 // Sort candidates. Toolchain that best meets the directories tree goes first.
1123 // Then select the first toolchains matches command line flags.
1124 MultilibSet *Candidates[] = {&CSMipsMultilibs, &DebianMipsMultilibs};
1125 if (CSMipsMultilibs.size() < DebianMipsMultilibs.size())
1126 std::iter_swap(Candidates, Candidates + 1);
1127 for (const MultilibSet *Candidate : Candidates) {
1128 if (Candidate->select(Flags, Result.SelectedMultilib)) {
1129 if (Candidate == &DebianMipsMultilibs)
1130 Result.BiarchSibling = Multilib();
1131 Result.Multilibs = *Candidate;
1132 return true;
1135 return false;
1138 static bool findMipsAndroidMultilibs(llvm::vfs::FileSystem &VFS, StringRef Path,
1139 const Multilib::flags_list &Flags,
1140 FilterNonExistent &NonExistent,
1141 DetectedMultilibs &Result) {
1143 MultilibSet AndroidMipsMultilibs =
1144 MultilibSet()
1145 .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
1146 .Maybe(Multilib("/mips-r6").flag("+march=mips32r6"))
1147 .FilterOut(NonExistent);
1149 MultilibSet AndroidMipselMultilibs =
1150 MultilibSet()
1151 .Either(Multilib().flag("+march=mips32"),
1152 Multilib("/mips-r2", "", "/mips-r2").flag("+march=mips32r2"),
1153 Multilib("/mips-r6", "", "/mips-r6").flag("+march=mips32r6"))
1154 .FilterOut(NonExistent);
1156 MultilibSet AndroidMips64elMultilibs =
1157 MultilibSet()
1158 .Either(
1159 Multilib().flag("+march=mips64r6"),
1160 Multilib("/32/mips-r1", "", "/mips-r1").flag("+march=mips32"),
1161 Multilib("/32/mips-r2", "", "/mips-r2").flag("+march=mips32r2"),
1162 Multilib("/32/mips-r6", "", "/mips-r6").flag("+march=mips32r6"))
1163 .FilterOut(NonExistent);
1165 MultilibSet *MS = &AndroidMipsMultilibs;
1166 if (VFS.exists(Path + "/mips-r6"))
1167 MS = &AndroidMipselMultilibs;
1168 else if (VFS.exists(Path + "/32"))
1169 MS = &AndroidMips64elMultilibs;
1170 if (MS->select(Flags, Result.SelectedMultilib)) {
1171 Result.Multilibs = *MS;
1172 return true;
1174 return false;
1177 static bool findMipsMuslMultilibs(const Multilib::flags_list &Flags,
1178 FilterNonExistent &NonExistent,
1179 DetectedMultilibs &Result) {
1180 // Musl toolchain multilibs
1181 MultilibSet MuslMipsMultilibs;
1183 auto MArchMipsR2 = makeMultilib("")
1184 .osSuffix("/mips-r2-hard-musl")
1185 .flag("+EB")
1186 .flag("-EL")
1187 .flag("+march=mips32r2");
1189 auto MArchMipselR2 = makeMultilib("/mipsel-r2-hard-musl")
1190 .flag("-EB")
1191 .flag("+EL")
1192 .flag("+march=mips32r2");
1194 MuslMipsMultilibs = MultilibSet().Either(MArchMipsR2, MArchMipselR2);
1196 // Specify the callback that computes the include directories.
1197 MuslMipsMultilibs.setIncludeDirsCallback([](const Multilib &M) {
1198 return std::vector<std::string>(
1199 {"/../sysroot" + M.osSuffix() + "/usr/include"});
1202 if (MuslMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
1203 Result.Multilibs = MuslMipsMultilibs;
1204 return true;
1206 return false;
1209 static bool findMipsMtiMultilibs(const Multilib::flags_list &Flags,
1210 FilterNonExistent &NonExistent,
1211 DetectedMultilibs &Result) {
1212 // CodeScape MTI toolchain v1.2 and early.
1213 MultilibSet MtiMipsMultilibsV1;
1215 auto MArchMips32 = makeMultilib("/mips32")
1216 .flag("+m32")
1217 .flag("-m64")
1218 .flag("-mmicromips")
1219 .flag("+march=mips32");
1221 auto MArchMicroMips = makeMultilib("/micromips")
1222 .flag("+m32")
1223 .flag("-m64")
1224 .flag("+mmicromips");
1226 auto MArchMips64r2 = makeMultilib("/mips64r2")
1227 .flag("-m32")
1228 .flag("+m64")
1229 .flag("+march=mips64r2");
1231 auto MArchMips64 = makeMultilib("/mips64").flag("-m32").flag("+m64").flag(
1232 "-march=mips64r2");
1234 auto MArchDefault = makeMultilib("")
1235 .flag("+m32")
1236 .flag("-m64")
1237 .flag("-mmicromips")
1238 .flag("+march=mips32r2");
1240 auto Mips16 = makeMultilib("/mips16").flag("+mips16");
1242 auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
1244 auto MAbi64 =
1245 makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1247 auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
1249 auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1251 auto SoftFloat = makeMultilib("/sof").flag("+msoft-float");
1253 auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
1255 MtiMipsMultilibsV1 =
1256 MultilibSet()
1257 .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64,
1258 MArchDefault)
1259 .Maybe(UCLibc)
1260 .Maybe(Mips16)
1261 .FilterOut("/mips64/mips16")
1262 .FilterOut("/mips64r2/mips16")
1263 .FilterOut("/micromips/mips16")
1264 .Maybe(MAbi64)
1265 .FilterOut("/micromips/64")
1266 .FilterOut("/mips32/64")
1267 .FilterOut("^/64")
1268 .FilterOut("/mips16/64")
1269 .Either(BigEndian, LittleEndian)
1270 .Maybe(SoftFloat)
1271 .Maybe(Nan2008)
1272 .FilterOut(".*sof/nan2008")
1273 .FilterOut(NonExistent)
1274 .setIncludeDirsCallback([](const Multilib &M) {
1275 std::vector<std::string> Dirs({"/include"});
1276 if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1277 Dirs.push_back("/../../../../sysroot/uclibc/usr/include");
1278 else
1279 Dirs.push_back("/../../../../sysroot/usr/include");
1280 return Dirs;
1284 // CodeScape IMG toolchain starting from v1.3.
1285 MultilibSet MtiMipsMultilibsV2;
1287 auto BeHard = makeMultilib("/mips-r2-hard")
1288 .flag("+EB")
1289 .flag("-msoft-float")
1290 .flag("-mnan=2008")
1291 .flag("-muclibc");
1292 auto BeSoft = makeMultilib("/mips-r2-soft")
1293 .flag("+EB")
1294 .flag("+msoft-float")
1295 .flag("-mnan=2008");
1296 auto ElHard = makeMultilib("/mipsel-r2-hard")
1297 .flag("+EL")
1298 .flag("-msoft-float")
1299 .flag("-mnan=2008")
1300 .flag("-muclibc");
1301 auto ElSoft = makeMultilib("/mipsel-r2-soft")
1302 .flag("+EL")
1303 .flag("+msoft-float")
1304 .flag("-mnan=2008")
1305 .flag("-mmicromips");
1306 auto BeHardNan = makeMultilib("/mips-r2-hard-nan2008")
1307 .flag("+EB")
1308 .flag("-msoft-float")
1309 .flag("+mnan=2008")
1310 .flag("-muclibc");
1311 auto ElHardNan = makeMultilib("/mipsel-r2-hard-nan2008")
1312 .flag("+EL")
1313 .flag("-msoft-float")
1314 .flag("+mnan=2008")
1315 .flag("-muclibc")
1316 .flag("-mmicromips");
1317 auto BeHardNanUclibc = makeMultilib("/mips-r2-hard-nan2008-uclibc")
1318 .flag("+EB")
1319 .flag("-msoft-float")
1320 .flag("+mnan=2008")
1321 .flag("+muclibc");
1322 auto ElHardNanUclibc = makeMultilib("/mipsel-r2-hard-nan2008-uclibc")
1323 .flag("+EL")
1324 .flag("-msoft-float")
1325 .flag("+mnan=2008")
1326 .flag("+muclibc");
1327 auto BeHardUclibc = makeMultilib("/mips-r2-hard-uclibc")
1328 .flag("+EB")
1329 .flag("-msoft-float")
1330 .flag("-mnan=2008")
1331 .flag("+muclibc");
1332 auto ElHardUclibc = makeMultilib("/mipsel-r2-hard-uclibc")
1333 .flag("+EL")
1334 .flag("-msoft-float")
1335 .flag("-mnan=2008")
1336 .flag("+muclibc");
1337 auto ElMicroHardNan = makeMultilib("/micromipsel-r2-hard-nan2008")
1338 .flag("+EL")
1339 .flag("-msoft-float")
1340 .flag("+mnan=2008")
1341 .flag("+mmicromips");
1342 auto ElMicroSoft = makeMultilib("/micromipsel-r2-soft")
1343 .flag("+EL")
1344 .flag("+msoft-float")
1345 .flag("-mnan=2008")
1346 .flag("+mmicromips");
1348 auto O32 =
1349 makeMultilib("/lib").osSuffix("").flag("-mabi=n32").flag("-mabi=n64");
1350 auto N32 =
1351 makeMultilib("/lib32").osSuffix("").flag("+mabi=n32").flag("-mabi=n64");
1352 auto N64 =
1353 makeMultilib("/lib64").osSuffix("").flag("-mabi=n32").flag("+mabi=n64");
1355 MtiMipsMultilibsV2 =
1356 MultilibSet()
1357 .Either({BeHard, BeSoft, ElHard, ElSoft, BeHardNan, ElHardNan,
1358 BeHardNanUclibc, ElHardNanUclibc, BeHardUclibc,
1359 ElHardUclibc, ElMicroHardNan, ElMicroSoft})
1360 .Either(O32, N32, N64)
1361 .FilterOut(NonExistent)
1362 .setIncludeDirsCallback([](const Multilib &M) {
1363 return std::vector<std::string>({"/../../../../sysroot" +
1364 M.includeSuffix() +
1365 "/../usr/include"});
1367 .setFilePathsCallback([](const Multilib &M) {
1368 return std::vector<std::string>(
1369 {"/../../../../mips-mti-linux-gnu/lib" + M.gccSuffix()});
1372 for (auto *Candidate : {&MtiMipsMultilibsV1, &MtiMipsMultilibsV2}) {
1373 if (Candidate->select(Flags, Result.SelectedMultilib)) {
1374 Result.Multilibs = *Candidate;
1375 return true;
1378 return false;
1381 static bool findMipsImgMultilibs(const Multilib::flags_list &Flags,
1382 FilterNonExistent &NonExistent,
1383 DetectedMultilibs &Result) {
1384 // CodeScape IMG toolchain v1.2 and early.
1385 MultilibSet ImgMultilibsV1;
1387 auto Mips64r6 = makeMultilib("/mips64r6").flag("+m64").flag("-m32");
1389 auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1391 auto MAbi64 =
1392 makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1394 ImgMultilibsV1 =
1395 MultilibSet()
1396 .Maybe(Mips64r6)
1397 .Maybe(MAbi64)
1398 .Maybe(LittleEndian)
1399 .FilterOut(NonExistent)
1400 .setIncludeDirsCallback([](const Multilib &M) {
1401 return std::vector<std::string>(
1402 {"/include", "/../../../../sysroot/usr/include"});
1406 // CodeScape IMG toolchain starting from v1.3.
1407 MultilibSet ImgMultilibsV2;
1409 auto BeHard = makeMultilib("/mips-r6-hard")
1410 .flag("+EB")
1411 .flag("-msoft-float")
1412 .flag("-mmicromips");
1413 auto BeSoft = makeMultilib("/mips-r6-soft")
1414 .flag("+EB")
1415 .flag("+msoft-float")
1416 .flag("-mmicromips");
1417 auto ElHard = makeMultilib("/mipsel-r6-hard")
1418 .flag("+EL")
1419 .flag("-msoft-float")
1420 .flag("-mmicromips");
1421 auto ElSoft = makeMultilib("/mipsel-r6-soft")
1422 .flag("+EL")
1423 .flag("+msoft-float")
1424 .flag("-mmicromips");
1425 auto BeMicroHard = makeMultilib("/micromips-r6-hard")
1426 .flag("+EB")
1427 .flag("-msoft-float")
1428 .flag("+mmicromips");
1429 auto BeMicroSoft = makeMultilib("/micromips-r6-soft")
1430 .flag("+EB")
1431 .flag("+msoft-float")
1432 .flag("+mmicromips");
1433 auto ElMicroHard = makeMultilib("/micromipsel-r6-hard")
1434 .flag("+EL")
1435 .flag("-msoft-float")
1436 .flag("+mmicromips");
1437 auto ElMicroSoft = makeMultilib("/micromipsel-r6-soft")
1438 .flag("+EL")
1439 .flag("+msoft-float")
1440 .flag("+mmicromips");
1442 auto O32 =
1443 makeMultilib("/lib").osSuffix("").flag("-mabi=n32").flag("-mabi=n64");
1444 auto N32 =
1445 makeMultilib("/lib32").osSuffix("").flag("+mabi=n32").flag("-mabi=n64");
1446 auto N64 =
1447 makeMultilib("/lib64").osSuffix("").flag("-mabi=n32").flag("+mabi=n64");
1449 ImgMultilibsV2 =
1450 MultilibSet()
1451 .Either({BeHard, BeSoft, ElHard, ElSoft, BeMicroHard, BeMicroSoft,
1452 ElMicroHard, ElMicroSoft})
1453 .Either(O32, N32, N64)
1454 .FilterOut(NonExistent)
1455 .setIncludeDirsCallback([](const Multilib &M) {
1456 return std::vector<std::string>({"/../../../../sysroot" +
1457 M.includeSuffix() +
1458 "/../usr/include"});
1460 .setFilePathsCallback([](const Multilib &M) {
1461 return std::vector<std::string>(
1462 {"/../../../../mips-img-linux-gnu/lib" + M.gccSuffix()});
1465 for (auto *Candidate : {&ImgMultilibsV1, &ImgMultilibsV2}) {
1466 if (Candidate->select(Flags, Result.SelectedMultilib)) {
1467 Result.Multilibs = *Candidate;
1468 return true;
1471 return false;
1474 bool clang::driver::findMIPSMultilibs(const Driver &D,
1475 const llvm::Triple &TargetTriple,
1476 StringRef Path, const ArgList &Args,
1477 DetectedMultilibs &Result) {
1478 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1480 StringRef CPUName;
1481 StringRef ABIName;
1482 tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
1484 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1486 Multilib::flags_list Flags;
1487 addMultilibFlag(TargetTriple.isMIPS32(), "m32", Flags);
1488 addMultilibFlag(TargetTriple.isMIPS64(), "m64", Flags);
1489 addMultilibFlag(isMips16(Args), "mips16", Flags);
1490 addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
1491 addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" ||
1492 CPUName == "mips32r5" || CPUName == "p5600",
1493 "march=mips32r2", Flags);
1494 addMultilibFlag(CPUName == "mips32r6", "march=mips32r6", Flags);
1495 addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
1496 addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" ||
1497 CPUName == "mips64r5" || CPUName == "octeon" ||
1498 CPUName == "octeon+",
1499 "march=mips64r2", Flags);
1500 addMultilibFlag(CPUName == "mips64r6", "march=mips64r6", Flags);
1501 addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
1502 addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
1503 addMultilibFlag(tools::mips::isNaN2008(D, Args, TargetTriple), "mnan=2008",
1504 Flags);
1505 addMultilibFlag(ABIName == "n32", "mabi=n32", Flags);
1506 addMultilibFlag(ABIName == "n64", "mabi=n64", Flags);
1507 addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags);
1508 addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags);
1509 addMultilibFlag(isMipsEL(TargetArch), "EL", Flags);
1510 addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags);
1512 if (TargetTriple.isAndroid())
1513 return findMipsAndroidMultilibs(D.getVFS(), Path, Flags, NonExistent,
1514 Result);
1516 if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
1517 TargetTriple.getOS() == llvm::Triple::Linux &&
1518 TargetTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
1519 return findMipsMuslMultilibs(Flags, NonExistent, Result);
1521 if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
1522 TargetTriple.getOS() == llvm::Triple::Linux &&
1523 TargetTriple.isGNUEnvironment())
1524 return findMipsMtiMultilibs(Flags, NonExistent, Result);
1526 if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1527 TargetTriple.getOS() == llvm::Triple::Linux &&
1528 TargetTriple.isGNUEnvironment())
1529 return findMipsImgMultilibs(Flags, NonExistent, Result);
1531 if (findMipsCsMultilibs(Flags, NonExistent, Result))
1532 return true;
1534 // Fallback to the regular toolchain-tree structure.
1535 Multilib Default;
1536 Result.Multilibs.push_back(Default);
1537 Result.Multilibs.FilterOut(NonExistent);
1539 if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) {
1540 Result.BiarchSibling = Multilib();
1541 return true;
1544 return false;
1547 static void findAndroidArmMultilibs(const Driver &D,
1548 const llvm::Triple &TargetTriple,
1549 StringRef Path, const ArgList &Args,
1550 DetectedMultilibs &Result) {
1551 // Find multilibs with subdirectories like armv7-a, thumb, armv7-a/thumb.
1552 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1553 Multilib ArmV7Multilib = makeMultilib("/armv7-a")
1554 .flag("+march=armv7-a")
1555 .flag("-mthumb");
1556 Multilib ThumbMultilib = makeMultilib("/thumb")
1557 .flag("-march=armv7-a")
1558 .flag("+mthumb");
1559 Multilib ArmV7ThumbMultilib = makeMultilib("/armv7-a/thumb")
1560 .flag("+march=armv7-a")
1561 .flag("+mthumb");
1562 Multilib DefaultMultilib = makeMultilib("")
1563 .flag("-march=armv7-a")
1564 .flag("-mthumb");
1565 MultilibSet AndroidArmMultilibs =
1566 MultilibSet()
1567 .Either(ThumbMultilib, ArmV7Multilib,
1568 ArmV7ThumbMultilib, DefaultMultilib)
1569 .FilterOut(NonExistent);
1571 Multilib::flags_list Flags;
1572 llvm::StringRef Arch = Args.getLastArgValue(options::OPT_march_EQ);
1573 bool IsArmArch = TargetTriple.getArch() == llvm::Triple::arm;
1574 bool IsThumbArch = TargetTriple.getArch() == llvm::Triple::thumb;
1575 bool IsV7SubArch = TargetTriple.getSubArch() == llvm::Triple::ARMSubArch_v7;
1576 bool IsThumbMode = IsThumbArch ||
1577 Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, false) ||
1578 (IsArmArch && llvm::ARM::parseArchISA(Arch) == llvm::ARM::ISAKind::THUMB);
1579 bool IsArmV7Mode = (IsArmArch || IsThumbArch) &&
1580 (llvm::ARM::parseArchVersion(Arch) == 7 ||
1581 (IsArmArch && Arch == "" && IsV7SubArch));
1582 addMultilibFlag(IsArmV7Mode, "march=armv7-a", Flags);
1583 addMultilibFlag(IsThumbMode, "mthumb", Flags);
1585 if (AndroidArmMultilibs.select(Flags, Result.SelectedMultilib))
1586 Result.Multilibs = AndroidArmMultilibs;
1589 static bool findMSP430Multilibs(const Driver &D,
1590 const llvm::Triple &TargetTriple,
1591 StringRef Path, const ArgList &Args,
1592 DetectedMultilibs &Result) {
1593 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1594 Multilib WithoutExceptions = makeMultilib("/430").flag("-exceptions");
1595 Multilib WithExceptions = makeMultilib("/430/exceptions").flag("+exceptions");
1597 // FIXME: when clang starts to support msp430x ISA additional logic
1598 // to select between multilib must be implemented
1599 // Multilib MSP430xMultilib = makeMultilib("/large");
1601 Result.Multilibs.push_back(WithoutExceptions);
1602 Result.Multilibs.push_back(WithExceptions);
1603 Result.Multilibs.FilterOut(NonExistent);
1605 Multilib::flags_list Flags;
1606 addMultilibFlag(Args.hasFlag(options::OPT_fexceptions,
1607 options::OPT_fno_exceptions, false),
1608 "exceptions", Flags);
1609 if (Result.Multilibs.select(Flags, Result.SelectedMultilib))
1610 return true;
1612 return false;
1615 static void findCSKYMultilibs(const Driver &D, const llvm::Triple &TargetTriple,
1616 StringRef Path, const ArgList &Args,
1617 DetectedMultilibs &Result) {
1618 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1620 tools::csky::FloatABI TheFloatABI = tools::csky::getCSKYFloatABI(D, Args);
1621 llvm::Optional<llvm::StringRef> Res = tools::csky::getCSKYArchName(D, Args, TargetTriple);
1623 if (!Res)
1624 return;
1625 auto ARCHName = *Res;
1627 Multilib::flags_list Flags;
1628 addMultilibFlag(TheFloatABI == tools::csky::FloatABI::Hard, "hard-fp", Flags);
1629 addMultilibFlag(TheFloatABI == tools::csky::FloatABI::SoftFP, "soft-fp",
1630 Flags);
1631 addMultilibFlag(TheFloatABI == tools::csky::FloatABI::Soft, "soft", Flags);
1632 addMultilibFlag(ARCHName == "ck801", "march=ck801", Flags);
1633 addMultilibFlag(ARCHName == "ck802", "march=ck802", Flags);
1634 addMultilibFlag(ARCHName == "ck803", "march=ck803", Flags);
1635 addMultilibFlag(ARCHName == "ck804", "march=ck804", Flags);
1636 addMultilibFlag(ARCHName == "ck805", "march=ck805", Flags);
1637 addMultilibFlag(ARCHName == "ck807", "march=ck807", Flags);
1638 addMultilibFlag(ARCHName == "ck810", "march=ck810", Flags);
1639 addMultilibFlag(ARCHName == "ck810v", "march=ck810v", Flags);
1640 addMultilibFlag(ARCHName == "ck860", "march=ck860", Flags);
1641 addMultilibFlag(ARCHName == "ck860v", "march=ck860v", Flags);
1643 bool isBigEndian = false;
1644 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
1645 options::OPT_mbig_endian))
1646 isBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
1647 addMultilibFlag(isBigEndian, "EB", Flags);
1649 auto HardFloat = makeMultilib("/hard-fp").flag("+hard-fp");
1650 auto SoftFpFloat = makeMultilib("/soft-fp").flag("+soft-fp");
1651 auto SoftFloat = makeMultilib("").flag("+soft");
1652 auto Arch801 = makeMultilib("/ck801").flag("+march=ck801");
1653 auto Arch802 = makeMultilib("/ck802").flag("+march=ck802");
1654 auto Arch803 = makeMultilib("/ck803").flag("+march=ck803");
1655 // CK804 use the same library as CK803
1656 auto Arch804 = makeMultilib("/ck803").flag("+march=ck804");
1657 auto Arch805 = makeMultilib("/ck805").flag("+march=ck805");
1658 auto Arch807 = makeMultilib("/ck807").flag("+march=ck807");
1659 auto Arch810 = makeMultilib("").flag("+march=ck810");
1660 auto Arch810v = makeMultilib("/ck810v").flag("+march=ck810v");
1661 auto Arch860 = makeMultilib("/ck860").flag("+march=ck860");
1662 auto Arch860v = makeMultilib("/ck860v").flag("+march=ck860v");
1663 auto BigEndian = makeMultilib("/big").flag("+EB");
1665 MultilibSet CSKYMultilibs =
1666 MultilibSet()
1667 .Maybe(BigEndian)
1668 .Either({Arch801, Arch802, Arch803, Arch804, Arch805, Arch807,
1669 Arch810, Arch810v, Arch860, Arch860v})
1670 .Either(HardFloat, SoftFpFloat, SoftFloat)
1671 .FilterOut(NonExistent);
1673 if (CSKYMultilibs.select(Flags, Result.SelectedMultilib))
1674 Result.Multilibs = CSKYMultilibs;
1677 static void findRISCVBareMetalMultilibs(const Driver &D,
1678 const llvm::Triple &TargetTriple,
1679 StringRef Path, const ArgList &Args,
1680 DetectedMultilibs &Result) {
1681 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1682 struct RiscvMultilib {
1683 StringRef march;
1684 StringRef mabi;
1686 // currently only support the set of multilibs like riscv-gnu-toolchain does.
1687 // TODO: support MULTILIB_REUSE
1688 constexpr RiscvMultilib RISCVMultilibSet[] = {
1689 {"rv32i", "ilp32"}, {"rv32im", "ilp32"}, {"rv32iac", "ilp32"},
1690 {"rv32imac", "ilp32"}, {"rv32imafc", "ilp32f"}, {"rv64imac", "lp64"},
1691 {"rv64imafdc", "lp64d"}};
1693 std::vector<Multilib> Ms;
1694 for (auto Element : RISCVMultilibSet) {
1695 // multilib path rule is ${march}/${mabi}
1696 Ms.emplace_back(
1697 makeMultilib((Twine(Element.march) + "/" + Twine(Element.mabi)).str())
1698 .flag(Twine("+march=", Element.march).str())
1699 .flag(Twine("+mabi=", Element.mabi).str()));
1701 MultilibSet RISCVMultilibs =
1702 MultilibSet()
1703 .Either(ArrayRef<Multilib>(Ms))
1704 .FilterOut(NonExistent)
1705 .setFilePathsCallback([](const Multilib &M) {
1706 return std::vector<std::string>(
1707 {M.gccSuffix(),
1708 "/../../../../riscv64-unknown-elf/lib" + M.gccSuffix(),
1709 "/../../../../riscv32-unknown-elf/lib" + M.gccSuffix()});
1713 Multilib::flags_list Flags;
1714 llvm::StringSet<> Added_ABIs;
1715 StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple);
1716 StringRef MArch = tools::riscv::getRISCVArch(Args, TargetTriple);
1717 for (auto Element : RISCVMultilibSet) {
1718 addMultilibFlag(MArch == Element.march,
1719 Twine("march=", Element.march).str().c_str(), Flags);
1720 if (!Added_ABIs.count(Element.mabi)) {
1721 Added_ABIs.insert(Element.mabi);
1722 addMultilibFlag(ABIName == Element.mabi,
1723 Twine("mabi=", Element.mabi).str().c_str(), Flags);
1727 if (RISCVMultilibs.select(Flags, Result.SelectedMultilib))
1728 Result.Multilibs = RISCVMultilibs;
1731 static void findRISCVMultilibs(const Driver &D,
1732 const llvm::Triple &TargetTriple, StringRef Path,
1733 const ArgList &Args, DetectedMultilibs &Result) {
1734 if (TargetTriple.getOS() == llvm::Triple::UnknownOS)
1735 return findRISCVBareMetalMultilibs(D, TargetTriple, Path, Args, Result);
1737 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1738 Multilib Ilp32 = makeMultilib("lib32/ilp32").flag("+m32").flag("+mabi=ilp32");
1739 Multilib Ilp32f =
1740 makeMultilib("lib32/ilp32f").flag("+m32").flag("+mabi=ilp32f");
1741 Multilib Ilp32d =
1742 makeMultilib("lib32/ilp32d").flag("+m32").flag("+mabi=ilp32d");
1743 Multilib Lp64 = makeMultilib("lib64/lp64").flag("+m64").flag("+mabi=lp64");
1744 Multilib Lp64f = makeMultilib("lib64/lp64f").flag("+m64").flag("+mabi=lp64f");
1745 Multilib Lp64d = makeMultilib("lib64/lp64d").flag("+m64").flag("+mabi=lp64d");
1746 MultilibSet RISCVMultilibs =
1747 MultilibSet()
1748 .Either({Ilp32, Ilp32f, Ilp32d, Lp64, Lp64f, Lp64d})
1749 .FilterOut(NonExistent);
1751 Multilib::flags_list Flags;
1752 bool IsRV64 = TargetTriple.getArch() == llvm::Triple::riscv64;
1753 StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple);
1755 addMultilibFlag(!IsRV64, "m32", Flags);
1756 addMultilibFlag(IsRV64, "m64", Flags);
1757 addMultilibFlag(ABIName == "ilp32", "mabi=ilp32", Flags);
1758 addMultilibFlag(ABIName == "ilp32f", "mabi=ilp32f", Flags);
1759 addMultilibFlag(ABIName == "ilp32d", "mabi=ilp32d", Flags);
1760 addMultilibFlag(ABIName == "lp64", "mabi=lp64", Flags);
1761 addMultilibFlag(ABIName == "lp64f", "mabi=lp64f", Flags);
1762 addMultilibFlag(ABIName == "lp64d", "mabi=lp64d", Flags);
1764 if (RISCVMultilibs.select(Flags, Result.SelectedMultilib))
1765 Result.Multilibs = RISCVMultilibs;
1768 static bool findBiarchMultilibs(const Driver &D,
1769 const llvm::Triple &TargetTriple,
1770 StringRef Path, const ArgList &Args,
1771 bool NeedsBiarchSuffix,
1772 DetectedMultilibs &Result) {
1773 Multilib Default;
1775 // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1776 // in what would normally be GCCInstallPath and put the 64-bit
1777 // libs in a subdirectory named 64. The simple logic we follow is that
1778 // *if* there is a subdirectory of the right name with crtbegin.o in it,
1779 // we use that. If not, and if not a biarch triple alias, we look for
1780 // crtbegin.o without the subdirectory.
1782 StringRef Suff64 = "/64";
1783 // Solaris uses platform-specific suffixes instead of /64.
1784 if (TargetTriple.getOS() == llvm::Triple::Solaris) {
1785 switch (TargetTriple.getArch()) {
1786 case llvm::Triple::x86:
1787 case llvm::Triple::x86_64:
1788 Suff64 = "/amd64";
1789 break;
1790 case llvm::Triple::sparc:
1791 case llvm::Triple::sparcv9:
1792 Suff64 = "/sparcv9";
1793 break;
1794 default:
1795 break;
1799 Multilib Alt64 = Multilib()
1800 .gccSuffix(Suff64)
1801 .includeSuffix(Suff64)
1802 .flag("-m32")
1803 .flag("+m64")
1804 .flag("-mx32");
1805 Multilib Alt32 = Multilib()
1806 .gccSuffix("/32")
1807 .includeSuffix("/32")
1808 .flag("+m32")
1809 .flag("-m64")
1810 .flag("-mx32");
1811 Multilib Altx32 = Multilib()
1812 .gccSuffix("/x32")
1813 .includeSuffix("/x32")
1814 .flag("-m32")
1815 .flag("-m64")
1816 .flag("+mx32");
1818 // GCC toolchain for IAMCU doesn't have crtbegin.o, so look for libgcc.a.
1819 FilterNonExistent NonExistent(
1820 Path, TargetTriple.isOSIAMCU() ? "/libgcc.a" : "/crtbegin.o", D.getVFS());
1822 // Determine default multilib from: 32, 64, x32
1823 // Also handle cases such as 64 on 32, 32 on 64, etc.
1824 enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
1825 const bool IsX32 = TargetTriple.isX32();
1826 if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
1827 Want = WANT64;
1828 else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
1829 Want = WANT64;
1830 else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
1831 Want = WANT32;
1832 else {
1833 if (TargetTriple.isArch32Bit())
1834 Want = NeedsBiarchSuffix ? WANT64 : WANT32;
1835 else if (IsX32)
1836 Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
1837 else
1838 Want = NeedsBiarchSuffix ? WANT32 : WANT64;
1841 if (Want == WANT32)
1842 Default.flag("+m32").flag("-m64").flag("-mx32");
1843 else if (Want == WANT64)
1844 Default.flag("-m32").flag("+m64").flag("-mx32");
1845 else if (Want == WANTX32)
1846 Default.flag("-m32").flag("-m64").flag("+mx32");
1847 else
1848 return false;
1850 Result.Multilibs.push_back(Default);
1851 Result.Multilibs.push_back(Alt64);
1852 Result.Multilibs.push_back(Alt32);
1853 Result.Multilibs.push_back(Altx32);
1855 Result.Multilibs.FilterOut(NonExistent);
1857 Multilib::flags_list Flags;
1858 addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "m64", Flags);
1859 addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags);
1860 addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "mx32", Flags);
1862 if (!Result.Multilibs.select(Flags, Result.SelectedMultilib))
1863 return false;
1865 if (Result.SelectedMultilib == Alt64 || Result.SelectedMultilib == Alt32 ||
1866 Result.SelectedMultilib == Altx32)
1867 Result.BiarchSibling = Default;
1869 return true;
1872 /// Generic_GCC - A tool chain using the 'gcc' command to perform
1873 /// all subcommands; this relies on gcc translating the majority of
1874 /// command line options.
1876 /// Less-than for GCCVersion, implementing a Strict Weak Ordering.
1877 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
1878 int RHSPatch,
1879 StringRef RHSPatchSuffix) const {
1880 if (Major != RHSMajor)
1881 return Major < RHSMajor;
1882 if (Minor != RHSMinor)
1883 return Minor < RHSMinor;
1884 if (Patch != RHSPatch) {
1885 // Note that versions without a specified patch sort higher than those with
1886 // a patch.
1887 if (RHSPatch == -1)
1888 return true;
1889 if (Patch == -1)
1890 return false;
1892 // Otherwise just sort on the patch itself.
1893 return Patch < RHSPatch;
1895 if (PatchSuffix != RHSPatchSuffix) {
1896 // Sort empty suffixes higher.
1897 if (RHSPatchSuffix.empty())
1898 return true;
1899 if (PatchSuffix.empty())
1900 return false;
1902 // Provide a lexicographic sort to make this a total ordering.
1903 return PatchSuffix < RHSPatchSuffix;
1906 // The versions are equal.
1907 return false;
1910 /// Parse a GCCVersion object out of a string of text.
1912 /// This is the primary means of forming GCCVersion objects.
1913 /*static*/
1914 Generic_GCC::GCCVersion Generic_GCC::GCCVersion::Parse(StringRef VersionText) {
1915 const GCCVersion BadVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1916 std::pair<StringRef, StringRef> First = VersionText.split('.');
1917 std::pair<StringRef, StringRef> Second = First.second.split('.');
1919 GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1920 if (First.first.getAsInteger(10, GoodVersion.Major) || GoodVersion.Major < 0)
1921 return BadVersion;
1922 GoodVersion.MajorStr = First.first.str();
1923 if (First.second.empty())
1924 return GoodVersion;
1925 StringRef MinorStr = Second.first;
1926 if (Second.second.empty()) {
1927 if (size_t EndNumber = MinorStr.find_first_not_of("0123456789")) {
1928 GoodVersion.PatchSuffix = std::string(MinorStr.substr(EndNumber));
1929 MinorStr = MinorStr.slice(0, EndNumber);
1932 if (MinorStr.getAsInteger(10, GoodVersion.Minor) || GoodVersion.Minor < 0)
1933 return BadVersion;
1934 GoodVersion.MinorStr = MinorStr.str();
1936 // First look for a number prefix and parse that if present. Otherwise just
1937 // stash the entire patch string in the suffix, and leave the number
1938 // unspecified. This covers versions strings such as:
1939 // 5 (handled above)
1940 // 4.4
1941 // 4.4-patched
1942 // 4.4.0
1943 // 4.4.x
1944 // 4.4.2-rc4
1945 // 4.4.x-patched
1946 // And retains any patch number it finds.
1947 StringRef PatchText = Second.second;
1948 if (!PatchText.empty()) {
1949 if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
1950 // Try to parse the number and any suffix.
1951 if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
1952 GoodVersion.Patch < 0)
1953 return BadVersion;
1954 GoodVersion.PatchSuffix = std::string(PatchText.substr(EndNumber));
1958 return GoodVersion;
1961 static llvm::StringRef getGCCToolchainDir(const ArgList &Args,
1962 llvm::StringRef SysRoot) {
1963 const Arg *A = Args.getLastArg(clang::driver::options::OPT_gcc_toolchain);
1964 if (A)
1965 return A->getValue();
1967 // If we have a SysRoot, ignore GCC_INSTALL_PREFIX.
1968 // GCC_INSTALL_PREFIX specifies the gcc installation for the default
1969 // sysroot and is likely not valid with a different sysroot.
1970 if (!SysRoot.empty())
1971 return "";
1973 return GCC_INSTALL_PREFIX;
1976 /// Initialize a GCCInstallationDetector from the driver.
1978 /// This performs all of the autodetection and sets up the various paths.
1979 /// Once constructed, a GCCInstallationDetector is essentially immutable.
1981 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1982 /// should instead pull the target out of the driver. This is currently
1983 /// necessary because the driver doesn't store the final version of the target
1984 /// triple.
1985 void Generic_GCC::GCCInstallationDetector::init(
1986 const llvm::Triple &TargetTriple, const ArgList &Args,
1987 ArrayRef<std::string> ExtraTripleAliases) {
1988 llvm::Triple BiarchVariantTriple = TargetTriple.isArch32Bit()
1989 ? TargetTriple.get64BitArchVariant()
1990 : TargetTriple.get32BitArchVariant();
1991 // The library directories which may contain GCC installations.
1992 SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
1993 // The compatible GCC triples for this particular architecture.
1994 SmallVector<StringRef, 16> CandidateTripleAliases;
1995 SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
1996 CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
1997 CandidateTripleAliases, CandidateBiarchLibDirs,
1998 CandidateBiarchTripleAliases);
2000 // Compute the set of prefixes for our search.
2001 SmallVector<std::string, 8> Prefixes;
2002 StringRef GCCToolchainDir = getGCCToolchainDir(Args, D.SysRoot);
2003 if (GCCToolchainDir != "") {
2004 if (GCCToolchainDir.back() == '/')
2005 GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
2007 Prefixes.push_back(std::string(GCCToolchainDir));
2008 } else {
2009 // If we have a SysRoot, try that first.
2010 if (!D.SysRoot.empty()) {
2011 Prefixes.push_back(D.SysRoot);
2012 AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
2015 // Then look for gcc installed alongside clang.
2016 Prefixes.push_back(D.InstalledDir + "/..");
2018 // Next, look for prefix(es) that correspond to distribution-supplied gcc
2019 // installations.
2020 if (D.SysRoot.empty()) {
2021 // Typically /usr.
2022 AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
2025 // Try to respect gcc-config on Gentoo if --gcc-toolchain is not provided.
2026 // This avoids accidentally enforcing the system GCC version when using a
2027 // custom toolchain.
2028 SmallVector<StringRef, 16> GentooTestTriples;
2029 // Try to match an exact triple as target triple first.
2030 // e.g. crossdev -S x86_64-gentoo-linux-gnu will install gcc libs for
2031 // x86_64-gentoo-linux-gnu. But "clang -target x86_64-gentoo-linux-gnu"
2032 // may pick the libraries for x86_64-pc-linux-gnu even when exact matching
2033 // triple x86_64-gentoo-linux-gnu is present.
2034 GentooTestTriples.push_back(TargetTriple.str());
2035 // Check rest of triples.
2036 GentooTestTriples.append(ExtraTripleAliases.begin(),
2037 ExtraTripleAliases.end());
2038 GentooTestTriples.append(CandidateTripleAliases.begin(),
2039 CandidateTripleAliases.end());
2040 if (ScanGentooConfigs(TargetTriple, Args, GentooTestTriples,
2041 CandidateBiarchTripleAliases))
2042 return;
2045 // Loop over the various components which exist and select the best GCC
2046 // installation available. GCC installs are ranked by version number.
2047 const GCCVersion VersionZero = GCCVersion::Parse("0.0.0");
2048 Version = VersionZero;
2049 for (const std::string &Prefix : Prefixes) {
2050 auto &VFS = D.getVFS();
2051 if (!VFS.exists(Prefix))
2052 continue;
2053 for (StringRef Suffix : CandidateLibDirs) {
2054 const std::string LibDir = concat(Prefix, Suffix);
2055 if (!VFS.exists(LibDir))
2056 continue;
2057 // Maybe filter out <libdir>/gcc and <libdir>/gcc-cross.
2058 bool GCCDirExists = VFS.exists(LibDir + "/gcc");
2059 bool GCCCrossDirExists = VFS.exists(LibDir + "/gcc-cross");
2060 // Try to match the exact target triple first.
2061 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, TargetTriple.str(),
2062 false, GCCDirExists, GCCCrossDirExists);
2063 // Try rest of possible triples.
2064 for (StringRef Candidate : ExtraTripleAliases) // Try these first.
2065 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, false,
2066 GCCDirExists, GCCCrossDirExists);
2067 for (StringRef Candidate : CandidateTripleAliases)
2068 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, false,
2069 GCCDirExists, GCCCrossDirExists);
2071 for (StringRef Suffix : CandidateBiarchLibDirs) {
2072 const std::string LibDir = Prefix + Suffix.str();
2073 if (!VFS.exists(LibDir))
2074 continue;
2075 bool GCCDirExists = VFS.exists(LibDir + "/gcc");
2076 bool GCCCrossDirExists = VFS.exists(LibDir + "/gcc-cross");
2077 for (StringRef Candidate : CandidateBiarchTripleAliases)
2078 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, true,
2079 GCCDirExists, GCCCrossDirExists);
2082 // Skip other prefixes once a GCC installation is found.
2083 if (Version > VersionZero)
2084 break;
2088 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
2089 for (const auto &InstallPath : CandidateGCCInstallPaths)
2090 OS << "Found candidate GCC installation: " << InstallPath << "\n";
2092 if (!GCCInstallPath.empty())
2093 OS << "Selected GCC installation: " << GCCInstallPath << "\n";
2095 for (const auto &Multilib : Multilibs)
2096 OS << "Candidate multilib: " << Multilib << "\n";
2098 if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
2099 OS << "Selected multilib: " << SelectedMultilib << "\n";
2102 bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const {
2103 if (BiarchSibling) {
2104 M = BiarchSibling.value();
2105 return true;
2107 return false;
2110 void Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes(
2111 const llvm::Triple &TargetTriple, SmallVectorImpl<std::string> &Prefixes,
2112 StringRef SysRoot) {
2113 if (TargetTriple.getOS() == llvm::Triple::Solaris) {
2114 // Solaris is a special case.
2115 // The GCC installation is under
2116 // /usr/gcc/<major>.<minor>/lib/gcc/<triple>/<major>.<minor>.<patch>/
2117 // so we need to find those /usr/gcc/*/lib/gcc libdirs and go with
2118 // /usr/gcc/<version> as a prefix.
2120 std::string PrefixDir = concat(SysRoot, "/usr/gcc");
2121 std::error_code EC;
2122 for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin(PrefixDir, EC),
2124 !EC && LI != LE; LI = LI.increment(EC)) {
2125 StringRef VersionText = llvm::sys::path::filename(LI->path());
2126 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2128 // Filter out obviously bad entries.
2129 if (CandidateVersion.Major == -1 || CandidateVersion.isOlderThan(4, 1, 1))
2130 continue;
2132 std::string CandidatePrefix = PrefixDir + "/" + VersionText.str();
2133 std::string CandidateLibPath = CandidatePrefix + "/lib/gcc";
2134 if (!D.getVFS().exists(CandidateLibPath))
2135 continue;
2137 Prefixes.push_back(CandidatePrefix);
2139 return;
2142 // For Linux, if --sysroot is not specified, look for RHEL/CentOS devtoolsets
2143 // and gcc-toolsets.
2144 if (SysRoot.empty() && TargetTriple.getOS() == llvm::Triple::Linux &&
2145 D.getVFS().exists("/opt/rh")) {
2146 // Find the directory in /opt/rh/ starting with gcc-toolset-* or
2147 // devtoolset-* with the highest version number and add that
2148 // one to our prefixes.
2149 std::string ChosenToolsetDir;
2150 unsigned ChosenToolsetVersion = 0;
2151 std::error_code EC;
2152 for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin("/opt/rh", EC),
2154 !EC && LI != LE; LI = LI.increment(EC)) {
2155 StringRef ToolsetDir = llvm::sys::path::filename(LI->path());
2156 unsigned ToolsetVersion;
2157 if ((!ToolsetDir.startswith("gcc-toolset-") &&
2158 !ToolsetDir.startswith("devtoolset-")) ||
2159 ToolsetDir.substr(ToolsetDir.rfind('-') + 1)
2160 .getAsInteger(10, ToolsetVersion))
2161 continue;
2163 if (ToolsetVersion > ChosenToolsetVersion) {
2164 ChosenToolsetVersion = ToolsetVersion;
2165 ChosenToolsetDir = "/opt/rh/" + ToolsetDir.str();
2169 if (ChosenToolsetVersion > 0)
2170 Prefixes.push_back(ChosenToolsetDir + "/root/usr");
2173 // Fall back to /usr which is used by most non-Solaris systems.
2174 Prefixes.push_back(concat(SysRoot, "/usr"));
2177 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
2178 const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
2179 SmallVectorImpl<StringRef> &LibDirs,
2180 SmallVectorImpl<StringRef> &TripleAliases,
2181 SmallVectorImpl<StringRef> &BiarchLibDirs,
2182 SmallVectorImpl<StringRef> &BiarchTripleAliases) {
2183 // Declare a bunch of static data sets that we'll select between below. These
2184 // are specifically designed to always refer to string literals to avoid any
2185 // lifetime or initialization issues.
2187 // The *Triples variables hard code some triples so that, for example,
2188 // --target=aarch64 (incomplete triple) can detect lib/aarch64-linux-gnu.
2189 // They are not needed when the user has correct LLVM_DEFAULT_TARGET_TRIPLE
2190 // and always uses the full --target (e.g. --target=aarch64-linux-gnu). The
2191 // lists should shrink over time. Please don't add more elements to *Triples.
2192 static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
2193 static const char *const AArch64Triples[] = {
2194 "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-redhat-linux",
2195 "aarch64-suse-linux"};
2196 static const char *const AArch64beLibDirs[] = {"/lib"};
2197 static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu",
2198 "aarch64_be-linux-gnu"};
2200 static const char *const ARMLibDirs[] = {"/lib"};
2201 static const char *const ARMTriples[] = {"arm-linux-gnueabi"};
2202 static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf",
2203 "armv7hl-redhat-linux-gnueabi",
2204 "armv6hl-suse-linux-gnueabi",
2205 "armv7hl-suse-linux-gnueabi"};
2206 static const char *const ARMebLibDirs[] = {"/lib"};
2207 static const char *const ARMebTriples[] = {"armeb-linux-gnueabi"};
2208 static const char *const ARMebHFTriples[] = {
2209 "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
2211 static const char *const AVRLibDirs[] = {"/lib"};
2212 static const char *const AVRTriples[] = {"avr"};
2214 static const char *const CSKYLibDirs[] = {"/lib"};
2215 static const char *const CSKYTriples[] = {
2216 "csky-linux-gnuabiv2", "csky-linux-uclibcabiv2", "csky-elf-noneabiv2"};
2218 static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
2219 static const char *const X86_64Triples[] = {
2220 "x86_64-linux-gnu", "x86_64-unknown-linux-gnu",
2221 "x86_64-pc-linux-gnu", "x86_64-redhat-linux6E",
2222 "x86_64-redhat-linux", "x86_64-suse-linux",
2223 "x86_64-manbo-linux-gnu", "x86_64-linux-gnu",
2224 "x86_64-slackware-linux", "x86_64-unknown-linux",
2225 "x86_64-amazon-linux"};
2226 static const char *const X32Triples[] = {"x86_64-linux-gnux32",
2227 "x86_64-pc-linux-gnux32"};
2228 static const char *const X32LibDirs[] = {"/libx32", "/lib"};
2229 static const char *const X86LibDirs[] = {"/lib32", "/lib"};
2230 static const char *const X86Triples[] = {
2231 "i586-linux-gnu", "i686-linux-gnu", "i686-pc-linux-gnu",
2232 "i386-redhat-linux6E", "i686-redhat-linux", "i386-redhat-linux",
2233 "i586-suse-linux", "i686-montavista-linux", "i686-gnu",
2236 static const char *const LoongArch64LibDirs[] = {"/lib64", "/lib"};
2237 static const char *const LoongArch64Triples[] = {
2238 "loongarch64-linux-gnu", "loongarch64-unknown-linux-gnu"};
2240 static const char *const M68kLibDirs[] = {"/lib"};
2241 static const char *const M68kTriples[] = {
2242 "m68k-linux-gnu", "m68k-unknown-linux-gnu", "m68k-suse-linux"};
2244 static const char *const MIPSLibDirs[] = {"/libo32", "/lib"};
2245 static const char *const MIPSTriples[] = {
2246 "mips-linux-gnu", "mips-mti-linux", "mips-mti-linux-gnu",
2247 "mips-img-linux-gnu", "mipsisa32r6-linux-gnu"};
2248 static const char *const MIPSELLibDirs[] = {"/libo32", "/lib"};
2249 static const char *const MIPSELTriples[] = {
2250 "mipsel-linux-gnu", "mips-img-linux-gnu", "mipsisa32r6el-linux-gnu"};
2252 static const char *const MIPS64LibDirs[] = {"/lib64", "/lib"};
2253 static const char *const MIPS64Triples[] = {
2254 "mips64-linux-gnu", "mips-mti-linux-gnu",
2255 "mips-img-linux-gnu", "mips64-linux-gnuabi64",
2256 "mipsisa64r6-linux-gnu", "mipsisa64r6-linux-gnuabi64"};
2257 static const char *const MIPS64ELLibDirs[] = {"/lib64", "/lib"};
2258 static const char *const MIPS64ELTriples[] = {
2259 "mips64el-linux-gnu", "mips-mti-linux-gnu",
2260 "mips-img-linux-gnu", "mips64el-linux-gnuabi64",
2261 "mipsisa64r6el-linux-gnu", "mipsisa64r6el-linux-gnuabi64"};
2263 static const char *const MIPSN32LibDirs[] = {"/lib32"};
2264 static const char *const MIPSN32Triples[] = {"mips64-linux-gnuabin32",
2265 "mipsisa64r6-linux-gnuabin32"};
2266 static const char *const MIPSN32ELLibDirs[] = {"/lib32"};
2267 static const char *const MIPSN32ELTriples[] = {
2268 "mips64el-linux-gnuabin32", "mipsisa64r6el-linux-gnuabin32"};
2270 static const char *const MSP430LibDirs[] = {"/lib"};
2271 static const char *const MSP430Triples[] = {"msp430-elf"};
2273 static const char *const PPCLibDirs[] = {"/lib32", "/lib"};
2274 static const char *const PPCTriples[] = {
2275 "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
2276 // On 32-bit PowerPC systems running SUSE Linux, gcc is configured as a
2277 // 64-bit compiler which defaults to "-m32", hence "powerpc64-suse-linux".
2278 "powerpc64-suse-linux", "powerpc-montavista-linuxspe"};
2279 static const char *const PPCLELibDirs[] = {"/lib32", "/lib"};
2280 static const char *const PPCLETriples[] = {"powerpcle-linux-gnu",
2281 "powerpcle-unknown-linux-gnu",
2282 "powerpcle-linux-musl"};
2284 static const char *const PPC64LibDirs[] = {"/lib64", "/lib"};
2285 static const char *const PPC64Triples[] = {
2286 "powerpc64-linux-gnu", "powerpc64-unknown-linux-gnu",
2287 "powerpc64-suse-linux", "ppc64-redhat-linux"};
2288 static const char *const PPC64LELibDirs[] = {"/lib64", "/lib"};
2289 static const char *const PPC64LETriples[] = {
2290 "powerpc64le-linux-gnu", "powerpc64le-unknown-linux-gnu",
2291 "powerpc64le-none-linux-gnu", "powerpc64le-suse-linux",
2292 "ppc64le-redhat-linux"};
2294 static const char *const RISCV32LibDirs[] = {"/lib32", "/lib"};
2295 static const char *const RISCV32Triples[] = {"riscv32-unknown-linux-gnu",
2296 "riscv32-linux-gnu",
2297 "riscv32-unknown-elf"};
2298 static const char *const RISCV64LibDirs[] = {"/lib64", "/lib"};
2299 static const char *const RISCV64Triples[] = {"riscv64-unknown-linux-gnu",
2300 "riscv64-linux-gnu",
2301 "riscv64-unknown-elf"};
2303 static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"};
2304 static const char *const SPARCv8Triples[] = {"sparc-linux-gnu",
2305 "sparcv8-linux-gnu"};
2306 static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"};
2307 static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu",
2308 "sparcv9-linux-gnu"};
2310 static const char *const SystemZLibDirs[] = {"/lib64", "/lib"};
2311 static const char *const SystemZTriples[] = {
2312 "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
2313 "s390x-suse-linux", "s390x-redhat-linux"};
2316 using std::begin;
2317 using std::end;
2319 if (TargetTriple.getOS() == llvm::Triple::Solaris) {
2320 static const char *const SolarisLibDirs[] = {"/lib"};
2321 static const char *const SolarisSparcV8Triples[] = {
2322 "sparc-sun-solaris2.11", "sparc-sun-solaris2.12"};
2323 static const char *const SolarisSparcV9Triples[] = {
2324 "sparcv9-sun-solaris2.11", "sparcv9-sun-solaris2.12"};
2325 static const char *const SolarisX86Triples[] = {"i386-pc-solaris2.11",
2326 "i386-pc-solaris2.12"};
2327 static const char *const SolarisX86_64Triples[] = {"x86_64-pc-solaris2.11",
2328 "x86_64-pc-solaris2.12"};
2329 LibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
2330 BiarchLibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
2331 switch (TargetTriple.getArch()) {
2332 case llvm::Triple::x86:
2333 TripleAliases.append(begin(SolarisX86Triples), end(SolarisX86Triples));
2334 BiarchTripleAliases.append(begin(SolarisX86_64Triples),
2335 end(SolarisX86_64Triples));
2336 break;
2337 case llvm::Triple::x86_64:
2338 TripleAliases.append(begin(SolarisX86_64Triples),
2339 end(SolarisX86_64Triples));
2340 BiarchTripleAliases.append(begin(SolarisX86Triples),
2341 end(SolarisX86Triples));
2342 break;
2343 case llvm::Triple::sparc:
2344 TripleAliases.append(begin(SolarisSparcV8Triples),
2345 end(SolarisSparcV8Triples));
2346 BiarchTripleAliases.append(begin(SolarisSparcV9Triples),
2347 end(SolarisSparcV9Triples));
2348 break;
2349 case llvm::Triple::sparcv9:
2350 TripleAliases.append(begin(SolarisSparcV9Triples),
2351 end(SolarisSparcV9Triples));
2352 BiarchTripleAliases.append(begin(SolarisSparcV8Triples),
2353 end(SolarisSparcV8Triples));
2354 break;
2355 default:
2356 break;
2358 return;
2361 // Android targets should not use GNU/Linux tools or libraries.
2362 if (TargetTriple.isAndroid()) {
2363 static const char *const AArch64AndroidTriples[] = {
2364 "aarch64-linux-android"};
2365 static const char *const ARMAndroidTriples[] = {"arm-linux-androideabi"};
2366 static const char *const MIPSELAndroidTriples[] = {"mipsel-linux-android"};
2367 static const char *const MIPS64ELAndroidTriples[] = {
2368 "mips64el-linux-android"};
2369 static const char *const X86AndroidTriples[] = {"i686-linux-android"};
2370 static const char *const X86_64AndroidTriples[] = {"x86_64-linux-android"};
2372 switch (TargetTriple.getArch()) {
2373 case llvm::Triple::aarch64:
2374 LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2375 TripleAliases.append(begin(AArch64AndroidTriples),
2376 end(AArch64AndroidTriples));
2377 break;
2378 case llvm::Triple::arm:
2379 case llvm::Triple::thumb:
2380 LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
2381 TripleAliases.append(begin(ARMAndroidTriples), end(ARMAndroidTriples));
2382 break;
2383 case llvm::Triple::mipsel:
2384 LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2385 TripleAliases.append(begin(MIPSELAndroidTriples),
2386 end(MIPSELAndroidTriples));
2387 BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2388 BiarchTripleAliases.append(begin(MIPS64ELAndroidTriples),
2389 end(MIPS64ELAndroidTriples));
2390 break;
2391 case llvm::Triple::mips64el:
2392 LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2393 TripleAliases.append(begin(MIPS64ELAndroidTriples),
2394 end(MIPS64ELAndroidTriples));
2395 BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2396 BiarchTripleAliases.append(begin(MIPSELAndroidTriples),
2397 end(MIPSELAndroidTriples));
2398 break;
2399 case llvm::Triple::x86_64:
2400 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2401 TripleAliases.append(begin(X86_64AndroidTriples),
2402 end(X86_64AndroidTriples));
2403 BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2404 BiarchTripleAliases.append(begin(X86AndroidTriples),
2405 end(X86AndroidTriples));
2406 break;
2407 case llvm::Triple::x86:
2408 LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2409 TripleAliases.append(begin(X86AndroidTriples), end(X86AndroidTriples));
2410 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2411 BiarchTripleAliases.append(begin(X86_64AndroidTriples),
2412 end(X86_64AndroidTriples));
2413 break;
2414 default:
2415 break;
2418 return;
2421 switch (TargetTriple.getArch()) {
2422 case llvm::Triple::aarch64:
2423 LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2424 TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
2425 BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2426 BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
2427 break;
2428 case llvm::Triple::aarch64_be:
2429 LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
2430 TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
2431 BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
2432 BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
2433 break;
2434 case llvm::Triple::arm:
2435 case llvm::Triple::thumb:
2436 LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
2437 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2438 TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
2439 } else {
2440 TripleAliases.append(begin(ARMTriples), end(ARMTriples));
2442 break;
2443 case llvm::Triple::armeb:
2444 case llvm::Triple::thumbeb:
2445 LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
2446 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2447 TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
2448 } else {
2449 TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
2451 break;
2452 case llvm::Triple::avr:
2453 LibDirs.append(begin(AVRLibDirs), end(AVRLibDirs));
2454 TripleAliases.append(begin(AVRTriples), end(AVRTriples));
2455 break;
2456 case llvm::Triple::csky:
2457 LibDirs.append(begin(CSKYLibDirs), end(CSKYLibDirs));
2458 TripleAliases.append(begin(CSKYTriples), end(CSKYTriples));
2459 break;
2460 case llvm::Triple::x86_64:
2461 if (TargetTriple.isX32()) {
2462 LibDirs.append(begin(X32LibDirs), end(X32LibDirs));
2463 TripleAliases.append(begin(X32Triples), end(X32Triples));
2464 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2465 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2466 } else {
2467 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2468 TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2469 BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
2470 BiarchTripleAliases.append(begin(X32Triples), end(X32Triples));
2472 BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2473 BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
2474 break;
2475 case llvm::Triple::x86:
2476 LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2477 // MCU toolchain is 32 bit only and its triple alias is TargetTriple
2478 // itself, which will be appended below.
2479 if (!TargetTriple.isOSIAMCU()) {
2480 TripleAliases.append(begin(X86Triples), end(X86Triples));
2481 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2482 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2483 BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
2484 BiarchTripleAliases.append(begin(X32Triples), end(X32Triples));
2486 break;
2487 // TODO: Handle loongarch32.
2488 case llvm::Triple::loongarch64:
2489 LibDirs.append(begin(LoongArch64LibDirs), end(LoongArch64LibDirs));
2490 TripleAliases.append(begin(LoongArch64Triples), end(LoongArch64Triples));
2491 break;
2492 case llvm::Triple::m68k:
2493 LibDirs.append(begin(M68kLibDirs), end(M68kLibDirs));
2494 TripleAliases.append(begin(M68kTriples), end(M68kTriples));
2495 break;
2496 case llvm::Triple::mips:
2497 LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
2498 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2499 BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
2500 BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
2501 BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs));
2502 BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples));
2503 break;
2504 case llvm::Triple::mipsel:
2505 LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2506 TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
2507 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2508 BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2509 BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
2510 BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs));
2511 BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples));
2512 break;
2513 case llvm::Triple::mips64:
2514 LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
2515 TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
2516 BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
2517 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2518 BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs));
2519 BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples));
2520 break;
2521 case llvm::Triple::mips64el:
2522 LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2523 TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
2524 BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2525 BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
2526 BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs));
2527 BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples));
2528 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2529 break;
2530 case llvm::Triple::msp430:
2531 LibDirs.append(begin(MSP430LibDirs), end(MSP430LibDirs));
2532 TripleAliases.append(begin(MSP430Triples), end(MSP430Triples));
2533 break;
2534 case llvm::Triple::ppc:
2535 LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
2536 TripleAliases.append(begin(PPCTriples), end(PPCTriples));
2537 BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
2538 BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
2539 break;
2540 case llvm::Triple::ppcle:
2541 LibDirs.append(begin(PPCLELibDirs), end(PPCLELibDirs));
2542 TripleAliases.append(begin(PPCLETriples), end(PPCLETriples));
2543 BiarchLibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
2544 BiarchTripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
2545 break;
2546 case llvm::Triple::ppc64:
2547 LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
2548 TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
2549 BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
2550 BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
2551 break;
2552 case llvm::Triple::ppc64le:
2553 LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
2554 TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
2555 BiarchLibDirs.append(begin(PPCLELibDirs), end(PPCLELibDirs));
2556 BiarchTripleAliases.append(begin(PPCLETriples), end(PPCLETriples));
2557 break;
2558 case llvm::Triple::riscv32:
2559 LibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
2560 TripleAliases.append(begin(RISCV32Triples), end(RISCV32Triples));
2561 BiarchLibDirs.append(begin(RISCV64LibDirs), end(RISCV64LibDirs));
2562 BiarchTripleAliases.append(begin(RISCV64Triples), end(RISCV64Triples));
2563 break;
2564 case llvm::Triple::riscv64:
2565 LibDirs.append(begin(RISCV64LibDirs), end(RISCV64LibDirs));
2566 TripleAliases.append(begin(RISCV64Triples), end(RISCV64Triples));
2567 BiarchLibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
2568 BiarchTripleAliases.append(begin(RISCV32Triples), end(RISCV32Triples));
2569 break;
2570 case llvm::Triple::sparc:
2571 case llvm::Triple::sparcel:
2572 LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
2573 TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
2574 BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
2575 BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
2576 break;
2577 case llvm::Triple::sparcv9:
2578 LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
2579 TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
2580 BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
2581 BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
2582 break;
2583 case llvm::Triple::systemz:
2584 LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
2585 TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
2586 break;
2587 default:
2588 // By default, just rely on the standard lib directories and the original
2589 // triple.
2590 break;
2593 // Always append the drivers target triple to the end, in case it doesn't
2594 // match any of our aliases.
2595 TripleAliases.push_back(TargetTriple.str());
2597 // Also include the multiarch variant if it's different.
2598 if (TargetTriple.str() != BiarchTriple.str())
2599 BiarchTripleAliases.push_back(BiarchTriple.str());
2602 bool Generic_GCC::GCCInstallationDetector::ScanGCCForMultilibs(
2603 const llvm::Triple &TargetTriple, const ArgList &Args,
2604 StringRef Path, bool NeedsBiarchSuffix) {
2605 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2606 DetectedMultilibs Detected;
2608 // Android standalone toolchain could have multilibs for ARM and Thumb.
2609 // Debian mips multilibs behave more like the rest of the biarch ones,
2610 // so handle them there
2611 if (isArmOrThumbArch(TargetArch) && TargetTriple.isAndroid()) {
2612 // It should also work without multilibs in a simplified toolchain.
2613 findAndroidArmMultilibs(D, TargetTriple, Path, Args, Detected);
2614 } else if (TargetTriple.isCSKY()) {
2615 findCSKYMultilibs(D, TargetTriple, Path, Args, Detected);
2616 } else if (TargetTriple.isMIPS()) {
2617 if (!findMIPSMultilibs(D, TargetTriple, Path, Args, Detected))
2618 return false;
2619 } else if (TargetTriple.isRISCV()) {
2620 findRISCVMultilibs(D, TargetTriple, Path, Args, Detected);
2621 } else if (isMSP430(TargetArch)) {
2622 findMSP430Multilibs(D, TargetTriple, Path, Args, Detected);
2623 } else if (TargetArch == llvm::Triple::avr) {
2624 // AVR has no multilibs.
2625 } else if (!findBiarchMultilibs(D, TargetTriple, Path, Args,
2626 NeedsBiarchSuffix, Detected)) {
2627 return false;
2630 Multilibs = Detected.Multilibs;
2631 SelectedMultilib = Detected.SelectedMultilib;
2632 BiarchSibling = Detected.BiarchSibling;
2634 return true;
2637 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
2638 const llvm::Triple &TargetTriple, const ArgList &Args,
2639 const std::string &LibDir, StringRef CandidateTriple,
2640 bool NeedsBiarchSuffix, bool GCCDirExists, bool GCCCrossDirExists) {
2641 // Locations relative to the system lib directory where GCC's triple-specific
2642 // directories might reside.
2643 struct GCCLibSuffix {
2644 // Path from system lib directory to GCC triple-specific directory.
2645 std::string LibSuffix;
2646 // Path from GCC triple-specific directory back to system lib directory.
2647 // This is one '..' component per component in LibSuffix.
2648 StringRef ReversePath;
2649 // Whether this library suffix is relevant for the triple.
2650 bool Active;
2651 } Suffixes[] = {
2652 // This is the normal place.
2653 {"gcc/" + CandidateTriple.str(), "../..", GCCDirExists},
2655 // Debian puts cross-compilers in gcc-cross.
2656 {"gcc-cross/" + CandidateTriple.str(), "../..", GCCCrossDirExists},
2658 // The Freescale PPC SDK has the gcc libraries in
2659 // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well. Only do
2660 // this on Freescale triples, though, since some systems put a *lot* of
2661 // files in that location, not just GCC installation data.
2662 {CandidateTriple.str(), "..",
2663 TargetTriple.getVendor() == llvm::Triple::Freescale ||
2664 TargetTriple.getVendor() == llvm::Triple::OpenEmbedded}};
2666 for (auto &Suffix : Suffixes) {
2667 if (!Suffix.Active)
2668 continue;
2670 StringRef LibSuffix = Suffix.LibSuffix;
2671 std::error_code EC;
2672 for (llvm::vfs::directory_iterator
2673 LI = D.getVFS().dir_begin(LibDir + "/" + LibSuffix, EC),
2675 !EC && LI != LE; LI = LI.increment(EC)) {
2676 StringRef VersionText = llvm::sys::path::filename(LI->path());
2677 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2678 if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2679 if (!CandidateGCCInstallPaths.insert(std::string(LI->path())).second)
2680 continue; // Saw this path before; no need to look at it again.
2681 if (CandidateVersion.isOlderThan(4, 1, 1))
2682 continue;
2683 if (CandidateVersion <= Version)
2684 continue;
2686 if (!ScanGCCForMultilibs(TargetTriple, Args, LI->path(),
2687 NeedsBiarchSuffix))
2688 continue;
2690 Version = CandidateVersion;
2691 GCCTriple.setTriple(CandidateTriple);
2692 // FIXME: We hack together the directory name here instead of
2693 // using LI to ensure stable path separators across Windows and
2694 // Linux.
2695 GCCInstallPath = (LibDir + "/" + LibSuffix + "/" + VersionText).str();
2696 GCCParentLibPath = (GCCInstallPath + "/../" + Suffix.ReversePath).str();
2697 IsValid = true;
2702 bool Generic_GCC::GCCInstallationDetector::ScanGentooConfigs(
2703 const llvm::Triple &TargetTriple, const ArgList &Args,
2704 const SmallVectorImpl<StringRef> &CandidateTriples,
2705 const SmallVectorImpl<StringRef> &CandidateBiarchTriples) {
2706 if (!D.getVFS().exists(concat(D.SysRoot, GentooConfigDir)))
2707 return false;
2709 for (StringRef CandidateTriple : CandidateTriples) {
2710 if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple))
2711 return true;
2714 for (StringRef CandidateTriple : CandidateBiarchTriples) {
2715 if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple, true))
2716 return true;
2718 return false;
2721 bool Generic_GCC::GCCInstallationDetector::ScanGentooGccConfig(
2722 const llvm::Triple &TargetTriple, const ArgList &Args,
2723 StringRef CandidateTriple, bool NeedsBiarchSuffix) {
2724 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
2725 D.getVFS().getBufferForFile(concat(D.SysRoot, GentooConfigDir,
2726 "/config-" + CandidateTriple.str()));
2727 if (File) {
2728 SmallVector<StringRef, 2> Lines;
2729 File.get()->getBuffer().split(Lines, "\n");
2730 for (StringRef Line : Lines) {
2731 Line = Line.trim();
2732 // CURRENT=triple-version
2733 if (!Line.consume_front("CURRENT="))
2734 continue;
2735 // Process the config file pointed to by CURRENT.
2736 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ConfigFile =
2737 D.getVFS().getBufferForFile(
2738 concat(D.SysRoot, GentooConfigDir, "/" + Line));
2739 std::pair<StringRef, StringRef> ActiveVersion = Line.rsplit('-');
2740 // List of paths to scan for libraries.
2741 SmallVector<StringRef, 4> GentooScanPaths;
2742 // Scan the Config file to find installed GCC libraries path.
2743 // Typical content of the GCC config file:
2744 // LDPATH="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x:/usr/lib/gcc/
2745 // (continued from previous line) x86_64-pc-linux-gnu/4.9.x/32"
2746 // MANPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/man"
2747 // INFOPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/info"
2748 // STDCXX_INCDIR="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x/include/g++-v4"
2749 // We are looking for the paths listed in LDPATH=... .
2750 if (ConfigFile) {
2751 SmallVector<StringRef, 2> ConfigLines;
2752 ConfigFile.get()->getBuffer().split(ConfigLines, "\n");
2753 for (StringRef ConfLine : ConfigLines) {
2754 ConfLine = ConfLine.trim();
2755 if (ConfLine.consume_front("LDPATH=")) {
2756 // Drop '"' from front and back if present.
2757 ConfLine.consume_back("\"");
2758 ConfLine.consume_front("\"");
2759 // Get all paths sperated by ':'
2760 ConfLine.split(GentooScanPaths, ':', -1, /*AllowEmpty*/ false);
2764 // Test the path based on the version in /etc/env.d/gcc/config-{tuple}.
2765 std::string basePath = "/usr/lib/gcc/" + ActiveVersion.first.str() + "/"
2766 + ActiveVersion.second.str();
2767 GentooScanPaths.push_back(StringRef(basePath));
2769 // Scan all paths for GCC libraries.
2770 for (const auto &GentooScanPath : GentooScanPaths) {
2771 std::string GentooPath = concat(D.SysRoot, GentooScanPath);
2772 if (D.getVFS().exists(GentooPath + "/crtbegin.o")) {
2773 if (!ScanGCCForMultilibs(TargetTriple, Args, GentooPath,
2774 NeedsBiarchSuffix))
2775 continue;
2777 Version = GCCVersion::Parse(ActiveVersion.second);
2778 GCCInstallPath = GentooPath;
2779 GCCParentLibPath = GentooPath + std::string("/../../..");
2780 GCCTriple.setTriple(ActiveVersion.first);
2781 IsValid = true;
2782 return true;
2788 return false;
2791 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple,
2792 const ArgList &Args)
2793 : ToolChain(D, Triple, Args), GCCInstallation(D),
2794 CudaInstallation(D, Triple, Args), RocmInstallation(D, Triple, Args) {
2795 getProgramPaths().push_back(getDriver().getInstalledDir());
2796 if (getDriver().getInstalledDir() != getDriver().Dir)
2797 getProgramPaths().push_back(getDriver().Dir);
2800 Generic_GCC::~Generic_GCC() {}
2802 Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
2803 switch (AC) {
2804 case Action::PreprocessJobClass:
2805 if (!Preprocess)
2806 Preprocess.reset(new clang::driver::tools::gcc::Preprocessor(*this));
2807 return Preprocess.get();
2808 case Action::CompileJobClass:
2809 if (!Compile)
2810 Compile.reset(new tools::gcc::Compiler(*this));
2811 return Compile.get();
2812 default:
2813 return ToolChain::getTool(AC);
2817 Tool *Generic_GCC::buildAssembler() const {
2818 return new tools::gnutools::Assembler(*this);
2821 Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); }
2823 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
2824 // Print the information about how we detected the GCC installation.
2825 GCCInstallation.print(OS);
2826 CudaInstallation.print(OS);
2827 RocmInstallation.print(OS);
2830 bool Generic_GCC::IsUnwindTablesDefault(const ArgList &Args) const {
2831 switch (getArch()) {
2832 case llvm::Triple::aarch64:
2833 case llvm::Triple::ppc:
2834 case llvm::Triple::ppcle:
2835 case llvm::Triple::ppc64:
2836 case llvm::Triple::ppc64le:
2837 case llvm::Triple::x86:
2838 case llvm::Triple::x86_64:
2839 return true;
2840 default:
2841 return false;
2845 bool Generic_GCC::isPICDefault() const {
2846 switch (getArch()) {
2847 case llvm::Triple::x86_64:
2848 return getTriple().isOSWindows();
2849 case llvm::Triple::mips64:
2850 case llvm::Triple::mips64el:
2851 return true;
2852 default:
2853 return false;
2857 bool Generic_GCC::isPIEDefault(const llvm::opt::ArgList &Args) const {
2858 return false;
2861 bool Generic_GCC::isPICDefaultForced() const {
2862 return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
2865 bool Generic_GCC::IsIntegratedAssemblerDefault() const {
2866 switch (getTriple().getArch()) {
2867 case llvm::Triple::aarch64:
2868 case llvm::Triple::aarch64_be:
2869 case llvm::Triple::arm:
2870 case llvm::Triple::armeb:
2871 case llvm::Triple::avr:
2872 case llvm::Triple::bpfel:
2873 case llvm::Triple::bpfeb:
2874 case llvm::Triple::csky:
2875 case llvm::Triple::hexagon:
2876 case llvm::Triple::lanai:
2877 case llvm::Triple::loongarch32:
2878 case llvm::Triple::loongarch64:
2879 case llvm::Triple::m68k:
2880 case llvm::Triple::mips:
2881 case llvm::Triple::mipsel:
2882 case llvm::Triple::mips64:
2883 case llvm::Triple::mips64el:
2884 case llvm::Triple::msp430:
2885 case llvm::Triple::ppc:
2886 case llvm::Triple::ppcle:
2887 case llvm::Triple::ppc64:
2888 case llvm::Triple::ppc64le:
2889 case llvm::Triple::riscv32:
2890 case llvm::Triple::riscv64:
2891 case llvm::Triple::sparc:
2892 case llvm::Triple::sparcel:
2893 case llvm::Triple::sparcv9:
2894 case llvm::Triple::systemz:
2895 case llvm::Triple::thumb:
2896 case llvm::Triple::thumbeb:
2897 case llvm::Triple::ve:
2898 case llvm::Triple::x86:
2899 case llvm::Triple::x86_64:
2900 return true;
2901 default:
2902 return false;
2906 void Generic_GCC::PushPPaths(ToolChain::path_list &PPaths) {
2907 // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
2908 // least) put various tools in a triple-prefixed directory off of the parent
2909 // of the GCC installation. We use the GCC triple here to ensure that we end
2910 // up with tools that support the same amount of cross compiling as the
2911 // detected GCC installation. For example, if we find a GCC installation
2912 // targeting x86_64, but it is a bi-arch GCC installation, it can also be
2913 // used to target i386.
2914 if (GCCInstallation.isValid()) {
2915 PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
2916 GCCInstallation.getTriple().str() + "/bin")
2917 .str());
2921 void Generic_GCC::AddMultilibPaths(const Driver &D,
2922 const std::string &SysRoot,
2923 const std::string &OSLibDir,
2924 const std::string &MultiarchTriple,
2925 path_list &Paths) {
2926 // Add the multilib suffixed paths where they are available.
2927 if (GCCInstallation.isValid()) {
2928 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2929 const std::string &LibPath =
2930 std::string(GCCInstallation.getParentLibPath());
2932 // Sourcery CodeBench MIPS toolchain holds some libraries under
2933 // a biarch-like suffix of the GCC installation.
2934 if (const auto &PathsCallback = Multilibs.filePathsCallback())
2935 for (const auto &Path : PathsCallback(SelectedMultilib))
2936 addPathIfExists(D, GCCInstallation.getInstallPath() + Path, Paths);
2938 // Add lib/gcc/$triple/$version, with an optional /multilib suffix.
2939 addPathIfExists(
2940 D, GCCInstallation.getInstallPath() + SelectedMultilib.gccSuffix(),
2941 Paths);
2943 // Add lib/gcc/$triple/$libdir
2944 // For GCC built with --enable-version-specific-runtime-libs.
2945 addPathIfExists(D, GCCInstallation.getInstallPath() + "/../" + OSLibDir,
2946 Paths);
2948 // GCC cross compiling toolchains will install target libraries which ship
2949 // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
2950 // any part of the GCC installation in
2951 // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
2952 // debatable, but is the reality today. We need to search this tree even
2953 // when we have a sysroot somewhere else. It is the responsibility of
2954 // whomever is doing the cross build targeting a sysroot using a GCC
2955 // installation that is *not* within the system root to ensure two things:
2957 // 1) Any DSOs that are linked in from this tree or from the install path
2958 // above must be present on the system root and found via an
2959 // appropriate rpath.
2960 // 2) There must not be libraries installed into
2961 // <prefix>/<triple>/<libdir> unless they should be preferred over
2962 // those within the system root.
2964 // Note that this matches the GCC behavior. See the below comment for where
2965 // Clang diverges from GCC's behavior.
2966 addPathIfExists(D,
2967 LibPath + "/../" + GCCTriple.str() + "/lib/../" + OSLibDir +
2968 SelectedMultilib.osSuffix(),
2969 Paths);
2971 // If the GCC installation we found is inside of the sysroot, we want to
2972 // prefer libraries installed in the parent prefix of the GCC installation.
2973 // It is important to *not* use these paths when the GCC installation is
2974 // outside of the system root as that can pick up unintended libraries.
2975 // This usually happens when there is an external cross compiler on the
2976 // host system, and a more minimal sysroot available that is the target of
2977 // the cross. Note that GCC does include some of these directories in some
2978 // configurations but this seems somewhere between questionable and simply
2979 // a bug.
2980 if (StringRef(LibPath).startswith(SysRoot))
2981 addPathIfExists(D, LibPath + "/../" + OSLibDir, Paths);
2985 void Generic_GCC::AddMultiarchPaths(const Driver &D,
2986 const std::string &SysRoot,
2987 const std::string &OSLibDir,
2988 path_list &Paths) {
2989 if (GCCInstallation.isValid()) {
2990 const std::string &LibPath =
2991 std::string(GCCInstallation.getParentLibPath());
2992 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2993 const Multilib &Multilib = GCCInstallation.getMultilib();
2994 addPathIfExists(
2995 D, LibPath + "/../" + GCCTriple.str() + "/lib" + Multilib.osSuffix(),
2996 Paths);
3000 void Generic_GCC::AddMultilibIncludeArgs(const ArgList &DriverArgs,
3001 ArgStringList &CC1Args) const {
3002 // Add include directories specific to the selected multilib set and multilib.
3003 if (!GCCInstallation.isValid())
3004 return;
3005 // gcc TOOL_INCLUDE_DIR.
3006 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3007 std::string LibPath(GCCInstallation.getParentLibPath());
3008 addSystemInclude(DriverArgs, CC1Args,
3009 Twine(LibPath) + "/../" + GCCTriple.str() + "/include");
3011 const auto &Callback = Multilibs.includeDirsCallback();
3012 if (Callback) {
3013 for (const auto &Path : Callback(GCCInstallation.getMultilib()))
3014 addExternCSystemIncludeIfExists(DriverArgs, CC1Args,
3015 GCCInstallation.getInstallPath() + Path);
3019 void Generic_GCC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3020 ArgStringList &CC1Args) const {
3021 if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdincxx,
3022 options::OPT_nostdlibinc))
3023 return;
3025 switch (GetCXXStdlibType(DriverArgs)) {
3026 case ToolChain::CST_Libcxx:
3027 addLibCxxIncludePaths(DriverArgs, CC1Args);
3028 break;
3030 case ToolChain::CST_Libstdcxx:
3031 addLibStdCxxIncludePaths(DriverArgs, CC1Args);
3032 break;
3036 void
3037 Generic_GCC::addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3038 llvm::opt::ArgStringList &CC1Args) const {
3039 const Driver &D = getDriver();
3040 std::string SysRoot = computeSysRoot();
3041 std::string Target = getTripleString();
3043 auto AddIncludePath = [&](std::string Path) {
3044 std::string Version = detectLibcxxVersion(Path);
3045 if (Version.empty())
3046 return false;
3048 // First add the per-target include path if it exists.
3049 std::string TargetDir = Path + "/" + Target + "/c++/" + Version;
3050 if (D.getVFS().exists(TargetDir))
3051 addSystemInclude(DriverArgs, CC1Args, TargetDir);
3053 // Second add the generic one.
3054 addSystemInclude(DriverArgs, CC1Args, Path + "/c++/" + Version);
3055 return true;
3058 // Android never uses the libc++ headers installed alongside the toolchain,
3059 // which are generally incompatible with the NDK libraries anyway.
3060 if (!getTriple().isAndroid())
3061 if (AddIncludePath(getDriver().Dir + "/../include"))
3062 return;
3063 // If this is a development, non-installed, clang, libcxx will
3064 // not be found at ../include/c++ but it likely to be found at
3065 // one of the following two locations:
3066 if (AddIncludePath(concat(SysRoot, "/usr/local/include")))
3067 return;
3068 if (AddIncludePath(concat(SysRoot, "/usr/include")))
3069 return;
3072 bool Generic_GCC::addLibStdCXXIncludePaths(Twine IncludeDir, StringRef Triple,
3073 Twine IncludeSuffix,
3074 const llvm::opt::ArgList &DriverArgs,
3075 llvm::opt::ArgStringList &CC1Args,
3076 bool DetectDebian) const {
3077 if (!getVFS().exists(IncludeDir))
3078 return false;
3080 // Debian native gcc uses g++-multiarch-incdir.diff which uses
3081 // include/x86_64-linux-gnu/c++/10$IncludeSuffix instead of
3082 // include/c++/10/x86_64-linux-gnu$IncludeSuffix.
3083 std::string Dir = IncludeDir.str();
3084 StringRef Include =
3085 llvm::sys::path::parent_path(llvm::sys::path::parent_path(Dir));
3086 std::string Path =
3087 (Include + "/" + Triple + Dir.substr(Include.size()) + IncludeSuffix)
3088 .str();
3089 if (DetectDebian && !getVFS().exists(Path))
3090 return false;
3092 // GPLUSPLUS_INCLUDE_DIR
3093 addSystemInclude(DriverArgs, CC1Args, IncludeDir);
3094 // GPLUSPLUS_TOOL_INCLUDE_DIR. If Triple is not empty, add a target-dependent
3095 // include directory.
3096 if (DetectDebian)
3097 addSystemInclude(DriverArgs, CC1Args, Path);
3098 else if (!Triple.empty())
3099 addSystemInclude(DriverArgs, CC1Args,
3100 IncludeDir + "/" + Triple + IncludeSuffix);
3101 // GPLUSPLUS_BACKWARD_INCLUDE_DIR
3102 addSystemInclude(DriverArgs, CC1Args, IncludeDir + "/backward");
3103 return true;
3106 bool Generic_GCC::addGCCLibStdCxxIncludePaths(
3107 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
3108 StringRef DebianMultiarch) const {
3109 assert(GCCInstallation.isValid());
3111 // By default, look for the C++ headers in an include directory adjacent to
3112 // the lib directory of the GCC installation. Note that this is expect to be
3113 // equivalent to '/usr/include/c++/X.Y' in almost all cases.
3114 StringRef LibDir = GCCInstallation.getParentLibPath();
3115 StringRef InstallDir = GCCInstallation.getInstallPath();
3116 StringRef TripleStr = GCCInstallation.getTriple().str();
3117 const Multilib &Multilib = GCCInstallation.getMultilib();
3118 const GCCVersion &Version = GCCInstallation.getVersion();
3120 // Try /../$triple/include/c++/$version (gcc --print-multiarch is not empty).
3121 if (addLibStdCXXIncludePaths(
3122 LibDir.str() + "/../" + TripleStr + "/include/c++/" + Version.Text,
3123 TripleStr, Multilib.includeSuffix(), DriverArgs, CC1Args))
3124 return true;
3126 // Try /gcc/$triple/$version/include/c++/ (gcc --print-multiarch is not
3127 // empty). Like above but for GCC built with
3128 // --enable-version-specific-runtime-libs.
3129 if (addLibStdCXXIncludePaths(LibDir.str() + "/gcc/" + TripleStr + "/" +
3130 Version.Text + "/include/c++/",
3131 TripleStr, Multilib.includeSuffix(), DriverArgs,
3132 CC1Args))
3133 return true;
3135 // Detect Debian g++-multiarch-incdir.diff.
3136 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include/c++/" + Version.Text,
3137 DebianMultiarch, Multilib.includeSuffix(),
3138 DriverArgs, CC1Args, /*Debian=*/true))
3139 return true;
3141 // Try /../include/c++/$version (gcc --print-multiarch is empty).
3142 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include/c++/" + Version.Text,
3143 TripleStr, Multilib.includeSuffix(), DriverArgs,
3144 CC1Args))
3145 return true;
3147 // Otherwise, fall back on a bunch of options which don't use multiarch
3148 // layouts for simplicity.
3149 const std::string LibStdCXXIncludePathCandidates[] = {
3150 // Gentoo is weird and places its headers inside the GCC install,
3151 // so if the first attempt to find the headers fails, try these patterns.
3152 InstallDir.str() + "/include/g++-v" + Version.Text,
3153 InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
3154 Version.MinorStr,
3155 InstallDir.str() + "/include/g++-v" + Version.MajorStr,
3158 for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
3159 if (addLibStdCXXIncludePaths(IncludePath, TripleStr,
3160 Multilib.includeSuffix(), DriverArgs, CC1Args))
3161 return true;
3163 return false;
3166 void
3167 Generic_GCC::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3168 llvm::opt::ArgStringList &CC1Args) const {
3169 if (GCCInstallation.isValid()) {
3170 addGCCLibStdCxxIncludePaths(DriverArgs, CC1Args,
3171 GCCInstallation.getTriple().str());
3175 llvm::opt::DerivedArgList *
3176 Generic_GCC::TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef,
3177 Action::OffloadKind DeviceOffloadKind) const {
3179 // If this tool chain is used for an OpenMP offloading device we have to make
3180 // sure we always generate a shared library regardless of the commands the
3181 // user passed to the host. This is required because the runtime library
3182 // is required to load the device image dynamically at run time.
3183 if (DeviceOffloadKind == Action::OFK_OpenMP) {
3184 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
3185 const OptTable &Opts = getDriver().getOpts();
3187 // Request the shared library. Given that these options are decided
3188 // implicitly, they do not refer to any base argument.
3189 DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_shared));
3190 DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_fPIC));
3192 // Filter all the arguments we don't care passing to the offloading
3193 // toolchain as they can mess up with the creation of a shared library.
3194 for (auto *A : Args) {
3195 switch ((options::ID)A->getOption().getID()) {
3196 default:
3197 DAL->append(A);
3198 break;
3199 case options::OPT_shared:
3200 case options::OPT_dynamic:
3201 case options::OPT_static:
3202 case options::OPT_fPIC:
3203 case options::OPT_fno_PIC:
3204 case options::OPT_fpic:
3205 case options::OPT_fno_pic:
3206 case options::OPT_fPIE:
3207 case options::OPT_fno_PIE:
3208 case options::OPT_fpie:
3209 case options::OPT_fno_pie:
3210 break;
3213 return DAL;
3215 return nullptr;
3218 void Generic_ELF::anchor() {}
3220 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
3221 ArgStringList &CC1Args,
3222 Action::OffloadKind) const {
3223 if (!DriverArgs.hasFlag(options::OPT_fuse_init_array,
3224 options::OPT_fno_use_init_array, true))
3225 CC1Args.push_back("-fno-use-init-array");