clang  8.0.0svn
Gnu.cpp
Go to the documentation of this file.
1 //===--- Gnu.cpp - Gnu Tool and ToolChain Implementations -------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "Gnu.h"
11 #include "Arch/ARM.h"
12 #include "Arch/Mips.h"
13 #include "Arch/PPC.h"
14 #include "Arch/RISCV.h"
15 #include "Arch/Sparc.h"
16 #include "Arch/SystemZ.h"
17 #include "CommonArgs.h"
18 #include "Linux.h"
20 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
22 #include "clang/Driver/Driver.h"
24 #include "clang/Driver/Options.h"
25 #include "clang/Driver/Tool.h"
26 #include "llvm/Option/ArgList.h"
27 #include "llvm/Support/CodeGen.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/TargetParser.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 void tools::GnuTool::anchor() {}
38 
39 static bool forwardToGCC(const Option &O) {
40  // Don't forward inputs from the original command line. They are added from
41  // InputInfoList.
42  return O.getKind() != Option::InputClass &&
43  !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
44 }
45 
46 // Switch CPU names not recognized by GNU assembler to a close CPU that it does
47 // recognize, instead of a lower march from being picked in the absence of a cpu
48 // flag.
49 static void normalizeCPUNamesForAssembler(const ArgList &Args,
50  ArgStringList &CmdArgs) {
51  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
52  StringRef CPUArg(A->getValue());
53  if (CPUArg.equals_lower("krait"))
54  CmdArgs.push_back("-mcpu=cortex-a15");
55  else if(CPUArg.equals_lower("kryo"))
56  CmdArgs.push_back("-mcpu=cortex-a57");
57  else
58  Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
59  }
60 }
61 
63  const InputInfo &Output,
64  const InputInfoList &Inputs,
65  const ArgList &Args,
66  const char *LinkingOutput) const {
67  const Driver &D = getToolChain().getDriver();
68  ArgStringList CmdArgs;
69 
70  for (const auto &A : Args) {
71  if (forwardToGCC(A->getOption())) {
72  // It is unfortunate that we have to claim here, as this means
73  // we will basically never report anything interesting for
74  // platforms using a generic gcc, even if we are just using gcc
75  // to get to the assembler.
76  A->claim();
77 
78  // Don't forward any -g arguments to assembly steps.
79  if (isa<AssembleJobAction>(JA) &&
80  A->getOption().matches(options::OPT_g_Group))
81  continue;
82 
83  // Don't forward any -W arguments to assembly and link steps.
84  if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
85  A->getOption().matches(options::OPT_W_Group))
86  continue;
87 
88  // Don't forward -mno-unaligned-access since GCC doesn't understand
89  // it and because it doesn't affect the assembly or link steps.
90  if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
91  (A->getOption().matches(options::OPT_munaligned_access) ||
92  A->getOption().matches(options::OPT_mno_unaligned_access)))
93  continue;
94 
95  A->render(Args, CmdArgs);
96  }
97  }
98 
99  RenderExtraToolArgs(JA, CmdArgs);
100 
101  // If using a driver driver, force the arch.
102  if (getToolChain().getTriple().isOSDarwin()) {
103  CmdArgs.push_back("-arch");
104  CmdArgs.push_back(
105  Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
106  }
107 
108  // Try to force gcc to match the tool chain we want, if we recognize
109  // the arch.
110  //
111  // FIXME: The triple class should directly provide the information we want
112  // here.
113  switch (getToolChain().getArch()) {
114  default:
115  break;
116  case llvm::Triple::x86:
117  case llvm::Triple::ppc:
118  CmdArgs.push_back("-m32");
119  break;
120  case llvm::Triple::x86_64:
121  case llvm::Triple::ppc64:
122  case llvm::Triple::ppc64le:
123  CmdArgs.push_back("-m64");
124  break;
125  case llvm::Triple::sparcel:
126  CmdArgs.push_back("-EL");
127  break;
128  }
129 
130  if (Output.isFilename()) {
131  CmdArgs.push_back("-o");
132  CmdArgs.push_back(Output.getFilename());
133  } else {
134  assert(Output.isNothing() && "Unexpected output");
135  CmdArgs.push_back("-fsyntax-only");
136  }
137 
138  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
139 
140  // Only pass -x if gcc will understand it; otherwise hope gcc
141  // understands the suffix correctly. The main use case this would go
142  // wrong in is for linker inputs if they happened to have an odd
143  // suffix; really the only way to get this to happen is a command
144  // like '-x foobar a.c' which will treat a.c like a linker input.
145  //
146  // FIXME: For the linker case specifically, can we safely convert
147  // inputs into '-Wl,' options?
148  for (const auto &II : Inputs) {
149  // Don't try to pass LLVM or AST inputs to a generic gcc.
150  if (types::isLLVMIR(II.getType()))
151  D.Diag(clang::diag::err_drv_no_linker_llvm_support)
152  << getToolChain().getTripleString();
153  else if (II.getType() == types::TY_AST)
154  D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
155  else if (II.getType() == types::TY_ModuleFile)
156  D.Diag(diag::err_drv_no_module_support)
157  << getToolChain().getTripleString();
158 
159  if (types::canTypeBeUserSpecified(II.getType())) {
160  CmdArgs.push_back("-x");
161  CmdArgs.push_back(types::getTypeName(II.getType()));
162  }
163 
164  if (II.isFilename())
165  CmdArgs.push_back(II.getFilename());
166  else {
167  const Arg &A = II.getInputArg();
168 
169  // Reverse translate some rewritten options.
170  if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
171  CmdArgs.push_back("-lstdc++");
172  continue;
173  }
174 
175  // Don't render as input, we need gcc to do the translations.
176  A.render(Args, CmdArgs);
177  }
178  }
179 
180  const std::string &customGCCName = D.getCCCGenericGCCName();
181  const char *GCCName;
182  if (!customGCCName.empty())
183  GCCName = customGCCName.c_str();
184  else if (D.CCCIsCXX()) {
185  GCCName = "g++";
186  } else
187  GCCName = "gcc";
188 
189  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
190  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
191 }
192 
194  const JobAction &JA, ArgStringList &CmdArgs) const {
195  CmdArgs.push_back("-E");
196 }
197 
199  ArgStringList &CmdArgs) const {
200  const Driver &D = getToolChain().getDriver();
201 
202  switch (JA.getType()) {
203  // If -flto, etc. are present then make sure not to force assembly output.
204  case types::TY_LLVM_IR:
205  case types::TY_LTO_IR:
206  case types::TY_LLVM_BC:
207  case types::TY_LTO_BC:
208  CmdArgs.push_back("-c");
209  break;
210  // We assume we've got an "integrated" assembler in that gcc will produce an
211  // object file itself.
212  case types::TY_Object:
213  CmdArgs.push_back("-c");
214  break;
215  case types::TY_PP_Asm:
216  CmdArgs.push_back("-S");
217  break;
218  case types::TY_Nothing:
219  CmdArgs.push_back("-fsyntax-only");
220  break;
221  default:
222  D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
223  }
224 }
225 
227  ArgStringList &CmdArgs) const {
228  // The types are (hopefully) good enough.
229 }
230 
231 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
232  switch (T.getArch()) {
233  case llvm::Triple::x86:
234  if (T.isOSIAMCU())
235  return "elf_iamcu";
236  return "elf_i386";
237  case llvm::Triple::aarch64:
238  return "aarch64linux";
239  case llvm::Triple::aarch64_be:
240  return "aarch64linuxb";
241  case llvm::Triple::arm:
242  case llvm::Triple::thumb:
243  return "armelf_linux_eabi";
244  case llvm::Triple::armeb:
245  case llvm::Triple::thumbeb:
246  return "armelfb_linux_eabi";
247  case llvm::Triple::ppc:
248  return "elf32ppclinux";
249  case llvm::Triple::ppc64:
250  return "elf64ppc";
251  case llvm::Triple::ppc64le:
252  return "elf64lppc";
253  case llvm::Triple::riscv32:
254  return "elf32lriscv";
255  case llvm::Triple::riscv64:
256  return "elf64lriscv";
257  case llvm::Triple::sparc:
258  case llvm::Triple::sparcel:
259  return "elf32_sparc";
260  case llvm::Triple::sparcv9:
261  return "elf64_sparc";
262  case llvm::Triple::mips:
263  return "elf32btsmip";
264  case llvm::Triple::mipsel:
265  return "elf32ltsmip";
266  case llvm::Triple::mips64:
267  if (tools::mips::hasMipsAbiArg(Args, "n32"))
268  return "elf32btsmipn32";
269  return "elf64btsmip";
270  case llvm::Triple::mips64el:
271  if (tools::mips::hasMipsAbiArg(Args, "n32"))
272  return "elf32ltsmipn32";
273  return "elf64ltsmip";
274  case llvm::Triple::systemz:
275  return "elf64_s390";
276  case llvm::Triple::x86_64:
277  if (T.getEnvironment() == llvm::Triple::GNUX32)
278  return "elf32_x86_64";
279  return "elf_x86_64";
280  default:
281  return nullptr;
282  }
283 }
284 
285 static bool getPIE(const ArgList &Args, const toolchains::Linux &ToolChain) {
286  if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_static) ||
287  Args.hasArg(options::OPT_r))
288  return false;
289 
290  Arg *A = Args.getLastArg(options::OPT_pie, options::OPT_no_pie,
291  options::OPT_nopie);
292  if (!A)
293  return ToolChain.isPIEDefault();
294  return A->getOption().matches(options::OPT_pie);
295 }
296 
298  const InputInfo &Output,
299  const InputInfoList &Inputs,
300  const ArgList &Args,
301  const char *LinkingOutput) const {
303  static_cast<const toolchains::Linux &>(getToolChain());
304  const Driver &D = ToolChain.getDriver();
305 
306  const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
307 
308  const llvm::Triple::ArchType Arch = ToolChain.getArch();
309  const bool isAndroid = ToolChain.getTriple().isAndroid();
310  const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
311  const bool IsPIE = getPIE(Args, ToolChain);
312  const bool HasCRTBeginEndFiles =
313  ToolChain.getTriple().hasEnvironment() ||
314  (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
315 
316  ArgStringList CmdArgs;
317 
318  // Silence warning for "clang -g foo.o -o foo"
319  Args.ClaimAllArgs(options::OPT_g_Group);
320  // and "clang -emit-llvm foo.o -o foo"
321  Args.ClaimAllArgs(options::OPT_emit_llvm);
322  // and for "clang -w foo.o -o foo". Other warning options are already
323  // handled somewhere else.
324  Args.ClaimAllArgs(options::OPT_w);
325 
326  if (!D.SysRoot.empty())
327  CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
328 
329  if (IsPIE)
330  CmdArgs.push_back("-pie");
331 
332  if (Args.hasArg(options::OPT_rdynamic))
333  CmdArgs.push_back("-export-dynamic");
334 
335  if (Args.hasArg(options::OPT_s))
336  CmdArgs.push_back("-s");
337 
338  if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
339  arm::appendEBLinkFlags(Args, CmdArgs, Triple);
340 
341  // Most Android ARM64 targets should enable the linker fix for erratum
342  // 843419. Only non-Cortex-A53 devices are allowed to skip this flag.
343  if (Arch == llvm::Triple::aarch64 && isAndroid) {
344  std::string CPU = getCPUName(Args, Triple);
345  if (CPU.empty() || CPU == "generic" || CPU == "cortex-a53")
346  CmdArgs.push_back("--fix-cortex-a53-843419");
347  }
348 
349  for (const auto &Opt : ToolChain.ExtraOpts)
350  CmdArgs.push_back(Opt.c_str());
351 
352  CmdArgs.push_back("--eh-frame-hdr");
353 
354  if (const char *LDMOption = getLDMOption(ToolChain.getTriple(), Args)) {
355  CmdArgs.push_back("-m");
356  CmdArgs.push_back(LDMOption);
357  } else {
358  D.Diag(diag::err_target_unknown_triple) << Triple.str();
359  return;
360  }
361 
362  if (Args.hasArg(options::OPT_static)) {
363  if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
364  Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
365  CmdArgs.push_back("-Bstatic");
366  else
367  CmdArgs.push_back("-static");
368  } else if (Args.hasArg(options::OPT_shared)) {
369  CmdArgs.push_back("-shared");
370  }
371 
372  if (!Args.hasArg(options::OPT_static)) {
373  if (Args.hasArg(options::OPT_rdynamic))
374  CmdArgs.push_back("-export-dynamic");
375 
376  if (!Args.hasArg(options::OPT_shared)) {
377  const std::string Loader =
378  D.DyldPrefix + ToolChain.getDynamicLinker(Args);
379  CmdArgs.push_back("-dynamic-linker");
380  CmdArgs.push_back(Args.MakeArgString(Loader));
381  }
382  }
383 
384  CmdArgs.push_back("-o");
385  CmdArgs.push_back(Output.getFilename());
386 
387  if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
388  if (!isAndroid && !IsIAMCU) {
389  const char *crt1 = nullptr;
390  if (!Args.hasArg(options::OPT_shared)) {
391  if (Args.hasArg(options::OPT_pg))
392  crt1 = "gcrt1.o";
393  else if (IsPIE)
394  crt1 = "Scrt1.o";
395  else
396  crt1 = "crt1.o";
397  }
398  if (crt1)
399  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
400 
401  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
402  }
403 
404  if (IsIAMCU)
405  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
406  else {
407  const char *crtbegin;
408  if (Args.hasArg(options::OPT_static))
409  crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
410  else if (Args.hasArg(options::OPT_shared))
411  crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
412  else if (IsPIE)
413  crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
414  else
415  crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
416 
417  if (HasCRTBeginEndFiles)
418  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
419  }
420 
421  // Add crtfastmath.o if available and fast math is enabled.
422  ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
423  }
424 
425  Args.AddAllArgs(CmdArgs, options::OPT_L);
426  Args.AddAllArgs(CmdArgs, options::OPT_u);
427 
428  ToolChain.AddFilePathLibArgs(Args, CmdArgs);
429 
430  if (D.isUsingLTO()) {
431  assert(!Inputs.empty() && "Must have at least one input.");
432  AddGoldPlugin(ToolChain, Args, CmdArgs, Output, Inputs[0],
433  D.getLTOMode() == LTOK_Thin);
434  }
435 
436  if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
437  CmdArgs.push_back("--no-demangle");
438 
439  bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
440  bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
441  AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
442  // The profile runtime also needs access to system libraries.
443  getToolChain().addProfileRTLibs(Args, CmdArgs);
444 
445  if (D.CCCIsCXX() &&
446  !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
447  if (ToolChain.ShouldLinkCXXStdlib(Args)) {
448  bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
449  !Args.hasArg(options::OPT_static);
450  if (OnlyLibstdcxxStatic)
451  CmdArgs.push_back("-Bstatic");
452  ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
453  if (OnlyLibstdcxxStatic)
454  CmdArgs.push_back("-Bdynamic");
455  }
456  CmdArgs.push_back("-lm");
457  }
458  // Silence warnings when linking C code with a C++ '-stdlib' argument.
459  Args.ClaimAllArgs(options::OPT_stdlib_EQ);
460 
461  if (!Args.hasArg(options::OPT_nostdlib)) {
462  if (!Args.hasArg(options::OPT_nodefaultlibs)) {
463  if (Args.hasArg(options::OPT_static))
464  CmdArgs.push_back("--start-group");
465 
466  if (NeedsSanitizerDeps)
467  linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
468 
469  if (NeedsXRayDeps)
470  linkXRayRuntimeDeps(ToolChain, CmdArgs);
471 
472  bool WantPthread = Args.hasArg(options::OPT_pthread) ||
473  Args.hasArg(options::OPT_pthreads);
474 
475  // FIXME: Only pass GompNeedsRT = true for platforms with libgomp that
476  // require librt. Most modern Linux platforms do, but some may not.
477  if (addOpenMPRuntime(CmdArgs, ToolChain, Args,
479  /* GompNeedsRT= */ true))
480  // OpenMP runtimes implies pthreads when using the GNU toolchain.
481  // FIXME: Does this really make sense for all GNU toolchains?
482  WantPthread = true;
483 
484  AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
485 
486  if (WantPthread && !isAndroid)
487  CmdArgs.push_back("-lpthread");
488 
489  if (Args.hasArg(options::OPT_fsplit_stack))
490  CmdArgs.push_back("--wrap=pthread_create");
491 
492  CmdArgs.push_back("-lc");
493 
494  // Add IAMCU specific libs, if needed.
495  if (IsIAMCU)
496  CmdArgs.push_back("-lgloss");
497 
498  if (Args.hasArg(options::OPT_static))
499  CmdArgs.push_back("--end-group");
500  else
501  AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
502 
503  // Add IAMCU specific libs (outside the group), if needed.
504  if (IsIAMCU) {
505  CmdArgs.push_back("--as-needed");
506  CmdArgs.push_back("-lsoftfp");
507  CmdArgs.push_back("--no-as-needed");
508  }
509  }
510 
511  if (!Args.hasArg(options::OPT_nostartfiles) && !IsIAMCU) {
512  const char *crtend;
513  if (Args.hasArg(options::OPT_shared))
514  crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
515  else if (IsPIE)
516  crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
517  else
518  crtend = isAndroid ? "crtend_android.o" : "crtend.o";
519 
520  if (HasCRTBeginEndFiles)
521  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
522  if (!isAndroid)
523  CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
524  }
525  }
526 
527  // Add OpenMP offloading linker script args if required.
528  AddOpenMPLinkerScript(getToolChain(), C, Output, Inputs, Args, CmdArgs, JA);
529 
530  // Add HIP offloading linker script args if required.
531  AddHIPLinkerScript(getToolChain(), C, Output, Inputs, Args, CmdArgs, JA,
532  *this);
533 
534  const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
535  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
536 }
537 
539  const JobAction &JA,
540  const InputInfo &Output,
541  const InputInfoList &Inputs,
542  const ArgList &Args,
543  const char *LinkingOutput) const {
544  const auto &D = getToolChain().getDriver();
545 
546  claimNoWarnArgs(Args);
547 
548  ArgStringList CmdArgs;
549 
550  llvm::Reloc::Model RelocationModel;
551  unsigned PICLevel;
552  bool IsPIE;
553  std::tie(RelocationModel, PICLevel, IsPIE) =
554  ParsePICArgs(getToolChain(), Args);
555 
556  if (const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ)) {
557  if (A->getOption().getID() == options::OPT_gz) {
558  CmdArgs.push_back("-compress-debug-sections");
559  } else {
560  StringRef Value = A->getValue();
561  if (Value == "none") {
562  CmdArgs.push_back("-compress-debug-sections=none");
563  } else if (Value == "zlib" || Value == "zlib-gnu") {
564  CmdArgs.push_back(
565  Args.MakeArgString("-compress-debug-sections=" + Twine(Value)));
566  } else {
567  D.Diag(diag::err_drv_unsupported_option_argument)
568  << A->getOption().getName() << Value;
569  }
570  }
571  }
572 
573  switch (getToolChain().getArch()) {
574  default:
575  break;
576  // Add --32/--64 to make sure we get the format we want.
577  // This is incomplete
578  case llvm::Triple::x86:
579  CmdArgs.push_back("--32");
580  break;
581  case llvm::Triple::x86_64:
582  if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
583  CmdArgs.push_back("--x32");
584  else
585  CmdArgs.push_back("--64");
586  break;
587  case llvm::Triple::ppc: {
588  CmdArgs.push_back("-a32");
589  CmdArgs.push_back("-mppc");
590  CmdArgs.push_back(
591  ppc::getPPCAsmModeForCPU(getCPUName(Args, getToolChain().getTriple())));
592  break;
593  }
594  case llvm::Triple::ppc64: {
595  CmdArgs.push_back("-a64");
596  CmdArgs.push_back("-mppc64");
597  CmdArgs.push_back(
598  ppc::getPPCAsmModeForCPU(getCPUName(Args, getToolChain().getTriple())));
599  break;
600  }
601  case llvm::Triple::ppc64le: {
602  CmdArgs.push_back("-a64");
603  CmdArgs.push_back("-mppc64");
604  CmdArgs.push_back("-mlittle-endian");
605  CmdArgs.push_back(
606  ppc::getPPCAsmModeForCPU(getCPUName(Args, getToolChain().getTriple())));
607  break;
608  }
609  case llvm::Triple::riscv32:
610  case llvm::Triple::riscv64: {
611  StringRef ABIName = riscv::getRISCVABI(Args, getToolChain().getTriple());
612  CmdArgs.push_back("-mabi");
613  CmdArgs.push_back(ABIName.data());
614  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
615  StringRef MArch = A->getValue();
616  CmdArgs.push_back("-march");
617  CmdArgs.push_back(MArch.data());
618  }
619  break;
620  }
621  case llvm::Triple::sparc:
622  case llvm::Triple::sparcel: {
623  CmdArgs.push_back("-32");
624  std::string CPU = getCPUName(Args, getToolChain().getTriple());
625  CmdArgs.push_back(sparc::getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
626  AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
627  break;
628  }
629  case llvm::Triple::sparcv9: {
630  CmdArgs.push_back("-64");
631  std::string CPU = getCPUName(Args, getToolChain().getTriple());
632  CmdArgs.push_back(sparc::getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
633  AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
634  break;
635  }
636  case llvm::Triple::arm:
637  case llvm::Triple::armeb:
638  case llvm::Triple::thumb:
639  case llvm::Triple::thumbeb: {
640  const llvm::Triple &Triple2 = getToolChain().getTriple();
641  switch (Triple2.getSubArch()) {
642  case llvm::Triple::ARMSubArch_v7:
643  CmdArgs.push_back("-mfpu=neon");
644  break;
645  case llvm::Triple::ARMSubArch_v8:
646  CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
647  break;
648  default:
649  break;
650  }
651 
652  switch (arm::getARMFloatABI(getToolChain(), Args)) {
653  case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
654  case arm::FloatABI::Soft:
655  CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
656  break;
657  case arm::FloatABI::SoftFP:
658  CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
659  break;
660  case arm::FloatABI::Hard:
661  CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
662  break;
663  }
664 
665  Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
666  normalizeCPUNamesForAssembler(Args, CmdArgs);
667 
668  Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
669  break;
670  }
671  case llvm::Triple::aarch64:
672  case llvm::Triple::aarch64_be: {
673  Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
674  normalizeCPUNamesForAssembler(Args, CmdArgs);
675 
676  break;
677  }
678  case llvm::Triple::mips:
679  case llvm::Triple::mipsel:
680  case llvm::Triple::mips64:
681  case llvm::Triple::mips64el: {
682  StringRef CPUName;
683  StringRef ABIName;
684  mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
685  ABIName = mips::getGnuCompatibleMipsABIName(ABIName);
686 
687  CmdArgs.push_back("-march");
688  CmdArgs.push_back(CPUName.data());
689 
690  CmdArgs.push_back("-mabi");
691  CmdArgs.push_back(ABIName.data());
692 
693  // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
694  // or -mshared (not implemented) is in effect.
695  if (RelocationModel == llvm::Reloc::Static)
696  CmdArgs.push_back("-mno-shared");
697 
698  // LLVM doesn't support -mplt yet and acts as if it is always given.
699  // However, -mplt has no effect with the N64 ABI.
700  if (ABIName != "64" && !Args.hasArg(options::OPT_mno_abicalls))
701  CmdArgs.push_back("-call_nonpic");
702 
703  if (getToolChain().getTriple().isLittleEndian())
704  CmdArgs.push_back("-EL");
705  else
706  CmdArgs.push_back("-EB");
707 
708  if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
709  if (StringRef(A->getValue()) == "2008")
710  CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
711  }
712 
713  // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
714  if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
715  options::OPT_mfp64)) {
716  A->claim();
717  A->render(Args, CmdArgs);
718  } else if (mips::shouldUseFPXX(
719  Args, getToolChain().getTriple(), CPUName, ABIName,
720  mips::getMipsFloatABI(getToolChain().getDriver(), Args)))
721  CmdArgs.push_back("-mfpxx");
722 
723  // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
724  // -mno-mips16 is actually -no-mips16.
725  if (Arg *A =
726  Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
727  if (A->getOption().matches(options::OPT_mips16)) {
728  A->claim();
729  A->render(Args, CmdArgs);
730  } else {
731  A->claim();
732  CmdArgs.push_back("-no-mips16");
733  }
734  }
735 
736  Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
737  options::OPT_mno_micromips);
738  Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
739  Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
740 
741  if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
742  // Do not use AddLastArg because not all versions of MIPS assembler
743  // support -mmsa / -mno-msa options.
744  if (A->getOption().matches(options::OPT_mmsa))
745  CmdArgs.push_back(Args.MakeArgString("-mmsa"));
746  }
747 
748  Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
749  options::OPT_msoft_float);
750 
751  Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
752  options::OPT_msingle_float);
753 
754  Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
755  options::OPT_mno_odd_spreg);
756 
757  AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
758  break;
759  }
760  case llvm::Triple::systemz: {
761  // Always pass an -march option, since our default of z10 is later
762  // than the GNU assembler's default.
763  StringRef CPUName = systemz::getSystemZTargetCPU(Args);
764  CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
765  break;
766  }
767  }
768 
769  Args.AddAllArgs(CmdArgs, options::OPT_I);
770  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
771 
772  CmdArgs.push_back("-o");
773  CmdArgs.push_back(Output.getFilename());
774 
775  for (const auto &II : Inputs)
776  CmdArgs.push_back(II.getFilename());
777 
778  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
779  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
780 
781  // Handle the debug info splitting at object creation time if we're
782  // creating an object.
783  // TODO: Currently only works on linux with newer objcopy.
784  if (Args.hasArg(options::OPT_gsplit_dwarf) &&
785  getToolChain().getTriple().isOSLinux())
786  SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
787  SplitDebugName(Args, Inputs[0]));
788 }
789 
790 namespace {
791 // Filter to remove Multilibs that don't exist as a suffix to Path
792 class FilterNonExistent {
793  StringRef Base, File;
794  vfs::FileSystem &VFS;
795 
796 public:
797  FilterNonExistent(StringRef Base, StringRef File, vfs::FileSystem &VFS)
798  : Base(Base), File(File), VFS(VFS) {}
799  bool operator()(const Multilib &M) {
800  return !VFS.exists(Base + M.gccSuffix() + File);
801  }
802 };
803 } // end anonymous namespace
804 
805 static bool isSoftFloatABI(const ArgList &Args) {
806  Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
807  options::OPT_mfloat_abi_EQ);
808  if (!A)
809  return false;
810 
811  return A->getOption().matches(options::OPT_msoft_float) ||
812  (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
813  A->getValue() == StringRef("soft"));
814 }
815 
816 /// \p Flag must be a flag accepted by the driver with its leading '-' removed,
817 // otherwise '-print-multi-lib' will not emit them correctly.
818 static void addMultilibFlag(bool Enabled, const char *const Flag,
819  std::vector<std::string> &Flags) {
820  if (Enabled)
821  Flags.push_back(std::string("+") + Flag);
822  else
823  Flags.push_back(std::string("-") + Flag);
824 }
825 
826 static bool isArmOrThumbArch(llvm::Triple::ArchType Arch) {
827  return Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb;
828 }
829 
830 static bool isMipsEL(llvm::Triple::ArchType Arch) {
831  return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
832 }
833 
834 static bool isMips16(const ArgList &Args) {
835  Arg *A = Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16);
836  return A && A->getOption().matches(options::OPT_mips16);
837 }
838 
839 static bool isMicroMips(const ArgList &Args) {
840  Arg *A = Args.getLastArg(options::OPT_mmicromips, options::OPT_mno_micromips);
841  return A && A->getOption().matches(options::OPT_mmicromips);
842 }
843 
844 static bool isRISCV(llvm::Triple::ArchType Arch) {
845  return Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64;
846 }
847 
848 static Multilib makeMultilib(StringRef commonSuffix) {
849  return Multilib(commonSuffix, commonSuffix, commonSuffix);
850 }
851 
852 static bool findMipsCsMultilibs(const Multilib::flags_list &Flags,
853  FilterNonExistent &NonExistent,
854  DetectedMultilibs &Result) {
855  // Check for Code Sourcery toolchain multilibs
856  MultilibSet CSMipsMultilibs;
857  {
858  auto MArchMips16 = makeMultilib("/mips16").flag("+m32").flag("+mips16");
859 
860  auto MArchMicroMips =
861  makeMultilib("/micromips").flag("+m32").flag("+mmicromips");
862 
863  auto MArchDefault = makeMultilib("").flag("-mips16").flag("-mmicromips");
864 
865  auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
866 
867  auto SoftFloat = makeMultilib("/soft-float").flag("+msoft-float");
868 
869  auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
870 
871  auto DefaultFloat =
872  makeMultilib("").flag("-msoft-float").flag("-mnan=2008");
873 
874  auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
875 
876  auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
877 
878  // Note that this one's osSuffix is ""
879  auto MAbi64 = makeMultilib("")
880  .gccSuffix("/64")
881  .includeSuffix("/64")
882  .flag("+mabi=n64")
883  .flag("-mabi=n32")
884  .flag("-m32");
885 
886  CSMipsMultilibs =
887  MultilibSet()
888  .Either(MArchMips16, MArchMicroMips, MArchDefault)
889  .Maybe(UCLibc)
890  .Either(SoftFloat, Nan2008, DefaultFloat)
891  .FilterOut("/micromips/nan2008")
892  .FilterOut("/mips16/nan2008")
893  .Either(BigEndian, LittleEndian)
894  .Maybe(MAbi64)
895  .FilterOut("/mips16.*/64")
896  .FilterOut("/micromips.*/64")
897  .FilterOut(NonExistent)
898  .setIncludeDirsCallback([](const Multilib &M) {
899  std::vector<std::string> Dirs({"/include"});
900  if (StringRef(M.includeSuffix()).startswith("/uclibc"))
901  Dirs.push_back(
902  "/../../../../mips-linux-gnu/libc/uclibc/usr/include");
903  else
904  Dirs.push_back("/../../../../mips-linux-gnu/libc/usr/include");
905  return Dirs;
906  });
907  }
908 
909  MultilibSet DebianMipsMultilibs;
910  {
911  Multilib MAbiN32 =
912  Multilib().gccSuffix("/n32").includeSuffix("/n32").flag("+mabi=n32");
913 
914  Multilib M64 = Multilib()
915  .gccSuffix("/64")
916  .includeSuffix("/64")
917  .flag("+m64")
918  .flag("-m32")
919  .flag("-mabi=n32");
920 
921  Multilib M32 = Multilib().flag("-m64").flag("+m32").flag("-mabi=n32");
922 
923  DebianMipsMultilibs =
924  MultilibSet().Either(M32, M64, MAbiN32).FilterOut(NonExistent);
925  }
926 
927  // Sort candidates. Toolchain that best meets the directories tree goes first.
928  // Then select the first toolchains matches command line flags.
929  MultilibSet *Candidates[] = {&CSMipsMultilibs, &DebianMipsMultilibs};
930  if (CSMipsMultilibs.size() < DebianMipsMultilibs.size())
931  std::iter_swap(Candidates, Candidates + 1);
932  for (const MultilibSet *Candidate : Candidates) {
933  if (Candidate->select(Flags, Result.SelectedMultilib)) {
934  if (Candidate == &DebianMipsMultilibs)
935  Result.BiarchSibling = Multilib();
936  Result.Multilibs = *Candidate;
937  return true;
938  }
939  }
940  return false;
941 }
942 
943 static bool findMipsAndroidMultilibs(vfs::FileSystem &VFS, StringRef Path,
944  const Multilib::flags_list &Flags,
945  FilterNonExistent &NonExistent,
946  DetectedMultilibs &Result) {
947 
948  MultilibSet AndroidMipsMultilibs =
949  MultilibSet()
950  .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
951  .Maybe(Multilib("/mips-r6").flag("+march=mips32r6"))
952  .FilterOut(NonExistent);
953 
954  MultilibSet AndroidMipselMultilibs =
955  MultilibSet()
956  .Either(Multilib().flag("+march=mips32"),
957  Multilib("/mips-r2", "", "/mips-r2").flag("+march=mips32r2"),
958  Multilib("/mips-r6", "", "/mips-r6").flag("+march=mips32r6"))
959  .FilterOut(NonExistent);
960 
961  MultilibSet AndroidMips64elMultilibs =
962  MultilibSet()
963  .Either(
964  Multilib().flag("+march=mips64r6"),
965  Multilib("/32/mips-r1", "", "/mips-r1").flag("+march=mips32"),
966  Multilib("/32/mips-r2", "", "/mips-r2").flag("+march=mips32r2"),
967  Multilib("/32/mips-r6", "", "/mips-r6").flag("+march=mips32r6"))
968  .FilterOut(NonExistent);
969 
970  MultilibSet *MS = &AndroidMipsMultilibs;
971  if (VFS.exists(Path + "/mips-r6"))
972  MS = &AndroidMipselMultilibs;
973  else if (VFS.exists(Path + "/32"))
974  MS = &AndroidMips64elMultilibs;
975  if (MS->select(Flags, Result.SelectedMultilib)) {
976  Result.Multilibs = *MS;
977  return true;
978  }
979  return false;
980 }
981 
983  FilterNonExistent &NonExistent,
984  DetectedMultilibs &Result) {
985  // Musl toolchain multilibs
986  MultilibSet MuslMipsMultilibs;
987  {
988  auto MArchMipsR2 = makeMultilib("")
989  .osSuffix("/mips-r2-hard-musl")
990  .flag("+EB")
991  .flag("-EL")
992  .flag("+march=mips32r2");
993 
994  auto MArchMipselR2 = makeMultilib("/mipsel-r2-hard-musl")
995  .flag("-EB")
996  .flag("+EL")
997  .flag("+march=mips32r2");
998 
999  MuslMipsMultilibs = MultilibSet().Either(MArchMipsR2, MArchMipselR2);
1000 
1001  // Specify the callback that computes the include directories.
1002  MuslMipsMultilibs.setIncludeDirsCallback([](const Multilib &M) {
1003  return std::vector<std::string>(
1004  {"/../sysroot" + M.osSuffix() + "/usr/include"});
1005  });
1006  }
1007  if (MuslMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
1008  Result.Multilibs = MuslMipsMultilibs;
1009  return true;
1010  }
1011  return false;
1012 }
1013 
1015  FilterNonExistent &NonExistent,
1016  DetectedMultilibs &Result) {
1017  // CodeScape MTI toolchain v1.2 and early.
1018  MultilibSet MtiMipsMultilibsV1;
1019  {
1020  auto MArchMips32 = makeMultilib("/mips32")
1021  .flag("+m32")
1022  .flag("-m64")
1023  .flag("-mmicromips")
1024  .flag("+march=mips32");
1025 
1026  auto MArchMicroMips = makeMultilib("/micromips")
1027  .flag("+m32")
1028  .flag("-m64")
1029  .flag("+mmicromips");
1030 
1031  auto MArchMips64r2 = makeMultilib("/mips64r2")
1032  .flag("-m32")
1033  .flag("+m64")
1034  .flag("+march=mips64r2");
1035 
1036  auto MArchMips64 = makeMultilib("/mips64").flag("-m32").flag("+m64").flag(
1037  "-march=mips64r2");
1038 
1039  auto MArchDefault = makeMultilib("")
1040  .flag("+m32")
1041  .flag("-m64")
1042  .flag("-mmicromips")
1043  .flag("+march=mips32r2");
1044 
1045  auto Mips16 = makeMultilib("/mips16").flag("+mips16");
1046 
1047  auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
1048 
1049  auto MAbi64 =
1050  makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1051 
1052  auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
1053 
1054  auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1055 
1056  auto SoftFloat = makeMultilib("/sof").flag("+msoft-float");
1057 
1058  auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
1059 
1060  MtiMipsMultilibsV1 =
1061  MultilibSet()
1062  .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64,
1063  MArchDefault)
1064  .Maybe(UCLibc)
1065  .Maybe(Mips16)
1066  .FilterOut("/mips64/mips16")
1067  .FilterOut("/mips64r2/mips16")
1068  .FilterOut("/micromips/mips16")
1069  .Maybe(MAbi64)
1070  .FilterOut("/micromips/64")
1071  .FilterOut("/mips32/64")
1072  .FilterOut("^/64")
1073  .FilterOut("/mips16/64")
1074  .Either(BigEndian, LittleEndian)
1075  .Maybe(SoftFloat)
1076  .Maybe(Nan2008)
1077  .FilterOut(".*sof/nan2008")
1078  .FilterOut(NonExistent)
1079  .setIncludeDirsCallback([](const Multilib &M) {
1080  std::vector<std::string> Dirs({"/include"});
1081  if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1082  Dirs.push_back("/../../../../sysroot/uclibc/usr/include");
1083  else
1084  Dirs.push_back("/../../../../sysroot/usr/include");
1085  return Dirs;
1086  });
1087  }
1088 
1089  // CodeScape IMG toolchain starting from v1.3.
1090  MultilibSet MtiMipsMultilibsV2;
1091  {
1092  auto BeHard = makeMultilib("/mips-r2-hard")
1093  .flag("+EB")
1094  .flag("-msoft-float")
1095  .flag("-mnan=2008")
1096  .flag("-muclibc");
1097  auto BeSoft = makeMultilib("/mips-r2-soft")
1098  .flag("+EB")
1099  .flag("+msoft-float")
1100  .flag("-mnan=2008");
1101  auto ElHard = makeMultilib("/mipsel-r2-hard")
1102  .flag("+EL")
1103  .flag("-msoft-float")
1104  .flag("-mnan=2008")
1105  .flag("-muclibc");
1106  auto ElSoft = makeMultilib("/mipsel-r2-soft")
1107  .flag("+EL")
1108  .flag("+msoft-float")
1109  .flag("-mnan=2008")
1110  .flag("-mmicromips");
1111  auto BeHardNan = makeMultilib("/mips-r2-hard-nan2008")
1112  .flag("+EB")
1113  .flag("-msoft-float")
1114  .flag("+mnan=2008")
1115  .flag("-muclibc");
1116  auto ElHardNan = makeMultilib("/mipsel-r2-hard-nan2008")
1117  .flag("+EL")
1118  .flag("-msoft-float")
1119  .flag("+mnan=2008")
1120  .flag("-muclibc")
1121  .flag("-mmicromips");
1122  auto BeHardNanUclibc = makeMultilib("/mips-r2-hard-nan2008-uclibc")
1123  .flag("+EB")
1124  .flag("-msoft-float")
1125  .flag("+mnan=2008")
1126  .flag("+muclibc");
1127  auto ElHardNanUclibc = makeMultilib("/mipsel-r2-hard-nan2008-uclibc")
1128  .flag("+EL")
1129  .flag("-msoft-float")
1130  .flag("+mnan=2008")
1131  .flag("+muclibc");
1132  auto BeHardUclibc = makeMultilib("/mips-r2-hard-uclibc")
1133  .flag("+EB")
1134  .flag("-msoft-float")
1135  .flag("-mnan=2008")
1136  .flag("+muclibc");
1137  auto ElHardUclibc = makeMultilib("/mipsel-r2-hard-uclibc")
1138  .flag("+EL")
1139  .flag("-msoft-float")
1140  .flag("-mnan=2008")
1141  .flag("+muclibc");
1142  auto ElMicroHardNan = makeMultilib("/micromipsel-r2-hard-nan2008")
1143  .flag("+EL")
1144  .flag("-msoft-float")
1145  .flag("+mnan=2008")
1146  .flag("+mmicromips");
1147  auto ElMicroSoft = makeMultilib("/micromipsel-r2-soft")
1148  .flag("+EL")
1149  .flag("+msoft-float")
1150  .flag("-mnan=2008")
1151  .flag("+mmicromips");
1152 
1153  auto O32 =
1154  makeMultilib("/lib").osSuffix("").flag("-mabi=n32").flag("-mabi=n64");
1155  auto N32 =
1156  makeMultilib("/lib32").osSuffix("").flag("+mabi=n32").flag("-mabi=n64");
1157  auto N64 =
1158  makeMultilib("/lib64").osSuffix("").flag("-mabi=n32").flag("+mabi=n64");
1159 
1160  MtiMipsMultilibsV2 =
1161  MultilibSet()
1162  .Either({BeHard, BeSoft, ElHard, ElSoft, BeHardNan, ElHardNan,
1163  BeHardNanUclibc, ElHardNanUclibc, BeHardUclibc,
1164  ElHardUclibc, ElMicroHardNan, ElMicroSoft})
1165  .Either(O32, N32, N64)
1166  .FilterOut(NonExistent)
1167  .setIncludeDirsCallback([](const Multilib &M) {
1168  return std::vector<std::string>({"/../../../../sysroot" +
1169  M.includeSuffix() +
1170  "/../usr/include"});
1171  })
1172  .setFilePathsCallback([](const Multilib &M) {
1173  return std::vector<std::string>(
1174  {"/../../../../mips-mti-linux-gnu/lib" + M.gccSuffix()});
1175  });
1176  }
1177  for (auto Candidate : {&MtiMipsMultilibsV1, &MtiMipsMultilibsV2}) {
1178  if (Candidate->select(Flags, Result.SelectedMultilib)) {
1179  Result.Multilibs = *Candidate;
1180  return true;
1181  }
1182  }
1183  return false;
1184 }
1185 
1187  FilterNonExistent &NonExistent,
1188  DetectedMultilibs &Result) {
1189  // CodeScape IMG toolchain v1.2 and early.
1190  MultilibSet ImgMultilibsV1;
1191  {
1192  auto Mips64r6 = makeMultilib("/mips64r6").flag("+m64").flag("-m32");
1193 
1194  auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1195 
1196  auto MAbi64 =
1197  makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1198 
1199  ImgMultilibsV1 =
1200  MultilibSet()
1201  .Maybe(Mips64r6)
1202  .Maybe(MAbi64)
1203  .Maybe(LittleEndian)
1204  .FilterOut(NonExistent)
1205  .setIncludeDirsCallback([](const Multilib &M) {
1206  return std::vector<std::string>(
1207  {"/include", "/../../../../sysroot/usr/include"});
1208  });
1209  }
1210 
1211  // CodeScape IMG toolchain starting from v1.3.
1212  MultilibSet ImgMultilibsV2;
1213  {
1214  auto BeHard = makeMultilib("/mips-r6-hard")
1215  .flag("+EB")
1216  .flag("-msoft-float")
1217  .flag("-mmicromips");
1218  auto BeSoft = makeMultilib("/mips-r6-soft")
1219  .flag("+EB")
1220  .flag("+msoft-float")
1221  .flag("-mmicromips");
1222  auto ElHard = makeMultilib("/mipsel-r6-hard")
1223  .flag("+EL")
1224  .flag("-msoft-float")
1225  .flag("-mmicromips");
1226  auto ElSoft = makeMultilib("/mipsel-r6-soft")
1227  .flag("+EL")
1228  .flag("+msoft-float")
1229  .flag("-mmicromips");
1230  auto BeMicroHard = makeMultilib("/micromips-r6-hard")
1231  .flag("+EB")
1232  .flag("-msoft-float")
1233  .flag("+mmicromips");
1234  auto BeMicroSoft = makeMultilib("/micromips-r6-soft")
1235  .flag("+EB")
1236  .flag("+msoft-float")
1237  .flag("+mmicromips");
1238  auto ElMicroHard = makeMultilib("/micromipsel-r6-hard")
1239  .flag("+EL")
1240  .flag("-msoft-float")
1241  .flag("+mmicromips");
1242  auto ElMicroSoft = makeMultilib("/micromipsel-r6-soft")
1243  .flag("+EL")
1244  .flag("+msoft-float")
1245  .flag("+mmicromips");
1246 
1247  auto O32 =
1248  makeMultilib("/lib").osSuffix("").flag("-mabi=n32").flag("-mabi=n64");
1249  auto N32 =
1250  makeMultilib("/lib32").osSuffix("").flag("+mabi=n32").flag("-mabi=n64");
1251  auto N64 =
1252  makeMultilib("/lib64").osSuffix("").flag("-mabi=n32").flag("+mabi=n64");
1253 
1254  ImgMultilibsV2 =
1255  MultilibSet()
1256  .Either({BeHard, BeSoft, ElHard, ElSoft, BeMicroHard, BeMicroSoft,
1257  ElMicroHard, ElMicroSoft})
1258  .Either(O32, N32, N64)
1259  .FilterOut(NonExistent)
1260  .setIncludeDirsCallback([](const Multilib &M) {
1261  return std::vector<std::string>({"/../../../../sysroot" +
1262  M.includeSuffix() +
1263  "/../usr/include"});
1264  })
1265  .setFilePathsCallback([](const Multilib &M) {
1266  return std::vector<std::string>(
1267  {"/../../../../mips-img-linux-gnu/lib" + M.gccSuffix()});
1268  });
1269  }
1270  for (auto Candidate : {&ImgMultilibsV1, &ImgMultilibsV2}) {
1271  if (Candidate->select(Flags, Result.SelectedMultilib)) {
1272  Result.Multilibs = *Candidate;
1273  return true;
1274  }
1275  }
1276  return false;
1277 }
1278 
1280  const llvm::Triple &TargetTriple,
1281  StringRef Path, const ArgList &Args,
1282  DetectedMultilibs &Result) {
1283  FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1284 
1285  StringRef CPUName;
1286  StringRef ABIName;
1287  tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
1288 
1289  llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1290 
1291  Multilib::flags_list Flags;
1292  addMultilibFlag(TargetTriple.isMIPS32(), "m32", Flags);
1293  addMultilibFlag(TargetTriple.isMIPS64(), "m64", Flags);
1294  addMultilibFlag(isMips16(Args), "mips16", Flags);
1295  addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
1296  addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" ||
1297  CPUName == "mips32r5" || CPUName == "p5600",
1298  "march=mips32r2", Flags);
1299  addMultilibFlag(CPUName == "mips32r6", "march=mips32r6", Flags);
1300  addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
1301  addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" ||
1302  CPUName == "mips64r5" || CPUName == "octeon",
1303  "march=mips64r2", Flags);
1304  addMultilibFlag(CPUName == "mips64r6", "march=mips64r6", Flags);
1305  addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
1306  addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
1307  addMultilibFlag(tools::mips::isNaN2008(Args, TargetTriple), "mnan=2008",
1308  Flags);
1309  addMultilibFlag(ABIName == "n32", "mabi=n32", Flags);
1310  addMultilibFlag(ABIName == "n64", "mabi=n64", Flags);
1311  addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags);
1312  addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags);
1313  addMultilibFlag(isMipsEL(TargetArch), "EL", Flags);
1314  addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags);
1315 
1316  if (TargetTriple.isAndroid())
1317  return findMipsAndroidMultilibs(D.getVFS(), Path, Flags, NonExistent,
1318  Result);
1319 
1320  if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
1321  TargetTriple.getOS() == llvm::Triple::Linux &&
1322  TargetTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
1323  return findMipsMuslMultilibs(Flags, NonExistent, Result);
1324 
1325  if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
1326  TargetTriple.getOS() == llvm::Triple::Linux &&
1327  TargetTriple.isGNUEnvironment())
1328  return findMipsMtiMultilibs(Flags, NonExistent, Result);
1329 
1330  if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1331  TargetTriple.getOS() == llvm::Triple::Linux &&
1332  TargetTriple.isGNUEnvironment())
1333  return findMipsImgMultilibs(Flags, NonExistent, Result);
1334 
1335  if (findMipsCsMultilibs(Flags, NonExistent, Result))
1336  return true;
1337 
1338  // Fallback to the regular toolchain-tree structure.
1339  Multilib Default;
1340  Result.Multilibs.push_back(Default);
1341  Result.Multilibs.FilterOut(NonExistent);
1342 
1343  if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) {
1344  Result.BiarchSibling = Multilib();
1345  return true;
1346  }
1347 
1348  return false;
1349 }
1350 
1351 static void findAndroidArmMultilibs(const Driver &D,
1352  const llvm::Triple &TargetTriple,
1353  StringRef Path, const ArgList &Args,
1354  DetectedMultilibs &Result) {
1355  // Find multilibs with subdirectories like armv7-a, thumb, armv7-a/thumb.
1356  FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1357  Multilib ArmV7Multilib = makeMultilib("/armv7-a")
1358  .flag("+march=armv7-a")
1359  .flag("-mthumb");
1360  Multilib ThumbMultilib = makeMultilib("/thumb")
1361  .flag("-march=armv7-a")
1362  .flag("+mthumb");
1363  Multilib ArmV7ThumbMultilib = makeMultilib("/armv7-a/thumb")
1364  .flag("+march=armv7-a")
1365  .flag("+mthumb");
1366  Multilib DefaultMultilib = makeMultilib("")
1367  .flag("-march=armv7-a")
1368  .flag("-mthumb");
1369  MultilibSet AndroidArmMultilibs =
1370  MultilibSet()
1371  .Either(ThumbMultilib, ArmV7Multilib,
1372  ArmV7ThumbMultilib, DefaultMultilib)
1373  .FilterOut(NonExistent);
1374 
1375  Multilib::flags_list Flags;
1376  llvm::StringRef Arch = Args.getLastArgValue(options::OPT_march_EQ);
1377  bool IsArmArch = TargetTriple.getArch() == llvm::Triple::arm;
1378  bool IsThumbArch = TargetTriple.getArch() == llvm::Triple::thumb;
1379  bool IsV7SubArch = TargetTriple.getSubArch() == llvm::Triple::ARMSubArch_v7;
1380  bool IsThumbMode = IsThumbArch ||
1381  Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, false) ||
1382  (IsArmArch && llvm::ARM::parseArchISA(Arch) == llvm::ARM::ISAKind::THUMB);
1383  bool IsArmV7Mode = (IsArmArch || IsThumbArch) &&
1384  (llvm::ARM::parseArchVersion(Arch) == 7 ||
1385  (IsArmArch && Arch == "" && IsV7SubArch));
1386  addMultilibFlag(IsArmV7Mode, "march=armv7-a", Flags);
1387  addMultilibFlag(IsThumbMode, "mthumb", Flags);
1388 
1389  if (AndroidArmMultilibs.select(Flags, Result.SelectedMultilib))
1390  Result.Multilibs = AndroidArmMultilibs;
1391 }
1392 
1393 static void findRISCVMultilibs(const Driver &D,
1394  const llvm::Triple &TargetTriple, StringRef Path,
1395  const ArgList &Args, DetectedMultilibs &Result) {
1396 
1397  FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1398  Multilib Ilp32 = makeMultilib("lib32/ilp32").flag("+m32").flag("+mabi=ilp32");
1399  Multilib Ilp32f =
1400  makeMultilib("lib32/ilp32f").flag("+m32").flag("+mabi=ilp32f");
1401  Multilib Ilp32d =
1402  makeMultilib("lib32/ilp32d").flag("+m32").flag("+mabi=ilp32d");
1403  Multilib Lp64 = makeMultilib("lib64/lp64").flag("+m64").flag("+mabi=lp64");
1404  Multilib Lp64f = makeMultilib("lib64/lp64f").flag("+m64").flag("+mabi=lp64f");
1405  Multilib Lp64d = makeMultilib("lib64/lp64d").flag("+m64").flag("+mabi=lp64d");
1406  MultilibSet RISCVMultilibs =
1407  MultilibSet()
1408  .Either({Ilp32, Ilp32f, Ilp32d, Lp64, Lp64f, Lp64d})
1409  .FilterOut(NonExistent);
1410 
1411  Multilib::flags_list Flags;
1412  bool IsRV64 = TargetTriple.getArch() == llvm::Triple::riscv64;
1413  StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple);
1414 
1415  addMultilibFlag(!IsRV64, "m32", Flags);
1416  addMultilibFlag(IsRV64, "m64", Flags);
1417  addMultilibFlag(ABIName == "ilp32", "mabi=ilp32", Flags);
1418  addMultilibFlag(ABIName == "ilp32f", "mabi=ilp32f", Flags);
1419  addMultilibFlag(ABIName == "ilp32d", "mabi=ilp32d", Flags);
1420  addMultilibFlag(ABIName == "lp64", "mabi=lp64", Flags);
1421  addMultilibFlag(ABIName == "lp64f", "mabi=lp64f", Flags);
1422  addMultilibFlag(ABIName == "lp64d", "mabi=lp64d", Flags);
1423 
1424  if (RISCVMultilibs.select(Flags, Result.SelectedMultilib))
1425  Result.Multilibs = RISCVMultilibs;
1426 }
1427 
1428 static bool findBiarchMultilibs(const Driver &D,
1429  const llvm::Triple &TargetTriple,
1430  StringRef Path, const ArgList &Args,
1431  bool NeedsBiarchSuffix,
1432  DetectedMultilibs &Result) {
1433  Multilib Default;
1434 
1435  // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1436  // in what would normally be GCCInstallPath and put the 64-bit
1437  // libs in a subdirectory named 64. The simple logic we follow is that
1438  // *if* there is a subdirectory of the right name with crtbegin.o in it,
1439  // we use that. If not, and if not a biarch triple alias, we look for
1440  // crtbegin.o without the subdirectory.
1441 
1442  StringRef Suff64 = "/64";
1443  // Solaris uses platform-specific suffixes instead of /64.
1444  if (TargetTriple.getOS() == llvm::Triple::Solaris) {
1445  switch (TargetTriple.getArch()) {
1446  case llvm::Triple::x86:
1447  case llvm::Triple::x86_64:
1448  Suff64 = "/amd64";
1449  break;
1450  case llvm::Triple::sparc:
1451  case llvm::Triple::sparcv9:
1452  Suff64 = "/sparcv9";
1453  break;
1454  default:
1455  break;
1456  }
1457  }
1458 
1459  Multilib Alt64 = Multilib()
1460  .gccSuffix(Suff64)
1461  .includeSuffix(Suff64)
1462  .flag("-m32")
1463  .flag("+m64")
1464  .flag("-mx32");
1465  Multilib Alt32 = Multilib()
1466  .gccSuffix("/32")
1467  .includeSuffix("/32")
1468  .flag("+m32")
1469  .flag("-m64")
1470  .flag("-mx32");
1471  Multilib Altx32 = Multilib()
1472  .gccSuffix("/x32")
1473  .includeSuffix("/x32")
1474  .flag("-m32")
1475  .flag("-m64")
1476  .flag("+mx32");
1477 
1478  // GCC toolchain for IAMCU doesn't have crtbegin.o, so look for libgcc.a.
1479  FilterNonExistent NonExistent(
1480  Path, TargetTriple.isOSIAMCU() ? "/libgcc.a" : "/crtbegin.o", D.getVFS());
1481 
1482  // Determine default multilib from: 32, 64, x32
1483  // Also handle cases such as 64 on 32, 32 on 64, etc.
1484  enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
1485  const bool IsX32 = TargetTriple.getEnvironment() == llvm::Triple::GNUX32;
1486  if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
1487  Want = WANT64;
1488  else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
1489  Want = WANT64;
1490  else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
1491  Want = WANT32;
1492  else {
1493  if (TargetTriple.isArch32Bit())
1494  Want = NeedsBiarchSuffix ? WANT64 : WANT32;
1495  else if (IsX32)
1496  Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
1497  else
1498  Want = NeedsBiarchSuffix ? WANT32 : WANT64;
1499  }
1500 
1501  if (Want == WANT32)
1502  Default.flag("+m32").flag("-m64").flag("-mx32");
1503  else if (Want == WANT64)
1504  Default.flag("-m32").flag("+m64").flag("-mx32");
1505  else if (Want == WANTX32)
1506  Default.flag("-m32").flag("-m64").flag("+mx32");
1507  else
1508  return false;
1509 
1510  Result.Multilibs.push_back(Default);
1511  Result.Multilibs.push_back(Alt64);
1512  Result.Multilibs.push_back(Alt32);
1513  Result.Multilibs.push_back(Altx32);
1514 
1515  Result.Multilibs.FilterOut(NonExistent);
1516 
1517  Multilib::flags_list Flags;
1518  addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "m64", Flags);
1519  addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags);
1520  addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "mx32", Flags);
1521 
1522  if (!Result.Multilibs.select(Flags, Result.SelectedMultilib))
1523  return false;
1524 
1525  if (Result.SelectedMultilib == Alt64 || Result.SelectedMultilib == Alt32 ||
1526  Result.SelectedMultilib == Altx32)
1527  Result.BiarchSibling = Default;
1528 
1529  return true;
1530 }
1531 
1532 /// Generic_GCC - A tool chain using the 'gcc' command to perform
1533 /// all subcommands; this relies on gcc translating the majority of
1534 /// command line options.
1535 
1536 /// Less-than for GCCVersion, implementing a Strict Weak Ordering.
1537 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
1538  int RHSPatch,
1539  StringRef RHSPatchSuffix) const {
1540  if (Major != RHSMajor)
1541  return Major < RHSMajor;
1542  if (Minor != RHSMinor)
1543  return Minor < RHSMinor;
1544  if (Patch != RHSPatch) {
1545  // Note that versions without a specified patch sort higher than those with
1546  // a patch.
1547  if (RHSPatch == -1)
1548  return true;
1549  if (Patch == -1)
1550  return false;
1551 
1552  // Otherwise just sort on the patch itself.
1553  return Patch < RHSPatch;
1554  }
1555  if (PatchSuffix != RHSPatchSuffix) {
1556  // Sort empty suffixes higher.
1557  if (RHSPatchSuffix.empty())
1558  return true;
1559  if (PatchSuffix.empty())
1560  return false;
1561 
1562  // Provide a lexicographic sort to make this a total ordering.
1563  return PatchSuffix < RHSPatchSuffix;
1564  }
1565 
1566  // The versions are equal.
1567  return false;
1568 }
1569 
1570 /// Parse a GCCVersion object out of a string of text.
1571 ///
1572 /// This is the primary means of forming GCCVersion objects.
1573 /*static*/
1575  const GCCVersion BadVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1576  std::pair<StringRef, StringRef> First = VersionText.split('.');
1577  std::pair<StringRef, StringRef> Second = First.second.split('.');
1578 
1579  GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1580  if (First.first.getAsInteger(10, GoodVersion.Major) || GoodVersion.Major < 0)
1581  return BadVersion;
1582  GoodVersion.MajorStr = First.first.str();
1583  if (First.second.empty())
1584  return GoodVersion;
1585  StringRef MinorStr = Second.first;
1586  if (Second.second.empty()) {
1587  if (size_t EndNumber = MinorStr.find_first_not_of("0123456789")) {
1588  GoodVersion.PatchSuffix = MinorStr.substr(EndNumber);
1589  MinorStr = MinorStr.slice(0, EndNumber);
1590  }
1591  }
1592  if (MinorStr.getAsInteger(10, GoodVersion.Minor) || GoodVersion.Minor < 0)
1593  return BadVersion;
1594  GoodVersion.MinorStr = MinorStr.str();
1595 
1596  // First look for a number prefix and parse that if present. Otherwise just
1597  // stash the entire patch string in the suffix, and leave the number
1598  // unspecified. This covers versions strings such as:
1599  // 5 (handled above)
1600  // 4.4
1601  // 4.4-patched
1602  // 4.4.0
1603  // 4.4.x
1604  // 4.4.2-rc4
1605  // 4.4.x-patched
1606  // And retains any patch number it finds.
1607  StringRef PatchText = Second.second;
1608  if (!PatchText.empty()) {
1609  if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
1610  // Try to parse the number and any suffix.
1611  if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
1612  GoodVersion.Patch < 0)
1613  return BadVersion;
1614  GoodVersion.PatchSuffix = PatchText.substr(EndNumber);
1615  }
1616  }
1617 
1618  return GoodVersion;
1619 }
1620 
1621 static llvm::StringRef getGCCToolchainDir(const ArgList &Args) {
1622  const Arg *A = Args.getLastArg(clang::driver::options::OPT_gcc_toolchain);
1623  if (A)
1624  return A->getValue();
1625  return GCC_INSTALL_PREFIX;
1626 }
1627 
1628 /// Initialize a GCCInstallationDetector from the driver.
1629 ///
1630 /// This performs all of the autodetection and sets up the various paths.
1631 /// Once constructed, a GCCInstallationDetector is essentially immutable.
1632 ///
1633 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1634 /// should instead pull the target out of the driver. This is currently
1635 /// necessary because the driver doesn't store the final version of the target
1636 /// triple.
1638  const llvm::Triple &TargetTriple, const ArgList &Args,
1639  ArrayRef<std::string> ExtraTripleAliases) {
1640  llvm::Triple BiarchVariantTriple = TargetTriple.isArch32Bit()
1641  ? TargetTriple.get64BitArchVariant()
1642  : TargetTriple.get32BitArchVariant();
1643  // The library directories which may contain GCC installations.
1644  SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
1645  // The compatible GCC triples for this particular architecture.
1646  SmallVector<StringRef, 16> CandidateTripleAliases;
1647  SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
1648  CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
1649  CandidateTripleAliases, CandidateBiarchLibDirs,
1650  CandidateBiarchTripleAliases);
1651 
1652  // Compute the set of prefixes for our search.
1653  SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1654  D.PrefixDirs.end());
1655 
1656  StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1657  if (GCCToolchainDir != "") {
1658  if (GCCToolchainDir.back() == '/')
1659  GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1660 
1661  Prefixes.push_back(GCCToolchainDir);
1662  } else {
1663  // If we have a SysRoot, try that first.
1664  if (!D.SysRoot.empty()) {
1665  Prefixes.push_back(D.SysRoot);
1666  AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
1667  }
1668 
1669  // Then look for gcc installed alongside clang.
1670  Prefixes.push_back(D.InstalledDir + "/..");
1671 
1672  // Next, look for prefix(es) that correspond to distribution-supplied gcc
1673  // installations.
1674  if (D.SysRoot.empty()) {
1675  // Typically /usr.
1676  AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
1677  }
1678  }
1679 
1680  // Try to respect gcc-config on Gentoo. However, do that only
1681  // if --gcc-toolchain is not provided or equal to the Gentoo install
1682  // in /usr. This avoids accidentally enforcing the system GCC version
1683  // when using a custom toolchain.
1684  if (GCCToolchainDir == "" || GCCToolchainDir == D.SysRoot + "/usr") {
1685  SmallVector<StringRef, 16> GentooTestTriples;
1686  // Try to match an exact triple as target triple first.
1687  // e.g. crossdev -S x86_64-gentoo-linux-gnu will install gcc libs for
1688  // x86_64-gentoo-linux-gnu. But "clang -target x86_64-gentoo-linux-gnu"
1689  // may pick the libraries for x86_64-pc-linux-gnu even when exact matching
1690  // triple x86_64-gentoo-linux-gnu is present.
1691  GentooTestTriples.push_back(TargetTriple.str());
1692  // Check rest of triples.
1693  GentooTestTriples.append(ExtraTripleAliases.begin(),
1694  ExtraTripleAliases.end());
1695  GentooTestTriples.append(CandidateTripleAliases.begin(),
1696  CandidateTripleAliases.end());
1697  if (ScanGentooConfigs(TargetTriple, Args, GentooTestTriples,
1698  CandidateBiarchTripleAliases))
1699  return;
1700  }
1701 
1702  // Loop over the various components which exist and select the best GCC
1703  // installation available. GCC installs are ranked by version number.
1704  Version = GCCVersion::Parse("0.0.0");
1705  for (const std::string &Prefix : Prefixes) {
1706  if (!D.getVFS().exists(Prefix))
1707  continue;
1708  for (StringRef Suffix : CandidateLibDirs) {
1709  const std::string LibDir = Prefix + Suffix.str();
1710  if (!D.getVFS().exists(LibDir))
1711  continue;
1712  // Try to match the exact target triple first.
1713  ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, TargetTriple.str());
1714  // Try rest of possible triples.
1715  for (StringRef Candidate : ExtraTripleAliases) // Try these first.
1716  ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate);
1717  for (StringRef Candidate : CandidateTripleAliases)
1718  ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate);
1719  }
1720  for (StringRef Suffix : CandidateBiarchLibDirs) {
1721  const std::string LibDir = Prefix + Suffix.str();
1722  if (!D.getVFS().exists(LibDir))
1723  continue;
1724  for (StringRef Candidate : CandidateBiarchTripleAliases)
1725  ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate,
1726  /*NeedsBiarchSuffix=*/ true);
1727  }
1728  }
1729 }
1730 
1731 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
1732  for (const auto &InstallPath : CandidateGCCInstallPaths)
1733  OS << "Found candidate GCC installation: " << InstallPath << "\n";
1734 
1735  if (!GCCInstallPath.empty())
1736  OS << "Selected GCC installation: " << GCCInstallPath << "\n";
1737 
1738  for (const auto &Multilib : Multilibs)
1739  OS << "Candidate multilib: " << Multilib << "\n";
1740 
1741  if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
1742  OS << "Selected multilib: " << SelectedMultilib << "\n";
1743 }
1744 
1746  if (BiarchSibling.hasValue()) {
1747  M = BiarchSibling.getValue();
1748  return true;
1749  }
1750  return false;
1751 }
1752 
1753 void Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes(
1754  const llvm::Triple &TargetTriple, SmallVectorImpl<std::string> &Prefixes,
1755  StringRef SysRoot) {
1756  if (TargetTriple.getOS() == llvm::Triple::Solaris) {
1757  // Solaris is a special case.
1758  // The GCC installation is under
1759  // /usr/gcc/<major>.<minor>/lib/gcc/<triple>/<major>.<minor>.<patch>/
1760  // so we need to find those /usr/gcc/*/lib/gcc libdirs and go with
1761  // /usr/gcc/<version> as a prefix.
1762 
1763  std::string PrefixDir = SysRoot.str() + "/usr/gcc";
1764  std::error_code EC;
1765  for (vfs::directory_iterator LI = D.getVFS().dir_begin(PrefixDir, EC), LE;
1766  !EC && LI != LE; LI = LI.increment(EC)) {
1767  StringRef VersionText = llvm::sys::path::filename(LI->path());
1768  GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
1769 
1770  // Filter out obviously bad entries.
1771  if (CandidateVersion.Major == -1 || CandidateVersion.isOlderThan(4, 1, 1))
1772  continue;
1773 
1774  std::string CandidatePrefix = PrefixDir + "/" + VersionText.str();
1775  std::string CandidateLibPath = CandidatePrefix + "/lib/gcc";
1776  if (!D.getVFS().exists(CandidateLibPath))
1777  continue;
1778 
1779  Prefixes.push_back(CandidatePrefix);
1780  }
1781  return;
1782  }
1783 
1784  // Non-Solaris is much simpler - most systems just go with "/usr".
1785  if (SysRoot.empty() && TargetTriple.getOS() == llvm::Triple::Linux) {
1786  // Yet, still look for RHEL devtoolsets.
1787  Prefixes.push_back("/opt/rh/devtoolset-7/root/usr");
1788  Prefixes.push_back("/opt/rh/devtoolset-6/root/usr");
1789  Prefixes.push_back("/opt/rh/devtoolset-4/root/usr");
1790  Prefixes.push_back("/opt/rh/devtoolset-3/root/usr");
1791  Prefixes.push_back("/opt/rh/devtoolset-2/root/usr");
1792  }
1793  Prefixes.push_back(SysRoot.str() + "/usr");
1794 }
1795 
1796 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1797  const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
1798  SmallVectorImpl<StringRef> &LibDirs,
1799  SmallVectorImpl<StringRef> &TripleAliases,
1800  SmallVectorImpl<StringRef> &BiarchLibDirs,
1801  SmallVectorImpl<StringRef> &BiarchTripleAliases) {
1802  // Declare a bunch of static data sets that we'll select between below. These
1803  // are specifically designed to always refer to string literals to avoid any
1804  // lifetime or initialization issues.
1805  static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
1806  static const char *const AArch64Triples[] = {
1807  "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-redhat-linux",
1808  "aarch64-suse-linux"};
1809  static const char *const AArch64beLibDirs[] = {"/lib"};
1810  static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu",
1811  "aarch64_be-linux-gnu"};
1812 
1813  static const char *const ARMLibDirs[] = {"/lib"};
1814  static const char *const ARMTriples[] = {"arm-linux-gnueabi"};
1815  static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf",
1816  "armv7hl-redhat-linux-gnueabi",
1817  "armv6hl-suse-linux-gnueabi",
1818  "armv7hl-suse-linux-gnueabi"};
1819  static const char *const ARMebLibDirs[] = {"/lib"};
1820  static const char *const ARMebTriples[] = {"armeb-linux-gnueabi"};
1821  static const char *const ARMebHFTriples[] = {
1822  "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
1823 
1824  static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
1825  static const char *const X86_64Triples[] = {
1826  "x86_64-linux-gnu", "x86_64-unknown-linux-gnu",
1827  "x86_64-pc-linux-gnu", "x86_64-redhat-linux6E",
1828  "x86_64-redhat-linux", "x86_64-suse-linux",
1829  "x86_64-manbo-linux-gnu", "x86_64-linux-gnu",
1830  "x86_64-slackware-linux", "x86_64-unknown-linux",
1831  "x86_64-amazon-linux"};
1832  static const char *const X32LibDirs[] = {"/libx32"};
1833  static const char *const X86LibDirs[] = {"/lib32", "/lib"};
1834  static const char *const X86Triples[] = {
1835  "i686-linux-gnu", "i686-pc-linux-gnu", "i486-linux-gnu",
1836  "i386-linux-gnu", "i386-redhat-linux6E", "i686-redhat-linux",
1837  "i586-redhat-linux", "i386-redhat-linux", "i586-suse-linux",
1838  "i486-slackware-linux", "i686-montavista-linux", "i586-linux-gnu"};
1839 
1840  static const char *const MIPSLibDirs[] = {"/lib"};
1841  static const char *const MIPSTriples[] = {"mips-linux-gnu", "mips-mti-linux",
1842  "mips-mti-linux-gnu",
1843  "mips-img-linux-gnu"};
1844  static const char *const MIPSELLibDirs[] = {"/lib"};
1845  static const char *const MIPSELTriples[] = {"mipsel-linux-gnu",
1846  "mips-img-linux-gnu"};
1847 
1848  static const char *const MIPS64LibDirs[] = {"/lib64", "/lib"};
1849  static const char *const MIPS64Triples[] = {
1850  "mips64-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu",
1851  "mips64-linux-gnuabi64"};
1852  static const char *const MIPS64ELLibDirs[] = {"/lib64", "/lib"};
1853  static const char *const MIPS64ELTriples[] = {
1854  "mips64el-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu",
1855  "mips64el-linux-gnuabi64"};
1856 
1857 
1858  static const char *const PPCLibDirs[] = {"/lib32", "/lib"};
1859  static const char *const PPCTriples[] = {
1860  "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
1861  "powerpc-suse-linux", "powerpc-montavista-linuxspe"};
1862  static const char *const PPC64LibDirs[] = {"/lib64", "/lib"};
1863  static const char *const PPC64Triples[] = {
1864  "powerpc64-linux-gnu", "powerpc64-unknown-linux-gnu",
1865  "powerpc64-suse-linux", "ppc64-redhat-linux"};
1866  static const char *const PPC64LELibDirs[] = {"/lib64", "/lib"};
1867  static const char *const PPC64LETriples[] = {
1868  "powerpc64le-linux-gnu", "powerpc64le-unknown-linux-gnu",
1869  "powerpc64le-suse-linux", "ppc64le-redhat-linux"};
1870 
1871  static const char *const RISCV32LibDirs[] = {"/lib", "/lib32"};
1872  static const char *const RISCVTriples[] = {"riscv32-unknown-linux-gnu",
1873  "riscv64-unknown-linux-gnu",
1874  "riscv32-unknown-elf"};
1875 
1876  static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"};
1877  static const char *const SPARCv8Triples[] = {"sparc-linux-gnu",
1878  "sparcv8-linux-gnu"};
1879  static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"};
1880  static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu",
1881  "sparcv9-linux-gnu"};
1882 
1883  static const char *const SystemZLibDirs[] = {"/lib64", "/lib"};
1884  static const char *const SystemZTriples[] = {
1885  "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
1886  "s390x-suse-linux", "s390x-redhat-linux"};
1887 
1888 
1889  using std::begin;
1890  using std::end;
1891 
1892  if (TargetTriple.getOS() == llvm::Triple::Solaris) {
1893  static const char *const SolarisLibDirs[] = {"/lib"};
1894  static const char *const SolarisSparcV8Triples[] = {
1895  "sparc-sun-solaris2.11", "sparc-sun-solaris2.12"};
1896  static const char *const SolarisSparcV9Triples[] = {
1897  "sparcv9-sun-solaris2.11", "sparcv9-sun-solaris2.12"};
1898  static const char *const SolarisX86Triples[] = {"i386-pc-solaris2.11",
1899  "i386-pc-solaris2.12"};
1900  static const char *const SolarisX86_64Triples[] = {"x86_64-pc-solaris2.11",
1901  "x86_64-pc-solaris2.12"};
1902  LibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
1903  BiarchLibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
1904  switch (TargetTriple.getArch()) {
1905  case llvm::Triple::x86:
1906  TripleAliases.append(begin(SolarisX86Triples), end(SolarisX86Triples));
1907  BiarchTripleAliases.append(begin(SolarisX86_64Triples),
1908  end(SolarisX86_64Triples));
1909  break;
1910  case llvm::Triple::x86_64:
1911  TripleAliases.append(begin(SolarisX86_64Triples),
1912  end(SolarisX86_64Triples));
1913  BiarchTripleAliases.append(begin(SolarisX86Triples),
1914  end(SolarisX86Triples));
1915  break;
1916  case llvm::Triple::sparc:
1917  TripleAliases.append(begin(SolarisSparcV8Triples),
1918  end(SolarisSparcV8Triples));
1919  BiarchTripleAliases.append(begin(SolarisSparcV9Triples),
1920  end(SolarisSparcV9Triples));
1921  break;
1922  case llvm::Triple::sparcv9:
1923  TripleAliases.append(begin(SolarisSparcV9Triples),
1924  end(SolarisSparcV9Triples));
1925  BiarchTripleAliases.append(begin(SolarisSparcV8Triples),
1926  end(SolarisSparcV8Triples));
1927  break;
1928  default:
1929  break;
1930  }
1931  return;
1932  }
1933 
1934  // Android targets should not use GNU/Linux tools or libraries.
1935  if (TargetTriple.isAndroid()) {
1936  static const char *const AArch64AndroidTriples[] = {
1937  "aarch64-linux-android"};
1938  static const char *const ARMAndroidTriples[] = {"arm-linux-androideabi"};
1939  static const char *const MIPSELAndroidTriples[] = {"mipsel-linux-android"};
1940  static const char *const MIPS64ELAndroidTriples[] = {
1941  "mips64el-linux-android"};
1942  static const char *const X86AndroidTriples[] = {"i686-linux-android"};
1943  static const char *const X86_64AndroidTriples[] = {"x86_64-linux-android"};
1944 
1945  switch (TargetTriple.getArch()) {
1946  case llvm::Triple::aarch64:
1947  LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1948  TripleAliases.append(begin(AArch64AndroidTriples),
1949  end(AArch64AndroidTriples));
1950  break;
1951  case llvm::Triple::arm:
1952  case llvm::Triple::thumb:
1953  LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
1954  TripleAliases.append(begin(ARMAndroidTriples), end(ARMAndroidTriples));
1955  break;
1956  case llvm::Triple::mipsel:
1957  LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1958  TripleAliases.append(begin(MIPSELAndroidTriples),
1959  end(MIPSELAndroidTriples));
1960  BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1961  BiarchTripleAliases.append(begin(MIPS64ELAndroidTriples),
1962  end(MIPS64ELAndroidTriples));
1963  break;
1964  case llvm::Triple::mips64el:
1965  LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1966  TripleAliases.append(begin(MIPS64ELAndroidTriples),
1967  end(MIPS64ELAndroidTriples));
1968  BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1969  BiarchTripleAliases.append(begin(MIPSELAndroidTriples),
1970  end(MIPSELAndroidTriples));
1971  break;
1972  case llvm::Triple::x86_64:
1973  LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1974  TripleAliases.append(begin(X86_64AndroidTriples),
1975  end(X86_64AndroidTriples));
1976  BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1977  BiarchTripleAliases.append(begin(X86AndroidTriples),
1978  end(X86AndroidTriples));
1979  break;
1980  case llvm::Triple::x86:
1981  LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1982  TripleAliases.append(begin(X86AndroidTriples), end(X86AndroidTriples));
1983  BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1984  BiarchTripleAliases.append(begin(X86_64AndroidTriples),
1985  end(X86_64AndroidTriples));
1986  break;
1987  default:
1988  break;
1989  }
1990 
1991  return;
1992  }
1993 
1994  switch (TargetTriple.getArch()) {
1995  case llvm::Triple::aarch64:
1996  LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1997  TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1998  BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1999  BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
2000  break;
2001  case llvm::Triple::aarch64_be:
2002  LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
2003  TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
2004  BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
2005  BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
2006  break;
2007  case llvm::Triple::arm:
2008  case llvm::Triple::thumb:
2009  LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
2010  if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2011  TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
2012  } else {
2013  TripleAliases.append(begin(ARMTriples), end(ARMTriples));
2014  }
2015  break;
2016  case llvm::Triple::armeb:
2017  case llvm::Triple::thumbeb:
2018  LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
2019  if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2020  TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
2021  } else {
2022  TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
2023  }
2024  break;
2025  case llvm::Triple::x86_64:
2026  LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2027  TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2028  // x32 is always available when x86_64 is available, so adding it as
2029  // secondary arch with x86_64 triples
2030  if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32) {
2031  BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
2032  BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2033  } else {
2034  BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2035  BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
2036  }
2037  break;
2038  case llvm::Triple::x86:
2039  LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2040  // MCU toolchain is 32 bit only and its triple alias is TargetTriple
2041  // itself, which will be appended below.
2042  if (!TargetTriple.isOSIAMCU()) {
2043  TripleAliases.append(begin(X86Triples), end(X86Triples));
2044  BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2045  BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2046  }
2047  break;
2048  case llvm::Triple::mips:
2049  LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
2050  TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2051  BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
2052  BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
2053  break;
2054  case llvm::Triple::mipsel:
2055  LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2056  TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
2057  TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2058  BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2059  BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
2060  break;
2061  case llvm::Triple::mips64:
2062  LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
2063  TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
2064  BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
2065  BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2066  break;
2067  case llvm::Triple::mips64el:
2068  LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2069  TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
2070  BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2071  BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
2072  BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2073  break;
2074  case llvm::Triple::ppc:
2075  LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
2076  TripleAliases.append(begin(PPCTriples), end(PPCTriples));
2077  BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
2078  BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
2079  break;
2080  case llvm::Triple::ppc64:
2081  LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
2082  TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
2083  BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
2084  BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
2085  break;
2086  case llvm::Triple::ppc64le:
2087  LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
2088  TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
2089  break;
2090  case llvm::Triple::riscv32:
2091  LibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
2092  BiarchLibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
2093  TripleAliases.append(begin(RISCVTriples), end(RISCVTriples));
2094  BiarchTripleAliases.append(begin(RISCVTriples), end(RISCVTriples));
2095  break;
2096  case llvm::Triple::sparc:
2097  case llvm::Triple::sparcel:
2098  LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
2099  TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
2100  BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
2101  BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
2102  break;
2103  case llvm::Triple::sparcv9:
2104  LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
2105  TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
2106  BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
2107  BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
2108  break;
2109  case llvm::Triple::systemz:
2110  LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
2111  TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
2112  break;
2113  default:
2114  // By default, just rely on the standard lib directories and the original
2115  // triple.
2116  break;
2117  }
2118 
2119  // Always append the drivers target triple to the end, in case it doesn't
2120  // match any of our aliases.
2121  TripleAliases.push_back(TargetTriple.str());
2122 
2123  // Also include the multiarch variant if it's different.
2124  if (TargetTriple.str() != BiarchTriple.str())
2125  BiarchTripleAliases.push_back(BiarchTriple.str());
2126 }
2127 
2128 bool Generic_GCC::GCCInstallationDetector::ScanGCCForMultilibs(
2129  const llvm::Triple &TargetTriple, const ArgList &Args,
2130  StringRef Path, bool NeedsBiarchSuffix) {
2131  llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2132  DetectedMultilibs Detected;
2133 
2134  // Android standalone toolchain could have multilibs for ARM and Thumb.
2135  // Debian mips multilibs behave more like the rest of the biarch ones,
2136  // so handle them there
2137  if (isArmOrThumbArch(TargetArch) && TargetTriple.isAndroid()) {
2138  // It should also work without multilibs in a simplified toolchain.
2139  findAndroidArmMultilibs(D, TargetTriple, Path, Args, Detected);
2140  } else if (TargetTriple.isMIPS()) {
2141  if (!findMIPSMultilibs(D, TargetTriple, Path, Args, Detected))
2142  return false;
2143  } else if (isRISCV(TargetArch)) {
2144  findRISCVMultilibs(D, TargetTriple, Path, Args, Detected);
2145  } else if (!findBiarchMultilibs(D, TargetTriple, Path, Args,
2146  NeedsBiarchSuffix, Detected)) {
2147  return false;
2148  }
2149 
2150  Multilibs = Detected.Multilibs;
2151  SelectedMultilib = Detected.SelectedMultilib;
2152  BiarchSibling = Detected.BiarchSibling;
2153 
2154  return true;
2155 }
2156 
2157 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
2158  const llvm::Triple &TargetTriple, const ArgList &Args,
2159  const std::string &LibDir, StringRef CandidateTriple,
2160  bool NeedsBiarchSuffix) {
2161  llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2162  // Locations relative to the system lib directory where GCC's triple-specific
2163  // directories might reside.
2164  struct GCCLibSuffix {
2165  // Path from system lib directory to GCC triple-specific directory.
2166  std::string LibSuffix;
2167  // Path from GCC triple-specific directory back to system lib directory.
2168  // This is one '..' component per component in LibSuffix.
2169  StringRef ReversePath;
2170  // Whether this library suffix is relevant for the triple.
2171  bool Active;
2172  } Suffixes[] = {
2173  // This is the normal place.
2174  {"gcc/" + CandidateTriple.str(), "../..", true},
2175 
2176  // Debian puts cross-compilers in gcc-cross.
2177  {"gcc-cross/" + CandidateTriple.str(), "../..",
2178  TargetTriple.getOS() != llvm::Triple::Solaris},
2179 
2180  // The Freescale PPC SDK has the gcc libraries in
2181  // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well. Only do
2182  // this on Freescale triples, though, since some systems put a *lot* of
2183  // files in that location, not just GCC installation data.
2184  {CandidateTriple.str(), "..",
2185  TargetTriple.getVendor() == llvm::Triple::Freescale ||
2186  TargetTriple.getVendor() == llvm::Triple::OpenEmbedded},
2187 
2188  // Natively multiarch systems sometimes put the GCC triple-specific
2189  // directory within their multiarch lib directory, resulting in the
2190  // triple appearing twice.
2191  {CandidateTriple.str() + "/gcc/" + CandidateTriple.str(), "../../..",
2192  TargetTriple.getOS() != llvm::Triple::Solaris},
2193 
2194  // Deal with cases (on Ubuntu) where the system architecture could be i386
2195  // but the GCC target architecture could be (say) i686.
2196  // FIXME: It may be worthwhile to generalize this and look for a second
2197  // triple.
2198  {"i386-linux-gnu/gcc/" + CandidateTriple.str(), "../../..",
2199  (TargetArch == llvm::Triple::x86 &&
2200  TargetTriple.getOS() != llvm::Triple::Solaris)}};
2201 
2202  for (auto &Suffix : Suffixes) {
2203  if (!Suffix.Active)
2204  continue;
2205 
2206  StringRef LibSuffix = Suffix.LibSuffix;
2207  std::error_code EC;
2209  LI = D.getVFS().dir_begin(LibDir + "/" + LibSuffix, EC),
2210  LE;
2211  !EC && LI != LE; LI = LI.increment(EC)) {
2212  StringRef VersionText = llvm::sys::path::filename(LI->path());
2213  GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2214  if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2215  if (!CandidateGCCInstallPaths.insert(LI->path()).second)
2216  continue; // Saw this path before; no need to look at it again.
2217  if (CandidateVersion.isOlderThan(4, 1, 1))
2218  continue;
2219  if (CandidateVersion <= Version)
2220  continue;
2221 
2222  if (!ScanGCCForMultilibs(TargetTriple, Args, LI->path(),
2223  NeedsBiarchSuffix))
2224  continue;
2225 
2226  Version = CandidateVersion;
2227  GCCTriple.setTriple(CandidateTriple);
2228  // FIXME: We hack together the directory name here instead of
2229  // using LI to ensure stable path separators across Windows and
2230  // Linux.
2231  GCCInstallPath = (LibDir + "/" + LibSuffix + "/" + VersionText).str();
2232  GCCParentLibPath = (GCCInstallPath + "/../" + Suffix.ReversePath).str();
2233  IsValid = true;
2234  }
2235  }
2236 }
2237 
2238 bool Generic_GCC::GCCInstallationDetector::ScanGentooConfigs(
2239  const llvm::Triple &TargetTriple, const ArgList &Args,
2240  const SmallVectorImpl<StringRef> &CandidateTriples,
2241  const SmallVectorImpl<StringRef> &CandidateBiarchTriples) {
2242  for (StringRef CandidateTriple : CandidateTriples) {
2243  if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple))
2244  return true;
2245  }
2246 
2247  for (StringRef CandidateTriple : CandidateBiarchTriples) {
2248  if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple, true))
2249  return true;
2250  }
2251  return false;
2252 }
2253 
2254 bool Generic_GCC::GCCInstallationDetector::ScanGentooGccConfig(
2255  const llvm::Triple &TargetTriple, const ArgList &Args,
2256  StringRef CandidateTriple, bool NeedsBiarchSuffix) {
2257  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
2258  D.getVFS().getBufferForFile(D.SysRoot + "/etc/env.d/gcc/config-" +
2259  CandidateTriple.str());
2260  if (File) {
2262  File.get()->getBuffer().split(Lines, "\n");
2263  for (StringRef Line : Lines) {
2264  Line = Line.trim();
2265  // CURRENT=triple-version
2266  if (!Line.consume_front("CURRENT="))
2267  continue;
2268  // Process the config file pointed to by CURRENT.
2269  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ConfigFile =
2270  D.getVFS().getBufferForFile(D.SysRoot + "/etc/env.d/gcc/" +
2271  Line.str());
2272  std::pair<StringRef, StringRef> ActiveVersion = Line.rsplit('-');
2273  // List of paths to scan for libraries.
2274  SmallVector<StringRef, 4> GentooScanPaths;
2275  // Scan the Config file to find installed GCC libraries path.
2276  // Typical content of the GCC config file:
2277  // LDPATH="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x:/usr/lib/gcc/
2278  // (continued from previous line) x86_64-pc-linux-gnu/4.9.x/32"
2279  // MANPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/man"
2280  // INFOPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/info"
2281  // STDCXX_INCDIR="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x/include/g++-v4"
2282  // We are looking for the paths listed in LDPATH=... .
2283  if (ConfigFile) {
2284  SmallVector<StringRef, 2> ConfigLines;
2285  ConfigFile.get()->getBuffer().split(ConfigLines, "\n");
2286  for (StringRef ConfLine : ConfigLines) {
2287  ConfLine = ConfLine.trim();
2288  if (ConfLine.consume_front("LDPATH=")) {
2289  // Drop '"' from front and back if present.
2290  ConfLine.consume_back("\"");
2291  ConfLine.consume_front("\"");
2292  // Get all paths sperated by ':'
2293  ConfLine.split(GentooScanPaths, ':', -1, /*AllowEmpty*/ false);
2294  }
2295  }
2296  }
2297  // Test the path based on the version in /etc/env.d/gcc/config-{tuple}.
2298  std::string basePath = "/usr/lib/gcc/" + ActiveVersion.first.str() + "/"
2299  + ActiveVersion.second.str();
2300  GentooScanPaths.push_back(StringRef(basePath));
2301 
2302  // Scan all paths for GCC libraries.
2303  for (const auto &GentooScanPath : GentooScanPaths) {
2304  std::string GentooPath = D.SysRoot + std::string(GentooScanPath);
2305  if (D.getVFS().exists(GentooPath + "/crtbegin.o")) {
2306  if (!ScanGCCForMultilibs(TargetTriple, Args, GentooPath,
2307  NeedsBiarchSuffix))
2308  continue;
2309 
2310  Version = GCCVersion::Parse(ActiveVersion.second);
2311  GCCInstallPath = GentooPath;
2312  GCCParentLibPath = GentooPath + std::string("/../../..");
2313  GCCTriple.setTriple(ActiveVersion.first);
2314  IsValid = true;
2315  return true;
2316  }
2317  }
2318  }
2319  }
2320 
2321  return false;
2322 }
2323 
2324 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple,
2325  const ArgList &Args)
2326  : ToolChain(D, Triple, Args), GCCInstallation(D),
2327  CudaInstallation(D, Triple, Args) {
2328  getProgramPaths().push_back(getDriver().getInstalledDir());
2329  if (getDriver().getInstalledDir() != getDriver().Dir)
2330  getProgramPaths().push_back(getDriver().Dir);
2331 }
2332 
2334 
2336  switch (AC) {
2338  if (!Preprocess)
2339  Preprocess.reset(new clang::driver::tools::gcc::Preprocessor(*this));
2340  return Preprocess.get();
2342  if (!Compile)
2343  Compile.reset(new tools::gcc::Compiler(*this));
2344  return Compile.get();
2345  default:
2346  return ToolChain::getTool(AC);
2347  }
2348 }
2349 
2351  return new tools::gnutools::Assembler(*this);
2352 }
2353 
2354 Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); }
2355 
2356 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
2357  // Print the information about how we detected the GCC installation.
2358  GCCInstallation.print(OS);
2359  CudaInstallation.print(OS);
2360 }
2361 
2362 bool Generic_GCC::IsUnwindTablesDefault(const ArgList &Args) const {
2363  return getArch() == llvm::Triple::x86_64;
2364 }
2365 
2367  switch (getArch()) {
2368  case llvm::Triple::x86_64:
2369  return getTriple().isOSWindows();
2370  case llvm::Triple::ppc64:
2371  case llvm::Triple::ppc64le:
2372  return !getTriple().isOSBinFormatMachO() && !getTriple().isMacOSX();
2373  case llvm::Triple::mips64:
2374  case llvm::Triple::mips64el:
2375  return true;
2376  default:
2377  return false;
2378  }
2379 }
2380 
2381 bool Generic_GCC::isPIEDefault() const { return false; }
2382 
2384  return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
2385 }
2386 
2388  switch (getTriple().getArch()) {
2389  case llvm::Triple::x86:
2390  case llvm::Triple::x86_64:
2391  case llvm::Triple::aarch64:
2392  case llvm::Triple::aarch64_be:
2393  case llvm::Triple::arm:
2394  case llvm::Triple::armeb:
2395  case llvm::Triple::avr:
2396  case llvm::Triple::bpfel:
2397  case llvm::Triple::bpfeb:
2398  case llvm::Triple::thumb:
2399  case llvm::Triple::thumbeb:
2400  case llvm::Triple::ppc:
2401  case llvm::Triple::ppc64:
2402  case llvm::Triple::ppc64le:
2403  case llvm::Triple::riscv32:
2404  case llvm::Triple::riscv64:
2405  case llvm::Triple::systemz:
2406  case llvm::Triple::mips:
2407  case llvm::Triple::mipsel:
2408  return true;
2409  case llvm::Triple::mips64:
2410  case llvm::Triple::mips64el:
2411  // Enabled for Debian, Android, FreeBSD and OpenBSD mips64/mipsel, as they
2412  // can precisely identify the ABI in use (Debian) or only use N64 for MIPS64
2413  // (Android). Other targets are unable to distinguish N32 from N64.
2414  if (getTriple().getEnvironment() == llvm::Triple::GNUABI64 ||
2415  getTriple().isAndroid() ||
2416  getTriple().isOSFreeBSD() ||
2417  getTriple().isOSOpenBSD())
2418  return true;
2419  return false;
2420  default:
2421  return false;
2422  }
2423 }
2424 
2425 void Generic_GCC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2426  ArgStringList &CC1Args) const {
2427  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2428  DriverArgs.hasArg(options::OPT_nostdincxx))
2429  return;
2430 
2431  switch (GetCXXStdlibType(DriverArgs)) {
2432  case ToolChain::CST_Libcxx:
2433  addLibCxxIncludePaths(DriverArgs, CC1Args);
2434  break;
2435 
2437  addLibStdCxxIncludePaths(DriverArgs, CC1Args);
2438  break;
2439  }
2440 }
2441 
2442 void
2443 Generic_GCC::addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
2444  llvm::opt::ArgStringList &CC1Args) const {
2445  // FIXME: The Linux behavior would probaby be a better approach here.
2446  addSystemInclude(DriverArgs, CC1Args,
2447  getDriver().SysRoot + "/usr/include/c++/v1");
2448 }
2449 
2450 void
2451 Generic_GCC::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
2452  llvm::opt::ArgStringList &CC1Args) const {
2453  // By default, we don't assume we know where libstdc++ might be installed.
2454  // FIXME: If we have a valid GCCInstallation, use it.
2455 }
2456 
2457 /// Helper to add the variant paths of a libstdc++ installation.
2459  Twine Base, Twine Suffix, StringRef GCCTriple, StringRef GCCMultiarchTriple,
2460  StringRef TargetMultiarchTriple, Twine IncludeSuffix,
2461  const ArgList &DriverArgs, ArgStringList &CC1Args) const {
2462  if (!getVFS().exists(Base + Suffix))
2463  return false;
2464 
2465  addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
2466 
2467  // The vanilla GCC layout of libstdc++ headers uses a triple subdirectory. If
2468  // that path exists or we have neither a GCC nor target multiarch triple, use
2469  // this vanilla search path.
2470  if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) ||
2471  getVFS().exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) {
2472  addSystemInclude(DriverArgs, CC1Args,
2473  Base + Suffix + "/" + GCCTriple + IncludeSuffix);
2474  } else {
2475  // Otherwise try to use multiarch naming schemes which have normalized the
2476  // triples and put the triple before the suffix.
2477  //
2478  // GCC surprisingly uses *both* the GCC triple with a multilib suffix and
2479  // the target triple, so we support that here.
2480  addSystemInclude(DriverArgs, CC1Args,
2481  Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
2482  addSystemInclude(DriverArgs, CC1Args,
2483  Base + "/" + TargetMultiarchTriple + Suffix);
2484  }
2485 
2486  addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
2487  return true;
2488 }
2489 
2490 llvm::opt::DerivedArgList *
2491 Generic_GCC::TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef,
2492  Action::OffloadKind DeviceOffloadKind) const {
2493 
2494  // If this tool chain is used for an OpenMP offloading device we have to make
2495  // sure we always generate a shared library regardless of the commands the
2496  // user passed to the host. This is required because the runtime library
2497  // is required to load the device image dynamically at run time.
2498  if (DeviceOffloadKind == Action::OFK_OpenMP) {
2499  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
2500  const OptTable &Opts = getDriver().getOpts();
2501 
2502  // Request the shared library. Given that these options are decided
2503  // implicitly, they do not refer to any base argument.
2504  DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_shared));
2505  DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_fPIC));
2506 
2507  // Filter all the arguments we don't care passing to the offloading
2508  // toolchain as they can mess up with the creation of a shared library.
2509  for (auto *A : Args) {
2510  switch ((options::ID)A->getOption().getID()) {
2511  default:
2512  DAL->append(A);
2513  break;
2514  case options::OPT_shared:
2515  case options::OPT_dynamic:
2516  case options::OPT_static:
2517  case options::OPT_fPIC:
2518  case options::OPT_fno_PIC:
2519  case options::OPT_fpic:
2520  case options::OPT_fno_pic:
2521  case options::OPT_fPIE:
2522  case options::OPT_fno_PIE:
2523  case options::OPT_fpie:
2524  case options::OPT_fno_pie:
2525  break;
2526  }
2527  }
2528  return DAL;
2529  }
2530  return nullptr;
2531 }
2532 
2533 void Generic_ELF::anchor() {}
2534 
2535 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
2536  ArgStringList &CC1Args,
2537  Action::OffloadKind) const {
2539  bool UseInitArrayDefault =
2540  getTriple().getArch() == llvm::Triple::aarch64 ||
2541  getTriple().getArch() == llvm::Triple::aarch64_be ||
2542  (getTriple().getOS() == llvm::Triple::FreeBSD &&
2543  getTriple().getOSMajorVersion() >= 12) ||
2544  (getTriple().getOS() == llvm::Triple::Linux &&
2545  ((!GCCInstallation.isValid() || !V.isOlderThan(4, 7, 0)) ||
2546  getTriple().isAndroid())) ||
2547  getTriple().getOS() == llvm::Triple::NaCl ||
2548  (getTriple().getVendor() == llvm::Triple::MipsTechnologies &&
2549  !getTriple().hasEnvironment()) ||
2550  getTriple().getOS() == llvm::Triple::Solaris ||
2551  getTriple().getArch() == llvm::Triple::riscv32 ||
2552  getTriple().getArch() == llvm::Triple::riscv64;
2553 
2554  if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
2555  options::OPT_fno_use_init_array, UseInitArrayDefault))
2556  CC1Args.push_back("-fuse-init-array");
2557 }
const char * getPPCAsmModeForCPU(StringRef Name)
Definition: PPC.cpp:89
MultilibSet & Either(const Multilib &M1, const Multilib &M2)
Add a set of mutually incompatible Multilib segments.
Definition: Multilib.cpp:152
MultilibSet & Maybe(const Multilib &M)
Add an optional Multilib segment.
Definition: Multilib.cpp:142
bool isPIEDefault() const override
Test whether this toolchain defaults to PIE.
Definition: Linux.cpp:905
virtual std::string getDynamicLinker(const llvm::opt::ArgList &Args) const
Definition: Linux.cpp:482
Tool * buildLinker() const override
Definition: Gnu.cpp:2354
bool addXRayRuntime(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
const char * getSystemZTargetCPU(const llvm::opt::ArgList &Args)
prefix_list PrefixDirs
Definition: Driver.h:146
const char * getSparcAsmModeForCPU(llvm::StringRef Name, const llvm::Triple &Triple)
static bool getPIE(const ArgList &Args, const toolchains::Linux &ToolChain)
Definition: Gnu.cpp:285
bool shouldUseFPXX(const llvm::opt::ArgList &Args, const llvm::Triple &Triple, StringRef CPUName, StringRef ABIName, mips::FloatABI FloatABI)
bool isDefault() const
Check whether the default is selected.
Definition: Multilib.h:102
Tool * getTool(Action::ActionClass AC) const override
Definition: Gnu.cpp:2335
bool getBiarchSibling(Multilib &M) const
Get the biarch sibling multilib (if it exists).
Definition: Gnu.cpp:1745
llvm::Optional< Multilib > BiarchSibling
On Biarch systems, this corresponds to the default multilib when targeting the non-default multilib...
Definition: Gnu.h:30
static llvm::StringRef getGCCToolchainDir(const ArgList &Args)
Definition: Gnu.cpp:1621
bool isUsingLTO() const
Returns true if we are performing any kind of LTO.
Definition: Driver.h:519
static GCCVersion Parse(StringRef VersionText)
Parse a GCCVersion object out of a string of text.
Definition: Gnu.cpp:1574
static bool findMipsAndroidMultilibs(vfs::FileSystem &VFS, StringRef Path, const Multilib::flags_list &Flags, FilterNonExistent &NonExistent, DetectedMultilibs &Result)
Definition: Gnu.cpp:943
std::string DyldPrefix
Dynamic loader prefix, if present.
Definition: Driver.h:152
bool canTypeBeUserSpecified(ID Id)
canTypeBeUserSpecified - Can this type be specified on the command line (by the type name); this is u...
Definition: Types.cpp:80
void AddRunTimeLibs(const ToolChain &TC, const Driver &D, llvm::opt::ArgStringList &CmdArgs, const llvm::opt::ArgList &Args)
void AddHIPLinkerScript(const ToolChain &TC, Compilation &C, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const JobAction &JA, const Tool &T)
bool isHostOffloading(OffloadKind OKind) const
Check if this action have any offload kinds.
Definition: Action.h:202
LTOKind getLTOMode() const
Get the specific kind of LTO being performed.
Definition: Driver.h:522
DiagnosticBuilder Diag(unsigned DiagID) const
Definition: Driver.h:110
Struct to store and manipulate GCC versions.
Definition: Gnu.h:157
void RenderExtraToolArgs(const JobAction &JA, llvm::opt::ArgStringList &CmdArgs) const override
RenderExtraToolArgs - Render any arguments necessary to force the particular tool mode...
Definition: Gnu.cpp:226
virtual directory_iterator dir_begin(const Twine &Dir, std::error_code &EC)=0
Get a directory_iterator for Dir.
std::string GetLinkerPath() const
Returns the linker path, respecting the -fuse-ld= argument to determine the linker suffix or name...
Definition: ToolChain.cpp:431
FloatABI getARMFloatABI(const ToolChain &TC, const llvm::opt::ArgList &Args)
std::string PatchSuffix
Any textual suffix on the patch number.
Definition: Gnu.h:168
bool isPIEDefault() const override
Test whether this toolchain defaults to PIE.
Definition: Gnu.cpp:2381
bool select(const Multilib::flags_list &Flags, Multilib &M) const
Pick the best multilib in the set,.
Definition: Multilib.cpp:244
void print(raw_ostream &OS) const
Print information about the detected CUDA installation.
Definition: Cuda.cpp:272
The virtual file system interface.
Multilib & flag(StringRef F)
Add a flag to the flags list Flag must be a flag accepted by the driver with its leading &#39;-&#39; removed...
Definition: Multilib.h:88
std::string getCPUName(const llvm::opt::ArgList &Args, const llvm::Triple &T, bool FromAs=false)
void print(raw_ostream &OS) const
Print information about the detected GCC installation.
Definition: Gnu.cpp:1731
const char * getFilename() const
Definition: InputInfo.h:84
void RenderExtraToolArgs(const JobAction &JA, llvm::opt::ArgStringList &CmdArgs) const override
RenderExtraToolArgs - Render any arguments necessary to force the particular tool mode...
Definition: Gnu.cpp:193
GCCInstallationDetector GCCInstallation
Definition: Gnu.h:280
path_list & getProgramPaths()
Definition: ToolChain.h:226
static Multilib makeMultilib(StringRef commonSuffix)
Definition: Gnu.cpp:848
void linkSanitizerRuntimeDeps(const ToolChain &TC, llvm::opt::ArgStringList &CmdArgs)
const std::string & includeSuffix() const
Get the include directory suffix.
Definition: Multilib.h:67
void AddGoldPlugin(const ToolChain &ToolChain, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const InputInfo &Output, const InputInfo &Input, bool IsThinLTO)
const std::string & gccSuffix() const
Get the detected GCC installation path suffix for the multi-arch target variant.
Definition: Multilib.h:45
bool addSanitizerRuntimes(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
bool isNaN2008(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
directory_iterator & increment(std::error_code &EC)
Equivalent to operator++, with an error code.
const std::string & osSuffix() const
Get the detected os path suffix for the multi-arch target variant.
Definition: Multilib.h:56
InputInfo - Wrapper for information about an input source.
Definition: InputInfo.h:23
static bool isMipsEL(llvm::Triple::ArchType Arch)
Definition: Gnu.cpp:830
MultilibSet & setIncludeDirsCallback(IncludeDirsFunc F)
Definition: Multilib.h:170
vfs::FileSystem & getVFS() const
Definition: ToolChain.cpp:102
std::string GetFilePath(const char *Name) const
Definition: ToolChain.cpp:423
types::ID getType() const
Definition: Action.h:141
virtual bool AddFastMathRuntimeIfAvailable(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddFastMathRuntimeIfAvailable - If a runtime library exists that sets global flags for unsafe floatin...
Definition: ToolChain.cpp:786
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:59
bool hasMipsAbiArg(const llvm::opt::ArgList &Args, const char *Value)
void RenderExtraToolArgs(const JobAction &JA, llvm::opt::ArgStringList &CmdArgs) const override
RenderExtraToolArgs - Render any arguments necessary to force the particular tool mode...
Definition: Gnu.cpp:198
bool addOpenMPRuntime(llvm::opt::ArgStringList &CmdArgs, const ToolChain &TC, const llvm::opt::ArgList &Args, bool IsOffloadingHost=false, bool GompNeedsRT=false)
Returns true, if an OpenMP runtime has been added.
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Gnu.cpp:297
void AddOpenMPLinkerScript(const ToolChain &TC, Compilation &C, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const JobAction &JA)
const GCCVersion & getVersion() const
Get the detected GCC version string.
Definition: Gnu.h:239
void linkXRayRuntimeDeps(const ToolChain &TC, llvm::opt::ArgStringList &CmdArgs)
static bool isMips16(const ArgList &Args)
Definition: Gnu.cpp:834
StringRef getRISCVABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
CudaInstallationDetector CudaInstallation
Definition: Gnu.h:281
static bool isSoftFloatABI(const ArgList &Args)
Definition: Gnu.cpp:805
static void addMultilibFlag(bool Enabled, const char *const Flag, std::vector< std::string > &Flags)
Flag must be a flag accepted by the driver with its leading &#39;-&#39; removed,
Definition: Gnu.cpp:818
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
Definition: Gnu.cpp:2425
const char * getTypeName(ID Id)
getTypeName - Return the name of the type for Id.
Definition: Types.cpp:39
const AnnotatedLine * Line
static bool findMipsMuslMultilibs(const Multilib::flags_list &Flags, FilterNonExistent &NonExistent, DetectedMultilibs &Result)
Definition: Gnu.cpp:982
static void normalizeCPUNamesForAssembler(const ArgList &Args, ArgStringList &CmdArgs)
Definition: Gnu.cpp:49
bool isPICDefault() const override
Test whether this toolchain defaults to PIC.
Definition: Gnu.cpp:2366
const char * SplitDebugName(const llvm::opt::ArgList &Args, const InputInfo &Input)
std::vector< std::string > flags_list
Definition: Multilib.h:31
void push_back(const Multilib &M)
Add a completed Multilib to the set.
Definition: Multilib.cpp:232
unsigned size() const
Definition: Multilib.h:165
void addCommand(std::unique_ptr< Command > C)
Definition: Compilation.h:206
This corresponds to a single GCC Multilib, or a segment of one controlled by a command line flag...
Definition: Multilib.h:29
static bool findMipsMtiMultilibs(const Multilib::flags_list &Flags, FilterNonExistent &NonExistent, DetectedMultilibs &Result)
Definition: Gnu.cpp:1014
Tool * buildAssembler() const override
Definition: Gnu.cpp:2350
std::tuple< llvm::Reloc::Model, unsigned, bool > ParsePICArgs(const ToolChain &ToolChain, const llvm::opt::ArgList &Args)
static bool forwardToGCC(const Option &O)
Definition: Gnu.cpp:39
bool IsUnwindTablesDefault(const llvm::opt::ArgList &Args) const override
IsUnwindTablesDefault - Does this tool chain use -funwind-tables by default.
Definition: Gnu.cpp:2362
static const char * getLDMOption(const llvm::Triple &T, const ArgList &Args)
Definition: Gnu.cpp:231
void AddAssemblerKPIC(const ToolChain &ToolChain, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
llvm::Triple::ArchType getArch() const
Definition: ToolChain.h:201
void printVerboseInfo(raw_ostream &OS) const override
Dispatch to the specific toolchain for verbose printing.
Definition: Gnu.cpp:2356
static bool findMipsImgMultilibs(const Multilib::flags_list &Flags, FilterNonExistent &NonExistent, DetectedMultilibs &Result)
Definition: Gnu.cpp:1186
void AddFilePathLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddFilePathLibArgs - Add each thing in getFilePaths() as a "-L" option.
Definition: ToolChain.cpp:770
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Gnu.cpp:62
mips::FloatABI getMipsFloatABI(const Driver &D, const llvm::opt::ArgList &Args)
vfs::FileSystem & getVFS() const
Definition: Driver.h:301
const Driver & getDriver() const
Definition: ToolChain.h:185
virtual void addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Definition: Gnu.cpp:2443
std::string InstalledDir
The path to the installed clang directory, if any.
Definition: Driver.h:130
bool isUCLibc(const llvm::opt::ArgList &Args)
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition: Driver.h:174
static void addSystemInclude(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Utility function to add a system include directory to CC1 arguments.
Definition: ToolChain.cpp:694
void appendEBLinkFlags(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple)
void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T, const JobAction &JA, const llvm::opt::ArgList &Args, const InputInfo &Output, const char *OutFile)
static bool isArmOrThumbArch(llvm::Triple::ArchType Arch)
Definition: Gnu.cpp:826
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs...
Definition: Gnu.cpp:538
bool isOlderThan(int RHSMajor, int RHSMinor, int RHSPatch, StringRef RHSPatchSuffix=StringRef()) const
Generic_GCC - A tool chain using the &#39;gcc&#39; command to perform all subcommands; this relies on gcc tra...
Definition: Gnu.cpp:1537
static bool findBiarchMultilibs(const Driver &D, const llvm::Triple &TargetTriple, StringRef Path, const ArgList &Args, bool NeedsBiarchSuffix, DetectedMultilibs &Result)
Definition: Gnu.cpp:1428
bool isPICDefaultForced() const override
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
Definition: Gnu.cpp:2383
bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const
Returns if the C++ standard library should be linked in.
Definition: ToolChain.cpp:747
Dataflow Directional Tag Classes.
Generic_GCC(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Definition: Gnu.cpp:2324
static bool isRISCV(llvm::Triple::ArchType Arch)
Definition: Gnu.cpp:844
const std::string & getCCCGenericGCCName() const
Name to use when invoking gcc/g++.
Definition: Driver.h:293
void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const JobAction &JA)
std::string SysRoot
sysroot, if present
Definition: Driver.h:149
Tool - Information on a specific compilation tool.
Definition: Tool.h:34
Defines the virtual file system interface vfs::FileSystem.
void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, Action::OffloadKind DeviceOffloadKind) const override
Add options that need to be passed to cc1 for this target.
Definition: Gnu.cpp:2535
static bool findMipsCsMultilibs(const Multilib::flags_list &Flags, FilterNonExistent &NonExistent, DetectedMultilibs &Result)
Definition: Gnu.cpp:852
bool IsIntegratedAssemblerDefault() const override
IsIntegratedAssemblerDefault - Does this tool chain enable -integrated-as by default.
Definition: Gnu.cpp:2387
void claimNoWarnArgs(const llvm::opt::ArgList &Args)
bool exists(const Twine &Path)
Check whether a file exists. Provided for convenience.
std::string MajorStr
The text of the parsed major, and major+minor versions.
Definition: Gnu.h:165
llvm::opt::DerivedArgList * TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const override
TranslateArgs - Create a new derived argument list for any argument translations this ToolChain may w...
Definition: Gnu.cpp:2491
Compilation - A set of tasks to perform for a single driver invocation.
Definition: Compilation.h:46
const llvm::Triple & getTriple() const
Definition: ToolChain.h:187
virtual void addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Definition: Gnu.cpp:2451
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const Twine &Name, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
This is a convenience method that opens a file, gets its content and then closes the file...
virtual Tool * getTool(Action::ActionClass AC) const
Definition: ToolChain.cpp:287
bool findMIPSMultilibs(const Driver &D, const llvm::Triple &TargetTriple, StringRef Path, const llvm::opt::ArgList &Args, DetectedMultilibs &Result)
StringRef getGnuCompatibleMipsABIName(StringRef ABI)
Definition: Mips.cpp:136
bool isNothing() const
Definition: InputInfo.h:75
An input iterator over the entries in a virtual path, similar to llvm::sys::fs::directory_iterator.
MultilibSet & FilterOut(FilterCallback F)
Filter out some subset of the Multilibs using a user defined callback.
Definition: Multilib.cpp:212
bool isFilename() const
Definition: InputInfo.h:76
const llvm::opt::OptTable & getOpts() const
Definition: Driver.h:297
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:675
static constexpr CPUSuffix Suffixes[]
Definition: Hexagon.cpp:152
bool addLibStdCXXIncludePaths(Twine Base, Twine Suffix, StringRef GCCTriple, StringRef GCCMultiarchTriple, StringRef TargetMultiarchTriple, Twine IncludeSuffix, const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Helper to add the variant paths of a libstdc++ installation.
Definition: Gnu.cpp:2458
void init(const llvm::Triple &TargetTriple, const llvm::opt::ArgList &Args, ArrayRef< std::string > ExtraTripleAliases=None)
Initialize a GCCInstallationDetector from the driver.
Definition: Gnu.cpp:1637
void getMipsCPUAndABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple, StringRef &CPUName, StringRef &ABIName)
MultilibSet Multilibs
The set of multilibs that the detected installation supports.
Definition: Gnu.h:23
std::vector< std::string > ExtraOpts
Definition: Linux.h:49
static bool isMicroMips(const ArgList &Args)
Definition: Gnu.cpp:839
bool isLLVMIR(ID Id)
Is this LLVM IR.
Definition: Types.cpp:154
int Major
The parsed major, minor, and patch numbers.
Definition: Gnu.h:162
static void findAndroidArmMultilibs(const Driver &D, const llvm::Triple &TargetTriple, StringRef Path, const ArgList &Args, DetectedMultilibs &Result)
Definition: Gnu.cpp:1351
static void findRISCVMultilibs(const Driver &D, const llvm::Triple &TargetTriple, StringRef Path, const ArgList &Args, DetectedMultilibs &Result)
Definition: Gnu.cpp:1393
virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
Definition: ToolChain.cpp:753
Multilib SelectedMultilib
The primary multilib appropriate for the given flags.
Definition: Gnu.h:26
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:88
bool isValid() const
Check whether we detected a valid GCC install.
Definition: Gnu.h:217