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