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