[Flang] remove whole-archive option for AIX linker (#76039)
[llvm-project.git] / clang / lib / Driver / ToolChains / Gnu.cpp
blob38361d6889a1c832b2ab4921e69029fd4c04156c
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/RISCVISAInfo.h"
34 #include "llvm/Support/VirtualFileSystem.h"
35 #include "llvm/TargetParser/TargetParser.h"
36 #include <system_error>
38 using namespace clang::driver;
39 using namespace clang::driver::toolchains;
40 using namespace clang;
41 using namespace llvm::opt;
43 using tools::addMultilibFlag;
44 using tools::addPathIfExists;
46 static bool forwardToGCC(const Option &O) {
47 // LinkerInput options have been forwarded. Don't duplicate.
48 if (O.hasFlag(options::LinkerInput))
49 return false;
50 return O.matches(options::OPT_Link_Group) || O.hasFlag(options::LinkOption);
53 // Switch CPU names not recognized by GNU assembler to a close CPU that it does
54 // recognize, instead of a lower march from being picked in the absence of a cpu
55 // flag.
56 static void normalizeCPUNamesForAssembler(const ArgList &Args,
57 ArgStringList &CmdArgs) {
58 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
59 StringRef CPUArg(A->getValue());
60 if (CPUArg.equals_insensitive("krait"))
61 CmdArgs.push_back("-mcpu=cortex-a15");
62 else if (CPUArg.equals_insensitive("kryo"))
63 CmdArgs.push_back("-mcpu=cortex-a57");
64 else
65 Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
69 void tools::gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
70 const InputInfo &Output,
71 const InputInfoList &Inputs,
72 const ArgList &Args,
73 const char *LinkingOutput) const {
74 const Driver &D = getToolChain().getDriver();
75 ArgStringList CmdArgs;
77 for (const auto &A : Args) {
78 if (forwardToGCC(A->getOption())) {
79 // It is unfortunate that we have to claim here, as this means
80 // we will basically never report anything interesting for
81 // platforms using a generic gcc, even if we are just using gcc
82 // to get to the assembler.
83 A->claim();
85 A->render(Args, CmdArgs);
89 RenderExtraToolArgs(JA, CmdArgs);
91 // If using a driver, force the arch.
92 if (getToolChain().getTriple().isOSDarwin()) {
93 CmdArgs.push_back("-arch");
94 CmdArgs.push_back(
95 Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
98 // Try to force gcc to match the tool chain we want, if we recognize
99 // the arch.
101 // FIXME: The triple class should directly provide the information we want
102 // here.
103 switch (getToolChain().getArch()) {
104 default:
105 break;
106 case llvm::Triple::x86:
107 case llvm::Triple::ppc:
108 case llvm::Triple::ppcle:
109 CmdArgs.push_back("-m32");
110 break;
111 case llvm::Triple::x86_64:
112 case llvm::Triple::ppc64:
113 case llvm::Triple::ppc64le:
114 CmdArgs.push_back("-m64");
115 break;
116 case llvm::Triple::sparcel:
117 CmdArgs.push_back("-EL");
118 break;
121 assert((Output.isFilename() || Output.isNothing()) && "Invalid output.");
122 if (Output.isFilename()) {
123 CmdArgs.push_back("-o");
124 CmdArgs.push_back(Output.getFilename());
125 } else {
126 CmdArgs.push_back("-fsyntax-only");
129 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
131 // Only pass -x if gcc will understand it; otherwise hope gcc
132 // understands the suffix correctly. The main use case this would go
133 // wrong in is for linker inputs if they happened to have an odd
134 // suffix; really the only way to get this to happen is a command
135 // like '-x foobar a.c' which will treat a.c like a linker input.
137 // FIXME: For the linker case specifically, can we safely convert
138 // inputs into '-Wl,' options?
139 for (const auto &II : Inputs) {
140 // Don't try to pass LLVM or AST inputs to a generic gcc.
141 if (types::isLLVMIR(II.getType()))
142 D.Diag(clang::diag::err_drv_no_linker_llvm_support)
143 << getToolChain().getTripleString();
144 else if (II.getType() == types::TY_AST)
145 D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
146 else if (II.getType() == types::TY_ModuleFile)
147 D.Diag(diag::err_drv_no_module_support)
148 << getToolChain().getTripleString();
150 if (types::canTypeBeUserSpecified(II.getType())) {
151 CmdArgs.push_back("-x");
152 CmdArgs.push_back(types::getTypeName(II.getType()));
155 if (II.isFilename())
156 CmdArgs.push_back(II.getFilename());
157 else {
158 const Arg &A = II.getInputArg();
160 // Reverse translate some rewritten options.
161 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
162 CmdArgs.push_back("-lstdc++");
163 continue;
166 // Don't render as input, we need gcc to do the translations.
167 A.render(Args, CmdArgs);
171 const std::string &customGCCName = D.getCCCGenericGCCName();
172 const char *GCCName;
173 if (!customGCCName.empty())
174 GCCName = customGCCName.c_str();
175 else if (D.CCCIsCXX()) {
176 GCCName = "g++";
177 } else
178 GCCName = "gcc";
180 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
181 C.addCommand(std::make_unique<Command>(JA, *this,
182 ResponseFileSupport::AtFileCurCP(),
183 Exec, CmdArgs, Inputs, Output));
186 void tools::gcc::Preprocessor::RenderExtraToolArgs(
187 const JobAction &JA, ArgStringList &CmdArgs) const {
188 CmdArgs.push_back("-E");
191 void tools::gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
192 ArgStringList &CmdArgs) const {
193 const Driver &D = getToolChain().getDriver();
195 switch (JA.getType()) {
196 // If -flto, etc. are present then make sure not to force assembly output.
197 case types::TY_LLVM_IR:
198 case types::TY_LTO_IR:
199 case types::TY_LLVM_BC:
200 case types::TY_LTO_BC:
201 CmdArgs.push_back("-c");
202 break;
203 // We assume we've got an "integrated" assembler in that gcc will produce an
204 // object file itself.
205 case types::TY_Object:
206 CmdArgs.push_back("-c");
207 break;
208 case types::TY_PP_Asm:
209 CmdArgs.push_back("-S");
210 break;
211 case types::TY_Nothing:
212 CmdArgs.push_back("-fsyntax-only");
213 break;
214 default:
215 D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
219 void tools::gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
220 ArgStringList &CmdArgs) const {
221 // The types are (hopefully) good enough.
224 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
225 switch (T.getArch()) {
226 case llvm::Triple::x86:
227 if (T.isOSIAMCU())
228 return "elf_iamcu";
229 return "elf_i386";
230 case llvm::Triple::aarch64:
231 return "aarch64linux";
232 case llvm::Triple::aarch64_be:
233 return "aarch64linuxb";
234 case llvm::Triple::arm:
235 case llvm::Triple::thumb:
236 case llvm::Triple::armeb:
237 case llvm::Triple::thumbeb:
238 return tools::arm::isARMBigEndian(T, Args) ? "armelfb_linux_eabi"
239 : "armelf_linux_eabi";
240 case llvm::Triple::m68k:
241 return "m68kelf";
242 case llvm::Triple::ppc:
243 if (T.isOSLinux())
244 return "elf32ppclinux";
245 return "elf32ppc";
246 case llvm::Triple::ppcle:
247 if (T.isOSLinux())
248 return "elf32lppclinux";
249 return "elf32lppc";
250 case llvm::Triple::ppc64:
251 return "elf64ppc";
252 case llvm::Triple::ppc64le:
253 return "elf64lppc";
254 case llvm::Triple::riscv32:
255 return "elf32lriscv";
256 case llvm::Triple::riscv64:
257 return "elf64lriscv";
258 case llvm::Triple::sparc:
259 case llvm::Triple::sparcel:
260 return "elf32_sparc";
261 case llvm::Triple::sparcv9:
262 return "elf64_sparc";
263 case llvm::Triple::loongarch32:
264 return "elf32loongarch";
265 case llvm::Triple::loongarch64:
266 return "elf64loongarch";
267 case llvm::Triple::mips:
268 return "elf32btsmip";
269 case llvm::Triple::mipsel:
270 return "elf32ltsmip";
271 case llvm::Triple::mips64:
272 if (tools::mips::hasMipsAbiArg(Args, "n32") ||
273 T.getEnvironment() == llvm::Triple::GNUABIN32)
274 return "elf32btsmipn32";
275 return "elf64btsmip";
276 case llvm::Triple::mips64el:
277 if (tools::mips::hasMipsAbiArg(Args, "n32") ||
278 T.getEnvironment() == llvm::Triple::GNUABIN32)
279 return "elf32ltsmipn32";
280 return "elf64ltsmip";
281 case llvm::Triple::systemz:
282 return "elf64_s390";
283 case llvm::Triple::x86_64:
284 if (T.isX32())
285 return "elf32_x86_64";
286 return "elf_x86_64";
287 case llvm::Triple::ve:
288 return "elf64ve";
289 case llvm::Triple::csky:
290 return "cskyelf_linux";
291 default:
292 return nullptr;
296 static bool getStaticPIE(const ArgList &Args, const ToolChain &TC) {
297 bool HasStaticPIE = Args.hasArg(options::OPT_static_pie);
298 if (HasStaticPIE && Args.hasArg(options::OPT_no_pie)) {
299 const Driver &D = TC.getDriver();
300 const llvm::opt::OptTable &Opts = D.getOpts();
301 StringRef StaticPIEName = Opts.getOptionName(options::OPT_static_pie);
302 StringRef NoPIEName = Opts.getOptionName(options::OPT_nopie);
303 D.Diag(diag::err_drv_cannot_mix_options) << StaticPIEName << NoPIEName;
305 return HasStaticPIE;
308 static bool getStatic(const ArgList &Args) {
309 return Args.hasArg(options::OPT_static) &&
310 !Args.hasArg(options::OPT_static_pie);
313 void tools::gnutools::StaticLibTool::ConstructJob(
314 Compilation &C, const JobAction &JA, const InputInfo &Output,
315 const InputInfoList &Inputs, const ArgList &Args,
316 const char *LinkingOutput) const {
317 const Driver &D = getToolChain().getDriver();
319 // Silence warning for "clang -g foo.o -o foo"
320 Args.ClaimAllArgs(options::OPT_g_Group);
321 // and "clang -emit-llvm foo.o -o foo"
322 Args.ClaimAllArgs(options::OPT_emit_llvm);
323 // and for "clang -w foo.o -o foo". Other warning options are already
324 // handled somewhere else.
325 Args.ClaimAllArgs(options::OPT_w);
326 // Silence warnings when linking C code with a C++ '-stdlib' argument.
327 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
329 // ar tool command "llvm-ar <options> <output_file> <input_files>".
330 ArgStringList CmdArgs;
331 // Create and insert file members with a deterministic index.
332 CmdArgs.push_back("rcsD");
333 CmdArgs.push_back(Output.getFilename());
335 for (const auto &II : Inputs) {
336 if (II.isFilename()) {
337 CmdArgs.push_back(II.getFilename());
341 // Delete old output archive file if it already exists before generating a new
342 // archive file.
343 auto OutputFileName = Output.getFilename();
344 if (Output.isFilename() && llvm::sys::fs::exists(OutputFileName)) {
345 if (std::error_code EC = llvm::sys::fs::remove(OutputFileName)) {
346 D.Diag(diag::err_drv_unable_to_remove_file) << EC.message();
347 return;
351 const char *Exec = Args.MakeArgString(getToolChain().GetStaticLibToolPath());
352 C.addCommand(std::make_unique<Command>(JA, *this,
353 ResponseFileSupport::AtFileCurCP(),
354 Exec, CmdArgs, Inputs, Output));
357 void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
358 const InputInfo &Output,
359 const InputInfoList &Inputs,
360 const ArgList &Args,
361 const char *LinkingOutput) const {
362 // FIXME: The Linker class constructor takes a ToolChain and not a
363 // Generic_ELF, so the static_cast might return a reference to a invalid
364 // instance (see PR45061). Ideally, the Linker constructor needs to take a
365 // Generic_ELF instead.
366 const auto &ToolChain = static_cast<const Generic_ELF &>(getToolChain());
367 const Driver &D = ToolChain.getDriver();
369 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
371 const llvm::Triple::ArchType Arch = ToolChain.getArch();
372 const bool isOHOSFamily = ToolChain.getTriple().isOHOSFamily();
373 const bool isAndroid = ToolChain.getTriple().isAndroid();
374 const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
375 const bool IsVE = ToolChain.getTriple().isVE();
376 const bool IsStaticPIE = getStaticPIE(Args, ToolChain);
377 const bool IsStatic = getStatic(Args);
378 const bool HasCRTBeginEndFiles =
379 ToolChain.getTriple().hasEnvironment() ||
380 (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
382 ArgStringList CmdArgs;
384 // Silence warning for "clang -g foo.o -o foo"
385 Args.ClaimAllArgs(options::OPT_g_Group);
386 // and "clang -emit-llvm foo.o -o foo"
387 Args.ClaimAllArgs(options::OPT_emit_llvm);
388 // and for "clang -w foo.o -o foo". Other warning options are already
389 // handled somewhere else.
390 Args.ClaimAllArgs(options::OPT_w);
392 if (!D.SysRoot.empty())
393 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
395 if (Args.hasArg(options::OPT_s))
396 CmdArgs.push_back("-s");
398 if (Triple.isARM() || Triple.isThumb()) {
399 bool IsBigEndian = arm::isARMBigEndian(Triple, Args);
400 if (IsBigEndian)
401 arm::appendBE8LinkFlag(Args, CmdArgs, Triple);
402 CmdArgs.push_back(IsBigEndian ? "-EB" : "-EL");
403 } else if (Triple.isAArch64()) {
404 CmdArgs.push_back(Arch == llvm::Triple::aarch64_be ? "-EB" : "-EL");
407 // Most Android ARM64 targets should enable the linker fix for erratum
408 // 843419. Only non-Cortex-A53 devices are allowed to skip this flag.
409 if (Arch == llvm::Triple::aarch64 && (isAndroid || isOHOSFamily)) {
410 std::string CPU = getCPUName(D, Args, Triple);
411 if (CPU.empty() || CPU == "generic" || CPU == "cortex-a53")
412 CmdArgs.push_back("--fix-cortex-a53-843419");
415 ToolChain.addExtraOpts(CmdArgs);
417 CmdArgs.push_back("--eh-frame-hdr");
419 if (const char *LDMOption = getLDMOption(ToolChain.getTriple(), Args)) {
420 CmdArgs.push_back("-m");
421 CmdArgs.push_back(LDMOption);
422 } else {
423 D.Diag(diag::err_target_unknown_triple) << Triple.str();
424 return;
426 if (Triple.isRISCV())
427 CmdArgs.push_back("-X");
429 const bool IsShared = Args.hasArg(options::OPT_shared);
430 if (IsShared)
431 CmdArgs.push_back("-shared");
432 bool IsPIE = false;
433 if (IsStaticPIE) {
434 CmdArgs.push_back("-static");
435 CmdArgs.push_back("-pie");
436 CmdArgs.push_back("--no-dynamic-linker");
437 CmdArgs.push_back("-z");
438 CmdArgs.push_back("text");
439 } else if (IsStatic) {
440 CmdArgs.push_back("-static");
441 } else if (!Args.hasArg(options::OPT_r)) {
442 if (Args.hasArg(options::OPT_rdynamic))
443 CmdArgs.push_back("-export-dynamic");
444 if (!IsShared) {
445 IsPIE = Args.hasFlag(options::OPT_pie, options::OPT_no_pie,
446 ToolChain.isPIEDefault(Args));
447 if (IsPIE)
448 CmdArgs.push_back("-pie");
449 CmdArgs.push_back("-dynamic-linker");
450 CmdArgs.push_back(Args.MakeArgString(Twine(D.DyldPrefix) +
451 ToolChain.getDynamicLinker(Args)));
455 CmdArgs.push_back("-o");
456 CmdArgs.push_back(Output.getFilename());
458 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
459 options::OPT_r)) {
460 if (!isAndroid && !IsIAMCU) {
461 const char *crt1 = nullptr;
462 if (!Args.hasArg(options::OPT_shared)) {
463 if (Args.hasArg(options::OPT_pg))
464 crt1 = "gcrt1.o";
465 else if (IsPIE)
466 crt1 = "Scrt1.o";
467 else if (IsStaticPIE)
468 crt1 = "rcrt1.o";
469 else
470 crt1 = "crt1.o";
472 if (crt1)
473 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
475 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
478 if (IsVE) {
479 CmdArgs.push_back("-z");
480 CmdArgs.push_back("max-page-size=0x4000000");
483 if (IsIAMCU)
484 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
485 else if (HasCRTBeginEndFiles) {
486 std::string P;
487 if (ToolChain.GetRuntimeLibType(Args) == ToolChain::RLT_CompilerRT &&
488 !isAndroid) {
489 std::string crtbegin = ToolChain.getCompilerRT(Args, "crtbegin",
490 ToolChain::FT_Object);
491 if (ToolChain.getVFS().exists(crtbegin))
492 P = crtbegin;
494 if (P.empty()) {
495 const char *crtbegin;
496 if (Args.hasArg(options::OPT_shared))
497 crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
498 else if (IsStatic)
499 crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
500 else if (IsPIE || IsStaticPIE)
501 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
502 else
503 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
504 P = ToolChain.GetFilePath(crtbegin);
506 CmdArgs.push_back(Args.MakeArgString(P));
509 // Add crtfastmath.o if available and fast math is enabled.
510 ToolChain.addFastMathRuntimeIfAvailable(Args, CmdArgs);
513 Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_u});
515 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
517 if (D.isUsingLTO()) {
518 assert(!Inputs.empty() && "Must have at least one input.");
519 // Find the first filename InputInfo object.
520 auto Input = llvm::find_if(
521 Inputs, [](const InputInfo &II) -> bool { return II.isFilename(); });
522 if (Input == Inputs.end())
523 // For a very rare case, all of the inputs to the linker are
524 // InputArg. If that happens, just use the first InputInfo.
525 Input = Inputs.begin();
527 addLTOOptions(ToolChain, Args, CmdArgs, Output, *Input,
528 D.getLTOMode() == LTOK_Thin);
531 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
532 CmdArgs.push_back("--no-demangle");
534 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
535 bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
536 addLinkerCompressDebugSectionsOption(ToolChain, Args, CmdArgs);
537 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
539 addHIPRuntimeLibArgs(ToolChain, C, Args, CmdArgs);
541 // The profile runtime also needs access to system libraries.
542 getToolChain().addProfileRTLibs(Args, CmdArgs);
544 if (D.CCCIsCXX() &&
545 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
546 options::OPT_r)) {
547 if (ToolChain.ShouldLinkCXXStdlib(Args)) {
548 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
549 !Args.hasArg(options::OPT_static);
550 if (OnlyLibstdcxxStatic)
551 CmdArgs.push_back("-Bstatic");
552 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
553 if (OnlyLibstdcxxStatic)
554 CmdArgs.push_back("-Bdynamic");
556 CmdArgs.push_back("-lm");
559 // Silence warnings when linking C code with a C++ '-stdlib' argument.
560 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
562 // Additional linker set-up and flags for Fortran. This is required in order
563 // to generate executables. As Fortran runtime depends on the C runtime,
564 // these dependencies need to be listed before the C runtime below (i.e.
565 // AddRunTimeLibs).
566 if (D.IsFlangMode()) {
567 addFortranRuntimeLibraryPath(ToolChain, Args, CmdArgs);
568 addFortranRuntimeLibs(ToolChain, Args, CmdArgs);
569 CmdArgs.push_back("-lm");
572 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_r)) {
573 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
574 if (IsStatic || IsStaticPIE)
575 CmdArgs.push_back("--start-group");
577 if (NeedsSanitizerDeps)
578 linkSanitizerRuntimeDeps(ToolChain, Args, CmdArgs);
580 if (NeedsXRayDeps)
581 linkXRayRuntimeDeps(ToolChain, Args, CmdArgs);
583 bool WantPthread = Args.hasArg(options::OPT_pthread) ||
584 Args.hasArg(options::OPT_pthreads);
586 // Use the static OpenMP runtime with -static-openmp
587 bool StaticOpenMP = Args.hasArg(options::OPT_static_openmp) &&
588 !Args.hasArg(options::OPT_static);
590 // FIXME: Only pass GompNeedsRT = true for platforms with libgomp that
591 // require librt. Most modern Linux platforms do, but some may not.
592 if (addOpenMPRuntime(CmdArgs, ToolChain, Args, StaticOpenMP,
593 JA.isHostOffloading(Action::OFK_OpenMP),
594 /* GompNeedsRT= */ true))
595 // OpenMP runtimes implies pthreads when using the GNU toolchain.
596 // FIXME: Does this really make sense for all GNU toolchains?
597 WantPthread = true;
599 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
601 // LLVM support for atomics on 32-bit SPARC V8+ is incomplete, so
602 // forcibly link with libatomic as a workaround.
603 // TODO: Issue #41880 and D118021.
604 if (getToolChain().getTriple().getArch() == llvm::Triple::sparc) {
605 CmdArgs.push_back("--push-state");
606 CmdArgs.push_back("--as-needed");
607 CmdArgs.push_back("-latomic");
608 CmdArgs.push_back("--pop-state");
611 // We don't need libpthread neither for bionic (Android) nor for musl,
612 // (used by OHOS as runtime library).
613 if (WantPthread && !isAndroid && !isOHOSFamily)
614 CmdArgs.push_back("-lpthread");
616 if (Args.hasArg(options::OPT_fsplit_stack))
617 CmdArgs.push_back("--wrap=pthread_create");
619 if (!Args.hasArg(options::OPT_nolibc))
620 CmdArgs.push_back("-lc");
622 // Add IAMCU specific libs, if needed.
623 if (IsIAMCU)
624 CmdArgs.push_back("-lgloss");
626 if (IsStatic || IsStaticPIE)
627 CmdArgs.push_back("--end-group");
628 else
629 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
631 // Add IAMCU specific libs (outside the group), if needed.
632 if (IsIAMCU) {
633 CmdArgs.push_back("--as-needed");
634 CmdArgs.push_back("-lsoftfp");
635 CmdArgs.push_back("--no-as-needed");
639 if (!Args.hasArg(options::OPT_nostartfiles) && !IsIAMCU) {
640 if (HasCRTBeginEndFiles) {
641 std::string P;
642 if (ToolChain.GetRuntimeLibType(Args) == ToolChain::RLT_CompilerRT &&
643 !isAndroid) {
644 std::string crtend = ToolChain.getCompilerRT(Args, "crtend",
645 ToolChain::FT_Object);
646 if (ToolChain.getVFS().exists(crtend))
647 P = crtend;
649 if (P.empty()) {
650 const char *crtend;
651 if (Args.hasArg(options::OPT_shared))
652 crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
653 else if (IsPIE || IsStaticPIE)
654 crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
655 else
656 crtend = isAndroid ? "crtend_android.o" : "crtend.o";
657 P = ToolChain.GetFilePath(crtend);
659 CmdArgs.push_back(Args.MakeArgString(P));
661 if (!isAndroid)
662 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
666 Args.AddAllArgs(CmdArgs, options::OPT_T);
668 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
669 C.addCommand(std::make_unique<Command>(JA, *this,
670 ResponseFileSupport::AtFileCurCP(),
671 Exec, CmdArgs, Inputs, Output));
674 void tools::gnutools::Assembler::ConstructJob(Compilation &C,
675 const JobAction &JA,
676 const InputInfo &Output,
677 const InputInfoList &Inputs,
678 const ArgList &Args,
679 const char *LinkingOutput) const {
680 const auto &D = getToolChain().getDriver();
682 claimNoWarnArgs(Args);
684 ArgStringList CmdArgs;
686 llvm::Reloc::Model RelocationModel;
687 unsigned PICLevel;
688 bool IsPIE;
689 const char *DefaultAssembler = "as";
690 // Enforce GNU as on Solaris; the native assembler's input syntax isn't fully
691 // compatible.
692 if (getToolChain().getTriple().isOSSolaris())
693 DefaultAssembler = "gas";
694 std::tie(RelocationModel, PICLevel, IsPIE) =
695 ParsePICArgs(getToolChain(), Args);
697 if (const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ)) {
698 if (A->getOption().getID() == options::OPT_gz) {
699 CmdArgs.push_back("--compress-debug-sections");
700 } else {
701 StringRef Value = A->getValue();
702 if (Value == "none" || Value == "zlib" || Value == "zstd") {
703 CmdArgs.push_back(
704 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
705 } else {
706 D.Diag(diag::err_drv_unsupported_option_argument)
707 << A->getSpelling() << Value;
712 switch (getToolChain().getArch()) {
713 default:
714 break;
715 // Add --32/--64 to make sure we get the format we want.
716 // This is incomplete
717 case llvm::Triple::x86:
718 CmdArgs.push_back("--32");
719 break;
720 case llvm::Triple::x86_64:
721 if (getToolChain().getTriple().isX32())
722 CmdArgs.push_back("--x32");
723 else
724 CmdArgs.push_back("--64");
725 break;
726 case llvm::Triple::ppc: {
727 CmdArgs.push_back("-a32");
728 CmdArgs.push_back("-mppc");
729 CmdArgs.push_back("-mbig-endian");
730 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
731 getCPUName(D, Args, getToolChain().getTriple())));
732 break;
734 case llvm::Triple::ppcle: {
735 CmdArgs.push_back("-a32");
736 CmdArgs.push_back("-mppc");
737 CmdArgs.push_back("-mlittle-endian");
738 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
739 getCPUName(D, Args, getToolChain().getTriple())));
740 break;
742 case llvm::Triple::ppc64: {
743 CmdArgs.push_back("-a64");
744 CmdArgs.push_back("-mppc64");
745 CmdArgs.push_back("-mbig-endian");
746 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
747 getCPUName(D, Args, getToolChain().getTriple())));
748 break;
750 case llvm::Triple::ppc64le: {
751 CmdArgs.push_back("-a64");
752 CmdArgs.push_back("-mppc64");
753 CmdArgs.push_back("-mlittle-endian");
754 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
755 getCPUName(D, Args, getToolChain().getTriple())));
756 break;
758 case llvm::Triple::riscv32:
759 case llvm::Triple::riscv64: {
760 StringRef ABIName = riscv::getRISCVABI(Args, getToolChain().getTriple());
761 CmdArgs.push_back("-mabi");
762 CmdArgs.push_back(ABIName.data());
763 StringRef MArchName = riscv::getRISCVArch(Args, getToolChain().getTriple());
764 CmdArgs.push_back("-march");
765 CmdArgs.push_back(MArchName.data());
766 if (!Args.hasFlag(options::OPT_mrelax, options::OPT_mno_relax, true))
767 Args.addOptOutFlag(CmdArgs, options::OPT_mrelax, options::OPT_mno_relax);
768 break;
770 case llvm::Triple::sparc:
771 case llvm::Triple::sparcel: {
772 CmdArgs.push_back("-32");
773 std::string CPU = getCPUName(D, Args, getToolChain().getTriple());
774 CmdArgs.push_back(
775 sparc::getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
776 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
777 break;
779 case llvm::Triple::sparcv9: {
780 CmdArgs.push_back("-64");
781 std::string CPU = getCPUName(D, Args, getToolChain().getTriple());
782 CmdArgs.push_back(
783 sparc::getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
784 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
785 break;
787 case llvm::Triple::arm:
788 case llvm::Triple::armeb:
789 case llvm::Triple::thumb:
790 case llvm::Triple::thumbeb: {
791 const llvm::Triple &Triple2 = getToolChain().getTriple();
792 CmdArgs.push_back(arm::isARMBigEndian(Triple2, Args) ? "-EB" : "-EL");
793 switch (Triple2.getSubArch()) {
794 case llvm::Triple::ARMSubArch_v7:
795 CmdArgs.push_back("-mfpu=neon");
796 break;
797 case llvm::Triple::ARMSubArch_v8:
798 CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
799 break;
800 default:
801 break;
804 switch (arm::getARMFloatABI(getToolChain(), Args)) {
805 case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
806 case arm::FloatABI::Soft:
807 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
808 break;
809 case arm::FloatABI::SoftFP:
810 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
811 break;
812 case arm::FloatABI::Hard:
813 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
814 break;
817 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
818 normalizeCPUNamesForAssembler(Args, CmdArgs);
820 Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
821 // The integrated assembler doesn't implement e_flags setting behavior for
822 // -meabi=gnu (gcc -mabi={apcs-gnu,atpcs} passes -meabi=gnu to gas). For
823 // compatibility we accept but warn.
824 if (Arg *A = Args.getLastArgNoClaim(options::OPT_mabi_EQ))
825 A->ignoreTargetSpecific();
826 break;
828 case llvm::Triple::aarch64:
829 case llvm::Triple::aarch64_be: {
830 CmdArgs.push_back(
831 getToolChain().getArch() == llvm::Triple::aarch64_be ? "-EB" : "-EL");
832 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
833 normalizeCPUNamesForAssembler(Args, CmdArgs);
835 break;
837 // TODO: handle loongarch32.
838 case llvm::Triple::loongarch64: {
839 StringRef ABIName =
840 loongarch::getLoongArchABI(D, Args, getToolChain().getTriple());
841 CmdArgs.push_back(Args.MakeArgString("-mabi=" + ABIName));
842 break;
844 case llvm::Triple::mips:
845 case llvm::Triple::mipsel:
846 case llvm::Triple::mips64:
847 case llvm::Triple::mips64el: {
848 StringRef CPUName;
849 StringRef ABIName;
850 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
851 ABIName = mips::getGnuCompatibleMipsABIName(ABIName);
853 CmdArgs.push_back("-march");
854 CmdArgs.push_back(CPUName.data());
856 CmdArgs.push_back("-mabi");
857 CmdArgs.push_back(ABIName.data());
859 // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
860 // or -mshared (not implemented) is in effect.
861 if (RelocationModel == llvm::Reloc::Static)
862 CmdArgs.push_back("-mno-shared");
864 // LLVM doesn't support -mplt yet and acts as if it is always given.
865 // However, -mplt has no effect with the N64 ABI.
866 if (ABIName != "64" && !Args.hasArg(options::OPT_mno_abicalls))
867 CmdArgs.push_back("-call_nonpic");
869 if (getToolChain().getTriple().isLittleEndian())
870 CmdArgs.push_back("-EL");
871 else
872 CmdArgs.push_back("-EB");
874 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
875 if (StringRef(A->getValue()) == "2008")
876 CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
879 // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
880 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
881 options::OPT_mfp64)) {
882 A->claim();
883 A->render(Args, CmdArgs);
884 } else if (mips::shouldUseFPXX(
885 Args, getToolChain().getTriple(), CPUName, ABIName,
886 mips::getMipsFloatABI(getToolChain().getDriver(), Args,
887 getToolChain().getTriple())))
888 CmdArgs.push_back("-mfpxx");
890 // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
891 // -mno-mips16 is actually -no-mips16.
892 if (Arg *A =
893 Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
894 if (A->getOption().matches(options::OPT_mips16)) {
895 A->claim();
896 A->render(Args, CmdArgs);
897 } else {
898 A->claim();
899 CmdArgs.push_back("-no-mips16");
903 Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
904 options::OPT_mno_micromips);
905 Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
906 Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
908 if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
909 // Do not use AddLastArg because not all versions of MIPS assembler
910 // support -mmsa / -mno-msa options.
911 if (A->getOption().matches(options::OPT_mmsa))
912 CmdArgs.push_back(Args.MakeArgString("-mmsa"));
915 Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
916 options::OPT_msoft_float);
918 Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
919 options::OPT_msingle_float);
921 Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
922 options::OPT_mno_odd_spreg);
924 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
925 break;
927 case llvm::Triple::systemz: {
928 // Always pass an -march option, since our default of z10 is later
929 // than the GNU assembler's default.
930 std::string CPUName = systemz::getSystemZTargetCPU(Args);
931 CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
932 break;
934 case llvm::Triple::ve:
935 DefaultAssembler = "nas";
938 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
939 options::OPT_fdebug_prefix_map_EQ)) {
940 StringRef Map = A->getValue();
941 if (!Map.contains('='))
942 D.Diag(diag::err_drv_invalid_argument_to_option)
943 << Map << A->getOption().getName();
944 else {
945 CmdArgs.push_back(Args.MakeArgString("--debug-prefix-map"));
946 CmdArgs.push_back(Args.MakeArgString(Map));
948 A->claim();
951 Args.AddAllArgs(CmdArgs, options::OPT_I);
952 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
954 CmdArgs.push_back("-o");
955 CmdArgs.push_back(Output.getFilename());
957 for (const auto &II : Inputs)
958 CmdArgs.push_back(II.getFilename());
960 if (Arg *A = Args.getLastArg(options::OPT_g_Flag, options::OPT_gN_Group,
961 options::OPT_gdwarf_2, options::OPT_gdwarf_3,
962 options::OPT_gdwarf_4, options::OPT_gdwarf_5,
963 options::OPT_gdwarf))
964 if (!A->getOption().matches(options::OPT_g0)) {
965 Args.AddLastArg(CmdArgs, options::OPT_g_Flag);
967 unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
968 CmdArgs.push_back(Args.MakeArgString("-gdwarf-" + Twine(DwarfVersion)));
971 const char *Exec =
972 Args.MakeArgString(getToolChain().GetProgramPath(DefaultAssembler));
973 C.addCommand(std::make_unique<Command>(JA, *this,
974 ResponseFileSupport::AtFileCurCP(),
975 Exec, CmdArgs, Inputs, Output));
977 // Handle the debug info splitting at object creation time if we're
978 // creating an object.
979 // TODO: Currently only works on linux with newer objcopy.
980 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
981 getToolChain().getTriple().isOSLinux())
982 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
983 SplitDebugName(JA, Args, Inputs[0], Output));
986 namespace {
987 // Filter to remove Multilibs that don't exist as a suffix to Path
988 class FilterNonExistent {
989 StringRef Base, File;
990 llvm::vfs::FileSystem &VFS;
992 public:
993 FilterNonExistent(StringRef Base, StringRef File, llvm::vfs::FileSystem &VFS)
994 : Base(Base), File(File), VFS(VFS) {}
995 bool operator()(const Multilib &M) {
996 return !VFS.exists(Base + M.gccSuffix() + File);
999 } // end anonymous namespace
1001 static bool isSoftFloatABI(const ArgList &Args) {
1002 Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1003 options::OPT_mfloat_abi_EQ);
1004 if (!A)
1005 return false;
1007 return A->getOption().matches(options::OPT_msoft_float) ||
1008 (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
1009 A->getValue() == StringRef("soft"));
1012 static bool isArmOrThumbArch(llvm::Triple::ArchType Arch) {
1013 return Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb;
1016 static bool isMipsEL(llvm::Triple::ArchType Arch) {
1017 return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
1020 static bool isMips16(const ArgList &Args) {
1021 Arg *A = Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16);
1022 return A && A->getOption().matches(options::OPT_mips16);
1025 static bool isMicroMips(const ArgList &Args) {
1026 Arg *A = Args.getLastArg(options::OPT_mmicromips, options::OPT_mno_micromips);
1027 return A && A->getOption().matches(options::OPT_mmicromips);
1030 static bool isMSP430(llvm::Triple::ArchType Arch) {
1031 return Arch == llvm::Triple::msp430;
1034 static bool findMipsCsMultilibs(const Multilib::flags_list &Flags,
1035 FilterNonExistent &NonExistent,
1036 DetectedMultilibs &Result) {
1037 // Check for Code Sourcery toolchain multilibs
1038 MultilibSet CSMipsMultilibs;
1040 auto MArchMips16 = MultilibBuilder("/mips16").flag("-m32").flag("-mips16");
1042 auto MArchMicroMips =
1043 MultilibBuilder("/micromips").flag("-m32").flag("-mmicromips");
1045 auto MArchDefault = MultilibBuilder("")
1046 .flag("-mips16", /*Disallow=*/true)
1047 .flag("-mmicromips", /*Disallow=*/true);
1049 auto UCLibc = MultilibBuilder("/uclibc").flag("-muclibc");
1051 auto SoftFloat = MultilibBuilder("/soft-float").flag("-msoft-float");
1053 auto Nan2008 = MultilibBuilder("/nan2008").flag("-mnan=2008");
1055 auto DefaultFloat = MultilibBuilder("")
1056 .flag("-msoft-float", /*Disallow=*/true)
1057 .flag("-mnan=2008", /*Disallow=*/true);
1059 auto BigEndian =
1060 MultilibBuilder("").flag("-EB").flag("-EL", /*Disallow=*/true);
1062 auto LittleEndian =
1063 MultilibBuilder("/el").flag("-EL").flag("-EB", /*Disallow=*/true);
1065 // Note that this one's osSuffix is ""
1066 auto MAbi64 = MultilibBuilder("")
1067 .gccSuffix("/64")
1068 .includeSuffix("/64")
1069 .flag("-mabi=n64")
1070 .flag("-mabi=n32", /*Disallow=*/true)
1071 .flag("-m32", /*Disallow=*/true);
1073 CSMipsMultilibs =
1074 MultilibSetBuilder()
1075 .Either(MArchMips16, MArchMicroMips, MArchDefault)
1076 .Maybe(UCLibc)
1077 .Either(SoftFloat, Nan2008, DefaultFloat)
1078 .FilterOut("/micromips/nan2008")
1079 .FilterOut("/mips16/nan2008")
1080 .Either(BigEndian, LittleEndian)
1081 .Maybe(MAbi64)
1082 .FilterOut("/mips16.*/64")
1083 .FilterOut("/micromips.*/64")
1084 .makeMultilibSet()
1085 .FilterOut(NonExistent)
1086 .setIncludeDirsCallback([](const Multilib &M) {
1087 std::vector<std::string> Dirs({"/include"});
1088 if (StringRef(M.includeSuffix()).starts_with("/uclibc"))
1089 Dirs.push_back(
1090 "/../../../../mips-linux-gnu/libc/uclibc/usr/include");
1091 else
1092 Dirs.push_back("/../../../../mips-linux-gnu/libc/usr/include");
1093 return Dirs;
1097 MultilibSet DebianMipsMultilibs;
1099 MultilibBuilder MAbiN32 =
1100 MultilibBuilder().gccSuffix("/n32").includeSuffix("/n32").flag(
1101 "-mabi=n32");
1103 MultilibBuilder M64 = MultilibBuilder()
1104 .gccSuffix("/64")
1105 .includeSuffix("/64")
1106 .flag("-m64")
1107 .flag("-m32", /*Disallow=*/true)
1108 .flag("-mabi=n32", /*Disallow=*/true);
1110 MultilibBuilder M32 = MultilibBuilder()
1111 .gccSuffix("/32")
1112 .flag("-m64", /*Disallow=*/true)
1113 .flag("-m32")
1114 .flag("-mabi=n32", /*Disallow=*/true);
1116 DebianMipsMultilibs = MultilibSetBuilder()
1117 .Either(M32, M64, MAbiN32)
1118 .makeMultilibSet()
1119 .FilterOut(NonExistent);
1122 // Sort candidates. Toolchain that best meets the directories tree goes first.
1123 // Then select the first toolchains matches command line flags.
1124 MultilibSet *Candidates[] = {&CSMipsMultilibs, &DebianMipsMultilibs};
1125 if (CSMipsMultilibs.size() < DebianMipsMultilibs.size())
1126 std::iter_swap(Candidates, Candidates + 1);
1127 for (const MultilibSet *Candidate : Candidates) {
1128 if (Candidate->select(Flags, Result.SelectedMultilibs)) {
1129 if (Candidate == &DebianMipsMultilibs)
1130 Result.BiarchSibling = Multilib();
1131 Result.Multilibs = *Candidate;
1132 return true;
1135 return false;
1138 static bool findMipsAndroidMultilibs(llvm::vfs::FileSystem &VFS, StringRef Path,
1139 const Multilib::flags_list &Flags,
1140 FilterNonExistent &NonExistent,
1141 DetectedMultilibs &Result) {
1143 MultilibSet AndroidMipsMultilibs =
1144 MultilibSetBuilder()
1145 .Maybe(MultilibBuilder("/mips-r2", {}, {}).flag("-march=mips32r2"))
1146 .Maybe(MultilibBuilder("/mips-r6", {}, {}).flag("-march=mips32r6"))
1147 .makeMultilibSet()
1148 .FilterOut(NonExistent);
1150 MultilibSet AndroidMipselMultilibs =
1151 MultilibSetBuilder()
1152 .Either(MultilibBuilder().flag("-march=mips32"),
1153 MultilibBuilder("/mips-r2", "", "/mips-r2")
1154 .flag("-march=mips32r2"),
1155 MultilibBuilder("/mips-r6", "", "/mips-r6")
1156 .flag("-march=mips32r6"))
1157 .makeMultilibSet()
1158 .FilterOut(NonExistent);
1160 MultilibSet AndroidMips64elMultilibs =
1161 MultilibSetBuilder()
1162 .Either(MultilibBuilder().flag("-march=mips64r6"),
1163 MultilibBuilder("/32/mips-r1", "", "/mips-r1")
1164 .flag("-march=mips32"),
1165 MultilibBuilder("/32/mips-r2", "", "/mips-r2")
1166 .flag("-march=mips32r2"),
1167 MultilibBuilder("/32/mips-r6", "", "/mips-r6")
1168 .flag("-march=mips32r6"))
1169 .makeMultilibSet()
1170 .FilterOut(NonExistent);
1172 MultilibSet *MS = &AndroidMipsMultilibs;
1173 if (VFS.exists(Path + "/mips-r6"))
1174 MS = &AndroidMipselMultilibs;
1175 else if (VFS.exists(Path + "/32"))
1176 MS = &AndroidMips64elMultilibs;
1177 if (MS->select(Flags, Result.SelectedMultilibs)) {
1178 Result.Multilibs = *MS;
1179 return true;
1181 return false;
1184 static bool findMipsMuslMultilibs(const Multilib::flags_list &Flags,
1185 FilterNonExistent &NonExistent,
1186 DetectedMultilibs &Result) {
1187 // Musl toolchain multilibs
1188 MultilibSet MuslMipsMultilibs;
1190 auto MArchMipsR2 = MultilibBuilder("")
1191 .osSuffix("/mips-r2-hard-musl")
1192 .flag("-EB")
1193 .flag("-EL", /*Disallow=*/true)
1194 .flag("-march=mips32r2");
1196 auto MArchMipselR2 = MultilibBuilder("/mipsel-r2-hard-musl")
1197 .flag("-EB", /*Disallow=*/true)
1198 .flag("-EL")
1199 .flag("-march=mips32r2");
1201 MuslMipsMultilibs = MultilibSetBuilder()
1202 .Either(MArchMipsR2, MArchMipselR2)
1203 .makeMultilibSet();
1205 // Specify the callback that computes the include directories.
1206 MuslMipsMultilibs.setIncludeDirsCallback([](const Multilib &M) {
1207 return std::vector<std::string>(
1208 {"/../sysroot" + M.osSuffix() + "/usr/include"});
1211 if (MuslMipsMultilibs.select(Flags, Result.SelectedMultilibs)) {
1212 Result.Multilibs = MuslMipsMultilibs;
1213 return true;
1215 return false;
1218 static bool findMipsMtiMultilibs(const Multilib::flags_list &Flags,
1219 FilterNonExistent &NonExistent,
1220 DetectedMultilibs &Result) {
1221 // CodeScape MTI toolchain v1.2 and early.
1222 MultilibSet MtiMipsMultilibsV1;
1224 auto MArchMips32 = MultilibBuilder("/mips32")
1225 .flag("-m32")
1226 .flag("-m64", /*Disallow=*/true)
1227 .flag("-mmicromips", /*Disallow=*/true)
1228 .flag("-march=mips32");
1230 auto MArchMicroMips = MultilibBuilder("/micromips")
1231 .flag("-m32")
1232 .flag("-m64", /*Disallow=*/true)
1233 .flag("-mmicromips");
1235 auto MArchMips64r2 = MultilibBuilder("/mips64r2")
1236 .flag("-m32", /*Disallow=*/true)
1237 .flag("-m64")
1238 .flag("-march=mips64r2");
1240 auto MArchMips64 = MultilibBuilder("/mips64")
1241 .flag("-m32", /*Disallow=*/true)
1242 .flag("-m64")
1243 .flag("-march=mips64r2", /*Disallow=*/true);
1245 auto MArchDefault = MultilibBuilder("")
1246 .flag("-m32")
1247 .flag("-m64", /*Disallow=*/true)
1248 .flag("-mmicromips", /*Disallow=*/true)
1249 .flag("-march=mips32r2");
1251 auto Mips16 = MultilibBuilder("/mips16").flag("-mips16");
1253 auto UCLibc = MultilibBuilder("/uclibc").flag("-muclibc");
1255 auto MAbi64 = MultilibBuilder("/64")
1256 .flag("-mabi=n64")
1257 .flag("-mabi=n32", /*Disallow=*/true)
1258 .flag("-m32", /*Disallow=*/true);
1260 auto BigEndian =
1261 MultilibBuilder("").flag("-EB").flag("-EL", /*Disallow=*/true);
1263 auto LittleEndian =
1264 MultilibBuilder("/el").flag("-EL").flag("-EB", /*Disallow=*/true);
1266 auto SoftFloat = MultilibBuilder("/sof").flag("-msoft-float");
1268 auto Nan2008 = MultilibBuilder("/nan2008").flag("-mnan=2008");
1270 MtiMipsMultilibsV1 =
1271 MultilibSetBuilder()
1272 .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64,
1273 MArchDefault)
1274 .Maybe(UCLibc)
1275 .Maybe(Mips16)
1276 .FilterOut("/mips64/mips16")
1277 .FilterOut("/mips64r2/mips16")
1278 .FilterOut("/micromips/mips16")
1279 .Maybe(MAbi64)
1280 .FilterOut("/micromips/64")
1281 .FilterOut("/mips32/64")
1282 .FilterOut("^/64")
1283 .FilterOut("/mips16/64")
1284 .Either(BigEndian, LittleEndian)
1285 .Maybe(SoftFloat)
1286 .Maybe(Nan2008)
1287 .FilterOut(".*sof/nan2008")
1288 .makeMultilibSet()
1289 .FilterOut(NonExistent)
1290 .setIncludeDirsCallback([](const Multilib &M) {
1291 std::vector<std::string> Dirs({"/include"});
1292 if (StringRef(M.includeSuffix()).starts_with("/uclibc"))
1293 Dirs.push_back("/../../../../sysroot/uclibc/usr/include");
1294 else
1295 Dirs.push_back("/../../../../sysroot/usr/include");
1296 return Dirs;
1300 // CodeScape IMG toolchain starting from v1.3.
1301 MultilibSet MtiMipsMultilibsV2;
1303 auto BeHard = MultilibBuilder("/mips-r2-hard")
1304 .flag("-EB")
1305 .flag("-msoft-float", /*Disallow=*/true)
1306 .flag("-mnan=2008", /*Disallow=*/true)
1307 .flag("-muclibc", /*Disallow=*/true);
1308 auto BeSoft = MultilibBuilder("/mips-r2-soft")
1309 .flag("-EB")
1310 .flag("-msoft-float")
1311 .flag("-mnan=2008", /*Disallow=*/true);
1312 auto ElHard = MultilibBuilder("/mipsel-r2-hard")
1313 .flag("-EL")
1314 .flag("-msoft-float", /*Disallow=*/true)
1315 .flag("-mnan=2008", /*Disallow=*/true)
1316 .flag("-muclibc", /*Disallow=*/true);
1317 auto ElSoft = MultilibBuilder("/mipsel-r2-soft")
1318 .flag("-EL")
1319 .flag("-msoft-float")
1320 .flag("-mnan=2008", /*Disallow=*/true)
1321 .flag("-mmicromips", /*Disallow=*/true);
1322 auto BeHardNan = MultilibBuilder("/mips-r2-hard-nan2008")
1323 .flag("-EB")
1324 .flag("-msoft-float", /*Disallow=*/true)
1325 .flag("-mnan=2008")
1326 .flag("-muclibc", /*Disallow=*/true);
1327 auto ElHardNan = MultilibBuilder("/mipsel-r2-hard-nan2008")
1328 .flag("-EL")
1329 .flag("-msoft-float", /*Disallow=*/true)
1330 .flag("-mnan=2008")
1331 .flag("-muclibc", /*Disallow=*/true)
1332 .flag("-mmicromips", /*Disallow=*/true);
1333 auto BeHardNanUclibc = MultilibBuilder("/mips-r2-hard-nan2008-uclibc")
1334 .flag("-EB")
1335 .flag("-msoft-float", /*Disallow=*/true)
1336 .flag("-mnan=2008")
1337 .flag("-muclibc");
1338 auto ElHardNanUclibc = MultilibBuilder("/mipsel-r2-hard-nan2008-uclibc")
1339 .flag("-EL")
1340 .flag("-msoft-float", /*Disallow=*/true)
1341 .flag("-mnan=2008")
1342 .flag("-muclibc");
1343 auto BeHardUclibc = MultilibBuilder("/mips-r2-hard-uclibc")
1344 .flag("-EB")
1345 .flag("-msoft-float", /*Disallow=*/true)
1346 .flag("-mnan=2008", /*Disallow=*/true)
1347 .flag("-muclibc");
1348 auto ElHardUclibc = MultilibBuilder("/mipsel-r2-hard-uclibc")
1349 .flag("-EL")
1350 .flag("-msoft-float", /*Disallow=*/true)
1351 .flag("-mnan=2008", /*Disallow=*/true)
1352 .flag("-muclibc");
1353 auto ElMicroHardNan = MultilibBuilder("/micromipsel-r2-hard-nan2008")
1354 .flag("-EL")
1355 .flag("-msoft-float", /*Disallow=*/true)
1356 .flag("-mnan=2008")
1357 .flag("-mmicromips");
1358 auto ElMicroSoft = MultilibBuilder("/micromipsel-r2-soft")
1359 .flag("-EL")
1360 .flag("-msoft-float")
1361 .flag("-mnan=2008", /*Disallow=*/true)
1362 .flag("-mmicromips");
1364 auto O32 = MultilibBuilder("/lib")
1365 .osSuffix("")
1366 .flag("-mabi=n32", /*Disallow=*/true)
1367 .flag("-mabi=n64", /*Disallow=*/true);
1368 auto N32 = MultilibBuilder("/lib32")
1369 .osSuffix("")
1370 .flag("-mabi=n32")
1371 .flag("-mabi=n64", /*Disallow=*/true);
1372 auto N64 = MultilibBuilder("/lib64")
1373 .osSuffix("")
1374 .flag("-mabi=n32", /*Disallow=*/true)
1375 .flag("-mabi=n64");
1377 MtiMipsMultilibsV2 =
1378 MultilibSetBuilder()
1379 .Either({BeHard, BeSoft, ElHard, ElSoft, BeHardNan, ElHardNan,
1380 BeHardNanUclibc, ElHardNanUclibc, BeHardUclibc,
1381 ElHardUclibc, ElMicroHardNan, ElMicroSoft})
1382 .Either(O32, N32, N64)
1383 .makeMultilibSet()
1384 .FilterOut(NonExistent)
1385 .setIncludeDirsCallback([](const Multilib &M) {
1386 return std::vector<std::string>({"/../../../../sysroot" +
1387 M.includeSuffix() +
1388 "/../usr/include"});
1390 .setFilePathsCallback([](const Multilib &M) {
1391 return std::vector<std::string>(
1392 {"/../../../../mips-mti-linux-gnu/lib" + M.gccSuffix()});
1395 for (auto *Candidate : {&MtiMipsMultilibsV1, &MtiMipsMultilibsV2}) {
1396 if (Candidate->select(Flags, Result.SelectedMultilibs)) {
1397 Result.Multilibs = *Candidate;
1398 return true;
1401 return false;
1404 static bool findMipsImgMultilibs(const Multilib::flags_list &Flags,
1405 FilterNonExistent &NonExistent,
1406 DetectedMultilibs &Result) {
1407 // CodeScape IMG toolchain v1.2 and early.
1408 MultilibSet ImgMultilibsV1;
1410 auto Mips64r6 = MultilibBuilder("/mips64r6")
1411 .flag("-m64")
1412 .flag("-m32", /*Disallow=*/true);
1414 auto LittleEndian =
1415 MultilibBuilder("/el").flag("-EL").flag("-EB", /*Disallow=*/true);
1417 auto MAbi64 = MultilibBuilder("/64")
1418 .flag("-mabi=n64")
1419 .flag("-mabi=n32", /*Disallow=*/true)
1420 .flag("-m32", /*Disallow=*/true);
1422 ImgMultilibsV1 =
1423 MultilibSetBuilder()
1424 .Maybe(Mips64r6)
1425 .Maybe(MAbi64)
1426 .Maybe(LittleEndian)
1427 .makeMultilibSet()
1428 .FilterOut(NonExistent)
1429 .setIncludeDirsCallback([](const Multilib &M) {
1430 return std::vector<std::string>(
1431 {"/include", "/../../../../sysroot/usr/include"});
1435 // CodeScape IMG toolchain starting from v1.3.
1436 MultilibSet ImgMultilibsV2;
1438 auto BeHard = MultilibBuilder("/mips-r6-hard")
1439 .flag("-EB")
1440 .flag("-msoft-float", /*Disallow=*/true)
1441 .flag("-mmicromips", /*Disallow=*/true);
1442 auto BeSoft = MultilibBuilder("/mips-r6-soft")
1443 .flag("-EB")
1444 .flag("-msoft-float")
1445 .flag("-mmicromips", /*Disallow=*/true);
1446 auto ElHard = MultilibBuilder("/mipsel-r6-hard")
1447 .flag("-EL")
1448 .flag("-msoft-float", /*Disallow=*/true)
1449 .flag("-mmicromips", /*Disallow=*/true);
1450 auto ElSoft = MultilibBuilder("/mipsel-r6-soft")
1451 .flag("-EL")
1452 .flag("-msoft-float")
1453 .flag("-mmicromips", /*Disallow=*/true);
1454 auto BeMicroHard = MultilibBuilder("/micromips-r6-hard")
1455 .flag("-EB")
1456 .flag("-msoft-float", /*Disallow=*/true)
1457 .flag("-mmicromips");
1458 auto BeMicroSoft = MultilibBuilder("/micromips-r6-soft")
1459 .flag("-EB")
1460 .flag("-msoft-float")
1461 .flag("-mmicromips");
1462 auto ElMicroHard = MultilibBuilder("/micromipsel-r6-hard")
1463 .flag("-EL")
1464 .flag("-msoft-float", /*Disallow=*/true)
1465 .flag("-mmicromips");
1466 auto ElMicroSoft = MultilibBuilder("/micromipsel-r6-soft")
1467 .flag("-EL")
1468 .flag("-msoft-float")
1469 .flag("-mmicromips");
1471 auto O32 = MultilibBuilder("/lib")
1472 .osSuffix("")
1473 .flag("-mabi=n32", /*Disallow=*/true)
1474 .flag("-mabi=n64", /*Disallow=*/true);
1475 auto N32 = MultilibBuilder("/lib32")
1476 .osSuffix("")
1477 .flag("-mabi=n32")
1478 .flag("-mabi=n64", /*Disallow=*/true);
1479 auto N64 = MultilibBuilder("/lib64")
1480 .osSuffix("")
1481 .flag("-mabi=n32", /*Disallow=*/true)
1482 .flag("-mabi=n64");
1484 ImgMultilibsV2 =
1485 MultilibSetBuilder()
1486 .Either({BeHard, BeSoft, ElHard, ElSoft, BeMicroHard, BeMicroSoft,
1487 ElMicroHard, ElMicroSoft})
1488 .Either(O32, N32, N64)
1489 .makeMultilibSet()
1490 .FilterOut(NonExistent)
1491 .setIncludeDirsCallback([](const Multilib &M) {
1492 return std::vector<std::string>({"/../../../../sysroot" +
1493 M.includeSuffix() +
1494 "/../usr/include"});
1496 .setFilePathsCallback([](const Multilib &M) {
1497 return std::vector<std::string>(
1498 {"/../../../../mips-img-linux-gnu/lib" + M.gccSuffix()});
1501 for (auto *Candidate : {&ImgMultilibsV1, &ImgMultilibsV2}) {
1502 if (Candidate->select(Flags, Result.SelectedMultilibs)) {
1503 Result.Multilibs = *Candidate;
1504 return true;
1507 return false;
1510 bool clang::driver::findMIPSMultilibs(const Driver &D,
1511 const llvm::Triple &TargetTriple,
1512 StringRef Path, const ArgList &Args,
1513 DetectedMultilibs &Result) {
1514 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1516 StringRef CPUName;
1517 StringRef ABIName;
1518 tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
1520 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1522 Multilib::flags_list Flags;
1523 addMultilibFlag(TargetTriple.isMIPS32(), "-m32", Flags);
1524 addMultilibFlag(TargetTriple.isMIPS64(), "-m64", Flags);
1525 addMultilibFlag(isMips16(Args), "-mips16", Flags);
1526 addMultilibFlag(CPUName == "mips32", "-march=mips32", Flags);
1527 addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" ||
1528 CPUName == "mips32r5" || CPUName == "p5600",
1529 "-march=mips32r2", Flags);
1530 addMultilibFlag(CPUName == "mips32r6", "-march=mips32r6", Flags);
1531 addMultilibFlag(CPUName == "mips64", "-march=mips64", Flags);
1532 addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" ||
1533 CPUName == "mips64r5" || CPUName == "octeon" ||
1534 CPUName == "octeon+",
1535 "-march=mips64r2", Flags);
1536 addMultilibFlag(CPUName == "mips64r6", "-march=mips64r6", Flags);
1537 addMultilibFlag(isMicroMips(Args), "-mmicromips", Flags);
1538 addMultilibFlag(tools::mips::isUCLibc(Args), "-muclibc", Flags);
1539 addMultilibFlag(tools::mips::isNaN2008(D, Args, TargetTriple), "-mnan=2008",
1540 Flags);
1541 addMultilibFlag(ABIName == "n32", "-mabi=n32", Flags);
1542 addMultilibFlag(ABIName == "n64", "-mabi=n64", Flags);
1543 addMultilibFlag(isSoftFloatABI(Args), "-msoft-float", Flags);
1544 addMultilibFlag(!isSoftFloatABI(Args), "-mhard-float", Flags);
1545 addMultilibFlag(isMipsEL(TargetArch), "-EL", Flags);
1546 addMultilibFlag(!isMipsEL(TargetArch), "-EB", Flags);
1548 if (TargetTriple.isAndroid())
1549 return findMipsAndroidMultilibs(D.getVFS(), Path, Flags, NonExistent,
1550 Result);
1552 if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
1553 TargetTriple.getOS() == llvm::Triple::Linux &&
1554 TargetTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
1555 return findMipsMuslMultilibs(Flags, NonExistent, Result);
1557 if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
1558 TargetTriple.getOS() == llvm::Triple::Linux &&
1559 TargetTriple.isGNUEnvironment())
1560 return findMipsMtiMultilibs(Flags, NonExistent, Result);
1562 if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1563 TargetTriple.getOS() == llvm::Triple::Linux &&
1564 TargetTriple.isGNUEnvironment())
1565 return findMipsImgMultilibs(Flags, NonExistent, Result);
1567 if (findMipsCsMultilibs(Flags, NonExistent, Result))
1568 return true;
1570 // Fallback to the regular toolchain-tree structure.
1571 Multilib Default;
1572 Result.Multilibs.push_back(Default);
1573 Result.Multilibs.FilterOut(NonExistent);
1575 if (Result.Multilibs.select(Flags, Result.SelectedMultilibs)) {
1576 Result.BiarchSibling = Multilib();
1577 return true;
1580 return false;
1583 static void findAndroidArmMultilibs(const Driver &D,
1584 const llvm::Triple &TargetTriple,
1585 StringRef Path, const ArgList &Args,
1586 DetectedMultilibs &Result) {
1587 // Find multilibs with subdirectories like armv7-a, thumb, armv7-a/thumb.
1588 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1589 MultilibBuilder ArmV7Multilib = MultilibBuilder("/armv7-a")
1590 .flag("-march=armv7-a")
1591 .flag("-mthumb", /*Disallow=*/true);
1592 MultilibBuilder ThumbMultilib = MultilibBuilder("/thumb")
1593 .flag("-march=armv7-a", /*Disallow=*/true)
1594 .flag("-mthumb");
1595 MultilibBuilder ArmV7ThumbMultilib =
1596 MultilibBuilder("/armv7-a/thumb").flag("-march=armv7-a").flag("-mthumb");
1597 MultilibBuilder DefaultMultilib =
1598 MultilibBuilder("")
1599 .flag("-march=armv7-a", /*Disallow=*/true)
1600 .flag("-mthumb", /*Disallow=*/true);
1601 MultilibSet AndroidArmMultilibs =
1602 MultilibSetBuilder()
1603 .Either(ThumbMultilib, ArmV7Multilib, ArmV7ThumbMultilib,
1604 DefaultMultilib)
1605 .makeMultilibSet()
1606 .FilterOut(NonExistent);
1608 Multilib::flags_list Flags;
1609 llvm::StringRef Arch = Args.getLastArgValue(options::OPT_march_EQ);
1610 bool IsArmArch = TargetTriple.getArch() == llvm::Triple::arm;
1611 bool IsThumbArch = TargetTriple.getArch() == llvm::Triple::thumb;
1612 bool IsV7SubArch = TargetTriple.getSubArch() == llvm::Triple::ARMSubArch_v7;
1613 bool IsThumbMode = IsThumbArch ||
1614 Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, false) ||
1615 (IsArmArch && llvm::ARM::parseArchISA(Arch) == llvm::ARM::ISAKind::THUMB);
1616 bool IsArmV7Mode = (IsArmArch || IsThumbArch) &&
1617 (llvm::ARM::parseArchVersion(Arch) == 7 ||
1618 (IsArmArch && Arch == "" && IsV7SubArch));
1619 addMultilibFlag(IsArmV7Mode, "-march=armv7-a", Flags);
1620 addMultilibFlag(IsThumbMode, "-mthumb", Flags);
1622 if (AndroidArmMultilibs.select(Flags, Result.SelectedMultilibs))
1623 Result.Multilibs = AndroidArmMultilibs;
1626 static bool findMSP430Multilibs(const Driver &D,
1627 const llvm::Triple &TargetTriple,
1628 StringRef Path, const ArgList &Args,
1629 DetectedMultilibs &Result) {
1630 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1631 MultilibBuilder WithoutExceptions =
1632 MultilibBuilder("/430").flag("-exceptions", /*Disallow=*/true);
1633 MultilibBuilder WithExceptions =
1634 MultilibBuilder("/430/exceptions").flag("-exceptions");
1636 // FIXME: when clang starts to support msp430x ISA additional logic
1637 // to select between multilib must be implemented
1638 // MultilibBuilder MSP430xMultilib = MultilibBuilder("/large");
1640 Result.Multilibs.push_back(WithoutExceptions.makeMultilib());
1641 Result.Multilibs.push_back(WithExceptions.makeMultilib());
1642 Result.Multilibs.FilterOut(NonExistent);
1644 Multilib::flags_list Flags;
1645 addMultilibFlag(Args.hasFlag(options::OPT_fexceptions,
1646 options::OPT_fno_exceptions, false),
1647 "-exceptions", Flags);
1648 if (Result.Multilibs.select(Flags, Result.SelectedMultilibs))
1649 return true;
1651 return false;
1654 static void findCSKYMultilibs(const Driver &D, const llvm::Triple &TargetTriple,
1655 StringRef Path, const ArgList &Args,
1656 DetectedMultilibs &Result) {
1657 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1659 tools::csky::FloatABI TheFloatABI = tools::csky::getCSKYFloatABI(D, Args);
1660 std::optional<llvm::StringRef> Res =
1661 tools::csky::getCSKYArchName(D, Args, TargetTriple);
1663 if (!Res)
1664 return;
1665 auto ARCHName = *Res;
1667 Multilib::flags_list Flags;
1668 addMultilibFlag(TheFloatABI == tools::csky::FloatABI::Hard, "-hard-fp",
1669 Flags);
1670 addMultilibFlag(TheFloatABI == tools::csky::FloatABI::SoftFP, "-soft-fp",
1671 Flags);
1672 addMultilibFlag(TheFloatABI == tools::csky::FloatABI::Soft, "-soft", Flags);
1673 addMultilibFlag(ARCHName == "ck801", "-march=ck801", Flags);
1674 addMultilibFlag(ARCHName == "ck802", "-march=ck802", Flags);
1675 addMultilibFlag(ARCHName == "ck803", "-march=ck803", Flags);
1676 addMultilibFlag(ARCHName == "ck804", "-march=ck804", Flags);
1677 addMultilibFlag(ARCHName == "ck805", "-march=ck805", Flags);
1678 addMultilibFlag(ARCHName == "ck807", "-march=ck807", Flags);
1679 addMultilibFlag(ARCHName == "ck810", "-march=ck810", Flags);
1680 addMultilibFlag(ARCHName == "ck810v", "-march=ck810v", Flags);
1681 addMultilibFlag(ARCHName == "ck860", "-march=ck860", Flags);
1682 addMultilibFlag(ARCHName == "ck860v", "-march=ck860v", Flags);
1684 bool isBigEndian = false;
1685 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
1686 options::OPT_mbig_endian))
1687 isBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
1688 addMultilibFlag(isBigEndian, "-EB", Flags);
1690 auto HardFloat = MultilibBuilder("/hard-fp").flag("-hard-fp");
1691 auto SoftFpFloat = MultilibBuilder("/soft-fp").flag("-soft-fp");
1692 auto SoftFloat = MultilibBuilder("").flag("-soft");
1693 auto Arch801 = MultilibBuilder("/ck801").flag("-march=ck801");
1694 auto Arch802 = MultilibBuilder("/ck802").flag("-march=ck802");
1695 auto Arch803 = MultilibBuilder("/ck803").flag("-march=ck803");
1696 // CK804 use the same library as CK803
1697 auto Arch804 = MultilibBuilder("/ck803").flag("-march=ck804");
1698 auto Arch805 = MultilibBuilder("/ck805").flag("-march=ck805");
1699 auto Arch807 = MultilibBuilder("/ck807").flag("-march=ck807");
1700 auto Arch810 = MultilibBuilder("").flag("-march=ck810");
1701 auto Arch810v = MultilibBuilder("/ck810v").flag("-march=ck810v");
1702 auto Arch860 = MultilibBuilder("/ck860").flag("-march=ck860");
1703 auto Arch860v = MultilibBuilder("/ck860v").flag("-march=ck860v");
1704 auto BigEndian = MultilibBuilder("/big").flag("-EB");
1706 MultilibSet CSKYMultilibs =
1707 MultilibSetBuilder()
1708 .Maybe(BigEndian)
1709 .Either({Arch801, Arch802, Arch803, Arch804, Arch805, Arch807,
1710 Arch810, Arch810v, Arch860, Arch860v})
1711 .Either(HardFloat, SoftFpFloat, SoftFloat)
1712 .makeMultilibSet()
1713 .FilterOut(NonExistent);
1715 if (CSKYMultilibs.select(Flags, Result.SelectedMultilibs))
1716 Result.Multilibs = CSKYMultilibs;
1719 /// Extend the multi-lib re-use selection mechanism for RISC-V.
1720 /// This function will try to re-use multi-lib if they are compatible.
1721 /// Definition of compatible:
1722 /// - ABI must be the same.
1723 /// - multi-lib is a subset of current arch, e.g. multi-lib=march=rv32im
1724 /// is a subset of march=rv32imc.
1725 /// - march that contains atomic extension can't reuse multi-lib that
1726 /// doesn't have atomic, vice versa. e.g. multi-lib=march=rv32im and
1727 /// march=rv32ima are not compatible, because software and hardware
1728 /// atomic operation can't work together correctly.
1729 static bool
1730 selectRISCVMultilib(const MultilibSet &RISCVMultilibSet, StringRef Arch,
1731 const Multilib::flags_list &Flags,
1732 llvm::SmallVectorImpl<Multilib> &SelectedMultilibs) {
1733 // Try to find the perfect matching multi-lib first.
1734 if (RISCVMultilibSet.select(Flags, SelectedMultilibs))
1735 return true;
1737 Multilib::flags_list NewFlags;
1738 std::vector<MultilibBuilder> NewMultilibs;
1740 llvm::Expected<std::unique_ptr<llvm::RISCVISAInfo>> ParseResult =
1741 llvm::RISCVISAInfo::parseArchString(
1742 Arch, /*EnableExperimentalExtension=*/true,
1743 /*ExperimentalExtensionVersionCheck=*/false);
1744 if (!ParseResult) {
1745 // Ignore any error here, we assume it will be handled in another place.
1746 consumeError(ParseResult.takeError());
1747 return false;
1750 auto &ISAInfo = *ParseResult;
1752 addMultilibFlag(ISAInfo->getXLen() == 32, "-m32", NewFlags);
1753 addMultilibFlag(ISAInfo->getXLen() == 64, "-m64", NewFlags);
1755 // Collect all flags except march=*
1756 for (StringRef Flag : Flags) {
1757 if (Flag.starts_with("!march=") || Flag.starts_with("-march="))
1758 continue;
1760 NewFlags.push_back(Flag.str());
1763 llvm::StringSet<> AllArchExts;
1764 // Reconstruct multi-lib list, and break march option into separated
1765 // extension. e.g. march=rv32im -> +i +m
1766 for (const auto &M : RISCVMultilibSet) {
1767 bool Skip = false;
1769 MultilibBuilder NewMultilib =
1770 MultilibBuilder(M.gccSuffix(), M.osSuffix(), M.includeSuffix());
1771 for (StringRef Flag : M.flags()) {
1772 // Add back all flags except -march.
1773 if (!Flag.consume_front("-march=")) {
1774 NewMultilib.flag(Flag);
1775 continue;
1778 // Break down -march into individual extension.
1779 llvm::Expected<std::unique_ptr<llvm::RISCVISAInfo>> MLConfigParseResult =
1780 llvm::RISCVISAInfo::parseArchString(
1781 Flag, /*EnableExperimentalExtension=*/true,
1782 /*ExperimentalExtensionVersionCheck=*/false);
1783 if (!MLConfigParseResult) {
1784 // Ignore any error here, we assume it will handled in another place.
1785 llvm::consumeError(MLConfigParseResult.takeError());
1787 // We might get a parsing error if rv32e in the list, we could just skip
1788 // that and process the rest of multi-lib configs.
1789 Skip = true;
1790 continue;
1792 auto &MLConfigISAInfo = *MLConfigParseResult;
1794 const llvm::RISCVISAInfo::OrderedExtensionMap &MLConfigArchExts =
1795 MLConfigISAInfo->getExtensions();
1796 for (auto MLConfigArchExt : MLConfigArchExts) {
1797 auto ExtName = MLConfigArchExt.first;
1798 NewMultilib.flag(Twine("-", ExtName).str());
1800 if (AllArchExts.insert(ExtName).second) {
1801 addMultilibFlag(ISAInfo->hasExtension(ExtName),
1802 Twine("-", ExtName).str(), NewFlags);
1806 // Check the XLEN explicitly.
1807 if (MLConfigISAInfo->getXLen() == 32) {
1808 NewMultilib.flag("-m32");
1809 NewMultilib.flag("-m64", /*Disallow*/ true);
1810 } else {
1811 NewMultilib.flag("-m32", /*Disallow*/ true);
1812 NewMultilib.flag("-m64");
1815 // Atomic extension must be explicitly checked, soft and hard atomic
1816 // operation never co-work correctly.
1817 if (!MLConfigISAInfo->hasExtension("a"))
1818 NewMultilib.flag("-a", /*Disallow*/ true);
1821 if (Skip)
1822 continue;
1824 NewMultilibs.emplace_back(NewMultilib);
1827 // Build an internal used only multi-lib list, used for checking any
1828 // compatible multi-lib.
1829 MultilibSet NewRISCVMultilibs =
1830 MultilibSetBuilder().Either(NewMultilibs).makeMultilibSet();
1832 if (NewRISCVMultilibs.select(NewFlags, SelectedMultilibs))
1833 for (const Multilib &NewSelectedM : SelectedMultilibs)
1834 for (const auto &M : RISCVMultilibSet)
1835 // Look up the corresponding multi-lib entry in original multi-lib set.
1836 if (M.gccSuffix() == NewSelectedM.gccSuffix())
1837 return true;
1839 return false;
1842 static void findRISCVBareMetalMultilibs(const Driver &D,
1843 const llvm::Triple &TargetTriple,
1844 StringRef Path, const ArgList &Args,
1845 DetectedMultilibs &Result) {
1846 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1847 struct RiscvMultilib {
1848 StringRef march;
1849 StringRef mabi;
1851 // currently only support the set of multilibs like riscv-gnu-toolchain does.
1852 // TODO: support MULTILIB_REUSE
1853 constexpr RiscvMultilib RISCVMultilibSet[] = {
1854 {"rv32i", "ilp32"}, {"rv32im", "ilp32"}, {"rv32iac", "ilp32"},
1855 {"rv32imac", "ilp32"}, {"rv32imafc", "ilp32f"}, {"rv64imac", "lp64"},
1856 {"rv64imafdc", "lp64d"}};
1858 std::vector<MultilibBuilder> Ms;
1859 for (auto Element : RISCVMultilibSet) {
1860 // multilib path rule is ${march}/${mabi}
1861 Ms.emplace_back(
1862 MultilibBuilder(
1863 (Twine(Element.march) + "/" + Twine(Element.mabi)).str())
1864 .flag(Twine("-march=", Element.march).str())
1865 .flag(Twine("-mabi=", Element.mabi).str()));
1867 MultilibSet RISCVMultilibs =
1868 MultilibSetBuilder()
1869 .Either(Ms)
1870 .makeMultilibSet()
1871 .FilterOut(NonExistent)
1872 .setFilePathsCallback([](const Multilib &M) {
1873 return std::vector<std::string>(
1874 {M.gccSuffix(),
1875 "/../../../../riscv64-unknown-elf/lib" + M.gccSuffix(),
1876 "/../../../../riscv32-unknown-elf/lib" + M.gccSuffix()});
1879 Multilib::flags_list Flags;
1880 llvm::StringSet<> Added_ABIs;
1881 StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple);
1882 StringRef MArch = tools::riscv::getRISCVArch(Args, TargetTriple);
1883 for (auto Element : RISCVMultilibSet) {
1884 addMultilibFlag(MArch == Element.march,
1885 Twine("-march=", Element.march).str().c_str(), Flags);
1886 if (!Added_ABIs.count(Element.mabi)) {
1887 Added_ABIs.insert(Element.mabi);
1888 addMultilibFlag(ABIName == Element.mabi,
1889 Twine("-mabi=", Element.mabi).str().c_str(), Flags);
1893 if (selectRISCVMultilib(RISCVMultilibs, MArch, Flags,
1894 Result.SelectedMultilibs))
1895 Result.Multilibs = RISCVMultilibs;
1898 static void findRISCVMultilibs(const Driver &D,
1899 const llvm::Triple &TargetTriple, StringRef Path,
1900 const ArgList &Args, DetectedMultilibs &Result) {
1901 if (TargetTriple.getOS() == llvm::Triple::UnknownOS)
1902 return findRISCVBareMetalMultilibs(D, TargetTriple, Path, Args, Result);
1904 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1905 MultilibBuilder Ilp32 =
1906 MultilibBuilder("lib32/ilp32").flag("-m32").flag("-mabi=ilp32");
1907 MultilibBuilder Ilp32f =
1908 MultilibBuilder("lib32/ilp32f").flag("-m32").flag("-mabi=ilp32f");
1909 MultilibBuilder Ilp32d =
1910 MultilibBuilder("lib32/ilp32d").flag("-m32").flag("-mabi=ilp32d");
1911 MultilibBuilder Lp64 =
1912 MultilibBuilder("lib64/lp64").flag("-m64").flag("-mabi=lp64");
1913 MultilibBuilder Lp64f =
1914 MultilibBuilder("lib64/lp64f").flag("-m64").flag("-mabi=lp64f");
1915 MultilibBuilder Lp64d =
1916 MultilibBuilder("lib64/lp64d").flag("-m64").flag("-mabi=lp64d");
1917 MultilibSet RISCVMultilibs =
1918 MultilibSetBuilder()
1919 .Either({Ilp32, Ilp32f, Ilp32d, Lp64, Lp64f, Lp64d})
1920 .makeMultilibSet()
1921 .FilterOut(NonExistent);
1923 Multilib::flags_list Flags;
1924 bool IsRV64 = TargetTriple.getArch() == llvm::Triple::riscv64;
1925 StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple);
1927 addMultilibFlag(!IsRV64, "-m32", Flags);
1928 addMultilibFlag(IsRV64, "-m64", Flags);
1929 addMultilibFlag(ABIName == "ilp32", "-mabi=ilp32", Flags);
1930 addMultilibFlag(ABIName == "ilp32f", "-mabi=ilp32f", Flags);
1931 addMultilibFlag(ABIName == "ilp32d", "-mabi=ilp32d", Flags);
1932 addMultilibFlag(ABIName == "lp64", "-mabi=lp64", Flags);
1933 addMultilibFlag(ABIName == "lp64f", "-mabi=lp64f", Flags);
1934 addMultilibFlag(ABIName == "lp64d", "-mabi=lp64d", Flags);
1936 if (RISCVMultilibs.select(Flags, Result.SelectedMultilibs))
1937 Result.Multilibs = RISCVMultilibs;
1940 static bool findBiarchMultilibs(const Driver &D,
1941 const llvm::Triple &TargetTriple,
1942 StringRef Path, const ArgList &Args,
1943 bool NeedsBiarchSuffix,
1944 DetectedMultilibs &Result) {
1945 MultilibBuilder DefaultBuilder;
1947 // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1948 // in what would normally be GCCInstallPath and put the 64-bit
1949 // libs in a subdirectory named 64. The simple logic we follow is that
1950 // *if* there is a subdirectory of the right name with crtbegin.o in it,
1951 // we use that. If not, and if not a biarch triple alias, we look for
1952 // crtbegin.o without the subdirectory.
1954 StringRef Suff64 = "/64";
1955 // Solaris uses platform-specific suffixes instead of /64.
1956 if (TargetTriple.isOSSolaris()) {
1957 switch (TargetTriple.getArch()) {
1958 case llvm::Triple::x86:
1959 case llvm::Triple::x86_64:
1960 Suff64 = "/amd64";
1961 break;
1962 case llvm::Triple::sparc:
1963 case llvm::Triple::sparcv9:
1964 Suff64 = "/sparcv9";
1965 break;
1966 default:
1967 break;
1971 Multilib Alt64 = MultilibBuilder()
1972 .gccSuffix(Suff64)
1973 .includeSuffix(Suff64)
1974 .flag("-m32", /*Disallow=*/true)
1975 .flag("-m64")
1976 .flag("-mx32", /*Disallow=*/true)
1977 .makeMultilib();
1978 Multilib Alt32 = MultilibBuilder()
1979 .gccSuffix("/32")
1980 .includeSuffix("/32")
1981 .flag("-m32")
1982 .flag("-m64", /*Disallow=*/true)
1983 .flag("-mx32", /*Disallow=*/true)
1984 .makeMultilib();
1985 Multilib Altx32 = MultilibBuilder()
1986 .gccSuffix("/x32")
1987 .includeSuffix("/x32")
1988 .flag("-m32", /*Disallow=*/true)
1989 .flag("-m64", /*Disallow=*/true)
1990 .flag("-mx32")
1991 .makeMultilib();
1992 Multilib Alt32sparc = MultilibBuilder()
1993 .gccSuffix("/sparcv8plus")
1994 .includeSuffix("/sparcv8plus")
1995 .flag("-m32")
1996 .flag("-m64", /*Disallow=*/true)
1997 .makeMultilib();
1999 // GCC toolchain for IAMCU doesn't have crtbegin.o, so look for libgcc.a.
2000 FilterNonExistent NonExistent(
2001 Path, TargetTriple.isOSIAMCU() ? "/libgcc.a" : "/crtbegin.o", D.getVFS());
2003 // Determine default multilib from: 32, 64, x32
2004 // Also handle cases such as 64 on 32, 32 on 64, etc.
2005 enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
2006 const bool IsX32 = TargetTriple.isX32();
2007 if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
2008 Want = WANT64;
2009 if (TargetTriple.isArch32Bit() && !NonExistent(Alt32sparc))
2010 Want = WANT64;
2011 else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
2012 Want = WANT64;
2013 else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
2014 Want = WANT32;
2015 else if (TargetTriple.isArch64Bit() && !NonExistent(Alt32sparc))
2016 Want = WANT64;
2017 else {
2018 if (TargetTriple.isArch32Bit())
2019 Want = NeedsBiarchSuffix ? WANT64 : WANT32;
2020 else if (IsX32)
2021 Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
2022 else
2023 Want = NeedsBiarchSuffix ? WANT32 : WANT64;
2026 if (Want == WANT32)
2027 DefaultBuilder.flag("-m32")
2028 .flag("-m64", /*Disallow=*/true)
2029 .flag("-mx32", /*Disallow=*/true);
2030 else if (Want == WANT64)
2031 DefaultBuilder.flag("-m32", /*Disallow=*/true)
2032 .flag("-m64")
2033 .flag("-mx32", /*Disallow=*/true);
2034 else if (Want == WANTX32)
2035 DefaultBuilder.flag("-m32", /*Disallow=*/true)
2036 .flag("-m64", /*Disallow=*/true)
2037 .flag("-mx32");
2038 else
2039 return false;
2041 Multilib Default = DefaultBuilder.makeMultilib();
2043 Result.Multilibs.push_back(Default);
2044 Result.Multilibs.push_back(Alt64);
2045 Result.Multilibs.push_back(Alt32);
2046 Result.Multilibs.push_back(Altx32);
2047 Result.Multilibs.push_back(Alt32sparc);
2049 Result.Multilibs.FilterOut(NonExistent);
2051 Multilib::flags_list Flags;
2052 addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "-m64", Flags);
2053 addMultilibFlag(TargetTriple.isArch32Bit(), "-m32", Flags);
2054 addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "-mx32", Flags);
2056 if (!Result.Multilibs.select(Flags, Result.SelectedMultilibs))
2057 return false;
2059 if (Result.SelectedMultilibs.back() == Alt64 ||
2060 Result.SelectedMultilibs.back() == Alt32 ||
2061 Result.SelectedMultilibs.back() == Altx32 ||
2062 Result.SelectedMultilibs.back() == Alt32sparc)
2063 Result.BiarchSibling = Default;
2065 return true;
2068 /// Generic_GCC - A tool chain using the 'gcc' command to perform
2069 /// all subcommands; this relies on gcc translating the majority of
2070 /// command line options.
2072 /// Less-than for GCCVersion, implementing a Strict Weak Ordering.
2073 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
2074 int RHSPatch,
2075 StringRef RHSPatchSuffix) const {
2076 if (Major != RHSMajor)
2077 return Major < RHSMajor;
2078 if (Minor != RHSMinor) {
2079 // Note that versions without a specified minor sort higher than those with
2080 // a minor.
2081 if (RHSMinor == -1)
2082 return true;
2083 if (Minor == -1)
2084 return false;
2085 return Minor < RHSMinor;
2087 if (Patch != RHSPatch) {
2088 // Note that versions without a specified patch sort higher than those with
2089 // a patch.
2090 if (RHSPatch == -1)
2091 return true;
2092 if (Patch == -1)
2093 return false;
2095 // Otherwise just sort on the patch itself.
2096 return Patch < RHSPatch;
2098 if (PatchSuffix != RHSPatchSuffix) {
2099 // Sort empty suffixes higher.
2100 if (RHSPatchSuffix.empty())
2101 return true;
2102 if (PatchSuffix.empty())
2103 return false;
2105 // Provide a lexicographic sort to make this a total ordering.
2106 return PatchSuffix < RHSPatchSuffix;
2109 // The versions are equal.
2110 return false;
2113 /// Parse a GCCVersion object out of a string of text.
2115 /// This is the primary means of forming GCCVersion objects.
2116 /*static*/
2117 Generic_GCC::GCCVersion Generic_GCC::GCCVersion::Parse(StringRef VersionText) {
2118 const GCCVersion BadVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
2119 std::pair<StringRef, StringRef> First = VersionText.split('.');
2120 std::pair<StringRef, StringRef> Second = First.second.split('.');
2122 StringRef MajorStr = First.first;
2123 StringRef MinorStr = Second.first;
2124 StringRef PatchStr = Second.second;
2126 GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
2128 // Parse version number strings such as:
2129 // 5
2130 // 4.4
2131 // 4.4-patched
2132 // 4.4.0
2133 // 4.4.x
2134 // 4.4.2-rc4
2135 // 4.4.x-patched
2136 // 10-win32
2137 // Split on '.', handle 1, 2 or 3 such segments. Each segment must contain
2138 // purely a number, except for the last one, where a non-number suffix
2139 // is stored in PatchSuffix. The third segment is allowed to not contain
2140 // a number at all.
2142 auto TryParseLastNumber = [&](StringRef Segment, int &Number,
2143 std::string &OutStr) -> bool {
2144 // Look for a number prefix and parse that, and split out any trailing
2145 // string into GoodVersion.PatchSuffix.
2147 if (size_t EndNumber = Segment.find_first_not_of("0123456789")) {
2148 StringRef NumberStr = Segment.slice(0, EndNumber);
2149 if (NumberStr.getAsInteger(10, Number) || Number < 0)
2150 return false;
2151 OutStr = NumberStr;
2152 GoodVersion.PatchSuffix = Segment.substr(EndNumber);
2153 return true;
2155 return false;
2157 auto TryParseNumber = [](StringRef Segment, int &Number) -> bool {
2158 if (Segment.getAsInteger(10, Number) || Number < 0)
2159 return false;
2160 return true;
2163 if (MinorStr.empty()) {
2164 // If no minor string, major is the last segment
2165 if (!TryParseLastNumber(MajorStr, GoodVersion.Major, GoodVersion.MajorStr))
2166 return BadVersion;
2167 return GoodVersion;
2170 if (!TryParseNumber(MajorStr, GoodVersion.Major))
2171 return BadVersion;
2172 GoodVersion.MajorStr = MajorStr;
2174 if (PatchStr.empty()) {
2175 // If no patch string, minor is the last segment
2176 if (!TryParseLastNumber(MinorStr, GoodVersion.Minor, GoodVersion.MinorStr))
2177 return BadVersion;
2178 return GoodVersion;
2181 if (!TryParseNumber(MinorStr, GoodVersion.Minor))
2182 return BadVersion;
2183 GoodVersion.MinorStr = MinorStr;
2185 // For the last segment, tolerate a missing number.
2186 std::string DummyStr;
2187 TryParseLastNumber(PatchStr, GoodVersion.Patch, DummyStr);
2188 return GoodVersion;
2191 static llvm::StringRef getGCCToolchainDir(const ArgList &Args,
2192 llvm::StringRef SysRoot) {
2193 const Arg *A = Args.getLastArg(clang::driver::options::OPT_gcc_toolchain);
2194 if (A)
2195 return A->getValue();
2197 // If we have a SysRoot, ignore GCC_INSTALL_PREFIX.
2198 // GCC_INSTALL_PREFIX specifies the gcc installation for the default
2199 // sysroot and is likely not valid with a different sysroot.
2200 if (!SysRoot.empty())
2201 return "";
2203 return GCC_INSTALL_PREFIX;
2206 /// Initialize a GCCInstallationDetector from the driver.
2208 /// This performs all of the autodetection and sets up the various paths.
2209 /// Once constructed, a GCCInstallationDetector is essentially immutable.
2211 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
2212 /// should instead pull the target out of the driver. This is currently
2213 /// necessary because the driver doesn't store the final version of the target
2214 /// triple.
2215 void Generic_GCC::GCCInstallationDetector::init(
2216 const llvm::Triple &TargetTriple, const ArgList &Args) {
2217 llvm::Triple BiarchVariantTriple = TargetTriple.isArch32Bit()
2218 ? TargetTriple.get64BitArchVariant()
2219 : TargetTriple.get32BitArchVariant();
2220 // The library directories which may contain GCC installations.
2221 SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
2222 // The compatible GCC triples for this particular architecture.
2223 SmallVector<StringRef, 16> CandidateTripleAliases;
2224 SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
2225 // Add some triples that we want to check first.
2226 CandidateTripleAliases.push_back(TargetTriple.str());
2227 std::string TripleNoVendor = TargetTriple.getArchName().str() + "-" +
2228 TargetTriple.getOSAndEnvironmentName().str();
2229 if (TargetTriple.getVendor() == llvm::Triple::UnknownVendor)
2230 CandidateTripleAliases.push_back(TripleNoVendor);
2232 CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
2233 CandidateTripleAliases, CandidateBiarchLibDirs,
2234 CandidateBiarchTripleAliases);
2236 // If --gcc-install-dir= is specified, skip filesystem detection.
2237 if (const Arg *A =
2238 Args.getLastArg(clang::driver::options::OPT_gcc_install_dir_EQ);
2239 A && A->getValue()[0]) {
2240 StringRef InstallDir = A->getValue();
2241 if (!ScanGCCForMultilibs(TargetTriple, Args, InstallDir, false)) {
2242 D.Diag(diag::err_drv_invalid_gcc_install_dir) << InstallDir;
2243 } else {
2244 (void)InstallDir.consume_back("/");
2245 StringRef VersionText = llvm::sys::path::filename(InstallDir);
2246 StringRef TripleText =
2247 llvm::sys::path::filename(llvm::sys::path::parent_path(InstallDir));
2249 Version = GCCVersion::Parse(VersionText);
2250 GCCTriple.setTriple(TripleText);
2251 GCCInstallPath = std::string(InstallDir);
2252 GCCParentLibPath = GCCInstallPath + "/../../..";
2253 IsValid = true;
2255 return;
2258 // Compute the set of prefixes for our search.
2259 SmallVector<std::string, 8> Prefixes;
2260 StringRef GCCToolchainDir = getGCCToolchainDir(Args, D.SysRoot);
2261 if (GCCToolchainDir != "") {
2262 if (GCCToolchainDir.back() == '/')
2263 GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
2265 Prefixes.push_back(std::string(GCCToolchainDir));
2266 } else {
2267 // If we have a SysRoot, try that first.
2268 if (!D.SysRoot.empty()) {
2269 Prefixes.push_back(D.SysRoot);
2270 AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
2273 // Then look for gcc installed alongside clang.
2274 Prefixes.push_back(D.InstalledDir + "/..");
2276 // Next, look for prefix(es) that correspond to distribution-supplied gcc
2277 // installations.
2278 if (D.SysRoot.empty()) {
2279 // Typically /usr.
2280 AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
2283 // Try to respect gcc-config on Gentoo if --gcc-toolchain is not provided.
2284 // This avoids accidentally enforcing the system GCC version when using a
2285 // custom toolchain.
2286 SmallVector<StringRef, 16> GentooTestTriples;
2287 // Try to match an exact triple as target triple first.
2288 // e.g. crossdev -S x86_64-gentoo-linux-gnu will install gcc libs for
2289 // x86_64-gentoo-linux-gnu. But "clang -target x86_64-gentoo-linux-gnu"
2290 // may pick the libraries for x86_64-pc-linux-gnu even when exact matching
2291 // triple x86_64-gentoo-linux-gnu is present.
2292 GentooTestTriples.push_back(TargetTriple.str());
2293 GentooTestTriples.append(CandidateTripleAliases.begin(),
2294 CandidateTripleAliases.end());
2295 if (ScanGentooConfigs(TargetTriple, Args, GentooTestTriples,
2296 CandidateBiarchTripleAliases))
2297 return;
2300 // Loop over the various components which exist and select the best GCC
2301 // installation available. GCC installs are ranked by version number.
2302 const GCCVersion VersionZero = GCCVersion::Parse("0.0.0");
2303 Version = VersionZero;
2304 for (const std::string &Prefix : Prefixes) {
2305 auto &VFS = D.getVFS();
2306 if (!VFS.exists(Prefix))
2307 continue;
2308 for (StringRef Suffix : CandidateLibDirs) {
2309 const std::string LibDir = concat(Prefix, Suffix);
2310 if (!VFS.exists(LibDir))
2311 continue;
2312 // Maybe filter out <libdir>/gcc and <libdir>/gcc-cross.
2313 bool GCCDirExists = VFS.exists(LibDir + "/gcc");
2314 bool GCCCrossDirExists = VFS.exists(LibDir + "/gcc-cross");
2315 for (StringRef Candidate : CandidateTripleAliases)
2316 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, false,
2317 GCCDirExists, GCCCrossDirExists);
2319 for (StringRef Suffix : CandidateBiarchLibDirs) {
2320 const std::string LibDir = Prefix + Suffix.str();
2321 if (!VFS.exists(LibDir))
2322 continue;
2323 bool GCCDirExists = VFS.exists(LibDir + "/gcc");
2324 bool GCCCrossDirExists = VFS.exists(LibDir + "/gcc-cross");
2325 for (StringRef Candidate : CandidateBiarchTripleAliases)
2326 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, true,
2327 GCCDirExists, GCCCrossDirExists);
2330 // Skip other prefixes once a GCC installation is found.
2331 if (Version > VersionZero)
2332 break;
2336 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
2337 for (const auto &InstallPath : CandidateGCCInstallPaths)
2338 OS << "Found candidate GCC installation: " << InstallPath << "\n";
2340 if (!GCCInstallPath.empty())
2341 OS << "Selected GCC installation: " << GCCInstallPath << "\n";
2343 for (const auto &Multilib : Multilibs)
2344 OS << "Candidate multilib: " << Multilib << "\n";
2346 if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
2347 OS << "Selected multilib: " << SelectedMultilib << "\n";
2350 bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const {
2351 if (BiarchSibling) {
2352 M = *BiarchSibling;
2353 return true;
2355 return false;
2358 void Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes(
2359 const llvm::Triple &TargetTriple, SmallVectorImpl<std::string> &Prefixes,
2360 StringRef SysRoot) {
2362 if (TargetTriple.isOSHaiku()) {
2363 Prefixes.push_back(concat(SysRoot, "/boot/system/develop/tools"));
2364 return;
2367 if (TargetTriple.isOSSolaris()) {
2368 // Solaris is a special case.
2369 // The GCC installation is under
2370 // /usr/gcc/<major>.<minor>/lib/gcc/<triple>/<major>.<minor>.<patch>/
2371 // so we need to find those /usr/gcc/*/lib/gcc libdirs and go with
2372 // /usr/gcc/<version> as a prefix.
2374 SmallVector<std::pair<GCCVersion, std::string>, 8> SolarisPrefixes;
2375 std::string PrefixDir = concat(SysRoot, "/usr/gcc");
2376 std::error_code EC;
2377 for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin(PrefixDir, EC),
2379 !EC && LI != LE; LI = LI.increment(EC)) {
2380 StringRef VersionText = llvm::sys::path::filename(LI->path());
2381 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2383 // Filter out obviously bad entries.
2384 if (CandidateVersion.Major == -1 || CandidateVersion.isOlderThan(4, 1, 1))
2385 continue;
2387 std::string CandidatePrefix = PrefixDir + "/" + VersionText.str();
2388 std::string CandidateLibPath = CandidatePrefix + "/lib/gcc";
2389 if (!D.getVFS().exists(CandidateLibPath))
2390 continue;
2392 SolarisPrefixes.emplace_back(
2393 std::make_pair(CandidateVersion, CandidatePrefix));
2395 // Sort in reverse order so GCCInstallationDetector::init picks the latest.
2396 std::sort(SolarisPrefixes.rbegin(), SolarisPrefixes.rend());
2397 for (auto p : SolarisPrefixes)
2398 Prefixes.emplace_back(p.second);
2399 return;
2402 // For Linux, if --sysroot is not specified, look for RHEL/CentOS devtoolsets
2403 // and gcc-toolsets.
2404 if (SysRoot.empty() && TargetTriple.getOS() == llvm::Triple::Linux &&
2405 D.getVFS().exists("/opt/rh")) {
2406 // TODO: We may want to remove this, since the functionality
2407 // can be achieved using config files.
2408 Prefixes.push_back("/opt/rh/gcc-toolset-12/root/usr");
2409 Prefixes.push_back("/opt/rh/gcc-toolset-11/root/usr");
2410 Prefixes.push_back("/opt/rh/gcc-toolset-10/root/usr");
2411 Prefixes.push_back("/opt/rh/devtoolset-12/root/usr");
2412 Prefixes.push_back("/opt/rh/devtoolset-11/root/usr");
2413 Prefixes.push_back("/opt/rh/devtoolset-10/root/usr");
2414 Prefixes.push_back("/opt/rh/devtoolset-9/root/usr");
2415 Prefixes.push_back("/opt/rh/devtoolset-8/root/usr");
2416 Prefixes.push_back("/opt/rh/devtoolset-7/root/usr");
2417 Prefixes.push_back("/opt/rh/devtoolset-6/root/usr");
2418 Prefixes.push_back("/opt/rh/devtoolset-4/root/usr");
2419 Prefixes.push_back("/opt/rh/devtoolset-3/root/usr");
2420 Prefixes.push_back("/opt/rh/devtoolset-2/root/usr");
2423 // Fall back to /usr which is used by most non-Solaris systems.
2424 Prefixes.push_back(concat(SysRoot, "/usr"));
2427 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
2428 const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
2429 SmallVectorImpl<StringRef> &LibDirs,
2430 SmallVectorImpl<StringRef> &TripleAliases,
2431 SmallVectorImpl<StringRef> &BiarchLibDirs,
2432 SmallVectorImpl<StringRef> &BiarchTripleAliases) {
2433 // Declare a bunch of static data sets that we'll select between below. These
2434 // are specifically designed to always refer to string literals to avoid any
2435 // lifetime or initialization issues.
2437 // The *Triples variables hard code some triples so that, for example,
2438 // --target=aarch64 (incomplete triple) can detect lib/aarch64-linux-gnu.
2439 // They are not needed when the user has correct LLVM_DEFAULT_TARGET_TRIPLE
2440 // and always uses the full --target (e.g. --target=aarch64-linux-gnu). The
2441 // lists should shrink over time. Please don't add more elements to *Triples.
2442 static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
2443 static const char *const AArch64Triples[] = {
2444 "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-redhat-linux",
2445 "aarch64-suse-linux"};
2446 static const char *const AArch64beLibDirs[] = {"/lib"};
2447 static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu",
2448 "aarch64_be-linux-gnu"};
2450 static const char *const ARMLibDirs[] = {"/lib"};
2451 static const char *const ARMTriples[] = {"arm-linux-gnueabi"};
2452 static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf",
2453 "armv7hl-redhat-linux-gnueabi",
2454 "armv6hl-suse-linux-gnueabi",
2455 "armv7hl-suse-linux-gnueabi"};
2456 static const char *const ARMebLibDirs[] = {"/lib"};
2457 static const char *const ARMebTriples[] = {"armeb-linux-gnueabi"};
2458 static const char *const ARMebHFTriples[] = {
2459 "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
2461 static const char *const AVRLibDirs[] = {"/lib"};
2462 static const char *const AVRTriples[] = {"avr"};
2464 static const char *const CSKYLibDirs[] = {"/lib"};
2465 static const char *const CSKYTriples[] = {
2466 "csky-linux-gnuabiv2", "csky-linux-uclibcabiv2", "csky-elf-noneabiv2"};
2468 static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
2469 static const char *const X86_64Triples[] = {
2470 "x86_64-linux-gnu", "x86_64-unknown-linux-gnu",
2471 "x86_64-pc-linux-gnu", "x86_64-redhat-linux6E",
2472 "x86_64-redhat-linux", "x86_64-suse-linux",
2473 "x86_64-manbo-linux-gnu", "x86_64-linux-gnu",
2474 "x86_64-slackware-linux", "x86_64-unknown-linux",
2475 "x86_64-amazon-linux"};
2476 static const char *const X32Triples[] = {"x86_64-linux-gnux32",
2477 "x86_64-pc-linux-gnux32"};
2478 static const char *const X32LibDirs[] = {"/libx32", "/lib"};
2479 static const char *const X86LibDirs[] = {"/lib32", "/lib"};
2480 static const char *const X86Triples[] = {
2481 "i586-linux-gnu", "i686-linux-gnu", "i686-pc-linux-gnu",
2482 "i386-redhat-linux6E", "i686-redhat-linux", "i386-redhat-linux",
2483 "i586-suse-linux", "i686-montavista-linux", "i686-gnu",
2486 static const char *const LoongArch64LibDirs[] = {"/lib64", "/lib"};
2487 static const char *const LoongArch64Triples[] = {
2488 "loongarch64-linux-gnu", "loongarch64-unknown-linux-gnu"};
2490 static const char *const M68kLibDirs[] = {"/lib"};
2491 static const char *const M68kTriples[] = {
2492 "m68k-linux-gnu", "m68k-unknown-linux-gnu", "m68k-suse-linux"};
2494 static const char *const MIPSLibDirs[] = {"/libo32", "/lib"};
2495 static const char *const MIPSTriples[] = {
2496 "mips-linux-gnu", "mips-mti-linux", "mips-mti-linux-gnu",
2497 "mips-img-linux-gnu", "mipsisa32r6-linux-gnu"};
2498 static const char *const MIPSELLibDirs[] = {"/libo32", "/lib"};
2499 static const char *const MIPSELTriples[] = {
2500 "mipsel-linux-gnu", "mips-img-linux-gnu", "mipsisa32r6el-linux-gnu"};
2502 static const char *const MIPS64LibDirs[] = {"/lib64", "/lib"};
2503 static const char *const MIPS64Triples[] = {
2504 "mips64-linux-gnu", "mips-mti-linux-gnu",
2505 "mips-img-linux-gnu", "mips64-linux-gnuabi64",
2506 "mipsisa64r6-linux-gnu", "mipsisa64r6-linux-gnuabi64"};
2507 static const char *const MIPS64ELLibDirs[] = {"/lib64", "/lib"};
2508 static const char *const MIPS64ELTriples[] = {
2509 "mips64el-linux-gnu", "mips-mti-linux-gnu",
2510 "mips-img-linux-gnu", "mips64el-linux-gnuabi64",
2511 "mipsisa64r6el-linux-gnu", "mipsisa64r6el-linux-gnuabi64"};
2513 static const char *const MIPSN32LibDirs[] = {"/lib32"};
2514 static const char *const MIPSN32Triples[] = {"mips64-linux-gnuabin32",
2515 "mipsisa64r6-linux-gnuabin32"};
2516 static const char *const MIPSN32ELLibDirs[] = {"/lib32"};
2517 static const char *const MIPSN32ELTriples[] = {
2518 "mips64el-linux-gnuabin32", "mipsisa64r6el-linux-gnuabin32"};
2520 static const char *const MSP430LibDirs[] = {"/lib"};
2521 static const char *const MSP430Triples[] = {"msp430-elf"};
2523 static const char *const PPCLibDirs[] = {"/lib32", "/lib"};
2524 static const char *const PPCTriples[] = {
2525 "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
2526 // On 32-bit PowerPC systems running SUSE Linux, gcc is configured as a
2527 // 64-bit compiler which defaults to "-m32", hence "powerpc64-suse-linux".
2528 "powerpc64-suse-linux", "powerpc-montavista-linuxspe"};
2529 static const char *const PPCLELibDirs[] = {"/lib32", "/lib"};
2530 static const char *const PPCLETriples[] = {"powerpcle-linux-gnu",
2531 "powerpcle-unknown-linux-gnu",
2532 "powerpcle-linux-musl"};
2534 static const char *const PPC64LibDirs[] = {"/lib64", "/lib"};
2535 static const char *const PPC64Triples[] = {
2536 "powerpc64-linux-gnu", "powerpc64-unknown-linux-gnu",
2537 "powerpc64-suse-linux", "ppc64-redhat-linux"};
2538 static const char *const PPC64LELibDirs[] = {"/lib64", "/lib"};
2539 static const char *const PPC64LETriples[] = {
2540 "powerpc64le-linux-gnu", "powerpc64le-unknown-linux-gnu",
2541 "powerpc64le-none-linux-gnu", "powerpc64le-suse-linux",
2542 "ppc64le-redhat-linux"};
2544 static const char *const RISCV32LibDirs[] = {"/lib32", "/lib"};
2545 static const char *const RISCV32Triples[] = {"riscv32-unknown-linux-gnu",
2546 "riscv32-linux-gnu",
2547 "riscv32-unknown-elf"};
2548 static const char *const RISCV64LibDirs[] = {"/lib64", "/lib"};
2549 static const char *const RISCV64Triples[] = {"riscv64-unknown-linux-gnu",
2550 "riscv64-linux-gnu",
2551 "riscv64-unknown-elf"};
2553 static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"};
2554 static const char *const SPARCv8Triples[] = {"sparc-linux-gnu",
2555 "sparcv8-linux-gnu"};
2556 static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"};
2557 static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu",
2558 "sparcv9-linux-gnu"};
2560 static const char *const SystemZLibDirs[] = {"/lib64", "/lib"};
2561 static const char *const SystemZTriples[] = {
2562 "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
2563 "s390x-suse-linux", "s390x-redhat-linux"};
2566 using std::begin;
2567 using std::end;
2569 if (TargetTriple.isOSSolaris()) {
2570 static const char *const SolarisLibDirs[] = {"/lib"};
2571 static const char *const SolarisSparcV8Triples[] = {
2572 "sparc-sun-solaris2.11"};
2573 static const char *const SolarisSparcV9Triples[] = {
2574 "sparcv9-sun-solaris2.11"};
2575 static const char *const SolarisX86Triples[] = {"i386-pc-solaris2.11"};
2576 static const char *const SolarisX86_64Triples[] = {"x86_64-pc-solaris2.11"};
2577 LibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
2578 BiarchLibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
2579 switch (TargetTriple.getArch()) {
2580 case llvm::Triple::x86:
2581 TripleAliases.append(begin(SolarisX86Triples), end(SolarisX86Triples));
2582 BiarchTripleAliases.append(begin(SolarisX86_64Triples),
2583 end(SolarisX86_64Triples));
2584 break;
2585 case llvm::Triple::x86_64:
2586 TripleAliases.append(begin(SolarisX86_64Triples),
2587 end(SolarisX86_64Triples));
2588 BiarchTripleAliases.append(begin(SolarisX86Triples),
2589 end(SolarisX86Triples));
2590 break;
2591 case llvm::Triple::sparc:
2592 TripleAliases.append(begin(SolarisSparcV8Triples),
2593 end(SolarisSparcV8Triples));
2594 BiarchTripleAliases.append(begin(SolarisSparcV9Triples),
2595 end(SolarisSparcV9Triples));
2596 break;
2597 case llvm::Triple::sparcv9:
2598 TripleAliases.append(begin(SolarisSparcV9Triples),
2599 end(SolarisSparcV9Triples));
2600 BiarchTripleAliases.append(begin(SolarisSparcV8Triples),
2601 end(SolarisSparcV8Triples));
2602 break;
2603 default:
2604 break;
2606 return;
2609 // Android targets should not use GNU/Linux tools or libraries.
2610 if (TargetTriple.isAndroid()) {
2611 static const char *const AArch64AndroidTriples[] = {
2612 "aarch64-linux-android"};
2613 static const char *const ARMAndroidTriples[] = {"arm-linux-androideabi"};
2614 static const char *const X86AndroidTriples[] = {"i686-linux-android"};
2615 static const char *const X86_64AndroidTriples[] = {"x86_64-linux-android"};
2617 switch (TargetTriple.getArch()) {
2618 case llvm::Triple::aarch64:
2619 LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2620 TripleAliases.append(begin(AArch64AndroidTriples),
2621 end(AArch64AndroidTriples));
2622 break;
2623 case llvm::Triple::arm:
2624 case llvm::Triple::thumb:
2625 LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
2626 TripleAliases.append(begin(ARMAndroidTriples), end(ARMAndroidTriples));
2627 break;
2628 case llvm::Triple::x86_64:
2629 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2630 TripleAliases.append(begin(X86_64AndroidTriples),
2631 end(X86_64AndroidTriples));
2632 BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2633 BiarchTripleAliases.append(begin(X86AndroidTriples),
2634 end(X86AndroidTriples));
2635 break;
2636 case llvm::Triple::x86:
2637 LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2638 TripleAliases.append(begin(X86AndroidTriples), end(X86AndroidTriples));
2639 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2640 BiarchTripleAliases.append(begin(X86_64AndroidTriples),
2641 end(X86_64AndroidTriples));
2642 break;
2643 default:
2644 break;
2647 return;
2650 switch (TargetTriple.getArch()) {
2651 case llvm::Triple::aarch64:
2652 LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2653 TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
2654 BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2655 BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
2656 break;
2657 case llvm::Triple::aarch64_be:
2658 LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
2659 TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
2660 BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
2661 BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
2662 break;
2663 case llvm::Triple::arm:
2664 case llvm::Triple::thumb:
2665 LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
2666 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2667 TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
2668 } else {
2669 TripleAliases.append(begin(ARMTriples), end(ARMTriples));
2671 break;
2672 case llvm::Triple::armeb:
2673 case llvm::Triple::thumbeb:
2674 LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
2675 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2676 TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
2677 } else {
2678 TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
2680 break;
2681 case llvm::Triple::avr:
2682 LibDirs.append(begin(AVRLibDirs), end(AVRLibDirs));
2683 TripleAliases.append(begin(AVRTriples), end(AVRTriples));
2684 break;
2685 case llvm::Triple::csky:
2686 LibDirs.append(begin(CSKYLibDirs), end(CSKYLibDirs));
2687 TripleAliases.append(begin(CSKYTriples), end(CSKYTriples));
2688 break;
2689 case llvm::Triple::x86_64:
2690 if (TargetTriple.isX32()) {
2691 LibDirs.append(begin(X32LibDirs), end(X32LibDirs));
2692 TripleAliases.append(begin(X32Triples), end(X32Triples));
2693 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2694 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2695 } else {
2696 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2697 TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2698 BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
2699 BiarchTripleAliases.append(begin(X32Triples), end(X32Triples));
2701 BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2702 BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
2703 break;
2704 case llvm::Triple::x86:
2705 LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2706 // MCU toolchain is 32 bit only and its triple alias is TargetTriple
2707 // itself, which will be appended below.
2708 if (!TargetTriple.isOSIAMCU()) {
2709 TripleAliases.append(begin(X86Triples), end(X86Triples));
2710 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2711 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2712 BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
2713 BiarchTripleAliases.append(begin(X32Triples), end(X32Triples));
2715 break;
2716 // TODO: Handle loongarch32.
2717 case llvm::Triple::loongarch64:
2718 LibDirs.append(begin(LoongArch64LibDirs), end(LoongArch64LibDirs));
2719 TripleAliases.append(begin(LoongArch64Triples), end(LoongArch64Triples));
2720 break;
2721 case llvm::Triple::m68k:
2722 LibDirs.append(begin(M68kLibDirs), end(M68kLibDirs));
2723 TripleAliases.append(begin(M68kTriples), end(M68kTriples));
2724 break;
2725 case llvm::Triple::mips:
2726 LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
2727 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2728 BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
2729 BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
2730 BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs));
2731 BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples));
2732 break;
2733 case llvm::Triple::mipsel:
2734 LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2735 TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
2736 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2737 BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2738 BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
2739 BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs));
2740 BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples));
2741 break;
2742 case llvm::Triple::mips64:
2743 LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
2744 TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
2745 BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
2746 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2747 BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs));
2748 BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples));
2749 break;
2750 case llvm::Triple::mips64el:
2751 LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2752 TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
2753 BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2754 BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
2755 BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs));
2756 BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples));
2757 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2758 break;
2759 case llvm::Triple::msp430:
2760 LibDirs.append(begin(MSP430LibDirs), end(MSP430LibDirs));
2761 TripleAliases.append(begin(MSP430Triples), end(MSP430Triples));
2762 break;
2763 case llvm::Triple::ppc:
2764 LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
2765 TripleAliases.append(begin(PPCTriples), end(PPCTriples));
2766 BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
2767 BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
2768 break;
2769 case llvm::Triple::ppcle:
2770 LibDirs.append(begin(PPCLELibDirs), end(PPCLELibDirs));
2771 TripleAliases.append(begin(PPCLETriples), end(PPCLETriples));
2772 BiarchLibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
2773 BiarchTripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
2774 break;
2775 case llvm::Triple::ppc64:
2776 LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
2777 TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
2778 BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
2779 BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
2780 break;
2781 case llvm::Triple::ppc64le:
2782 LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
2783 TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
2784 BiarchLibDirs.append(begin(PPCLELibDirs), end(PPCLELibDirs));
2785 BiarchTripleAliases.append(begin(PPCLETriples), end(PPCLETriples));
2786 break;
2787 case llvm::Triple::riscv32:
2788 LibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
2789 TripleAliases.append(begin(RISCV32Triples), end(RISCV32Triples));
2790 BiarchLibDirs.append(begin(RISCV64LibDirs), end(RISCV64LibDirs));
2791 BiarchTripleAliases.append(begin(RISCV64Triples), end(RISCV64Triples));
2792 break;
2793 case llvm::Triple::riscv64:
2794 LibDirs.append(begin(RISCV64LibDirs), end(RISCV64LibDirs));
2795 TripleAliases.append(begin(RISCV64Triples), end(RISCV64Triples));
2796 BiarchLibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
2797 BiarchTripleAliases.append(begin(RISCV32Triples), end(RISCV32Triples));
2798 break;
2799 case llvm::Triple::sparc:
2800 case llvm::Triple::sparcel:
2801 LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
2802 TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
2803 BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
2804 BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
2805 break;
2806 case llvm::Triple::sparcv9:
2807 LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
2808 TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
2809 BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
2810 BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
2811 break;
2812 case llvm::Triple::systemz:
2813 LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
2814 TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
2815 break;
2816 default:
2817 // By default, just rely on the standard lib directories and the original
2818 // triple.
2819 break;
2822 // Also include the multiarch variant if it's different.
2823 if (TargetTriple.str() != BiarchTriple.str())
2824 BiarchTripleAliases.push_back(BiarchTriple.str());
2827 bool Generic_GCC::GCCInstallationDetector::ScanGCCForMultilibs(
2828 const llvm::Triple &TargetTriple, const ArgList &Args,
2829 StringRef Path, bool NeedsBiarchSuffix) {
2830 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2831 DetectedMultilibs Detected;
2833 // Android standalone toolchain could have multilibs for ARM and Thumb.
2834 // Debian mips multilibs behave more like the rest of the biarch ones,
2835 // so handle them there
2836 if (isArmOrThumbArch(TargetArch) && TargetTriple.isAndroid()) {
2837 // It should also work without multilibs in a simplified toolchain.
2838 findAndroidArmMultilibs(D, TargetTriple, Path, Args, Detected);
2839 } else if (TargetTriple.isCSKY()) {
2840 findCSKYMultilibs(D, TargetTriple, Path, Args, Detected);
2841 } else if (TargetTriple.isMIPS()) {
2842 if (!findMIPSMultilibs(D, TargetTriple, Path, Args, Detected))
2843 return false;
2844 } else if (TargetTriple.isRISCV()) {
2845 findRISCVMultilibs(D, TargetTriple, Path, Args, Detected);
2846 } else if (isMSP430(TargetArch)) {
2847 findMSP430Multilibs(D, TargetTriple, Path, Args, Detected);
2848 } else if (TargetArch == llvm::Triple::avr) {
2849 // AVR has no multilibs.
2850 } else if (!findBiarchMultilibs(D, TargetTriple, Path, Args,
2851 NeedsBiarchSuffix, Detected)) {
2852 return false;
2855 Multilibs = Detected.Multilibs;
2856 SelectedMultilib = Detected.SelectedMultilibs.empty()
2857 ? Multilib()
2858 : Detected.SelectedMultilibs.back();
2859 BiarchSibling = Detected.BiarchSibling;
2861 return true;
2864 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
2865 const llvm::Triple &TargetTriple, const ArgList &Args,
2866 const std::string &LibDir, StringRef CandidateTriple,
2867 bool NeedsBiarchSuffix, bool GCCDirExists, bool GCCCrossDirExists) {
2868 // Locations relative to the system lib directory where GCC's triple-specific
2869 // directories might reside.
2870 struct GCCLibSuffix {
2871 // Path from system lib directory to GCC triple-specific directory.
2872 std::string LibSuffix;
2873 // Path from GCC triple-specific directory back to system lib directory.
2874 // This is one '..' component per component in LibSuffix.
2875 StringRef ReversePath;
2876 // Whether this library suffix is relevant for the triple.
2877 bool Active;
2878 } Suffixes[] = {
2879 // This is the normal place.
2880 {"gcc/" + CandidateTriple.str(), "../..", GCCDirExists},
2882 // Debian puts cross-compilers in gcc-cross.
2883 {"gcc-cross/" + CandidateTriple.str(), "../..", GCCCrossDirExists},
2885 // The Freescale PPC SDK has the gcc libraries in
2886 // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well. Only do
2887 // this on Freescale triples, though, since some systems put a *lot* of
2888 // files in that location, not just GCC installation data.
2889 {CandidateTriple.str(), "..",
2890 TargetTriple.getVendor() == llvm::Triple::Freescale ||
2891 TargetTriple.getVendor() == llvm::Triple::OpenEmbedded}};
2893 for (auto &Suffix : Suffixes) {
2894 if (!Suffix.Active)
2895 continue;
2897 StringRef LibSuffix = Suffix.LibSuffix;
2898 std::error_code EC;
2899 for (llvm::vfs::directory_iterator
2900 LI = D.getVFS().dir_begin(LibDir + "/" + LibSuffix, EC),
2902 !EC && LI != LE; LI = LI.increment(EC)) {
2903 StringRef VersionText = llvm::sys::path::filename(LI->path());
2904 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2905 if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2906 if (!CandidateGCCInstallPaths.insert(std::string(LI->path())).second)
2907 continue; // Saw this path before; no need to look at it again.
2908 if (CandidateVersion.isOlderThan(4, 1, 1))
2909 continue;
2910 if (CandidateVersion <= Version)
2911 continue;
2913 if (!ScanGCCForMultilibs(TargetTriple, Args, LI->path(),
2914 NeedsBiarchSuffix))
2915 continue;
2917 Version = CandidateVersion;
2918 GCCTriple.setTriple(CandidateTriple);
2919 // FIXME: We hack together the directory name here instead of
2920 // using LI to ensure stable path separators across Windows and
2921 // Linux.
2922 GCCInstallPath = (LibDir + "/" + LibSuffix + "/" + VersionText).str();
2923 GCCParentLibPath = (GCCInstallPath + "/../" + Suffix.ReversePath).str();
2924 IsValid = true;
2929 bool Generic_GCC::GCCInstallationDetector::ScanGentooConfigs(
2930 const llvm::Triple &TargetTriple, const ArgList &Args,
2931 const SmallVectorImpl<StringRef> &CandidateTriples,
2932 const SmallVectorImpl<StringRef> &CandidateBiarchTriples) {
2933 if (!D.getVFS().exists(concat(D.SysRoot, GentooConfigDir)))
2934 return false;
2936 for (StringRef CandidateTriple : CandidateTriples) {
2937 if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple))
2938 return true;
2941 for (StringRef CandidateTriple : CandidateBiarchTriples) {
2942 if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple, true))
2943 return true;
2945 return false;
2948 bool Generic_GCC::GCCInstallationDetector::ScanGentooGccConfig(
2949 const llvm::Triple &TargetTriple, const ArgList &Args,
2950 StringRef CandidateTriple, bool NeedsBiarchSuffix) {
2951 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
2952 D.getVFS().getBufferForFile(concat(D.SysRoot, GentooConfigDir,
2953 "/config-" + CandidateTriple.str()));
2954 if (File) {
2955 SmallVector<StringRef, 2> Lines;
2956 File.get()->getBuffer().split(Lines, "\n");
2957 for (StringRef Line : Lines) {
2958 Line = Line.trim();
2959 // CURRENT=triple-version
2960 if (!Line.consume_front("CURRENT="))
2961 continue;
2962 // Process the config file pointed to by CURRENT.
2963 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ConfigFile =
2964 D.getVFS().getBufferForFile(
2965 concat(D.SysRoot, GentooConfigDir, "/" + Line));
2966 std::pair<StringRef, StringRef> ActiveVersion = Line.rsplit('-');
2967 // List of paths to scan for libraries.
2968 SmallVector<StringRef, 4> GentooScanPaths;
2969 // Scan the Config file to find installed GCC libraries path.
2970 // Typical content of the GCC config file:
2971 // LDPATH="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x:/usr/lib/gcc/
2972 // (continued from previous line) x86_64-pc-linux-gnu/4.9.x/32"
2973 // MANPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/man"
2974 // INFOPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/info"
2975 // STDCXX_INCDIR="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x/include/g++-v4"
2976 // We are looking for the paths listed in LDPATH=... .
2977 if (ConfigFile) {
2978 SmallVector<StringRef, 2> ConfigLines;
2979 ConfigFile.get()->getBuffer().split(ConfigLines, "\n");
2980 for (StringRef ConfLine : ConfigLines) {
2981 ConfLine = ConfLine.trim();
2982 if (ConfLine.consume_front("LDPATH=")) {
2983 // Drop '"' from front and back if present.
2984 ConfLine.consume_back("\"");
2985 ConfLine.consume_front("\"");
2986 // Get all paths sperated by ':'
2987 ConfLine.split(GentooScanPaths, ':', -1, /*AllowEmpty*/ false);
2991 // Test the path based on the version in /etc/env.d/gcc/config-{tuple}.
2992 std::string basePath = "/usr/lib/gcc/" + ActiveVersion.first.str() + "/"
2993 + ActiveVersion.second.str();
2994 GentooScanPaths.push_back(StringRef(basePath));
2996 // Scan all paths for GCC libraries.
2997 for (const auto &GentooScanPath : GentooScanPaths) {
2998 std::string GentooPath = concat(D.SysRoot, GentooScanPath);
2999 if (D.getVFS().exists(GentooPath + "/crtbegin.o")) {
3000 if (!ScanGCCForMultilibs(TargetTriple, Args, GentooPath,
3001 NeedsBiarchSuffix))
3002 continue;
3004 Version = GCCVersion::Parse(ActiveVersion.second);
3005 GCCInstallPath = GentooPath;
3006 GCCParentLibPath = GentooPath + std::string("/../../..");
3007 GCCTriple.setTriple(ActiveVersion.first);
3008 IsValid = true;
3009 return true;
3015 return false;
3018 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple,
3019 const ArgList &Args)
3020 : ToolChain(D, Triple, Args), GCCInstallation(D),
3021 CudaInstallation(D, Triple, Args), RocmInstallation(D, Triple, Args) {
3022 getProgramPaths().push_back(getDriver().getInstalledDir());
3023 if (getDriver().getInstalledDir() != getDriver().Dir)
3024 getProgramPaths().push_back(getDriver().Dir);
3027 Generic_GCC::~Generic_GCC() {}
3029 Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
3030 switch (AC) {
3031 case Action::PreprocessJobClass:
3032 if (!Preprocess)
3033 Preprocess.reset(new clang::driver::tools::gcc::Preprocessor(*this));
3034 return Preprocess.get();
3035 case Action::CompileJobClass:
3036 if (!Compile)
3037 Compile.reset(new tools::gcc::Compiler(*this));
3038 return Compile.get();
3039 default:
3040 return ToolChain::getTool(AC);
3044 Tool *Generic_GCC::buildAssembler() const {
3045 return new tools::gnutools::Assembler(*this);
3048 Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); }
3050 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
3051 // Print the information about how we detected the GCC installation.
3052 GCCInstallation.print(OS);
3053 CudaInstallation->print(OS);
3054 RocmInstallation->print(OS);
3057 ToolChain::UnwindTableLevel
3058 Generic_GCC::getDefaultUnwindTableLevel(const ArgList &Args) const {
3059 switch (getArch()) {
3060 case llvm::Triple::aarch64:
3061 case llvm::Triple::aarch64_be:
3062 case llvm::Triple::ppc:
3063 case llvm::Triple::ppcle:
3064 case llvm::Triple::ppc64:
3065 case llvm::Triple::ppc64le:
3066 case llvm::Triple::riscv32:
3067 case llvm::Triple::riscv64:
3068 case llvm::Triple::x86:
3069 case llvm::Triple::x86_64:
3070 return UnwindTableLevel::Asynchronous;
3071 default:
3072 return UnwindTableLevel::None;
3076 bool Generic_GCC::isPICDefault() const {
3077 switch (getArch()) {
3078 case llvm::Triple::x86_64:
3079 return getTriple().isOSWindows();
3080 case llvm::Triple::mips64:
3081 case llvm::Triple::mips64el:
3082 return true;
3083 default:
3084 return false;
3088 bool Generic_GCC::isPIEDefault(const llvm::opt::ArgList &Args) const {
3089 return false;
3092 bool Generic_GCC::isPICDefaultForced() const {
3093 return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
3096 bool Generic_GCC::IsIntegratedAssemblerDefault() const {
3097 switch (getTriple().getArch()) {
3098 case llvm::Triple::nvptx:
3099 case llvm::Triple::nvptx64:
3100 case llvm::Triple::xcore:
3101 return false;
3102 default:
3103 return true;
3107 void Generic_GCC::PushPPaths(ToolChain::path_list &PPaths) {
3108 // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
3109 // least) put various tools in a triple-prefixed directory off of the parent
3110 // of the GCC installation. We use the GCC triple here to ensure that we end
3111 // up with tools that support the same amount of cross compiling as the
3112 // detected GCC installation. For example, if we find a GCC installation
3113 // targeting x86_64, but it is a bi-arch GCC installation, it can also be
3114 // used to target i386.
3115 if (GCCInstallation.isValid()) {
3116 PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
3117 GCCInstallation.getTriple().str() + "/bin")
3118 .str());
3122 void Generic_GCC::AddMultilibPaths(const Driver &D,
3123 const std::string &SysRoot,
3124 const std::string &OSLibDir,
3125 const std::string &MultiarchTriple,
3126 path_list &Paths) {
3127 // Add the multilib suffixed paths where they are available.
3128 if (GCCInstallation.isValid()) {
3129 assert(!SelectedMultilibs.empty());
3130 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3131 const std::string &LibPath =
3132 std::string(GCCInstallation.getParentLibPath());
3134 // Sourcery CodeBench MIPS toolchain holds some libraries under
3135 // a biarch-like suffix of the GCC installation.
3136 if (const auto &PathsCallback = Multilibs.filePathsCallback())
3137 for (const auto &Path : PathsCallback(SelectedMultilibs.back()))
3138 addPathIfExists(D, GCCInstallation.getInstallPath() + Path, Paths);
3140 // Add lib/gcc/$triple/$version, with an optional /multilib suffix.
3141 addPathIfExists(D,
3142 GCCInstallation.getInstallPath() +
3143 SelectedMultilibs.back().gccSuffix(),
3144 Paths);
3146 // Add lib/gcc/$triple/$libdir
3147 // For GCC built with --enable-version-specific-runtime-libs.
3148 addPathIfExists(D, GCCInstallation.getInstallPath() + "/../" + OSLibDir,
3149 Paths);
3151 // GCC cross compiling toolchains will install target libraries which ship
3152 // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
3153 // any part of the GCC installation in
3154 // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
3155 // debatable, but is the reality today. We need to search this tree even
3156 // when we have a sysroot somewhere else. It is the responsibility of
3157 // whomever is doing the cross build targeting a sysroot using a GCC
3158 // installation that is *not* within the system root to ensure two things:
3160 // 1) Any DSOs that are linked in from this tree or from the install path
3161 // above must be present on the system root and found via an
3162 // appropriate rpath.
3163 // 2) There must not be libraries installed into
3164 // <prefix>/<triple>/<libdir> unless they should be preferred over
3165 // those within the system root.
3167 // Note that this matches the GCC behavior. See the below comment for where
3168 // Clang diverges from GCC's behavior.
3169 addPathIfExists(D,
3170 LibPath + "/../" + GCCTriple.str() + "/lib/../" + OSLibDir +
3171 SelectedMultilibs.back().osSuffix(),
3172 Paths);
3174 // If the GCC installation we found is inside of the sysroot, we want to
3175 // prefer libraries installed in the parent prefix of the GCC installation.
3176 // It is important to *not* use these paths when the GCC installation is
3177 // outside of the system root as that can pick up unintended libraries.
3178 // This usually happens when there is an external cross compiler on the
3179 // host system, and a more minimal sysroot available that is the target of
3180 // the cross. Note that GCC does include some of these directories in some
3181 // configurations but this seems somewhere between questionable and simply
3182 // a bug.
3183 if (StringRef(LibPath).starts_with(SysRoot))
3184 addPathIfExists(D, LibPath + "/../" + OSLibDir, Paths);
3188 void Generic_GCC::AddMultiarchPaths(const Driver &D,
3189 const std::string &SysRoot,
3190 const std::string &OSLibDir,
3191 path_list &Paths) {
3192 if (GCCInstallation.isValid()) {
3193 const std::string &LibPath =
3194 std::string(GCCInstallation.getParentLibPath());
3195 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3196 const Multilib &Multilib = GCCInstallation.getMultilib();
3197 addPathIfExists(
3198 D, LibPath + "/../" + GCCTriple.str() + "/lib" + Multilib.osSuffix(),
3199 Paths);
3203 void Generic_GCC::AddMultilibIncludeArgs(const ArgList &DriverArgs,
3204 ArgStringList &CC1Args) const {
3205 // Add include directories specific to the selected multilib set and multilib.
3206 if (!GCCInstallation.isValid())
3207 return;
3208 // gcc TOOL_INCLUDE_DIR.
3209 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3210 std::string LibPath(GCCInstallation.getParentLibPath());
3211 addSystemInclude(DriverArgs, CC1Args,
3212 Twine(LibPath) + "/../" + GCCTriple.str() + "/include");
3214 const auto &Callback = Multilibs.includeDirsCallback();
3215 if (Callback) {
3216 for (const auto &Path : Callback(GCCInstallation.getMultilib()))
3217 addExternCSystemIncludeIfExists(DriverArgs, CC1Args,
3218 GCCInstallation.getInstallPath() + Path);
3222 void Generic_GCC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3223 ArgStringList &CC1Args) const {
3224 if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdincxx,
3225 options::OPT_nostdlibinc))
3226 return;
3228 switch (GetCXXStdlibType(DriverArgs)) {
3229 case ToolChain::CST_Libcxx:
3230 addLibCxxIncludePaths(DriverArgs, CC1Args);
3231 break;
3233 case ToolChain::CST_Libstdcxx:
3234 addLibStdCxxIncludePaths(DriverArgs, CC1Args);
3235 break;
3239 void
3240 Generic_GCC::addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3241 llvm::opt::ArgStringList &CC1Args) const {
3242 const Driver &D = getDriver();
3243 std::string SysRoot = computeSysRoot();
3244 if (SysRoot.empty())
3245 SysRoot = llvm::sys::path::get_separator();
3247 auto AddIncludePath = [&](StringRef Path, bool TargetDirRequired = false) {
3248 std::string Version = detectLibcxxVersion(Path);
3249 if (Version.empty())
3250 return false;
3252 // First add the per-target include path if it exists.
3253 bool TargetDirExists = false;
3254 std::optional<std::string> TargetIncludeDir = getTargetSubDirPath(Path);
3255 if (TargetIncludeDir) {
3256 SmallString<128> TargetDir(*TargetIncludeDir);
3257 llvm::sys::path::append(TargetDir, "c++", Version);
3258 if (D.getVFS().exists(TargetDir)) {
3259 addSystemInclude(DriverArgs, CC1Args, TargetDir);
3260 TargetDirExists = true;
3263 if (TargetDirRequired && !TargetDirExists)
3264 return false;
3266 // Second add the generic one.
3267 SmallString<128> GenericDir(Path);
3268 llvm::sys::path::append(GenericDir, "c++", Version);
3269 addSystemInclude(DriverArgs, CC1Args, GenericDir);
3270 return true;
3273 // Android only uses the libc++ headers installed alongside the toolchain if
3274 // they contain an Android-specific target include path, otherwise they're
3275 // incompatible with the NDK libraries.
3276 SmallString<128> DriverIncludeDir(getDriver().Dir);
3277 llvm::sys::path::append(DriverIncludeDir, "..", "include");
3278 if (AddIncludePath(DriverIncludeDir,
3279 /*TargetDirRequired=*/getTriple().isAndroid()))
3280 return;
3281 // If this is a development, non-installed, clang, libcxx will
3282 // not be found at ../include/c++ but it likely to be found at
3283 // one of the following two locations:
3284 SmallString<128> UsrLocalIncludeDir(SysRoot);
3285 llvm::sys::path::append(UsrLocalIncludeDir, "usr", "local", "include");
3286 if (AddIncludePath(UsrLocalIncludeDir))
3287 return;
3288 SmallString<128> UsrIncludeDir(SysRoot);
3289 llvm::sys::path::append(UsrIncludeDir, "usr", "include");
3290 if (AddIncludePath(UsrIncludeDir))
3291 return;
3294 bool Generic_GCC::addLibStdCXXIncludePaths(Twine IncludeDir, StringRef Triple,
3295 Twine IncludeSuffix,
3296 const llvm::opt::ArgList &DriverArgs,
3297 llvm::opt::ArgStringList &CC1Args,
3298 bool DetectDebian) const {
3299 if (!getVFS().exists(IncludeDir))
3300 return false;
3302 // Debian native gcc uses g++-multiarch-incdir.diff which uses
3303 // include/x86_64-linux-gnu/c++/10$IncludeSuffix instead of
3304 // include/c++/10/x86_64-linux-gnu$IncludeSuffix.
3305 std::string Dir = IncludeDir.str();
3306 StringRef Include =
3307 llvm::sys::path::parent_path(llvm::sys::path::parent_path(Dir));
3308 std::string Path =
3309 (Include + "/" + Triple + Dir.substr(Include.size()) + IncludeSuffix)
3310 .str();
3311 if (DetectDebian && !getVFS().exists(Path))
3312 return false;
3314 // GPLUSPLUS_INCLUDE_DIR
3315 addSystemInclude(DriverArgs, CC1Args, IncludeDir);
3316 // GPLUSPLUS_TOOL_INCLUDE_DIR. If Triple is not empty, add a target-dependent
3317 // include directory.
3318 if (DetectDebian)
3319 addSystemInclude(DriverArgs, CC1Args, Path);
3320 else if (!Triple.empty())
3321 addSystemInclude(DriverArgs, CC1Args,
3322 IncludeDir + "/" + Triple + IncludeSuffix);
3323 // GPLUSPLUS_BACKWARD_INCLUDE_DIR
3324 addSystemInclude(DriverArgs, CC1Args, IncludeDir + "/backward");
3325 return true;
3328 bool Generic_GCC::addGCCLibStdCxxIncludePaths(
3329 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
3330 StringRef DebianMultiarch) const {
3331 assert(GCCInstallation.isValid());
3333 // By default, look for the C++ headers in an include directory adjacent to
3334 // the lib directory of the GCC installation. Note that this is expect to be
3335 // equivalent to '/usr/include/c++/X.Y' in almost all cases.
3336 StringRef LibDir = GCCInstallation.getParentLibPath();
3337 StringRef InstallDir = GCCInstallation.getInstallPath();
3338 StringRef TripleStr = GCCInstallation.getTriple().str();
3339 const Multilib &Multilib = GCCInstallation.getMultilib();
3340 const GCCVersion &Version = GCCInstallation.getVersion();
3342 // Try /../$triple/include/c++/$version (gcc --print-multiarch is not empty).
3343 if (addLibStdCXXIncludePaths(
3344 LibDir.str() + "/../" + TripleStr + "/include/c++/" + Version.Text,
3345 TripleStr, Multilib.includeSuffix(), DriverArgs, CC1Args))
3346 return true;
3348 // Try /gcc/$triple/$version/include/c++/ (gcc --print-multiarch is not
3349 // empty). Like above but for GCC built with
3350 // --enable-version-specific-runtime-libs.
3351 if (addLibStdCXXIncludePaths(LibDir.str() + "/gcc/" + TripleStr + "/" +
3352 Version.Text + "/include/c++/",
3353 TripleStr, Multilib.includeSuffix(), DriverArgs,
3354 CC1Args))
3355 return true;
3357 // Detect Debian g++-multiarch-incdir.diff.
3358 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include/c++/" + Version.Text,
3359 DebianMultiarch, Multilib.includeSuffix(),
3360 DriverArgs, CC1Args, /*Debian=*/true))
3361 return true;
3363 // Try /../include/c++/$version (gcc --print-multiarch is empty).
3364 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include/c++/" + Version.Text,
3365 TripleStr, Multilib.includeSuffix(), DriverArgs,
3366 CC1Args))
3367 return true;
3369 // Otherwise, fall back on a bunch of options which don't use multiarch
3370 // layouts for simplicity.
3371 const std::string LibStdCXXIncludePathCandidates[] = {
3372 // Gentoo is weird and places its headers inside the GCC install,
3373 // so if the first attempt to find the headers fails, try these patterns.
3374 InstallDir.str() + "/include/g++-v" + Version.Text,
3375 InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
3376 Version.MinorStr,
3377 InstallDir.str() + "/include/g++-v" + Version.MajorStr,
3380 for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
3381 if (addLibStdCXXIncludePaths(IncludePath, TripleStr,
3382 Multilib.includeSuffix(), DriverArgs, CC1Args))
3383 return true;
3385 return false;
3388 void
3389 Generic_GCC::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3390 llvm::opt::ArgStringList &CC1Args) const {
3391 if (GCCInstallation.isValid()) {
3392 addGCCLibStdCxxIncludePaths(DriverArgs, CC1Args,
3393 GCCInstallation.getTriple().str());
3397 llvm::opt::DerivedArgList *
3398 Generic_GCC::TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef,
3399 Action::OffloadKind DeviceOffloadKind) const {
3401 // If this tool chain is used for an OpenMP offloading device we have to make
3402 // sure we always generate a shared library regardless of the commands the
3403 // user passed to the host. This is required because the runtime library
3404 // is required to load the device image dynamically at run time.
3405 if (DeviceOffloadKind == Action::OFK_OpenMP) {
3406 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
3407 const OptTable &Opts = getDriver().getOpts();
3409 // Request the shared library. Given that these options are decided
3410 // implicitly, they do not refer to any base argument.
3411 DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_shared));
3412 DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_fPIC));
3414 // Filter all the arguments we don't care passing to the offloading
3415 // toolchain as they can mess up with the creation of a shared library.
3416 for (auto *A : Args) {
3417 switch ((options::ID)A->getOption().getID()) {
3418 default:
3419 DAL->append(A);
3420 break;
3421 case options::OPT_shared:
3422 case options::OPT_dynamic:
3423 case options::OPT_static:
3424 case options::OPT_fPIC:
3425 case options::OPT_fno_PIC:
3426 case options::OPT_fpic:
3427 case options::OPT_fno_pic:
3428 case options::OPT_fPIE:
3429 case options::OPT_fno_PIE:
3430 case options::OPT_fpie:
3431 case options::OPT_fno_pie:
3432 break;
3435 return DAL;
3437 return nullptr;
3440 void Generic_ELF::anchor() {}
3442 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
3443 ArgStringList &CC1Args,
3444 Action::OffloadKind) const {
3445 if (!DriverArgs.hasFlag(options::OPT_fuse_init_array,
3446 options::OPT_fno_use_init_array, true))
3447 CC1Args.push_back("-fno-use-init-array");