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