clang 19.0.0git
Gnu.cpp
Go to the documentation of this file.
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//===----------------------------------------------------------------------===//
8
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
22#include "clang/Driver/Driver.h"
26#include "clang/Driver/Tool.h"
28#include "llvm/ADT/StringSet.h"
29#include "llvm/ADT/Twine.h"
30#include "llvm/Option/ArgList.h"
31#include "llvm/Support/CodeGen.h"
32#include "llvm/Support/Path.h"
33#include "llvm/Support/VirtualFileSystem.h"
34#include "llvm/TargetParser/RISCVISAInfo.h"
35#include "llvm/TargetParser/TargetParser.h"
36#include <system_error>
37
38using namespace clang::driver;
39using namespace clang::driver::toolchains;
40using namespace clang;
41using namespace llvm::opt;
42
45
46static 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);
51}
52
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.
56static 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);
66 }
67}
68
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;
76
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();
84
85 A->render(Args, CmdArgs);
86 }
87 }
88
89 RenderExtraToolArgs(JA, CmdArgs);
90
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()));
96 }
97
98 // Try to force gcc to match the tool chain we want, if we recognize
99 // the arch.
100 //
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;
119 }
120
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");
127 }
128
129 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
130
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.
136 //
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)
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)
149
150 if (types::canTypeBeUserSpecified(II.getType())) {
151 CmdArgs.push_back("-x");
152 CmdArgs.push_back(types::getTypeName(II.getType()));
153 }
154
155 if (II.isFilename())
156 CmdArgs.push_back(II.getFilename());
157 else {
158 const Arg &A = II.getInputArg();
159
160 // Reverse translate some rewritten options.
161 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
162 CmdArgs.push_back("-lstdc++");
163 continue;
164 }
165
166 // Don't render as input, we need gcc to do the translations.
167 A.render(Args, CmdArgs);
168 }
169 }
170
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";
179
180 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
181 C.addCommand(std::make_unique<Command>(JA, *this,
183 Exec, CmdArgs, Inputs, Output));
184}
185
187 const JobAction &JA, ArgStringList &CmdArgs) const {
188 CmdArgs.push_back("-E");
189}
190
192 ArgStringList &CmdArgs) const {
193 const Driver &D = getToolChain().getDriver();
194
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());
216 }
217}
218
220 ArgStringList &CmdArgs) const {
221 // The types are (hopefully) good enough.
222}
223
224static 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;
293 }
294}
295
296static 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;
304 }
305 return HasStaticPIE;
306}
307
308static bool getStatic(const ArgList &Args) {
309 return Args.hasArg(options::OPT_static) &&
310 !Args.hasArg(options::OPT_static_pie);
311}
312
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();
318
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);
328
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());
334
335 for (const auto &II : Inputs) {
336 if (II.isFilename()) {
337 CmdArgs.push_back(II.getFilename());
338 }
339 }
340
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;
348 }
349 }
350
351 const char *Exec = Args.MakeArgString(getToolChain().GetStaticLibToolPath());
352 C.addCommand(std::make_unique<Command>(JA, *this,
354 Exec, CmdArgs, Inputs, Output));
355}
356
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();
368
369 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
370
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);
381
382 ArgStringList CmdArgs;
383
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);
391
392 if (!D.SysRoot.empty())
393 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
394
395 if (Args.hasArg(options::OPT_s))
396 CmdArgs.push_back("-s");
397
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");
405 }
406
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");
413 }
414
415 ToolChain.addExtraOpts(CmdArgs);
416
417 CmdArgs.push_back("--eh-frame-hdr");
418
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;
425 }
426
427 if (Triple.isRISCV()) {
428 CmdArgs.push_back("-X");
429 if (Args.hasArg(options::OPT_mno_relax))
430 CmdArgs.push_back("--no-relax");
431 }
432
433 const bool IsShared = Args.hasArg(options::OPT_shared);
434 if (IsShared)
435 CmdArgs.push_back("-shared");
436 bool IsPIE = false;
437 if (IsStaticPIE) {
438 CmdArgs.push_back("-static");
439 CmdArgs.push_back("-pie");
440 CmdArgs.push_back("--no-dynamic-linker");
441 CmdArgs.push_back("-z");
442 CmdArgs.push_back("text");
443 } else if (IsStatic) {
444 CmdArgs.push_back("-static");
445 } else if (!Args.hasArg(options::OPT_r)) {
446 if (Args.hasArg(options::OPT_rdynamic))
447 CmdArgs.push_back("-export-dynamic");
448 if (!IsShared) {
449 IsPIE = Args.hasFlag(options::OPT_pie, options::OPT_no_pie,
450 ToolChain.isPIEDefault(Args));
451 if (IsPIE)
452 CmdArgs.push_back("-pie");
453 CmdArgs.push_back("-dynamic-linker");
454 CmdArgs.push_back(Args.MakeArgString(Twine(D.DyldPrefix) +
455 ToolChain.getDynamicLinker(Args)));
456 }
457 }
458
459 CmdArgs.push_back("-o");
460 CmdArgs.push_back(Output.getFilename());
461
462 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
463 options::OPT_r)) {
464 if (!isAndroid && !IsIAMCU) {
465 const char *crt1 = nullptr;
466 if (!Args.hasArg(options::OPT_shared)) {
467 if (Args.hasArg(options::OPT_pg))
468 crt1 = "gcrt1.o";
469 else if (IsPIE)
470 crt1 = "Scrt1.o";
471 else if (IsStaticPIE)
472 crt1 = "rcrt1.o";
473 else
474 crt1 = "crt1.o";
475 }
476 if (crt1)
477 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
478
479 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
480 }
481
482 if (IsVE) {
483 CmdArgs.push_back("-z");
484 CmdArgs.push_back("max-page-size=0x4000000");
485 }
486
487 if (IsIAMCU)
488 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
489 else if (HasCRTBeginEndFiles) {
490 std::string P;
492 !isAndroid) {
493 std::string crtbegin = ToolChain.getCompilerRT(Args, "crtbegin",
495 if (ToolChain.getVFS().exists(crtbegin))
496 P = crtbegin;
497 }
498 if (P.empty()) {
499 const char *crtbegin;
500 if (Args.hasArg(options::OPT_shared))
501 crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
502 else if (IsStatic)
503 crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
504 else if (IsPIE || IsStaticPIE)
505 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
506 else
507 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
508 P = ToolChain.GetFilePath(crtbegin);
509 }
510 CmdArgs.push_back(Args.MakeArgString(P));
511 }
512
513 // Add crtfastmath.o if available and fast math is enabled.
515
516 if (isAndroid && Args.hasFlag(options::OPT_fandroid_pad_segment,
517 options::OPT_fno_android_pad_segment, false))
518 CmdArgs.push_back(
519 Args.MakeArgString(ToolChain.GetFilePath("crt_pad_segment.o")));
520 }
521
522 Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_u});
523
524 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
525
526 if (D.isUsingLTO()) {
527 assert(!Inputs.empty() && "Must have at least one input.");
528 // Find the first filename InputInfo object.
529 auto Input = llvm::find_if(
530 Inputs, [](const InputInfo &II) -> bool { return II.isFilename(); });
531 if (Input == Inputs.end())
532 // For a very rare case, all of the inputs to the linker are
533 // InputArg. If that happens, just use the first InputInfo.
534 Input = Inputs.begin();
535
536 addLTOOptions(ToolChain, Args, CmdArgs, Output, *Input,
537 D.getLTOMode() == LTOK_Thin);
538 }
539
540 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
541 CmdArgs.push_back("--no-demangle");
542
543 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
544 bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
546 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
547
548 addHIPRuntimeLibArgs(ToolChain, C, Args, CmdArgs);
549
550 // The profile runtime also needs access to system libraries.
551 getToolChain().addProfileRTLibs(Args, CmdArgs);
552
553 if (D.CCCIsCXX() &&
554 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
555 options::OPT_r)) {
556 if (ToolChain.ShouldLinkCXXStdlib(Args)) {
557 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
558 !Args.hasArg(options::OPT_static);
559 if (OnlyLibstdcxxStatic)
560 CmdArgs.push_back("-Bstatic");
561 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
562 if (OnlyLibstdcxxStatic)
563 CmdArgs.push_back("-Bdynamic");
564 }
565 CmdArgs.push_back("-lm");
566 }
567
568 // Silence warnings when linking C code with a C++ '-stdlib' argument.
569 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
570
571 // Additional linker set-up and flags for Fortran. This is required in order
572 // to generate executables. As Fortran runtime depends on the C runtime,
573 // these dependencies need to be listed before the C runtime below (i.e.
574 // AddRunTimeLibs).
575 if (D.IsFlangMode()) {
577 addFortranRuntimeLibs(ToolChain, Args, CmdArgs);
578 CmdArgs.push_back("-lm");
579 }
580
581 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_r)) {
582 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
583 if (IsStatic || IsStaticPIE)
584 CmdArgs.push_back("--start-group");
585
586 if (NeedsSanitizerDeps)
587 linkSanitizerRuntimeDeps(ToolChain, Args, CmdArgs);
588
589 if (NeedsXRayDeps)
590 linkXRayRuntimeDeps(ToolChain, Args, CmdArgs);
591
592 bool WantPthread = Args.hasArg(options::OPT_pthread) ||
593 Args.hasArg(options::OPT_pthreads);
594
595 // Use the static OpenMP runtime with -static-openmp
596 bool StaticOpenMP = Args.hasArg(options::OPT_static_openmp) &&
597 !Args.hasArg(options::OPT_static);
598
599 // FIXME: Only pass GompNeedsRT = true for platforms with libgomp that
600 // require librt. Most modern Linux platforms do, but some may not.
601 if (addOpenMPRuntime(C, CmdArgs, ToolChain, Args, StaticOpenMP,
603 /* GompNeedsRT= */ true))
604 // OpenMP runtimes implies pthreads when using the GNU toolchain.
605 // FIXME: Does this really make sense for all GNU toolchains?
606 WantPthread = true;
607
608 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
609
610 // LLVM support for atomics on 32-bit SPARC V8+ is incomplete, so
611 // forcibly link with libatomic as a workaround.
612 // TODO: Issue #41880 and D118021.
613 if (getToolChain().getTriple().getArch() == llvm::Triple::sparc) {
614 CmdArgs.push_back("--push-state");
615 CmdArgs.push_back("--as-needed");
616 CmdArgs.push_back("-latomic");
617 CmdArgs.push_back("--pop-state");
618 }
619
620 // We don't need libpthread neither for bionic (Android) nor for musl,
621 // (used by OHOS as runtime library).
622 if (WantPthread && !isAndroid && !isOHOSFamily)
623 CmdArgs.push_back("-lpthread");
624
625 if (Args.hasArg(options::OPT_fsplit_stack))
626 CmdArgs.push_back("--wrap=pthread_create");
627
628 if (!Args.hasArg(options::OPT_nolibc))
629 CmdArgs.push_back("-lc");
630
631 // Add IAMCU specific libs, if needed.
632 if (IsIAMCU)
633 CmdArgs.push_back("-lgloss");
634
635 if (IsStatic || IsStaticPIE)
636 CmdArgs.push_back("--end-group");
637 else
638 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
639
640 // Add IAMCU specific libs (outside the group), if needed.
641 if (IsIAMCU) {
642 CmdArgs.push_back("--as-needed");
643 CmdArgs.push_back("-lsoftfp");
644 CmdArgs.push_back("--no-as-needed");
645 }
646 }
647
648 if (!Args.hasArg(options::OPT_nostartfiles) && !IsIAMCU) {
649 if (HasCRTBeginEndFiles) {
650 std::string P;
652 !isAndroid) {
653 std::string crtend = ToolChain.getCompilerRT(Args, "crtend",
655 if (ToolChain.getVFS().exists(crtend))
656 P = crtend;
657 }
658 if (P.empty()) {
659 const char *crtend;
660 if (Args.hasArg(options::OPT_shared))
661 crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
662 else if (IsPIE || IsStaticPIE)
663 crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
664 else
665 crtend = isAndroid ? "crtend_android.o" : "crtend.o";
666 P = ToolChain.GetFilePath(crtend);
667 }
668 CmdArgs.push_back(Args.MakeArgString(P));
669 }
670 if (!isAndroid)
671 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
672 }
673 }
674
675 Args.AddAllArgs(CmdArgs, options::OPT_T);
676
677 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
678 C.addCommand(std::make_unique<Command>(JA, *this,
680 Exec, CmdArgs, Inputs, Output));
681}
682
684 const JobAction &JA,
685 const InputInfo &Output,
686 const InputInfoList &Inputs,
687 const ArgList &Args,
688 const char *LinkingOutput) const {
689 const auto &D = getToolChain().getDriver();
690
691 claimNoWarnArgs(Args);
692
693 ArgStringList CmdArgs;
694
695 llvm::Reloc::Model RelocationModel;
696 unsigned PICLevel;
697 bool IsPIE;
698 const char *DefaultAssembler = "as";
699 // Enforce GNU as on Solaris; the native assembler's input syntax isn't fully
700 // compatible.
701 if (getToolChain().getTriple().isOSSolaris())
702 DefaultAssembler = "gas";
703 std::tie(RelocationModel, PICLevel, IsPIE) =
704 ParsePICArgs(getToolChain(), Args);
705
706 if (const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ)) {
707 if (A->getOption().getID() == options::OPT_gz) {
708 CmdArgs.push_back("--compress-debug-sections");
709 } else {
710 StringRef Value = A->getValue();
711 if (Value == "none" || Value == "zlib" || Value == "zstd") {
712 CmdArgs.push_back(
713 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
714 } else {
715 D.Diag(diag::err_drv_unsupported_option_argument)
716 << A->getSpelling() << Value;
717 }
718 }
719 }
720
721 switch (getToolChain().getArch()) {
722 default:
723 break;
724 // Add --32/--64 to make sure we get the format we want.
725 // This is incomplete
726 case llvm::Triple::x86:
727 CmdArgs.push_back("--32");
728 break;
729 case llvm::Triple::x86_64:
730 if (getToolChain().getTriple().isX32())
731 CmdArgs.push_back("--x32");
732 else
733 CmdArgs.push_back("--64");
734 break;
735 case llvm::Triple::ppc: {
736 CmdArgs.push_back("-a32");
737 CmdArgs.push_back("-mppc");
738 CmdArgs.push_back("-mbig-endian");
739 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
740 getCPUName(D, Args, getToolChain().getTriple())));
741 break;
742 }
743 case llvm::Triple::ppcle: {
744 CmdArgs.push_back("-a32");
745 CmdArgs.push_back("-mppc");
746 CmdArgs.push_back("-mlittle-endian");
747 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
748 getCPUName(D, Args, getToolChain().getTriple())));
749 break;
750 }
751 case llvm::Triple::ppc64: {
752 CmdArgs.push_back("-a64");
753 CmdArgs.push_back("-mppc64");
754 CmdArgs.push_back("-mbig-endian");
755 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
756 getCPUName(D, Args, getToolChain().getTriple())));
757 break;
758 }
759 case llvm::Triple::ppc64le: {
760 CmdArgs.push_back("-a64");
761 CmdArgs.push_back("-mppc64");
762 CmdArgs.push_back("-mlittle-endian");
763 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
764 getCPUName(D, Args, getToolChain().getTriple())));
765 break;
766 }
767 case llvm::Triple::riscv32:
768 case llvm::Triple::riscv64: {
769 StringRef ABIName = riscv::getRISCVABI(Args, getToolChain().getTriple());
770 CmdArgs.push_back("-mabi");
771 CmdArgs.push_back(ABIName.data());
772 std::string MArchName =
773 riscv::getRISCVArch(Args, getToolChain().getTriple());
774 CmdArgs.push_back("-march");
775 CmdArgs.push_back(Args.MakeArgString(MArchName));
776 if (!Args.hasFlag(options::OPT_mrelax, options::OPT_mno_relax, true))
777 Args.addOptOutFlag(CmdArgs, options::OPT_mrelax, options::OPT_mno_relax);
778 break;
779 }
780 case llvm::Triple::sparc:
781 case llvm::Triple::sparcel: {
782 CmdArgs.push_back("-32");
783 std::string CPU = getCPUName(D, Args, getToolChain().getTriple());
784 CmdArgs.push_back(
785 sparc::getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
786 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
787 break;
788 }
789 case llvm::Triple::sparcv9: {
790 CmdArgs.push_back("-64");
791 std::string CPU = getCPUName(D, Args, getToolChain().getTriple());
792 CmdArgs.push_back(
793 sparc::getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
794 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
795 break;
796 }
797 case llvm::Triple::arm:
798 case llvm::Triple::armeb:
799 case llvm::Triple::thumb:
800 case llvm::Triple::thumbeb: {
801 const llvm::Triple &Triple2 = getToolChain().getTriple();
802 CmdArgs.push_back(arm::isARMBigEndian(Triple2, Args) ? "-EB" : "-EL");
803 switch (Triple2.getSubArch()) {
804 case llvm::Triple::ARMSubArch_v7:
805 CmdArgs.push_back("-mfpu=neon");
806 break;
807 case llvm::Triple::ARMSubArch_v8:
808 CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
809 break;
810 default:
811 break;
812 }
813
814 switch (arm::getARMFloatABI(getToolChain(), Args)) {
815 case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
817 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
818 break;
820 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
821 break;
823 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
824 break;
825 }
826
827 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
828 normalizeCPUNamesForAssembler(Args, CmdArgs);
829
830 Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
831 // The integrated assembler doesn't implement e_flags setting behavior for
832 // -meabi=gnu (gcc -mabi={apcs-gnu,atpcs} passes -meabi=gnu to gas). For
833 // compatibility we accept but warn.
834 if (Arg *A = Args.getLastArgNoClaim(options::OPT_mabi_EQ))
835 A->ignoreTargetSpecific();
836 break;
837 }
838 case llvm::Triple::aarch64:
839 case llvm::Triple::aarch64_be: {
840 CmdArgs.push_back(
841 getToolChain().getArch() == llvm::Triple::aarch64_be ? "-EB" : "-EL");
842 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
843 normalizeCPUNamesForAssembler(Args, CmdArgs);
844
845 break;
846 }
847 // TODO: handle loongarch32.
848 case llvm::Triple::loongarch64: {
849 StringRef ABIName =
850 loongarch::getLoongArchABI(D, Args, getToolChain().getTriple());
851 CmdArgs.push_back(Args.MakeArgString("-mabi=" + ABIName));
852 break;
853 }
854 case llvm::Triple::mips:
855 case llvm::Triple::mipsel:
856 case llvm::Triple::mips64:
857 case llvm::Triple::mips64el: {
858 StringRef CPUName;
859 StringRef ABIName;
860 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
861 ABIName = mips::getGnuCompatibleMipsABIName(ABIName);
862
863 CmdArgs.push_back("-march");
864 CmdArgs.push_back(CPUName.data());
865
866 CmdArgs.push_back("-mabi");
867 CmdArgs.push_back(ABIName.data());
868
869 // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
870 // or -mshared (not implemented) is in effect.
871 if (RelocationModel == llvm::Reloc::Static)
872 CmdArgs.push_back("-mno-shared");
873
874 // LLVM doesn't support -mplt yet and acts as if it is always given.
875 // However, -mplt has no effect with the N64 ABI.
876 if (ABIName != "64" && !Args.hasArg(options::OPT_mno_abicalls))
877 CmdArgs.push_back("-call_nonpic");
878
879 if (getToolChain().getTriple().isLittleEndian())
880 CmdArgs.push_back("-EL");
881 else
882 CmdArgs.push_back("-EB");
883
884 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
885 if (StringRef(A->getValue()) == "2008")
886 CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
887 }
888
889 // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
890 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
891 options::OPT_mfp64)) {
892 A->claim();
893 A->render(Args, CmdArgs);
894 } else if (mips::shouldUseFPXX(
895 Args, getToolChain().getTriple(), CPUName, ABIName,
896 mips::getMipsFloatABI(getToolChain().getDriver(), Args,
897 getToolChain().getTriple())))
898 CmdArgs.push_back("-mfpxx");
899
900 // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
901 // -mno-mips16 is actually -no-mips16.
902 if (Arg *A =
903 Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
904 if (A->getOption().matches(options::OPT_mips16)) {
905 A->claim();
906 A->render(Args, CmdArgs);
907 } else {
908 A->claim();
909 CmdArgs.push_back("-no-mips16");
910 }
911 }
912
913 Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
914 options::OPT_mno_micromips);
915 Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
916 Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
917
918 if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
919 // Do not use AddLastArg because not all versions of MIPS assembler
920 // support -mmsa / -mno-msa options.
921 if (A->getOption().matches(options::OPT_mmsa))
922 CmdArgs.push_back(Args.MakeArgString("-mmsa"));
923 }
924
925 Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
926 options::OPT_msoft_float);
927
928 Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
929 options::OPT_msingle_float);
930
931 Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
932 options::OPT_mno_odd_spreg);
933
934 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
935 break;
936 }
937 case llvm::Triple::systemz: {
938 // Always pass an -march option, since our default of z10 is later
939 // than the GNU assembler's default.
940 std::string CPUName = systemz::getSystemZTargetCPU(Args);
941 CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
942 break;
943 }
944 case llvm::Triple::ve:
945 DefaultAssembler = "nas";
946 }
947
948 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
949 options::OPT_fdebug_prefix_map_EQ)) {
950 StringRef Map = A->getValue();
951 if (!Map.contains('='))
952 D.Diag(diag::err_drv_invalid_argument_to_option)
953 << Map << A->getOption().getName();
954 else {
955 CmdArgs.push_back(Args.MakeArgString("--debug-prefix-map"));
956 CmdArgs.push_back(Args.MakeArgString(Map));
957 }
958 A->claim();
959 }
960
961 Args.AddAllArgs(CmdArgs, options::OPT_I);
962 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
963
964 CmdArgs.push_back("-o");
965 CmdArgs.push_back(Output.getFilename());
966
967 for (const auto &II : Inputs)
968 CmdArgs.push_back(II.getFilename());
969
970 if (Arg *A = Args.getLastArg(options::OPT_g_Flag, options::OPT_gN_Group,
971 options::OPT_gdwarf_2, options::OPT_gdwarf_3,
972 options::OPT_gdwarf_4, options::OPT_gdwarf_5,
973 options::OPT_gdwarf))
974 if (!A->getOption().matches(options::OPT_g0)) {
975 Args.AddLastArg(CmdArgs, options::OPT_g_Flag);
976
977 unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
978 CmdArgs.push_back(Args.MakeArgString("-gdwarf-" + Twine(DwarfVersion)));
979 }
980
981 const char *Exec =
982 Args.MakeArgString(getToolChain().GetProgramPath(DefaultAssembler));
983 C.addCommand(std::make_unique<Command>(JA, *this,
985 Exec, CmdArgs, Inputs, Output));
986
987 // Handle the debug info splitting at object creation time if we're
988 // creating an object.
989 // TODO: Currently only works on linux with newer objcopy.
990 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
991 getToolChain().getTriple().isOSLinux())
992 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
993 SplitDebugName(JA, Args, Inputs[0], Output));
994}
995
996namespace {
997// Filter to remove Multilibs that don't exist as a suffix to Path
998class FilterNonExistent {
999 StringRef Base, File;
1000 llvm::vfs::FileSystem &VFS;
1001
1002public:
1003 FilterNonExistent(StringRef Base, StringRef File, llvm::vfs::FileSystem &VFS)
1004 : Base(Base), File(File), VFS(VFS) {}
1005 bool operator()(const Multilib &M) {
1006 return !VFS.exists(Base + M.gccSuffix() + File);
1007 }
1008};
1009} // end anonymous namespace
1010
1011static bool isSoftFloatABI(const ArgList &Args) {
1012 Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1013 options::OPT_mfloat_abi_EQ);
1014 if (!A)
1015 return false;
1016
1017 return A->getOption().matches(options::OPT_msoft_float) ||
1018 (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
1019 A->getValue() == StringRef("soft"));
1020}
1021
1022static bool isArmOrThumbArch(llvm::Triple::ArchType Arch) {
1023 return Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb;
1024}
1025
1026static bool isMipsEL(llvm::Triple::ArchType Arch) {
1027 return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
1028}
1029
1030static bool isMips16(const ArgList &Args) {
1031 Arg *A = Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16);
1032 return A && A->getOption().matches(options::OPT_mips16);
1033}
1034
1035static bool isMicroMips(const ArgList &Args) {
1036 Arg *A = Args.getLastArg(options::OPT_mmicromips, options::OPT_mno_micromips);
1037 return A && A->getOption().matches(options::OPT_mmicromips);
1038}
1039
1040static bool isMSP430(llvm::Triple::ArchType Arch) {
1041 return Arch == llvm::Triple::msp430;
1042}
1043
1045 FilterNonExistent &NonExistent,
1047 // Check for Code Sourcery toolchain multilibs
1048 MultilibSet CSMipsMultilibs;
1049 {
1050 auto MArchMips16 = MultilibBuilder("/mips16").flag("-m32").flag("-mips16");
1051
1052 auto MArchMicroMips =
1053 MultilibBuilder("/micromips").flag("-m32").flag("-mmicromips");
1054
1055 auto MArchDefault = MultilibBuilder("")
1056 .flag("-mips16", /*Disallow=*/true)
1057 .flag("-mmicromips", /*Disallow=*/true);
1058
1059 auto UCLibc = MultilibBuilder("/uclibc").flag("-muclibc");
1060
1061 auto SoftFloat = MultilibBuilder("/soft-float").flag("-msoft-float");
1062
1063 auto Nan2008 = MultilibBuilder("/nan2008").flag("-mnan=2008");
1064
1065 auto DefaultFloat = MultilibBuilder("")
1066 .flag("-msoft-float", /*Disallow=*/true)
1067 .flag("-mnan=2008", /*Disallow=*/true);
1068
1069 auto BigEndian =
1070 MultilibBuilder("").flag("-EB").flag("-EL", /*Disallow=*/true);
1071
1072 auto LittleEndian =
1073 MultilibBuilder("/el").flag("-EL").flag("-EB", /*Disallow=*/true);
1074
1075 // Note that this one's osSuffix is ""
1076 auto MAbi64 = MultilibBuilder("")
1077 .gccSuffix("/64")
1078 .includeSuffix("/64")
1079 .flag("-mabi=n64")
1080 .flag("-mabi=n32", /*Disallow=*/true)
1081 .flag("-m32", /*Disallow=*/true);
1082
1083 CSMipsMultilibs =
1085 .Either(MArchMips16, MArchMicroMips, MArchDefault)
1086 .Maybe(UCLibc)
1087 .Either(SoftFloat, Nan2008, DefaultFloat)
1088 .FilterOut("/micromips/nan2008")
1089 .FilterOut("/mips16/nan2008")
1090 .Either(BigEndian, LittleEndian)
1091 .Maybe(MAbi64)
1092 .FilterOut("/mips16.*/64")
1093 .FilterOut("/micromips.*/64")
1095 .FilterOut(NonExistent)
1096 .setIncludeDirsCallback([](const Multilib &M) {
1097 std::vector<std::string> Dirs({"/include"});
1098 if (StringRef(M.includeSuffix()).starts_with("/uclibc"))
1099 Dirs.push_back(
1100 "/../../../../mips-linux-gnu/libc/uclibc/usr/include");
1101 else
1102 Dirs.push_back("/../../../../mips-linux-gnu/libc/usr/include");
1103 return Dirs;
1104 });
1105 }
1106
1107 MultilibSet DebianMipsMultilibs;
1108 {
1109 MultilibBuilder MAbiN32 =
1110 MultilibBuilder().gccSuffix("/n32").includeSuffix("/n32").flag(
1111 "-mabi=n32");
1112
1114 .gccSuffix("/64")
1115 .includeSuffix("/64")
1116 .flag("-m64")
1117 .flag("-m32", /*Disallow=*/true)
1118 .flag("-mabi=n32", /*Disallow=*/true);
1119
1121 .gccSuffix("/32")
1122 .flag("-m64", /*Disallow=*/true)
1123 .flag("-m32")
1124 .flag("-mabi=n32", /*Disallow=*/true);
1125
1126 DebianMipsMultilibs = MultilibSetBuilder()
1127 .Either(M32, M64, MAbiN32)
1129 .FilterOut(NonExistent);
1130 }
1131
1132 // Sort candidates. Toolchain that best meets the directories tree goes first.
1133 // Then select the first toolchains matches command line flags.
1134 MultilibSet *Candidates[] = {&CSMipsMultilibs, &DebianMipsMultilibs};
1135 if (CSMipsMultilibs.size() < DebianMipsMultilibs.size())
1136 std::iter_swap(Candidates, Candidates + 1);
1137 for (const MultilibSet *Candidate : Candidates) {
1138 if (Candidate->select(Flags, Result.SelectedMultilibs)) {
1139 if (Candidate == &DebianMipsMultilibs)
1140 Result.BiarchSibling = Multilib();
1141 Result.Multilibs = *Candidate;
1142 return true;
1143 }
1144 }
1145 return false;
1146}
1147
1148static bool findMipsAndroidMultilibs(llvm::vfs::FileSystem &VFS, StringRef Path,
1149 const Multilib::flags_list &Flags,
1150 FilterNonExistent &NonExistent,
1152
1153 MultilibSet AndroidMipsMultilibs =
1155 .Maybe(MultilibBuilder("/mips-r2", {}, {}).flag("-march=mips32r2"))
1156 .Maybe(MultilibBuilder("/mips-r6", {}, {}).flag("-march=mips32r6"))
1158 .FilterOut(NonExistent);
1159
1160 MultilibSet AndroidMipselMultilibs =
1162 .Either(MultilibBuilder().flag("-march=mips32"),
1163 MultilibBuilder("/mips-r2", "", "/mips-r2")
1164 .flag("-march=mips32r2"),
1165 MultilibBuilder("/mips-r6", "", "/mips-r6")
1166 .flag("-march=mips32r6"))
1168 .FilterOut(NonExistent);
1169
1170 MultilibSet AndroidMips64elMultilibs =
1172 .Either(MultilibBuilder().flag("-march=mips64r6"),
1173 MultilibBuilder("/32/mips-r1", "", "/mips-r1")
1174 .flag("-march=mips32"),
1175 MultilibBuilder("/32/mips-r2", "", "/mips-r2")
1176 .flag("-march=mips32r2"),
1177 MultilibBuilder("/32/mips-r6", "", "/mips-r6")
1178 .flag("-march=mips32r6"))
1180 .FilterOut(NonExistent);
1181
1182 MultilibSet *MS = &AndroidMipsMultilibs;
1183 if (VFS.exists(Path + "/mips-r6"))
1184 MS = &AndroidMipselMultilibs;
1185 else if (VFS.exists(Path + "/32"))
1186 MS = &AndroidMips64elMultilibs;
1187 if (MS->select(Flags, Result.SelectedMultilibs)) {
1188 Result.Multilibs = *MS;
1189 return true;
1190 }
1191 return false;
1192}
1193
1195 FilterNonExistent &NonExistent,
1197 // Musl toolchain multilibs
1198 MultilibSet MuslMipsMultilibs;
1199 {
1200 auto MArchMipsR2 = MultilibBuilder("")
1201 .osSuffix("/mips-r2-hard-musl")
1202 .flag("-EB")
1203 .flag("-EL", /*Disallow=*/true)
1204 .flag("-march=mips32r2");
1205
1206 auto MArchMipselR2 = MultilibBuilder("/mipsel-r2-hard-musl")
1207 .flag("-EB", /*Disallow=*/true)
1208 .flag("-EL")
1209 .flag("-march=mips32r2");
1210
1211 MuslMipsMultilibs = MultilibSetBuilder()
1212 .Either(MArchMipsR2, MArchMipselR2)
1213 .makeMultilibSet();
1214
1215 // Specify the callback that computes the include directories.
1216 MuslMipsMultilibs.setIncludeDirsCallback([](const Multilib &M) {
1217 return std::vector<std::string>(
1218 {"/../sysroot" + M.osSuffix() + "/usr/include"});
1219 });
1220 }
1221 if (MuslMipsMultilibs.select(Flags, Result.SelectedMultilibs)) {
1222 Result.Multilibs = MuslMipsMultilibs;
1223 return true;
1224 }
1225 return false;
1226}
1227
1229 FilterNonExistent &NonExistent,
1231 // CodeScape MTI toolchain v1.2 and early.
1232 MultilibSet MtiMipsMultilibsV1;
1233 {
1234 auto MArchMips32 = MultilibBuilder("/mips32")
1235 .flag("-m32")
1236 .flag("-m64", /*Disallow=*/true)
1237 .flag("-mmicromips", /*Disallow=*/true)
1238 .flag("-march=mips32");
1239
1240 auto MArchMicroMips = MultilibBuilder("/micromips")
1241 .flag("-m32")
1242 .flag("-m64", /*Disallow=*/true)
1243 .flag("-mmicromips");
1244
1245 auto MArchMips64r2 = MultilibBuilder("/mips64r2")
1246 .flag("-m32", /*Disallow=*/true)
1247 .flag("-m64")
1248 .flag("-march=mips64r2");
1249
1250 auto MArchMips64 = MultilibBuilder("/mips64")
1251 .flag("-m32", /*Disallow=*/true)
1252 .flag("-m64")
1253 .flag("-march=mips64r2", /*Disallow=*/true);
1254
1255 auto MArchDefault = MultilibBuilder("")
1256 .flag("-m32")
1257 .flag("-m64", /*Disallow=*/true)
1258 .flag("-mmicromips", /*Disallow=*/true)
1259 .flag("-march=mips32r2");
1260
1261 auto Mips16 = MultilibBuilder("/mips16").flag("-mips16");
1262
1263 auto UCLibc = MultilibBuilder("/uclibc").flag("-muclibc");
1264
1265 auto MAbi64 = MultilibBuilder("/64")
1266 .flag("-mabi=n64")
1267 .flag("-mabi=n32", /*Disallow=*/true)
1268 .flag("-m32", /*Disallow=*/true);
1269
1270 auto BigEndian =
1271 MultilibBuilder("").flag("-EB").flag("-EL", /*Disallow=*/true);
1272
1273 auto LittleEndian =
1274 MultilibBuilder("/el").flag("-EL").flag("-EB", /*Disallow=*/true);
1275
1276 auto SoftFloat = MultilibBuilder("/sof").flag("-msoft-float");
1277
1278 auto Nan2008 = MultilibBuilder("/nan2008").flag("-mnan=2008");
1279
1280 MtiMipsMultilibsV1 =
1282 .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64,
1283 MArchDefault)
1284 .Maybe(UCLibc)
1285 .Maybe(Mips16)
1286 .FilterOut("/mips64/mips16")
1287 .FilterOut("/mips64r2/mips16")
1288 .FilterOut("/micromips/mips16")
1289 .Maybe(MAbi64)
1290 .FilterOut("/micromips/64")
1291 .FilterOut("/mips32/64")
1292 .FilterOut("^/64")
1293 .FilterOut("/mips16/64")
1294 .Either(BigEndian, LittleEndian)
1295 .Maybe(SoftFloat)
1296 .Maybe(Nan2008)
1297 .FilterOut(".*sof/nan2008")
1299 .FilterOut(NonExistent)
1300 .setIncludeDirsCallback([](const Multilib &M) {
1301 std::vector<std::string> Dirs({"/include"});
1302 if (StringRef(M.includeSuffix()).starts_with("/uclibc"))
1303 Dirs.push_back("/../../../../sysroot/uclibc/usr/include");
1304 else
1305 Dirs.push_back("/../../../../sysroot/usr/include");
1306 return Dirs;
1307 });
1308 }
1309
1310 // CodeScape IMG toolchain starting from v1.3.
1311 MultilibSet MtiMipsMultilibsV2;
1312 {
1313 auto BeHard = MultilibBuilder("/mips-r2-hard")
1314 .flag("-EB")
1315 .flag("-msoft-float", /*Disallow=*/true)
1316 .flag("-mnan=2008", /*Disallow=*/true)
1317 .flag("-muclibc", /*Disallow=*/true);
1318 auto BeSoft = MultilibBuilder("/mips-r2-soft")
1319 .flag("-EB")
1320 .flag("-msoft-float")
1321 .flag("-mnan=2008", /*Disallow=*/true);
1322 auto ElHard = MultilibBuilder("/mipsel-r2-hard")
1323 .flag("-EL")
1324 .flag("-msoft-float", /*Disallow=*/true)
1325 .flag("-mnan=2008", /*Disallow=*/true)
1326 .flag("-muclibc", /*Disallow=*/true);
1327 auto ElSoft = MultilibBuilder("/mipsel-r2-soft")
1328 .flag("-EL")
1329 .flag("-msoft-float")
1330 .flag("-mnan=2008", /*Disallow=*/true)
1331 .flag("-mmicromips", /*Disallow=*/true);
1332 auto BeHardNan = MultilibBuilder("/mips-r2-hard-nan2008")
1333 .flag("-EB")
1334 .flag("-msoft-float", /*Disallow=*/true)
1335 .flag("-mnan=2008")
1336 .flag("-muclibc", /*Disallow=*/true);
1337 auto ElHardNan = MultilibBuilder("/mipsel-r2-hard-nan2008")
1338 .flag("-EL")
1339 .flag("-msoft-float", /*Disallow=*/true)
1340 .flag("-mnan=2008")
1341 .flag("-muclibc", /*Disallow=*/true)
1342 .flag("-mmicromips", /*Disallow=*/true);
1343 auto BeHardNanUclibc = MultilibBuilder("/mips-r2-hard-nan2008-uclibc")
1344 .flag("-EB")
1345 .flag("-msoft-float", /*Disallow=*/true)
1346 .flag("-mnan=2008")
1347 .flag("-muclibc");
1348 auto ElHardNanUclibc = MultilibBuilder("/mipsel-r2-hard-nan2008-uclibc")
1349 .flag("-EL")
1350 .flag("-msoft-float", /*Disallow=*/true)
1351 .flag("-mnan=2008")
1352 .flag("-muclibc");
1353 auto BeHardUclibc = MultilibBuilder("/mips-r2-hard-uclibc")
1354 .flag("-EB")
1355 .flag("-msoft-float", /*Disallow=*/true)
1356 .flag("-mnan=2008", /*Disallow=*/true)
1357 .flag("-muclibc");
1358 auto ElHardUclibc = MultilibBuilder("/mipsel-r2-hard-uclibc")
1359 .flag("-EL")
1360 .flag("-msoft-float", /*Disallow=*/true)
1361 .flag("-mnan=2008", /*Disallow=*/true)
1362 .flag("-muclibc");
1363 auto ElMicroHardNan = MultilibBuilder("/micromipsel-r2-hard-nan2008")
1364 .flag("-EL")
1365 .flag("-msoft-float", /*Disallow=*/true)
1366 .flag("-mnan=2008")
1367 .flag("-mmicromips");
1368 auto ElMicroSoft = MultilibBuilder("/micromipsel-r2-soft")
1369 .flag("-EL")
1370 .flag("-msoft-float")
1371 .flag("-mnan=2008", /*Disallow=*/true)
1372 .flag("-mmicromips");
1373
1374 auto O32 = MultilibBuilder("/lib")
1375 .osSuffix("")
1376 .flag("-mabi=n32", /*Disallow=*/true)
1377 .flag("-mabi=n64", /*Disallow=*/true);
1378 auto N32 = MultilibBuilder("/lib32")
1379 .osSuffix("")
1380 .flag("-mabi=n32")
1381 .flag("-mabi=n64", /*Disallow=*/true);
1382 auto N64 = MultilibBuilder("/lib64")
1383 .osSuffix("")
1384 .flag("-mabi=n32", /*Disallow=*/true)
1385 .flag("-mabi=n64");
1386
1387 MtiMipsMultilibsV2 =
1389 .Either({BeHard, BeSoft, ElHard, ElSoft, BeHardNan, ElHardNan,
1390 BeHardNanUclibc, ElHardNanUclibc, BeHardUclibc,
1391 ElHardUclibc, ElMicroHardNan, ElMicroSoft})
1392 .Either(O32, N32, N64)
1394 .FilterOut(NonExistent)
1395 .setIncludeDirsCallback([](const Multilib &M) {
1396 return std::vector<std::string>({"/../../../../sysroot" +
1397 M.includeSuffix() +
1398 "/../usr/include"});
1399 })
1400 .setFilePathsCallback([](const Multilib &M) {
1401 return std::vector<std::string>(
1402 {"/../../../../mips-mti-linux-gnu/lib" + M.gccSuffix()});
1403 });
1404 }
1405 for (auto *Candidate : {&MtiMipsMultilibsV1, &MtiMipsMultilibsV2}) {
1406 if (Candidate->select(Flags, Result.SelectedMultilibs)) {
1407 Result.Multilibs = *Candidate;
1408 return true;
1409 }
1410 }
1411 return false;
1412}
1413
1415 FilterNonExistent &NonExistent,
1417 // CodeScape IMG toolchain v1.2 and early.
1418 MultilibSet ImgMultilibsV1;
1419 {
1420 auto Mips64r6 = MultilibBuilder("/mips64r6")
1421 .flag("-m64")
1422 .flag("-m32", /*Disallow=*/true);
1423
1424 auto LittleEndian =
1425 MultilibBuilder("/el").flag("-EL").flag("-EB", /*Disallow=*/true);
1426
1427 auto MAbi64 = MultilibBuilder("/64")
1428 .flag("-mabi=n64")
1429 .flag("-mabi=n32", /*Disallow=*/true)
1430 .flag("-m32", /*Disallow=*/true);
1431
1432 ImgMultilibsV1 =
1434 .Maybe(Mips64r6)
1435 .Maybe(MAbi64)
1436 .Maybe(LittleEndian)
1438 .FilterOut(NonExistent)
1439 .setIncludeDirsCallback([](const Multilib &M) {
1440 return std::vector<std::string>(
1441 {"/include", "/../../../../sysroot/usr/include"});
1442 });
1443 }
1444
1445 // CodeScape IMG toolchain starting from v1.3.
1446 MultilibSet ImgMultilibsV2;
1447 {
1448 auto BeHard = MultilibBuilder("/mips-r6-hard")
1449 .flag("-EB")
1450 .flag("-msoft-float", /*Disallow=*/true)
1451 .flag("-mmicromips", /*Disallow=*/true);
1452 auto BeSoft = MultilibBuilder("/mips-r6-soft")
1453 .flag("-EB")
1454 .flag("-msoft-float")
1455 .flag("-mmicromips", /*Disallow=*/true);
1456 auto ElHard = MultilibBuilder("/mipsel-r6-hard")
1457 .flag("-EL")
1458 .flag("-msoft-float", /*Disallow=*/true)
1459 .flag("-mmicromips", /*Disallow=*/true);
1460 auto ElSoft = MultilibBuilder("/mipsel-r6-soft")
1461 .flag("-EL")
1462 .flag("-msoft-float")
1463 .flag("-mmicromips", /*Disallow=*/true);
1464 auto BeMicroHard = MultilibBuilder("/micromips-r6-hard")
1465 .flag("-EB")
1466 .flag("-msoft-float", /*Disallow=*/true)
1467 .flag("-mmicromips");
1468 auto BeMicroSoft = MultilibBuilder("/micromips-r6-soft")
1469 .flag("-EB")
1470 .flag("-msoft-float")
1471 .flag("-mmicromips");
1472 auto ElMicroHard = MultilibBuilder("/micromipsel-r6-hard")
1473 .flag("-EL")
1474 .flag("-msoft-float", /*Disallow=*/true)
1475 .flag("-mmicromips");
1476 auto ElMicroSoft = MultilibBuilder("/micromipsel-r6-soft")
1477 .flag("-EL")
1478 .flag("-msoft-float")
1479 .flag("-mmicromips");
1480
1481 auto O32 = MultilibBuilder("/lib")
1482 .osSuffix("")
1483 .flag("-mabi=n32", /*Disallow=*/true)
1484 .flag("-mabi=n64", /*Disallow=*/true);
1485 auto N32 = MultilibBuilder("/lib32")
1486 .osSuffix("")
1487 .flag("-mabi=n32")
1488 .flag("-mabi=n64", /*Disallow=*/true);
1489 auto N64 = MultilibBuilder("/lib64")
1490 .osSuffix("")
1491 .flag("-mabi=n32", /*Disallow=*/true)
1492 .flag("-mabi=n64");
1493
1494 ImgMultilibsV2 =
1496 .Either({BeHard, BeSoft, ElHard, ElSoft, BeMicroHard, BeMicroSoft,
1497 ElMicroHard, ElMicroSoft})
1498 .Either(O32, N32, N64)
1500 .FilterOut(NonExistent)
1501 .setIncludeDirsCallback([](const Multilib &M) {
1502 return std::vector<std::string>({"/../../../../sysroot" +
1503 M.includeSuffix() +
1504 "/../usr/include"});
1505 })
1506 .setFilePathsCallback([](const Multilib &M) {
1507 return std::vector<std::string>(
1508 {"/../../../../mips-img-linux-gnu/lib" + M.gccSuffix()});
1509 });
1510 }
1511 for (auto *Candidate : {&ImgMultilibsV1, &ImgMultilibsV2}) {
1512 if (Candidate->select(Flags, Result.SelectedMultilibs)) {
1513 Result.Multilibs = *Candidate;
1514 return true;
1515 }
1516 }
1517 return false;
1518}
1519
1521 const llvm::Triple &TargetTriple,
1522 StringRef Path, const ArgList &Args,
1524 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1525
1526 StringRef CPUName;
1527 StringRef ABIName;
1528 tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
1529
1530 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1531
1533 addMultilibFlag(TargetTriple.isMIPS32(), "-m32", Flags);
1534 addMultilibFlag(TargetTriple.isMIPS64(), "-m64", Flags);
1535 addMultilibFlag(isMips16(Args), "-mips16", Flags);
1536 addMultilibFlag(CPUName == "mips32", "-march=mips32", Flags);
1537 addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" ||
1538 CPUName == "mips32r5" || CPUName == "p5600",
1539 "-march=mips32r2", Flags);
1540 addMultilibFlag(CPUName == "mips32r6", "-march=mips32r6", Flags);
1541 addMultilibFlag(CPUName == "mips64", "-march=mips64", Flags);
1542 addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" ||
1543 CPUName == "mips64r5" || CPUName == "octeon" ||
1544 CPUName == "octeon+",
1545 "-march=mips64r2", Flags);
1546 addMultilibFlag(CPUName == "mips64r6", "-march=mips64r6", Flags);
1547 addMultilibFlag(isMicroMips(Args), "-mmicromips", Flags);
1548 addMultilibFlag(tools::mips::isUCLibc(Args), "-muclibc", Flags);
1549 addMultilibFlag(tools::mips::isNaN2008(D, Args, TargetTriple), "-mnan=2008",
1550 Flags);
1551 addMultilibFlag(ABIName == "n32", "-mabi=n32", Flags);
1552 addMultilibFlag(ABIName == "n64", "-mabi=n64", Flags);
1553 addMultilibFlag(isSoftFloatABI(Args), "-msoft-float", Flags);
1554 addMultilibFlag(!isSoftFloatABI(Args), "-mhard-float", Flags);
1555 addMultilibFlag(isMipsEL(TargetArch), "-EL", Flags);
1556 addMultilibFlag(!isMipsEL(TargetArch), "-EB", Flags);
1557
1558 if (TargetTriple.isAndroid())
1559 return findMipsAndroidMultilibs(D.getVFS(), Path, Flags, NonExistent,
1560 Result);
1561
1562 if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
1563 TargetTriple.getOS() == llvm::Triple::Linux &&
1564 TargetTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
1565 return findMipsMuslMultilibs(Flags, NonExistent, Result);
1566
1567 if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
1568 TargetTriple.getOS() == llvm::Triple::Linux &&
1569 TargetTriple.isGNUEnvironment())
1570 return findMipsMtiMultilibs(Flags, NonExistent, Result);
1571
1572 if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1573 TargetTriple.getOS() == llvm::Triple::Linux &&
1574 TargetTriple.isGNUEnvironment())
1575 return findMipsImgMultilibs(Flags, NonExistent, Result);
1576
1577 if (findMipsCsMultilibs(Flags, NonExistent, Result))
1578 return true;
1579
1580 // Fallback to the regular toolchain-tree structure.
1582 Result.Multilibs.push_back(Default);
1583 Result.Multilibs.FilterOut(NonExistent);
1584
1585 if (Result.Multilibs.select(Flags, Result.SelectedMultilibs)) {
1586 Result.BiarchSibling = Multilib();
1587 return true;
1588 }
1589
1590 return false;
1591}
1592
1594 const llvm::Triple &TargetTriple,
1595 StringRef Path, const ArgList &Args,
1597 // Find multilibs with subdirectories like armv7-a, thumb, armv7-a/thumb.
1598 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1599 MultilibBuilder ArmV7Multilib = MultilibBuilder("/armv7-a")
1600 .flag("-march=armv7-a")
1601 .flag("-mthumb", /*Disallow=*/true);
1602 MultilibBuilder ThumbMultilib = MultilibBuilder("/thumb")
1603 .flag("-march=armv7-a", /*Disallow=*/true)
1604 .flag("-mthumb");
1605 MultilibBuilder ArmV7ThumbMultilib =
1606 MultilibBuilder("/armv7-a/thumb").flag("-march=armv7-a").flag("-mthumb");
1607 MultilibBuilder DefaultMultilib =
1608 MultilibBuilder("")
1609 .flag("-march=armv7-a", /*Disallow=*/true)
1610 .flag("-mthumb", /*Disallow=*/true);
1611 MultilibSet AndroidArmMultilibs =
1613 .Either(ThumbMultilib, ArmV7Multilib, ArmV7ThumbMultilib,
1614 DefaultMultilib)
1616 .FilterOut(NonExistent);
1617
1619 llvm::StringRef Arch = Args.getLastArgValue(options::OPT_march_EQ);
1620 bool IsArmArch = TargetTriple.getArch() == llvm::Triple::arm;
1621 bool IsThumbArch = TargetTriple.getArch() == llvm::Triple::thumb;
1622 bool IsV7SubArch = TargetTriple.getSubArch() == llvm::Triple::ARMSubArch_v7;
1623 bool IsThumbMode = IsThumbArch ||
1624 Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, false) ||
1625 (IsArmArch && llvm::ARM::parseArchISA(Arch) == llvm::ARM::ISAKind::THUMB);
1626 bool IsArmV7Mode = (IsArmArch || IsThumbArch) &&
1627 (llvm::ARM::parseArchVersion(Arch) == 7 ||
1628 (IsArmArch && Arch == "" && IsV7SubArch));
1629 addMultilibFlag(IsArmV7Mode, "-march=armv7-a", Flags);
1630 addMultilibFlag(IsThumbMode, "-mthumb", Flags);
1631
1632 if (AndroidArmMultilibs.select(Flags, Result.SelectedMultilibs))
1633 Result.Multilibs = AndroidArmMultilibs;
1634}
1635
1636static bool findMSP430Multilibs(const Driver &D,
1637 const llvm::Triple &TargetTriple,
1638 StringRef Path, const ArgList &Args,
1640 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1641 MultilibBuilder WithoutExceptions =
1642 MultilibBuilder("/430").flag("-exceptions", /*Disallow=*/true);
1643 MultilibBuilder WithExceptions =
1644 MultilibBuilder("/430/exceptions").flag("-exceptions");
1645
1646 // FIXME: when clang starts to support msp430x ISA additional logic
1647 // to select between multilib must be implemented
1648 // MultilibBuilder MSP430xMultilib = MultilibBuilder("/large");
1649
1650 Result.Multilibs.push_back(WithoutExceptions.makeMultilib());
1651 Result.Multilibs.push_back(WithExceptions.makeMultilib());
1652 Result.Multilibs.FilterOut(NonExistent);
1653
1655 addMultilibFlag(Args.hasFlag(options::OPT_fexceptions,
1656 options::OPT_fno_exceptions, false),
1657 "-exceptions", Flags);
1658 if (Result.Multilibs.select(Flags, Result.SelectedMultilibs))
1659 return true;
1660
1661 return false;
1662}
1663
1664static void findCSKYMultilibs(const Driver &D, const llvm::Triple &TargetTriple,
1665 StringRef Path, const ArgList &Args,
1667 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1668
1670 std::optional<llvm::StringRef> Res =
1671 tools::csky::getCSKYArchName(D, Args, TargetTriple);
1672
1673 if (!Res)
1674 return;
1675 auto ARCHName = *Res;
1676
1678 addMultilibFlag(TheFloatABI == tools::csky::FloatABI::Hard, "-hard-fp",
1679 Flags);
1680 addMultilibFlag(TheFloatABI == tools::csky::FloatABI::SoftFP, "-soft-fp",
1681 Flags);
1682 addMultilibFlag(TheFloatABI == tools::csky::FloatABI::Soft, "-soft", Flags);
1683 addMultilibFlag(ARCHName == "ck801", "-march=ck801", Flags);
1684 addMultilibFlag(ARCHName == "ck802", "-march=ck802", Flags);
1685 addMultilibFlag(ARCHName == "ck803", "-march=ck803", Flags);
1686 addMultilibFlag(ARCHName == "ck804", "-march=ck804", Flags);
1687 addMultilibFlag(ARCHName == "ck805", "-march=ck805", Flags);
1688 addMultilibFlag(ARCHName == "ck807", "-march=ck807", Flags);
1689 addMultilibFlag(ARCHName == "ck810", "-march=ck810", Flags);
1690 addMultilibFlag(ARCHName == "ck810v", "-march=ck810v", Flags);
1691 addMultilibFlag(ARCHName == "ck860", "-march=ck860", Flags);
1692 addMultilibFlag(ARCHName == "ck860v", "-march=ck860v", Flags);
1693
1694 bool isBigEndian = false;
1695 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
1696 options::OPT_mbig_endian))
1697 isBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
1698 addMultilibFlag(isBigEndian, "-EB", Flags);
1699
1700 auto HardFloat = MultilibBuilder("/hard-fp").flag("-hard-fp");
1701 auto SoftFpFloat = MultilibBuilder("/soft-fp").flag("-soft-fp");
1702 auto SoftFloat = MultilibBuilder("").flag("-soft");
1703 auto Arch801 = MultilibBuilder("/ck801").flag("-march=ck801");
1704 auto Arch802 = MultilibBuilder("/ck802").flag("-march=ck802");
1705 auto Arch803 = MultilibBuilder("/ck803").flag("-march=ck803");
1706 // CK804 use the same library as CK803
1707 auto Arch804 = MultilibBuilder("/ck803").flag("-march=ck804");
1708 auto Arch805 = MultilibBuilder("/ck805").flag("-march=ck805");
1709 auto Arch807 = MultilibBuilder("/ck807").flag("-march=ck807");
1710 auto Arch810 = MultilibBuilder("").flag("-march=ck810");
1711 auto Arch810v = MultilibBuilder("/ck810v").flag("-march=ck810v");
1712 auto Arch860 = MultilibBuilder("/ck860").flag("-march=ck860");
1713 auto Arch860v = MultilibBuilder("/ck860v").flag("-march=ck860v");
1714 auto BigEndian = MultilibBuilder("/big").flag("-EB");
1715
1716 MultilibSet CSKYMultilibs =
1718 .Maybe(BigEndian)
1719 .Either({Arch801, Arch802, Arch803, Arch804, Arch805, Arch807,
1720 Arch810, Arch810v, Arch860, Arch860v})
1721 .Either(HardFloat, SoftFpFloat, SoftFloat)
1723 .FilterOut(NonExistent);
1724
1725 if (CSKYMultilibs.select(Flags, Result.SelectedMultilibs))
1726 Result.Multilibs = CSKYMultilibs;
1727}
1728
1729/// Extend the multi-lib re-use selection mechanism for RISC-V.
1730/// This function will try to re-use multi-lib if they are compatible.
1731/// Definition of compatible:
1732/// - ABI must be the same.
1733/// - multi-lib is a subset of current arch, e.g. multi-lib=march=rv32im
1734/// is a subset of march=rv32imc.
1735/// - march that contains atomic extension can't reuse multi-lib that
1736/// doesn't have atomic, vice versa. e.g. multi-lib=march=rv32im and
1737/// march=rv32ima are not compatible, because software and hardware
1738/// atomic operation can't work together correctly.
1739static bool
1740selectRISCVMultilib(const MultilibSet &RISCVMultilibSet, StringRef Arch,
1741 const Multilib::flags_list &Flags,
1742 llvm::SmallVectorImpl<Multilib> &SelectedMultilibs) {
1743 // Try to find the perfect matching multi-lib first.
1744 if (RISCVMultilibSet.select(Flags, SelectedMultilibs))
1745 return true;
1746
1747 Multilib::flags_list NewFlags;
1748 std::vector<MultilibBuilder> NewMultilibs;
1749
1751 llvm::RISCVISAInfo::parseArchString(
1752 Arch, /*EnableExperimentalExtension=*/true,
1753 /*ExperimentalExtensionVersionCheck=*/false);
1754 // Ignore any error here, we assume it will be handled in another place.
1755 if (llvm::errorToBool(ParseResult.takeError()))
1756 return false;
1757
1758 auto &ISAInfo = *ParseResult;
1759
1760 addMultilibFlag(ISAInfo->getXLen() == 32, "-m32", NewFlags);
1761 addMultilibFlag(ISAInfo->getXLen() == 64, "-m64", NewFlags);
1762
1763 // Collect all flags except march=*
1764 for (StringRef Flag : Flags) {
1765 if (Flag.starts_with("!march=") || Flag.starts_with("-march="))
1766 continue;
1767
1768 NewFlags.push_back(Flag.str());
1769 }
1770
1771 llvm::StringSet<> AllArchExts;
1772 // Reconstruct multi-lib list, and break march option into separated
1773 // extension. e.g. march=rv32im -> +i +m
1774 for (const auto &M : RISCVMultilibSet) {
1775 bool Skip = false;
1776
1777 MultilibBuilder NewMultilib =
1778 MultilibBuilder(M.gccSuffix(), M.osSuffix(), M.includeSuffix());
1779 for (StringRef Flag : M.flags()) {
1780 // Add back all flags except -march.
1781 if (!Flag.consume_front("-march=")) {
1782 NewMultilib.flag(Flag);
1783 continue;
1784 }
1785
1786 // Break down -march into individual extension.
1788 llvm::RISCVISAInfo::parseArchString(
1789 Flag, /*EnableExperimentalExtension=*/true,
1790 /*ExperimentalExtensionVersionCheck=*/false);
1791 // Ignore any error here, we assume it will handled in another place.
1792 if (llvm::errorToBool(MLConfigParseResult.takeError())) {
1793 // We might get a parsing error if rv32e in the list, we could just skip
1794 // that and process the rest of multi-lib configs.
1795 Skip = true;
1796 continue;
1797 }
1798 auto &MLConfigISAInfo = *MLConfigParseResult;
1799
1800 for (auto &MLConfigArchExt : MLConfigISAInfo->getExtensions()) {
1801 auto ExtName = MLConfigArchExt.first;
1802 NewMultilib.flag(Twine("-", ExtName).str());
1803
1804 if (AllArchExts.insert(ExtName).second) {
1805 addMultilibFlag(ISAInfo->hasExtension(ExtName),
1806 Twine("-", ExtName).str(), NewFlags);
1807 }
1808 }
1809
1810 // Check the XLEN explicitly.
1811 if (MLConfigISAInfo->getXLen() == 32) {
1812 NewMultilib.flag("-m32");
1813 NewMultilib.flag("-m64", /*Disallow*/ true);
1814 } else {
1815 NewMultilib.flag("-m32", /*Disallow*/ true);
1816 NewMultilib.flag("-m64");
1817 }
1818
1819 // Atomic extension must be explicitly checked, soft and hard atomic
1820 // operation never co-work correctly.
1821 if (!MLConfigISAInfo->hasExtension("a"))
1822 NewMultilib.flag("-a", /*Disallow*/ true);
1823 }
1824
1825 if (Skip)
1826 continue;
1827
1828 NewMultilibs.emplace_back(NewMultilib);
1829 }
1830
1831 // Build an internal used only multi-lib list, used for checking any
1832 // compatible multi-lib.
1833 MultilibSet NewRISCVMultilibs =
1834 MultilibSetBuilder().Either(NewMultilibs).makeMultilibSet();
1835
1836 if (NewRISCVMultilibs.select(NewFlags, SelectedMultilibs))
1837 for (const Multilib &NewSelectedM : SelectedMultilibs)
1838 for (const auto &M : RISCVMultilibSet)
1839 // Look up the corresponding multi-lib entry in original multi-lib set.
1840 if (M.gccSuffix() == NewSelectedM.gccSuffix())
1841 return true;
1842
1843 return false;
1844}
1845
1847 const llvm::Triple &TargetTriple,
1848 StringRef Path, const ArgList &Args,
1850 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1851 struct RiscvMultilib {
1852 StringRef march;
1853 StringRef mabi;
1854 };
1855 // currently only support the set of multilibs like riscv-gnu-toolchain does.
1856 // TODO: support MULTILIB_REUSE
1857 constexpr RiscvMultilib RISCVMultilibSet[] = {
1858 {"rv32i", "ilp32"}, {"rv32im", "ilp32"}, {"rv32iac", "ilp32"},
1859 {"rv32imac", "ilp32"}, {"rv32imafc", "ilp32f"}, {"rv64imac", "lp64"},
1860 {"rv64imafdc", "lp64d"}};
1861
1862 std::vector<MultilibBuilder> Ms;
1863 for (auto Element : RISCVMultilibSet) {
1864 // multilib path rule is ${march}/${mabi}
1865 Ms.emplace_back(
1867 (Twine(Element.march) + "/" + Twine(Element.mabi)).str())
1868 .flag(Twine("-march=", Element.march).str())
1869 .flag(Twine("-mabi=", Element.mabi).str()));
1870 }
1871 MultilibSet RISCVMultilibs =
1873 .Either(Ms)
1875 .FilterOut(NonExistent)
1876 .setFilePathsCallback([](const Multilib &M) {
1877 return std::vector<std::string>(
1878 {M.gccSuffix(),
1879 "/../../../../riscv64-unknown-elf/lib" + M.gccSuffix(),
1880 "/../../../../riscv32-unknown-elf/lib" + M.gccSuffix()});
1881 });
1882
1884 llvm::StringSet<> Added_ABIs;
1885 StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple);
1886 std::string MArch = tools::riscv::getRISCVArch(Args, TargetTriple);
1887 for (auto Element : RISCVMultilibSet) {
1888 addMultilibFlag(MArch == Element.march,
1889 Twine("-march=", Element.march).str().c_str(), Flags);
1890 if (!Added_ABIs.count(Element.mabi)) {
1891 Added_ABIs.insert(Element.mabi);
1892 addMultilibFlag(ABIName == Element.mabi,
1893 Twine("-mabi=", Element.mabi).str().c_str(), Flags);
1894 }
1895 }
1896
1897 if (selectRISCVMultilib(RISCVMultilibs, MArch, Flags,
1898 Result.SelectedMultilibs))
1899 Result.Multilibs = RISCVMultilibs;
1900}
1901
1902static void findRISCVMultilibs(const Driver &D,
1903 const llvm::Triple &TargetTriple, StringRef Path,
1904 const ArgList &Args, DetectedMultilibs &Result) {
1905 if (TargetTriple.getOS() == llvm::Triple::UnknownOS)
1906 return findRISCVBareMetalMultilibs(D, TargetTriple, Path, Args, Result);
1907
1908 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1909 MultilibBuilder Ilp32 =
1910 MultilibBuilder("lib32/ilp32").flag("-m32").flag("-mabi=ilp32");
1911 MultilibBuilder Ilp32f =
1912 MultilibBuilder("lib32/ilp32f").flag("-m32").flag("-mabi=ilp32f");
1913 MultilibBuilder Ilp32d =
1914 MultilibBuilder("lib32/ilp32d").flag("-m32").flag("-mabi=ilp32d");
1915 MultilibBuilder Lp64 =
1916 MultilibBuilder("lib64/lp64").flag("-m64").flag("-mabi=lp64");
1917 MultilibBuilder Lp64f =
1918 MultilibBuilder("lib64/lp64f").flag("-m64").flag("-mabi=lp64f");
1919 MultilibBuilder Lp64d =
1920 MultilibBuilder("lib64/lp64d").flag("-m64").flag("-mabi=lp64d");
1921 MultilibSet RISCVMultilibs =
1923 .Either({Ilp32, Ilp32f, Ilp32d, Lp64, Lp64f, Lp64d})
1924 .makeMultilibSet()
1925 .FilterOut(NonExistent);
1926
1928 bool IsRV64 = TargetTriple.getArch() == llvm::Triple::riscv64;
1929 StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple);
1930
1931 addMultilibFlag(!IsRV64, "-m32", Flags);
1932 addMultilibFlag(IsRV64, "-m64", Flags);
1933 addMultilibFlag(ABIName == "ilp32", "-mabi=ilp32", Flags);
1934 addMultilibFlag(ABIName == "ilp32f", "-mabi=ilp32f", Flags);
1935 addMultilibFlag(ABIName == "ilp32d", "-mabi=ilp32d", Flags);
1936 addMultilibFlag(ABIName == "lp64", "-mabi=lp64", Flags);
1937 addMultilibFlag(ABIName == "lp64f", "-mabi=lp64f", Flags);
1938 addMultilibFlag(ABIName == "lp64d", "-mabi=lp64d", Flags);
1939
1940 if (RISCVMultilibs.select(Flags, Result.SelectedMultilibs))
1941 Result.Multilibs = RISCVMultilibs;
1942}
1943
1944static bool findBiarchMultilibs(const Driver &D,
1945 const llvm::Triple &TargetTriple,
1946 StringRef Path, const ArgList &Args,
1947 bool NeedsBiarchSuffix,
1949 MultilibBuilder DefaultBuilder;
1950
1951 // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1952 // in what would normally be GCCInstallPath and put the 64-bit
1953 // libs in a subdirectory named 64. The simple logic we follow is that
1954 // *if* there is a subdirectory of the right name with crtbegin.o in it,
1955 // we use that. If not, and if not a biarch triple alias, we look for
1956 // crtbegin.o without the subdirectory.
1957
1958 StringRef Suff64 = "/64";
1959 // Solaris uses platform-specific suffixes instead of /64.
1960 if (TargetTriple.isOSSolaris()) {
1961 switch (TargetTriple.getArch()) {
1962 case llvm::Triple::x86:
1963 case llvm::Triple::x86_64:
1964 Suff64 = "/amd64";
1965 break;
1966 case llvm::Triple::sparc:
1967 case llvm::Triple::sparcv9:
1968 Suff64 = "/sparcv9";
1969 break;
1970 default:
1971 break;
1972 }
1973 }
1974
1975 Multilib Alt64 = MultilibBuilder()
1976 .gccSuffix(Suff64)
1977 .includeSuffix(Suff64)
1978 .flag("-m32", /*Disallow=*/true)
1979 .flag("-m64")
1980 .flag("-mx32", /*Disallow=*/true)
1981 .makeMultilib();
1982 Multilib Alt32 = MultilibBuilder()
1983 .gccSuffix("/32")
1984 .includeSuffix("/32")
1985 .flag("-m32")
1986 .flag("-m64", /*Disallow=*/true)
1987 .flag("-mx32", /*Disallow=*/true)
1988 .makeMultilib();
1989 Multilib Altx32 = MultilibBuilder()
1990 .gccSuffix("/x32")
1991 .includeSuffix("/x32")
1992 .flag("-m32", /*Disallow=*/true)
1993 .flag("-m64", /*Disallow=*/true)
1994 .flag("-mx32")
1995 .makeMultilib();
1996 Multilib Alt32sparc = MultilibBuilder()
1997 .gccSuffix("/sparcv8plus")
1998 .includeSuffix("/sparcv8plus")
1999 .flag("-m32")
2000 .flag("-m64", /*Disallow=*/true)
2001 .makeMultilib();
2002
2003 // GCC toolchain for IAMCU doesn't have crtbegin.o, so look for libgcc.a.
2004 FilterNonExistent NonExistent(
2005 Path, TargetTriple.isOSIAMCU() ? "/libgcc.a" : "/crtbegin.o", D.getVFS());
2006
2007 // Determine default multilib from: 32, 64, x32
2008 // Also handle cases such as 64 on 32, 32 on 64, etc.
2009 enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
2010 const bool IsX32 = TargetTriple.isX32();
2011 if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
2012 Want = WANT64;
2013 if (TargetTriple.isArch32Bit() && !NonExistent(Alt32sparc))
2014 Want = WANT64;
2015 else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
2016 Want = WANT64;
2017 else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
2018 Want = WANT32;
2019 else if (TargetTriple.isArch64Bit() && !NonExistent(Alt32sparc))
2020 Want = WANT64;
2021 else {
2022 if (TargetTriple.isArch32Bit())
2023 Want = NeedsBiarchSuffix ? WANT64 : WANT32;
2024 else if (IsX32)
2025 Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
2026 else
2027 Want = NeedsBiarchSuffix ? WANT32 : WANT64;
2028 }
2029
2030 if (Want == WANT32)
2031 DefaultBuilder.flag("-m32")
2032 .flag("-m64", /*Disallow=*/true)
2033 .flag("-mx32", /*Disallow=*/true);
2034 else if (Want == WANT64)
2035 DefaultBuilder.flag("-m32", /*Disallow=*/true)
2036 .flag("-m64")
2037 .flag("-mx32", /*Disallow=*/true);
2038 else if (Want == WANTX32)
2039 DefaultBuilder.flag("-m32", /*Disallow=*/true)
2040 .flag("-m64", /*Disallow=*/true)
2041 .flag("-mx32");
2042 else
2043 return false;
2044
2045 Multilib Default = DefaultBuilder.makeMultilib();
2046
2047 Result.Multilibs.push_back(Default);
2048 Result.Multilibs.push_back(Alt64);
2049 Result.Multilibs.push_back(Alt32);
2050 Result.Multilibs.push_back(Altx32);
2051 Result.Multilibs.push_back(Alt32sparc);
2052
2053 Result.Multilibs.FilterOut(NonExistent);
2054
2056 addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "-m64", Flags);
2057 addMultilibFlag(TargetTriple.isArch32Bit(), "-m32", Flags);
2058 addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "-mx32", Flags);
2059
2060 if (!Result.Multilibs.select(Flags, Result.SelectedMultilibs))
2061 return false;
2062
2063 if (Result.SelectedMultilibs.back() == Alt64 ||
2064 Result.SelectedMultilibs.back() == Alt32 ||
2065 Result.SelectedMultilibs.back() == Altx32 ||
2066 Result.SelectedMultilibs.back() == Alt32sparc)
2067 Result.BiarchSibling = Default;
2068
2069 return true;
2070}
2071
2072/// Generic_GCC - A tool chain using the 'gcc' command to perform
2073/// all subcommands; this relies on gcc translating the majority of
2074/// command line options.
2075
2076/// Less-than for GCCVersion, implementing a Strict Weak Ordering.
2077bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
2078 int RHSPatch,
2079 StringRef RHSPatchSuffix) const {
2080 if (Major != RHSMajor)
2081 return Major < RHSMajor;
2082 if (Minor != RHSMinor) {
2083 // Note that versions without a specified minor sort higher than those with
2084 // a minor.
2085 if (RHSMinor == -1)
2086 return true;
2087 if (Minor == -1)
2088 return false;
2089 return Minor < RHSMinor;
2090 }
2091 if (Patch != RHSPatch) {
2092 // Note that versions without a specified patch sort higher than those with
2093 // a patch.
2094 if (RHSPatch == -1)
2095 return true;
2096 if (Patch == -1)
2097 return false;
2098
2099 // Otherwise just sort on the patch itself.
2100 return Patch < RHSPatch;
2101 }
2102 if (PatchSuffix != RHSPatchSuffix) {
2103 // Sort empty suffixes higher.
2104 if (RHSPatchSuffix.empty())
2105 return true;
2106 if (PatchSuffix.empty())
2107 return false;
2108
2109 // Provide a lexicographic sort to make this a total ordering.
2110 return PatchSuffix < RHSPatchSuffix;
2111 }
2112
2113 // The versions are equal.
2114 return false;
2115}
2116
2117/// Parse a GCCVersion object out of a string of text.
2118///
2119/// This is the primary means of forming GCCVersion objects.
2120/*static*/
2122 const GCCVersion BadVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
2123 std::pair<StringRef, StringRef> First = VersionText.split('.');
2124 std::pair<StringRef, StringRef> Second = First.second.split('.');
2125
2126 StringRef MajorStr = First.first;
2127 StringRef MinorStr = Second.first;
2128 StringRef PatchStr = Second.second;
2129
2130 GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
2131
2132 // Parse version number strings such as:
2133 // 5
2134 // 4.4
2135 // 4.4-patched
2136 // 4.4.0
2137 // 4.4.x
2138 // 4.4.2-rc4
2139 // 4.4.x-patched
2140 // 10-win32
2141 // Split on '.', handle 1, 2 or 3 such segments. Each segment must contain
2142 // purely a number, except for the last one, where a non-number suffix
2143 // is stored in PatchSuffix. The third segment is allowed to not contain
2144 // a number at all.
2145
2146 auto TryParseLastNumber = [&](StringRef Segment, int &Number,
2147 std::string &OutStr) -> bool {
2148 // Look for a number prefix and parse that, and split out any trailing
2149 // string into GoodVersion.PatchSuffix.
2150
2151 if (size_t EndNumber = Segment.find_first_not_of("0123456789")) {
2152 StringRef NumberStr = Segment.slice(0, EndNumber);
2153 if (NumberStr.getAsInteger(10, Number) || Number < 0)
2154 return false;
2155 OutStr = NumberStr;
2156 GoodVersion.PatchSuffix = Segment.substr(EndNumber);
2157 return true;
2158 }
2159 return false;
2160 };
2161 auto TryParseNumber = [](StringRef Segment, int &Number) -> bool {
2162 if (Segment.getAsInteger(10, Number) || Number < 0)
2163 return false;
2164 return true;
2165 };
2166
2167 if (MinorStr.empty()) {
2168 // If no minor string, major is the last segment
2169 if (!TryParseLastNumber(MajorStr, GoodVersion.Major, GoodVersion.MajorStr))
2170 return BadVersion;
2171 return GoodVersion;
2172 }
2173
2174 if (!TryParseNumber(MajorStr, GoodVersion.Major))
2175 return BadVersion;
2176 GoodVersion.MajorStr = MajorStr;
2177
2178 if (PatchStr.empty()) {
2179 // If no patch string, minor is the last segment
2180 if (!TryParseLastNumber(MinorStr, GoodVersion.Minor, GoodVersion.MinorStr))
2181 return BadVersion;
2182 return GoodVersion;
2183 }
2184
2185 if (!TryParseNumber(MinorStr, GoodVersion.Minor))
2186 return BadVersion;
2187 GoodVersion.MinorStr = MinorStr;
2188
2189 // For the last segment, tolerate a missing number.
2190 std::string DummyStr;
2191 TryParseLastNumber(PatchStr, GoodVersion.Patch, DummyStr);
2192 return GoodVersion;
2193}
2194
2195static llvm::StringRef getGCCToolchainDir(const ArgList &Args,
2196 llvm::StringRef SysRoot) {
2197 const Arg *A = Args.getLastArg(clang::driver::options::OPT_gcc_toolchain);
2198 if (A)
2199 return A->getValue();
2200
2201 // If we have a SysRoot, ignore GCC_INSTALL_PREFIX.
2202 // GCC_INSTALL_PREFIX specifies the gcc installation for the default
2203 // sysroot and is likely not valid with a different sysroot.
2204 if (!SysRoot.empty())
2205 return "";
2206
2207 return GCC_INSTALL_PREFIX;
2208}
2209
2210/// Initialize a GCCInstallationDetector from the driver.
2211///
2212/// This performs all of the autodetection and sets up the various paths.
2213/// Once constructed, a GCCInstallationDetector is essentially immutable.
2214///
2215/// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
2216/// should instead pull the target out of the driver. This is currently
2217/// necessary because the driver doesn't store the final version of the target
2218/// triple.
2220 const llvm::Triple &TargetTriple, const ArgList &Args) {
2221 llvm::Triple BiarchVariantTriple = TargetTriple.isArch32Bit()
2222 ? TargetTriple.get64BitArchVariant()
2223 : TargetTriple.get32BitArchVariant();
2224 // The library directories which may contain GCC installations.
2225 SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
2226 // The compatible GCC triples for this particular architecture.
2227 SmallVector<StringRef, 16> CandidateTripleAliases;
2228 SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
2229 // Add some triples that we want to check first.
2230 CandidateTripleAliases.push_back(TargetTriple.str());
2231 std::string TripleNoVendor, BiarchTripleNoVendor;
2232 if (TargetTriple.getVendor() == llvm::Triple::UnknownVendor) {
2233 StringRef OSEnv = TargetTriple.getOSAndEnvironmentName();
2234 if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32)
2235 OSEnv = "linux-gnu";
2236 TripleNoVendor = (TargetTriple.getArchName().str() + '-' + OSEnv).str();
2237 CandidateTripleAliases.push_back(TripleNoVendor);
2238 if (BiarchVariantTriple.getArch() != llvm::Triple::UnknownArch) {
2239 BiarchTripleNoVendor =
2240 (BiarchVariantTriple.getArchName().str() + '-' + OSEnv).str();
2241 CandidateBiarchTripleAliases.push_back(BiarchTripleNoVendor);
2242 }
2243 }
2244
2245 CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
2246 CandidateTripleAliases, CandidateBiarchLibDirs,
2247 CandidateBiarchTripleAliases);
2248
2249 // If --gcc-install-dir= is specified, skip filesystem detection.
2250 if (const Arg *A =
2251 Args.getLastArg(clang::driver::options::OPT_gcc_install_dir_EQ);
2252 A && A->getValue()[0]) {
2253 StringRef InstallDir = A->getValue();
2254 if (!ScanGCCForMultilibs(TargetTriple, Args, InstallDir, false)) {
2255 D.Diag(diag::err_drv_invalid_gcc_install_dir) << InstallDir;
2256 } else {
2257 (void)InstallDir.consume_back("/");
2258 StringRef VersionText = llvm::sys::path::filename(InstallDir);
2259 StringRef TripleText =
2260 llvm::sys::path::filename(llvm::sys::path::parent_path(InstallDir));
2261
2262 Version = GCCVersion::Parse(VersionText);
2263 GCCTriple.setTriple(TripleText);
2264 GCCInstallPath = std::string(InstallDir);
2265 GCCParentLibPath = GCCInstallPath + "/../../..";
2266 IsValid = true;
2267 }
2268 return;
2269 }
2270
2271 // If --gcc-triple is specified use this instead of trying to
2272 // auto-detect a triple.
2273 if (const Arg *A =
2274 Args.getLastArg(clang::driver::options::OPT_gcc_triple_EQ)) {
2275 StringRef GCCTriple = A->getValue();
2276 CandidateTripleAliases.clear();
2277 CandidateTripleAliases.push_back(GCCTriple);
2278 }
2279
2280 // Compute the set of prefixes for our search.
2282 StringRef GCCToolchainDir = getGCCToolchainDir(Args, D.SysRoot);
2283 if (GCCToolchainDir != "") {
2284 if (GCCToolchainDir.back() == '/')
2285 GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
2286
2287 Prefixes.push_back(std::string(GCCToolchainDir));
2288 } else {
2289 // If we have a SysRoot, try that first.
2290 if (!D.SysRoot.empty()) {
2291 Prefixes.push_back(D.SysRoot);
2292 AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
2293 }
2294
2295 // Then look for gcc installed alongside clang.
2296 Prefixes.push_back(D.Dir + "/..");
2297
2298 // Next, look for prefix(es) that correspond to distribution-supplied gcc
2299 // installations.
2300 if (D.SysRoot.empty()) {
2301 // Typically /usr.
2302 AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
2303 }
2304
2305 // Try to respect gcc-config on Gentoo if --gcc-toolchain is not provided.
2306 // This avoids accidentally enforcing the system GCC version when using a
2307 // custom toolchain.
2308 SmallVector<StringRef, 16> GentooTestTriples;
2309 // Try to match an exact triple as target triple first.
2310 // e.g. crossdev -S x86_64-gentoo-linux-gnu will install gcc libs for
2311 // x86_64-gentoo-linux-gnu. But "clang -target x86_64-gentoo-linux-gnu"
2312 // may pick the libraries for x86_64-pc-linux-gnu even when exact matching
2313 // triple x86_64-gentoo-linux-gnu is present.
2314 GentooTestTriples.push_back(TargetTriple.str());
2315 GentooTestTriples.append(CandidateTripleAliases.begin(),
2316 CandidateTripleAliases.end());
2317 if (ScanGentooConfigs(TargetTriple, Args, GentooTestTriples,
2318 CandidateBiarchTripleAliases))
2319 return;
2320 }
2321
2322 // Loop over the various components which exist and select the best GCC
2323 // installation available. GCC installs are ranked by version number.
2324 const GCCVersion VersionZero = GCCVersion::Parse("0.0.0");
2325 Version = VersionZero;
2326 for (const std::string &Prefix : Prefixes) {
2327 auto &VFS = D.getVFS();
2328 if (!VFS.exists(Prefix))
2329 continue;
2330 for (StringRef Suffix : CandidateLibDirs) {
2331 const std::string LibDir = concat(Prefix, Suffix);
2332 if (!VFS.exists(LibDir))
2333 continue;
2334 // Maybe filter out <libdir>/gcc and <libdir>/gcc-cross.
2335 bool GCCDirExists = VFS.exists(LibDir + "/gcc");
2336 bool GCCCrossDirExists = VFS.exists(LibDir + "/gcc-cross");
2337 for (StringRef Candidate : CandidateTripleAliases)
2338 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, false,
2339 GCCDirExists, GCCCrossDirExists);
2340 }
2341 for (StringRef Suffix : CandidateBiarchLibDirs) {
2342 const std::string LibDir = Prefix + Suffix.str();
2343 if (!VFS.exists(LibDir))
2344 continue;
2345 bool GCCDirExists = VFS.exists(LibDir + "/gcc");
2346 bool GCCCrossDirExists = VFS.exists(LibDir + "/gcc-cross");
2347 for (StringRef Candidate : CandidateBiarchTripleAliases)
2348 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, true,
2349 GCCDirExists, GCCCrossDirExists);
2350 }
2351
2352 // Skip other prefixes once a GCC installation is found.
2353 if (Version > VersionZero)
2354 break;
2355 }
2356}
2357
2359 for (const auto &InstallPath : CandidateGCCInstallPaths)
2360 OS << "Found candidate GCC installation: " << InstallPath << "\n";
2361
2362 if (!GCCInstallPath.empty())
2363 OS << "Selected GCC installation: " << GCCInstallPath << "\n";
2364
2365 for (const auto &Multilib : Multilibs)
2366 OS << "Candidate multilib: " << Multilib << "\n";
2367
2368 if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
2369 OS << "Selected multilib: " << SelectedMultilib << "\n";
2370}
2371
2373 if (BiarchSibling) {
2374 M = *BiarchSibling;
2375 return true;
2376 }
2377 return false;
2378}
2379
2380void Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes(
2381 const llvm::Triple &TargetTriple, SmallVectorImpl<std::string> &Prefixes,
2382 StringRef SysRoot) {
2383
2384 if (TargetTriple.isOSHaiku()) {
2385 Prefixes.push_back(concat(SysRoot, "/boot/system/develop/tools"));
2386 return;
2387 }
2388
2389 if (TargetTriple.isOSSolaris()) {
2390 // Solaris is a special case.
2391 // The GCC installation is under
2392 // /usr/gcc/<major>.<minor>/lib/gcc/<triple>/<major>.<minor>.<patch>/
2393 // so we need to find those /usr/gcc/*/lib/gcc libdirs and go with
2394 // /usr/gcc/<version> as a prefix.
2395
2397 std::string PrefixDir = concat(SysRoot, "/usr/gcc");
2398 std::error_code EC;
2399 for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin(PrefixDir, EC),
2400 LE;
2401 !EC && LI != LE; LI = LI.increment(EC)) {
2402 StringRef VersionText = llvm::sys::path::filename(LI->path());
2403 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2404
2405 // Filter out obviously bad entries.
2406 if (CandidateVersion.Major == -1 || CandidateVersion.isOlderThan(4, 1, 1))
2407 continue;
2408
2409 std::string CandidatePrefix = PrefixDir + "/" + VersionText.str();
2410 std::string CandidateLibPath = CandidatePrefix + "/lib/gcc";
2411 if (!D.getVFS().exists(CandidateLibPath))
2412 continue;
2413
2414 SolarisPrefixes.emplace_back(
2415 std::make_pair(CandidateVersion, CandidatePrefix));
2416 }
2417 // Sort in reverse order so GCCInstallationDetector::init picks the latest.
2418 std::sort(SolarisPrefixes.rbegin(), SolarisPrefixes.rend());
2419 for (auto p : SolarisPrefixes)
2420 Prefixes.emplace_back(p.second);
2421 return;
2422 }
2423
2424 // For Linux, if --sysroot is not specified, look for RHEL/CentOS devtoolsets
2425 // and gcc-toolsets.
2426 if (SysRoot.empty() && TargetTriple.getOS() == llvm::Triple::Linux &&
2427 D.getVFS().exists("/opt/rh")) {
2428 // TODO: We may want to remove this, since the functionality
2429 // can be achieved using config files.
2430 Prefixes.push_back("/opt/rh/gcc-toolset-12/root/usr");
2431 Prefixes.push_back("/opt/rh/gcc-toolset-11/root/usr");
2432 Prefixes.push_back("/opt/rh/gcc-toolset-10/root/usr");
2433 Prefixes.push_back("/opt/rh/devtoolset-12/root/usr");
2434 Prefixes.push_back("/opt/rh/devtoolset-11/root/usr");
2435 Prefixes.push_back("/opt/rh/devtoolset-10/root/usr");
2436 Prefixes.push_back("/opt/rh/devtoolset-9/root/usr");
2437 Prefixes.push_back("/opt/rh/devtoolset-8/root/usr");
2438 Prefixes.push_back("/opt/rh/devtoolset-7/root/usr");
2439 Prefixes.push_back("/opt/rh/devtoolset-6/root/usr");
2440 Prefixes.push_back("/opt/rh/devtoolset-4/root/usr");
2441 Prefixes.push_back("/opt/rh/devtoolset-3/root/usr");
2442 Prefixes.push_back("/opt/rh/devtoolset-2/root/usr");
2443 }
2444
2445 // Fall back to /usr which is used by most non-Solaris systems.
2446 Prefixes.push_back(concat(SysRoot, "/usr"));
2447}
2448
2449/*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
2450 const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
2452 SmallVectorImpl<StringRef> &TripleAliases,
2453 SmallVectorImpl<StringRef> &BiarchLibDirs,
2454 SmallVectorImpl<StringRef> &BiarchTripleAliases) {
2455 // Declare a bunch of static data sets that we'll select between below. These
2456 // are specifically designed to always refer to string literals to avoid any
2457 // lifetime or initialization issues.
2458 //
2459 // The *Triples variables hard code some triples so that, for example,
2460 // --target=aarch64 (incomplete triple) can detect lib/aarch64-linux-gnu.
2461 // They are not needed when the user has correct LLVM_DEFAULT_TARGET_TRIPLE
2462 // and always uses the full --target (e.g. --target=aarch64-linux-gnu). The
2463 // lists should shrink over time. Please don't add more elements to *Triples.
2464 static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
2465 static const char *const AArch64Triples[] = {
2466 "aarch64-none-linux-gnu", "aarch64-redhat-linux", "aarch64-suse-linux"};
2467 static const char *const AArch64beLibDirs[] = {"/lib"};
2468 static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu"};
2469
2470 static const char *const ARMLibDirs[] = {"/lib"};
2471 static const char *const ARMTriples[] = {"arm-linux-gnueabi"};
2472 static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf",
2473 "armv7hl-redhat-linux-gnueabi",
2474 "armv6hl-suse-linux-gnueabi",
2475 "armv7hl-suse-linux-gnueabi"};
2476 static const char *const ARMebLibDirs[] = {"/lib"};
2477 static const char *const ARMebTriples[] = {"armeb-linux-gnueabi"};
2478 static const char *const ARMebHFTriples[] = {
2479 "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
2480
2481 static const char *const AVRLibDirs[] = {"/lib"};
2482 static const char *const AVRTriples[] = {"avr"};
2483
2484 static const char *const CSKYLibDirs[] = {"/lib"};
2485 static const char *const CSKYTriples[] = {
2486 "csky-linux-gnuabiv2", "csky-linux-uclibcabiv2", "csky-elf-noneabiv2"};
2487
2488 static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
2489 static const char *const X86_64Triples[] = {
2490 "x86_64-linux-gnu", "x86_64-unknown-linux-gnu",
2491 "x86_64-pc-linux-gnu", "x86_64-redhat-linux6E",
2492 "x86_64-redhat-linux", "x86_64-suse-linux",
2493 "x86_64-manbo-linux-gnu", "x86_64-slackware-linux",
2494 "x86_64-unknown-linux", "x86_64-amazon-linux"};
2495 static const char *const X32Triples[] = {"x86_64-linux-gnux32",
2496 "x86_64-pc-linux-gnux32"};
2497 static const char *const X32LibDirs[] = {"/libx32", "/lib"};
2498 static const char *const X86LibDirs[] = {"/lib32", "/lib"};
2499 static const char *const X86Triples[] = {
2500 "i586-linux-gnu", "i686-linux-gnu", "i686-pc-linux-gnu",
2501 "i386-redhat-linux6E", "i686-redhat-linux", "i386-redhat-linux",
2502 "i586-suse-linux", "i686-montavista-linux",
2503 };
2504
2505 static const char *const LoongArch64LibDirs[] = {"/lib64", "/lib"};
2506 static const char *const LoongArch64Triples[] = {
2507 "loongarch64-linux-gnu", "loongarch64-unknown-linux-gnu"};
2508
2509 static const char *const M68kLibDirs[] = {"/lib"};
2510 static const char *const M68kTriples[] = {"m68k-unknown-linux-gnu",
2511 "m68k-suse-linux"};
2512
2513 static const char *const MIPSLibDirs[] = {"/libo32", "/lib"};
2514 static const char *const MIPSTriples[] = {
2515 "mips-linux-gnu", "mips-mti-linux", "mips-mti-linux-gnu",
2516 "mips-img-linux-gnu", "mipsisa32r6-linux-gnu"};
2517 static const char *const MIPSELLibDirs[] = {"/libo32", "/lib"};
2518 static const char *const MIPSELTriples[] = {"mipsel-linux-gnu",
2519 "mips-img-linux-gnu"};
2520
2521 static const char *const MIPS64LibDirs[] = {"/lib64", "/lib"};
2522 static const char *const MIPS64Triples[] = {
2523 "mips-mti-linux-gnu", "mips-img-linux-gnu", "mips64-linux-gnuabi64",
2524 "mipsisa64r6-linux-gnu", "mipsisa64r6-linux-gnuabi64"};
2525 static const char *const MIPS64ELLibDirs[] = {"/lib64", "/lib"};
2526 static const char *const MIPS64ELTriples[] = {
2527 "mips-mti-linux-gnu", "mips-img-linux-gnu", "mips64el-linux-gnuabi64",
2528 "mipsisa64r6el-linux-gnu", "mipsisa64r6el-linux-gnuabi64"};
2529
2530 static const char *const MIPSN32LibDirs[] = {"/lib32"};
2531 static const char *const MIPSN32Triples[] = {"mips64-linux-gnuabin32",
2532 "mipsisa64r6-linux-gnuabin32"};
2533 static const char *const MIPSN32ELLibDirs[] = {"/lib32"};
2534 static const char *const MIPSN32ELTriples[] = {
2535 "mips64el-linux-gnuabin32", "mipsisa64r6el-linux-gnuabin32"};
2536
2537 static const char *const MSP430LibDirs[] = {"/lib"};
2538 static const char *const MSP430Triples[] = {"msp430-elf"};
2539
2540 static const char *const PPCLibDirs[] = {"/lib32", "/lib"};
2541 static const char *const PPCTriples[] = {
2542 "powerpc-unknown-linux-gnu",
2543 // On 32-bit PowerPC systems running SUSE Linux, gcc is configured as a
2544 // 64-bit compiler which defaults to "-m32", hence "powerpc64-suse-linux".
2545 "powerpc64-suse-linux", "powerpc-montavista-linuxspe"};
2546 static const char *const PPCLELibDirs[] = {"/lib32", "/lib"};
2547 static const char *const PPCLETriples[] = {"powerpcle-unknown-linux-gnu",
2548 "powerpcle-linux-musl"};
2549
2550 static const char *const PPC64LibDirs[] = {"/lib64", "/lib"};
2551 static const char *const PPC64Triples[] = {"powerpc64-unknown-linux-gnu",
2552 "powerpc64-suse-linux",
2553 "ppc64-redhat-linux"};
2554 static const char *const PPC64LELibDirs[] = {"/lib64", "/lib"};
2555 static const char *const PPC64LETriples[] = {
2556 "powerpc64le-unknown-linux-gnu", "powerpc64le-none-linux-gnu",
2557 "powerpc64le-suse-linux", "ppc64le-redhat-linux"};
2558
2559 static const char *const RISCV32LibDirs[] = {"/lib32", "/lib"};
2560 static const char *const RISCV32Triples[] = {"riscv32-unknown-linux-gnu",
2561 "riscv32-unknown-elf"};
2562 static const char *const RISCV64LibDirs[] = {"/lib64", "/lib"};
2563 static const char *const RISCV64Triples[] = {"riscv64-unknown-linux-gnu",
2564 "riscv64-unknown-elf"};
2565
2566 static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"};
2567 static const char *const SPARCv8Triples[] = {"sparc-linux-gnu",
2568 "sparcv8-linux-gnu"};
2569 static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"};
2570 static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu",
2571 "sparcv9-linux-gnu"};
2572
2573 static const char *const SystemZLibDirs[] = {"/lib64", "/lib"};
2574 static const char *const SystemZTriples[] = {
2575 "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu", "s390x-suse-linux",
2576 "s390x-redhat-linux"};
2577
2578 using std::begin;
2579 using std::end;
2580
2581 if (TargetTriple.isOSSolaris()) {
2582 static const char *const SolarisLibDirs[] = {"/lib"};
2583 static const char *const SolarisSparcV8Triples[] = {
2584 "sparc-sun-solaris2.11"};
2585 static const char *const SolarisSparcV9Triples[] = {
2586 "sparcv9-sun-solaris2.11"};
2587 static const char *const SolarisX86Triples[] = {"i386-pc-solaris2.11"};
2588 static const char *const SolarisX86_64Triples[] = {"x86_64-pc-solaris2.11"};
2589 LibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
2590 BiarchLibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
2591 switch (TargetTriple.getArch()) {
2592 case llvm::Triple::x86:
2593 TripleAliases.append(begin(SolarisX86Triples), end(SolarisX86Triples));
2594 BiarchTripleAliases.append(begin(SolarisX86_64Triples),
2595 end(SolarisX86_64Triples));
2596 break;
2597 case llvm::Triple::x86_64:
2598 TripleAliases.append(begin(SolarisX86_64Triples),
2599 end(SolarisX86_64Triples));
2600 BiarchTripleAliases.append(begin(SolarisX86Triples),
2601 end(SolarisX86Triples));
2602 break;
2603 case llvm::Triple::sparc:
2604 TripleAliases.append(begin(SolarisSparcV8Triples),
2605 end(SolarisSparcV8Triples));
2606 BiarchTripleAliases.append(begin(SolarisSparcV9Triples),
2607 end(SolarisSparcV9Triples));
2608 break;
2609 case llvm::Triple::sparcv9:
2610 TripleAliases.append(begin(SolarisSparcV9Triples),
2611 end(SolarisSparcV9Triples));
2612 BiarchTripleAliases.append(begin(SolarisSparcV8Triples),
2613 end(SolarisSparcV8Triples));
2614 break;
2615 default:
2616 break;
2617 }
2618 return;
2619 }
2620
2621 // Android targets should not use GNU/Linux tools or libraries.
2622 if (TargetTriple.isAndroid()) {
2623 static const char *const AArch64AndroidTriples[] = {
2624 "aarch64-linux-android"};
2625 static const char *const ARMAndroidTriples[] = {"arm-linux-androideabi"};
2626 static const char *const X86AndroidTriples[] = {"i686-linux-android"};
2627 static const char *const X86_64AndroidTriples[] = {"x86_64-linux-android"};
2628
2629 switch (TargetTriple.getArch()) {
2630 case llvm::Triple::aarch64:
2631 LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2632 TripleAliases.append(begin(AArch64AndroidTriples),
2633 end(AArch64AndroidTriples));
2634 break;
2635 case llvm::Triple::arm:
2636 case llvm::Triple::thumb:
2637 LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
2638 TripleAliases.append(begin(ARMAndroidTriples), end(ARMAndroidTriples));
2639 break;
2640 case llvm::Triple::x86_64:
2641 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2642 TripleAliases.append(begin(X86_64AndroidTriples),
2643 end(X86_64AndroidTriples));
2644 BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2645 BiarchTripleAliases.append(begin(X86AndroidTriples),
2646 end(X86AndroidTriples));
2647 break;
2648 case llvm::Triple::x86:
2649 LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2650 TripleAliases.append(begin(X86AndroidTriples), end(X86AndroidTriples));
2651 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2652 BiarchTripleAliases.append(begin(X86_64AndroidTriples),
2653 end(X86_64AndroidTriples));
2654 break;
2655 default:
2656 break;
2657 }
2658
2659 return;
2660 }
2661
2662 if (TargetTriple.isOSHurd()) {
2663 switch (TargetTriple.getArch()) {
2664 case llvm::Triple::x86_64:
2665 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2666 TripleAliases.push_back("x86_64-gnu");
2667 break;
2668 case llvm::Triple::x86:
2669 LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2670 TripleAliases.push_back("i686-gnu");
2671 break;
2672 default:
2673 break;
2674 }
2675
2676 return;
2677 }
2678
2679 switch (TargetTriple.getArch()) {
2680 case llvm::Triple::aarch64:
2681 LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2682 TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
2683 BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2684 BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
2685 break;
2686 case llvm::Triple::aarch64_be:
2687 LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
2688 TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
2689 BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
2690 BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
2691 break;
2692 case llvm::Triple::arm:
2693 case llvm::Triple::thumb:
2694 LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
2695 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF ||
2696 TargetTriple.getEnvironment() == llvm::Triple::MuslEABIHF ||
2697 TargetTriple.getEnvironment() == llvm::Triple::EABIHF) {
2698 TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
2699 } else {
2700 TripleAliases.append(begin(ARMTriples), end(ARMTriples));
2701 }
2702 break;
2703 case llvm::Triple::armeb:
2704 case llvm::Triple::thumbeb:
2705 LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
2706 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF ||
2707 TargetTriple.getEnvironment() == llvm::Triple::MuslEABIHF ||
2708 TargetTriple.getEnvironment() == llvm::Triple::EABIHF) {
2709 TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
2710 } else {
2711 TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
2712 }
2713 break;
2714 case llvm::Triple::avr:
2715 LibDirs.append(begin(AVRLibDirs), end(AVRLibDirs));
2716 TripleAliases.append(begin(AVRTriples), end(AVRTriples));
2717 break;
2718 case llvm::Triple::csky:
2719 LibDirs.append(begin(CSKYLibDirs), end(CSKYLibDirs));
2720 TripleAliases.append(begin(CSKYTriples), end(CSKYTriples));
2721 break;
2722 case llvm::Triple::x86_64:
2723 if (TargetTriple.isX32()) {
2724 LibDirs.append(begin(X32LibDirs), end(X32LibDirs));
2725 TripleAliases.append(begin(X32Triples), end(X32Triples));
2726 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2727 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2728 } else {
2729 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2730 TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2731 BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
2732 BiarchTripleAliases.append(begin(X32Triples), end(X32Triples));
2733 }
2734 BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2735 BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
2736 break;
2737 case llvm::Triple::x86:
2738 LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2739 // MCU toolchain is 32 bit only and its triple alias is TargetTriple
2740 // itself, which will be appended below.
2741 if (!TargetTriple.isOSIAMCU()) {
2742 TripleAliases.append(begin(X86Triples), end(X86Triples));
2743 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2744 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2745 BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
2746 BiarchTripleAliases.append(begin(X32Triples), end(X32Triples));
2747 }
2748 break;
2749 // TODO: Handle loongarch32.
2750 case llvm::Triple::loongarch64:
2751 LibDirs.append(begin(LoongArch64LibDirs), end(LoongArch64LibDirs));
2752 TripleAliases.append(begin(LoongArch64Triples), end(LoongArch64Triples));
2753 break;
2754 case llvm::Triple::m68k:
2755 LibDirs.append(begin(M68kLibDirs), end(M68kLibDirs));
2756 TripleAliases.append(begin(M68kTriples), end(M68kTriples));
2757 break;
2758 case llvm::Triple::mips:
2759 LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
2760 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2761 BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
2762 BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
2763 BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs));
2764 BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples));
2765 break;
2766 case llvm::Triple::mipsel:
2767 LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2768 TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
2769 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2770 BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2771 BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
2772 BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs));
2773 BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples));
2774 break;
2775 case llvm::Triple::mips64:
2776 LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
2777 TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
2778 BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
2779 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2780 BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs));
2781 BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples));
2782 break;
2783 case llvm::Triple::mips64el:
2784 LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2785 TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
2786 BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2787 BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
2788 BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs));
2789 BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples));
2790 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2791 break;
2792 case llvm::Triple::msp430:
2793 LibDirs.append(begin(MSP430LibDirs), end(MSP430LibDirs));
2794 TripleAliases.append(begin(MSP430Triples), end(MSP430Triples));
2795 break;
2796 case llvm::Triple::ppc:
2797 LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
2798 TripleAliases.append(begin(PPCTriples), end(PPCTriples));
2799 BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
2800 BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
2801 break;
2802 case llvm::Triple::ppcle:
2803 LibDirs.append(begin(PPCLELibDirs), end(PPCLELibDirs));
2804 TripleAliases.append(begin(PPCLETriples), end(PPCLETriples));
2805 BiarchLibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
2806 BiarchTripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
2807 break;
2808 case llvm::Triple::ppc64:
2809 LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
2810 TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
2811 BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
2812 BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
2813 break;
2814 case llvm::Triple::ppc64le:
2815 LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
2816 TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
2817 BiarchLibDirs.append(begin(PPCLELibDirs), end(PPCLELibDirs));
2818 BiarchTripleAliases.append(begin(PPCLETriples), end(PPCLETriples));
2819 break;
2820 case llvm::Triple::riscv32:
2821 LibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
2822 TripleAliases.append(begin(RISCV32Triples), end(RISCV32Triples));
2823 BiarchLibDirs.append(begin(RISCV64LibDirs), end(RISCV64LibDirs));
2824 BiarchTripleAliases.append(begin(RISCV64Triples), end(RISCV64Triples));
2825 break;
2826 case llvm::Triple::riscv64:
2827 LibDirs.append(begin(RISCV64LibDirs), end(RISCV64LibDirs));
2828 TripleAliases.append(begin(RISCV64Triples), end(RISCV64Triples));
2829 BiarchLibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
2830 BiarchTripleAliases.append(begin(RISCV32Triples), end(RISCV32Triples));
2831 break;
2832 case llvm::Triple::sparc:
2833 case llvm::Triple::sparcel:
2834 LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
2835 TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
2836 BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
2837 BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
2838 break;
2839 case llvm::Triple::sparcv9:
2840 LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
2841 TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
2842 BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
2843 BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
2844 break;
2845 case llvm::Triple::systemz:
2846 LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
2847 TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
2848 break;
2849 default:
2850 // By default, just rely on the standard lib directories and the original
2851 // triple.
2852 break;
2853 }
2854
2855 // Also include the multiarch variant if it's different.
2856 if (TargetTriple.str() != BiarchTriple.str())
2857 BiarchTripleAliases.push_back(BiarchTriple.str());
2858}
2859
2860bool Generic_GCC::GCCInstallationDetector::ScanGCCForMultilibs(
2861 const llvm::Triple &TargetTriple, const ArgList &Args,
2862 StringRef Path, bool NeedsBiarchSuffix) {
2863 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2864 DetectedMultilibs Detected;
2865
2866 // Android standalone toolchain could have multilibs for ARM and Thumb.
2867 // Debian mips multilibs behave more like the rest of the biarch ones,
2868 // so handle them there
2869 if (isArmOrThumbArch(TargetArch) && TargetTriple.isAndroid()) {
2870 // It should also work without multilibs in a simplified toolchain.
2871 findAndroidArmMultilibs(D, TargetTriple, Path, Args, Detected);
2872 } else if (TargetTriple.isCSKY()) {
2873 findCSKYMultilibs(D, TargetTriple, Path, Args, Detected);
2874 } else if (TargetTriple.isMIPS()) {
2875 if (!findMIPSMultilibs(D, TargetTriple, Path, Args, Detected))
2876 return false;
2877 } else if (TargetTriple.isRISCV()) {
2878 findRISCVMultilibs(D, TargetTriple, Path, Args, Detected);
2879 } else if (isMSP430(TargetArch)) {
2880 findMSP430Multilibs(D, TargetTriple, Path, Args, Detected);
2881 } else if (TargetArch == llvm::Triple::avr) {
2882 // AVR has no multilibs.
2883 } else if (!findBiarchMultilibs(D, TargetTriple, Path, Args,
2884 NeedsBiarchSuffix, Detected)) {
2885 return false;
2886 }
2887
2888 Multilibs = Detected.Multilibs;
2889 SelectedMultilib = Detected.SelectedMultilibs.empty()
2890 ? Multilib()
2891 : Detected.SelectedMultilibs.back();
2892 BiarchSibling = Detected.BiarchSibling;
2893
2894 return true;
2895}
2896
2897void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
2898 const llvm::Triple &TargetTriple, const ArgList &Args,
2899 const std::string &LibDir, StringRef CandidateTriple,
2900 bool NeedsBiarchSuffix, bool GCCDirExists, bool GCCCrossDirExists) {
2901 // Locations relative to the system lib directory where GCC's triple-specific
2902 // directories might reside.
2903 struct GCCLibSuffix {
2904 // Path from system lib directory to GCC triple-specific directory.
2905 std::string LibSuffix;
2906 // Path from GCC triple-specific directory back to system lib directory.
2907 // This is one '..' component per component in LibSuffix.
2908 StringRef ReversePath;
2909 // Whether this library suffix is relevant for the triple.
2910 bool Active;
2911 } Suffixes[] = {
2912 // This is the normal place.
2913 {"gcc/" + CandidateTriple.str(), "../..", GCCDirExists},
2914
2915 // Debian puts cross-compilers in gcc-cross.
2916 {"gcc-cross/" + CandidateTriple.str(), "../..", GCCCrossDirExists},
2917
2918 // The Freescale PPC SDK has the gcc libraries in
2919 // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well. Only do
2920 // this on Freescale triples, though, since some systems put a *lot* of
2921 // files in that location, not just GCC installation data.
2922 {CandidateTriple.str(), "..",
2923 TargetTriple.getVendor() == llvm::Triple::Freescale ||
2924 TargetTriple.getVendor() == llvm::Triple::OpenEmbedded}};
2925
2926 for (auto &Suffix : Suffixes) {
2927 if (!Suffix.Active)
2928 continue;
2929
2930 StringRef LibSuffix = Suffix.LibSuffix;
2931 std::error_code EC;
2932 for (llvm::vfs::directory_iterator
2933 LI = D.getVFS().dir_begin(LibDir + "/" + LibSuffix, EC),
2934 LE;
2935 !EC && LI != LE; LI = LI.increment(EC)) {
2936 StringRef VersionText = llvm::sys::path::filename(LI->path());
2937 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2938 if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2939 if (!CandidateGCCInstallPaths.insert(std::string(LI->path())).second)
2940 continue; // Saw this path before; no need to look at it again.
2941 if (CandidateVersion.isOlderThan(4, 1, 1))
2942 continue;
2943 if (CandidateVersion <= Version)
2944 continue;
2945
2946 if (!ScanGCCForMultilibs(TargetTriple, Args, LI->path(),
2947 NeedsBiarchSuffix))
2948 continue;
2949
2950 Version = CandidateVersion;
2951 GCCTriple.setTriple(CandidateTriple);
2952 // FIXME: We hack together the directory name here instead of
2953 // using LI to ensure stable path separators across Windows and
2954 // Linux.
2955 GCCInstallPath = (LibDir + "/" + LibSuffix + "/" + VersionText).str();
2956 GCCParentLibPath = (GCCInstallPath + "/../" + Suffix.ReversePath).str();
2957 IsValid = true;
2958 }
2959 }
2960}
2961
2962bool Generic_GCC::GCCInstallationDetector::ScanGentooConfigs(
2963 const llvm::Triple &TargetTriple, const ArgList &Args,
2964 const SmallVectorImpl<StringRef> &CandidateTriples,
2965 const SmallVectorImpl<StringRef> &CandidateBiarchTriples) {
2966 if (!D.getVFS().exists(concat(D.SysRoot, GentooConfigDir)))
2967 return false;
2968
2969 for (StringRef CandidateTriple : CandidateTriples) {
2970 if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple))
2971 return true;
2972 }
2973
2974 for (StringRef CandidateTriple : CandidateBiarchTriples) {
2975 if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple, true))
2976 return true;
2977 }
2978 return false;
2979}
2980
2981bool Generic_GCC::GCCInstallationDetector::ScanGentooGccConfig(
2982 const llvm::Triple &TargetTriple, const ArgList &Args,
2983 StringRef CandidateTriple, bool NeedsBiarchSuffix) {
2984 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
2985 D.getVFS().getBufferForFile(concat(D.SysRoot, GentooConfigDir,
2986 "/config-" + CandidateTriple.str()));
2987 if (File) {
2989 File.get()->getBuffer().split(Lines, "\n");
2990 for (StringRef Line : Lines) {
2991 Line = Line.trim();
2992 // CURRENT=triple-version
2993 if (!Line.consume_front("CURRENT="))
2994 continue;
2995 // Process the config file pointed to by CURRENT.
2996 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ConfigFile =
2997 D.getVFS().getBufferForFile(
2998 concat(D.SysRoot, GentooConfigDir, "/" + Line));
2999 std::pair<StringRef, StringRef> ActiveVersion = Line.rsplit('-');
3000 // List of paths to scan for libraries.
3001 SmallVector<StringRef, 4> GentooScanPaths;
3002 // Scan the Config file to find installed GCC libraries path.
3003 // Typical content of the GCC config file:
3004 // LDPATH="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x:/usr/lib/gcc/
3005 // (continued from previous line) x86_64-pc-linux-gnu/4.9.x/32"
3006 // MANPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/man"
3007 // INFOPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/info"
3008 // STDCXX_INCDIR="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x/include/g++-v4"
3009 // We are looking for the paths listed in LDPATH=... .
3010 if (ConfigFile) {
3011 SmallVector<StringRef, 2> ConfigLines;
3012 ConfigFile.get()->getBuffer().split(ConfigLines, "\n");
3013 for (StringRef ConfLine : ConfigLines) {
3014 ConfLine = ConfLine.trim();
3015 if (ConfLine.consume_front("LDPATH=")) {
3016 // Drop '"' from front and back if present.
3017 ConfLine.consume_back("\"");
3018 ConfLine.consume_front("\"");
3019 // Get all paths sperated by ':'
3020 ConfLine.split(GentooScanPaths, ':', -1, /*AllowEmpty*/ false);
3021 }
3022 }
3023 }
3024 // Test the path based on the version in /etc/env.d/gcc/config-{tuple}.
3025 std::string basePath = "/usr/lib/gcc/" + ActiveVersion.first.str() + "/"
3026 + ActiveVersion.second.str();
3027 GentooScanPaths.push_back(StringRef(basePath));
3028
3029 // Scan all paths for GCC libraries.
3030 for (const auto &GentooScanPath : GentooScanPaths) {
3031 std::string GentooPath = concat(D.SysRoot, GentooScanPath);
3032 if (D.getVFS().exists(GentooPath + "/crtbegin.o")) {
3033 if (!ScanGCCForMultilibs(TargetTriple, Args, GentooPath,
3034 NeedsBiarchSuffix))
3035 continue;
3036
3037 Version = GCCVersion::Parse(ActiveVersion.second);
3038 GCCInstallPath = GentooPath;
3039 GCCParentLibPath = GentooPath + std::string("/../../..");
3040 GCCTriple.setTriple(ActiveVersion.first);
3041 IsValid = true;
3042 return true;
3043 }
3044 }
3045 }
3046 }
3047
3048 return false;
3049}
3050
3051Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple,
3052 const ArgList &Args)
3053 : ToolChain(D, Triple, Args), GCCInstallation(D),
3054 CudaInstallation(D, Triple, Args), RocmInstallation(D, Triple, Args) {
3055 getProgramPaths().push_back(getDriver().Dir);
3056}
3057
3059
3061 switch (AC) {
3063 if (!Preprocess)
3064 Preprocess.reset(new clang::driver::tools::gcc::Preprocessor(*this));
3065 return Preprocess.get();
3067 if (!Compile)
3068 Compile.reset(new tools::gcc::Compiler(*this));
3069 return Compile.get();
3070 default:
3071 return ToolChain::getTool(AC);
3072 }
3073}
3074
3076 return new tools::gnutools::Assembler(*this);
3077}
3078
3079Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); }
3080
3081void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
3082 // Print the information about how we detected the GCC installation.
3084 CudaInstallation->print(OS);
3085 RocmInstallation->print(OS);
3086}
3087
3090 switch (getArch()) {
3091 case llvm::Triple::aarch64:
3092 case llvm::Triple::aarch64_be:
3093 case llvm::Triple::ppc:
3094 case llvm::Triple::ppcle:
3095 case llvm::Triple::ppc64:
3096 case llvm::Triple::ppc64le:
3097 case llvm::Triple::riscv32:
3098 case llvm::Triple::riscv64:
3099 case llvm::Triple::x86:
3100 case llvm::Triple::x86_64:
3102 default:
3104 }
3105}
3106
3108 switch (getArch()) {
3109 case llvm::Triple::x86_64:
3110 return getTriple().isOSWindows();
3111 case llvm::Triple::mips64:
3112 case llvm::Triple::mips64el:
3113 return true;
3114 default:
3115 return false;
3116 }
3117}
3118
3119bool Generic_GCC::isPIEDefault(const llvm::opt::ArgList &Args) const {
3120 return false;
3121}
3122
3124 return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
3125}
3126
3128 switch (getTriple().getArch()) {
3129 case llvm::Triple::nvptx:
3130 case llvm::Triple::nvptx64:
3131 case llvm::Triple::xcore:
3132 return false;
3133 default:
3134 return true;
3135 }
3136}
3137
3139 // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
3140 // least) put various tools in a triple-prefixed directory off of the parent
3141 // of the GCC installation. We use the GCC triple here to ensure that we end
3142 // up with tools that support the same amount of cross compiling as the
3143 // detected GCC installation. For example, if we find a GCC installation
3144 // targeting x86_64, but it is a bi-arch GCC installation, it can also be
3145 // used to target i386.
3146 if (GCCInstallation.isValid()) {
3147 PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
3148 GCCInstallation.getTriple().str() + "/bin")
3149 .str());
3150 }
3151}
3152
3154 const std::string &SysRoot,
3155 const std::string &OSLibDir,
3156 const std::string &MultiarchTriple,
3157 path_list &Paths) {
3158 // Add the multilib suffixed paths where they are available.
3159 if (GCCInstallation.isValid()) {
3160 assert(!SelectedMultilibs.empty());
3161 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3162 const std::string &LibPath =
3163 std::string(GCCInstallation.getParentLibPath());
3164
3165 // Sourcery CodeBench MIPS toolchain holds some libraries under
3166 // a biarch-like suffix of the GCC installation.
3167 if (const auto &PathsCallback = Multilibs.filePathsCallback())
3168 for (const auto &Path : PathsCallback(SelectedMultilibs.back()))
3169 addPathIfExists(D, GCCInstallation.getInstallPath() + Path, Paths);
3170
3171 // Add lib/gcc/$triple/$version, with an optional /multilib suffix.
3172 addPathIfExists(D,
3174 SelectedMultilibs.back().gccSuffix(),
3175 Paths);
3176
3177 // Add lib/gcc/$triple/$libdir
3178 // For GCC built with --enable-version-specific-runtime-libs.
3179 addPathIfExists(D, GCCInstallation.getInstallPath() + "/../" + OSLibDir,
3180 Paths);
3181
3182 // GCC cross compiling toolchains will install target libraries which ship
3183 // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
3184 // any part of the GCC installation in
3185 // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
3186 // debatable, but is the reality today. We need to search this tree even
3187 // when we have a sysroot somewhere else. It is the responsibility of
3188 // whomever is doing the cross build targeting a sysroot using a GCC
3189 // installation that is *not* within the system root to ensure two things:
3190 //
3191 // 1) Any DSOs that are linked in from this tree or from the install path
3192 // above must be present on the system root and found via an
3193 // appropriate rpath.
3194 // 2) There must not be libraries installed into
3195 // <prefix>/<triple>/<libdir> unless they should be preferred over
3196 // those within the system root.
3197 //
3198 // Note that this matches the GCC behavior. See the below comment for where
3199 // Clang diverges from GCC's behavior.
3200 addPathIfExists(D,
3201 LibPath + "/../" + GCCTriple.str() + "/lib/../" + OSLibDir +
3202 SelectedMultilibs.back().osSuffix(),
3203 Paths);
3204
3205 // If the GCC installation we found is inside of the sysroot, we want to
3206 // prefer libraries installed in the parent prefix of the GCC installation.
3207 // It is important to *not* use these paths when the GCC installation is
3208 // outside of the system root as that can pick up unintended libraries.
3209 // This usually happens when there is an external cross compiler on the
3210 // host system, and a more minimal sysroot available that is the target of
3211 // the cross. Note that GCC does include some of these directories in some
3212 // configurations but this seems somewhere between questionable and simply
3213 // a bug.
3214 if (StringRef(LibPath).starts_with(SysRoot))
3215 addPathIfExists(D, LibPath + "/../" + OSLibDir, Paths);
3216 }
3217}
3218
3220 const std::string &SysRoot,
3221 const std::string &OSLibDir,
3222 path_list &Paths) {
3223 if (GCCInstallation.isValid()) {
3224 const std::string &LibPath =
3225 std::string(GCCInstallation.getParentLibPath());
3226 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3228 addPathIfExists(
3229 D, LibPath + "/../" + GCCTriple.str() + "/lib" + Multilib.osSuffix(),
3230 Paths);
3231 }
3232}
3233
3234void Generic_GCC::AddMultilibIncludeArgs(const ArgList &DriverArgs,
3235 ArgStringList &CC1Args) const {
3236 // Add include directories specific to the selected multilib set and multilib.
3237 if (!GCCInstallation.isValid())
3238 return;
3239 // gcc TOOL_INCLUDE_DIR.
3240 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3241 std::string LibPath(GCCInstallation.getParentLibPath());
3242 addSystemInclude(DriverArgs, CC1Args,
3243 Twine(LibPath) + "/../" + GCCTriple.str() + "/include");
3244
3245 const auto &Callback = Multilibs.includeDirsCallback();
3246 if (Callback) {
3247 for (const auto &Path : Callback(GCCInstallation.getMultilib()))
3248 addExternCSystemIncludeIfExists(DriverArgs, CC1Args,
3250 }
3251}
3252
3253void Generic_GCC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3254 ArgStringList &CC1Args) const {
3255 if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdincxx,
3256 options::OPT_nostdlibinc))
3257 return;
3258
3259 switch (GetCXXStdlibType(DriverArgs)) {
3261 addLibCxxIncludePaths(DriverArgs, CC1Args);
3262 break;
3263
3265 addLibStdCxxIncludePaths(DriverArgs, CC1Args);
3266 break;
3267 }
3268}
3269
3270void
3271Generic_GCC::addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3272 llvm::opt::ArgStringList &CC1Args) const {
3273 const Driver &D = getDriver();
3274 std::string SysRoot = computeSysRoot();
3275 if (SysRoot.empty())
3276 SysRoot = llvm::sys::path::get_separator();
3277
3278 auto AddIncludePath = [&](StringRef Path, bool TargetDirRequired = false) {
3279 std::string Version = detectLibcxxVersion(Path);
3280 if (Version.empty())
3281 return false;
3282
3283 // First add the per-target include path if it exists.
3284 bool TargetDirExists = false;
3285 std::optional<std::string> TargetIncludeDir = getTargetSubDirPath(Path);
3286 if (TargetIncludeDir) {
3287 SmallString<128> TargetDir(*TargetIncludeDir);
3288 llvm::sys::path::append(TargetDir, "c++", Version);
3289 if (D.getVFS().exists(TargetDir)) {
3290 addSystemInclude(DriverArgs, CC1Args, TargetDir);
3291 TargetDirExists = true;
3292 }
3293 }
3294 if (TargetDirRequired && !TargetDirExists)
3295 return false;
3296
3297 // Second add the generic one.
3298 SmallString<128> GenericDir(Path);
3299 llvm::sys::path::append(GenericDir, "c++", Version);
3300 addSystemInclude(DriverArgs, CC1Args, GenericDir);
3301 return true;
3302 };
3303
3304 // Android only uses the libc++ headers installed alongside the toolchain if
3305 // they contain an Android-specific target include path, otherwise they're
3306 // incompatible with the NDK libraries.
3307 SmallString<128> DriverIncludeDir(getDriver().Dir);
3308 llvm::sys::path::append(DriverIncludeDir, "..", "include");
3309 if (AddIncludePath(DriverIncludeDir,
3310 /*TargetDirRequired=*/getTriple().isAndroid()))
3311 return;
3312 // If this is a development, non-installed, clang, libcxx will
3313 // not be found at ../include/c++ but it likely to be found at
3314 // one of the following two locations:
3315 SmallString<128> UsrLocalIncludeDir(SysRoot);
3316 llvm::sys::path::append(UsrLocalIncludeDir, "usr", "local", "include");
3317 if (AddIncludePath(UsrLocalIncludeDir))
3318 return;
3319 SmallString<128> UsrIncludeDir(SysRoot);
3320 llvm::sys::path::append(UsrIncludeDir, "usr", "include");
3321 if (AddIncludePath(UsrIncludeDir))
3322 return;
3323}
3324
3325bool Generic_GCC::addLibStdCXXIncludePaths(Twine IncludeDir, StringRef Triple,
3326 Twine IncludeSuffix,
3327 const llvm::opt::ArgList &DriverArgs,
3328 llvm::opt::ArgStringList &CC1Args,
3329 bool DetectDebian) const {
3330 if (!getVFS().exists(IncludeDir))
3331 return false;
3332
3333 // Debian native gcc uses g++-multiarch-incdir.diff which uses
3334 // include/x86_64-linux-gnu/c++/10$IncludeSuffix instead of
3335 // include/c++/10/x86_64-linux-gnu$IncludeSuffix.
3336 std::string Dir = IncludeDir.str();
3337 StringRef Include =
3338 llvm::sys::path::parent_path(llvm::sys::path::parent_path(Dir));
3339 std::string Path =
3340 (Include + "/" + Triple + Dir.substr(Include.size()) + IncludeSuffix)
3341 .str();
3342 if (DetectDebian && !getVFS().exists(Path))
3343 return false;
3344
3345 // GPLUSPLUS_INCLUDE_DIR
3346 addSystemInclude(DriverArgs, CC1Args, IncludeDir);
3347 // GPLUSPLUS_TOOL_INCLUDE_DIR. If Triple is not empty, add a target-dependent
3348 // include directory.
3349 if (DetectDebian)
3350 addSystemInclude(DriverArgs, CC1Args, Path);
3351 else if (!Triple.empty())
3352 addSystemInclude(DriverArgs, CC1Args,
3353 IncludeDir + "/" + Triple + IncludeSuffix);
3354 // GPLUSPLUS_BACKWARD_INCLUDE_DIR
3355 addSystemInclude(DriverArgs, CC1Args, IncludeDir + "/backward");
3356 return true;
3357}
3358
3360 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
3361 StringRef DebianMultiarch) const {
3362 assert(GCCInstallation.isValid());
3363
3364 // By default, look for the C++ headers in an include directory adjacent to
3365 // the lib directory of the GCC installation. Note that this is expect to be
3366 // equivalent to '/usr/include/c++/X.Y' in almost all cases.
3367 StringRef LibDir = GCCInstallation.getParentLibPath();
3368 StringRef InstallDir = GCCInstallation.getInstallPath();
3369 StringRef TripleStr = GCCInstallation.getTriple().str();
3371 const GCCVersion &Version = GCCInstallation.getVersion();
3372
3373 // Try /../$triple/include/c++/$version (gcc --print-multiarch is not empty).
3375 LibDir.str() + "/../" + TripleStr + "/include/c++/" + Version.Text,
3376 TripleStr, Multilib.includeSuffix(), DriverArgs, CC1Args))
3377 return true;
3378
3379 // Try /gcc/$triple/$version/include/c++/ (gcc --print-multiarch is not
3380 // empty). Like above but for GCC built with
3381 // --enable-version-specific-runtime-libs.
3382 if (addLibStdCXXIncludePaths(LibDir.str() + "/gcc/" + TripleStr + "/" +
3383 Version.Text + "/include/c++/",
3384 TripleStr, Multilib.includeSuffix(), DriverArgs,
3385 CC1Args))
3386 return true;
3387
3388 // Detect Debian g++-multiarch-incdir.diff.
3389 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include/c++/" + Version.Text,
3390 DebianMultiarch, Multilib.includeSuffix(),
3391 DriverArgs, CC1Args, /*Debian=*/true))
3392 return true;
3393
3394 // Try /../include/c++/$version (gcc --print-multiarch is empty).
3395 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include/c++/" + Version.Text,
3396 TripleStr, Multilib.includeSuffix(), DriverArgs,
3397 CC1Args))
3398 return true;
3399
3400 // Otherwise, fall back on a bunch of options which don't use multiarch
3401 // layouts for simplicity.
3402 const std::string LibStdCXXIncludePathCandidates[] = {
3403 // Gentoo is weird and places its headers inside the GCC install,
3404 // so if the first attempt to find the headers fails, try these patterns.
3405 InstallDir.str() + "/include/g++-v" + Version.Text,
3406 InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
3407 Version.MinorStr,
3408 InstallDir.str() + "/include/g++-v" + Version.MajorStr,
3409 };
3410
3411 for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
3412 if (addLibStdCXXIncludePaths(IncludePath, TripleStr,
3413 Multilib.includeSuffix(), DriverArgs, CC1Args))
3414 return true;
3415 }
3416 return false;
3417}
3418
3419void
3420Generic_GCC::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3421 llvm::opt::ArgStringList &CC1Args) const {
3422 if (GCCInstallation.isValid()) {
3423 addGCCLibStdCxxIncludePaths(DriverArgs, CC1Args,
3424 GCCInstallation.getTriple().str());
3425 }
3426}
3427
3428llvm::opt::DerivedArgList *
3429Generic_GCC::TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef,
3430 Action::OffloadKind DeviceOffloadKind) const {
3431
3432 // If this tool chain is used for an OpenMP offloading device we have to make
3433 // sure we always generate a shared library regardless of the commands the
3434 // user passed to the host. This is required because the runtime library
3435 // is required to load the device image dynamically at run time.
3436 if (DeviceOffloadKind == Action::OFK_OpenMP) {
3437 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
3438 const OptTable &Opts = getDriver().getOpts();
3439
3440 // Request the shared library. Given that these options are decided
3441 // implicitly, they do not refer to any base argument.
3442 DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_shared));
3443 DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_fPIC));
3444
3445 // Filter all the arguments we don't care passing to the offloading
3446 // toolchain as they can mess up with the creation of a shared library.
3447 for (auto *A : Args) {
3448 switch ((options::ID)A->getOption().getID()) {
3449 default:
3450 DAL->append(A);
3451 break;
3452 case options::OPT_shared:
3453 case options::OPT_dynamic:
3454 case options::OPT_static:
3455 case options::OPT_fPIC:
3456 case options::OPT_fno_PIC:
3457 case options::OPT_fpic:
3458 case options::OPT_fno_pic:
3459 case options::OPT_fPIE:
3460 case options::OPT_fno_PIE:
3461 case options::OPT_fpie:
3462 case options::OPT_fno_pie:
3463 break;
3464 }
3465 }
3466 return DAL;
3467 }
3468 return nullptr;
3469}
3470
3471void Generic_ELF::anchor() {}
3472
3473void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
3474 ArgStringList &CC1Args,
3475 Action::OffloadKind) const {
3476 if (!DriverArgs.hasFlag(options::OPT_fuse_init_array,
3477 options::OPT_fno_use_init_array, true))
3478 CC1Args.push_back("-fno-use-init-array");
3479}
StringRef P
static bool findRISCVMultilibs(const Driver &D, const llvm::Triple &TargetTriple, const ArgList &Args, DetectedMultilibs &Result)
Definition: BareMetal.cpp:36
static constexpr CPUSuffix Suffixes[]
Definition: Hexagon.cpp:231
const Decl * D
IndirectLocalPath & Path
bool IsStatic
Definition: Format.cpp:3001
static void findCSKYMultilibs(const Driver &D, const llvm::Triple &TargetTriple, StringRef Path, const ArgList &Args, DetectedMultilibs &Result)
Definition: Gnu.cpp:1664
static void findAndroidArmMultilibs(const Driver &D, const llvm::Triple &TargetTriple, StringRef Path, const ArgList &Args, DetectedMultilibs &Result)
Definition: Gnu.cpp:1593
static bool isArmOrThumbArch(llvm::Triple::ArchType Arch)
Definition: Gnu.cpp:1022
static void normalizeCPUNamesForAssembler(const ArgList &Args, ArgStringList &CmdArgs)
Definition: Gnu.cpp:56
static bool findBiarchMultilibs(const Driver &D, const llvm::Triple &TargetTriple, StringRef Path, const ArgList &Args, bool NeedsBiarchSuffix, DetectedMultilibs &Result)
Definition: Gnu.cpp:1944
static bool isMips16(const ArgList &Args)
Definition: Gnu.cpp:1030
static llvm::StringRef getGCCToolchainDir(const ArgList &Args, llvm::StringRef SysRoot)
Definition: Gnu.cpp:2195
static bool findMSP430Multilibs(const Driver &D, const llvm::Triple &TargetTriple, StringRef Path, const ArgList &Args, DetectedMultilibs &Result)
Definition: Gnu.cpp:1636
static bool getStatic(const ArgList &Args)
Definition: Gnu.cpp:308
static bool selectRISCVMultilib(const MultilibSet &RISCVMultilibSet, StringRef Arch, const Multilib::flags_list &Flags, llvm::SmallVectorImpl< Multilib > &SelectedMultilibs)
Extend the multi-lib re-use selection mechanism for RISC-V.
Definition: Gnu.cpp:1740
static bool findMipsCsMultilibs(const Multilib::flags_list &Flags, FilterNonExistent &NonExistent, DetectedMultilibs &Result)
Definition: Gnu.cpp:1044
static bool findMipsMtiMultilibs(const Multilib::flags_list &Flags, FilterNonExistent &NonExistent, DetectedMultilibs &Result)
Definition: Gnu.cpp:1228
static bool isMipsEL(llvm::Triple::ArchType Arch)
Definition: Gnu.cpp:1026
static const char * getLDMOption(const llvm::Triple &T, const ArgList &Args)
Definition: Gnu.cpp:224
static bool findMipsMuslMultilibs(const Multilib::flags_list &Flags, FilterNonExistent &NonExistent, DetectedMultilibs &Result)
Definition: Gnu.cpp:1194
static void findRISCVBareMetalMultilibs(const Driver &D, const llvm::Triple &TargetTriple, StringRef Path, const ArgList &Args, DetectedMultilibs &Result)
Definition: Gnu.cpp:1846
static bool findMipsAndroidMultilibs(llvm::vfs::FileSystem &VFS, StringRef Path, const Multilib::flags_list &Flags, FilterNonExistent &NonExistent, DetectedMultilibs &Result)
Definition: Gnu.cpp:1148
static bool isMSP430(llvm::Triple::ArchType Arch)
Definition: Gnu.cpp:1040
static bool isSoftFloatABI(const ArgList &Args)
Definition: Gnu.cpp:1011
static bool findMipsImgMultilibs(const Multilib::flags_list &Flags, FilterNonExistent &NonExistent, DetectedMultilibs &Result)
Definition: Gnu.cpp:1414
static bool getStaticPIE(const ArgList &Args, const ToolChain &TC)
Definition: Gnu.cpp:296
static bool forwardToGCC(const Option &O)
Definition: Gnu.cpp:46
static bool isMicroMips(const ArgList &Args)
Definition: Gnu.cpp:1035
types::ID getType() const
Definition: Action.h:148
bool isHostOffloading(unsigned int OKind) const
Check if this action have any offload kinds.
Definition: Action.h:218
Compilation - A set of tasks to perform for a single driver invocation.
Definition: Compilation.h:45
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:77
const llvm::opt::OptTable & getOpts() const
Definition: Driver.h:399
InputInfo - Wrapper for information about an input source.
Definition: InputInfo.h:22
const char * getFilename() const
Definition: InputInfo.h:83
bool isNothing() const
Definition: InputInfo.h:74
bool isFilename() const
Definition: InputInfo.h:75
This corresponds to a single GCC multilib, or a segment of one controlled by a command line flag.
MultilibBuilder & flag(StringRef Flag, bool Disallow=false)
Add a flag to the flags list Flag must be a flag accepted by the driver.
const std::string & gccSuffix() const
Get the detected GCC installation path suffix for the multi-arch target variant.
const std::string & osSuffix() const
Get the detected os path suffix for the multi-arch target variant.
This class can be used to create a MultilibSet, and contains helper functions to add combinations of ...
MultilibSetBuilder & Maybe(const MultilibBuilder &M)
Add an optional Multilib segment.
MultilibSetBuilder & FilterOut(const char *Regex)
Filter out those Multilibs whose gccSuffix matches the given expression.
MultilibSetBuilder & Either(const MultilibBuilder &M1, const MultilibBuilder &M2)
Add a set of mutually incompatible Multilib segments.
See also MultilibSetBuilder for combining multilibs into a set.
Definition: Multilib.h:92
MultilibSet & setFilePathsCallback(IncludeDirsFunc F)
Definition: Multilib.h:152
unsigned size() const
Definition: Multilib.h:135
MultilibSet & FilterOut(FilterCallback F)
Filter out some subset of the Multilibs using a user defined callback.
Definition: Multilib.cpp:90
const IncludeDirsFunc & filePathsCallback() const
Definition: Multilib.h:157
bool select(const Multilib::flags_list &Flags, llvm::SmallVectorImpl< Multilib > &) const
Select compatible variants,.
Definition: Multilib.cpp:97
const IncludeDirsFunc & includeDirsCallback() const
Definition: Multilib.h:150
MultilibSet & setIncludeDirsCallback(IncludeDirsFunc F)
Definition: Multilib.h:145
This corresponds to a single GCC Multilib, or a segment of one controlled by a command line flag.
Definition: Multilib.h:32
const std::string & gccSuffix() const
Get the detected GCC installation path suffix for the multi-arch target variant.
Definition: Multilib.h:61
const std::string & osSuffix() const
Get the detected os path suffix for the multi-arch target variant.
Definition: Multilib.h:65
std::vector< std::string > flags_list
Definition: Multilib.h:34
const std::string & includeSuffix() const
Get the include directory suffix.
Definition: Multilib.h:69
bool isDefault() const
Check whether the default is selected.
Definition: Multilib.h:83
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:92
static void addSystemInclude(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Utility function to add a system include directory to CC1 arguments.
Definition: ToolChain.cpp:1179
virtual std::string computeSysRoot() const
Return the sysroot, possibly searching for a default sysroot using target-specific logic.
Definition: ToolChain.cpp:1065
virtual RuntimeLibType GetRuntimeLibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:1091
bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const
Returns if the C++ standard library should be linked in.
Definition: ToolChain.cpp:1281
std::string GetFilePath(const char *Name) const
Definition: ToolChain.cpp:870
llvm::Triple::ArchType getArch() const
Definition: ToolChain.h:269
const Driver & getDriver() const
Definition: ToolChain.h:253
virtual std::string detectLibcxxVersion(StringRef IncludePath) const
Definition: ToolChain.cpp:1226
llvm::vfs::FileSystem & getVFS() const
Definition: ToolChain.cpp:141
virtual bool isPIEDefault(const llvm::opt::ArgList &Args) const =0
Test whether this toolchain defaults to PIE.
bool addFastMathRuntimeIfAvailable(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddFastMathRuntimeIfAvailable - If a runtime library exists that sets global flags for unsafe floatin...
Definition: ToolChain.cpp:1354
path_list & getProgramPaths()
Definition: ToolChain.h:298
static void addExternCSystemIncludeIfExists(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Definition: ToolChain.cpp:1201
virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
Definition: ToolChain.cpp:1287
const llvm::Triple & getTriple() const
Definition: ToolChain.h:255
std::optional< std::string > getTargetSubDirPath(StringRef BaseDir) const
Find the target-specific subdirectory for the current target triple under BaseDir,...
Definition: ToolChain.cpp:759
std::string GetLinkerPath(bool *LinkerIsLLD=nullptr) const
Returns the linker path, respecting the -fuse-ld= argument to determine the linker suffix or name.
Definition: ToolChain.cpp:878
virtual std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
Definition: ToolChain.cpp:677
void AddFilePathLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddFilePathLibArgs - Add each thing in getFilePaths() as a "-L" option.
Definition: ToolChain.cpp:1306
std::string getTripleString() const
Definition: ToolChain.h:278
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:1153
llvm::SmallVector< Multilib > SelectedMultilibs
Definition: ToolChain.h:201
virtual Tool * getTool(Action::ActionClass AC) const
Definition: ToolChain.cpp:532
Tool - Information on a specific compilation tool.
Definition: Tool.h:32
const ToolChain & getToolChain() const
Definition: Tool.h:52
void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, Action::OffloadKind DeviceOffloadKind) const override
Add options that need to be passed to cc1 for this target.
Definition: Gnu.cpp:3473
void print(raw_ostream &OS) const
Print information about the detected GCC installation.
Definition: Gnu.cpp:2358
const Multilib & getMultilib() const
Get the detected Multilib.
Definition: Gnu.h:236
const llvm::Triple & getTriple() const
Get the GCC triple for the detected install.
Definition: Gnu.h:227
bool isValid() const
Check whether we detected a valid GCC install.
Definition: Gnu.h:224
bool getBiarchSibling(Multilib &M) const
Get the biarch sibling multilib (if it exists).
Definition: Gnu.cpp:2372
void init(const llvm::Triple &TargetTriple, const llvm::opt::ArgList &Args)
Initialize a GCCInstallationDetector from the driver.
Definition: Gnu.cpp:2219
StringRef getParentLibPath() const
Get the detected GCC parent lib path.
Definition: Gnu.h:233
StringRef getInstallPath() const
Get the detected GCC installation path.
Definition: Gnu.h:230
const GCCVersion & getVersion() const
Get the detected GCC version string.
Definition: Gnu.h:246
llvm::opt::DerivedArgList * TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const override
TranslateArgs - Create a new derived argument list for any argument translations this ToolChain may w...
Definition: Gnu.cpp:3429
void AddMultilibPaths(const Driver &D, const std::string &SysRoot, const std::string &OSLibDir, const std::string &MultiarchTriple, path_list &Paths)
Definition: Gnu.cpp:3153
bool addGCCLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, StringRef DebianMultiarch) const
Definition: Gnu.cpp:3359
LazyDetector< CudaInstallationDetector > CudaInstallation
Definition: Gnu.h:289
void PushPPaths(ToolChain::path_list &PPaths)
Definition: Gnu.cpp:3138
Tool * getTool(Action::ActionClass AC) const override
Definition: Gnu.cpp:3060
Generic_GCC(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Definition: Gnu.cpp:3051
GCCInstallationDetector GCCInstallation
Definition: Gnu.h:288
void AddMultilibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Definition: Gnu.cpp:3234
bool IsIntegratedAssemblerDefault() const override
IsIntegratedAssemblerDefault - Does this tool chain enable -integrated-as by default.
Definition: Gnu.cpp:3127
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
Definition: Gnu.cpp:3253
Tool * buildLinker() const override
Definition: Gnu.cpp:3079
bool isPICDefaultForced() const override
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
Definition: Gnu.cpp:3123
bool isPIEDefault(const llvm::opt::ArgList &Args) const override
Test whether this toolchain defaults to PIE.
Definition: Gnu.cpp:3119
void printVerboseInfo(raw_ostream &OS) const override
Dispatch to the specific toolchain for verbose printing.
Definition: Gnu.cpp:3081
void AddMultiarchPaths(const Driver &D, const std::string &SysRoot, const std::string &OSLibDir, path_list &Paths)
Definition: Gnu.cpp:3219
Tool * buildAssembler() const override
Definition: Gnu.cpp:3075
UnwindTableLevel getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const override
How detailed should the unwind tables be by default.
Definition: Gnu.cpp:3089
bool addLibStdCXXIncludePaths(Twine IncludeDir, StringRef Triple, Twine IncludeSuffix, const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, bool DetectDebian=false) const
Definition: Gnu.cpp:3325
bool isPICDefault() const override
Test whether this toolchain defaults to PIC.
Definition: Gnu.cpp:3107
virtual void addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Definition: Gnu.cpp:3271
LazyDetector< RocmInstallationDetector > RocmInstallation
Definition: Gnu.h:290
virtual void addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Definition: Gnu.cpp:3420
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition: Gnu.cpp:69
virtual void RenderExtraToolArgs(const JobAction &JA, llvm::opt::ArgStringList &CmdArgs) const =0
RenderExtraToolArgs - Render any arguments necessary to force the particular tool mode.
void RenderExtraToolArgs(const JobAction &JA, llvm::opt::ArgStringList &CmdArgs) const override
RenderExtraToolArgs - Render any arguments necessary to force the particular tool mode.
Definition: Gnu.cpp:191
void RenderExtraToolArgs(const JobAction &JA, llvm::opt::ArgStringList &CmdArgs) const override
RenderExtraToolArgs - Render any arguments necessary to force the particular tool mode.
Definition: Gnu.cpp:219
void RenderExtraToolArgs(const JobAction &JA, llvm::opt::ArgStringList &CmdArgs) const override
RenderExtraToolArgs - Render any arguments necessary to force the particular tool mode.
Definition: Gnu.cpp:186
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition: Gnu.cpp:683
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition: Gnu.cpp:357
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition: Gnu.cpp:313
void appendBE8LinkFlag(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple)
FloatABI getARMFloatABI(const ToolChain &TC, const llvm::opt::ArgList &Args)
bool isARMBigEndian(const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
FloatABI getCSKYFloatABI(const Driver &D, const llvm::opt::ArgList &Args)
std::optional< llvm::StringRef > getCSKYArchName(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
StringRef getLoongArchABI(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
StringRef getGnuCompatibleMipsABIName(StringRef ABI)
Definition: Mips.cpp:137
bool isNaN2008(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
bool hasMipsAbiArg(const llvm::opt::ArgList &Args, const char *Value)
mips::FloatABI getMipsFloatABI(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
bool shouldUseFPXX(const llvm::opt::ArgList &Args, const llvm::Triple &Triple, StringRef CPUName, StringRef ABIName, mips::FloatABI FloatABI)
bool isUCLibc(const llvm::opt::ArgList &Args)
void getMipsCPUAndABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple, StringRef &CPUName, StringRef &ABIName)
const char * getPPCAsmModeForCPU(StringRef Name)
Definition: PPC.cpp:95
std::string getRISCVArch(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition: RISCV.cpp:276
StringRef getRISCVABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
const char * getSparcAsmModeForCPU(llvm::StringRef Name, const llvm::Triple &Triple)
std::string getSystemZTargetCPU(const llvm::opt::ArgList &Args)
const char * SplitDebugName(const JobAction &JA, const llvm::opt::ArgList &Args, const InputInfo &Input, const InputInfo &Output)
std::string getCPUName(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &T, bool FromAs=false)
void addHIPRuntimeLibArgs(const ToolChain &TC, Compilation &C, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
void addMultilibFlag(bool Enabled, const StringRef Flag, Multilib::flags_list &Flags)
Flag must be a flag accepted by the driver.
void linkXRayRuntimeDeps(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
void AddRunTimeLibs(const ToolChain &TC, const Driver &D, llvm::opt::ArgStringList &CmdArgs, const llvm::opt::ArgList &Args)
void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T, const JobAction &JA, const llvm::opt::ArgList &Args, const InputInfo &Output, const char *OutFile)
void linkSanitizerRuntimeDeps(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
bool addSanitizerRuntimes(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
bool addXRayRuntime(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
void AddAssemblerKPIC(const ToolChain &ToolChain, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
void addPathIfExists(const Driver &D, const Twine &Path, ToolChain::path_list &Paths)
Definition: CommonArgs.cpp:340
void addFortranRuntimeLibraryPath(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Adds the path for the Fortran runtime libraries to CmdArgs.
void addLinkerCompressDebugSectionsOption(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Definition: CommonArgs.cpp:494
void addLTOOptions(const ToolChain &ToolChain, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const InputInfo &Output, const InputInfo &Input, bool IsThinLTO)
bool addOpenMPRuntime(const Compilation &C, llvm::opt::ArgStringList &CmdArgs, const ToolChain &TC, const llvm::opt::ArgList &Args, bool ForceStaticHostRuntime=false, bool IsOffloadingHost=false, bool GompNeedsRT=false)
Returns true, if an OpenMP runtime has been added.
std::tuple< llvm::Reloc::Model, unsigned, bool > ParsePICArgs(const ToolChain &ToolChain, const llvm::opt::ArgList &Args)
void claimNoWarnArgs(const llvm::opt::ArgList &Args)
void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const JobAction &JA)
unsigned getDwarfVersion(const ToolChain &TC, const llvm::opt::ArgList &Args)
void addFortranRuntimeLibs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Adds Fortran runtime libraries to CmdArgs.
bool isLLVMIR(ID Id)
Is this LLVM IR.
Definition: Types.cpp:255
const char * getTypeName(ID Id)
getTypeName - Return the name of the type for Id.
Definition: Types.cpp:52
bool canTypeBeUserSpecified(ID Id)
canTypeBeUserSpecified - Can this type be specified on the command line (by the type name); this is u...
Definition: Types.cpp:105
bool findMIPSMultilibs(const Driver &D, const llvm::Triple &TargetTriple, StringRef Path, const llvm::opt::ArgList &Args, DetectedMultilibs &Result)
The JSON file list parser is used to communicate input to InstallAPI.
@ Result
The result type of a method or function.
const FunctionProtoType * T
MultilibSet Multilibs
The set of multilibs that the detected installation supports.
Definition: Gnu.h:24
std::optional< Multilib > BiarchSibling
On Biarch systems, this corresponds to the default multilib when targeting the non-default multilib.
Definition: Gnu.h:31
llvm::SmallVector< Multilib > SelectedMultilibs
The multilibs appropriate for the given flags.
Definition: Gnu.h:27
static constexpr ResponseFileSupport AtFileCurCP()
Definition: Job.h:92
Struct to store and manipulate GCC versions.
Definition: Gnu.h:162
std::string MajorStr
The text of the parsed major, and major+minor versions.
Definition: Gnu.h:170
bool isOlderThan(int RHSMajor, int RHSMinor, int RHSPatch, StringRef RHSPatchSuffix=StringRef()) const
Generic_GCC - A tool chain using the 'gcc' command to perform all subcommands; this relies on gcc tra...
Definition: Gnu.cpp:2077
std::string PatchSuffix
Any textual suffix on the patch number.
Definition: Gnu.h:173
int Major
The parsed major, minor, and patch numbers.
Definition: Gnu.h:167
std::string Text
The unparsed text of the version.
Definition: Gnu.h:164
static GCCVersion Parse(StringRef VersionText)
Parse a GCCVersion object out of a string of text.
Definition: Gnu.cpp:2121