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