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