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