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