Coverage Report

Created: 2020-09-19 12:23

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