[DFAJumpThreading] Remove incoming StartBlock from all phis when unfolding select...
[llvm-project.git] / clang / lib / Driver / ToolChains / Gnu.cpp
blob5237951f84cce0342cfb2fee6edb3c5aad5e94f5
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/LoongArch.h"
13 #include "Arch/Mips.h"
14 #include "Arch/PPC.h"
15 #include "Arch/RISCV.h"
16 #include "Arch/Sparc.h"
17 #include "Arch/SystemZ.h"
18 #include "CommonArgs.h"
19 #include "Linux.h"
20 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
21 #include "clang/Driver/Compilation.h"
22 #include "clang/Driver/Driver.h"
23 #include "clang/Driver/DriverDiagnostic.h"
24 #include "clang/Driver/MultilibBuilder.h"
25 #include "clang/Driver/Options.h"
26 #include "clang/Driver/Tool.h"
27 #include "clang/Driver/ToolChain.h"
28 #include "llvm/ADT/StringSet.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/Option/ArgList.h"
31 #include "llvm/Support/CodeGen.h"
32 #include "llvm/Support/Path.h"
33 #include "llvm/Support/VirtualFileSystem.h"
34 #include "llvm/TargetParser/TargetParser.h"
35 #include <system_error>
37 using namespace clang::driver;
38 using namespace clang::driver::toolchains;
39 using namespace clang;
40 using namespace llvm::opt;
42 using tools::addMultilibFlag;
43 using tools::addPathIfExists;
45 static bool forwardToGCC(const Option &O) {
46 // LinkerInput options have been forwarded. Don't duplicate.
47 if (O.hasFlag(options::LinkerInput))
48 return false;
49 return O.matches(options::OPT_Link_Group) || O.hasFlag(options::LinkOption);
52 // Switch CPU names not recognized by GNU assembler to a close CPU that it does
53 // recognize, instead of a lower march from being picked in the absence of a cpu
54 // flag.
55 static void normalizeCPUNamesForAssembler(const ArgList &Args,
56 ArgStringList &CmdArgs) {
57 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
58 StringRef CPUArg(A->getValue());
59 if (CPUArg.equals_insensitive("krait"))
60 CmdArgs.push_back("-mcpu=cortex-a15");
61 else if (CPUArg.equals_insensitive("kryo"))
62 CmdArgs.push_back("-mcpu=cortex-a57");
63 else
64 Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
68 void tools::gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
69 const InputInfo &Output,
70 const InputInfoList &Inputs,
71 const ArgList &Args,
72 const char *LinkingOutput) const {
73 const Driver &D = getToolChain().getDriver();
74 ArgStringList CmdArgs;
76 for (const auto &A : Args) {
77 if (forwardToGCC(A->getOption())) {
78 // It is unfortunate that we have to claim here, as this means
79 // we will basically never report anything interesting for
80 // platforms using a generic gcc, even if we are just using gcc
81 // to get to the assembler.
82 A->claim();
84 A->render(Args, CmdArgs);
88 RenderExtraToolArgs(JA, CmdArgs);
90 // If using a driver, force the arch.
91 if (getToolChain().getTriple().isOSDarwin()) {
92 CmdArgs.push_back("-arch");
93 CmdArgs.push_back(
94 Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
97 // Try to force gcc to match the tool chain we want, if we recognize
98 // the arch.
100 // FIXME: The triple class should directly provide the information we want
101 // here.
102 switch (getToolChain().getArch()) {
103 default:
104 break;
105 case llvm::Triple::x86:
106 case llvm::Triple::ppc:
107 case llvm::Triple::ppcle:
108 CmdArgs.push_back("-m32");
109 break;
110 case llvm::Triple::x86_64:
111 case llvm::Triple::ppc64:
112 case llvm::Triple::ppc64le:
113 CmdArgs.push_back("-m64");
114 break;
115 case llvm::Triple::sparcel:
116 CmdArgs.push_back("-EL");
117 break;
120 assert((Output.isFilename() || Output.isNothing()) && "Invalid output.");
121 if (Output.isFilename()) {
122 CmdArgs.push_back("-o");
123 CmdArgs.push_back(Output.getFilename());
124 } else {
125 CmdArgs.push_back("-fsyntax-only");
128 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
130 // Only pass -x if gcc will understand it; otherwise hope gcc
131 // understands the suffix correctly. The main use case this would go
132 // wrong in is for linker inputs if they happened to have an odd
133 // suffix; really the only way to get this to happen is a command
134 // like '-x foobar a.c' which will treat a.c like a linker input.
136 // FIXME: For the linker case specifically, can we safely convert
137 // inputs into '-Wl,' options?
138 for (const auto &II : Inputs) {
139 // Don't try to pass LLVM or AST inputs to a generic gcc.
140 if (types::isLLVMIR(II.getType()))
141 D.Diag(clang::diag::err_drv_no_linker_llvm_support)
142 << getToolChain().getTripleString();
143 else if (II.getType() == types::TY_AST)
144 D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
145 else if (II.getType() == types::TY_ModuleFile)
146 D.Diag(diag::err_drv_no_module_support)
147 << getToolChain().getTripleString();
149 if (types::canTypeBeUserSpecified(II.getType())) {
150 CmdArgs.push_back("-x");
151 CmdArgs.push_back(types::getTypeName(II.getType()));
154 if (II.isFilename())
155 CmdArgs.push_back(II.getFilename());
156 else {
157 const Arg &A = II.getInputArg();
159 // Reverse translate some rewritten options.
160 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
161 CmdArgs.push_back("-lstdc++");
162 continue;
165 // Don't render as input, we need gcc to do the translations.
166 A.render(Args, CmdArgs);
170 const std::string &customGCCName = D.getCCCGenericGCCName();
171 const char *GCCName;
172 if (!customGCCName.empty())
173 GCCName = customGCCName.c_str();
174 else if (D.CCCIsCXX()) {
175 GCCName = "g++";
176 } else
177 GCCName = "gcc";
179 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
180 C.addCommand(std::make_unique<Command>(JA, *this,
181 ResponseFileSupport::AtFileCurCP(),
182 Exec, CmdArgs, Inputs, Output));
185 void tools::gcc::Preprocessor::RenderExtraToolArgs(
186 const JobAction &JA, ArgStringList &CmdArgs) const {
187 CmdArgs.push_back("-E");
190 void tools::gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
191 ArgStringList &CmdArgs) const {
192 const Driver &D = getToolChain().getDriver();
194 switch (JA.getType()) {
195 // If -flto, etc. are present then make sure not to force assembly output.
196 case types::TY_LLVM_IR:
197 case types::TY_LTO_IR:
198 case types::TY_LLVM_BC:
199 case types::TY_LTO_BC:
200 CmdArgs.push_back("-c");
201 break;
202 // We assume we've got an "integrated" assembler in that gcc will produce an
203 // object file itself.
204 case types::TY_Object:
205 CmdArgs.push_back("-c");
206 break;
207 case types::TY_PP_Asm:
208 CmdArgs.push_back("-S");
209 break;
210 case types::TY_Nothing:
211 CmdArgs.push_back("-fsyntax-only");
212 break;
213 default:
214 D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
218 void tools::gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
219 ArgStringList &CmdArgs) const {
220 // The types are (hopefully) good enough.
223 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
224 switch (T.getArch()) {
225 case llvm::Triple::x86:
226 if (T.isOSIAMCU())
227 return "elf_iamcu";
228 return "elf_i386";
229 case llvm::Triple::aarch64:
230 return "aarch64linux";
231 case llvm::Triple::aarch64_be:
232 return "aarch64linuxb";
233 case llvm::Triple::arm:
234 case llvm::Triple::thumb:
235 case llvm::Triple::armeb:
236 case llvm::Triple::thumbeb:
237 return tools::arm::isARMBigEndian(T, Args) ? "armelfb_linux_eabi"
238 : "armelf_linux_eabi";
239 case llvm::Triple::m68k:
240 return "m68kelf";
241 case llvm::Triple::ppc:
242 if (T.isOSLinux())
243 return "elf32ppclinux";
244 return "elf32ppc";
245 case llvm::Triple::ppcle:
246 if (T.isOSLinux())
247 return "elf32lppclinux";
248 return "elf32lppc";
249 case llvm::Triple::ppc64:
250 return "elf64ppc";
251 case llvm::Triple::ppc64le:
252 return "elf64lppc";
253 case llvm::Triple::riscv32:
254 return "elf32lriscv";
255 case llvm::Triple::riscv64:
256 return "elf64lriscv";
257 case llvm::Triple::sparc:
258 case llvm::Triple::sparcel:
259 return "elf32_sparc";
260 case llvm::Triple::sparcv9:
261 return "elf64_sparc";
262 case llvm::Triple::loongarch32:
263 return "elf32loongarch";
264 case llvm::Triple::loongarch64:
265 return "elf64loongarch";
266 case llvm::Triple::mips:
267 return "elf32btsmip";
268 case llvm::Triple::mipsel:
269 return "elf32ltsmip";
270 case llvm::Triple::mips64:
271 if (tools::mips::hasMipsAbiArg(Args, "n32") ||
272 T.getEnvironment() == llvm::Triple::GNUABIN32)
273 return "elf32btsmipn32";
274 return "elf64btsmip";
275 case llvm::Triple::mips64el:
276 if (tools::mips::hasMipsAbiArg(Args, "n32") ||
277 T.getEnvironment() == llvm::Triple::GNUABIN32)
278 return "elf32ltsmipn32";
279 return "elf64ltsmip";
280 case llvm::Triple::systemz:
281 return "elf64_s390";
282 case llvm::Triple::x86_64:
283 if (T.isX32())
284 return "elf32_x86_64";
285 return "elf_x86_64";
286 case llvm::Triple::ve:
287 return "elf64ve";
288 case llvm::Triple::csky:
289 return "cskyelf_linux";
290 default:
291 return nullptr;
295 static bool getPIE(const ArgList &Args, const ToolChain &TC) {
296 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_static) ||
297 Args.hasArg(options::OPT_r) || Args.hasArg(options::OPT_static_pie))
298 return false;
300 Arg *A = Args.getLastArg(options::OPT_pie, options::OPT_no_pie,
301 options::OPT_nopie);
302 if (!A)
303 return TC.isPIEDefault(Args);
304 return A->getOption().matches(options::OPT_pie);
307 static bool getStaticPIE(const ArgList &Args, const ToolChain &TC) {
308 bool HasStaticPIE = Args.hasArg(options::OPT_static_pie);
309 // -no-pie is an alias for -nopie. So, handling -nopie takes care of
310 // -no-pie as well.
311 if (HasStaticPIE && Args.hasArg(options::OPT_nopie)) {
312 const Driver &D = TC.getDriver();
313 const llvm::opt::OptTable &Opts = D.getOpts();
314 StringRef StaticPIEName = Opts.getOptionName(options::OPT_static_pie);
315 StringRef NoPIEName = Opts.getOptionName(options::OPT_nopie);
316 D.Diag(diag::err_drv_cannot_mix_options) << StaticPIEName << NoPIEName;
318 return HasStaticPIE;
321 static bool getStatic(const ArgList &Args) {
322 return Args.hasArg(options::OPT_static) &&
323 !Args.hasArg(options::OPT_static_pie);
326 void tools::gnutools::StaticLibTool::ConstructJob(
327 Compilation &C, const JobAction &JA, const InputInfo &Output,
328 const InputInfoList &Inputs, const ArgList &Args,
329 const char *LinkingOutput) const {
330 const Driver &D = getToolChain().getDriver();
332 // Silence warning for "clang -g foo.o -o foo"
333 Args.ClaimAllArgs(options::OPT_g_Group);
334 // and "clang -emit-llvm foo.o -o foo"
335 Args.ClaimAllArgs(options::OPT_emit_llvm);
336 // and for "clang -w foo.o -o foo". Other warning options are already
337 // handled somewhere else.
338 Args.ClaimAllArgs(options::OPT_w);
339 // Silence warnings when linking C code with a C++ '-stdlib' argument.
340 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
342 // ar tool command "llvm-ar <options> <output_file> <input_files>".
343 ArgStringList CmdArgs;
344 // Create and insert file members with a deterministic index.
345 CmdArgs.push_back("rcsD");
346 CmdArgs.push_back(Output.getFilename());
348 for (const auto &II : Inputs) {
349 if (II.isFilename()) {
350 CmdArgs.push_back(II.getFilename());
354 // Delete old output archive file if it already exists before generating a new
355 // archive file.
356 auto OutputFileName = Output.getFilename();
357 if (Output.isFilename() && llvm::sys::fs::exists(OutputFileName)) {
358 if (std::error_code EC = llvm::sys::fs::remove(OutputFileName)) {
359 D.Diag(diag::err_drv_unable_to_remove_file) << EC.message();
360 return;
364 const char *Exec = Args.MakeArgString(getToolChain().GetStaticLibToolPath());
365 C.addCommand(std::make_unique<Command>(JA, *this,
366 ResponseFileSupport::AtFileCurCP(),
367 Exec, CmdArgs, Inputs, Output));
370 void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
371 const InputInfo &Output,
372 const InputInfoList &Inputs,
373 const ArgList &Args,
374 const char *LinkingOutput) const {
375 // FIXME: The Linker class constructor takes a ToolChain and not a
376 // Generic_ELF, so the static_cast might return a reference to a invalid
377 // instance (see PR45061). Ideally, the Linker constructor needs to take a
378 // Generic_ELF instead.
379 const auto &ToolChain = static_cast<const Generic_ELF &>(getToolChain());
380 const Driver &D = ToolChain.getDriver();
382 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
384 const llvm::Triple::ArchType Arch = ToolChain.getArch();
385 const bool isOHOSFamily = ToolChain.getTriple().isOHOSFamily();
386 const bool isAndroid = ToolChain.getTriple().isAndroid();
387 const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
388 const bool IsVE = ToolChain.getTriple().isVE();
389 const bool IsPIE = getPIE(Args, ToolChain);
390 const bool IsStaticPIE = getStaticPIE(Args, ToolChain);
391 const bool IsStatic = getStatic(Args);
392 const bool HasCRTBeginEndFiles =
393 ToolChain.getTriple().hasEnvironment() ||
394 (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
396 ArgStringList CmdArgs;
398 // Silence warning for "clang -g foo.o -o foo"
399 Args.ClaimAllArgs(options::OPT_g_Group);
400 // and "clang -emit-llvm foo.o -o foo"
401 Args.ClaimAllArgs(options::OPT_emit_llvm);
402 // and for "clang -w foo.o -o foo". Other warning options are already
403 // handled somewhere else.
404 Args.ClaimAllArgs(options::OPT_w);
406 if (!D.SysRoot.empty())
407 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
409 if (IsPIE)
410 CmdArgs.push_back("-pie");
412 if (IsStaticPIE) {
413 CmdArgs.push_back("-static");
414 CmdArgs.push_back("-pie");
415 CmdArgs.push_back("--no-dynamic-linker");
416 CmdArgs.push_back("-z");
417 CmdArgs.push_back("text");
420 if (Args.hasArg(options::OPT_rdynamic))
421 CmdArgs.push_back("-export-dynamic");
423 if (Args.hasArg(options::OPT_s))
424 CmdArgs.push_back("-s");
426 if (Triple.isARM() || Triple.isThumb()) {
427 bool IsBigEndian = arm::isARMBigEndian(Triple, Args);
428 if (IsBigEndian)
429 arm::appendBE8LinkFlag(Args, CmdArgs, Triple);
430 CmdArgs.push_back(IsBigEndian ? "-EB" : "-EL");
431 } else if (Triple.isAArch64()) {
432 CmdArgs.push_back(Arch == llvm::Triple::aarch64_be ? "-EB" : "-EL");
435 // Most Android ARM64 targets should enable the linker fix for erratum
436 // 843419. Only non-Cortex-A53 devices are allowed to skip this flag.
437 if (Arch == llvm::Triple::aarch64 && (isAndroid || isOHOSFamily)) {
438 std::string CPU = getCPUName(D, Args, Triple);
439 if (CPU.empty() || CPU == "generic" || CPU == "cortex-a53")
440 CmdArgs.push_back("--fix-cortex-a53-843419");
443 ToolChain.addExtraOpts(CmdArgs);
445 CmdArgs.push_back("--eh-frame-hdr");
447 if (const char *LDMOption = getLDMOption(ToolChain.getTriple(), Args)) {
448 CmdArgs.push_back("-m");
449 CmdArgs.push_back(LDMOption);
450 } else {
451 D.Diag(diag::err_target_unknown_triple) << Triple.str();
452 return;
454 if (Triple.isRISCV())
455 CmdArgs.push_back("-X");
457 if (Args.hasArg(options::OPT_shared))
458 CmdArgs.push_back("-shared");
460 if (IsStatic) {
461 CmdArgs.push_back("-static");
462 } else {
463 if (Args.hasArg(options::OPT_rdynamic))
464 CmdArgs.push_back("-export-dynamic");
466 if (!Args.hasArg(options::OPT_shared) && !IsStaticPIE &&
467 !Args.hasArg(options::OPT_r)) {
468 CmdArgs.push_back("-dynamic-linker");
469 CmdArgs.push_back(Args.MakeArgString(Twine(D.DyldPrefix) +
470 ToolChain.getDynamicLinker(Args)));
474 CmdArgs.push_back("-o");
475 CmdArgs.push_back(Output.getFilename());
477 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
478 options::OPT_r)) {
479 if (!isAndroid && !IsIAMCU) {
480 const char *crt1 = nullptr;
481 if (!Args.hasArg(options::OPT_shared)) {
482 if (Args.hasArg(options::OPT_pg))
483 crt1 = "gcrt1.o";
484 else if (IsPIE)
485 crt1 = "Scrt1.o";
486 else if (IsStaticPIE)
487 crt1 = "rcrt1.o";
488 else
489 crt1 = "crt1.o";
491 if (crt1)
492 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
494 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
497 if (IsVE) {
498 CmdArgs.push_back("-z");
499 CmdArgs.push_back("max-page-size=0x4000000");
502 if (IsIAMCU)
503 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
504 else if (HasCRTBeginEndFiles) {
505 std::string P;
506 if (ToolChain.GetRuntimeLibType(Args) == ToolChain::RLT_CompilerRT &&
507 !isAndroid) {
508 std::string crtbegin = ToolChain.getCompilerRT(Args, "crtbegin",
509 ToolChain::FT_Object);
510 if (ToolChain.getVFS().exists(crtbegin))
511 P = crtbegin;
513 if (P.empty()) {
514 const char *crtbegin;
515 if (Args.hasArg(options::OPT_shared))
516 crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
517 else if (IsStatic)
518 crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
519 else if (IsPIE || IsStaticPIE)
520 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
521 else
522 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
523 P = ToolChain.GetFilePath(crtbegin);
525 CmdArgs.push_back(Args.MakeArgString(P));
528 // Add crtfastmath.o if available and fast math is enabled.
529 ToolChain.addFastMathRuntimeIfAvailable(Args, CmdArgs);
532 Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_u});
534 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
536 if (D.isUsingLTO()) {
537 assert(!Inputs.empty() && "Must have at least one input.");
538 addLTOOptions(ToolChain, Args, CmdArgs, Output, Inputs[0],
539 D.getLTOMode() == LTOK_Thin);
542 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
543 CmdArgs.push_back("--no-demangle");
545 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
546 bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
547 addLinkerCompressDebugSectionsOption(ToolChain, Args, CmdArgs);
548 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
550 addHIPRuntimeLibArgs(ToolChain, C, Args, CmdArgs);
552 // The profile runtime also needs access to system libraries.
553 getToolChain().addProfileRTLibs(Args, CmdArgs);
555 if (D.CCCIsCXX() &&
556 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
557 options::OPT_r)) {
558 if (ToolChain.ShouldLinkCXXStdlib(Args)) {
559 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
560 !Args.hasArg(options::OPT_static);
561 if (OnlyLibstdcxxStatic)
562 CmdArgs.push_back("-Bstatic");
563 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
564 if (OnlyLibstdcxxStatic)
565 CmdArgs.push_back("-Bdynamic");
567 CmdArgs.push_back("-lm");
570 // Silence warnings when linking C code with a C++ '-stdlib' argument.
571 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
573 // Additional linker set-up and flags for Fortran. This is required in order
574 // to generate executables. As Fortran runtime depends on the C runtime,
575 // these dependencies need to be listed before the C runtime below (i.e.
576 // AddRunTimeLibs).
577 if (D.IsFlangMode()) {
578 addFortranRuntimeLibraryPath(ToolChain, Args, CmdArgs);
579 addFortranRuntimeLibs(ToolChain, CmdArgs);
580 CmdArgs.push_back("-lm");
583 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_r)) {
584 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
585 if (IsStatic || IsStaticPIE)
586 CmdArgs.push_back("--start-group");
588 if (NeedsSanitizerDeps)
589 linkSanitizerRuntimeDeps(ToolChain, Args, CmdArgs);
591 if (NeedsXRayDeps)
592 linkXRayRuntimeDeps(ToolChain, Args, CmdArgs);
594 bool WantPthread = Args.hasArg(options::OPT_pthread) ||
595 Args.hasArg(options::OPT_pthreads);
597 // Use the static OpenMP runtime with -static-openmp
598 bool StaticOpenMP = Args.hasArg(options::OPT_static_openmp) &&
599 !Args.hasArg(options::OPT_static);
601 // FIXME: Only pass GompNeedsRT = true for platforms with libgomp that
602 // require librt. Most modern Linux platforms do, but some may not.
603 if (addOpenMPRuntime(CmdArgs, ToolChain, Args, StaticOpenMP,
604 JA.isHostOffloading(Action::OFK_OpenMP),
605 /* GompNeedsRT= */ true))
606 // OpenMP runtimes implies pthreads when using the GNU toolchain.
607 // FIXME: Does this really make sense for all GNU toolchains?
608 WantPthread = true;
610 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
612 // LLVM support for atomics on 32-bit SPARC V8+ is incomplete, so
613 // forcibly link with libatomic as a workaround.
614 // TODO: Issue #41880 and D118021.
615 if (getToolChain().getTriple().getArch() == llvm::Triple::sparc) {
616 CmdArgs.push_back("--push-state");
617 CmdArgs.push_back("--as-needed");
618 CmdArgs.push_back("-latomic");
619 CmdArgs.push_back("--pop-state");
622 // We don't need libpthread neither for bionic (Android) nor for musl,
623 // (used by OHOS as runtime library).
624 if (WantPthread && !isAndroid && !isOHOSFamily)
625 CmdArgs.push_back("-lpthread");
627 if (Args.hasArg(options::OPT_fsplit_stack))
628 CmdArgs.push_back("--wrap=pthread_create");
630 if (!Args.hasArg(options::OPT_nolibc))
631 CmdArgs.push_back("-lc");
633 // Add IAMCU specific libs, if needed.
634 if (IsIAMCU)
635 CmdArgs.push_back("-lgloss");
637 if (IsStatic || IsStaticPIE)
638 CmdArgs.push_back("--end-group");
639 else
640 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
642 // Add IAMCU specific libs (outside the group), if needed.
643 if (IsIAMCU) {
644 CmdArgs.push_back("--as-needed");
645 CmdArgs.push_back("-lsoftfp");
646 CmdArgs.push_back("--no-as-needed");
650 if (!Args.hasArg(options::OPT_nostartfiles) && !IsIAMCU) {
651 if (HasCRTBeginEndFiles) {
652 std::string P;
653 if (ToolChain.GetRuntimeLibType(Args) == ToolChain::RLT_CompilerRT &&
654 !isAndroid) {
655 std::string crtend = ToolChain.getCompilerRT(Args, "crtend",
656 ToolChain::FT_Object);
657 if (ToolChain.getVFS().exists(crtend))
658 P = crtend;
660 if (P.empty()) {
661 const char *crtend;
662 if (Args.hasArg(options::OPT_shared))
663 crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
664 else if (IsPIE || IsStaticPIE)
665 crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
666 else
667 crtend = isAndroid ? "crtend_android.o" : "crtend.o";
668 P = ToolChain.GetFilePath(crtend);
670 CmdArgs.push_back(Args.MakeArgString(P));
672 if (!isAndroid)
673 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
677 Args.AddAllArgs(CmdArgs, options::OPT_T);
679 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
680 C.addCommand(std::make_unique<Command>(JA, *this,
681 ResponseFileSupport::AtFileCurCP(),
682 Exec, CmdArgs, Inputs, Output));
685 void tools::gnutools::Assembler::ConstructJob(Compilation &C,
686 const JobAction &JA,
687 const InputInfo &Output,
688 const InputInfoList &Inputs,
689 const ArgList &Args,
690 const char *LinkingOutput) const {
691 const auto &D = getToolChain().getDriver();
693 claimNoWarnArgs(Args);
695 ArgStringList CmdArgs;
697 llvm::Reloc::Model RelocationModel;
698 unsigned PICLevel;
699 bool IsPIE;
700 const char *DefaultAssembler = "as";
701 // Enforce GNU as on Solaris; the native assembler's input syntax isn't fully
702 // compatible.
703 if (getToolChain().getTriple().isOSSolaris())
704 DefaultAssembler = "gas";
705 std::tie(RelocationModel, PICLevel, IsPIE) =
706 ParsePICArgs(getToolChain(), Args);
708 if (const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ)) {
709 if (A->getOption().getID() == options::OPT_gz) {
710 CmdArgs.push_back("--compress-debug-sections");
711 } else {
712 StringRef Value = A->getValue();
713 if (Value == "none" || Value == "zlib" || Value == "zstd") {
714 CmdArgs.push_back(
715 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
716 } else {
717 D.Diag(diag::err_drv_unsupported_option_argument)
718 << A->getSpelling() << Value;
723 switch (getToolChain().getArch()) {
724 default:
725 break;
726 // Add --32/--64 to make sure we get the format we want.
727 // This is incomplete
728 case llvm::Triple::x86:
729 CmdArgs.push_back("--32");
730 break;
731 case llvm::Triple::x86_64:
732 if (getToolChain().getTriple().isX32())
733 CmdArgs.push_back("--x32");
734 else
735 CmdArgs.push_back("--64");
736 break;
737 case llvm::Triple::ppc: {
738 CmdArgs.push_back("-a32");
739 CmdArgs.push_back("-mppc");
740 CmdArgs.push_back("-mbig-endian");
741 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
742 getCPUName(D, Args, getToolChain().getTriple())));
743 break;
745 case llvm::Triple::ppcle: {
746 CmdArgs.push_back("-a32");
747 CmdArgs.push_back("-mppc");
748 CmdArgs.push_back("-mlittle-endian");
749 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
750 getCPUName(D, Args, getToolChain().getTriple())));
751 break;
753 case llvm::Triple::ppc64: {
754 CmdArgs.push_back("-a64");
755 CmdArgs.push_back("-mppc64");
756 CmdArgs.push_back("-mbig-endian");
757 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
758 getCPUName(D, Args, getToolChain().getTriple())));
759 break;
761 case llvm::Triple::ppc64le: {
762 CmdArgs.push_back("-a64");
763 CmdArgs.push_back("-mppc64");
764 CmdArgs.push_back("-mlittle-endian");
765 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
766 getCPUName(D, Args, getToolChain().getTriple())));
767 break;
769 case llvm::Triple::riscv32:
770 case llvm::Triple::riscv64: {
771 StringRef ABIName = riscv::getRISCVABI(Args, getToolChain().getTriple());
772 CmdArgs.push_back("-mabi");
773 CmdArgs.push_back(ABIName.data());
774 StringRef MArchName = riscv::getRISCVArch(Args, getToolChain().getTriple());
775 CmdArgs.push_back("-march");
776 CmdArgs.push_back(MArchName.data());
777 if (!Args.hasFlag(options::OPT_mrelax, options::OPT_mno_relax, true))
778 Args.addOptOutFlag(CmdArgs, options::OPT_mrelax, options::OPT_mno_relax);
779 break;
781 case llvm::Triple::sparc:
782 case llvm::Triple::sparcel: {
783 CmdArgs.push_back("-32");
784 std::string CPU = getCPUName(D, Args, getToolChain().getTriple());
785 CmdArgs.push_back(
786 sparc::getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
787 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
788 break;
790 case llvm::Triple::sparcv9: {
791 CmdArgs.push_back("-64");
792 std::string CPU = getCPUName(D, Args, getToolChain().getTriple());
793 CmdArgs.push_back(
794 sparc::getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
795 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
796 break;
798 case llvm::Triple::arm:
799 case llvm::Triple::armeb:
800 case llvm::Triple::thumb:
801 case llvm::Triple::thumbeb: {
802 const llvm::Triple &Triple2 = getToolChain().getTriple();
803 CmdArgs.push_back(arm::isARMBigEndian(Triple2, Args) ? "-EB" : "-EL");
804 switch (Triple2.getSubArch()) {
805 case llvm::Triple::ARMSubArch_v7:
806 CmdArgs.push_back("-mfpu=neon");
807 break;
808 case llvm::Triple::ARMSubArch_v8:
809 CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
810 break;
811 default:
812 break;
815 switch (arm::getARMFloatABI(getToolChain(), Args)) {
816 case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
817 case arm::FloatABI::Soft:
818 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
819 break;
820 case arm::FloatABI::SoftFP:
821 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
822 break;
823 case arm::FloatABI::Hard:
824 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
825 break;
828 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
829 normalizeCPUNamesForAssembler(Args, CmdArgs);
831 Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
832 // The integrated assembler doesn't implement e_flags setting behavior for
833 // -meabi=gnu (gcc -mabi={apcs-gnu,atpcs} passes -meabi=gnu to gas). For
834 // compatibility we accept but warn.
835 if (Arg *A = Args.getLastArgNoClaim(options::OPT_mabi_EQ))
836 A->ignoreTargetSpecific();
837 break;
839 case llvm::Triple::aarch64:
840 case llvm::Triple::aarch64_be: {
841 CmdArgs.push_back(
842 getToolChain().getArch() == llvm::Triple::aarch64_be ? "-EB" : "-EL");
843 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
844 normalizeCPUNamesForAssembler(Args, CmdArgs);
846 break;
848 // TODO: handle loongarch32.
849 case llvm::Triple::loongarch64: {
850 StringRef ABIName =
851 loongarch::getLoongArchABI(D, Args, getToolChain().getTriple());
852 CmdArgs.push_back(Args.MakeArgString("-mabi=" + ABIName));
853 break;
855 case llvm::Triple::mips:
856 case llvm::Triple::mipsel:
857 case llvm::Triple::mips64:
858 case llvm::Triple::mips64el: {
859 StringRef CPUName;
860 StringRef ABIName;
861 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
862 ABIName = mips::getGnuCompatibleMipsABIName(ABIName);
864 CmdArgs.push_back("-march");
865 CmdArgs.push_back(CPUName.data());
867 CmdArgs.push_back("-mabi");
868 CmdArgs.push_back(ABIName.data());
870 // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
871 // or -mshared (not implemented) is in effect.
872 if (RelocationModel == llvm::Reloc::Static)
873 CmdArgs.push_back("-mno-shared");
875 // LLVM doesn't support -mplt yet and acts as if it is always given.
876 // However, -mplt has no effect with the N64 ABI.
877 if (ABIName != "64" && !Args.hasArg(options::OPT_mno_abicalls))
878 CmdArgs.push_back("-call_nonpic");
880 if (getToolChain().getTriple().isLittleEndian())
881 CmdArgs.push_back("-EL");
882 else
883 CmdArgs.push_back("-EB");
885 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
886 if (StringRef(A->getValue()) == "2008")
887 CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
890 // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
891 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
892 options::OPT_mfp64)) {
893 A->claim();
894 A->render(Args, CmdArgs);
895 } else if (mips::shouldUseFPXX(
896 Args, getToolChain().getTriple(), CPUName, ABIName,
897 mips::getMipsFloatABI(getToolChain().getDriver(), Args,
898 getToolChain().getTriple())))
899 CmdArgs.push_back("-mfpxx");
901 // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
902 // -mno-mips16 is actually -no-mips16.
903 if (Arg *A =
904 Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
905 if (A->getOption().matches(options::OPT_mips16)) {
906 A->claim();
907 A->render(Args, CmdArgs);
908 } else {
909 A->claim();
910 CmdArgs.push_back("-no-mips16");
914 Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
915 options::OPT_mno_micromips);
916 Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
917 Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
919 if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
920 // Do not use AddLastArg because not all versions of MIPS assembler
921 // support -mmsa / -mno-msa options.
922 if (A->getOption().matches(options::OPT_mmsa))
923 CmdArgs.push_back(Args.MakeArgString("-mmsa"));
926 Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
927 options::OPT_msoft_float);
929 Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
930 options::OPT_msingle_float);
932 Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
933 options::OPT_mno_odd_spreg);
935 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
936 break;
938 case llvm::Triple::systemz: {
939 // Always pass an -march option, since our default of z10 is later
940 // than the GNU assembler's default.
941 std::string CPUName = systemz::getSystemZTargetCPU(Args);
942 CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
943 break;
945 case llvm::Triple::ve:
946 DefaultAssembler = "nas";
949 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
950 options::OPT_fdebug_prefix_map_EQ)) {
951 StringRef Map = A->getValue();
952 if (!Map.contains('='))
953 D.Diag(diag::err_drv_invalid_argument_to_option)
954 << Map << A->getOption().getName();
955 else {
956 CmdArgs.push_back(Args.MakeArgString("--debug-prefix-map"));
957 CmdArgs.push_back(Args.MakeArgString(Map));
959 A->claim();
962 Args.AddAllArgs(CmdArgs, options::OPT_I);
963 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
965 CmdArgs.push_back("-o");
966 CmdArgs.push_back(Output.getFilename());
968 for (const auto &II : Inputs)
969 CmdArgs.push_back(II.getFilename());
971 if (Arg *A = Args.getLastArg(options::OPT_g_Flag, options::OPT_gN_Group,
972 options::OPT_gdwarf_2, options::OPT_gdwarf_3,
973 options::OPT_gdwarf_4, options::OPT_gdwarf_5,
974 options::OPT_gdwarf))
975 if (!A->getOption().matches(options::OPT_g0)) {
976 Args.AddLastArg(CmdArgs, options::OPT_g_Flag);
978 unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
979 CmdArgs.push_back(Args.MakeArgString("-gdwarf-" + Twine(DwarfVersion)));
982 const char *Exec =
983 Args.MakeArgString(getToolChain().GetProgramPath(DefaultAssembler));
984 C.addCommand(std::make_unique<Command>(JA, *this,
985 ResponseFileSupport::AtFileCurCP(),
986 Exec, CmdArgs, Inputs, Output));
988 // Handle the debug info splitting at object creation time if we're
989 // creating an object.
990 // TODO: Currently only works on linux with newer objcopy.
991 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
992 getToolChain().getTriple().isOSLinux())
993 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
994 SplitDebugName(JA, Args, Inputs[0], Output));
997 namespace {
998 // Filter to remove Multilibs that don't exist as a suffix to Path
999 class FilterNonExistent {
1000 StringRef Base, File;
1001 llvm::vfs::FileSystem &VFS;
1003 public:
1004 FilterNonExistent(StringRef Base, StringRef File, llvm::vfs::FileSystem &VFS)
1005 : Base(Base), File(File), VFS(VFS) {}
1006 bool operator()(const Multilib &M) {
1007 return !VFS.exists(Base + M.gccSuffix() + File);
1010 } // end anonymous namespace
1012 static bool isSoftFloatABI(const ArgList &Args) {
1013 Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1014 options::OPT_mfloat_abi_EQ);
1015 if (!A)
1016 return false;
1018 return A->getOption().matches(options::OPT_msoft_float) ||
1019 (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
1020 A->getValue() == StringRef("soft"));
1023 static bool isArmOrThumbArch(llvm::Triple::ArchType Arch) {
1024 return Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb;
1027 static bool isMipsEL(llvm::Triple::ArchType Arch) {
1028 return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
1031 static bool isMips16(const ArgList &Args) {
1032 Arg *A = Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16);
1033 return A && A->getOption().matches(options::OPT_mips16);
1036 static bool isMicroMips(const ArgList &Args) {
1037 Arg *A = Args.getLastArg(options::OPT_mmicromips, options::OPT_mno_micromips);
1038 return A && A->getOption().matches(options::OPT_mmicromips);
1041 static bool isMSP430(llvm::Triple::ArchType Arch) {
1042 return Arch == llvm::Triple::msp430;
1045 static bool findMipsCsMultilibs(const Multilib::flags_list &Flags,
1046 FilterNonExistent &NonExistent,
1047 DetectedMultilibs &Result) {
1048 // Check for Code Sourcery toolchain multilibs
1049 MultilibSet CSMipsMultilibs;
1051 auto MArchMips16 = MultilibBuilder("/mips16").flag("-m32").flag("-mips16");
1053 auto MArchMicroMips =
1054 MultilibBuilder("/micromips").flag("-m32").flag("-mmicromips");
1056 auto MArchDefault = MultilibBuilder("")
1057 .flag("-mips16", /*Disallow=*/true)
1058 .flag("-mmicromips", /*Disallow=*/true);
1060 auto UCLibc = MultilibBuilder("/uclibc").flag("-muclibc");
1062 auto SoftFloat = MultilibBuilder("/soft-float").flag("-msoft-float");
1064 auto Nan2008 = MultilibBuilder("/nan2008").flag("-mnan=2008");
1066 auto DefaultFloat = MultilibBuilder("")
1067 .flag("-msoft-float", /*Disallow=*/true)
1068 .flag("-mnan=2008", /*Disallow=*/true);
1070 auto BigEndian =
1071 MultilibBuilder("").flag("-EB").flag("-EL", /*Disallow=*/true);
1073 auto LittleEndian =
1074 MultilibBuilder("/el").flag("-EL").flag("-EB", /*Disallow=*/true);
1076 // Note that this one's osSuffix is ""
1077 auto MAbi64 = MultilibBuilder("")
1078 .gccSuffix("/64")
1079 .includeSuffix("/64")
1080 .flag("-mabi=n64")
1081 .flag("-mabi=n32", /*Disallow=*/true)
1082 .flag("-m32", /*Disallow=*/true);
1084 CSMipsMultilibs =
1085 MultilibSetBuilder()
1086 .Either(MArchMips16, MArchMicroMips, MArchDefault)
1087 .Maybe(UCLibc)
1088 .Either(SoftFloat, Nan2008, DefaultFloat)
1089 .FilterOut("/micromips/nan2008")
1090 .FilterOut("/mips16/nan2008")
1091 .Either(BigEndian, LittleEndian)
1092 .Maybe(MAbi64)
1093 .FilterOut("/mips16.*/64")
1094 .FilterOut("/micromips.*/64")
1095 .makeMultilibSet()
1096 .FilterOut(NonExistent)
1097 .setIncludeDirsCallback([](const Multilib &M) {
1098 std::vector<std::string> Dirs({"/include"});
1099 if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1100 Dirs.push_back(
1101 "/../../../../mips-linux-gnu/libc/uclibc/usr/include");
1102 else
1103 Dirs.push_back("/../../../../mips-linux-gnu/libc/usr/include");
1104 return Dirs;
1108 MultilibSet DebianMipsMultilibs;
1110 MultilibBuilder MAbiN32 =
1111 MultilibBuilder().gccSuffix("/n32").includeSuffix("/n32").flag(
1112 "-mabi=n32");
1114 MultilibBuilder M64 = MultilibBuilder()
1115 .gccSuffix("/64")
1116 .includeSuffix("/64")
1117 .flag("-m64")
1118 .flag("-m32", /*Disallow=*/true)
1119 .flag("-mabi=n32", /*Disallow=*/true);
1121 MultilibBuilder M32 = MultilibBuilder()
1122 .gccSuffix("/32")
1123 .flag("-m64", /*Disallow=*/true)
1124 .flag("-m32")
1125 .flag("-mabi=n32", /*Disallow=*/true);
1127 DebianMipsMultilibs = MultilibSetBuilder()
1128 .Either(M32, M64, MAbiN32)
1129 .makeMultilibSet()
1130 .FilterOut(NonExistent);
1133 // Sort candidates. Toolchain that best meets the directories tree goes first.
1134 // Then select the first toolchains matches command line flags.
1135 MultilibSet *Candidates[] = {&CSMipsMultilibs, &DebianMipsMultilibs};
1136 if (CSMipsMultilibs.size() < DebianMipsMultilibs.size())
1137 std::iter_swap(Candidates, Candidates + 1);
1138 for (const MultilibSet *Candidate : Candidates) {
1139 if (Candidate->select(Flags, Result.SelectedMultilibs)) {
1140 if (Candidate == &DebianMipsMultilibs)
1141 Result.BiarchSibling = Multilib();
1142 Result.Multilibs = *Candidate;
1143 return true;
1146 return false;
1149 static bool findMipsAndroidMultilibs(llvm::vfs::FileSystem &VFS, StringRef Path,
1150 const Multilib::flags_list &Flags,
1151 FilterNonExistent &NonExistent,
1152 DetectedMultilibs &Result) {
1154 MultilibSet AndroidMipsMultilibs =
1155 MultilibSetBuilder()
1156 .Maybe(MultilibBuilder("/mips-r2", {}, {}).flag("-march=mips32r2"))
1157 .Maybe(MultilibBuilder("/mips-r6", {}, {}).flag("-march=mips32r6"))
1158 .makeMultilibSet()
1159 .FilterOut(NonExistent);
1161 MultilibSet AndroidMipselMultilibs =
1162 MultilibSetBuilder()
1163 .Either(MultilibBuilder().flag("-march=mips32"),
1164 MultilibBuilder("/mips-r2", "", "/mips-r2")
1165 .flag("-march=mips32r2"),
1166 MultilibBuilder("/mips-r6", "", "/mips-r6")
1167 .flag("-march=mips32r6"))
1168 .makeMultilibSet()
1169 .FilterOut(NonExistent);
1171 MultilibSet AndroidMips64elMultilibs =
1172 MultilibSetBuilder()
1173 .Either(MultilibBuilder().flag("-march=mips64r6"),
1174 MultilibBuilder("/32/mips-r1", "", "/mips-r1")
1175 .flag("-march=mips32"),
1176 MultilibBuilder("/32/mips-r2", "", "/mips-r2")
1177 .flag("-march=mips32r2"),
1178 MultilibBuilder("/32/mips-r6", "", "/mips-r6")
1179 .flag("-march=mips32r6"))
1180 .makeMultilibSet()
1181 .FilterOut(NonExistent);
1183 MultilibSet *MS = &AndroidMipsMultilibs;
1184 if (VFS.exists(Path + "/mips-r6"))
1185 MS = &AndroidMipselMultilibs;
1186 else if (VFS.exists(Path + "/32"))
1187 MS = &AndroidMips64elMultilibs;
1188 if (MS->select(Flags, Result.SelectedMultilibs)) {
1189 Result.Multilibs = *MS;
1190 return true;
1192 return false;
1195 static bool findMipsMuslMultilibs(const Multilib::flags_list &Flags,
1196 FilterNonExistent &NonExistent,
1197 DetectedMultilibs &Result) {
1198 // Musl toolchain multilibs
1199 MultilibSet MuslMipsMultilibs;
1201 auto MArchMipsR2 = MultilibBuilder("")
1202 .osSuffix("/mips-r2-hard-musl")
1203 .flag("-EB")
1204 .flag("-EL", /*Disallow=*/true)
1205 .flag("-march=mips32r2");
1207 auto MArchMipselR2 = MultilibBuilder("/mipsel-r2-hard-musl")
1208 .flag("-EB", /*Disallow=*/true)
1209 .flag("-EL")
1210 .flag("-march=mips32r2");
1212 MuslMipsMultilibs = MultilibSetBuilder()
1213 .Either(MArchMipsR2, MArchMipselR2)
1214 .makeMultilibSet();
1216 // Specify the callback that computes the include directories.
1217 MuslMipsMultilibs.setIncludeDirsCallback([](const Multilib &M) {
1218 return std::vector<std::string>(
1219 {"/../sysroot" + M.osSuffix() + "/usr/include"});
1222 if (MuslMipsMultilibs.select(Flags, Result.SelectedMultilibs)) {
1223 Result.Multilibs = MuslMipsMultilibs;
1224 return true;
1226 return false;
1229 static bool findMipsMtiMultilibs(const Multilib::flags_list &Flags,
1230 FilterNonExistent &NonExistent,
1231 DetectedMultilibs &Result) {
1232 // CodeScape MTI toolchain v1.2 and early.
1233 MultilibSet MtiMipsMultilibsV1;
1235 auto MArchMips32 = MultilibBuilder("/mips32")
1236 .flag("-m32")
1237 .flag("-m64", /*Disallow=*/true)
1238 .flag("-mmicromips", /*Disallow=*/true)
1239 .flag("-march=mips32");
1241 auto MArchMicroMips = MultilibBuilder("/micromips")
1242 .flag("-m32")
1243 .flag("-m64", /*Disallow=*/true)
1244 .flag("-mmicromips");
1246 auto MArchMips64r2 = MultilibBuilder("/mips64r2")
1247 .flag("-m32", /*Disallow=*/true)
1248 .flag("-m64")
1249 .flag("-march=mips64r2");
1251 auto MArchMips64 = MultilibBuilder("/mips64")
1252 .flag("-m32", /*Disallow=*/true)
1253 .flag("-m64")
1254 .flag("-march=mips64r2", /*Disallow=*/true);
1256 auto MArchDefault = MultilibBuilder("")
1257 .flag("-m32")
1258 .flag("-m64", /*Disallow=*/true)
1259 .flag("-mmicromips", /*Disallow=*/true)
1260 .flag("-march=mips32r2");
1262 auto Mips16 = MultilibBuilder("/mips16").flag("-mips16");
1264 auto UCLibc = MultilibBuilder("/uclibc").flag("-muclibc");
1266 auto MAbi64 = MultilibBuilder("/64")
1267 .flag("-mabi=n64")
1268 .flag("-mabi=n32", /*Disallow=*/true)
1269 .flag("-m32", /*Disallow=*/true);
1271 auto BigEndian =
1272 MultilibBuilder("").flag("-EB").flag("-EL", /*Disallow=*/true);
1274 auto LittleEndian =
1275 MultilibBuilder("/el").flag("-EL").flag("-EB", /*Disallow=*/true);
1277 auto SoftFloat = MultilibBuilder("/sof").flag("-msoft-float");
1279 auto Nan2008 = MultilibBuilder("/nan2008").flag("-mnan=2008");
1281 MtiMipsMultilibsV1 =
1282 MultilibSetBuilder()
1283 .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64,
1284 MArchDefault)
1285 .Maybe(UCLibc)
1286 .Maybe(Mips16)
1287 .FilterOut("/mips64/mips16")
1288 .FilterOut("/mips64r2/mips16")
1289 .FilterOut("/micromips/mips16")
1290 .Maybe(MAbi64)
1291 .FilterOut("/micromips/64")
1292 .FilterOut("/mips32/64")
1293 .FilterOut("^/64")
1294 .FilterOut("/mips16/64")
1295 .Either(BigEndian, LittleEndian)
1296 .Maybe(SoftFloat)
1297 .Maybe(Nan2008)
1298 .FilterOut(".*sof/nan2008")
1299 .makeMultilibSet()
1300 .FilterOut(NonExistent)
1301 .setIncludeDirsCallback([](const Multilib &M) {
1302 std::vector<std::string> Dirs({"/include"});
1303 if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1304 Dirs.push_back("/../../../../sysroot/uclibc/usr/include");
1305 else
1306 Dirs.push_back("/../../../../sysroot/usr/include");
1307 return Dirs;
1311 // CodeScape IMG toolchain starting from v1.3.
1312 MultilibSet MtiMipsMultilibsV2;
1314 auto BeHard = MultilibBuilder("/mips-r2-hard")
1315 .flag("-EB")
1316 .flag("-msoft-float", /*Disallow=*/true)
1317 .flag("-mnan=2008", /*Disallow=*/true)
1318 .flag("-muclibc", /*Disallow=*/true);
1319 auto BeSoft = MultilibBuilder("/mips-r2-soft")
1320 .flag("-EB")
1321 .flag("-msoft-float")
1322 .flag("-mnan=2008", /*Disallow=*/true);
1323 auto ElHard = MultilibBuilder("/mipsel-r2-hard")
1324 .flag("-EL")
1325 .flag("-msoft-float", /*Disallow=*/true)
1326 .flag("-mnan=2008", /*Disallow=*/true)
1327 .flag("-muclibc", /*Disallow=*/true);
1328 auto ElSoft = MultilibBuilder("/mipsel-r2-soft")
1329 .flag("-EL")
1330 .flag("-msoft-float")
1331 .flag("-mnan=2008", /*Disallow=*/true)
1332 .flag("-mmicromips", /*Disallow=*/true);
1333 auto BeHardNan = MultilibBuilder("/mips-r2-hard-nan2008")
1334 .flag("-EB")
1335 .flag("-msoft-float", /*Disallow=*/true)
1336 .flag("-mnan=2008")
1337 .flag("-muclibc", /*Disallow=*/true);
1338 auto ElHardNan = MultilibBuilder("/mipsel-r2-hard-nan2008")
1339 .flag("-EL")
1340 .flag("-msoft-float", /*Disallow=*/true)
1341 .flag("-mnan=2008")
1342 .flag("-muclibc", /*Disallow=*/true)
1343 .flag("-mmicromips", /*Disallow=*/true);
1344 auto BeHardNanUclibc = MultilibBuilder("/mips-r2-hard-nan2008-uclibc")
1345 .flag("-EB")
1346 .flag("-msoft-float", /*Disallow=*/true)
1347 .flag("-mnan=2008")
1348 .flag("-muclibc");
1349 auto ElHardNanUclibc = MultilibBuilder("/mipsel-r2-hard-nan2008-uclibc")
1350 .flag("-EL")
1351 .flag("-msoft-float", /*Disallow=*/true)
1352 .flag("-mnan=2008")
1353 .flag("-muclibc");
1354 auto BeHardUclibc = MultilibBuilder("/mips-r2-hard-uclibc")
1355 .flag("-EB")
1356 .flag("-msoft-float", /*Disallow=*/true)
1357 .flag("-mnan=2008", /*Disallow=*/true)
1358 .flag("-muclibc");
1359 auto ElHardUclibc = MultilibBuilder("/mipsel-r2-hard-uclibc")
1360 .flag("-EL")
1361 .flag("-msoft-float", /*Disallow=*/true)
1362 .flag("-mnan=2008", /*Disallow=*/true)
1363 .flag("-muclibc");
1364 auto ElMicroHardNan = MultilibBuilder("/micromipsel-r2-hard-nan2008")
1365 .flag("-EL")
1366 .flag("-msoft-float", /*Disallow=*/true)
1367 .flag("-mnan=2008")
1368 .flag("-mmicromips");
1369 auto ElMicroSoft = MultilibBuilder("/micromipsel-r2-soft")
1370 .flag("-EL")
1371 .flag("-msoft-float")
1372 .flag("-mnan=2008", /*Disallow=*/true)
1373 .flag("-mmicromips");
1375 auto O32 = MultilibBuilder("/lib")
1376 .osSuffix("")
1377 .flag("-mabi=n32", /*Disallow=*/true)
1378 .flag("-mabi=n64", /*Disallow=*/true);
1379 auto N32 = MultilibBuilder("/lib32")
1380 .osSuffix("")
1381 .flag("-mabi=n32")
1382 .flag("-mabi=n64", /*Disallow=*/true);
1383 auto N64 = MultilibBuilder("/lib64")
1384 .osSuffix("")
1385 .flag("-mabi=n32", /*Disallow=*/true)
1386 .flag("-mabi=n64");
1388 MtiMipsMultilibsV2 =
1389 MultilibSetBuilder()
1390 .Either({BeHard, BeSoft, ElHard, ElSoft, BeHardNan, ElHardNan,
1391 BeHardNanUclibc, ElHardNanUclibc, BeHardUclibc,
1392 ElHardUclibc, ElMicroHardNan, ElMicroSoft})
1393 .Either(O32, N32, N64)
1394 .makeMultilibSet()
1395 .FilterOut(NonExistent)
1396 .setIncludeDirsCallback([](const Multilib &M) {
1397 return std::vector<std::string>({"/../../../../sysroot" +
1398 M.includeSuffix() +
1399 "/../usr/include"});
1401 .setFilePathsCallback([](const Multilib &M) {
1402 return std::vector<std::string>(
1403 {"/../../../../mips-mti-linux-gnu/lib" + M.gccSuffix()});
1406 for (auto *Candidate : {&MtiMipsMultilibsV1, &MtiMipsMultilibsV2}) {
1407 if (Candidate->select(Flags, Result.SelectedMultilibs)) {
1408 Result.Multilibs = *Candidate;
1409 return true;
1412 return false;
1415 static bool findMipsImgMultilibs(const Multilib::flags_list &Flags,
1416 FilterNonExistent &NonExistent,
1417 DetectedMultilibs &Result) {
1418 // CodeScape IMG toolchain v1.2 and early.
1419 MultilibSet ImgMultilibsV1;
1421 auto Mips64r6 = MultilibBuilder("/mips64r6")
1422 .flag("-m64")
1423 .flag("-m32", /*Disallow=*/true);
1425 auto LittleEndian =
1426 MultilibBuilder("/el").flag("-EL").flag("-EB", /*Disallow=*/true);
1428 auto MAbi64 = MultilibBuilder("/64")
1429 .flag("-mabi=n64")
1430 .flag("-mabi=n32", /*Disallow=*/true)
1431 .flag("-m32", /*Disallow=*/true);
1433 ImgMultilibsV1 =
1434 MultilibSetBuilder()
1435 .Maybe(Mips64r6)
1436 .Maybe(MAbi64)
1437 .Maybe(LittleEndian)
1438 .makeMultilibSet()
1439 .FilterOut(NonExistent)
1440 .setIncludeDirsCallback([](const Multilib &M) {
1441 return std::vector<std::string>(
1442 {"/include", "/../../../../sysroot/usr/include"});
1446 // CodeScape IMG toolchain starting from v1.3.
1447 MultilibSet ImgMultilibsV2;
1449 auto BeHard = MultilibBuilder("/mips-r6-hard")
1450 .flag("-EB")
1451 .flag("-msoft-float", /*Disallow=*/true)
1452 .flag("-mmicromips", /*Disallow=*/true);
1453 auto BeSoft = MultilibBuilder("/mips-r6-soft")
1454 .flag("-EB")
1455 .flag("-msoft-float")
1456 .flag("-mmicromips", /*Disallow=*/true);
1457 auto ElHard = MultilibBuilder("/mipsel-r6-hard")
1458 .flag("-EL")
1459 .flag("-msoft-float", /*Disallow=*/true)
1460 .flag("-mmicromips", /*Disallow=*/true);
1461 auto ElSoft = MultilibBuilder("/mipsel-r6-soft")
1462 .flag("-EL")
1463 .flag("-msoft-float")
1464 .flag("-mmicromips", /*Disallow=*/true);
1465 auto BeMicroHard = MultilibBuilder("/micromips-r6-hard")
1466 .flag("-EB")
1467 .flag("-msoft-float", /*Disallow=*/true)
1468 .flag("-mmicromips");
1469 auto BeMicroSoft = MultilibBuilder("/micromips-r6-soft")
1470 .flag("-EB")
1471 .flag("-msoft-float")
1472 .flag("-mmicromips");
1473 auto ElMicroHard = MultilibBuilder("/micromipsel-r6-hard")
1474 .flag("-EL")
1475 .flag("-msoft-float", /*Disallow=*/true)
1476 .flag("-mmicromips");
1477 auto ElMicroSoft = MultilibBuilder("/micromipsel-r6-soft")
1478 .flag("-EL")
1479 .flag("-msoft-float")
1480 .flag("-mmicromips");
1482 auto O32 = MultilibBuilder("/lib")
1483 .osSuffix("")
1484 .flag("-mabi=n32", /*Disallow=*/true)
1485 .flag("-mabi=n64", /*Disallow=*/true);
1486 auto N32 = MultilibBuilder("/lib32")
1487 .osSuffix("")
1488 .flag("-mabi=n32")
1489 .flag("-mabi=n64", /*Disallow=*/true);
1490 auto N64 = MultilibBuilder("/lib64")
1491 .osSuffix("")
1492 .flag("-mabi=n32", /*Disallow=*/true)
1493 .flag("-mabi=n64");
1495 ImgMultilibsV2 =
1496 MultilibSetBuilder()
1497 .Either({BeHard, BeSoft, ElHard, ElSoft, BeMicroHard, BeMicroSoft,
1498 ElMicroHard, ElMicroSoft})
1499 .Either(O32, N32, N64)
1500 .makeMultilibSet()
1501 .FilterOut(NonExistent)
1502 .setIncludeDirsCallback([](const Multilib &M) {
1503 return std::vector<std::string>({"/../../../../sysroot" +
1504 M.includeSuffix() +
1505 "/../usr/include"});
1507 .setFilePathsCallback([](const Multilib &M) {
1508 return std::vector<std::string>(
1509 {"/../../../../mips-img-linux-gnu/lib" + M.gccSuffix()});
1512 for (auto *Candidate : {&ImgMultilibsV1, &ImgMultilibsV2}) {
1513 if (Candidate->select(Flags, Result.SelectedMultilibs)) {
1514 Result.Multilibs = *Candidate;
1515 return true;
1518 return false;
1521 bool clang::driver::findMIPSMultilibs(const Driver &D,
1522 const llvm::Triple &TargetTriple,
1523 StringRef Path, const ArgList &Args,
1524 DetectedMultilibs &Result) {
1525 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1527 StringRef CPUName;
1528 StringRef ABIName;
1529 tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
1531 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1533 Multilib::flags_list Flags;
1534 addMultilibFlag(TargetTriple.isMIPS32(), "-m32", Flags);
1535 addMultilibFlag(TargetTriple.isMIPS64(), "-m64", Flags);
1536 addMultilibFlag(isMips16(Args), "-mips16", Flags);
1537 addMultilibFlag(CPUName == "mips32", "-march=mips32", Flags);
1538 addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" ||
1539 CPUName == "mips32r5" || CPUName == "p5600",
1540 "-march=mips32r2", Flags);
1541 addMultilibFlag(CPUName == "mips32r6", "-march=mips32r6", Flags);
1542 addMultilibFlag(CPUName == "mips64", "-march=mips64", Flags);
1543 addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" ||
1544 CPUName == "mips64r5" || CPUName == "octeon" ||
1545 CPUName == "octeon+",
1546 "-march=mips64r2", Flags);
1547 addMultilibFlag(CPUName == "mips64r6", "-march=mips64r6", Flags);
1548 addMultilibFlag(isMicroMips(Args), "-mmicromips", Flags);
1549 addMultilibFlag(tools::mips::isUCLibc(Args), "-muclibc", Flags);
1550 addMultilibFlag(tools::mips::isNaN2008(D, Args, TargetTriple), "-mnan=2008",
1551 Flags);
1552 addMultilibFlag(ABIName == "n32", "-mabi=n32", Flags);
1553 addMultilibFlag(ABIName == "n64", "-mabi=n64", Flags);
1554 addMultilibFlag(isSoftFloatABI(Args), "-msoft-float", Flags);
1555 addMultilibFlag(!isSoftFloatABI(Args), "-mhard-float", Flags);
1556 addMultilibFlag(isMipsEL(TargetArch), "-EL", Flags);
1557 addMultilibFlag(!isMipsEL(TargetArch), "-EB", Flags);
1559 if (TargetTriple.isAndroid())
1560 return findMipsAndroidMultilibs(D.getVFS(), Path, Flags, NonExistent,
1561 Result);
1563 if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
1564 TargetTriple.getOS() == llvm::Triple::Linux &&
1565 TargetTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
1566 return findMipsMuslMultilibs(Flags, NonExistent, Result);
1568 if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
1569 TargetTriple.getOS() == llvm::Triple::Linux &&
1570 TargetTriple.isGNUEnvironment())
1571 return findMipsMtiMultilibs(Flags, NonExistent, Result);
1573 if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1574 TargetTriple.getOS() == llvm::Triple::Linux &&
1575 TargetTriple.isGNUEnvironment())
1576 return findMipsImgMultilibs(Flags, NonExistent, Result);
1578 if (findMipsCsMultilibs(Flags, NonExistent, Result))
1579 return true;
1581 // Fallback to the regular toolchain-tree structure.
1582 Multilib Default;
1583 Result.Multilibs.push_back(Default);
1584 Result.Multilibs.FilterOut(NonExistent);
1586 if (Result.Multilibs.select(Flags, Result.SelectedMultilibs)) {
1587 Result.BiarchSibling = Multilib();
1588 return true;
1591 return false;
1594 static void findAndroidArmMultilibs(const Driver &D,
1595 const llvm::Triple &TargetTriple,
1596 StringRef Path, const ArgList &Args,
1597 DetectedMultilibs &Result) {
1598 // Find multilibs with subdirectories like armv7-a, thumb, armv7-a/thumb.
1599 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1600 MultilibBuilder ArmV7Multilib = MultilibBuilder("/armv7-a")
1601 .flag("-march=armv7-a")
1602 .flag("-mthumb", /*Disallow=*/true);
1603 MultilibBuilder ThumbMultilib = MultilibBuilder("/thumb")
1604 .flag("-march=armv7-a", /*Disallow=*/true)
1605 .flag("-mthumb");
1606 MultilibBuilder ArmV7ThumbMultilib =
1607 MultilibBuilder("/armv7-a/thumb").flag("-march=armv7-a").flag("-mthumb");
1608 MultilibBuilder DefaultMultilib =
1609 MultilibBuilder("")
1610 .flag("-march=armv7-a", /*Disallow=*/true)
1611 .flag("-mthumb", /*Disallow=*/true);
1612 MultilibSet AndroidArmMultilibs =
1613 MultilibSetBuilder()
1614 .Either(ThumbMultilib, ArmV7Multilib, ArmV7ThumbMultilib,
1615 DefaultMultilib)
1616 .makeMultilibSet()
1617 .FilterOut(NonExistent);
1619 Multilib::flags_list Flags;
1620 llvm::StringRef Arch = Args.getLastArgValue(options::OPT_march_EQ);
1621 bool IsArmArch = TargetTriple.getArch() == llvm::Triple::arm;
1622 bool IsThumbArch = TargetTriple.getArch() == llvm::Triple::thumb;
1623 bool IsV7SubArch = TargetTriple.getSubArch() == llvm::Triple::ARMSubArch_v7;
1624 bool IsThumbMode = IsThumbArch ||
1625 Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, false) ||
1626 (IsArmArch && llvm::ARM::parseArchISA(Arch) == llvm::ARM::ISAKind::THUMB);
1627 bool IsArmV7Mode = (IsArmArch || IsThumbArch) &&
1628 (llvm::ARM::parseArchVersion(Arch) == 7 ||
1629 (IsArmArch && Arch == "" && IsV7SubArch));
1630 addMultilibFlag(IsArmV7Mode, "-march=armv7-a", Flags);
1631 addMultilibFlag(IsThumbMode, "-mthumb", Flags);
1633 if (AndroidArmMultilibs.select(Flags, Result.SelectedMultilibs))
1634 Result.Multilibs = AndroidArmMultilibs;
1637 static bool findMSP430Multilibs(const Driver &D,
1638 const llvm::Triple &TargetTriple,
1639 StringRef Path, const ArgList &Args,
1640 DetectedMultilibs &Result) {
1641 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1642 MultilibBuilder WithoutExceptions =
1643 MultilibBuilder("/430").flag("-exceptions", /*Disallow=*/true);
1644 MultilibBuilder WithExceptions =
1645 MultilibBuilder("/430/exceptions").flag("-exceptions");
1647 // FIXME: when clang starts to support msp430x ISA additional logic
1648 // to select between multilib must be implemented
1649 // MultilibBuilder MSP430xMultilib = MultilibBuilder("/large");
1651 Result.Multilibs.push_back(WithoutExceptions.makeMultilib());
1652 Result.Multilibs.push_back(WithExceptions.makeMultilib());
1653 Result.Multilibs.FilterOut(NonExistent);
1655 Multilib::flags_list Flags;
1656 addMultilibFlag(Args.hasFlag(options::OPT_fexceptions,
1657 options::OPT_fno_exceptions, false),
1658 "-exceptions", Flags);
1659 if (Result.Multilibs.select(Flags, Result.SelectedMultilibs))
1660 return true;
1662 return false;
1665 static void findCSKYMultilibs(const Driver &D, const llvm::Triple &TargetTriple,
1666 StringRef Path, const ArgList &Args,
1667 DetectedMultilibs &Result) {
1668 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1670 tools::csky::FloatABI TheFloatABI = tools::csky::getCSKYFloatABI(D, Args);
1671 std::optional<llvm::StringRef> Res =
1672 tools::csky::getCSKYArchName(D, Args, TargetTriple);
1674 if (!Res)
1675 return;
1676 auto ARCHName = *Res;
1678 Multilib::flags_list Flags;
1679 addMultilibFlag(TheFloatABI == tools::csky::FloatABI::Hard, "-hard-fp",
1680 Flags);
1681 addMultilibFlag(TheFloatABI == tools::csky::FloatABI::SoftFP, "-soft-fp",
1682 Flags);
1683 addMultilibFlag(TheFloatABI == tools::csky::FloatABI::Soft, "-soft", Flags);
1684 addMultilibFlag(ARCHName == "ck801", "-march=ck801", Flags);
1685 addMultilibFlag(ARCHName == "ck802", "-march=ck802", Flags);
1686 addMultilibFlag(ARCHName == "ck803", "-march=ck803", Flags);
1687 addMultilibFlag(ARCHName == "ck804", "-march=ck804", Flags);
1688 addMultilibFlag(ARCHName == "ck805", "-march=ck805", Flags);
1689 addMultilibFlag(ARCHName == "ck807", "-march=ck807", Flags);
1690 addMultilibFlag(ARCHName == "ck810", "-march=ck810", Flags);
1691 addMultilibFlag(ARCHName == "ck810v", "-march=ck810v", Flags);
1692 addMultilibFlag(ARCHName == "ck860", "-march=ck860", Flags);
1693 addMultilibFlag(ARCHName == "ck860v", "-march=ck860v", Flags);
1695 bool isBigEndian = false;
1696 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
1697 options::OPT_mbig_endian))
1698 isBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
1699 addMultilibFlag(isBigEndian, "-EB", Flags);
1701 auto HardFloat = MultilibBuilder("/hard-fp").flag("-hard-fp");
1702 auto SoftFpFloat = MultilibBuilder("/soft-fp").flag("-soft-fp");
1703 auto SoftFloat = MultilibBuilder("").flag("-soft");
1704 auto Arch801 = MultilibBuilder("/ck801").flag("-march=ck801");
1705 auto Arch802 = MultilibBuilder("/ck802").flag("-march=ck802");
1706 auto Arch803 = MultilibBuilder("/ck803").flag("-march=ck803");
1707 // CK804 use the same library as CK803
1708 auto Arch804 = MultilibBuilder("/ck803").flag("-march=ck804");
1709 auto Arch805 = MultilibBuilder("/ck805").flag("-march=ck805");
1710 auto Arch807 = MultilibBuilder("/ck807").flag("-march=ck807");
1711 auto Arch810 = MultilibBuilder("").flag("-march=ck810");
1712 auto Arch810v = MultilibBuilder("/ck810v").flag("-march=ck810v");
1713 auto Arch860 = MultilibBuilder("/ck860").flag("-march=ck860");
1714 auto Arch860v = MultilibBuilder("/ck860v").flag("-march=ck860v");
1715 auto BigEndian = MultilibBuilder("/big").flag("-EB");
1717 MultilibSet CSKYMultilibs =
1718 MultilibSetBuilder()
1719 .Maybe(BigEndian)
1720 .Either({Arch801, Arch802, Arch803, Arch804, Arch805, Arch807,
1721 Arch810, Arch810v, Arch860, Arch860v})
1722 .Either(HardFloat, SoftFpFloat, SoftFloat)
1723 .makeMultilibSet()
1724 .FilterOut(NonExistent);
1726 if (CSKYMultilibs.select(Flags, Result.SelectedMultilibs))
1727 Result.Multilibs = CSKYMultilibs;
1730 static void findRISCVBareMetalMultilibs(const Driver &D,
1731 const llvm::Triple &TargetTriple,
1732 StringRef Path, const ArgList &Args,
1733 DetectedMultilibs &Result) {
1734 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1735 struct RiscvMultilib {
1736 StringRef march;
1737 StringRef mabi;
1739 // currently only support the set of multilibs like riscv-gnu-toolchain does.
1740 // TODO: support MULTILIB_REUSE
1741 constexpr RiscvMultilib RISCVMultilibSet[] = {
1742 {"rv32i", "ilp32"}, {"rv32im", "ilp32"}, {"rv32iac", "ilp32"},
1743 {"rv32imac", "ilp32"}, {"rv32imafc", "ilp32f"}, {"rv64imac", "lp64"},
1744 {"rv64imafdc", "lp64d"}};
1746 std::vector<MultilibBuilder> Ms;
1747 for (auto Element : RISCVMultilibSet) {
1748 // multilib path rule is ${march}/${mabi}
1749 Ms.emplace_back(
1750 MultilibBuilder(
1751 (Twine(Element.march) + "/" + Twine(Element.mabi)).str())
1752 .flag(Twine("-march=", Element.march).str())
1753 .flag(Twine("-mabi=", Element.mabi).str()));
1755 MultilibSet RISCVMultilibs =
1756 MultilibSetBuilder()
1757 .Either(Ms)
1758 .makeMultilibSet()
1759 .FilterOut(NonExistent)
1760 .setFilePathsCallback([](const Multilib &M) {
1761 return std::vector<std::string>(
1762 {M.gccSuffix(),
1763 "/../../../../riscv64-unknown-elf/lib" + M.gccSuffix(),
1764 "/../../../../riscv32-unknown-elf/lib" + M.gccSuffix()});
1767 Multilib::flags_list Flags;
1768 llvm::StringSet<> Added_ABIs;
1769 StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple);
1770 StringRef MArch = tools::riscv::getRISCVArch(Args, TargetTriple);
1771 for (auto Element : RISCVMultilibSet) {
1772 addMultilibFlag(MArch == Element.march,
1773 Twine("-march=", Element.march).str().c_str(), Flags);
1774 if (!Added_ABIs.count(Element.mabi)) {
1775 Added_ABIs.insert(Element.mabi);
1776 addMultilibFlag(ABIName == Element.mabi,
1777 Twine("-mabi=", Element.mabi).str().c_str(), Flags);
1781 if (RISCVMultilibs.select(Flags, Result.SelectedMultilibs))
1782 Result.Multilibs = RISCVMultilibs;
1785 static void findRISCVMultilibs(const Driver &D,
1786 const llvm::Triple &TargetTriple, StringRef Path,
1787 const ArgList &Args, DetectedMultilibs &Result) {
1788 if (TargetTriple.getOS() == llvm::Triple::UnknownOS)
1789 return findRISCVBareMetalMultilibs(D, TargetTriple, Path, Args, Result);
1791 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1792 MultilibBuilder Ilp32 =
1793 MultilibBuilder("lib32/ilp32").flag("-m32").flag("-mabi=ilp32");
1794 MultilibBuilder Ilp32f =
1795 MultilibBuilder("lib32/ilp32f").flag("-m32").flag("-mabi=ilp32f");
1796 MultilibBuilder Ilp32d =
1797 MultilibBuilder("lib32/ilp32d").flag("-m32").flag("-mabi=ilp32d");
1798 MultilibBuilder Lp64 =
1799 MultilibBuilder("lib64/lp64").flag("-m64").flag("-mabi=lp64");
1800 MultilibBuilder Lp64f =
1801 MultilibBuilder("lib64/lp64f").flag("-m64").flag("-mabi=lp64f");
1802 MultilibBuilder Lp64d =
1803 MultilibBuilder("lib64/lp64d").flag("-m64").flag("-mabi=lp64d");
1804 MultilibSet RISCVMultilibs =
1805 MultilibSetBuilder()
1806 .Either({Ilp32, Ilp32f, Ilp32d, Lp64, Lp64f, Lp64d})
1807 .makeMultilibSet()
1808 .FilterOut(NonExistent);
1810 Multilib::flags_list Flags;
1811 bool IsRV64 = TargetTriple.getArch() == llvm::Triple::riscv64;
1812 StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple);
1814 addMultilibFlag(!IsRV64, "-m32", Flags);
1815 addMultilibFlag(IsRV64, "-m64", Flags);
1816 addMultilibFlag(ABIName == "ilp32", "-mabi=ilp32", Flags);
1817 addMultilibFlag(ABIName == "ilp32f", "-mabi=ilp32f", Flags);
1818 addMultilibFlag(ABIName == "ilp32d", "-mabi=ilp32d", Flags);
1819 addMultilibFlag(ABIName == "lp64", "-mabi=lp64", Flags);
1820 addMultilibFlag(ABIName == "lp64f", "-mabi=lp64f", Flags);
1821 addMultilibFlag(ABIName == "lp64d", "-mabi=lp64d", Flags);
1823 if (RISCVMultilibs.select(Flags, Result.SelectedMultilibs))
1824 Result.Multilibs = RISCVMultilibs;
1827 static bool findBiarchMultilibs(const Driver &D,
1828 const llvm::Triple &TargetTriple,
1829 StringRef Path, const ArgList &Args,
1830 bool NeedsBiarchSuffix,
1831 DetectedMultilibs &Result) {
1832 MultilibBuilder DefaultBuilder;
1834 // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1835 // in what would normally be GCCInstallPath and put the 64-bit
1836 // libs in a subdirectory named 64. The simple logic we follow is that
1837 // *if* there is a subdirectory of the right name with crtbegin.o in it,
1838 // we use that. If not, and if not a biarch triple alias, we look for
1839 // crtbegin.o without the subdirectory.
1841 StringRef Suff64 = "/64";
1842 // Solaris uses platform-specific suffixes instead of /64.
1843 if (TargetTriple.isOSSolaris()) {
1844 switch (TargetTriple.getArch()) {
1845 case llvm::Triple::x86:
1846 case llvm::Triple::x86_64:
1847 Suff64 = "/amd64";
1848 break;
1849 case llvm::Triple::sparc:
1850 case llvm::Triple::sparcv9:
1851 Suff64 = "/sparcv9";
1852 break;
1853 default:
1854 break;
1858 Multilib Alt64 = MultilibBuilder()
1859 .gccSuffix(Suff64)
1860 .includeSuffix(Suff64)
1861 .flag("-m32", /*Disallow=*/true)
1862 .flag("-m64")
1863 .flag("-mx32", /*Disallow=*/true)
1864 .makeMultilib();
1865 Multilib Alt32 = MultilibBuilder()
1866 .gccSuffix("/32")
1867 .includeSuffix("/32")
1868 .flag("-m32")
1869 .flag("-m64", /*Disallow=*/true)
1870 .flag("-mx32", /*Disallow=*/true)
1871 .makeMultilib();
1872 Multilib Altx32 = MultilibBuilder()
1873 .gccSuffix("/x32")
1874 .includeSuffix("/x32")
1875 .flag("-m32", /*Disallow=*/true)
1876 .flag("-m64", /*Disallow=*/true)
1877 .flag("-mx32")
1878 .makeMultilib();
1879 Multilib Alt32sparc = MultilibBuilder()
1880 .gccSuffix("/sparcv8plus")
1881 .includeSuffix("/sparcv8plus")
1882 .flag("-m32")
1883 .flag("-m64", /*Disallow=*/true)
1884 .makeMultilib();
1886 // GCC toolchain for IAMCU doesn't have crtbegin.o, so look for libgcc.a.
1887 FilterNonExistent NonExistent(
1888 Path, TargetTriple.isOSIAMCU() ? "/libgcc.a" : "/crtbegin.o", D.getVFS());
1890 // Determine default multilib from: 32, 64, x32
1891 // Also handle cases such as 64 on 32, 32 on 64, etc.
1892 enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
1893 const bool IsX32 = TargetTriple.isX32();
1894 if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
1895 Want = WANT64;
1896 if (TargetTriple.isArch32Bit() && !NonExistent(Alt32sparc))
1897 Want = WANT64;
1898 else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
1899 Want = WANT64;
1900 else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
1901 Want = WANT32;
1902 else if (TargetTriple.isArch64Bit() && !NonExistent(Alt32sparc))
1903 Want = WANT64;
1904 else {
1905 if (TargetTriple.isArch32Bit())
1906 Want = NeedsBiarchSuffix ? WANT64 : WANT32;
1907 else if (IsX32)
1908 Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
1909 else
1910 Want = NeedsBiarchSuffix ? WANT32 : WANT64;
1913 if (Want == WANT32)
1914 DefaultBuilder.flag("-m32")
1915 .flag("-m64", /*Disallow=*/true)
1916 .flag("-mx32", /*Disallow=*/true);
1917 else if (Want == WANT64)
1918 DefaultBuilder.flag("-m32", /*Disallow=*/true)
1919 .flag("-m64")
1920 .flag("-mx32", /*Disallow=*/true);
1921 else if (Want == WANTX32)
1922 DefaultBuilder.flag("-m32", /*Disallow=*/true)
1923 .flag("-m64", /*Disallow=*/true)
1924 .flag("-mx32");
1925 else
1926 return false;
1928 Multilib Default = DefaultBuilder.makeMultilib();
1930 Result.Multilibs.push_back(Default);
1931 Result.Multilibs.push_back(Alt64);
1932 Result.Multilibs.push_back(Alt32);
1933 Result.Multilibs.push_back(Altx32);
1934 Result.Multilibs.push_back(Alt32sparc);
1936 Result.Multilibs.FilterOut(NonExistent);
1938 Multilib::flags_list Flags;
1939 addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "-m64", Flags);
1940 addMultilibFlag(TargetTriple.isArch32Bit(), "-m32", Flags);
1941 addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "-mx32", Flags);
1943 if (!Result.Multilibs.select(Flags, Result.SelectedMultilibs))
1944 return false;
1946 if (Result.SelectedMultilibs.back() == Alt64 ||
1947 Result.SelectedMultilibs.back() == Alt32 ||
1948 Result.SelectedMultilibs.back() == Altx32 ||
1949 Result.SelectedMultilibs.back() == Alt32sparc)
1950 Result.BiarchSibling = Default;
1952 return true;
1955 /// Generic_GCC - A tool chain using the 'gcc' command to perform
1956 /// all subcommands; this relies on gcc translating the majority of
1957 /// command line options.
1959 /// Less-than for GCCVersion, implementing a Strict Weak Ordering.
1960 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
1961 int RHSPatch,
1962 StringRef RHSPatchSuffix) const {
1963 if (Major != RHSMajor)
1964 return Major < RHSMajor;
1965 if (Minor != RHSMinor) {
1966 // Note that versions without a specified minor sort higher than those with
1967 // a minor.
1968 if (RHSMinor == -1)
1969 return true;
1970 if (Minor == -1)
1971 return false;
1972 return Minor < RHSMinor;
1974 if (Patch != RHSPatch) {
1975 // Note that versions without a specified patch sort higher than those with
1976 // a patch.
1977 if (RHSPatch == -1)
1978 return true;
1979 if (Patch == -1)
1980 return false;
1982 // Otherwise just sort on the patch itself.
1983 return Patch < RHSPatch;
1985 if (PatchSuffix != RHSPatchSuffix) {
1986 // Sort empty suffixes higher.
1987 if (RHSPatchSuffix.empty())
1988 return true;
1989 if (PatchSuffix.empty())
1990 return false;
1992 // Provide a lexicographic sort to make this a total ordering.
1993 return PatchSuffix < RHSPatchSuffix;
1996 // The versions are equal.
1997 return false;
2000 /// Parse a GCCVersion object out of a string of text.
2002 /// This is the primary means of forming GCCVersion objects.
2003 /*static*/
2004 Generic_GCC::GCCVersion Generic_GCC::GCCVersion::Parse(StringRef VersionText) {
2005 const GCCVersion BadVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
2006 std::pair<StringRef, StringRef> First = VersionText.split('.');
2007 std::pair<StringRef, StringRef> Second = First.second.split('.');
2009 StringRef MajorStr = First.first;
2010 StringRef MinorStr = Second.first;
2011 StringRef PatchStr = Second.second;
2013 GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
2015 // Parse version number strings such as:
2016 // 5
2017 // 4.4
2018 // 4.4-patched
2019 // 4.4.0
2020 // 4.4.x
2021 // 4.4.2-rc4
2022 // 4.4.x-patched
2023 // 10-win32
2024 // Split on '.', handle 1, 2 or 3 such segments. Each segment must contain
2025 // purely a number, except for the last one, where a non-number suffix
2026 // is stored in PatchSuffix. The third segment is allowed to not contain
2027 // a number at all.
2029 auto TryParseLastNumber = [&](StringRef Segment, int &Number,
2030 std::string &OutStr) -> bool {
2031 // Look for a number prefix and parse that, and split out any trailing
2032 // string into GoodVersion.PatchSuffix.
2034 if (size_t EndNumber = Segment.find_first_not_of("0123456789")) {
2035 StringRef NumberStr = Segment.slice(0, EndNumber);
2036 if (NumberStr.getAsInteger(10, Number) || Number < 0)
2037 return false;
2038 OutStr = NumberStr;
2039 GoodVersion.PatchSuffix = Segment.substr(EndNumber);
2040 return true;
2042 return false;
2044 auto TryParseNumber = [](StringRef Segment, int &Number) -> bool {
2045 if (Segment.getAsInteger(10, Number) || Number < 0)
2046 return false;
2047 return true;
2050 if (MinorStr.empty()) {
2051 // If no minor string, major is the last segment
2052 if (!TryParseLastNumber(MajorStr, GoodVersion.Major, GoodVersion.MajorStr))
2053 return BadVersion;
2054 return GoodVersion;
2057 if (!TryParseNumber(MajorStr, GoodVersion.Major))
2058 return BadVersion;
2059 GoodVersion.MajorStr = MajorStr;
2061 if (PatchStr.empty()) {
2062 // If no patch string, minor is the last segment
2063 if (!TryParseLastNumber(MinorStr, GoodVersion.Minor, GoodVersion.MinorStr))
2064 return BadVersion;
2065 return GoodVersion;
2068 if (!TryParseNumber(MinorStr, GoodVersion.Minor))
2069 return BadVersion;
2070 GoodVersion.MinorStr = MinorStr;
2072 // For the last segment, tolerate a missing number.
2073 std::string DummyStr;
2074 TryParseLastNumber(PatchStr, GoodVersion.Patch, DummyStr);
2075 return GoodVersion;
2078 static llvm::StringRef getGCCToolchainDir(const ArgList &Args,
2079 llvm::StringRef SysRoot) {
2080 const Arg *A = Args.getLastArg(clang::driver::options::OPT_gcc_toolchain);
2081 if (A)
2082 return A->getValue();
2084 // If we have a SysRoot, ignore GCC_INSTALL_PREFIX.
2085 // GCC_INSTALL_PREFIX specifies the gcc installation for the default
2086 // sysroot and is likely not valid with a different sysroot.
2087 if (!SysRoot.empty())
2088 return "";
2090 return GCC_INSTALL_PREFIX;
2093 /// Initialize a GCCInstallationDetector from the driver.
2095 /// This performs all of the autodetection and sets up the various paths.
2096 /// Once constructed, a GCCInstallationDetector is essentially immutable.
2098 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
2099 /// should instead pull the target out of the driver. This is currently
2100 /// necessary because the driver doesn't store the final version of the target
2101 /// triple.
2102 void Generic_GCC::GCCInstallationDetector::init(
2103 const llvm::Triple &TargetTriple, const ArgList &Args) {
2104 llvm::Triple BiarchVariantTriple = TargetTriple.isArch32Bit()
2105 ? TargetTriple.get64BitArchVariant()
2106 : TargetTriple.get32BitArchVariant();
2107 // The library directories which may contain GCC installations.
2108 SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
2109 // The compatible GCC triples for this particular architecture.
2110 SmallVector<StringRef, 16> CandidateTripleAliases;
2111 SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
2112 CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
2113 CandidateTripleAliases, CandidateBiarchLibDirs,
2114 CandidateBiarchTripleAliases);
2116 TripleNoVendor = TargetTriple.getArchName().str() + "-" +
2117 TargetTriple.getOSAndEnvironmentName().str();
2118 StringRef TripleNoVendorRef(TripleNoVendor);
2120 // If --gcc-install-dir= is specified, skip filesystem detection.
2121 if (const Arg *A =
2122 Args.getLastArg(clang::driver::options::OPT_gcc_install_dir_EQ);
2123 A && A->getValue()[0]) {
2124 StringRef InstallDir = A->getValue();
2125 if (!ScanGCCForMultilibs(TargetTriple, Args, InstallDir, false)) {
2126 D.Diag(diag::err_drv_invalid_gcc_install_dir) << InstallDir;
2127 } else {
2128 (void)InstallDir.consume_back("/");
2129 StringRef VersionText = llvm::sys::path::filename(InstallDir);
2130 StringRef TripleText =
2131 llvm::sys::path::filename(llvm::sys::path::parent_path(InstallDir));
2133 Version = GCCVersion::Parse(VersionText);
2134 GCCTriple.setTriple(TripleText);
2135 GCCInstallPath = std::string(InstallDir);
2136 GCCParentLibPath = GCCInstallPath + "/../../..";
2137 IsValid = true;
2139 return;
2142 // Compute the set of prefixes for our search.
2143 SmallVector<std::string, 8> Prefixes;
2144 StringRef GCCToolchainDir = getGCCToolchainDir(Args, D.SysRoot);
2145 if (GCCToolchainDir != "") {
2146 if (GCCToolchainDir.back() == '/')
2147 GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
2149 Prefixes.push_back(std::string(GCCToolchainDir));
2150 } else {
2151 // If we have a SysRoot, try that first.
2152 if (!D.SysRoot.empty()) {
2153 Prefixes.push_back(D.SysRoot);
2154 AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
2157 // Then look for gcc installed alongside clang.
2158 Prefixes.push_back(D.InstalledDir + "/..");
2160 // Next, look for prefix(es) that correspond to distribution-supplied gcc
2161 // installations.
2162 if (D.SysRoot.empty()) {
2163 // Typically /usr.
2164 AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
2167 // Try to respect gcc-config on Gentoo if --gcc-toolchain is not provided.
2168 // This avoids accidentally enforcing the system GCC version when using a
2169 // custom toolchain.
2170 SmallVector<StringRef, 16> GentooTestTriples;
2171 // Try to match an exact triple as target triple first.
2172 // e.g. crossdev -S x86_64-gentoo-linux-gnu will install gcc libs for
2173 // x86_64-gentoo-linux-gnu. But "clang -target x86_64-gentoo-linux-gnu"
2174 // may pick the libraries for x86_64-pc-linux-gnu even when exact matching
2175 // triple x86_64-gentoo-linux-gnu is present.
2176 GentooTestTriples.push_back(TargetTriple.str());
2177 GentooTestTriples.append(CandidateTripleAliases.begin(),
2178 CandidateTripleAliases.end());
2179 if (ScanGentooConfigs(TargetTriple, Args, GentooTestTriples,
2180 CandidateBiarchTripleAliases))
2181 return;
2184 // Loop over the various components which exist and select the best GCC
2185 // installation available. GCC installs are ranked by version number.
2186 const GCCVersion VersionZero = GCCVersion::Parse("0.0.0");
2187 Version = VersionZero;
2188 for (const std::string &Prefix : Prefixes) {
2189 auto &VFS = D.getVFS();
2190 if (!VFS.exists(Prefix))
2191 continue;
2192 for (StringRef Suffix : CandidateLibDirs) {
2193 const std::string LibDir = concat(Prefix, Suffix);
2194 if (!VFS.exists(LibDir))
2195 continue;
2196 // Maybe filter out <libdir>/gcc and <libdir>/gcc-cross.
2197 bool GCCDirExists = VFS.exists(LibDir + "/gcc");
2198 bool GCCCrossDirExists = VFS.exists(LibDir + "/gcc-cross");
2199 // Try to match the exact target triple first.
2200 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, TargetTriple.str(),
2201 false, GCCDirExists, GCCCrossDirExists);
2202 // If vendor is unknown, let's try triple without vendor.
2203 if (TargetTriple.getVendor() == llvm::Triple::UnknownVendor)
2204 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, TripleNoVendorRef,
2205 false, GCCDirExists, GCCCrossDirExists);
2206 for (StringRef Candidate : CandidateTripleAliases)
2207 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, false,
2208 GCCDirExists, GCCCrossDirExists);
2210 for (StringRef Suffix : CandidateBiarchLibDirs) {
2211 const std::string LibDir = Prefix + Suffix.str();
2212 if (!VFS.exists(LibDir))
2213 continue;
2214 bool GCCDirExists = VFS.exists(LibDir + "/gcc");
2215 bool GCCCrossDirExists = VFS.exists(LibDir + "/gcc-cross");
2216 for (StringRef Candidate : CandidateBiarchTripleAliases)
2217 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, true,
2218 GCCDirExists, GCCCrossDirExists);
2221 // Skip other prefixes once a GCC installation is found.
2222 if (Version > VersionZero)
2223 break;
2227 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
2228 for (const auto &InstallPath : CandidateGCCInstallPaths)
2229 OS << "Found candidate GCC installation: " << InstallPath << "\n";
2231 if (!GCCInstallPath.empty())
2232 OS << "Selected GCC installation: " << GCCInstallPath << "\n";
2234 for (const auto &Multilib : Multilibs)
2235 OS << "Candidate multilib: " << Multilib << "\n";
2237 if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
2238 OS << "Selected multilib: " << SelectedMultilib << "\n";
2241 bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const {
2242 if (BiarchSibling) {
2243 M = *BiarchSibling;
2244 return true;
2246 return false;
2249 void Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes(
2250 const llvm::Triple &TargetTriple, SmallVectorImpl<std::string> &Prefixes,
2251 StringRef SysRoot) {
2253 if (TargetTriple.isOSHaiku()) {
2254 Prefixes.push_back(concat(SysRoot, "/boot/system/develop/tools"));
2255 return;
2258 if (TargetTriple.isOSSolaris()) {
2259 // Solaris is a special case.
2260 // The GCC installation is under
2261 // /usr/gcc/<major>.<minor>/lib/gcc/<triple>/<major>.<minor>.<patch>/
2262 // so we need to find those /usr/gcc/*/lib/gcc libdirs and go with
2263 // /usr/gcc/<version> as a prefix.
2265 SmallVector<std::pair<GCCVersion, std::string>, 8> SolarisPrefixes;
2266 std::string PrefixDir = concat(SysRoot, "/usr/gcc");
2267 std::error_code EC;
2268 for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin(PrefixDir, EC),
2270 !EC && LI != LE; LI = LI.increment(EC)) {
2271 StringRef VersionText = llvm::sys::path::filename(LI->path());
2272 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2274 // Filter out obviously bad entries.
2275 if (CandidateVersion.Major == -1 || CandidateVersion.isOlderThan(4, 1, 1))
2276 continue;
2278 std::string CandidatePrefix = PrefixDir + "/" + VersionText.str();
2279 std::string CandidateLibPath = CandidatePrefix + "/lib/gcc";
2280 if (!D.getVFS().exists(CandidateLibPath))
2281 continue;
2283 SolarisPrefixes.emplace_back(
2284 std::make_pair(CandidateVersion, CandidatePrefix));
2286 // Sort in reverse order so GCCInstallationDetector::init picks the latest.
2287 std::sort(SolarisPrefixes.rbegin(), SolarisPrefixes.rend());
2288 for (auto p : SolarisPrefixes)
2289 Prefixes.emplace_back(p.second);
2290 return;
2293 // For Linux, if --sysroot is not specified, look for RHEL/CentOS devtoolsets
2294 // and gcc-toolsets.
2295 if (SysRoot.empty() && TargetTriple.getOS() == llvm::Triple::Linux &&
2296 D.getVFS().exists("/opt/rh")) {
2297 // TODO: We may want to remove this, since the functionality
2298 // can be achieved using config files.
2299 Prefixes.push_back("/opt/rh/gcc-toolset-12/root/usr");
2300 Prefixes.push_back("/opt/rh/gcc-toolset-11/root/usr");
2301 Prefixes.push_back("/opt/rh/gcc-toolset-10/root/usr");
2302 Prefixes.push_back("/opt/rh/devtoolset-12/root/usr");
2303 Prefixes.push_back("/opt/rh/devtoolset-11/root/usr");
2304 Prefixes.push_back("/opt/rh/devtoolset-10/root/usr");
2305 Prefixes.push_back("/opt/rh/devtoolset-9/root/usr");
2306 Prefixes.push_back("/opt/rh/devtoolset-8/root/usr");
2307 Prefixes.push_back("/opt/rh/devtoolset-7/root/usr");
2308 Prefixes.push_back("/opt/rh/devtoolset-6/root/usr");
2309 Prefixes.push_back("/opt/rh/devtoolset-4/root/usr");
2310 Prefixes.push_back("/opt/rh/devtoolset-3/root/usr");
2311 Prefixes.push_back("/opt/rh/devtoolset-2/root/usr");
2314 // Fall back to /usr which is used by most non-Solaris systems.
2315 Prefixes.push_back(concat(SysRoot, "/usr"));
2318 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
2319 const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
2320 SmallVectorImpl<StringRef> &LibDirs,
2321 SmallVectorImpl<StringRef> &TripleAliases,
2322 SmallVectorImpl<StringRef> &BiarchLibDirs,
2323 SmallVectorImpl<StringRef> &BiarchTripleAliases) {
2324 // Declare a bunch of static data sets that we'll select between below. These
2325 // are specifically designed to always refer to string literals to avoid any
2326 // lifetime or initialization issues.
2328 // The *Triples variables hard code some triples so that, for example,
2329 // --target=aarch64 (incomplete triple) can detect lib/aarch64-linux-gnu.
2330 // They are not needed when the user has correct LLVM_DEFAULT_TARGET_TRIPLE
2331 // and always uses the full --target (e.g. --target=aarch64-linux-gnu). The
2332 // lists should shrink over time. Please don't add more elements to *Triples.
2333 static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
2334 static const char *const AArch64Triples[] = {
2335 "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-redhat-linux",
2336 "aarch64-suse-linux"};
2337 static const char *const AArch64beLibDirs[] = {"/lib"};
2338 static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu",
2339 "aarch64_be-linux-gnu"};
2341 static const char *const ARMLibDirs[] = {"/lib"};
2342 static const char *const ARMTriples[] = {"arm-linux-gnueabi"};
2343 static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf",
2344 "armv7hl-redhat-linux-gnueabi",
2345 "armv6hl-suse-linux-gnueabi",
2346 "armv7hl-suse-linux-gnueabi"};
2347 static const char *const ARMebLibDirs[] = {"/lib"};
2348 static const char *const ARMebTriples[] = {"armeb-linux-gnueabi"};
2349 static const char *const ARMebHFTriples[] = {
2350 "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
2352 static const char *const AVRLibDirs[] = {"/lib"};
2353 static const char *const AVRTriples[] = {"avr"};
2355 static const char *const CSKYLibDirs[] = {"/lib"};
2356 static const char *const CSKYTriples[] = {
2357 "csky-linux-gnuabiv2", "csky-linux-uclibcabiv2", "csky-elf-noneabiv2"};
2359 static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
2360 static const char *const X86_64Triples[] = {
2361 "x86_64-linux-gnu", "x86_64-unknown-linux-gnu",
2362 "x86_64-pc-linux-gnu", "x86_64-redhat-linux6E",
2363 "x86_64-redhat-linux", "x86_64-suse-linux",
2364 "x86_64-manbo-linux-gnu", "x86_64-linux-gnu",
2365 "x86_64-slackware-linux", "x86_64-unknown-linux",
2366 "x86_64-amazon-linux"};
2367 static const char *const X32Triples[] = {"x86_64-linux-gnux32",
2368 "x86_64-pc-linux-gnux32"};
2369 static const char *const X32LibDirs[] = {"/libx32", "/lib"};
2370 static const char *const X86LibDirs[] = {"/lib32", "/lib"};
2371 static const char *const X86Triples[] = {
2372 "i586-linux-gnu", "i686-linux-gnu", "i686-pc-linux-gnu",
2373 "i386-redhat-linux6E", "i686-redhat-linux", "i386-redhat-linux",
2374 "i586-suse-linux", "i686-montavista-linux", "i686-gnu",
2377 static const char *const LoongArch64LibDirs[] = {"/lib64", "/lib"};
2378 static const char *const LoongArch64Triples[] = {
2379 "loongarch64-linux-gnu", "loongarch64-unknown-linux-gnu"};
2381 static const char *const M68kLibDirs[] = {"/lib"};
2382 static const char *const M68kTriples[] = {
2383 "m68k-linux-gnu", "m68k-unknown-linux-gnu", "m68k-suse-linux"};
2385 static const char *const MIPSLibDirs[] = {"/libo32", "/lib"};
2386 static const char *const MIPSTriples[] = {
2387 "mips-linux-gnu", "mips-mti-linux", "mips-mti-linux-gnu",
2388 "mips-img-linux-gnu", "mipsisa32r6-linux-gnu"};
2389 static const char *const MIPSELLibDirs[] = {"/libo32", "/lib"};
2390 static const char *const MIPSELTriples[] = {
2391 "mipsel-linux-gnu", "mips-img-linux-gnu", "mipsisa32r6el-linux-gnu"};
2393 static const char *const MIPS64LibDirs[] = {"/lib64", "/lib"};
2394 static const char *const MIPS64Triples[] = {
2395 "mips64-linux-gnu", "mips-mti-linux-gnu",
2396 "mips-img-linux-gnu", "mips64-linux-gnuabi64",
2397 "mipsisa64r6-linux-gnu", "mipsisa64r6-linux-gnuabi64"};
2398 static const char *const MIPS64ELLibDirs[] = {"/lib64", "/lib"};
2399 static const char *const MIPS64ELTriples[] = {
2400 "mips64el-linux-gnu", "mips-mti-linux-gnu",
2401 "mips-img-linux-gnu", "mips64el-linux-gnuabi64",
2402 "mipsisa64r6el-linux-gnu", "mipsisa64r6el-linux-gnuabi64"};
2404 static const char *const MIPSN32LibDirs[] = {"/lib32"};
2405 static const char *const MIPSN32Triples[] = {"mips64-linux-gnuabin32",
2406 "mipsisa64r6-linux-gnuabin32"};
2407 static const char *const MIPSN32ELLibDirs[] = {"/lib32"};
2408 static const char *const MIPSN32ELTriples[] = {
2409 "mips64el-linux-gnuabin32", "mipsisa64r6el-linux-gnuabin32"};
2411 static const char *const MSP430LibDirs[] = {"/lib"};
2412 static const char *const MSP430Triples[] = {"msp430-elf"};
2414 static const char *const PPCLibDirs[] = {"/lib32", "/lib"};
2415 static const char *const PPCTriples[] = {
2416 "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
2417 // On 32-bit PowerPC systems running SUSE Linux, gcc is configured as a
2418 // 64-bit compiler which defaults to "-m32", hence "powerpc64-suse-linux".
2419 "powerpc64-suse-linux", "powerpc-montavista-linuxspe"};
2420 static const char *const PPCLELibDirs[] = {"/lib32", "/lib"};
2421 static const char *const PPCLETriples[] = {"powerpcle-linux-gnu",
2422 "powerpcle-unknown-linux-gnu",
2423 "powerpcle-linux-musl"};
2425 static const char *const PPC64LibDirs[] = {"/lib64", "/lib"};
2426 static const char *const PPC64Triples[] = {
2427 "powerpc64-linux-gnu", "powerpc64-unknown-linux-gnu",
2428 "powerpc64-suse-linux", "ppc64-redhat-linux"};
2429 static const char *const PPC64LELibDirs[] = {"/lib64", "/lib"};
2430 static const char *const PPC64LETriples[] = {
2431 "powerpc64le-linux-gnu", "powerpc64le-unknown-linux-gnu",
2432 "powerpc64le-none-linux-gnu", "powerpc64le-suse-linux",
2433 "ppc64le-redhat-linux"};
2435 static const char *const RISCV32LibDirs[] = {"/lib32", "/lib"};
2436 static const char *const RISCV32Triples[] = {"riscv32-unknown-linux-gnu",
2437 "riscv32-linux-gnu",
2438 "riscv32-unknown-elf"};
2439 static const char *const RISCV64LibDirs[] = {"/lib64", "/lib"};
2440 static const char *const RISCV64Triples[] = {"riscv64-unknown-linux-gnu",
2441 "riscv64-linux-gnu",
2442 "riscv64-unknown-elf"};
2444 static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"};
2445 static const char *const SPARCv8Triples[] = {"sparc-linux-gnu",
2446 "sparcv8-linux-gnu"};
2447 static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"};
2448 static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu",
2449 "sparcv9-linux-gnu"};
2451 static const char *const SystemZLibDirs[] = {"/lib64", "/lib"};
2452 static const char *const SystemZTriples[] = {
2453 "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
2454 "s390x-suse-linux", "s390x-redhat-linux"};
2457 using std::begin;
2458 using std::end;
2460 if (TargetTriple.isOSSolaris()) {
2461 static const char *const SolarisLibDirs[] = {"/lib"};
2462 static const char *const SolarisSparcV8Triples[] = {
2463 "sparc-sun-solaris2.11"};
2464 static const char *const SolarisSparcV9Triples[] = {
2465 "sparcv9-sun-solaris2.11"};
2466 static const char *const SolarisX86Triples[] = {"i386-pc-solaris2.11"};
2467 static const char *const SolarisX86_64Triples[] = {"x86_64-pc-solaris2.11"};
2468 LibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
2469 BiarchLibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
2470 switch (TargetTriple.getArch()) {
2471 case llvm::Triple::x86:
2472 TripleAliases.append(begin(SolarisX86Triples), end(SolarisX86Triples));
2473 BiarchTripleAliases.append(begin(SolarisX86_64Triples),
2474 end(SolarisX86_64Triples));
2475 break;
2476 case llvm::Triple::x86_64:
2477 TripleAliases.append(begin(SolarisX86_64Triples),
2478 end(SolarisX86_64Triples));
2479 BiarchTripleAliases.append(begin(SolarisX86Triples),
2480 end(SolarisX86Triples));
2481 break;
2482 case llvm::Triple::sparc:
2483 TripleAliases.append(begin(SolarisSparcV8Triples),
2484 end(SolarisSparcV8Triples));
2485 BiarchTripleAliases.append(begin(SolarisSparcV9Triples),
2486 end(SolarisSparcV9Triples));
2487 break;
2488 case llvm::Triple::sparcv9:
2489 TripleAliases.append(begin(SolarisSparcV9Triples),
2490 end(SolarisSparcV9Triples));
2491 BiarchTripleAliases.append(begin(SolarisSparcV8Triples),
2492 end(SolarisSparcV8Triples));
2493 break;
2494 default:
2495 break;
2497 return;
2500 // Android targets should not use GNU/Linux tools or libraries.
2501 if (TargetTriple.isAndroid()) {
2502 static const char *const AArch64AndroidTriples[] = {
2503 "aarch64-linux-android"};
2504 static const char *const ARMAndroidTriples[] = {"arm-linux-androideabi"};
2505 static const char *const X86AndroidTriples[] = {"i686-linux-android"};
2506 static const char *const X86_64AndroidTriples[] = {"x86_64-linux-android"};
2508 switch (TargetTriple.getArch()) {
2509 case llvm::Triple::aarch64:
2510 LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2511 TripleAliases.append(begin(AArch64AndroidTriples),
2512 end(AArch64AndroidTriples));
2513 break;
2514 case llvm::Triple::arm:
2515 case llvm::Triple::thumb:
2516 LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
2517 TripleAliases.append(begin(ARMAndroidTriples), end(ARMAndroidTriples));
2518 break;
2519 case llvm::Triple::x86_64:
2520 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2521 TripleAliases.append(begin(X86_64AndroidTriples),
2522 end(X86_64AndroidTriples));
2523 BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2524 BiarchTripleAliases.append(begin(X86AndroidTriples),
2525 end(X86AndroidTriples));
2526 break;
2527 case llvm::Triple::x86:
2528 LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2529 TripleAliases.append(begin(X86AndroidTriples), end(X86AndroidTriples));
2530 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2531 BiarchTripleAliases.append(begin(X86_64AndroidTriples),
2532 end(X86_64AndroidTriples));
2533 break;
2534 default:
2535 break;
2538 return;
2541 switch (TargetTriple.getArch()) {
2542 case llvm::Triple::aarch64:
2543 LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2544 TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
2545 BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2546 BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
2547 break;
2548 case llvm::Triple::aarch64_be:
2549 LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
2550 TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
2551 BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
2552 BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
2553 break;
2554 case llvm::Triple::arm:
2555 case llvm::Triple::thumb:
2556 LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
2557 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2558 TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
2559 } else {
2560 TripleAliases.append(begin(ARMTriples), end(ARMTriples));
2562 break;
2563 case llvm::Triple::armeb:
2564 case llvm::Triple::thumbeb:
2565 LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
2566 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2567 TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
2568 } else {
2569 TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
2571 break;
2572 case llvm::Triple::avr:
2573 LibDirs.append(begin(AVRLibDirs), end(AVRLibDirs));
2574 TripleAliases.append(begin(AVRTriples), end(AVRTriples));
2575 break;
2576 case llvm::Triple::csky:
2577 LibDirs.append(begin(CSKYLibDirs), end(CSKYLibDirs));
2578 TripleAliases.append(begin(CSKYTriples), end(CSKYTriples));
2579 break;
2580 case llvm::Triple::x86_64:
2581 if (TargetTriple.isX32()) {
2582 LibDirs.append(begin(X32LibDirs), end(X32LibDirs));
2583 TripleAliases.append(begin(X32Triples), end(X32Triples));
2584 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2585 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2586 } else {
2587 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2588 TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2589 BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
2590 BiarchTripleAliases.append(begin(X32Triples), end(X32Triples));
2592 BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2593 BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
2594 break;
2595 case llvm::Triple::x86:
2596 LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2597 // MCU toolchain is 32 bit only and its triple alias is TargetTriple
2598 // itself, which will be appended below.
2599 if (!TargetTriple.isOSIAMCU()) {
2600 TripleAliases.append(begin(X86Triples), end(X86Triples));
2601 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2602 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2603 BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
2604 BiarchTripleAliases.append(begin(X32Triples), end(X32Triples));
2606 break;
2607 // TODO: Handle loongarch32.
2608 case llvm::Triple::loongarch64:
2609 LibDirs.append(begin(LoongArch64LibDirs), end(LoongArch64LibDirs));
2610 TripleAliases.append(begin(LoongArch64Triples), end(LoongArch64Triples));
2611 break;
2612 case llvm::Triple::m68k:
2613 LibDirs.append(begin(M68kLibDirs), end(M68kLibDirs));
2614 TripleAliases.append(begin(M68kTriples), end(M68kTriples));
2615 break;
2616 case llvm::Triple::mips:
2617 LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
2618 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2619 BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
2620 BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
2621 BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs));
2622 BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples));
2623 break;
2624 case llvm::Triple::mipsel:
2625 LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2626 TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
2627 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2628 BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2629 BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
2630 BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs));
2631 BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples));
2632 break;
2633 case llvm::Triple::mips64:
2634 LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
2635 TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
2636 BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
2637 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2638 BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs));
2639 BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples));
2640 break;
2641 case llvm::Triple::mips64el:
2642 LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2643 TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
2644 BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2645 BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
2646 BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs));
2647 BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples));
2648 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2649 break;
2650 case llvm::Triple::msp430:
2651 LibDirs.append(begin(MSP430LibDirs), end(MSP430LibDirs));
2652 TripleAliases.append(begin(MSP430Triples), end(MSP430Triples));
2653 break;
2654 case llvm::Triple::ppc:
2655 LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
2656 TripleAliases.append(begin(PPCTriples), end(PPCTriples));
2657 BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
2658 BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
2659 break;
2660 case llvm::Triple::ppcle:
2661 LibDirs.append(begin(PPCLELibDirs), end(PPCLELibDirs));
2662 TripleAliases.append(begin(PPCLETriples), end(PPCLETriples));
2663 BiarchLibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
2664 BiarchTripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
2665 break;
2666 case llvm::Triple::ppc64:
2667 LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
2668 TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
2669 BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
2670 BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
2671 break;
2672 case llvm::Triple::ppc64le:
2673 LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
2674 TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
2675 BiarchLibDirs.append(begin(PPCLELibDirs), end(PPCLELibDirs));
2676 BiarchTripleAliases.append(begin(PPCLETriples), end(PPCLETriples));
2677 break;
2678 case llvm::Triple::riscv32:
2679 LibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
2680 TripleAliases.append(begin(RISCV32Triples), end(RISCV32Triples));
2681 BiarchLibDirs.append(begin(RISCV64LibDirs), end(RISCV64LibDirs));
2682 BiarchTripleAliases.append(begin(RISCV64Triples), end(RISCV64Triples));
2683 break;
2684 case llvm::Triple::riscv64:
2685 LibDirs.append(begin(RISCV64LibDirs), end(RISCV64LibDirs));
2686 TripleAliases.append(begin(RISCV64Triples), end(RISCV64Triples));
2687 BiarchLibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
2688 BiarchTripleAliases.append(begin(RISCV32Triples), end(RISCV32Triples));
2689 break;
2690 case llvm::Triple::sparc:
2691 case llvm::Triple::sparcel:
2692 LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
2693 TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
2694 BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
2695 BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
2696 break;
2697 case llvm::Triple::sparcv9:
2698 LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
2699 TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
2700 BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
2701 BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
2702 break;
2703 case llvm::Triple::systemz:
2704 LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
2705 TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
2706 break;
2707 default:
2708 // By default, just rely on the standard lib directories and the original
2709 // triple.
2710 break;
2713 // Also include the multiarch variant if it's different.
2714 if (TargetTriple.str() != BiarchTriple.str())
2715 BiarchTripleAliases.push_back(BiarchTriple.str());
2718 bool Generic_GCC::GCCInstallationDetector::ScanGCCForMultilibs(
2719 const llvm::Triple &TargetTriple, const ArgList &Args,
2720 StringRef Path, bool NeedsBiarchSuffix) {
2721 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2722 DetectedMultilibs Detected;
2724 // Android standalone toolchain could have multilibs for ARM and Thumb.
2725 // Debian mips multilibs behave more like the rest of the biarch ones,
2726 // so handle them there
2727 if (isArmOrThumbArch(TargetArch) && TargetTriple.isAndroid()) {
2728 // It should also work without multilibs in a simplified toolchain.
2729 findAndroidArmMultilibs(D, TargetTriple, Path, Args, Detected);
2730 } else if (TargetTriple.isCSKY()) {
2731 findCSKYMultilibs(D, TargetTriple, Path, Args, Detected);
2732 } else if (TargetTriple.isMIPS()) {
2733 if (!findMIPSMultilibs(D, TargetTriple, Path, Args, Detected))
2734 return false;
2735 } else if (TargetTriple.isRISCV()) {
2736 findRISCVMultilibs(D, TargetTriple, Path, Args, Detected);
2737 } else if (isMSP430(TargetArch)) {
2738 findMSP430Multilibs(D, TargetTriple, Path, Args, Detected);
2739 } else if (TargetArch == llvm::Triple::avr) {
2740 // AVR has no multilibs.
2741 } else if (!findBiarchMultilibs(D, TargetTriple, Path, Args,
2742 NeedsBiarchSuffix, Detected)) {
2743 return false;
2746 Multilibs = Detected.Multilibs;
2747 SelectedMultilib = Detected.SelectedMultilibs.empty()
2748 ? Multilib()
2749 : Detected.SelectedMultilibs.back();
2750 BiarchSibling = Detected.BiarchSibling;
2752 return true;
2755 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
2756 const llvm::Triple &TargetTriple, const ArgList &Args,
2757 const std::string &LibDir, StringRef CandidateTriple,
2758 bool NeedsBiarchSuffix, bool GCCDirExists, bool GCCCrossDirExists) {
2759 // Locations relative to the system lib directory where GCC's triple-specific
2760 // directories might reside.
2761 struct GCCLibSuffix {
2762 // Path from system lib directory to GCC triple-specific directory.
2763 std::string LibSuffix;
2764 // Path from GCC triple-specific directory back to system lib directory.
2765 // This is one '..' component per component in LibSuffix.
2766 StringRef ReversePath;
2767 // Whether this library suffix is relevant for the triple.
2768 bool Active;
2769 } Suffixes[] = {
2770 // This is the normal place.
2771 {"gcc/" + CandidateTriple.str(), "../..", GCCDirExists},
2773 // Debian puts cross-compilers in gcc-cross.
2774 {"gcc-cross/" + CandidateTriple.str(), "../..", GCCCrossDirExists},
2776 // The Freescale PPC SDK has the gcc libraries in
2777 // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well. Only do
2778 // this on Freescale triples, though, since some systems put a *lot* of
2779 // files in that location, not just GCC installation data.
2780 {CandidateTriple.str(), "..",
2781 TargetTriple.getVendor() == llvm::Triple::Freescale ||
2782 TargetTriple.getVendor() == llvm::Triple::OpenEmbedded}};
2784 for (auto &Suffix : Suffixes) {
2785 if (!Suffix.Active)
2786 continue;
2788 StringRef LibSuffix = Suffix.LibSuffix;
2789 std::error_code EC;
2790 for (llvm::vfs::directory_iterator
2791 LI = D.getVFS().dir_begin(LibDir + "/" + LibSuffix, EC),
2793 !EC && LI != LE; LI = LI.increment(EC)) {
2794 StringRef VersionText = llvm::sys::path::filename(LI->path());
2795 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2796 if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2797 if (!CandidateGCCInstallPaths.insert(std::string(LI->path())).second)
2798 continue; // Saw this path before; no need to look at it again.
2799 if (CandidateVersion.isOlderThan(4, 1, 1))
2800 continue;
2801 if (CandidateVersion <= Version)
2802 continue;
2804 if (!ScanGCCForMultilibs(TargetTriple, Args, LI->path(),
2805 NeedsBiarchSuffix))
2806 continue;
2808 Version = CandidateVersion;
2809 GCCTriple.setTriple(CandidateTriple);
2810 // FIXME: We hack together the directory name here instead of
2811 // using LI to ensure stable path separators across Windows and
2812 // Linux.
2813 GCCInstallPath = (LibDir + "/" + LibSuffix + "/" + VersionText).str();
2814 GCCParentLibPath = (GCCInstallPath + "/../" + Suffix.ReversePath).str();
2815 IsValid = true;
2820 bool Generic_GCC::GCCInstallationDetector::ScanGentooConfigs(
2821 const llvm::Triple &TargetTriple, const ArgList &Args,
2822 const SmallVectorImpl<StringRef> &CandidateTriples,
2823 const SmallVectorImpl<StringRef> &CandidateBiarchTriples) {
2824 if (!D.getVFS().exists(concat(D.SysRoot, GentooConfigDir)))
2825 return false;
2827 for (StringRef CandidateTriple : CandidateTriples) {
2828 if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple))
2829 return true;
2832 for (StringRef CandidateTriple : CandidateBiarchTriples) {
2833 if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple, true))
2834 return true;
2836 return false;
2839 bool Generic_GCC::GCCInstallationDetector::ScanGentooGccConfig(
2840 const llvm::Triple &TargetTriple, const ArgList &Args,
2841 StringRef CandidateTriple, bool NeedsBiarchSuffix) {
2842 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
2843 D.getVFS().getBufferForFile(concat(D.SysRoot, GentooConfigDir,
2844 "/config-" + CandidateTriple.str()));
2845 if (File) {
2846 SmallVector<StringRef, 2> Lines;
2847 File.get()->getBuffer().split(Lines, "\n");
2848 for (StringRef Line : Lines) {
2849 Line = Line.trim();
2850 // CURRENT=triple-version
2851 if (!Line.consume_front("CURRENT="))
2852 continue;
2853 // Process the config file pointed to by CURRENT.
2854 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ConfigFile =
2855 D.getVFS().getBufferForFile(
2856 concat(D.SysRoot, GentooConfigDir, "/" + Line));
2857 std::pair<StringRef, StringRef> ActiveVersion = Line.rsplit('-');
2858 // List of paths to scan for libraries.
2859 SmallVector<StringRef, 4> GentooScanPaths;
2860 // Scan the Config file to find installed GCC libraries path.
2861 // Typical content of the GCC config file:
2862 // LDPATH="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x:/usr/lib/gcc/
2863 // (continued from previous line) x86_64-pc-linux-gnu/4.9.x/32"
2864 // MANPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/man"
2865 // INFOPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/info"
2866 // STDCXX_INCDIR="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x/include/g++-v4"
2867 // We are looking for the paths listed in LDPATH=... .
2868 if (ConfigFile) {
2869 SmallVector<StringRef, 2> ConfigLines;
2870 ConfigFile.get()->getBuffer().split(ConfigLines, "\n");
2871 for (StringRef ConfLine : ConfigLines) {
2872 ConfLine = ConfLine.trim();
2873 if (ConfLine.consume_front("LDPATH=")) {
2874 // Drop '"' from front and back if present.
2875 ConfLine.consume_back("\"");
2876 ConfLine.consume_front("\"");
2877 // Get all paths sperated by ':'
2878 ConfLine.split(GentooScanPaths, ':', -1, /*AllowEmpty*/ false);
2882 // Test the path based on the version in /etc/env.d/gcc/config-{tuple}.
2883 std::string basePath = "/usr/lib/gcc/" + ActiveVersion.first.str() + "/"
2884 + ActiveVersion.second.str();
2885 GentooScanPaths.push_back(StringRef(basePath));
2887 // Scan all paths for GCC libraries.
2888 for (const auto &GentooScanPath : GentooScanPaths) {
2889 std::string GentooPath = concat(D.SysRoot, GentooScanPath);
2890 if (D.getVFS().exists(GentooPath + "/crtbegin.o")) {
2891 if (!ScanGCCForMultilibs(TargetTriple, Args, GentooPath,
2892 NeedsBiarchSuffix))
2893 continue;
2895 Version = GCCVersion::Parse(ActiveVersion.second);
2896 GCCInstallPath = GentooPath;
2897 GCCParentLibPath = GentooPath + std::string("/../../..");
2898 GCCTriple.setTriple(ActiveVersion.first);
2899 IsValid = true;
2900 return true;
2906 return false;
2909 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple,
2910 const ArgList &Args)
2911 : ToolChain(D, Triple, Args), GCCInstallation(D),
2912 CudaInstallation(D, Triple, Args), RocmInstallation(D, Triple, Args) {
2913 getProgramPaths().push_back(getDriver().getInstalledDir());
2914 if (getDriver().getInstalledDir() != getDriver().Dir)
2915 getProgramPaths().push_back(getDriver().Dir);
2918 Generic_GCC::~Generic_GCC() {}
2920 Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
2921 switch (AC) {
2922 case Action::PreprocessJobClass:
2923 if (!Preprocess)
2924 Preprocess.reset(new clang::driver::tools::gcc::Preprocessor(*this));
2925 return Preprocess.get();
2926 case Action::CompileJobClass:
2927 if (!Compile)
2928 Compile.reset(new tools::gcc::Compiler(*this));
2929 return Compile.get();
2930 default:
2931 return ToolChain::getTool(AC);
2935 Tool *Generic_GCC::buildAssembler() const {
2936 return new tools::gnutools::Assembler(*this);
2939 Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); }
2941 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
2942 // Print the information about how we detected the GCC installation.
2943 GCCInstallation.print(OS);
2944 CudaInstallation->print(OS);
2945 RocmInstallation->print(OS);
2948 ToolChain::UnwindTableLevel
2949 Generic_GCC::getDefaultUnwindTableLevel(const ArgList &Args) const {
2950 switch (getArch()) {
2951 case llvm::Triple::aarch64:
2952 case llvm::Triple::ppc:
2953 case llvm::Triple::ppcle:
2954 case llvm::Triple::ppc64:
2955 case llvm::Triple::ppc64le:
2956 case llvm::Triple::riscv32:
2957 case llvm::Triple::riscv64:
2958 case llvm::Triple::x86:
2959 case llvm::Triple::x86_64:
2960 return UnwindTableLevel::Asynchronous;
2961 default:
2962 return UnwindTableLevel::None;
2966 bool Generic_GCC::isPICDefault() const {
2967 switch (getArch()) {
2968 case llvm::Triple::x86_64:
2969 return getTriple().isOSWindows();
2970 case llvm::Triple::mips64:
2971 case llvm::Triple::mips64el:
2972 return true;
2973 default:
2974 return false;
2978 bool Generic_GCC::isPIEDefault(const llvm::opt::ArgList &Args) const {
2979 return false;
2982 bool Generic_GCC::isPICDefaultForced() const {
2983 return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
2986 bool Generic_GCC::IsIntegratedAssemblerDefault() const {
2987 switch (getTriple().getArch()) {
2988 case llvm::Triple::nvptx:
2989 case llvm::Triple::nvptx64:
2990 case llvm::Triple::xcore:
2991 return false;
2992 default:
2993 return true;
2997 void Generic_GCC::PushPPaths(ToolChain::path_list &PPaths) {
2998 // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
2999 // least) put various tools in a triple-prefixed directory off of the parent
3000 // of the GCC installation. We use the GCC triple here to ensure that we end
3001 // up with tools that support the same amount of cross compiling as the
3002 // detected GCC installation. For example, if we find a GCC installation
3003 // targeting x86_64, but it is a bi-arch GCC installation, it can also be
3004 // used to target i386.
3005 if (GCCInstallation.isValid()) {
3006 PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
3007 GCCInstallation.getTriple().str() + "/bin")
3008 .str());
3012 void Generic_GCC::AddMultilibPaths(const Driver &D,
3013 const std::string &SysRoot,
3014 const std::string &OSLibDir,
3015 const std::string &MultiarchTriple,
3016 path_list &Paths) {
3017 // Add the multilib suffixed paths where they are available.
3018 if (GCCInstallation.isValid()) {
3019 assert(!SelectedMultilibs.empty());
3020 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3021 const std::string &LibPath =
3022 std::string(GCCInstallation.getParentLibPath());
3024 // Sourcery CodeBench MIPS toolchain holds some libraries under
3025 // a biarch-like suffix of the GCC installation.
3026 if (const auto &PathsCallback = Multilibs.filePathsCallback())
3027 for (const auto &Path : PathsCallback(SelectedMultilibs.back()))
3028 addPathIfExists(D, GCCInstallation.getInstallPath() + Path, Paths);
3030 // Add lib/gcc/$triple/$version, with an optional /multilib suffix.
3031 addPathIfExists(D,
3032 GCCInstallation.getInstallPath() +
3033 SelectedMultilibs.back().gccSuffix(),
3034 Paths);
3036 // Add lib/gcc/$triple/$libdir
3037 // For GCC built with --enable-version-specific-runtime-libs.
3038 addPathIfExists(D, GCCInstallation.getInstallPath() + "/../" + OSLibDir,
3039 Paths);
3041 // GCC cross compiling toolchains will install target libraries which ship
3042 // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
3043 // any part of the GCC installation in
3044 // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
3045 // debatable, but is the reality today. We need to search this tree even
3046 // when we have a sysroot somewhere else. It is the responsibility of
3047 // whomever is doing the cross build targeting a sysroot using a GCC
3048 // installation that is *not* within the system root to ensure two things:
3050 // 1) Any DSOs that are linked in from this tree or from the install path
3051 // above must be present on the system root and found via an
3052 // appropriate rpath.
3053 // 2) There must not be libraries installed into
3054 // <prefix>/<triple>/<libdir> unless they should be preferred over
3055 // those within the system root.
3057 // Note that this matches the GCC behavior. See the below comment for where
3058 // Clang diverges from GCC's behavior.
3059 addPathIfExists(D,
3060 LibPath + "/../" + GCCTriple.str() + "/lib/../" + OSLibDir +
3061 SelectedMultilibs.back().osSuffix(),
3062 Paths);
3064 // If the GCC installation we found is inside of the sysroot, we want to
3065 // prefer libraries installed in the parent prefix of the GCC installation.
3066 // It is important to *not* use these paths when the GCC installation is
3067 // outside of the system root as that can pick up unintended libraries.
3068 // This usually happens when there is an external cross compiler on the
3069 // host system, and a more minimal sysroot available that is the target of
3070 // the cross. Note that GCC does include some of these directories in some
3071 // configurations but this seems somewhere between questionable and simply
3072 // a bug.
3073 if (StringRef(LibPath).startswith(SysRoot))
3074 addPathIfExists(D, LibPath + "/../" + OSLibDir, Paths);
3078 void Generic_GCC::AddMultiarchPaths(const Driver &D,
3079 const std::string &SysRoot,
3080 const std::string &OSLibDir,
3081 path_list &Paths) {
3082 if (GCCInstallation.isValid()) {
3083 const std::string &LibPath =
3084 std::string(GCCInstallation.getParentLibPath());
3085 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3086 const Multilib &Multilib = GCCInstallation.getMultilib();
3087 addPathIfExists(
3088 D, LibPath + "/../" + GCCTriple.str() + "/lib" + Multilib.osSuffix(),
3089 Paths);
3093 void Generic_GCC::AddMultilibIncludeArgs(const ArgList &DriverArgs,
3094 ArgStringList &CC1Args) const {
3095 // Add include directories specific to the selected multilib set and multilib.
3096 if (!GCCInstallation.isValid())
3097 return;
3098 // gcc TOOL_INCLUDE_DIR.
3099 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3100 std::string LibPath(GCCInstallation.getParentLibPath());
3101 addSystemInclude(DriverArgs, CC1Args,
3102 Twine(LibPath) + "/../" + GCCTriple.str() + "/include");
3104 const auto &Callback = Multilibs.includeDirsCallback();
3105 if (Callback) {
3106 for (const auto &Path : Callback(GCCInstallation.getMultilib()))
3107 addExternCSystemIncludeIfExists(DriverArgs, CC1Args,
3108 GCCInstallation.getInstallPath() + Path);
3112 void Generic_GCC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3113 ArgStringList &CC1Args) const {
3114 if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdincxx,
3115 options::OPT_nostdlibinc))
3116 return;
3118 switch (GetCXXStdlibType(DriverArgs)) {
3119 case ToolChain::CST_Libcxx:
3120 addLibCxxIncludePaths(DriverArgs, CC1Args);
3121 break;
3123 case ToolChain::CST_Libstdcxx:
3124 addLibStdCxxIncludePaths(DriverArgs, CC1Args);
3125 break;
3129 void
3130 Generic_GCC::addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3131 llvm::opt::ArgStringList &CC1Args) const {
3132 const Driver &D = getDriver();
3133 std::string SysRoot = computeSysRoot();
3134 if (SysRoot.empty())
3135 SysRoot = llvm::sys::path::get_separator();
3137 auto AddIncludePath = [&](StringRef Path, bool TargetDirRequired = false) {
3138 std::string Version = detectLibcxxVersion(Path);
3139 if (Version.empty())
3140 return false;
3142 // First add the per-target include path if it exists.
3143 bool TargetDirExists = false;
3144 std::optional<std::string> TargetIncludeDir = getTargetSubDirPath(Path);
3145 if (TargetIncludeDir) {
3146 SmallString<128> TargetDir(*TargetIncludeDir);
3147 llvm::sys::path::append(TargetDir, "c++", Version);
3148 if (D.getVFS().exists(TargetDir)) {
3149 addSystemInclude(DriverArgs, CC1Args, TargetDir);
3150 TargetDirExists = true;
3153 if (TargetDirRequired && !TargetDirExists)
3154 return false;
3156 // Second add the generic one.
3157 SmallString<128> GenericDir(Path);
3158 llvm::sys::path::append(GenericDir, "c++", Version);
3159 addSystemInclude(DriverArgs, CC1Args, GenericDir);
3160 return true;
3163 // Android only uses the libc++ headers installed alongside the toolchain if
3164 // they contain an Android-specific target include path, otherwise they're
3165 // incompatible with the NDK libraries.
3166 SmallString<128> DriverIncludeDir(getDriver().Dir);
3167 llvm::sys::path::append(DriverIncludeDir, "..", "include");
3168 if (AddIncludePath(DriverIncludeDir,
3169 /*TargetDirRequired=*/getTriple().isAndroid()))
3170 return;
3171 // If this is a development, non-installed, clang, libcxx will
3172 // not be found at ../include/c++ but it likely to be found at
3173 // one of the following two locations:
3174 SmallString<128> UsrLocalIncludeDir(SysRoot);
3175 llvm::sys::path::append(UsrLocalIncludeDir, "usr", "local", "include");
3176 if (AddIncludePath(UsrLocalIncludeDir))
3177 return;
3178 SmallString<128> UsrIncludeDir(SysRoot);
3179 llvm::sys::path::append(UsrIncludeDir, "usr", "include");
3180 if (AddIncludePath(UsrIncludeDir))
3181 return;
3184 bool Generic_GCC::addLibStdCXXIncludePaths(Twine IncludeDir, StringRef Triple,
3185 Twine IncludeSuffix,
3186 const llvm::opt::ArgList &DriverArgs,
3187 llvm::opt::ArgStringList &CC1Args,
3188 bool DetectDebian) const {
3189 if (!getVFS().exists(IncludeDir))
3190 return false;
3192 // Debian native gcc uses g++-multiarch-incdir.diff which uses
3193 // include/x86_64-linux-gnu/c++/10$IncludeSuffix instead of
3194 // include/c++/10/x86_64-linux-gnu$IncludeSuffix.
3195 std::string Dir = IncludeDir.str();
3196 StringRef Include =
3197 llvm::sys::path::parent_path(llvm::sys::path::parent_path(Dir));
3198 std::string Path =
3199 (Include + "/" + Triple + Dir.substr(Include.size()) + IncludeSuffix)
3200 .str();
3201 if (DetectDebian && !getVFS().exists(Path))
3202 return false;
3204 // GPLUSPLUS_INCLUDE_DIR
3205 addSystemInclude(DriverArgs, CC1Args, IncludeDir);
3206 // GPLUSPLUS_TOOL_INCLUDE_DIR. If Triple is not empty, add a target-dependent
3207 // include directory.
3208 if (DetectDebian)
3209 addSystemInclude(DriverArgs, CC1Args, Path);
3210 else if (!Triple.empty())
3211 addSystemInclude(DriverArgs, CC1Args,
3212 IncludeDir + "/" + Triple + IncludeSuffix);
3213 // GPLUSPLUS_BACKWARD_INCLUDE_DIR
3214 addSystemInclude(DriverArgs, CC1Args, IncludeDir + "/backward");
3215 return true;
3218 bool Generic_GCC::addGCCLibStdCxxIncludePaths(
3219 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
3220 StringRef DebianMultiarch) const {
3221 assert(GCCInstallation.isValid());
3223 // By default, look for the C++ headers in an include directory adjacent to
3224 // the lib directory of the GCC installation. Note that this is expect to be
3225 // equivalent to '/usr/include/c++/X.Y' in almost all cases.
3226 StringRef LibDir = GCCInstallation.getParentLibPath();
3227 StringRef InstallDir = GCCInstallation.getInstallPath();
3228 StringRef TripleStr = GCCInstallation.getTriple().str();
3229 const Multilib &Multilib = GCCInstallation.getMultilib();
3230 const GCCVersion &Version = GCCInstallation.getVersion();
3232 // Try /../$triple/include/c++/$version (gcc --print-multiarch is not empty).
3233 if (addLibStdCXXIncludePaths(
3234 LibDir.str() + "/../" + TripleStr + "/include/c++/" + Version.Text,
3235 TripleStr, Multilib.includeSuffix(), DriverArgs, CC1Args))
3236 return true;
3238 // Try /gcc/$triple/$version/include/c++/ (gcc --print-multiarch is not
3239 // empty). Like above but for GCC built with
3240 // --enable-version-specific-runtime-libs.
3241 if (addLibStdCXXIncludePaths(LibDir.str() + "/gcc/" + TripleStr + "/" +
3242 Version.Text + "/include/c++/",
3243 TripleStr, Multilib.includeSuffix(), DriverArgs,
3244 CC1Args))
3245 return true;
3247 // Detect Debian g++-multiarch-incdir.diff.
3248 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include/c++/" + Version.Text,
3249 DebianMultiarch, Multilib.includeSuffix(),
3250 DriverArgs, CC1Args, /*Debian=*/true))
3251 return true;
3253 // Try /../include/c++/$version (gcc --print-multiarch is empty).
3254 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include/c++/" + Version.Text,
3255 TripleStr, Multilib.includeSuffix(), DriverArgs,
3256 CC1Args))
3257 return true;
3259 // Otherwise, fall back on a bunch of options which don't use multiarch
3260 // layouts for simplicity.
3261 const std::string LibStdCXXIncludePathCandidates[] = {
3262 // Gentoo is weird and places its headers inside the GCC install,
3263 // so if the first attempt to find the headers fails, try these patterns.
3264 InstallDir.str() + "/include/g++-v" + Version.Text,
3265 InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
3266 Version.MinorStr,
3267 InstallDir.str() + "/include/g++-v" + Version.MajorStr,
3270 for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
3271 if (addLibStdCXXIncludePaths(IncludePath, TripleStr,
3272 Multilib.includeSuffix(), DriverArgs, CC1Args))
3273 return true;
3275 return false;
3278 void
3279 Generic_GCC::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3280 llvm::opt::ArgStringList &CC1Args) const {
3281 if (GCCInstallation.isValid()) {
3282 addGCCLibStdCxxIncludePaths(DriverArgs, CC1Args,
3283 GCCInstallation.getTriple().str());
3287 llvm::opt::DerivedArgList *
3288 Generic_GCC::TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef,
3289 Action::OffloadKind DeviceOffloadKind) const {
3291 // If this tool chain is used for an OpenMP offloading device we have to make
3292 // sure we always generate a shared library regardless of the commands the
3293 // user passed to the host. This is required because the runtime library
3294 // is required to load the device image dynamically at run time.
3295 if (DeviceOffloadKind == Action::OFK_OpenMP) {
3296 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
3297 const OptTable &Opts = getDriver().getOpts();
3299 // Request the shared library. Given that these options are decided
3300 // implicitly, they do not refer to any base argument.
3301 DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_shared));
3302 DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_fPIC));
3304 // Filter all the arguments we don't care passing to the offloading
3305 // toolchain as they can mess up with the creation of a shared library.
3306 for (auto *A : Args) {
3307 switch ((options::ID)A->getOption().getID()) {
3308 default:
3309 DAL->append(A);
3310 break;
3311 case options::OPT_shared:
3312 case options::OPT_dynamic:
3313 case options::OPT_static:
3314 case options::OPT_fPIC:
3315 case options::OPT_fno_PIC:
3316 case options::OPT_fpic:
3317 case options::OPT_fno_pic:
3318 case options::OPT_fPIE:
3319 case options::OPT_fno_PIE:
3320 case options::OPT_fpie:
3321 case options::OPT_fno_pie:
3322 break;
3325 return DAL;
3327 return nullptr;
3330 void Generic_ELF::anchor() {}
3332 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
3333 ArgStringList &CC1Args,
3334 Action::OffloadKind) const {
3335 if (!DriverArgs.hasFlag(options::OPT_fuse_init_array,
3336 options::OPT_fno_use_init_array, true))
3337 CC1Args.push_back("-fno-use-init-array");