Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Driver/Driver.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
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 "clang/Driver/Driver.h"
10
#include "ToolChains/AIX.h"
11
#include "ToolChains/AMDGPU.h"
12
#include "ToolChains/AMDGPUOpenMP.h"
13
#include "ToolChains/AVR.h"
14
#include "ToolChains/Arch/RISCV.h"
15
#include "ToolChains/BareMetal.h"
16
#include "ToolChains/CSKYToolChain.h"
17
#include "ToolChains/Clang.h"
18
#include "ToolChains/CrossWindows.h"
19
#include "ToolChains/Cuda.h"
20
#include "ToolChains/Darwin.h"
21
#include "ToolChains/DragonFly.h"
22
#include "ToolChains/FreeBSD.h"
23
#include "ToolChains/Fuchsia.h"
24
#include "ToolChains/Gnu.h"
25
#include "ToolChains/HIPAMD.h"
26
#include "ToolChains/HIPSPV.h"
27
#include "ToolChains/HLSL.h"
28
#include "ToolChains/Haiku.h"
29
#include "ToolChains/Hexagon.h"
30
#include "ToolChains/Hurd.h"
31
#include "ToolChains/Lanai.h"
32
#include "ToolChains/Linux.h"
33
#include "ToolChains/MSP430.h"
34
#include "ToolChains/MSVC.h"
35
#include "ToolChains/MinGW.h"
36
#include "ToolChains/MipsLinux.h"
37
#include "ToolChains/NaCl.h"
38
#include "ToolChains/NetBSD.h"
39
#include "ToolChains/OHOS.h"
40
#include "ToolChains/OpenBSD.h"
41
#include "ToolChains/PPCFreeBSD.h"
42
#include "ToolChains/PPCLinux.h"
43
#include "ToolChains/PS4CPU.h"
44
#include "ToolChains/RISCVToolchain.h"
45
#include "ToolChains/SPIRV.h"
46
#include "ToolChains/Solaris.h"
47
#include "ToolChains/TCE.h"
48
#include "ToolChains/VEToolchain.h"
49
#include "ToolChains/WebAssembly.h"
50
#include "ToolChains/XCore.h"
51
#include "ToolChains/ZOS.h"
52
#include "clang/Basic/TargetID.h"
53
#include "clang/Basic/Version.h"
54
#include "clang/Config/config.h"
55
#include "clang/Driver/Action.h"
56
#include "clang/Driver/Compilation.h"
57
#include "clang/Driver/DriverDiagnostic.h"
58
#include "clang/Driver/InputInfo.h"
59
#include "clang/Driver/Job.h"
60
#include "clang/Driver/Options.h"
61
#include "clang/Driver/Phases.h"
62
#include "clang/Driver/SanitizerArgs.h"
63
#include "clang/Driver/Tool.h"
64
#include "clang/Driver/ToolChain.h"
65
#include "clang/Driver/Types.h"
66
#include "llvm/ADT/ArrayRef.h"
67
#include "llvm/ADT/STLExtras.h"
68
#include "llvm/ADT/StringExtras.h"
69
#include "llvm/ADT/StringRef.h"
70
#include "llvm/ADT/StringSet.h"
71
#include "llvm/ADT/StringSwitch.h"
72
#include "llvm/Config/llvm-config.h"
73
#include "llvm/MC/TargetRegistry.h"
74
#include "llvm/Option/Arg.h"
75
#include "llvm/Option/ArgList.h"
76
#include "llvm/Option/OptSpecifier.h"
77
#include "llvm/Option/OptTable.h"
78
#include "llvm/Option/Option.h"
79
#include "llvm/Support/CommandLine.h"
80
#include "llvm/Support/ErrorHandling.h"
81
#include "llvm/Support/ExitCodes.h"
82
#include "llvm/Support/FileSystem.h"
83
#include "llvm/Support/FormatVariadic.h"
84
#include "llvm/Support/MD5.h"
85
#include "llvm/Support/Path.h"
86
#include "llvm/Support/PrettyStackTrace.h"
87
#include "llvm/Support/Process.h"
88
#include "llvm/Support/Program.h"
89
#include "llvm/Support/RISCVISAInfo.h"
90
#include "llvm/Support/StringSaver.h"
91
#include "llvm/Support/VirtualFileSystem.h"
92
#include "llvm/Support/raw_ostream.h"
93
#include "llvm/TargetParser/Host.h"
94
#include <cstdlib> // ::getenv
95
#include <map>
96
#include <memory>
97
#include <optional>
98
#include <set>
99
#include <utility>
100
#if LLVM_ON_UNIX
101
#include <unistd.h> // getpid
102
#endif
103
104
using namespace clang::driver;
105
using namespace clang;
106
using namespace llvm::opt;
107
108
static std::optional<llvm::Triple> getOffloadTargetTriple(const Driver &D,
109
0
                                                          const ArgList &Args) {
110
0
  auto OffloadTargets = Args.getAllArgValues(options::OPT_offload_EQ);
111
  // Offload compilation flow does not support multiple targets for now. We
112
  // need the HIPActionBuilder (and possibly the CudaActionBuilder{,Base}too)
113
  // to support multiple tool chains first.
114
0
  switch (OffloadTargets.size()) {
115
0
  default:
116
0
    D.Diag(diag::err_drv_only_one_offload_target_supported);
117
0
    return std::nullopt;
118
0
  case 0:
119
0
    D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << "";
120
0
    return std::nullopt;
121
0
  case 1:
122
0
    break;
123
0
  }
124
0
  return llvm::Triple(OffloadTargets[0]);
125
0
}
126
127
static std::optional<llvm::Triple>
128
getNVIDIAOffloadTargetTriple(const Driver &D, const ArgList &Args,
129
0
                             const llvm::Triple &HostTriple) {
130
0
  if (!Args.hasArg(options::OPT_offload_EQ)) {
131
0
    return llvm::Triple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
132
0
                                                 : "nvptx-nvidia-cuda");
133
0
  }
134
0
  auto TT = getOffloadTargetTriple(D, Args);
135
0
  if (TT && (TT->getArch() == llvm::Triple::spirv32 ||
136
0
             TT->getArch() == llvm::Triple::spirv64)) {
137
0
    if (Args.hasArg(options::OPT_emit_llvm))
138
0
      return TT;
139
0
    D.Diag(diag::err_drv_cuda_offload_only_emit_bc);
140
0
    return std::nullopt;
141
0
  }
142
0
  D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str();
143
0
  return std::nullopt;
144
0
}
145
static std::optional<llvm::Triple>
146
0
getHIPOffloadTargetTriple(const Driver &D, const ArgList &Args) {
147
0
  if (!Args.hasArg(options::OPT_offload_EQ)) {
148
0
    return llvm::Triple("amdgcn-amd-amdhsa"); // Default HIP triple.
149
0
  }
150
0
  auto TT = getOffloadTargetTriple(D, Args);
151
0
  if (!TT)
152
0
    return std::nullopt;
153
0
  if (TT->getArch() == llvm::Triple::amdgcn &&
154
0
      TT->getVendor() == llvm::Triple::AMD &&
155
0
      TT->getOS() == llvm::Triple::AMDHSA)
156
0
    return TT;
157
0
  if (TT->getArch() == llvm::Triple::spirv64)
158
0
    return TT;
159
0
  D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str();
160
0
  return std::nullopt;
161
0
}
162
163
// static
164
std::string Driver::GetResourcesPath(StringRef BinaryPath,
165
0
                                     StringRef CustomResourceDir) {
166
  // Since the resource directory is embedded in the module hash, it's important
167
  // that all places that need it call this function, so that they get the
168
  // exact same string ("a/../b/" and "b/" get different hashes, for example).
169
170
  // Dir is bin/ or lib/, depending on where BinaryPath is.
171
0
  std::string Dir = std::string(llvm::sys::path::parent_path(BinaryPath));
172
173
0
  SmallString<128> P(Dir);
174
0
  if (CustomResourceDir != "") {
175
0
    llvm::sys::path::append(P, CustomResourceDir);
176
0
  } else {
177
    // On Windows, libclang.dll is in bin/.
178
    // On non-Windows, libclang.so/.dylib is in lib/.
179
    // With a static-library build of libclang, LibClangPath will contain the
180
    // path of the embedding binary, which for LLVM binaries will be in bin/.
181
    // ../lib gets us to lib/ in both cases.
182
0
    P = llvm::sys::path::parent_path(Dir);
183
    // This search path is also created in the COFF driver of lld, so any
184
    // changes here also needs to happen in lld/COFF/Driver.cpp
185
0
    llvm::sys::path::append(P, CLANG_INSTALL_LIBDIR_BASENAME, "clang",
186
0
                            CLANG_VERSION_MAJOR_STRING);
187
0
  }
188
189
0
  return std::string(P.str());
190
0
}
191
192
Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
193
               DiagnosticsEngine &Diags, std::string Title,
194
               IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
195
    : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
196
      SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
197
      Offload(OffloadHostDevice), CXX20HeaderType(HeaderMode_None),
198
      ModulesModeCXX20(false), LTOMode(LTOK_None),
199
      ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
200
      DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false),
201
      CCLogDiagnostics(false), CCGenDiagnostics(false),
202
      CCPrintProcessStats(false), CCPrintInternalStats(false),
203
      TargetTriple(TargetTriple), Saver(Alloc), PrependArg(nullptr),
204
      CheckInputsExist(true), ProbePrecompiled(true),
205
0
      SuppressMissingInputWarning(false) {
206
  // Provide a sane fallback if no VFS is specified.
207
0
  if (!this->VFS)
208
0
    this->VFS = llvm::vfs::getRealFileSystem();
209
210
0
  Name = std::string(llvm::sys::path::filename(ClangExecutable));
211
0
  Dir = std::string(llvm::sys::path::parent_path(ClangExecutable));
212
0
  InstalledDir = Dir; // Provide a sensible default installed dir.
213
214
0
  if ((!SysRoot.empty()) && llvm::sys::path::is_relative(SysRoot)) {
215
    // Prepend InstalledDir if SysRoot is relative
216
0
    SmallString<128> P(InstalledDir);
217
0
    llvm::sys::path::append(P, SysRoot);
218
0
    SysRoot = std::string(P);
219
0
  }
220
221
#if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
222
  SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
223
#endif
224
#if defined(CLANG_CONFIG_FILE_USER_DIR)
225
  {
226
    SmallString<128> P;
227
    llvm::sys::fs::expand_tilde(CLANG_CONFIG_FILE_USER_DIR, P);
228
    UserConfigDir = static_cast<std::string>(P);
229
  }
230
#endif
231
232
  // Compute the path to the resource directory.
233
0
  ResourceDir = GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
234
0
}
235
236
0
void Driver::setDriverMode(StringRef Value) {
237
0
  static StringRef OptName =
238
0
      getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
239
0
  if (auto M = llvm::StringSwitch<std::optional<DriverMode>>(Value)
240
0
                   .Case("gcc", GCCMode)
241
0
                   .Case("g++", GXXMode)
242
0
                   .Case("cpp", CPPMode)
243
0
                   .Case("cl", CLMode)
244
0
                   .Case("flang", FlangMode)
245
0
                   .Case("dxc", DXCMode)
246
0
                   .Default(std::nullopt))
247
0
    Mode = *M;
248
0
  else
249
0
    Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
250
0
}
251
252
InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
253
0
                                     bool UseDriverMode, bool &ContainsError) {
254
0
  llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
255
0
  ContainsError = false;
256
257
0
  llvm::opt::Visibility VisibilityMask = getOptionVisibilityMask(UseDriverMode);
258
0
  unsigned MissingArgIndex, MissingArgCount;
259
0
  InputArgList Args = getOpts().ParseArgs(ArgStrings, MissingArgIndex,
260
0
                                          MissingArgCount, VisibilityMask);
261
262
  // Check for missing argument error.
263
0
  if (MissingArgCount) {
264
0
    Diag(diag::err_drv_missing_argument)
265
0
        << Args.getArgString(MissingArgIndex) << MissingArgCount;
266
0
    ContainsError |=
267
0
        Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
268
0
                                 SourceLocation()) > DiagnosticsEngine::Warning;
269
0
  }
270
271
  // Check for unsupported options.
272
0
  for (const Arg *A : Args) {
273
0
    if (A->getOption().hasFlag(options::Unsupported)) {
274
0
      Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
275
0
      ContainsError |= Diags.getDiagnosticLevel(diag::err_drv_unsupported_opt,
276
0
                                                SourceLocation()) >
277
0
                       DiagnosticsEngine::Warning;
278
0
      continue;
279
0
    }
280
281
    // Warn about -mcpu= without an argument.
282
0
    if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
283
0
      Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
284
0
      ContainsError |= Diags.getDiagnosticLevel(
285
0
                           diag::warn_drv_empty_joined_argument,
286
0
                           SourceLocation()) > DiagnosticsEngine::Warning;
287
0
    }
288
0
  }
289
290
0
  for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
291
0
    unsigned DiagID;
292
0
    auto ArgString = A->getAsString(Args);
293
0
    std::string Nearest;
294
0
    if (getOpts().findNearest(ArgString, Nearest, VisibilityMask) > 1) {
295
0
      if (!IsCLMode() &&
296
0
          getOpts().findExact(ArgString, Nearest,
297
0
                              llvm::opt::Visibility(options::CC1Option))) {
298
0
        DiagID = diag::err_drv_unknown_argument_with_suggestion;
299
0
        Diags.Report(DiagID) << ArgString << "-Xclang " + Nearest;
300
0
      } else {
301
0
        DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
302
0
                            : diag::err_drv_unknown_argument;
303
0
        Diags.Report(DiagID) << ArgString;
304
0
      }
305
0
    } else {
306
0
      DiagID = IsCLMode()
307
0
                   ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
308
0
                   : diag::err_drv_unknown_argument_with_suggestion;
309
0
      Diags.Report(DiagID) << ArgString << Nearest;
310
0
    }
311
0
    ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
312
0
                     DiagnosticsEngine::Warning;
313
0
  }
314
315
0
  for (const Arg *A : Args.filtered(options::OPT_o)) {
316
0
    if (ArgStrings[A->getIndex()] == A->getSpelling())
317
0
      continue;
318
319
    // Warn on joined arguments that are similar to a long argument.
320
0
    std::string ArgString = ArgStrings[A->getIndex()];
321
0
    std::string Nearest;
322
0
    if (getOpts().findExact("-" + ArgString, Nearest, VisibilityMask))
323
0
      Diags.Report(diag::warn_drv_potentially_misspelled_joined_argument)
324
0
          << A->getAsString(Args) << Nearest;
325
0
  }
326
327
0
  return Args;
328
0
}
329
330
// Determine which compilation mode we are in. We look for options which
331
// affect the phase, starting with the earliest phases, and record which
332
// option we used to determine the final phase.
333
phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
334
0
                                 Arg **FinalPhaseArg) const {
335
0
  Arg *PhaseArg = nullptr;
336
0
  phases::ID FinalPhase;
337
338
  // -{E,EP,P,M,MM} only run the preprocessor.
339
0
  if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
340
0
      (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
341
0
      (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
342
0
      (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P)) ||
343
0
      CCGenDiagnostics) {
344
0
    FinalPhase = phases::Preprocess;
345
346
    // --precompile only runs up to precompilation.
347
    // Options that cause the output of C++20 compiled module interfaces or
348
    // header units have the same effect.
349
0
  } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile)) ||
350
0
             (PhaseArg = DAL.getLastArg(options::OPT_extract_api)) ||
351
0
             (PhaseArg = DAL.getLastArg(options::OPT_fmodule_header,
352
0
                                        options::OPT_fmodule_header_EQ))) {
353
0
    FinalPhase = phases::Precompile;
354
    // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
355
0
  } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
356
0
             (PhaseArg = DAL.getLastArg(options::OPT_print_supported_cpus)) ||
357
0
             (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
358
0
             (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
359
0
             (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
360
0
             (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
361
0
             (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
362
0
             (PhaseArg = DAL.getLastArg(options::OPT__analyze)) ||
363
0
             (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
364
0
    FinalPhase = phases::Compile;
365
366
  // -S only runs up to the backend.
367
0
  } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
368
0
    FinalPhase = phases::Backend;
369
370
  // -c compilation only runs up to the assembler.
371
0
  } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
372
0
    FinalPhase = phases::Assemble;
373
374
0
  } else if ((PhaseArg = DAL.getLastArg(options::OPT_emit_interface_stubs))) {
375
0
    FinalPhase = phases::IfsMerge;
376
377
  // Otherwise do everything.
378
0
  } else
379
0
    FinalPhase = phases::Link;
380
381
0
  if (FinalPhaseArg)
382
0
    *FinalPhaseArg = PhaseArg;
383
384
0
  return FinalPhase;
385
0
}
386
387
static Arg *MakeInputArg(DerivedArgList &Args, const OptTable &Opts,
388
0
                         StringRef Value, bool Claim = true) {
389
0
  Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
390
0
                   Args.getBaseArgs().MakeIndex(Value), Value.data());
391
0
  Args.AddSynthesizedArg(A);
392
0
  if (Claim)
393
0
    A->claim();
394
0
  return A;
395
0
}
396
397
0
DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
398
0
  const llvm::opt::OptTable &Opts = getOpts();
399
0
  DerivedArgList *DAL = new DerivedArgList(Args);
400
401
0
  bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
402
0
  bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
403
0
  bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
404
0
  bool IgnoreUnused = false;
405
0
  for (Arg *A : Args) {
406
0
    if (IgnoreUnused)
407
0
      A->claim();
408
409
0
    if (A->getOption().matches(options::OPT_start_no_unused_arguments)) {
410
0
      IgnoreUnused = true;
411
0
      continue;
412
0
    }
413
0
    if (A->getOption().matches(options::OPT_end_no_unused_arguments)) {
414
0
      IgnoreUnused = false;
415
0
      continue;
416
0
    }
417
418
    // Unfortunately, we have to parse some forwarding options (-Xassembler,
419
    // -Xlinker, -Xpreprocessor) because we either integrate their functionality
420
    // (assembler and preprocessor), or bypass a previous driver ('collect2').
421
422
    // Rewrite linker options, to replace --no-demangle with a custom internal
423
    // option.
424
0
    if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
425
0
         A->getOption().matches(options::OPT_Xlinker)) &&
426
0
        A->containsValue("--no-demangle")) {
427
      // Add the rewritten no-demangle argument.
428
0
      DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_Xlinker__no_demangle));
429
430
      // Add the remaining values as Xlinker arguments.
431
0
      for (StringRef Val : A->getValues())
432
0
        if (Val != "--no-demangle")
433
0
          DAL->AddSeparateArg(A, Opts.getOption(options::OPT_Xlinker), Val);
434
435
0
      continue;
436
0
    }
437
438
    // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
439
    // some build systems. We don't try to be complete here because we don't
440
    // care to encourage this usage model.
441
0
    if (A->getOption().matches(options::OPT_Wp_COMMA) &&
442
0
        (A->getValue(0) == StringRef("-MD") ||
443
0
         A->getValue(0) == StringRef("-MMD"))) {
444
      // Rewrite to -MD/-MMD along with -MF.
445
0
      if (A->getValue(0) == StringRef("-MD"))
446
0
        DAL->AddFlagArg(A, Opts.getOption(options::OPT_MD));
447
0
      else
448
0
        DAL->AddFlagArg(A, Opts.getOption(options::OPT_MMD));
449
0
      if (A->getNumValues() == 2)
450
0
        DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue(1));
451
0
      continue;
452
0
    }
453
454
    // Rewrite reserved library names.
455
0
    if (A->getOption().matches(options::OPT_l)) {
456
0
      StringRef Value = A->getValue();
457
458
      // Rewrite unless -nostdlib is present.
459
0
      if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx &&
460
0
          Value == "stdc++") {
461
0
        DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_stdcxx));
462
0
        continue;
463
0
      }
464
465
      // Rewrite unconditionally.
466
0
      if (Value == "cc_kext") {
467
0
        DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_cckext));
468
0
        continue;
469
0
      }
470
0
    }
471
472
    // Pick up inputs via the -- option.
473
0
    if (A->getOption().matches(options::OPT__DASH_DASH)) {
474
0
      A->claim();
475
0
      for (StringRef Val : A->getValues())
476
0
        DAL->append(MakeInputArg(*DAL, Opts, Val, false));
477
0
      continue;
478
0
    }
479
480
0
    DAL->append(A);
481
0
  }
482
483
  // DXC mode quits before assembly if an output object file isn't specified.
484
0
  if (IsDXCMode() && !Args.hasArg(options::OPT_dxc_Fo))
485
0
    DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_S));
486
487
  // Enforce -static if -miamcu is present.
488
0
  if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
489
0
    DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_static));
490
491
// Add a default value of -mlinker-version=, if one was given and the user
492
// didn't specify one.
493
#if defined(HOST_LINK_VERSION)
494
  if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
495
      strlen(HOST_LINK_VERSION) > 0) {
496
    DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ),
497
                      HOST_LINK_VERSION);
498
    DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
499
  }
500
#endif
501
502
0
  return DAL;
503
0
}
504
505
/// Compute target triple from args.
506
///
507
/// This routine provides the logic to compute a target triple from various
508
/// args passed to the driver and the default triple string.
509
static llvm::Triple computeTargetTriple(const Driver &D,
510
                                        StringRef TargetTriple,
511
                                        const ArgList &Args,
512
0
                                        StringRef DarwinArchName = "") {
513
  // FIXME: Already done in Compilation *Driver::BuildCompilation
514
0
  if (const Arg *A = Args.getLastArg(options::OPT_target))
515
0
    TargetTriple = A->getValue();
516
517
0
  llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
518
519
  // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
520
  // -gnu* only, and we can not change this, so we have to detect that case as
521
  // being the Hurd OS.
522
0
  if (TargetTriple.contains("-unknown-gnu") || TargetTriple.contains("-pc-gnu"))
523
0
    Target.setOSName("hurd");
524
525
  // Handle Apple-specific options available here.
526
0
  if (Target.isOSBinFormatMachO()) {
527
    // If an explicit Darwin arch name is given, that trumps all.
528
0
    if (!DarwinArchName.empty()) {
529
0
      tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName,
530
0
                                                   Args);
531
0
      return Target;
532
0
    }
533
534
    // Handle the Darwin '-arch' flag.
535
0
    if (Arg *A = Args.getLastArg(options::OPT_arch)) {
536
0
      StringRef ArchName = A->getValue();
537
0
      tools::darwin::setTripleTypeForMachOArchName(Target, ArchName, Args);
538
0
    }
539
0
  }
540
541
  // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
542
  // '-mbig-endian'/'-EB'.
543
0
  if (Arg *A = Args.getLastArgNoClaim(options::OPT_mlittle_endian,
544
0
                                      options::OPT_mbig_endian)) {
545
0
    llvm::Triple T = A->getOption().matches(options::OPT_mlittle_endian)
546
0
                         ? Target.getLittleEndianArchVariant()
547
0
                         : Target.getBigEndianArchVariant();
548
0
    if (T.getArch() != llvm::Triple::UnknownArch) {
549
0
      Target = std::move(T);
550
0
      Args.claimAllArgs(options::OPT_mlittle_endian, options::OPT_mbig_endian);
551
0
    }
552
0
  }
553
554
  // Skip further flag support on OSes which don't support '-m32' or '-m64'.
555
0
  if (Target.getArch() == llvm::Triple::tce)
556
0
    return Target;
557
558
  // On AIX, the env OBJECT_MODE may affect the resulting arch variant.
559
0
  if (Target.isOSAIX()) {
560
0
    if (std::optional<std::string> ObjectModeValue =
561
0
            llvm::sys::Process::GetEnv("OBJECT_MODE")) {
562
0
      StringRef ObjectMode = *ObjectModeValue;
563
0
      llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
564
565
0
      if (ObjectMode.equals("64")) {
566
0
        AT = Target.get64BitArchVariant().getArch();
567
0
      } else if (ObjectMode.equals("32")) {
568
0
        AT = Target.get32BitArchVariant().getArch();
569
0
      } else {
570
0
        D.Diag(diag::err_drv_invalid_object_mode) << ObjectMode;
571
0
      }
572
573
0
      if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
574
0
        Target.setArch(AT);
575
0
    }
576
0
  }
577
578
  // The `-maix[32|64]` flags are only valid for AIX targets.
579
0
  if (Arg *A = Args.getLastArgNoClaim(options::OPT_maix32, options::OPT_maix64);
580
0
      A && !Target.isOSAIX())
581
0
    D.Diag(diag::err_drv_unsupported_opt_for_target)
582
0
        << A->getAsString(Args) << Target.str();
583
584
  // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
585
0
  Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
586
0
                           options::OPT_m32, options::OPT_m16,
587
0
                           options::OPT_maix32, options::OPT_maix64);
588
0
  if (A) {
589
0
    llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
590
591
0
    if (A->getOption().matches(options::OPT_m64) ||
592
0
        A->getOption().matches(options::OPT_maix64)) {
593
0
      AT = Target.get64BitArchVariant().getArch();
594
0
      if (Target.getEnvironment() == llvm::Triple::GNUX32)
595
0
        Target.setEnvironment(llvm::Triple::GNU);
596
0
      else if (Target.getEnvironment() == llvm::Triple::MuslX32)
597
0
        Target.setEnvironment(llvm::Triple::Musl);
598
0
    } else if (A->getOption().matches(options::OPT_mx32) &&
599
0
               Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
600
0
      AT = llvm::Triple::x86_64;
601
0
      if (Target.getEnvironment() == llvm::Triple::Musl)
602
0
        Target.setEnvironment(llvm::Triple::MuslX32);
603
0
      else
604
0
        Target.setEnvironment(llvm::Triple::GNUX32);
605
0
    } else if (A->getOption().matches(options::OPT_m32) ||
606
0
               A->getOption().matches(options::OPT_maix32)) {
607
0
      AT = Target.get32BitArchVariant().getArch();
608
0
      if (Target.getEnvironment() == llvm::Triple::GNUX32)
609
0
        Target.setEnvironment(llvm::Triple::GNU);
610
0
      else if (Target.getEnvironment() == llvm::Triple::MuslX32)
611
0
        Target.setEnvironment(llvm::Triple::Musl);
612
0
    } else if (A->getOption().matches(options::OPT_m16) &&
613
0
               Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
614
0
      AT = llvm::Triple::x86;
615
0
      Target.setEnvironment(llvm::Triple::CODE16);
616
0
    }
617
618
0
    if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) {
619
0
      Target.setArch(AT);
620
0
      if (Target.isWindowsGNUEnvironment())
621
0
        toolchains::MinGW::fixTripleArch(D, Target, Args);
622
0
    }
623
0
  }
624
625
  // Handle -miamcu flag.
626
0
  if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
627
0
    if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
628
0
      D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
629
0
                                                       << Target.str();
630
631
0
    if (A && !A->getOption().matches(options::OPT_m32))
632
0
      D.Diag(diag::err_drv_argument_not_allowed_with)
633
0
          << "-miamcu" << A->getBaseArg().getAsString(Args);
634
635
0
    Target.setArch(llvm::Triple::x86);
636
0
    Target.setArchName("i586");
637
0
    Target.setEnvironment(llvm::Triple::UnknownEnvironment);
638
0
    Target.setEnvironmentName("");
639
0
    Target.setOS(llvm::Triple::ELFIAMCU);
640
0
    Target.setVendor(llvm::Triple::UnknownVendor);
641
0
    Target.setVendorName("intel");
642
0
  }
643
644
  // If target is MIPS adjust the target triple
645
  // accordingly to provided ABI name.
646
0
  if (Target.isMIPS()) {
647
0
    if ((A = Args.getLastArg(options::OPT_mabi_EQ))) {
648
0
      StringRef ABIName = A->getValue();
649
0
      if (ABIName == "32") {
650
0
        Target = Target.get32BitArchVariant();
651
0
        if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
652
0
            Target.getEnvironment() == llvm::Triple::GNUABIN32)
653
0
          Target.setEnvironment(llvm::Triple::GNU);
654
0
      } else if (ABIName == "n32") {
655
0
        Target = Target.get64BitArchVariant();
656
0
        if (Target.getEnvironment() == llvm::Triple::GNU ||
657
0
            Target.getEnvironment() == llvm::Triple::GNUABI64)
658
0
          Target.setEnvironment(llvm::Triple::GNUABIN32);
659
0
      } else if (ABIName == "64") {
660
0
        Target = Target.get64BitArchVariant();
661
0
        if (Target.getEnvironment() == llvm::Triple::GNU ||
662
0
            Target.getEnvironment() == llvm::Triple::GNUABIN32)
663
0
          Target.setEnvironment(llvm::Triple::GNUABI64);
664
0
      }
665
0
    }
666
0
  }
667
668
  // If target is RISC-V adjust the target triple according to
669
  // provided architecture name
670
0
  if (Target.isRISCV()) {
671
0
    if (Args.hasArg(options::OPT_march_EQ) ||
672
0
        Args.hasArg(options::OPT_mcpu_EQ)) {
673
0
      StringRef ArchName = tools::riscv::getRISCVArch(Args, Target);
674
0
      auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
675
0
          ArchName, /*EnableExperimentalExtensions=*/true);
676
0
      if (!llvm::errorToBool(ISAInfo.takeError())) {
677
0
        unsigned XLen = (*ISAInfo)->getXLen();
678
0
        if (XLen == 32)
679
0
          Target.setArch(llvm::Triple::riscv32);
680
0
        else if (XLen == 64)
681
0
          Target.setArch(llvm::Triple::riscv64);
682
0
      }
683
0
    }
684
0
  }
685
686
0
  return Target;
687
0
}
688
689
// Parse the LTO options and record the type of LTO compilation
690
// based on which -f(no-)?lto(=.*)? or -f(no-)?offload-lto(=.*)?
691
// option occurs last.
692
static driver::LTOKind parseLTOMode(Driver &D, const llvm::opt::ArgList &Args,
693
0
                                    OptSpecifier OptEq, OptSpecifier OptNeg) {
694
0
  if (!Args.hasFlag(OptEq, OptNeg, false))
695
0
    return LTOK_None;
696
697
0
  const Arg *A = Args.getLastArg(OptEq);
698
0
  StringRef LTOName = A->getValue();
699
700
0
  driver::LTOKind LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
701
0
                                .Case("full", LTOK_Full)
702
0
                                .Case("thin", LTOK_Thin)
703
0
                                .Default(LTOK_Unknown);
704
705
0
  if (LTOMode == LTOK_Unknown) {
706
0
    D.Diag(diag::err_drv_unsupported_option_argument)
707
0
        << A->getSpelling() << A->getValue();
708
0
    return LTOK_None;
709
0
  }
710
0
  return LTOMode;
711
0
}
712
713
// Parse the LTO options.
714
0
void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
715
0
  LTOMode =
716
0
      parseLTOMode(*this, Args, options::OPT_flto_EQ, options::OPT_fno_lto);
717
718
0
  OffloadLTOMode = parseLTOMode(*this, Args, options::OPT_foffload_lto_EQ,
719
0
                                options::OPT_fno_offload_lto);
720
721
  // Try to enable `-foffload-lto=full` if `-fopenmp-target-jit` is on.
722
0
  if (Args.hasFlag(options::OPT_fopenmp_target_jit,
723
0
                   options::OPT_fno_openmp_target_jit, false)) {
724
0
    if (Arg *A = Args.getLastArg(options::OPT_foffload_lto_EQ,
725
0
                                 options::OPT_fno_offload_lto))
726
0
      if (OffloadLTOMode != LTOK_Full)
727
0
        Diag(diag::err_drv_incompatible_options)
728
0
            << A->getSpelling() << "-fopenmp-target-jit";
729
0
    OffloadLTOMode = LTOK_Full;
730
0
  }
731
0
}
732
733
/// Compute the desired OpenMP runtime from the flags provided.
734
0
Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
735
0
  StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
736
737
0
  const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
738
0
  if (A)
739
0
    RuntimeName = A->getValue();
740
741
0
  auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
742
0
                .Case("libomp", OMPRT_OMP)
743
0
                .Case("libgomp", OMPRT_GOMP)
744
0
                .Case("libiomp5", OMPRT_IOMP5)
745
0
                .Default(OMPRT_Unknown);
746
747
0
  if (RT == OMPRT_Unknown) {
748
0
    if (A)
749
0
      Diag(diag::err_drv_unsupported_option_argument)
750
0
          << A->getSpelling() << A->getValue();
751
0
    else
752
      // FIXME: We could use a nicer diagnostic here.
753
0
      Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
754
0
  }
755
756
0
  return RT;
757
0
}
758
759
void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
760
0
                                              InputList &Inputs) {
761
762
  //
763
  // CUDA/HIP
764
  //
765
  // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
766
  // or HIP type. However, mixed CUDA/HIP compilation is not supported.
767
0
  bool IsCuda =
768
0
      llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
769
0
        return types::isCuda(I.first);
770
0
      });
771
0
  bool IsHIP =
772
0
      llvm::any_of(Inputs,
773
0
                   [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
774
0
                     return types::isHIP(I.first);
775
0
                   }) ||
776
0
      C.getInputArgs().hasArg(options::OPT_hip_link) ||
777
0
      C.getInputArgs().hasArg(options::OPT_hipstdpar);
778
0
  if (IsCuda && IsHIP) {
779
0
    Diag(clang::diag::err_drv_mix_cuda_hip);
780
0
    return;
781
0
  }
782
0
  if (IsCuda) {
783
0
    const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
784
0
    const llvm::Triple &HostTriple = HostTC->getTriple();
785
0
    auto OFK = Action::OFK_Cuda;
786
0
    auto CudaTriple =
787
0
        getNVIDIAOffloadTargetTriple(*this, C.getInputArgs(), HostTriple);
788
0
    if (!CudaTriple)
789
0
      return;
790
    // Use the CUDA and host triples as the key into the ToolChains map,
791
    // because the device toolchain we create depends on both.
792
0
    auto &CudaTC = ToolChains[CudaTriple->str() + "/" + HostTriple.str()];
793
0
    if (!CudaTC) {
794
0
      CudaTC = std::make_unique<toolchains::CudaToolChain>(
795
0
          *this, *CudaTriple, *HostTC, C.getInputArgs());
796
797
      // Emit a warning if the detected CUDA version is too new.
798
0
      CudaInstallationDetector &CudaInstallation =
799
0
          static_cast<toolchains::CudaToolChain &>(*CudaTC).CudaInstallation;
800
0
      if (CudaInstallation.isValid())
801
0
        CudaInstallation.WarnIfUnsupportedVersion();
802
0
    }
803
0
    C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
804
0
  } else if (IsHIP) {
805
0
    if (auto *OMPTargetArg =
806
0
            C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
807
0
      Diag(clang::diag::err_drv_unsupported_opt_for_language_mode)
808
0
          << OMPTargetArg->getSpelling() << "HIP";
809
0
      return;
810
0
    }
811
0
    const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
812
0
    auto OFK = Action::OFK_HIP;
813
0
    auto HIPTriple = getHIPOffloadTargetTriple(*this, C.getInputArgs());
814
0
    if (!HIPTriple)
815
0
      return;
816
0
    auto *HIPTC = &getOffloadingDeviceToolChain(C.getInputArgs(), *HIPTriple,
817
0
                                                *HostTC, OFK);
818
0
    assert(HIPTC && "Could not create offloading device tool chain.");
819
0
    C.addOffloadDeviceToolChain(HIPTC, OFK);
820
0
  }
821
822
  //
823
  // OpenMP
824
  //
825
  // We need to generate an OpenMP toolchain if the user specified targets with
826
  // the -fopenmp-targets option or used --offload-arch with OpenMP enabled.
827
0
  bool IsOpenMPOffloading =
828
0
      C.getInputArgs().hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
829
0
                               options::OPT_fno_openmp, false) &&
830
0
      (C.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ) ||
831
0
       C.getInputArgs().hasArg(options::OPT_offload_arch_EQ));
832
0
  if (IsOpenMPOffloading) {
833
    // We expect that -fopenmp-targets is always used in conjunction with the
834
    // option -fopenmp specifying a valid runtime with offloading support, i.e.
835
    // libomp or libiomp.
836
0
    OpenMPRuntimeKind RuntimeKind = getOpenMPRuntime(C.getInputArgs());
837
0
    if (RuntimeKind != OMPRT_OMP && RuntimeKind != OMPRT_IOMP5) {
838
0
      Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
839
0
      return;
840
0
    }
841
842
0
    llvm::StringMap<llvm::DenseSet<StringRef>> DerivedArchs;
843
0
    llvm::StringMap<StringRef> FoundNormalizedTriples;
844
0
    std::multiset<StringRef> OpenMPTriples;
845
846
    // If the user specified -fopenmp-targets= we create a toolchain for each
847
    // valid triple. Otherwise, if only --offload-arch= was specified we instead
848
    // attempt to derive the appropriate toolchains from the arguments.
849
0
    if (Arg *OpenMPTargets =
850
0
            C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
851
0
      if (OpenMPTargets && !OpenMPTargets->getNumValues()) {
852
0
        Diag(clang::diag::warn_drv_empty_joined_argument)
853
0
            << OpenMPTargets->getAsString(C.getInputArgs());
854
0
        return;
855
0
      }
856
0
      for (StringRef T : OpenMPTargets->getValues())
857
0
        OpenMPTriples.insert(T);
858
0
    } else if (C.getInputArgs().hasArg(options::OPT_offload_arch_EQ) &&
859
0
               !IsHIP && !IsCuda) {
860
0
      const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
861
0
      auto AMDTriple = getHIPOffloadTargetTriple(*this, C.getInputArgs());
862
0
      auto NVPTXTriple = getNVIDIAOffloadTargetTriple(*this, C.getInputArgs(),
863
0
                                                      HostTC->getTriple());
864
865
      // Attempt to deduce the offloading triple from the set of architectures.
866
      // We can only correctly deduce NVPTX / AMDGPU triples currently. We need
867
      // to temporarily create these toolchains so that we can access tools for
868
      // inferring architectures.
869
0
      llvm::DenseSet<StringRef> Archs;
870
0
      if (NVPTXTriple) {
871
0
        auto TempTC = std::make_unique<toolchains::CudaToolChain>(
872
0
            *this, *NVPTXTriple, *HostTC, C.getInputArgs());
873
0
        for (StringRef Arch : getOffloadArchs(
874
0
                 C, C.getArgs(), Action::OFK_OpenMP, &*TempTC, true))
875
0
          Archs.insert(Arch);
876
0
      }
877
0
      if (AMDTriple) {
878
0
        auto TempTC = std::make_unique<toolchains::AMDGPUOpenMPToolChain>(
879
0
            *this, *AMDTriple, *HostTC, C.getInputArgs());
880
0
        for (StringRef Arch : getOffloadArchs(
881
0
                 C, C.getArgs(), Action::OFK_OpenMP, &*TempTC, true))
882
0
          Archs.insert(Arch);
883
0
      }
884
0
      if (!AMDTriple && !NVPTXTriple) {
885
0
        for (StringRef Arch :
886
0
             getOffloadArchs(C, C.getArgs(), Action::OFK_OpenMP, nullptr, true))
887
0
          Archs.insert(Arch);
888
0
      }
889
890
0
      for (StringRef Arch : Archs) {
891
0
        if (NVPTXTriple && IsNVIDIAGpuArch(StringToCudaArch(
892
0
                               getProcessorFromTargetID(*NVPTXTriple, Arch)))) {
893
0
          DerivedArchs[NVPTXTriple->getTriple()].insert(Arch);
894
0
        } else if (AMDTriple &&
895
0
                   IsAMDGpuArch(StringToCudaArch(
896
0
                       getProcessorFromTargetID(*AMDTriple, Arch)))) {
897
0
          DerivedArchs[AMDTriple->getTriple()].insert(Arch);
898
0
        } else {
899
0
          Diag(clang::diag::err_drv_failed_to_deduce_target_from_arch) << Arch;
900
0
          return;
901
0
        }
902
0
      }
903
904
      // If the set is empty then we failed to find a native architecture.
905
0
      if (Archs.empty()) {
906
0
        Diag(clang::diag::err_drv_failed_to_deduce_target_from_arch)
907
0
            << "native";
908
0
        return;
909
0
      }
910
911
0
      for (const auto &TripleAndArchs : DerivedArchs)
912
0
        OpenMPTriples.insert(TripleAndArchs.first());
913
0
    }
914
915
0
    for (StringRef Val : OpenMPTriples) {
916
0
      llvm::Triple TT(ToolChain::getOpenMPTriple(Val));
917
0
      std::string NormalizedName = TT.normalize();
918
919
      // Make sure we don't have a duplicate triple.
920
0
      auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
921
0
      if (Duplicate != FoundNormalizedTriples.end()) {
922
0
        Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
923
0
            << Val << Duplicate->second;
924
0
        continue;
925
0
      }
926
927
      // Store the current triple so that we can check for duplicates in the
928
      // following iterations.
929
0
      FoundNormalizedTriples[NormalizedName] = Val;
930
931
      // If the specified target is invalid, emit a diagnostic.
932
0
      if (TT.getArch() == llvm::Triple::UnknownArch)
933
0
        Diag(clang::diag::err_drv_invalid_omp_target) << Val;
934
0
      else {
935
0
        const ToolChain *TC;
936
        // Device toolchains have to be selected differently. They pair host
937
        // and device in their implementation.
938
0
        if (TT.isNVPTX() || TT.isAMDGCN()) {
939
0
          const ToolChain *HostTC =
940
0
              C.getSingleOffloadToolChain<Action::OFK_Host>();
941
0
          assert(HostTC && "Host toolchain should be always defined.");
942
0
          auto &DeviceTC =
943
0
              ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
944
0
          if (!DeviceTC) {
945
0
            if (TT.isNVPTX())
946
0
              DeviceTC = std::make_unique<toolchains::CudaToolChain>(
947
0
                  *this, TT, *HostTC, C.getInputArgs());
948
0
            else if (TT.isAMDGCN())
949
0
              DeviceTC = std::make_unique<toolchains::AMDGPUOpenMPToolChain>(
950
0
                  *this, TT, *HostTC, C.getInputArgs());
951
0
            else
952
0
              assert(DeviceTC && "Device toolchain not defined.");
953
0
          }
954
955
0
          TC = DeviceTC.get();
956
0
        } else
957
0
          TC = &getToolChain(C.getInputArgs(), TT);
958
0
        C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
959
0
        if (DerivedArchs.contains(TT.getTriple()))
960
0
          KnownArchs[TC] = DerivedArchs[TT.getTriple()];
961
0
      }
962
0
    }
963
0
  } else if (C.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ)) {
964
0
    Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
965
0
    return;
966
0
  }
967
968
  //
969
  // TODO: Add support for other offloading programming models here.
970
  //
971
0
}
972
973
static void appendOneArg(InputArgList &Args, const Arg *Opt,
974
0
                         const Arg *BaseArg) {
975
  // The args for config files or /clang: flags belong to different InputArgList
976
  // objects than Args. This copies an Arg from one of those other InputArgLists
977
  // to the ownership of Args.
978
0
  unsigned Index = Args.MakeIndex(Opt->getSpelling());
979
0
  Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Args.getArgString(Index),
980
0
                                 Index, BaseArg);
981
0
  Copy->getValues() = Opt->getValues();
982
0
  if (Opt->isClaimed())
983
0
    Copy->claim();
984
0
  Copy->setOwnsValues(Opt->getOwnsValues());
985
0
  Opt->setOwnsValues(false);
986
0
  Args.append(Copy);
987
0
}
988
989
bool Driver::readConfigFile(StringRef FileName,
990
0
                            llvm::cl::ExpansionContext &ExpCtx) {
991
  // Try opening the given file.
992
0
  auto Status = getVFS().status(FileName);
993
0
  if (!Status) {
994
0
    Diag(diag::err_drv_cannot_open_config_file)
995
0
        << FileName << Status.getError().message();
996
0
    return true;
997
0
  }
998
0
  if (Status->getType() != llvm::sys::fs::file_type::regular_file) {
999
0
    Diag(diag::err_drv_cannot_open_config_file)
1000
0
        << FileName << "not a regular file";
1001
0
    return true;
1002
0
  }
1003
1004
  // Try reading the given file.
1005
0
  SmallVector<const char *, 32> NewCfgArgs;
1006
0
  if (llvm::Error Err = ExpCtx.readConfigFile(FileName, NewCfgArgs)) {
1007
0
    Diag(diag::err_drv_cannot_read_config_file)
1008
0
        << FileName << toString(std::move(Err));
1009
0
    return true;
1010
0
  }
1011
1012
  // Read options from config file.
1013
0
  llvm::SmallString<128> CfgFileName(FileName);
1014
0
  llvm::sys::path::native(CfgFileName);
1015
0
  bool ContainErrors;
1016
0
  std::unique_ptr<InputArgList> NewOptions = std::make_unique<InputArgList>(
1017
0
      ParseArgStrings(NewCfgArgs, /*UseDriverMode=*/true, ContainErrors));
1018
0
  if (ContainErrors)
1019
0
    return true;
1020
1021
  // Claim all arguments that come from a configuration file so that the driver
1022
  // does not warn on any that is unused.
1023
0
  for (Arg *A : *NewOptions)
1024
0
    A->claim();
1025
1026
0
  if (!CfgOptions)
1027
0
    CfgOptions = std::move(NewOptions);
1028
0
  else {
1029
    // If this is a subsequent config file, append options to the previous one.
1030
0
    for (auto *Opt : *NewOptions) {
1031
0
      const Arg *BaseArg = &Opt->getBaseArg();
1032
0
      if (BaseArg == Opt)
1033
0
        BaseArg = nullptr;
1034
0
      appendOneArg(*CfgOptions, Opt, BaseArg);
1035
0
    }
1036
0
  }
1037
0
  ConfigFiles.push_back(std::string(CfgFileName));
1038
0
  return false;
1039
0
}
1040
1041
0
bool Driver::loadConfigFiles() {
1042
0
  llvm::cl::ExpansionContext ExpCtx(Saver.getAllocator(),
1043
0
                                    llvm::cl::tokenizeConfigFile);
1044
0
  ExpCtx.setVFS(&getVFS());
1045
1046
  // Process options that change search path for config files.
1047
0
  if (CLOptions) {
1048
0
    if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
1049
0
      SmallString<128> CfgDir;
1050
0
      CfgDir.append(
1051
0
          CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
1052
0
      if (CfgDir.empty() || getVFS().makeAbsolute(CfgDir))
1053
0
        SystemConfigDir.clear();
1054
0
      else
1055
0
        SystemConfigDir = static_cast<std::string>(CfgDir);
1056
0
    }
1057
0
    if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
1058
0
      SmallString<128> CfgDir;
1059
0
      llvm::sys::fs::expand_tilde(
1060
0
          CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ), CfgDir);
1061
0
      if (CfgDir.empty() || getVFS().makeAbsolute(CfgDir))
1062
0
        UserConfigDir.clear();
1063
0
      else
1064
0
        UserConfigDir = static_cast<std::string>(CfgDir);
1065
0
    }
1066
0
  }
1067
1068
  // Prepare list of directories where config file is searched for.
1069
0
  StringRef CfgFileSearchDirs[] = {UserConfigDir, SystemConfigDir, Dir};
1070
0
  ExpCtx.setSearchDirs(CfgFileSearchDirs);
1071
1072
  // First try to load configuration from the default files, return on error.
1073
0
  if (loadDefaultConfigFiles(ExpCtx))
1074
0
    return true;
1075
1076
  // Then load configuration files specified explicitly.
1077
0
  SmallString<128> CfgFilePath;
1078
0
  if (CLOptions) {
1079
0
    for (auto CfgFileName : CLOptions->getAllArgValues(options::OPT_config)) {
1080
      // If argument contains directory separator, treat it as a path to
1081
      // configuration file.
1082
0
      if (llvm::sys::path::has_parent_path(CfgFileName)) {
1083
0
        CfgFilePath.assign(CfgFileName);
1084
0
        if (llvm::sys::path::is_relative(CfgFilePath)) {
1085
0
          if (getVFS().makeAbsolute(CfgFilePath)) {
1086
0
            Diag(diag::err_drv_cannot_open_config_file)
1087
0
                << CfgFilePath << "cannot get absolute path";
1088
0
            return true;
1089
0
          }
1090
0
        }
1091
0
      } else if (!ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) {
1092
        // Report an error that the config file could not be found.
1093
0
        Diag(diag::err_drv_config_file_not_found) << CfgFileName;
1094
0
        for (const StringRef &SearchDir : CfgFileSearchDirs)
1095
0
          if (!SearchDir.empty())
1096
0
            Diag(diag::note_drv_config_file_searched_in) << SearchDir;
1097
0
        return true;
1098
0
      }
1099
1100
      // Try to read the config file, return on error.
1101
0
      if (readConfigFile(CfgFilePath, ExpCtx))
1102
0
        return true;
1103
0
    }
1104
0
  }
1105
1106
  // No error occurred.
1107
0
  return false;
1108
0
}
1109
1110
0
bool Driver::loadDefaultConfigFiles(llvm::cl::ExpansionContext &ExpCtx) {
1111
  // Disable default config if CLANG_NO_DEFAULT_CONFIG is set to a non-empty
1112
  // value.
1113
0
  if (const char *NoConfigEnv = ::getenv("CLANG_NO_DEFAULT_CONFIG")) {
1114
0
    if (*NoConfigEnv)
1115
0
      return false;
1116
0
  }
1117
0
  if (CLOptions && CLOptions->hasArg(options::OPT_no_default_config))
1118
0
    return false;
1119
1120
0
  std::string RealMode = getExecutableForDriverMode(Mode);
1121
0
  std::string Triple;
1122
1123
  // If name prefix is present, no --target= override was passed via CLOptions
1124
  // and the name prefix is not a valid triple, force it for backwards
1125
  // compatibility.
1126
0
  if (!ClangNameParts.TargetPrefix.empty() &&
1127
0
      computeTargetTriple(*this, "/invalid/", *CLOptions).str() ==
1128
0
          "/invalid/") {
1129
0
    llvm::Triple PrefixTriple{ClangNameParts.TargetPrefix};
1130
0
    if (PrefixTriple.getArch() == llvm::Triple::UnknownArch ||
1131
0
        PrefixTriple.isOSUnknown())
1132
0
      Triple = PrefixTriple.str();
1133
0
  }
1134
1135
  // Otherwise, use the real triple as used by the driver.
1136
0
  if (Triple.empty()) {
1137
0
    llvm::Triple RealTriple =
1138
0
        computeTargetTriple(*this, TargetTriple, *CLOptions);
1139
0
    Triple = RealTriple.str();
1140
0
    assert(!Triple.empty());
1141
0
  }
1142
1143
  // Search for config files in the following order:
1144
  // 1. <triple>-<mode>.cfg using real driver mode
1145
  //    (e.g. i386-pc-linux-gnu-clang++.cfg).
1146
  // 2. <triple>-<mode>.cfg using executable suffix
1147
  //    (e.g. i386-pc-linux-gnu-clang-g++.cfg for *clang-g++).
1148
  // 3. <triple>.cfg + <mode>.cfg using real driver mode
1149
  //    (e.g. i386-pc-linux-gnu.cfg + clang++.cfg).
1150
  // 4. <triple>.cfg + <mode>.cfg using executable suffix
1151
  //    (e.g. i386-pc-linux-gnu.cfg + clang-g++.cfg for *clang-g++).
1152
1153
  // Try loading <triple>-<mode>.cfg, and return if we find a match.
1154
0
  SmallString<128> CfgFilePath;
1155
0
  std::string CfgFileName = Triple + '-' + RealMode + ".cfg";
1156
0
  if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath))
1157
0
    return readConfigFile(CfgFilePath, ExpCtx);
1158
1159
0
  bool TryModeSuffix = !ClangNameParts.ModeSuffix.empty() &&
1160
0
                       ClangNameParts.ModeSuffix != RealMode;
1161
0
  if (TryModeSuffix) {
1162
0
    CfgFileName = Triple + '-' + ClangNameParts.ModeSuffix + ".cfg";
1163
0
    if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath))
1164
0
      return readConfigFile(CfgFilePath, ExpCtx);
1165
0
  }
1166
1167
  // Try loading <mode>.cfg, and return if loading failed.  If a matching file
1168
  // was not found, still proceed on to try <triple>.cfg.
1169
0
  CfgFileName = RealMode + ".cfg";
1170
0
  if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) {
1171
0
    if (readConfigFile(CfgFilePath, ExpCtx))
1172
0
      return true;
1173
0
  } else if (TryModeSuffix) {
1174
0
    CfgFileName = ClangNameParts.ModeSuffix + ".cfg";
1175
0
    if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath) &&
1176
0
        readConfigFile(CfgFilePath, ExpCtx))
1177
0
      return true;
1178
0
  }
1179
1180
  // Try loading <triple>.cfg and return if we find a match.
1181
0
  CfgFileName = Triple + ".cfg";
1182
0
  if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath))
1183
0
    return readConfigFile(CfgFilePath, ExpCtx);
1184
1185
  // If we were unable to find a config file deduced from executable name,
1186
  // that is not an error.
1187
0
  return false;
1188
0
}
1189
1190
0
Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
1191
0
  llvm::PrettyStackTraceString CrashInfo("Compilation construction");
1192
1193
  // FIXME: Handle environment options which affect driver behavior, somewhere
1194
  // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
1195
1196
  // We look for the driver mode option early, because the mode can affect
1197
  // how other options are parsed.
1198
1199
0
  auto DriverMode = getDriverMode(ClangExecutable, ArgList.slice(1));
1200
0
  if (!DriverMode.empty())
1201
0
    setDriverMode(DriverMode);
1202
1203
  // FIXME: What are we going to do with -V and -b?
1204
1205
  // Arguments specified in command line.
1206
0
  bool ContainsError;
1207
0
  CLOptions = std::make_unique<InputArgList>(
1208
0
      ParseArgStrings(ArgList.slice(1), /*UseDriverMode=*/true, ContainsError));
1209
1210
  // Try parsing configuration file.
1211
0
  if (!ContainsError)
1212
0
    ContainsError = loadConfigFiles();
1213
0
  bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
1214
1215
  // All arguments, from both config file and command line.
1216
0
  InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
1217
0
                                              : std::move(*CLOptions));
1218
1219
0
  if (HasConfigFile)
1220
0
    for (auto *Opt : *CLOptions) {
1221
0
      if (Opt->getOption().matches(options::OPT_config))
1222
0
        continue;
1223
0
      const Arg *BaseArg = &Opt->getBaseArg();
1224
0
      if (BaseArg == Opt)
1225
0
        BaseArg = nullptr;
1226
0
      appendOneArg(Args, Opt, BaseArg);
1227
0
    }
1228
1229
  // In CL mode, look for any pass-through arguments
1230
0
  if (IsCLMode() && !ContainsError) {
1231
0
    SmallVector<const char *, 16> CLModePassThroughArgList;
1232
0
    for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
1233
0
      A->claim();
1234
0
      CLModePassThroughArgList.push_back(A->getValue());
1235
0
    }
1236
1237
0
    if (!CLModePassThroughArgList.empty()) {
1238
      // Parse any pass through args using default clang processing rather
1239
      // than clang-cl processing.
1240
0
      auto CLModePassThroughOptions = std::make_unique<InputArgList>(
1241
0
          ParseArgStrings(CLModePassThroughArgList, /*UseDriverMode=*/false,
1242
0
                          ContainsError));
1243
1244
0
      if (!ContainsError)
1245
0
        for (auto *Opt : *CLModePassThroughOptions) {
1246
0
          appendOneArg(Args, Opt, nullptr);
1247
0
        }
1248
0
    }
1249
0
  }
1250
1251
  // Check for working directory option before accessing any files
1252
0
  if (Arg *WD = Args.getLastArg(options::OPT_working_directory))
1253
0
    if (VFS->setCurrentWorkingDirectory(WD->getValue()))
1254
0
      Diag(diag::err_drv_unable_to_set_working_directory) << WD->getValue();
1255
1256
  // FIXME: This stuff needs to go into the Compilation, not the driver.
1257
0
  bool CCCPrintPhases;
1258
1259
  // -canonical-prefixes, -no-canonical-prefixes are used very early in main.
1260
0
  Args.ClaimAllArgs(options::OPT_canonical_prefixes);
1261
0
  Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
1262
1263
  // f(no-)integated-cc1 is also used very early in main.
1264
0
  Args.ClaimAllArgs(options::OPT_fintegrated_cc1);
1265
0
  Args.ClaimAllArgs(options::OPT_fno_integrated_cc1);
1266
1267
  // Ignore -pipe.
1268
0
  Args.ClaimAllArgs(options::OPT_pipe);
1269
1270
  // Extract -ccc args.
1271
  //
1272
  // FIXME: We need to figure out where this behavior should live. Most of it
1273
  // should be outside in the client; the parts that aren't should have proper
1274
  // options, either by introducing new ones or by overloading gcc ones like -V
1275
  // or -b.
1276
0
  CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
1277
0
  CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
1278
0
  if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
1279
0
    CCCGenericGCCName = A->getValue();
1280
1281
  // Process -fproc-stat-report options.
1282
0
  if (const Arg *A = Args.getLastArg(options::OPT_fproc_stat_report_EQ)) {
1283
0
    CCPrintProcessStats = true;
1284
0
    CCPrintStatReportFilename = A->getValue();
1285
0
  }
1286
0
  if (Args.hasArg(options::OPT_fproc_stat_report))
1287
0
    CCPrintProcessStats = true;
1288
1289
  // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
1290
  // and getToolChain is const.
1291
0
  if (IsCLMode()) {
1292
    // clang-cl targets MSVC-style Win32.
1293
0
    llvm::Triple T(TargetTriple);
1294
0
    T.setOS(llvm::Triple::Win32);
1295
0
    T.setVendor(llvm::Triple::PC);
1296
0
    T.setEnvironment(llvm::Triple::MSVC);
1297
0
    T.setObjectFormat(llvm::Triple::COFF);
1298
0
    if (Args.hasArg(options::OPT__SLASH_arm64EC))
1299
0
      T.setArch(llvm::Triple::aarch64, llvm::Triple::AArch64SubArch_arm64ec);
1300
0
    TargetTriple = T.str();
1301
0
  } else if (IsDXCMode()) {
1302
    // Build TargetTriple from target_profile option for clang-dxc.
1303
0
    if (const Arg *A = Args.getLastArg(options::OPT_target_profile)) {
1304
0
      StringRef TargetProfile = A->getValue();
1305
0
      if (auto Triple =
1306
0
              toolchains::HLSLToolChain::parseTargetProfile(TargetProfile))
1307
0
        TargetTriple = *Triple;
1308
0
      else
1309
0
        Diag(diag::err_drv_invalid_directx_shader_module) << TargetProfile;
1310
1311
0
      A->claim();
1312
1313
      // TODO: Specify Vulkan target environment somewhere in the triple.
1314
0
      if (Args.hasArg(options::OPT_spirv)) {
1315
0
        llvm::Triple T(TargetTriple);
1316
0
        T.setArch(llvm::Triple::spirv);
1317
0
        TargetTriple = T.str();
1318
0
      }
1319
0
    } else {
1320
0
      Diag(diag::err_drv_dxc_missing_target_profile);
1321
0
    }
1322
0
  }
1323
1324
0
  if (const Arg *A = Args.getLastArg(options::OPT_target))
1325
0
    TargetTriple = A->getValue();
1326
0
  if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
1327
0
    Dir = InstalledDir = A->getValue();
1328
0
  for (const Arg *A : Args.filtered(options::OPT_B)) {
1329
0
    A->claim();
1330
0
    PrefixDirs.push_back(A->getValue(0));
1331
0
  }
1332
0
  if (std::optional<std::string> CompilerPathValue =
1333
0
          llvm::sys::Process::GetEnv("COMPILER_PATH")) {
1334
0
    StringRef CompilerPath = *CompilerPathValue;
1335
0
    while (!CompilerPath.empty()) {
1336
0
      std::pair<StringRef, StringRef> Split =
1337
0
          CompilerPath.split(llvm::sys::EnvPathSeparator);
1338
0
      PrefixDirs.push_back(std::string(Split.first));
1339
0
      CompilerPath = Split.second;
1340
0
    }
1341
0
  }
1342
0
  if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
1343
0
    SysRoot = A->getValue();
1344
0
  if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
1345
0
    DyldPrefix = A->getValue();
1346
1347
0
  if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
1348
0
    ResourceDir = A->getValue();
1349
1350
0
  if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
1351
0
    SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1352
0
                    .Case("cwd", SaveTempsCwd)
1353
0
                    .Case("obj", SaveTempsObj)
1354
0
                    .Default(SaveTempsCwd);
1355
0
  }
1356
1357
0
  if (const Arg *A = Args.getLastArg(options::OPT_offload_host_only,
1358
0
                                     options::OPT_offload_device_only,
1359
0
                                     options::OPT_offload_host_device)) {
1360
0
    if (A->getOption().matches(options::OPT_offload_host_only))
1361
0
      Offload = OffloadHost;
1362
0
    else if (A->getOption().matches(options::OPT_offload_device_only))
1363
0
      Offload = OffloadDevice;
1364
0
    else
1365
0
      Offload = OffloadHostDevice;
1366
0
  }
1367
1368
0
  setLTOMode(Args);
1369
1370
  // Process -fembed-bitcode= flags.
1371
0
  if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1372
0
    StringRef Name = A->getValue();
1373
0
    unsigned Model = llvm::StringSwitch<unsigned>(Name)
1374
0
        .Case("off", EmbedNone)
1375
0
        .Case("all", EmbedBitcode)
1376
0
        .Case("bitcode", EmbedBitcode)
1377
0
        .Case("marker", EmbedMarker)
1378
0
        .Default(~0U);
1379
0
    if (Model == ~0U) {
1380
0
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1381
0
                                                << Name;
1382
0
    } else
1383
0
      BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
1384
0
  }
1385
1386
  // Remove existing compilation database so that each job can append to it.
1387
0
  if (Arg *A = Args.getLastArg(options::OPT_MJ))
1388
0
    llvm::sys::fs::remove(A->getValue());
1389
1390
  // Setting up the jobs for some precompile cases depends on whether we are
1391
  // treating them as PCH, implicit modules or C++20 ones.
1392
  // TODO: inferring the mode like this seems fragile (it meets the objective
1393
  // of not requiring anything new for operation, however).
1394
0
  const Arg *Std = Args.getLastArg(options::OPT_std_EQ);
1395
0
  ModulesModeCXX20 =
1396
0
      !Args.hasArg(options::OPT_fmodules) && Std &&
1397
0
      (Std->containsValue("c++20") || Std->containsValue("c++2a") ||
1398
0
       Std->containsValue("c++23") || Std->containsValue("c++2b") ||
1399
0
       Std->containsValue("c++26") || Std->containsValue("c++2c") ||
1400
0
       Std->containsValue("c++latest"));
1401
1402
  // Process -fmodule-header{=} flags.
1403
0
  if (Arg *A = Args.getLastArg(options::OPT_fmodule_header_EQ,
1404
0
                               options::OPT_fmodule_header)) {
1405
    // These flags force C++20 handling of headers.
1406
0
    ModulesModeCXX20 = true;
1407
0
    if (A->getOption().matches(options::OPT_fmodule_header))
1408
0
      CXX20HeaderType = HeaderMode_Default;
1409
0
    else {
1410
0
      StringRef ArgName = A->getValue();
1411
0
      unsigned Kind = llvm::StringSwitch<unsigned>(ArgName)
1412
0
                          .Case("user", HeaderMode_User)
1413
0
                          .Case("system", HeaderMode_System)
1414
0
                          .Default(~0U);
1415
0
      if (Kind == ~0U) {
1416
0
        Diags.Report(diag::err_drv_invalid_value)
1417
0
            << A->getAsString(Args) << ArgName;
1418
0
      } else
1419
0
        CXX20HeaderType = static_cast<ModuleHeaderMode>(Kind);
1420
0
    }
1421
0
  }
1422
1423
0
  std::unique_ptr<llvm::opt::InputArgList> UArgs =
1424
0
      std::make_unique<InputArgList>(std::move(Args));
1425
1426
  // Perform the default argument translations.
1427
0
  DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
1428
1429
  // Owned by the host.
1430
0
  const ToolChain &TC = getToolChain(
1431
0
      *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
1432
1433
0
  if (TC.getTriple().isAndroid()) {
1434
0
    llvm::Triple Triple = TC.getTriple();
1435
0
    StringRef TripleVersionName = Triple.getEnvironmentVersionString();
1436
1437
0
    if (Triple.getEnvironmentVersion().empty() && TripleVersionName != "") {
1438
0
      Diags.Report(diag::err_drv_triple_version_invalid)
1439
0
          << TripleVersionName << TC.getTripleString();
1440
0
      ContainsError = true;
1441
0
    }
1442
0
  }
1443
1444
  // Report warning when arm64EC option is overridden by specified target
1445
0
  if ((TC.getTriple().getArch() != llvm::Triple::aarch64 ||
1446
0
       TC.getTriple().getSubArch() != llvm::Triple::AArch64SubArch_arm64ec) &&
1447
0
      UArgs->hasArg(options::OPT__SLASH_arm64EC)) {
1448
0
    getDiags().Report(clang::diag::warn_target_override_arm64ec)
1449
0
        << TC.getTriple().str();
1450
0
  }
1451
1452
  // A common user mistake is specifying a target of aarch64-none-eabi or
1453
  // arm-none-elf whereas the correct names are aarch64-none-elf &
1454
  // arm-none-eabi. Detect these cases and issue a warning.
1455
0
  if (TC.getTriple().getOS() == llvm::Triple::UnknownOS &&
1456
0
      TC.getTriple().getVendor() == llvm::Triple::UnknownVendor) {
1457
0
    switch (TC.getTriple().getArch()) {
1458
0
    case llvm::Triple::arm:
1459
0
    case llvm::Triple::armeb:
1460
0
    case llvm::Triple::thumb:
1461
0
    case llvm::Triple::thumbeb:
1462
0
      if (TC.getTriple().getEnvironmentName() == "elf") {
1463
0
        Diag(diag::warn_target_unrecognized_env)
1464
0
            << TargetTriple
1465
0
            << (TC.getTriple().getArchName().str() + "-none-eabi");
1466
0
      }
1467
0
      break;
1468
0
    case llvm::Triple::aarch64:
1469
0
    case llvm::Triple::aarch64_be:
1470
0
    case llvm::Triple::aarch64_32:
1471
0
      if (TC.getTriple().getEnvironmentName().starts_with("eabi")) {
1472
0
        Diag(diag::warn_target_unrecognized_env)
1473
0
            << TargetTriple
1474
0
            << (TC.getTriple().getArchName().str() + "-none-elf");
1475
0
      }
1476
0
      break;
1477
0
    default:
1478
0
      break;
1479
0
    }
1480
0
  }
1481
1482
  // The compilation takes ownership of Args.
1483
0
  Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1484
0
                                   ContainsError);
1485
1486
0
  if (!HandleImmediateArgs(*C))
1487
0
    return C;
1488
1489
  // Construct the list of inputs.
1490
0
  InputList Inputs;
1491
0
  BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
1492
1493
  // Populate the tool chains for the offloading devices, if any.
1494
0
  CreateOffloadingDeviceToolChains(*C, Inputs);
1495
1496
  // Construct the list of abstract actions to perform for this compilation. On
1497
  // MachO targets this uses the driver-driver and universal actions.
1498
0
  if (TC.getTriple().isOSBinFormatMachO())
1499
0
    BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
1500
0
  else
1501
0
    BuildActions(*C, C->getArgs(), Inputs, C->getActions());
1502
1503
0
  if (CCCPrintPhases) {
1504
0
    PrintActions(*C);
1505
0
    return C;
1506
0
  }
1507
1508
0
  BuildJobs(*C);
1509
1510
0
  return C;
1511
0
}
1512
1513
0
static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1514
0
  llvm::opt::ArgStringList ASL;
1515
0
  for (const auto *A : Args) {
1516
    // Use user's original spelling of flags. For example, use
1517
    // `/source-charset:utf-8` instead of `-finput-charset=utf-8` if the user
1518
    // wrote the former.
1519
0
    while (A->getAlias())
1520
0
      A = A->getAlias();
1521
0
    A->render(Args, ASL);
1522
0
  }
1523
1524
0
  for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1525
0
    if (I != ASL.begin())
1526
0
      OS << ' ';
1527
0
    llvm::sys::printArg(OS, *I, true);
1528
0
  }
1529
0
  OS << '\n';
1530
0
}
1531
1532
bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1533
0
                                    SmallString<128> &CrashDiagDir) {
1534
0
  using namespace llvm::sys;
1535
0
  assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1536
0
         "Only knows about .crash files on Darwin");
1537
1538
  // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1539
  // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1540
  // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1541
0
  path::home_directory(CrashDiagDir);
1542
0
  if (CrashDiagDir.starts_with("/var/root"))
1543
0
    CrashDiagDir = "/";
1544
0
  path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1545
0
  int PID =
1546
0
#if LLVM_ON_UNIX
1547
0
      getpid();
1548
#else
1549
      0;
1550
#endif
1551
0
  std::error_code EC;
1552
0
  fs::file_status FileStatus;
1553
0
  TimePoint<> LastAccessTime;
1554
0
  SmallString<128> CrashFilePath;
1555
  // Lookup the .crash files and get the one generated by a subprocess spawned
1556
  // by this driver invocation.
1557
0
  for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1558
0
       File != FileEnd && !EC; File.increment(EC)) {
1559
0
    StringRef FileName = path::filename(File->path());
1560
0
    if (!FileName.starts_with(Name))
1561
0
      continue;
1562
0
    if (fs::status(File->path(), FileStatus))
1563
0
      continue;
1564
0
    llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1565
0
        llvm::MemoryBuffer::getFile(File->path());
1566
0
    if (!CrashFile)
1567
0
      continue;
1568
    // The first line should start with "Process:", otherwise this isn't a real
1569
    // .crash file.
1570
0
    StringRef Data = CrashFile.get()->getBuffer();
1571
0
    if (!Data.starts_with("Process:"))
1572
0
      continue;
1573
    // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1574
0
    size_t ParentProcPos = Data.find("Parent Process:");
1575
0
    if (ParentProcPos == StringRef::npos)
1576
0
      continue;
1577
0
    size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1578
0
    if (LineEnd == StringRef::npos)
1579
0
      continue;
1580
0
    StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1581
0
    int OpenBracket = -1, CloseBracket = -1;
1582
0
    for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1583
0
      if (ParentProcess[i] == '[')
1584
0
        OpenBracket = i;
1585
0
      if (ParentProcess[i] == ']')
1586
0
        CloseBracket = i;
1587
0
    }
1588
    // Extract the parent process PID from the .crash file and check whether
1589
    // it matches this driver invocation pid.
1590
0
    int CrashPID;
1591
0
    if (OpenBracket < 0 || CloseBracket < 0 ||
1592
0
        ParentProcess.slice(OpenBracket + 1, CloseBracket)
1593
0
            .getAsInteger(10, CrashPID) || CrashPID != PID) {
1594
0
      continue;
1595
0
    }
1596
1597
    // Found a .crash file matching the driver pid. To avoid getting an older
1598
    // and misleading crash file, continue looking for the most recent.
1599
    // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1600
    // multiple crashes poiting to the same parent process. Since the driver
1601
    // does not collect pid information for the dispatched invocation there's
1602
    // currently no way to distinguish among them.
1603
0
    const auto FileAccessTime = FileStatus.getLastModificationTime();
1604
0
    if (FileAccessTime > LastAccessTime) {
1605
0
      CrashFilePath.assign(File->path());
1606
0
      LastAccessTime = FileAccessTime;
1607
0
    }
1608
0
  }
1609
1610
  // If found, copy it over to the location of other reproducer files.
1611
0
  if (!CrashFilePath.empty()) {
1612
0
    EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1613
0
    if (EC)
1614
0
      return false;
1615
0
    return true;
1616
0
  }
1617
1618
0
  return false;
1619
0
}
1620
1621
static const char BugReporMsg[] =
1622
    "\n********************\n\n"
1623
    "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1624
    "Preprocessed source(s) and associated run script(s) are located at:";
1625
1626
// When clang crashes, produce diagnostic information including the fully
1627
// preprocessed source file(s).  Request that the developer attach the
1628
// diagnostic information to a bug report.
1629
void Driver::generateCompilationDiagnostics(
1630
    Compilation &C, const Command &FailingCommand,
1631
0
    StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
1632
0
  if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
1633
0
    return;
1634
1635
0
  unsigned Level = 1;
1636
0
  if (Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_EQ)) {
1637
0
    Level = llvm::StringSwitch<unsigned>(A->getValue())
1638
0
                .Case("off", 0)
1639
0
                .Case("compiler", 1)
1640
0
                .Case("all", 2)
1641
0
                .Default(1);
1642
0
  }
1643
0
  if (!Level)
1644
0
    return;
1645
1646
  // Don't try to generate diagnostics for dsymutil jobs.
1647
0
  if (FailingCommand.getCreator().isDsymutilJob())
1648
0
    return;
1649
1650
0
  bool IsLLD = false;
1651
0
  ArgStringList SavedTemps;
1652
0
  if (FailingCommand.getCreator().isLinkJob()) {
1653
0
    C.getDefaultToolChain().GetLinkerPath(&IsLLD);
1654
0
    if (!IsLLD || Level < 2)
1655
0
      return;
1656
1657
    // If lld crashed, we will re-run the same command with the input it used
1658
    // to have. In that case we should not remove temp files in
1659
    // initCompilationForDiagnostics yet. They will be added back and removed
1660
    // later.
1661
0
    SavedTemps = std::move(C.getTempFiles());
1662
0
    assert(!C.getTempFiles().size());
1663
0
  }
1664
1665
  // Print the version of the compiler.
1666
0
  PrintVersion(C, llvm::errs());
1667
1668
  // Suppress driver output and emit preprocessor output to temp file.
1669
0
  CCGenDiagnostics = true;
1670
1671
  // Save the original job command(s).
1672
0
  Command Cmd = FailingCommand;
1673
1674
  // Keep track of whether we produce any errors while trying to produce
1675
  // preprocessed sources.
1676
0
  DiagnosticErrorTrap Trap(Diags);
1677
1678
  // Suppress tool output.
1679
0
  C.initCompilationForDiagnostics();
1680
1681
  // If lld failed, rerun it again with --reproduce.
1682
0
  if (IsLLD) {
1683
0
    const char *TmpName = CreateTempFile(C, "linker-crash", "tar");
1684
0
    Command NewLLDInvocation = Cmd;
1685
0
    llvm::opt::ArgStringList ArgList = NewLLDInvocation.getArguments();
1686
0
    StringRef ReproduceOption =
1687
0
        C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment()
1688
0
            ? "/reproduce:"
1689
0
            : "--reproduce=";
1690
0
    ArgList.push_back(Saver.save(Twine(ReproduceOption) + TmpName).data());
1691
0
    NewLLDInvocation.replaceArguments(std::move(ArgList));
1692
1693
    // Redirect stdout/stderr to /dev/null.
1694
0
    NewLLDInvocation.Execute({std::nullopt, {""}, {""}}, nullptr, nullptr);
1695
0
    Diag(clang::diag::note_drv_command_failed_diag_msg) << BugReporMsg;
1696
0
    Diag(clang::diag::note_drv_command_failed_diag_msg) << TmpName;
1697
0
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1698
0
        << "\n\n********************";
1699
0
    if (Report)
1700
0
      Report->TemporaryFiles.push_back(TmpName);
1701
0
    return;
1702
0
  }
1703
1704
  // Construct the list of inputs.
1705
0
  InputList Inputs;
1706
0
  BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
1707
1708
0
  for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
1709
0
    bool IgnoreInput = false;
1710
1711
    // Ignore input from stdin or any inputs that cannot be preprocessed.
1712
    // Check type first as not all linker inputs have a value.
1713
0
    if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
1714
0
      IgnoreInput = true;
1715
0
    } else if (!strcmp(it->second->getValue(), "-")) {
1716
0
      Diag(clang::diag::note_drv_command_failed_diag_msg)
1717
0
          << "Error generating preprocessed source(s) - "
1718
0
             "ignoring input from stdin.";
1719
0
      IgnoreInput = true;
1720
0
    }
1721
1722
0
    if (IgnoreInput) {
1723
0
      it = Inputs.erase(it);
1724
0
      ie = Inputs.end();
1725
0
    } else {
1726
0
      ++it;
1727
0
    }
1728
0
  }
1729
1730
0
  if (Inputs.empty()) {
1731
0
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1732
0
        << "Error generating preprocessed source(s) - "
1733
0
           "no preprocessable inputs.";
1734
0
    return;
1735
0
  }
1736
1737
  // Don't attempt to generate preprocessed files if multiple -arch options are
1738
  // used, unless they're all duplicates.
1739
0
  llvm::StringSet<> ArchNames;
1740
0
  for (const Arg *A : C.getArgs()) {
1741
0
    if (A->getOption().matches(options::OPT_arch)) {
1742
0
      StringRef ArchName = A->getValue();
1743
0
      ArchNames.insert(ArchName);
1744
0
    }
1745
0
  }
1746
0
  if (ArchNames.size() > 1) {
1747
0
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1748
0
        << "Error generating preprocessed source(s) - cannot generate "
1749
0
           "preprocessed source with multiple -arch options.";
1750
0
    return;
1751
0
  }
1752
1753
  // Construct the list of abstract actions to perform for this compilation. On
1754
  // Darwin OSes this uses the driver-driver and builds universal actions.
1755
0
  const ToolChain &TC = C.getDefaultToolChain();
1756
0
  if (TC.getTriple().isOSBinFormatMachO())
1757
0
    BuildUniversalActions(C, TC, Inputs);
1758
0
  else
1759
0
    BuildActions(C, C.getArgs(), Inputs, C.getActions());
1760
1761
0
  BuildJobs(C);
1762
1763
  // If there were errors building the compilation, quit now.
1764
0
  if (Trap.hasErrorOccurred()) {
1765
0
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1766
0
        << "Error generating preprocessed source(s).";
1767
0
    return;
1768
0
  }
1769
1770
  // Generate preprocessed output.
1771
0
  SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
1772
0
  C.ExecuteJobs(C.getJobs(), FailingCommands);
1773
1774
  // If any of the preprocessing commands failed, clean up and exit.
1775
0
  if (!FailingCommands.empty()) {
1776
0
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1777
0
        << "Error generating preprocessed source(s).";
1778
0
    return;
1779
0
  }
1780
1781
0
  const ArgStringList &TempFiles = C.getTempFiles();
1782
0
  if (TempFiles.empty()) {
1783
0
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1784
0
        << "Error generating preprocessed source(s).";
1785
0
    return;
1786
0
  }
1787
1788
0
  Diag(clang::diag::note_drv_command_failed_diag_msg) << BugReporMsg;
1789
1790
0
  SmallString<128> VFS;
1791
0
  SmallString<128> ReproCrashFilename;
1792
0
  for (const char *TempFile : TempFiles) {
1793
0
    Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
1794
0
    if (Report)
1795
0
      Report->TemporaryFiles.push_back(TempFile);
1796
0
    if (ReproCrashFilename.empty()) {
1797
0
      ReproCrashFilename = TempFile;
1798
0
      llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1799
0
    }
1800
0
    if (StringRef(TempFile).ends_with(".cache")) {
1801
      // In some cases (modules) we'll dump extra data to help with reproducing
1802
      // the crash into a directory next to the output.
1803
0
      VFS = llvm::sys::path::filename(TempFile);
1804
0
      llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1805
0
    }
1806
0
  }
1807
1808
0
  for (const char *TempFile : SavedTemps)
1809
0
    C.addTempFile(TempFile);
1810
1811
  // Assume associated files are based off of the first temporary file.
1812
0
  CrashReportInfo CrashInfo(TempFiles[0], VFS);
1813
1814
0
  llvm::SmallString<128> Script(CrashInfo.Filename);
1815
0
  llvm::sys::path::replace_extension(Script, "sh");
1816
0
  std::error_code EC;
1817
0
  llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew,
1818
0
                                llvm::sys::fs::FA_Write,
1819
0
                                llvm::sys::fs::OF_Text);
1820
0
  if (EC) {
1821
0
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1822
0
        << "Error generating run script: " << Script << " " << EC.message();
1823
0
  } else {
1824
0
    ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
1825
0
             << "# Driver args: ";
1826
0
    printArgList(ScriptOS, C.getInputArgs());
1827
0
    ScriptOS << "# Original command: ";
1828
0
    Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
1829
0
    Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
1830
0
    if (!AdditionalInformation.empty())
1831
0
      ScriptOS << "\n# Additional information: " << AdditionalInformation
1832
0
               << "\n";
1833
0
    if (Report)
1834
0
      Report->TemporaryFiles.push_back(std::string(Script.str()));
1835
0
    Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
1836
0
  }
1837
1838
  // On darwin, provide information about the .crash diagnostic report.
1839
0
  if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1840
0
    SmallString<128> CrashDiagDir;
1841
0
    if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1842
0
      Diag(clang::diag::note_drv_command_failed_diag_msg)
1843
0
          << ReproCrashFilename.str();
1844
0
    } else { // Suggest a directory for the user to look for .crash files.
1845
0
      llvm::sys::path::append(CrashDiagDir, Name);
1846
0
      CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1847
0
      Diag(clang::diag::note_drv_command_failed_diag_msg)
1848
0
          << "Crash backtrace is located in";
1849
0
      Diag(clang::diag::note_drv_command_failed_diag_msg)
1850
0
          << CrashDiagDir.str();
1851
0
      Diag(clang::diag::note_drv_command_failed_diag_msg)
1852
0
          << "(choose the .crash file that corresponds to your crash)";
1853
0
    }
1854
0
  }
1855
1856
0
  Diag(clang::diag::note_drv_command_failed_diag_msg)
1857
0
      << "\n\n********************";
1858
0
}
1859
1860
0
void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1861
  // Since commandLineFitsWithinSystemLimits() may underestimate system's
1862
  // capacity if the tool does not support response files, there is a chance/
1863
  // that things will just work without a response file, so we silently just
1864
  // skip it.
1865
0
  if (Cmd.getResponseFileSupport().ResponseKind ==
1866
0
          ResponseFileSupport::RF_None ||
1867
0
      llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(),
1868
0
                                                   Cmd.getArguments()))
1869
0
    return;
1870
1871
0
  std::string TmpName = GetTemporaryPath("response", "txt");
1872
0
  Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1873
0
}
1874
1875
int Driver::ExecuteCompilation(
1876
    Compilation &C,
1877
0
    SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1878
0
  if (C.getArgs().hasArg(options::OPT_fdriver_only)) {
1879
0
    if (C.getArgs().hasArg(options::OPT_v))
1880
0
      C.getJobs().Print(llvm::errs(), "\n", true);
1881
1882
0
    C.ExecuteJobs(C.getJobs(), FailingCommands, /*LogOnly=*/true);
1883
1884
    // If there were errors building the compilation, quit now.
1885
0
    if (!FailingCommands.empty() || Diags.hasErrorOccurred())
1886
0
      return 1;
1887
1888
0
    return 0;
1889
0
  }
1890
1891
  // Just print if -### was present.
1892
0
  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1893
0
    C.getJobs().Print(llvm::errs(), "\n", true);
1894
0
    return Diags.hasErrorOccurred() ? 1 : 0;
1895
0
  }
1896
1897
  // If there were errors building the compilation, quit now.
1898
0
  if (Diags.hasErrorOccurred())
1899
0
    return 1;
1900
1901
  // Set up response file names for each command, if necessary.
1902
0
  for (auto &Job : C.getJobs())
1903
0
    setUpResponseFiles(C, Job);
1904
1905
0
  C.ExecuteJobs(C.getJobs(), FailingCommands);
1906
1907
  // If the command succeeded, we are done.
1908
0
  if (FailingCommands.empty())
1909
0
    return 0;
1910
1911
  // Otherwise, remove result files and print extra information about abnormal
1912
  // failures.
1913
0
  int Res = 0;
1914
0
  for (const auto &CmdPair : FailingCommands) {
1915
0
    int CommandRes = CmdPair.first;
1916
0
    const Command *FailingCommand = CmdPair.second;
1917
1918
    // Remove result files if we're not saving temps.
1919
0
    if (!isSaveTempsEnabled()) {
1920
0
      const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1921
0
      C.CleanupFileMap(C.getResultFiles(), JA, true);
1922
1923
      // Failure result files are valid unless we crashed.
1924
0
      if (CommandRes < 0)
1925
0
        C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1926
0
    }
1927
1928
    // llvm/lib/Support/*/Signals.inc will exit with a special return code
1929
    // for SIGPIPE. Do not print diagnostics for this case.
1930
0
    if (CommandRes == EX_IOERR) {
1931
0
      Res = CommandRes;
1932
0
      continue;
1933
0
    }
1934
1935
    // Print extra information about abnormal failures, if possible.
1936
    //
1937
    // This is ad-hoc, but we don't want to be excessively noisy. If the result
1938
    // status was 1, assume the command failed normally. In particular, if it
1939
    // was the compiler then assume it gave a reasonable error code. Failures
1940
    // in other tools are less common, and they generally have worse
1941
    // diagnostics, so always print the diagnostic there.
1942
0
    const Tool &FailingTool = FailingCommand->getCreator();
1943
1944
0
    if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
1945
      // FIXME: See FIXME above regarding result code interpretation.
1946
0
      if (CommandRes < 0)
1947
0
        Diag(clang::diag::err_drv_command_signalled)
1948
0
            << FailingTool.getShortName();
1949
0
      else
1950
0
        Diag(clang::diag::err_drv_command_failed)
1951
0
            << FailingTool.getShortName() << CommandRes;
1952
0
    }
1953
0
  }
1954
0
  return Res;
1955
0
}
1956
1957
0
void Driver::PrintHelp(bool ShowHidden) const {
1958
0
  llvm::opt::Visibility VisibilityMask = getOptionVisibilityMask();
1959
1960
0
  std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1961
0
  getOpts().printHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
1962
0
                      ShowHidden, /*ShowAllAliases=*/false,
1963
0
                      VisibilityMask);
1964
0
}
1965
1966
0
void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1967
0
  if (IsFlangMode()) {
1968
0
    OS << getClangToolFullVersion("flang-new") << '\n';
1969
0
  } else {
1970
    // FIXME: The following handlers should use a callback mechanism, we don't
1971
    // know what the client would like to do.
1972
0
    OS << getClangFullVersion() << '\n';
1973
0
  }
1974
0
  const ToolChain &TC = C.getDefaultToolChain();
1975
0
  OS << "Target: " << TC.getTripleString() << '\n';
1976
1977
  // Print the threading model.
1978
0
  if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1979
    // Don't print if the ToolChain would have barfed on it already
1980
0
    if (TC.isThreadModelSupported(A->getValue()))
1981
0
      OS << "Thread model: " << A->getValue();
1982
0
  } else
1983
0
    OS << "Thread model: " << TC.getThreadModel();
1984
0
  OS << '\n';
1985
1986
  // Print out the install directory.
1987
0
  OS << "InstalledDir: " << InstalledDir << '\n';
1988
1989
  // If configuration files were used, print their paths.
1990
0
  for (auto ConfigFile : ConfigFiles)
1991
0
    OS << "Configuration file: " << ConfigFile << '\n';
1992
0
}
1993
1994
/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1995
/// option.
1996
0
static void PrintDiagnosticCategories(raw_ostream &OS) {
1997
  // Skip the empty category.
1998
0
  for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1999
0
       ++i)
2000
0
    OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
2001
0
}
2002
2003
0
void Driver::HandleAutocompletions(StringRef PassedFlags) const {
2004
0
  if (PassedFlags == "")
2005
0
    return;
2006
  // Print out all options that start with a given argument. This is used for
2007
  // shell autocompletion.
2008
0
  std::vector<std::string> SuggestedCompletions;
2009
0
  std::vector<std::string> Flags;
2010
2011
0
  llvm::opt::Visibility VisibilityMask(options::ClangOption);
2012
2013
  // Make sure that Flang-only options don't pollute the Clang output
2014
  // TODO: Make sure that Clang-only options don't pollute Flang output
2015
0
  if (IsFlangMode())
2016
0
    VisibilityMask = llvm::opt::Visibility(options::FlangOption);
2017
2018
  // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
2019
  // because the latter indicates that the user put space before pushing tab
2020
  // which should end up in a file completion.
2021
0
  const bool HasSpace = PassedFlags.ends_with(",");
2022
2023
  // Parse PassedFlags by "," as all the command-line flags are passed to this
2024
  // function separated by ","
2025
0
  StringRef TargetFlags = PassedFlags;
2026
0
  while (TargetFlags != "") {
2027
0
    StringRef CurFlag;
2028
0
    std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
2029
0
    Flags.push_back(std::string(CurFlag));
2030
0
  }
2031
2032
  // We want to show cc1-only options only when clang is invoked with -cc1 or
2033
  // -Xclang.
2034
0
  if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1"))
2035
0
    VisibilityMask = llvm::opt::Visibility(options::CC1Option);
2036
2037
0
  const llvm::opt::OptTable &Opts = getOpts();
2038
0
  StringRef Cur;
2039
0
  Cur = Flags.at(Flags.size() - 1);
2040
0
  StringRef Prev;
2041
0
  if (Flags.size() >= 2) {
2042
0
    Prev = Flags.at(Flags.size() - 2);
2043
0
    SuggestedCompletions = Opts.suggestValueCompletions(Prev, Cur);
2044
0
  }
2045
2046
0
  if (SuggestedCompletions.empty())
2047
0
    SuggestedCompletions = Opts.suggestValueCompletions(Cur, "");
2048
2049
  // If Flags were empty, it means the user typed `clang [tab]` where we should
2050
  // list all possible flags. If there was no value completion and the user
2051
  // pressed tab after a space, we should fall back to a file completion.
2052
  // We're printing a newline to be consistent with what we print at the end of
2053
  // this function.
2054
0
  if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
2055
0
    llvm::outs() << '\n';
2056
0
    return;
2057
0
  }
2058
2059
  // When flag ends with '=' and there was no value completion, return empty
2060
  // string and fall back to the file autocompletion.
2061
0
  if (SuggestedCompletions.empty() && !Cur.ends_with("=")) {
2062
    // If the flag is in the form of "--autocomplete=-foo",
2063
    // we were requested to print out all option names that start with "-foo".
2064
    // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
2065
0
    SuggestedCompletions = Opts.findByPrefix(
2066
0
        Cur, VisibilityMask,
2067
0
        /*DisableFlags=*/options::Unsupported | options::Ignored);
2068
2069
    // We have to query the -W flags manually as they're not in the OptTable.
2070
    // TODO: Find a good way to add them to OptTable instead and them remove
2071
    // this code.
2072
0
    for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
2073
0
      if (S.starts_with(Cur))
2074
0
        SuggestedCompletions.push_back(std::string(S));
2075
0
  }
2076
2077
  // Sort the autocomplete candidates so that shells print them out in a
2078
  // deterministic order. We could sort in any way, but we chose
2079
  // case-insensitive sorting for consistency with the -help option
2080
  // which prints out options in the case-insensitive alphabetical order.
2081
0
  llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
2082
0
    if (int X = A.compare_insensitive(B))
2083
0
      return X < 0;
2084
0
    return A.compare(B) > 0;
2085
0
  });
2086
2087
0
  llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
2088
0
}
2089
2090
0
bool Driver::HandleImmediateArgs(const Compilation &C) {
2091
  // The order these options are handled in gcc is all over the place, but we
2092
  // don't expect inconsistencies w.r.t. that to matter in practice.
2093
2094
0
  if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
2095
0
    llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
2096
0
    return false;
2097
0
  }
2098
2099
0
  if (C.getArgs().hasArg(options::OPT_dumpversion)) {
2100
    // Since -dumpversion is only implemented for pedantic GCC compatibility, we
2101
    // return an answer which matches our definition of __VERSION__.
2102
0
    llvm::outs() << CLANG_VERSION_STRING << "\n";
2103
0
    return false;
2104
0
  }
2105
2106
0
  if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
2107
0
    PrintDiagnosticCategories(llvm::outs());
2108
0
    return false;
2109
0
  }
2110
2111
0
  if (C.getArgs().hasArg(options::OPT_help) ||
2112
0
      C.getArgs().hasArg(options::OPT__help_hidden)) {
2113
0
    PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
2114
0
    return false;
2115
0
  }
2116
2117
0
  if (C.getArgs().hasArg(options::OPT__version)) {
2118
    // Follow gcc behavior and use stdout for --version and stderr for -v.
2119
0
    PrintVersion(C, llvm::outs());
2120
0
    return false;
2121
0
  }
2122
2123
0
  if (C.getArgs().hasArg(options::OPT_v) ||
2124
0
      C.getArgs().hasArg(options::OPT__HASH_HASH_HASH) ||
2125
0
      C.getArgs().hasArg(options::OPT_print_supported_cpus) ||
2126
0
      C.getArgs().hasArg(options::OPT_print_supported_extensions)) {
2127
0
    PrintVersion(C, llvm::errs());
2128
0
    SuppressMissingInputWarning = true;
2129
0
  }
2130
2131
0
  if (C.getArgs().hasArg(options::OPT_v)) {
2132
0
    if (!SystemConfigDir.empty())
2133
0
      llvm::errs() << "System configuration file directory: "
2134
0
                   << SystemConfigDir << "\n";
2135
0
    if (!UserConfigDir.empty())
2136
0
      llvm::errs() << "User configuration file directory: "
2137
0
                   << UserConfigDir << "\n";
2138
0
  }
2139
2140
0
  const ToolChain &TC = C.getDefaultToolChain();
2141
2142
0
  if (C.getArgs().hasArg(options::OPT_v))
2143
0
    TC.printVerboseInfo(llvm::errs());
2144
2145
0
  if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
2146
0
    llvm::outs() << ResourceDir << '\n';
2147
0
    return false;
2148
0
  }
2149
2150
0
  if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
2151
0
    llvm::outs() << "programs: =";
2152
0
    bool separator = false;
2153
    // Print -B and COMPILER_PATH.
2154
0
    for (const std::string &Path : PrefixDirs) {
2155
0
      if (separator)
2156
0
        llvm::outs() << llvm::sys::EnvPathSeparator;
2157
0
      llvm::outs() << Path;
2158
0
      separator = true;
2159
0
    }
2160
0
    for (const std::string &Path : TC.getProgramPaths()) {
2161
0
      if (separator)
2162
0
        llvm::outs() << llvm::sys::EnvPathSeparator;
2163
0
      llvm::outs() << Path;
2164
0
      separator = true;
2165
0
    }
2166
0
    llvm::outs() << "\n";
2167
0
    llvm::outs() << "libraries: =" << ResourceDir;
2168
2169
0
    StringRef sysroot = C.getSysRoot();
2170
2171
0
    for (const std::string &Path : TC.getFilePaths()) {
2172
      // Always print a separator. ResourceDir was the first item shown.
2173
0
      llvm::outs() << llvm::sys::EnvPathSeparator;
2174
      // Interpretation of leading '=' is needed only for NetBSD.
2175
0
      if (Path[0] == '=')
2176
0
        llvm::outs() << sysroot << Path.substr(1);
2177
0
      else
2178
0
        llvm::outs() << Path;
2179
0
    }
2180
0
    llvm::outs() << "\n";
2181
0
    return false;
2182
0
  }
2183
2184
0
  if (C.getArgs().hasArg(options::OPT_print_runtime_dir)) {
2185
0
    if (std::optional<std::string> RuntimePath = TC.getRuntimePath())
2186
0
      llvm::outs() << *RuntimePath << '\n';
2187
0
    else
2188
0
      llvm::outs() << TC.getCompilerRTPath() << '\n';
2189
0
    return false;
2190
0
  }
2191
2192
0
  if (C.getArgs().hasArg(options::OPT_print_diagnostic_options)) {
2193
0
    std::vector<std::string> Flags = DiagnosticIDs::getDiagnosticFlags();
2194
0
    for (std::size_t I = 0; I != Flags.size(); I += 2)
2195
0
      llvm::outs() << "  " << Flags[I] << "\n  " << Flags[I + 1] << "\n\n";
2196
0
    return false;
2197
0
  }
2198
2199
  // FIXME: The following handlers should use a callback mechanism, we don't
2200
  // know what the client would like to do.
2201
0
  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
2202
0
    llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
2203
0
    return false;
2204
0
  }
2205
2206
0
  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
2207
0
    StringRef ProgName = A->getValue();
2208
2209
    // Null program name cannot have a path.
2210
0
    if (! ProgName.empty())
2211
0
      llvm::outs() << GetProgramPath(ProgName, TC);
2212
2213
0
    llvm::outs() << "\n";
2214
0
    return false;
2215
0
  }
2216
2217
0
  if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
2218
0
    StringRef PassedFlags = A->getValue();
2219
0
    HandleAutocompletions(PassedFlags);
2220
0
    return false;
2221
0
  }
2222
2223
0
  if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
2224
0
    ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
2225
0
    const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
2226
0
    RegisterEffectiveTriple TripleRAII(TC, Triple);
2227
0
    switch (RLT) {
2228
0
    case ToolChain::RLT_CompilerRT:
2229
0
      llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
2230
0
      break;
2231
0
    case ToolChain::RLT_Libgcc:
2232
0
      llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
2233
0
      break;
2234
0
    }
2235
0
    return false;
2236
0
  }
2237
2238
0
  if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
2239
0
    for (const Multilib &Multilib : TC.getMultilibs())
2240
0
      llvm::outs() << Multilib << "\n";
2241
0
    return false;
2242
0
  }
2243
2244
0
  if (C.getArgs().hasArg(options::OPT_print_multi_flags)) {
2245
0
    Multilib::flags_list ArgFlags = TC.getMultilibFlags(C.getArgs());
2246
0
    llvm::StringSet<> ExpandedFlags = TC.getMultilibs().expandFlags(ArgFlags);
2247
0
    std::set<llvm::StringRef> SortedFlags;
2248
0
    for (const auto &FlagEntry : ExpandedFlags)
2249
0
      SortedFlags.insert(FlagEntry.getKey());
2250
0
    for (auto Flag : SortedFlags)
2251
0
      llvm::outs() << Flag << '\n';
2252
0
    return false;
2253
0
  }
2254
2255
0
  if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
2256
0
    for (const Multilib &Multilib : TC.getSelectedMultilibs()) {
2257
0
      if (Multilib.gccSuffix().empty())
2258
0
        llvm::outs() << ".\n";
2259
0
      else {
2260
0
        StringRef Suffix(Multilib.gccSuffix());
2261
0
        assert(Suffix.front() == '/');
2262
0
        llvm::outs() << Suffix.substr(1) << "\n";
2263
0
      }
2264
0
    }
2265
0
    return false;
2266
0
  }
2267
2268
0
  if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
2269
0
    llvm::outs() << TC.getTripleString() << "\n";
2270
0
    return false;
2271
0
  }
2272
2273
0
  if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
2274
0
    const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
2275
0
    llvm::outs() << Triple.getTriple() << "\n";
2276
0
    return false;
2277
0
  }
2278
2279
0
  if (C.getArgs().hasArg(options::OPT_print_targets)) {
2280
0
    llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
2281
0
    return false;
2282
0
  }
2283
2284
0
  return true;
2285
0
}
2286
2287
enum {
2288
  TopLevelAction = 0,
2289
  HeadSibAction = 1,
2290
  OtherSibAction = 2,
2291
};
2292
2293
// Display an action graph human-readably.  Action A is the "sink" node
2294
// and latest-occuring action. Traversal is in pre-order, visiting the
2295
// inputs to each action before printing the action itself.
2296
static unsigned PrintActions1(const Compilation &C, Action *A,
2297
                              std::map<Action *, unsigned> &Ids,
2298
0
                              Twine Indent = {}, int Kind = TopLevelAction) {
2299
0
  if (Ids.count(A)) // A was already visited.
2300
0
    return Ids[A];
2301
2302
0
  std::string str;
2303
0
  llvm::raw_string_ostream os(str);
2304
2305
0
  auto getSibIndent = [](int K) -> Twine {
2306
0
    return (K == HeadSibAction) ? "   " : (K == OtherSibAction) ? "|  " : "";
2307
0
  };
2308
2309
0
  Twine SibIndent = Indent + getSibIndent(Kind);
2310
0
  int SibKind = HeadSibAction;
2311
0
  os << Action::getClassName(A->getKind()) << ", ";
2312
0
  if (InputAction *IA = dyn_cast<InputAction>(A)) {
2313
0
    os << "\"" << IA->getInputArg().getValue() << "\"";
2314
0
  } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
2315
0
    os << '"' << BIA->getArchName() << '"' << ", {"
2316
0
       << PrintActions1(C, *BIA->input_begin(), Ids, SibIndent, SibKind) << "}";
2317
0
  } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
2318
0
    bool IsFirst = true;
2319
0
    OA->doOnEachDependence(
2320
0
        [&](Action *A, const ToolChain *TC, const char *BoundArch) {
2321
0
          assert(TC && "Unknown host toolchain");
2322
          // E.g. for two CUDA device dependences whose bound arch is sm_20 and
2323
          // sm_35 this will generate:
2324
          // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
2325
          // (nvptx64-nvidia-cuda:sm_35) {#ID}
2326
0
          if (!IsFirst)
2327
0
            os << ", ";
2328
0
          os << '"';
2329
0
          os << A->getOffloadingKindPrefix();
2330
0
          os << " (";
2331
0
          os << TC->getTriple().normalize();
2332
0
          if (BoundArch)
2333
0
            os << ":" << BoundArch;
2334
0
          os << ")";
2335
0
          os << '"';
2336
0
          os << " {" << PrintActions1(C, A, Ids, SibIndent, SibKind) << "}";
2337
0
          IsFirst = false;
2338
0
          SibKind = OtherSibAction;
2339
0
        });
2340
0
  } else {
2341
0
    const ActionList *AL = &A->getInputs();
2342
2343
0
    if (AL->size()) {
2344
0
      const char *Prefix = "{";
2345
0
      for (Action *PreRequisite : *AL) {
2346
0
        os << Prefix << PrintActions1(C, PreRequisite, Ids, SibIndent, SibKind);
2347
0
        Prefix = ", ";
2348
0
        SibKind = OtherSibAction;
2349
0
      }
2350
0
      os << "}";
2351
0
    } else
2352
0
      os << "{}";
2353
0
  }
2354
2355
  // Append offload info for all options other than the offloading action
2356
  // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
2357
0
  std::string offload_str;
2358
0
  llvm::raw_string_ostream offload_os(offload_str);
2359
0
  if (!isa<OffloadAction>(A)) {
2360
0
    auto S = A->getOffloadingKindPrefix();
2361
0
    if (!S.empty()) {
2362
0
      offload_os << ", (" << S;
2363
0
      if (A->getOffloadingArch())
2364
0
        offload_os << ", " << A->getOffloadingArch();
2365
0
      offload_os << ")";
2366
0
    }
2367
0
  }
2368
2369
0
  auto getSelfIndent = [](int K) -> Twine {
2370
0
    return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : "";
2371
0
  };
2372
2373
0
  unsigned Id = Ids.size();
2374
0
  Ids[A] = Id;
2375
0
  llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", "
2376
0
               << types::getTypeName(A->getType()) << offload_os.str() << "\n";
2377
2378
0
  return Id;
2379
0
}
2380
2381
// Print the action graphs in a compilation C.
2382
// For example "clang -c file1.c file2.c" is composed of two subgraphs.
2383
0
void Driver::PrintActions(const Compilation &C) const {
2384
0
  std::map<Action *, unsigned> Ids;
2385
0
  for (Action *A : C.getActions())
2386
0
    PrintActions1(C, A, Ids);
2387
0
}
2388
2389
/// Check whether the given input tree contains any compilation or
2390
/// assembly actions.
2391
0
static bool ContainsCompileOrAssembleAction(const Action *A) {
2392
0
  if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
2393
0
      isa<AssembleJobAction>(A))
2394
0
    return true;
2395
2396
0
  return llvm::any_of(A->inputs(), ContainsCompileOrAssembleAction);
2397
0
}
2398
2399
void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
2400
0
                                   const InputList &BAInputs) const {
2401
0
  DerivedArgList &Args = C.getArgs();
2402
0
  ActionList &Actions = C.getActions();
2403
0
  llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
2404
  // Collect the list of architectures. Duplicates are allowed, but should only
2405
  // be handled once (in the order seen).
2406
0
  llvm::StringSet<> ArchNames;
2407
0
  SmallVector<const char *, 4> Archs;
2408
0
  for (Arg *A : Args) {
2409
0
    if (A->getOption().matches(options::OPT_arch)) {
2410
      // Validate the option here; we don't save the type here because its
2411
      // particular spelling may participate in other driver choices.
2412
0
      llvm::Triple::ArchType Arch =
2413
0
          tools::darwin::getArchTypeForMachOArchName(A->getValue());
2414
0
      if (Arch == llvm::Triple::UnknownArch) {
2415
0
        Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
2416
0
        continue;
2417
0
      }
2418
2419
0
      A->claim();
2420
0
      if (ArchNames.insert(A->getValue()).second)
2421
0
        Archs.push_back(A->getValue());
2422
0
    }
2423
0
  }
2424
2425
  // When there is no explicit arch for this platform, make sure we still bind
2426
  // the architecture (to the default) so that -Xarch_ is handled correctly.
2427
0
  if (!Archs.size())
2428
0
    Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
2429
2430
0
  ActionList SingleActions;
2431
0
  BuildActions(C, Args, BAInputs, SingleActions);
2432
2433
  // Add in arch bindings for every top level action, as well as lipo and
2434
  // dsymutil steps if needed.
2435
0
  for (Action* Act : SingleActions) {
2436
    // Make sure we can lipo this kind of output. If not (and it is an actual
2437
    // output) then we disallow, since we can't create an output file with the
2438
    // right name without overwriting it. We could remove this oddity by just
2439
    // changing the output names to include the arch, which would also fix
2440
    // -save-temps. Compatibility wins for now.
2441
2442
0
    if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
2443
0
      Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
2444
0
          << types::getTypeName(Act->getType());
2445
2446
0
    ActionList Inputs;
2447
0
    for (unsigned i = 0, e = Archs.size(); i != e; ++i)
2448
0
      Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
2449
2450
    // Lipo if necessary, we do it this way because we need to set the arch flag
2451
    // so that -Xarch_ gets overwritten.
2452
0
    if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
2453
0
      Actions.append(Inputs.begin(), Inputs.end());
2454
0
    else
2455
0
      Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
2456
2457
    // Handle debug info queries.
2458
0
    Arg *A = Args.getLastArg(options::OPT_g_Group);
2459
0
    bool enablesDebugInfo = A && !A->getOption().matches(options::OPT_g0) &&
2460
0
                            !A->getOption().matches(options::OPT_gstabs);
2461
0
    if ((enablesDebugInfo || willEmitRemarks(Args)) &&
2462
0
        ContainsCompileOrAssembleAction(Actions.back())) {
2463
2464
      // Add a 'dsymutil' step if necessary, when debug info is enabled and we
2465
      // have a compile input. We need to run 'dsymutil' ourselves in such cases
2466
      // because the debug info will refer to a temporary object file which
2467
      // will be removed at the end of the compilation process.
2468
0
      if (Act->getType() == types::TY_Image) {
2469
0
        ActionList Inputs;
2470
0
        Inputs.push_back(Actions.back());
2471
0
        Actions.pop_back();
2472
0
        Actions.push_back(
2473
0
            C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
2474
0
      }
2475
2476
      // Verify the debug info output.
2477
0
      if (Args.hasArg(options::OPT_verify_debug_info)) {
2478
0
        Action* LastAction = Actions.back();
2479
0
        Actions.pop_back();
2480
0
        Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
2481
0
            LastAction, types::TY_Nothing));
2482
0
      }
2483
0
    }
2484
0
  }
2485
0
}
2486
2487
bool Driver::DiagnoseInputExistence(const DerivedArgList &Args, StringRef Value,
2488
0
                                    types::ID Ty, bool TypoCorrect) const {
2489
0
  if (!getCheckInputsExist())
2490
0
    return true;
2491
2492
  // stdin always exists.
2493
0
  if (Value == "-")
2494
0
    return true;
2495
2496
  // If it's a header to be found in the system or user search path, then defer
2497
  // complaints about its absence until those searches can be done.  When we
2498
  // are definitely processing headers for C++20 header units, extend this to
2499
  // allow the user to put "-fmodule-header -xc++-header vector" for example.
2500
0
  if (Ty == types::TY_CXXSHeader || Ty == types::TY_CXXUHeader ||
2501
0
      (ModulesModeCXX20 && Ty == types::TY_CXXHeader))
2502
0
    return true;
2503
2504
0
  if (getVFS().exists(Value))
2505
0
    return true;
2506
2507
0
  if (TypoCorrect) {
2508
    // Check if the filename is a typo for an option flag. OptTable thinks
2509
    // that all args that are not known options and that start with / are
2510
    // filenames, but e.g. `/diagnostic:caret` is more likely a typo for
2511
    // the option `/diagnostics:caret` than a reference to a file in the root
2512
    // directory.
2513
0
    std::string Nearest;
2514
0
    if (getOpts().findNearest(Value, Nearest, getOptionVisibilityMask()) <= 1) {
2515
0
      Diag(clang::diag::err_drv_no_such_file_with_suggestion)
2516
0
          << Value << Nearest;
2517
0
      return false;
2518
0
    }
2519
0
  }
2520
2521
  // In CL mode, don't error on apparently non-existent linker inputs, because
2522
  // they can be influenced by linker flags the clang driver might not
2523
  // understand.
2524
  // Examples:
2525
  // - `clang-cl main.cc ole32.lib` in a non-MSVC shell will make the driver
2526
  //   module look for an MSVC installation in the registry. (We could ask
2527
  //   the MSVCToolChain object if it can find `ole32.lib`, but the logic to
2528
  //   look in the registry might move into lld-link in the future so that
2529
  //   lld-link invocations in non-MSVC shells just work too.)
2530
  // - `clang-cl ... /link ...` can pass arbitrary flags to the linker,
2531
  //   including /libpath:, which is used to find .lib and .obj files.
2532
  // So do not diagnose this on the driver level. Rely on the linker diagnosing
2533
  // it. (If we don't end up invoking the linker, this means we'll emit a
2534
  // "'linker' input unused [-Wunused-command-line-argument]" warning instead
2535
  // of an error.)
2536
  //
2537
  // Only do this skip after the typo correction step above. `/Brepo` is treated
2538
  // as TY_Object, but it's clearly a typo for `/Brepro`. It seems fine to emit
2539
  // an error if we have a flag that's within an edit distance of 1 from a
2540
  // flag. (Users can use `-Wl,` or `/linker` to launder the flag past the
2541
  // driver in the unlikely case they run into this.)
2542
  //
2543
  // Don't do this for inputs that start with a '/', else we'd pass options
2544
  // like /libpath: through to the linker silently.
2545
  //
2546
  // Emitting an error for linker inputs can also cause incorrect diagnostics
2547
  // with the gcc driver. The command
2548
  //     clang -fuse-ld=lld -Wl,--chroot,some/dir /file.o
2549
  // will make lld look for some/dir/file.o, while we will diagnose here that
2550
  // `/file.o` does not exist. However, configure scripts check if
2551
  // `clang /GR-` compiles without error to see if the compiler is cl.exe,
2552
  // so we can't downgrade diagnostics for `/GR-` from an error to a warning
2553
  // in cc mode. (We can in cl mode because cl.exe itself only warns on
2554
  // unknown flags.)
2555
0
  if (IsCLMode() && Ty == types::TY_Object && !Value.starts_with("/"))
2556
0
    return true;
2557
2558
0
  Diag(clang::diag::err_drv_no_such_file) << Value;
2559
0
  return false;
2560
0
}
2561
2562
// Get the C++20 Header Unit type corresponding to the input type.
2563
0
static types::ID CXXHeaderUnitType(ModuleHeaderMode HM) {
2564
0
  switch (HM) {
2565
0
  case HeaderMode_User:
2566
0
    return types::TY_CXXUHeader;
2567
0
  case HeaderMode_System:
2568
0
    return types::TY_CXXSHeader;
2569
0
  case HeaderMode_Default:
2570
0
    break;
2571
0
  case HeaderMode_None:
2572
0
    llvm_unreachable("should not be called in this case");
2573
0
  }
2574
0
  return types::TY_CXXHUHeader;
2575
0
}
2576
2577
// Construct a the list of inputs and their types.
2578
void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
2579
0
                         InputList &Inputs) const {
2580
0
  const llvm::opt::OptTable &Opts = getOpts();
2581
  // Track the current user specified (-x) input. We also explicitly track the
2582
  // argument used to set the type; we only want to claim the type when we
2583
  // actually use it, so we warn about unused -x arguments.
2584
0
  types::ID InputType = types::TY_Nothing;
2585
0
  Arg *InputTypeArg = nullptr;
2586
2587
  // The last /TC or /TP option sets the input type to C or C++ globally.
2588
0
  if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
2589
0
                                         options::OPT__SLASH_TP)) {
2590
0
    InputTypeArg = TCTP;
2591
0
    InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
2592
0
                    ? types::TY_C
2593
0
                    : types::TY_CXX;
2594
2595
0
    Arg *Previous = nullptr;
2596
0
    bool ShowNote = false;
2597
0
    for (Arg *A :
2598
0
         Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
2599
0
      if (Previous) {
2600
0
        Diag(clang::diag::warn_drv_overriding_option)
2601
0
            << Previous->getSpelling() << A->getSpelling();
2602
0
        ShowNote = true;
2603
0
      }
2604
0
      Previous = A;
2605
0
    }
2606
0
    if (ShowNote)
2607
0
      Diag(clang::diag::note_drv_t_option_is_global);
2608
0
  }
2609
2610
  // CUDA/HIP and their preprocessor expansions can be accepted by CL mode.
2611
  // Warn -x after last input file has no effect
2612
0
  auto LastXArg = Args.getLastArgValue(options::OPT_x);
2613
0
  const llvm::StringSet<> ValidXArgs = {"cuda", "hip", "cui", "hipi"};
2614
0
  if (!IsCLMode() || ValidXArgs.contains(LastXArg)) {
2615
0
    Arg *LastXArg = Args.getLastArgNoClaim(options::OPT_x);
2616
0
    Arg *LastInputArg = Args.getLastArgNoClaim(options::OPT_INPUT);
2617
0
    if (LastXArg && LastInputArg &&
2618
0
        LastInputArg->getIndex() < LastXArg->getIndex())
2619
0
      Diag(clang::diag::warn_drv_unused_x) << LastXArg->getValue();
2620
0
  } else {
2621
    // In CL mode suggest /TC or /TP since -x doesn't make sense if passed via
2622
    // /clang:.
2623
0
    if (auto *A = Args.getLastArg(options::OPT_x))
2624
0
      Diag(diag::err_drv_unsupported_opt_with_suggestion)
2625
0
          << A->getAsString(Args) << "/TC' or '/TP";
2626
0
  }
2627
2628
0
  for (Arg *A : Args) {
2629
0
    if (A->getOption().getKind() == Option::InputClass) {
2630
0
      const char *Value = A->getValue();
2631
0
      types::ID Ty = types::TY_INVALID;
2632
2633
      // Infer the input type if necessary.
2634
0
      if (InputType == types::TY_Nothing) {
2635
        // If there was an explicit arg for this, claim it.
2636
0
        if (InputTypeArg)
2637
0
          InputTypeArg->claim();
2638
2639
        // stdin must be handled specially.
2640
0
        if (memcmp(Value, "-", 2) == 0) {
2641
0
          if (IsFlangMode()) {
2642
0
            Ty = types::TY_Fortran;
2643
0
          } else if (IsDXCMode()) {
2644
0
            Ty = types::TY_HLSL;
2645
0
          } else {
2646
            // If running with -E, treat as a C input (this changes the
2647
            // builtin macros, for example). This may be overridden by -ObjC
2648
            // below.
2649
            //
2650
            // Otherwise emit an error but still use a valid type to avoid
2651
            // spurious errors (e.g., no inputs).
2652
0
            assert(!CCGenDiagnostics && "stdin produces no crash reproducer");
2653
0
            if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
2654
0
              Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2655
0
                              : clang::diag::err_drv_unknown_stdin_type);
2656
0
            Ty = types::TY_C;
2657
0
          }
2658
0
        } else {
2659
          // Otherwise lookup by extension.
2660
          // Fallback is C if invoked as C preprocessor, C++ if invoked with
2661
          // clang-cl /E, or Object otherwise.
2662
          // We use a host hook here because Darwin at least has its own
2663
          // idea of what .s is.
2664
0
          if (const char *Ext = strrchr(Value, '.'))
2665
0
            Ty = TC.LookupTypeForExtension(Ext + 1);
2666
2667
0
          if (Ty == types::TY_INVALID) {
2668
0
            if (IsCLMode() && (Args.hasArgNoClaim(options::OPT_E) || CCGenDiagnostics))
2669
0
              Ty = types::TY_CXX;
2670
0
            else if (CCCIsCPP() || CCGenDiagnostics)
2671
0
              Ty = types::TY_C;
2672
0
            else
2673
0
              Ty = types::TY_Object;
2674
0
          }
2675
2676
          // If the driver is invoked as C++ compiler (like clang++ or c++) it
2677
          // should autodetect some input files as C++ for g++ compatibility.
2678
0
          if (CCCIsCXX()) {
2679
0
            types::ID OldTy = Ty;
2680
0
            Ty = types::lookupCXXTypeForCType(Ty);
2681
2682
            // Do not complain about foo.h, when we are known to be processing
2683
            // it as a C++20 header unit.
2684
0
            if (Ty != OldTy && !(OldTy == types::TY_CHeader && hasHeaderMode()))
2685
0
              Diag(clang::diag::warn_drv_treating_input_as_cxx)
2686
0
                  << getTypeName(OldTy) << getTypeName(Ty);
2687
0
          }
2688
2689
          // If running with -fthinlto-index=, extensions that normally identify
2690
          // native object files actually identify LLVM bitcode files.
2691
0
          if (Args.hasArgNoClaim(options::OPT_fthinlto_index_EQ) &&
2692
0
              Ty == types::TY_Object)
2693
0
            Ty = types::TY_LLVM_BC;
2694
0
        }
2695
2696
        // -ObjC and -ObjC++ override the default language, but only for "source
2697
        // files". We just treat everything that isn't a linker input as a
2698
        // source file.
2699
        //
2700
        // FIXME: Clean this up if we move the phase sequence into the type.
2701
0
        if (Ty != types::TY_Object) {
2702
0
          if (Args.hasArg(options::OPT_ObjC))
2703
0
            Ty = types::TY_ObjC;
2704
0
          else if (Args.hasArg(options::OPT_ObjCXX))
2705
0
            Ty = types::TY_ObjCXX;
2706
0
        }
2707
2708
        // Disambiguate headers that are meant to be header units from those
2709
        // intended to be PCH.  Avoid missing '.h' cases that are counted as
2710
        // C headers by default - we know we are in C++ mode and we do not
2711
        // want to issue a complaint about compiling things in the wrong mode.
2712
0
        if ((Ty == types::TY_CXXHeader || Ty == types::TY_CHeader) &&
2713
0
            hasHeaderMode())
2714
0
          Ty = CXXHeaderUnitType(CXX20HeaderType);
2715
0
      } else {
2716
0
        assert(InputTypeArg && "InputType set w/o InputTypeArg");
2717
0
        if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2718
          // If emulating cl.exe, make sure that /TC and /TP don't affect input
2719
          // object files.
2720
0
          const char *Ext = strrchr(Value, '.');
2721
0
          if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2722
0
            Ty = types::TY_Object;
2723
0
        }
2724
0
        if (Ty == types::TY_INVALID) {
2725
0
          Ty = InputType;
2726
0
          InputTypeArg->claim();
2727
0
        }
2728
0
      }
2729
2730
0
      if ((Ty == types::TY_C || Ty == types::TY_CXX) &&
2731
0
          Args.hasArgNoClaim(options::OPT_hipstdpar))
2732
0
        Ty = types::TY_HIP;
2733
2734
0
      if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true))
2735
0
        Inputs.push_back(std::make_pair(Ty, A));
2736
2737
0
    } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2738
0
      StringRef Value = A->getValue();
2739
0
      if (DiagnoseInputExistence(Args, Value, types::TY_C,
2740
0
                                 /*TypoCorrect=*/false)) {
2741
0
        Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2742
0
        Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2743
0
      }
2744
0
      A->claim();
2745
0
    } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2746
0
      StringRef Value = A->getValue();
2747
0
      if (DiagnoseInputExistence(Args, Value, types::TY_CXX,
2748
0
                                 /*TypoCorrect=*/false)) {
2749
0
        Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2750
0
        Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2751
0
      }
2752
0
      A->claim();
2753
0
    } else if (A->getOption().hasFlag(options::LinkerInput)) {
2754
      // Just treat as object type, we could make a special type for this if
2755
      // necessary.
2756
0
      Inputs.push_back(std::make_pair(types::TY_Object, A));
2757
2758
0
    } else if (A->getOption().matches(options::OPT_x)) {
2759
0
      InputTypeArg = A;
2760
0
      InputType = types::lookupTypeForTypeSpecifier(A->getValue());
2761
0
      A->claim();
2762
2763
      // Follow gcc behavior and treat as linker input for invalid -x
2764
      // options. Its not clear why we shouldn't just revert to unknown; but
2765
      // this isn't very important, we might as well be bug compatible.
2766
0
      if (!InputType) {
2767
0
        Diag(clang::diag::err_drv_unknown_language) << A->getValue();
2768
0
        InputType = types::TY_Object;
2769
0
      }
2770
2771
      // If the user has put -fmodule-header{,=} then we treat C++ headers as
2772
      // header unit inputs.  So we 'promote' -xc++-header appropriately.
2773
0
      if (InputType == types::TY_CXXHeader && hasHeaderMode())
2774
0
        InputType = CXXHeaderUnitType(CXX20HeaderType);
2775
0
    } else if (A->getOption().getID() == options::OPT_U) {
2776
0
      assert(A->getNumValues() == 1 && "The /U option has one value.");
2777
0
      StringRef Val = A->getValue(0);
2778
0
      if (Val.find_first_of("/\\") != StringRef::npos) {
2779
        // Warn about e.g. "/Users/me/myfile.c".
2780
0
        Diag(diag::warn_slash_u_filename) << Val;
2781
0
        Diag(diag::note_use_dashdash);
2782
0
      }
2783
0
    }
2784
0
  }
2785
0
  if (CCCIsCPP() && Inputs.empty()) {
2786
    // If called as standalone preprocessor, stdin is processed
2787
    // if no other input is present.
2788
0
    Arg *A = MakeInputArg(Args, Opts, "-");
2789
0
    Inputs.push_back(std::make_pair(types::TY_C, A));
2790
0
  }
2791
0
}
2792
2793
namespace {
2794
/// Provides a convenient interface for different programming models to generate
2795
/// the required device actions.
2796
class OffloadingActionBuilder final {
2797
  /// Flag used to trace errors in the builder.
2798
  bool IsValid = false;
2799
2800
  /// The compilation that is using this builder.
2801
  Compilation &C;
2802
2803
  /// Map between an input argument and the offload kinds used to process it.
2804
  std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2805
2806
  /// Map between a host action and its originating input argument.
2807
  std::map<Action *, const Arg *> HostActionToInputArgMap;
2808
2809
  /// Builder interface. It doesn't build anything or keep any state.
2810
  class DeviceActionBuilder {
2811
  public:
2812
    typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy;
2813
2814
    enum ActionBuilderReturnCode {
2815
      // The builder acted successfully on the current action.
2816
      ABRT_Success,
2817
      // The builder didn't have to act on the current action.
2818
      ABRT_Inactive,
2819
      // The builder was successful and requested the host action to not be
2820
      // generated.
2821
      ABRT_Ignore_Host,
2822
    };
2823
2824
  protected:
2825
    /// Compilation associated with this builder.
2826
    Compilation &C;
2827
2828
    /// Tool chains associated with this builder. The same programming
2829
    /// model may have associated one or more tool chains.
2830
    SmallVector<const ToolChain *, 2> ToolChains;
2831
2832
    /// The derived arguments associated with this builder.
2833
    DerivedArgList &Args;
2834
2835
    /// The inputs associated with this builder.
2836
    const Driver::InputList &Inputs;
2837
2838
    /// The associated offload kind.
2839
    Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2840
2841
  public:
2842
    DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2843
                        const Driver::InputList &Inputs,
2844
                        Action::OffloadKind AssociatedOffloadKind)
2845
        : C(C), Args(Args), Inputs(Inputs),
2846
0
          AssociatedOffloadKind(AssociatedOffloadKind) {}
2847
0
    virtual ~DeviceActionBuilder() {}
2848
2849
    /// Fill up the array \a DA with all the device dependences that should be
2850
    /// added to the provided host action \a HostAction. By default it is
2851
    /// inactive.
2852
    virtual ActionBuilderReturnCode
2853
    getDeviceDependences(OffloadAction::DeviceDependences &DA,
2854
                         phases::ID CurPhase, phases::ID FinalPhase,
2855
0
                         PhasesTy &Phases) {
2856
0
      return ABRT_Inactive;
2857
0
    }
2858
2859
    /// Update the state to include the provided host action \a HostAction as a
2860
    /// dependency of the current device action. By default it is inactive.
2861
0
    virtual ActionBuilderReturnCode addDeviceDependences(Action *HostAction) {
2862
0
      return ABRT_Inactive;
2863
0
    }
2864
2865
    /// Append top level actions generated by the builder.
2866
0
    virtual void appendTopLevelActions(ActionList &AL) {}
2867
2868
    /// Append linker device actions generated by the builder.
2869
0
    virtual void appendLinkDeviceActions(ActionList &AL) {}
2870
2871
    /// Append linker host action generated by the builder.
2872
0
    virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; }
2873
2874
    /// Append linker actions generated by the builder.
2875
0
    virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2876
2877
    /// Initialize the builder. Return true if any initialization errors are
2878
    /// found.
2879
0
    virtual bool initialize() { return false; }
2880
2881
    /// Return true if the builder can use bundling/unbundling.
2882
0
    virtual bool canUseBundlerUnbundler() const { return false; }
2883
2884
    /// Return true if this builder is valid. We have a valid builder if we have
2885
    /// associated device tool chains.
2886
0
    bool isValid() { return !ToolChains.empty(); }
2887
2888
    /// Return the associated offload kind.
2889
0
    Action::OffloadKind getAssociatedOffloadKind() {
2890
0
      return AssociatedOffloadKind;
2891
0
    }
2892
  };
2893
2894
  /// Base class for CUDA/HIP action builder. It injects device code in
2895
  /// the host backend action.
2896
  class CudaActionBuilderBase : public DeviceActionBuilder {
2897
  protected:
2898
    /// Flags to signal if the user requested host-only or device-only
2899
    /// compilation.
2900
    bool CompileHostOnly = false;
2901
    bool CompileDeviceOnly = false;
2902
    bool EmitLLVM = false;
2903
    bool EmitAsm = false;
2904
2905
    /// ID to identify each device compilation. For CUDA it is simply the
2906
    /// GPU arch string. For HIP it is either the GPU arch string or GPU
2907
    /// arch string plus feature strings delimited by a plus sign, e.g.
2908
    /// gfx906+xnack.
2909
    struct TargetID {
2910
      /// Target ID string which is persistent throughout the compilation.
2911
      const char *ID;
2912
0
      TargetID(CudaArch Arch) { ID = CudaArchToString(Arch); }
2913
0
      TargetID(const char *ID) : ID(ID) {}
2914
0
      operator const char *() { return ID; }
2915
0
      operator StringRef() { return StringRef(ID); }
2916
    };
2917
    /// List of GPU architectures to use in this compilation.
2918
    SmallVector<TargetID, 4> GpuArchList;
2919
2920
    /// The CUDA actions for the current input.
2921
    ActionList CudaDeviceActions;
2922
2923
    /// The CUDA fat binary if it was generated for the current input.
2924
    Action *CudaFatBinary = nullptr;
2925
2926
    /// Flag that is set to true if this builder acted on the current input.
2927
    bool IsActive = false;
2928
2929
    /// Flag for -fgpu-rdc.
2930
    bool Relocatable = false;
2931
2932
    /// Default GPU architecture if there's no one specified.
2933
    CudaArch DefaultCudaArch = CudaArch::UNKNOWN;
2934
2935
    /// Method to generate compilation unit ID specified by option
2936
    /// '-fuse-cuid='.
2937
    enum UseCUIDKind { CUID_Hash, CUID_Random, CUID_None, CUID_Invalid };
2938
    UseCUIDKind UseCUID = CUID_Hash;
2939
2940
    /// Compilation unit ID specified by option '-cuid='.
2941
    StringRef FixedCUID;
2942
2943
  public:
2944
    CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2945
                          const Driver::InputList &Inputs,
2946
                          Action::OffloadKind OFKind)
2947
0
        : DeviceActionBuilder(C, Args, Inputs, OFKind) {
2948
2949
0
      CompileDeviceOnly = C.getDriver().offloadDeviceOnly();
2950
0
      Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2951
0
                                 options::OPT_fno_gpu_rdc, /*Default=*/false);
2952
0
    }
2953
2954
0
    ActionBuilderReturnCode addDeviceDependences(Action *HostAction) override {
2955
      // While generating code for CUDA, we only depend on the host input action
2956
      // to trigger the creation of all the CUDA device actions.
2957
2958
      // If we are dealing with an input action, replicate it for each GPU
2959
      // architecture. If we are in host-only mode we return 'success' so that
2960
      // the host uses the CUDA offload kind.
2961
0
      if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2962
0
        assert(!GpuArchList.empty() &&
2963
0
               "We should have at least one GPU architecture.");
2964
2965
        // If the host input is not CUDA or HIP, we don't need to bother about
2966
        // this input.
2967
0
        if (!(IA->getType() == types::TY_CUDA ||
2968
0
              IA->getType() == types::TY_HIP ||
2969
0
              IA->getType() == types::TY_PP_HIP)) {
2970
          // The builder will ignore this input.
2971
0
          IsActive = false;
2972
0
          return ABRT_Inactive;
2973
0
        }
2974
2975
        // Set the flag to true, so that the builder acts on the current input.
2976
0
        IsActive = true;
2977
2978
0
        if (CompileHostOnly)
2979
0
          return ABRT_Success;
2980
2981
        // Replicate inputs for each GPU architecture.
2982
0
        auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2983
0
                                                 : types::TY_CUDA_DEVICE;
2984
0
        std::string CUID = FixedCUID.str();
2985
0
        if (CUID.empty()) {
2986
0
          if (UseCUID == CUID_Random)
2987
0
            CUID = llvm::utohexstr(llvm::sys::Process::GetRandomNumber(),
2988
0
                                   /*LowerCase=*/true);
2989
0
          else if (UseCUID == CUID_Hash) {
2990
0
            llvm::MD5 Hasher;
2991
0
            llvm::MD5::MD5Result Hash;
2992
0
            SmallString<256> RealPath;
2993
0
            llvm::sys::fs::real_path(IA->getInputArg().getValue(), RealPath,
2994
0
                                     /*expand_tilde=*/true);
2995
0
            Hasher.update(RealPath);
2996
0
            for (auto *A : Args) {
2997
0
              if (A->getOption().matches(options::OPT_INPUT))
2998
0
                continue;
2999
0
              Hasher.update(A->getAsString(Args));
3000
0
            }
3001
0
            Hasher.final(Hash);
3002
0
            CUID = llvm::utohexstr(Hash.low(), /*LowerCase=*/true);
3003
0
          }
3004
0
        }
3005
0
        IA->setId(CUID);
3006
3007
0
        for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3008
0
          CudaDeviceActions.push_back(
3009
0
              C.MakeAction<InputAction>(IA->getInputArg(), Ty, IA->getId()));
3010
0
        }
3011
3012
0
        return ABRT_Success;
3013
0
      }
3014
3015
      // If this is an unbundling action use it as is for each CUDA toolchain.
3016
0
      if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
3017
3018
        // If -fgpu-rdc is disabled, should not unbundle since there is no
3019
        // device code to link.
3020
0
        if (UA->getType() == types::TY_Object && !Relocatable)
3021
0
          return ABRT_Inactive;
3022
3023
0
        CudaDeviceActions.clear();
3024
0
        auto *IA = cast<InputAction>(UA->getInputs().back());
3025
0
        std::string FileName = IA->getInputArg().getAsString(Args);
3026
        // Check if the type of the file is the same as the action. Do not
3027
        // unbundle it if it is not. Do not unbundle .so files, for example,
3028
        // which are not object files. Files with extension ".lib" is classified
3029
        // as TY_Object but they are actually archives, therefore should not be
3030
        // unbundled here as objects. They will be handled at other places.
3031
0
        const StringRef LibFileExt = ".lib";
3032
0
        if (IA->getType() == types::TY_Object &&
3033
0
            (!llvm::sys::path::has_extension(FileName) ||
3034
0
             types::lookupTypeForExtension(
3035
0
                 llvm::sys::path::extension(FileName).drop_front()) !=
3036
0
                 types::TY_Object ||
3037
0
             llvm::sys::path::extension(FileName) == LibFileExt))
3038
0
          return ABRT_Inactive;
3039
3040
0
        for (auto Arch : GpuArchList) {
3041
0
          CudaDeviceActions.push_back(UA);
3042
0
          UA->registerDependentActionInfo(ToolChains[0], Arch,
3043
0
                                          AssociatedOffloadKind);
3044
0
        }
3045
0
        IsActive = true;
3046
0
        return ABRT_Success;
3047
0
      }
3048
3049
0
      return IsActive ? ABRT_Success : ABRT_Inactive;
3050
0
    }
3051
3052
0
    void appendTopLevelActions(ActionList &AL) override {
3053
      // Utility to append actions to the top level list.
3054
0
      auto AddTopLevel = [&](Action *A, TargetID TargetID) {
3055
0
        OffloadAction::DeviceDependences Dep;
3056
0
        Dep.add(*A, *ToolChains.front(), TargetID, AssociatedOffloadKind);
3057
0
        AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
3058
0
      };
3059
3060
      // If we have a fat binary, add it to the list.
3061
0
      if (CudaFatBinary) {
3062
0
        AddTopLevel(CudaFatBinary, CudaArch::UNUSED);
3063
0
        CudaDeviceActions.clear();
3064
0
        CudaFatBinary = nullptr;
3065
0
        return;
3066
0
      }
3067
3068
0
      if (CudaDeviceActions.empty())
3069
0
        return;
3070
3071
      // If we have CUDA actions at this point, that's because we have a have
3072
      // partial compilation, so we should have an action for each GPU
3073
      // architecture.
3074
0
      assert(CudaDeviceActions.size() == GpuArchList.size() &&
3075
0
             "Expecting one action per GPU architecture.");
3076
0
      assert(ToolChains.size() == 1 &&
3077
0
             "Expecting to have a single CUDA toolchain.");
3078
0
      for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
3079
0
        AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
3080
3081
0
      CudaDeviceActions.clear();
3082
0
    }
3083
3084
    /// Get canonicalized offload arch option. \returns empty StringRef if the
3085
    /// option is invalid.
3086
    virtual StringRef getCanonicalOffloadArch(StringRef Arch) = 0;
3087
3088
    virtual std::optional<std::pair<llvm::StringRef, llvm::StringRef>>
3089
    getConflictOffloadArchCombination(const std::set<StringRef> &GpuArchs) = 0;
3090
3091
0
    bool initialize() override {
3092
0
      assert(AssociatedOffloadKind == Action::OFK_Cuda ||
3093
0
             AssociatedOffloadKind == Action::OFK_HIP);
3094
3095
      // We don't need to support CUDA.
3096
0
      if (AssociatedOffloadKind == Action::OFK_Cuda &&
3097
0
          !C.hasOffloadToolChain<Action::OFK_Cuda>())
3098
0
        return false;
3099
3100
      // We don't need to support HIP.
3101
0
      if (AssociatedOffloadKind == Action::OFK_HIP &&
3102
0
          !C.hasOffloadToolChain<Action::OFK_HIP>())
3103
0
        return false;
3104
3105
0
      const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
3106
0
      assert(HostTC && "No toolchain for host compilation.");
3107
0
      if (HostTC->getTriple().isNVPTX() ||
3108
0
          HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
3109
        // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
3110
        // an error and abort pipeline construction early so we don't trip
3111
        // asserts that assume device-side compilation.
3112
0
        C.getDriver().Diag(diag::err_drv_cuda_host_arch)
3113
0
            << HostTC->getTriple().getArchName();
3114
0
        return true;
3115
0
      }
3116
3117
0
      ToolChains.push_back(
3118
0
          AssociatedOffloadKind == Action::OFK_Cuda
3119
0
              ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3120
0
              : C.getSingleOffloadToolChain<Action::OFK_HIP>());
3121
3122
0
      CompileHostOnly = C.getDriver().offloadHostOnly();
3123
0
      EmitLLVM = Args.getLastArg(options::OPT_emit_llvm);
3124
0
      EmitAsm = Args.getLastArg(options::OPT_S);
3125
0
      FixedCUID = Args.getLastArgValue(options::OPT_cuid_EQ);
3126
0
      if (Arg *A = Args.getLastArg(options::OPT_fuse_cuid_EQ)) {
3127
0
        StringRef UseCUIDStr = A->getValue();
3128
0
        UseCUID = llvm::StringSwitch<UseCUIDKind>(UseCUIDStr)
3129
0
                      .Case("hash", CUID_Hash)
3130
0
                      .Case("random", CUID_Random)
3131
0
                      .Case("none", CUID_None)
3132
0
                      .Default(CUID_Invalid);
3133
0
        if (UseCUID == CUID_Invalid) {
3134
0
          C.getDriver().Diag(diag::err_drv_invalid_value)
3135
0
              << A->getAsString(Args) << UseCUIDStr;
3136
0
          C.setContainsError();
3137
0
          return true;
3138
0
        }
3139
0
      }
3140
3141
      // --offload and --offload-arch options are mutually exclusive.
3142
0
      if (Args.hasArgNoClaim(options::OPT_offload_EQ) &&
3143
0
          Args.hasArgNoClaim(options::OPT_offload_arch_EQ,
3144
0
                             options::OPT_no_offload_arch_EQ)) {
3145
0
        C.getDriver().Diag(diag::err_opt_not_valid_with_opt) << "--offload-arch"
3146
0
                                                             << "--offload";
3147
0
      }
3148
3149
      // Collect all offload arch parameters, removing duplicates.
3150
0
      std::set<StringRef> GpuArchs;
3151
0
      bool Error = false;
3152
0
      for (Arg *A : Args) {
3153
0
        if (!(A->getOption().matches(options::OPT_offload_arch_EQ) ||
3154
0
              A->getOption().matches(options::OPT_no_offload_arch_EQ)))
3155
0
          continue;
3156
0
        A->claim();
3157
3158
0
        for (StringRef ArchStr : llvm::split(A->getValue(), ",")) {
3159
0
          if (A->getOption().matches(options::OPT_no_offload_arch_EQ) &&
3160
0
              ArchStr == "all") {
3161
0
            GpuArchs.clear();
3162
0
          } else if (ArchStr == "native") {
3163
0
            const ToolChain &TC = *ToolChains.front();
3164
0
            auto GPUsOrErr = ToolChains.front()->getSystemGPUArchs(Args);
3165
0
            if (!GPUsOrErr) {
3166
0
              TC.getDriver().Diag(diag::err_drv_undetermined_gpu_arch)
3167
0
                  << llvm::Triple::getArchTypeName(TC.getArch())
3168
0
                  << llvm::toString(GPUsOrErr.takeError()) << "--offload-arch";
3169
0
              continue;
3170
0
            }
3171
3172
0
            for (auto GPU : *GPUsOrErr) {
3173
0
              GpuArchs.insert(Args.MakeArgString(GPU));
3174
0
            }
3175
0
          } else {
3176
0
            ArchStr = getCanonicalOffloadArch(ArchStr);
3177
0
            if (ArchStr.empty()) {
3178
0
              Error = true;
3179
0
            } else if (A->getOption().matches(options::OPT_offload_arch_EQ))
3180
0
              GpuArchs.insert(ArchStr);
3181
0
            else if (A->getOption().matches(options::OPT_no_offload_arch_EQ))
3182
0
              GpuArchs.erase(ArchStr);
3183
0
            else
3184
0
              llvm_unreachable("Unexpected option.");
3185
0
          }
3186
0
        }
3187
0
      }
3188
3189
0
      auto &&ConflictingArchs = getConflictOffloadArchCombination(GpuArchs);
3190
0
      if (ConflictingArchs) {
3191
0
        C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo)
3192
0
            << ConflictingArchs->first << ConflictingArchs->second;
3193
0
        C.setContainsError();
3194
0
        return true;
3195
0
      }
3196
3197
      // Collect list of GPUs remaining in the set.
3198
0
      for (auto Arch : GpuArchs)
3199
0
        GpuArchList.push_back(Arch.data());
3200
3201
      // Default to sm_20 which is the lowest common denominator for
3202
      // supported GPUs.  sm_20 code should work correctly, if
3203
      // suboptimally, on all newer GPUs.
3204
0
      if (GpuArchList.empty()) {
3205
0
        if (ToolChains.front()->getTriple().isSPIRV())
3206
0
          GpuArchList.push_back(CudaArch::Generic);
3207
0
        else
3208
0
          GpuArchList.push_back(DefaultCudaArch);
3209
0
      }
3210
3211
0
      return Error;
3212
0
    }
3213
  };
3214
3215
  /// \brief CUDA action builder. It injects device code in the host backend
3216
  /// action.
3217
  class CudaActionBuilder final : public CudaActionBuilderBase {
3218
  public:
3219
    CudaActionBuilder(Compilation &C, DerivedArgList &Args,
3220
                      const Driver::InputList &Inputs)
3221
0
        : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {
3222
0
      DefaultCudaArch = CudaArch::SM_35;
3223
0
    }
3224
3225
0
    StringRef getCanonicalOffloadArch(StringRef ArchStr) override {
3226
0
      CudaArch Arch = StringToCudaArch(ArchStr);
3227
0
      if (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch)) {
3228
0
        C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
3229
0
        return StringRef();
3230
0
      }
3231
0
      return CudaArchToString(Arch);
3232
0
    }
3233
3234
    std::optional<std::pair<llvm::StringRef, llvm::StringRef>>
3235
    getConflictOffloadArchCombination(
3236
0
        const std::set<StringRef> &GpuArchs) override {
3237
0
      return std::nullopt;
3238
0
    }
3239
3240
    ActionBuilderReturnCode
3241
    getDeviceDependences(OffloadAction::DeviceDependences &DA,
3242
                         phases::ID CurPhase, phases::ID FinalPhase,
3243
0
                         PhasesTy &Phases) override {
3244
0
      if (!IsActive)
3245
0
        return ABRT_Inactive;
3246
3247
      // If we don't have more CUDA actions, we don't have any dependences to
3248
      // create for the host.
3249
0
      if (CudaDeviceActions.empty())
3250
0
        return ABRT_Success;
3251
3252
0
      assert(CudaDeviceActions.size() == GpuArchList.size() &&
3253
0
             "Expecting one action per GPU architecture.");
3254
0
      assert(!CompileHostOnly &&
3255
0
             "Not expecting CUDA actions in host-only compilation.");
3256
3257
      // If we are generating code for the device or we are in a backend phase,
3258
      // we attempt to generate the fat binary. We compile each arch to ptx and
3259
      // assemble to cubin, then feed the cubin *and* the ptx into a device
3260
      // "link" action, which uses fatbinary to combine these cubins into one
3261
      // fatbin.  The fatbin is then an input to the host action if not in
3262
      // device-only mode.
3263
0
      if (CompileDeviceOnly || CurPhase == phases::Backend) {
3264
0
        ActionList DeviceActions;
3265
0
        for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3266
          // Produce the device action from the current phase up to the assemble
3267
          // phase.
3268
0
          for (auto Ph : Phases) {
3269
            // Skip the phases that were already dealt with.
3270
0
            if (Ph < CurPhase)
3271
0
              continue;
3272
            // We have to be consistent with the host final phase.
3273
0
            if (Ph > FinalPhase)
3274
0
              break;
3275
3276
0
            CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
3277
0
                C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
3278
3279
0
            if (Ph == phases::Assemble)
3280
0
              break;
3281
0
          }
3282
3283
          // If we didn't reach the assemble phase, we can't generate the fat
3284
          // binary. We don't need to generate the fat binary if we are not in
3285
          // device-only mode.
3286
0
          if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
3287
0
              CompileDeviceOnly)
3288
0
            continue;
3289
3290
0
          Action *AssembleAction = CudaDeviceActions[I];
3291
0
          assert(AssembleAction->getType() == types::TY_Object);
3292
0
          assert(AssembleAction->getInputs().size() == 1);
3293
3294
0
          Action *BackendAction = AssembleAction->getInputs()[0];
3295
0
          assert(BackendAction->getType() == types::TY_PP_Asm);
3296
3297
0
          for (auto &A : {AssembleAction, BackendAction}) {
3298
0
            OffloadAction::DeviceDependences DDep;
3299
0
            DDep.add(*A, *ToolChains.front(), GpuArchList[I], Action::OFK_Cuda);
3300
0
            DeviceActions.push_back(
3301
0
                C.MakeAction<OffloadAction>(DDep, A->getType()));
3302
0
          }
3303
0
        }
3304
3305
        // We generate the fat binary if we have device input actions.
3306
0
        if (!DeviceActions.empty()) {
3307
0
          CudaFatBinary =
3308
0
              C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
3309
3310
0
          if (!CompileDeviceOnly) {
3311
0
            DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
3312
0
                   Action::OFK_Cuda);
3313
            // Clear the fat binary, it is already a dependence to an host
3314
            // action.
3315
0
            CudaFatBinary = nullptr;
3316
0
          }
3317
3318
          // Remove the CUDA actions as they are already connected to an host
3319
          // action or fat binary.
3320
0
          CudaDeviceActions.clear();
3321
0
        }
3322
3323
        // We avoid creating host action in device-only mode.
3324
0
        return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
3325
0
      } else if (CurPhase > phases::Backend) {
3326
        // If we are past the backend phase and still have a device action, we
3327
        // don't have to do anything as this action is already a device
3328
        // top-level action.
3329
0
        return ABRT_Success;
3330
0
      }
3331
3332
0
      assert(CurPhase < phases::Backend && "Generating single CUDA "
3333
0
                                           "instructions should only occur "
3334
0
                                           "before the backend phase!");
3335
3336
      // By default, we produce an action for each device arch.
3337
0
      for (Action *&A : CudaDeviceActions)
3338
0
        A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
3339
3340
0
      return ABRT_Success;
3341
0
    }
3342
  };
3343
  /// \brief HIP action builder. It injects device code in the host backend
3344
  /// action.
3345
  class HIPActionBuilder final : public CudaActionBuilderBase {
3346
    /// The linker inputs obtained for each device arch.
3347
    SmallVector<ActionList, 8> DeviceLinkerInputs;
3348
    // The default bundling behavior depends on the type of output, therefore
3349
    // BundleOutput needs to be tri-value: None, true, or false.
3350
    // Bundle code objects except --no-gpu-output is specified for device
3351
    // only compilation. Bundle other type of output files only if
3352
    // --gpu-bundle-output is specified for device only compilation.
3353
    std::optional<bool> BundleOutput;
3354
    std::optional<bool> EmitReloc;
3355
3356
  public:
3357
    HIPActionBuilder(Compilation &C, DerivedArgList &Args,
3358
                     const Driver::InputList &Inputs)
3359
0
        : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {
3360
3361
0
      DefaultCudaArch = CudaArch::GFX906;
3362
3363
0
      if (Args.hasArg(options::OPT_fhip_emit_relocatable,
3364
0
                      options::OPT_fno_hip_emit_relocatable)) {
3365
0
        EmitReloc = Args.hasFlag(options::OPT_fhip_emit_relocatable,
3366
0
                                 options::OPT_fno_hip_emit_relocatable, false);
3367
3368
0
        if (*EmitReloc) {
3369
0
          if (Relocatable) {
3370
0
            C.getDriver().Diag(diag::err_opt_not_valid_with_opt)
3371
0
                << "-fhip-emit-relocatable"
3372
0
                << "-fgpu-rdc";
3373
0
          }
3374
3375
0
          if (!CompileDeviceOnly) {
3376
0
            C.getDriver().Diag(diag::err_opt_not_valid_without_opt)
3377
0
                << "-fhip-emit-relocatable"
3378
0
                << "--cuda-device-only";
3379
0
          }
3380
0
        }
3381
0
      }
3382
3383
0
      if (Args.hasArg(options::OPT_gpu_bundle_output,
3384
0
                      options::OPT_no_gpu_bundle_output))
3385
0
        BundleOutput = Args.hasFlag(options::OPT_gpu_bundle_output,
3386
0
                                    options::OPT_no_gpu_bundle_output, true) &&
3387
0
                       (!EmitReloc || !*EmitReloc);
3388
0
    }
3389
3390
0
    bool canUseBundlerUnbundler() const override { return true; }
3391
3392
0
    StringRef getCanonicalOffloadArch(StringRef IdStr) override {
3393
0
      llvm::StringMap<bool> Features;
3394
      // getHIPOffloadTargetTriple() is known to return valid value as it has
3395
      // been called successfully in the CreateOffloadingDeviceToolChains().
3396
0
      auto ArchStr = parseTargetID(
3397
0
          *getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs()), IdStr,
3398
0
          &Features);
3399
0
      if (!ArchStr) {
3400
0
        C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << IdStr;
3401
0
        C.setContainsError();
3402
0
        return StringRef();
3403
0
      }
3404
0
      auto CanId = getCanonicalTargetID(*ArchStr, Features);
3405
0
      return Args.MakeArgStringRef(CanId);
3406
0
    };
3407
3408
    std::optional<std::pair<llvm::StringRef, llvm::StringRef>>
3409
    getConflictOffloadArchCombination(
3410
0
        const std::set<StringRef> &GpuArchs) override {
3411
0
      return getConflictTargetIDCombination(GpuArchs);
3412
0
    }
3413
3414
    ActionBuilderReturnCode
3415
    getDeviceDependences(OffloadAction::DeviceDependences &DA,
3416
                         phases::ID CurPhase, phases::ID FinalPhase,
3417
0
                         PhasesTy &Phases) override {
3418
0
      if (!IsActive)
3419
0
        return ABRT_Inactive;
3420
3421
      // amdgcn does not support linking of object files, therefore we skip
3422
      // backend and assemble phases to output LLVM IR. Except for generating
3423
      // non-relocatable device code, where we generate fat binary for device
3424
      // code and pass to host in Backend phase.
3425
0
      if (CudaDeviceActions.empty())
3426
0
        return ABRT_Success;
3427
3428
0
      assert(((CurPhase == phases::Link && Relocatable) ||
3429
0
              CudaDeviceActions.size() == GpuArchList.size()) &&
3430
0
             "Expecting one action per GPU architecture.");
3431
0
      assert(!CompileHostOnly &&
3432
0
             "Not expecting HIP actions in host-only compilation.");
3433
3434
0
      bool ShouldLink = !EmitReloc || !*EmitReloc;
3435
3436
0
      if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM &&
3437
0
          !EmitAsm && ShouldLink) {
3438
        // If we are in backend phase, we attempt to generate the fat binary.
3439
        // We compile each arch to IR and use a link action to generate code
3440
        // object containing ISA. Then we use a special "link" action to create
3441
        // a fat binary containing all the code objects for different GPU's.
3442
        // The fat binary is then an input to the host action.
3443
0
        for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3444
0
          if (C.getDriver().isUsingLTO(/*IsOffload=*/true)) {
3445
            // When LTO is enabled, skip the backend and assemble phases and
3446
            // use lld to link the bitcode.
3447
0
            ActionList AL;
3448
0
            AL.push_back(CudaDeviceActions[I]);
3449
            // Create a link action to link device IR with device library
3450
            // and generate ISA.
3451
0
            CudaDeviceActions[I] =
3452
0
                C.MakeAction<LinkJobAction>(AL, types::TY_Image);
3453
0
          } else {
3454
            // When LTO is not enabled, we follow the conventional
3455
            // compiler phases, including backend and assemble phases.
3456
0
            ActionList AL;
3457
0
            Action *BackendAction = nullptr;
3458
0
            if (ToolChains.front()->getTriple().isSPIRV()) {
3459
              // Emit LLVM bitcode for SPIR-V targets. SPIR-V device tool chain
3460
              // (HIPSPVToolChain) runs post-link LLVM IR passes.
3461
0
              types::ID Output = Args.hasArg(options::OPT_S)
3462
0
                                     ? types::TY_LLVM_IR
3463
0
                                     : types::TY_LLVM_BC;
3464
0
              BackendAction =
3465
0
                  C.MakeAction<BackendJobAction>(CudaDeviceActions[I], Output);
3466
0
            } else
3467
0
              BackendAction = C.getDriver().ConstructPhaseAction(
3468
0
                  C, Args, phases::Backend, CudaDeviceActions[I],
3469
0
                  AssociatedOffloadKind);
3470
0
            auto AssembleAction = C.getDriver().ConstructPhaseAction(
3471
0
                C, Args, phases::Assemble, BackendAction,
3472
0
                AssociatedOffloadKind);
3473
0
            AL.push_back(AssembleAction);
3474
            // Create a link action to link device IR with device library
3475
            // and generate ISA.
3476
0
            CudaDeviceActions[I] =
3477
0
                C.MakeAction<LinkJobAction>(AL, types::TY_Image);
3478
0
          }
3479
3480
          // OffloadingActionBuilder propagates device arch until an offload
3481
          // action. Since the next action for creating fatbin does
3482
          // not have device arch, whereas the above link action and its input
3483
          // have device arch, an offload action is needed to stop the null
3484
          // device arch of the next action being propagated to the above link
3485
          // action.
3486
0
          OffloadAction::DeviceDependences DDep;
3487
0
          DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I],
3488
0
                   AssociatedOffloadKind);
3489
0
          CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
3490
0
              DDep, CudaDeviceActions[I]->getType());
3491
0
        }
3492
3493
0
        if (!CompileDeviceOnly || !BundleOutput || *BundleOutput) {
3494
          // Create HIP fat binary with a special "link" action.
3495
0
          CudaFatBinary = C.MakeAction<LinkJobAction>(CudaDeviceActions,
3496
0
                                                      types::TY_HIP_FATBIN);
3497
3498
0
          if (!CompileDeviceOnly) {
3499
0
            DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
3500
0
                   AssociatedOffloadKind);
3501
            // Clear the fat binary, it is already a dependence to an host
3502
            // action.
3503
0
            CudaFatBinary = nullptr;
3504
0
          }
3505
3506
          // Remove the CUDA actions as they are already connected to an host
3507
          // action or fat binary.
3508
0
          CudaDeviceActions.clear();
3509
0
        }
3510
3511
0
        return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
3512
0
      } else if (CurPhase == phases::Link) {
3513
0
        if (!ShouldLink)
3514
0
          return ABRT_Success;
3515
        // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
3516
        // This happens to each device action originated from each input file.
3517
        // Later on, device actions in DeviceLinkerInputs are used to create
3518
        // device link actions in appendLinkDependences and the created device
3519
        // link actions are passed to the offload action as device dependence.
3520
0
        DeviceLinkerInputs.resize(CudaDeviceActions.size());
3521
0
        auto LI = DeviceLinkerInputs.begin();
3522
0
        for (auto *A : CudaDeviceActions) {
3523
0
          LI->push_back(A);
3524
0
          ++LI;
3525
0
        }
3526
3527
        // We will pass the device action as a host dependence, so we don't
3528
        // need to do anything else with them.
3529
0
        CudaDeviceActions.clear();
3530
0
        return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
3531
0
      }
3532
3533
      // By default, we produce an action for each device arch.
3534
0
      for (Action *&A : CudaDeviceActions)
3535
0
        A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
3536
0
                                               AssociatedOffloadKind);
3537
3538
0
      if (CompileDeviceOnly && CurPhase == FinalPhase && BundleOutput &&
3539
0
          *BundleOutput) {
3540
0
        for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3541
0
          OffloadAction::DeviceDependences DDep;
3542
0
          DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I],
3543
0
                   AssociatedOffloadKind);
3544
0
          CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
3545
0
              DDep, CudaDeviceActions[I]->getType());
3546
0
        }
3547
0
        CudaFatBinary =
3548
0
            C.MakeAction<OffloadBundlingJobAction>(CudaDeviceActions);
3549
0
        CudaDeviceActions.clear();
3550
0
      }
3551
3552
0
      return (CompileDeviceOnly &&
3553
0
              (CurPhase == FinalPhase ||
3554
0
               (!ShouldLink && CurPhase == phases::Assemble)))
3555
0
                 ? ABRT_Ignore_Host
3556
0
                 : ABRT_Success;
3557
0
    }
3558
3559
0
    void appendLinkDeviceActions(ActionList &AL) override {
3560
0
      if (DeviceLinkerInputs.size() == 0)
3561
0
        return;
3562
3563
0
      assert(DeviceLinkerInputs.size() == GpuArchList.size() &&
3564
0
             "Linker inputs and GPU arch list sizes do not match.");
3565
3566
0
      ActionList Actions;
3567
0
      unsigned I = 0;
3568
      // Append a new link action for each device.
3569
      // Each entry in DeviceLinkerInputs corresponds to a GPU arch.
3570
0
      for (auto &LI : DeviceLinkerInputs) {
3571
3572
0
        types::ID Output = Args.hasArg(options::OPT_emit_llvm)
3573
0
                                   ? types::TY_LLVM_BC
3574
0
                                   : types::TY_Image;
3575
3576
0
        auto *DeviceLinkAction = C.MakeAction<LinkJobAction>(LI, Output);
3577
        // Linking all inputs for the current GPU arch.
3578
        // LI contains all the inputs for the linker.
3579
0
        OffloadAction::DeviceDependences DeviceLinkDeps;
3580
0
        DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0],
3581
0
            GpuArchList[I], AssociatedOffloadKind);
3582
0
        Actions.push_back(C.MakeAction<OffloadAction>(
3583
0
            DeviceLinkDeps, DeviceLinkAction->getType()));
3584
0
        ++I;
3585
0
      }
3586
0
      DeviceLinkerInputs.clear();
3587
3588
      // If emitting LLVM, do not generate final host/device compilation action
3589
0
      if (Args.hasArg(options::OPT_emit_llvm)) {
3590
0
          AL.append(Actions);
3591
0
          return;
3592
0
      }
3593
3594
      // Create a host object from all the device images by embedding them
3595
      // in a fat binary for mixed host-device compilation. For device-only
3596
      // compilation, creates a fat binary.
3597
0
      OffloadAction::DeviceDependences DDeps;
3598
0
      if (!CompileDeviceOnly || !BundleOutput || *BundleOutput) {
3599
0
        auto *TopDeviceLinkAction = C.MakeAction<LinkJobAction>(
3600
0
            Actions,
3601
0
            CompileDeviceOnly ? types::TY_HIP_FATBIN : types::TY_Object);
3602
0
        DDeps.add(*TopDeviceLinkAction, *ToolChains[0], nullptr,
3603
0
                  AssociatedOffloadKind);
3604
        // Offload the host object to the host linker.
3605
0
        AL.push_back(
3606
0
            C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType()));
3607
0
      } else {
3608
0
        AL.append(Actions);
3609
0
      }
3610
0
    }
3611
3612
0
    Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); }
3613
3614
0
    void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
3615
  };
3616
3617
  ///
3618
  /// TODO: Add the implementation for other specialized builders here.
3619
  ///
3620
3621
  /// Specialized builders being used by this offloading action builder.
3622
  SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
3623
3624
  /// Flag set to true if all valid builders allow file bundling/unbundling.
3625
  bool CanUseBundler;
3626
3627
public:
3628
  OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
3629
                          const Driver::InputList &Inputs)
3630
0
      : C(C) {
3631
    // Create a specialized builder for each device toolchain.
3632
3633
0
    IsValid = true;
3634
3635
    // Create a specialized builder for CUDA.
3636
0
    SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
3637
3638
    // Create a specialized builder for HIP.
3639
0
    SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
3640
3641
    //
3642
    // TODO: Build other specialized builders here.
3643
    //
3644
3645
    // Initialize all the builders, keeping track of errors. If all valid
3646
    // builders agree that we can use bundling, set the flag to true.
3647
0
    unsigned ValidBuilders = 0u;
3648
0
    unsigned ValidBuildersSupportingBundling = 0u;
3649
0
    for (auto *SB : SpecializedBuilders) {
3650
0
      IsValid = IsValid && !SB->initialize();
3651
3652
      // Update the counters if the builder is valid.
3653
0
      if (SB->isValid()) {
3654
0
        ++ValidBuilders;
3655
0
        if (SB->canUseBundlerUnbundler())
3656
0
          ++ValidBuildersSupportingBundling;
3657
0
      }
3658
0
    }
3659
0
    CanUseBundler =
3660
0
        ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
3661
0
  }
3662
3663
0
  ~OffloadingActionBuilder() {
3664
0
    for (auto *SB : SpecializedBuilders)
3665
0
      delete SB;
3666
0
  }
3667
3668
  /// Record a host action and its originating input argument.
3669
0
  void recordHostAction(Action *HostAction, const Arg *InputArg) {
3670
0
    assert(HostAction && "Invalid host action");
3671
0
    assert(InputArg && "Invalid input argument");
3672
0
    auto Loc = HostActionToInputArgMap.find(HostAction);
3673
0
    if (Loc == HostActionToInputArgMap.end())
3674
0
      HostActionToInputArgMap[HostAction] = InputArg;
3675
0
    assert(HostActionToInputArgMap[HostAction] == InputArg &&
3676
0
           "host action mapped to multiple input arguments");
3677
0
  }
3678
3679
  /// Generate an action that adds device dependences (if any) to a host action.
3680
  /// If no device dependence actions exist, just return the host action \a
3681
  /// HostAction. If an error is found or if no builder requires the host action
3682
  /// to be generated, return nullptr.
3683
  Action *
3684
  addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
3685
                                   phases::ID CurPhase, phases::ID FinalPhase,
3686
0
                                   DeviceActionBuilder::PhasesTy &Phases) {
3687
0
    if (!IsValid)
3688
0
      return nullptr;
3689
3690
0
    if (SpecializedBuilders.empty())
3691
0
      return HostAction;
3692
3693
0
    assert(HostAction && "Invalid host action!");
3694
0
    recordHostAction(HostAction, InputArg);
3695
3696
0
    OffloadAction::DeviceDependences DDeps;
3697
    // Check if all the programming models agree we should not emit the host
3698
    // action. Also, keep track of the offloading kinds employed.
3699
0
    auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3700
0
    unsigned InactiveBuilders = 0u;
3701
0
    unsigned IgnoringBuilders = 0u;
3702
0
    for (auto *SB : SpecializedBuilders) {
3703
0
      if (!SB->isValid()) {
3704
0
        ++InactiveBuilders;
3705
0
        continue;
3706
0
      }
3707
0
      auto RetCode =
3708
0
          SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
3709
3710
      // If the builder explicitly says the host action should be ignored,
3711
      // we need to increment the variable that tracks the builders that request
3712
      // the host object to be ignored.
3713
0
      if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
3714
0
        ++IgnoringBuilders;
3715
3716
      // Unless the builder was inactive for this action, we have to record the
3717
      // offload kind because the host will have to use it.
3718
0
      if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3719
0
        OffloadKind |= SB->getAssociatedOffloadKind();
3720
0
    }
3721
3722
    // If all builders agree that the host object should be ignored, just return
3723
    // nullptr.
3724
0
    if (IgnoringBuilders &&
3725
0
        SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
3726
0
      return nullptr;
3727
3728
0
    if (DDeps.getActions().empty())
3729
0
      return HostAction;
3730
3731
    // We have dependences we need to bundle together. We use an offload action
3732
    // for that.
3733
0
    OffloadAction::HostDependence HDep(
3734
0
        *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3735
0
        /*BoundArch=*/nullptr, DDeps);
3736
0
    return C.MakeAction<OffloadAction>(HDep, DDeps);
3737
0
  }
3738
3739
  /// Generate an action that adds a host dependence to a device action. The
3740
  /// results will be kept in this action builder. Return true if an error was
3741
  /// found.
3742
  bool addHostDependenceToDeviceActions(Action *&HostAction,
3743
0
                                        const Arg *InputArg) {
3744
0
    if (!IsValid)
3745
0
      return true;
3746
3747
0
    recordHostAction(HostAction, InputArg);
3748
3749
    // If we are supporting bundling/unbundling and the current action is an
3750
    // input action of non-source file, we replace the host action by the
3751
    // unbundling action. The bundler tool has the logic to detect if an input
3752
    // is a bundle or not and if the input is not a bundle it assumes it is a
3753
    // host file. Therefore it is safe to create an unbundling action even if
3754
    // the input is not a bundle.
3755
0
    if (CanUseBundler && isa<InputAction>(HostAction) &&
3756
0
        InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
3757
0
        (!types::isSrcFile(HostAction->getType()) ||
3758
0
         HostAction->getType() == types::TY_PP_HIP)) {
3759
0
      auto UnbundlingHostAction =
3760
0
          C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
3761
0
      UnbundlingHostAction->registerDependentActionInfo(
3762
0
          C.getSingleOffloadToolChain<Action::OFK_Host>(),
3763
0
          /*BoundArch=*/StringRef(), Action::OFK_Host);
3764
0
      HostAction = UnbundlingHostAction;
3765
0
      recordHostAction(HostAction, InputArg);
3766
0
    }
3767
3768
0
    assert(HostAction && "Invalid host action!");
3769
3770
    // Register the offload kinds that are used.
3771
0
    auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3772
0
    for (auto *SB : SpecializedBuilders) {
3773
0
      if (!SB->isValid())
3774
0
        continue;
3775
3776
0
      auto RetCode = SB->addDeviceDependences(HostAction);
3777
3778
      // Host dependences for device actions are not compatible with that same
3779
      // action being ignored.
3780
0
      assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
3781
0
             "Host dependence not expected to be ignored.!");
3782
3783
      // Unless the builder was inactive for this action, we have to record the
3784
      // offload kind because the host will have to use it.
3785
0
      if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3786
0
        OffloadKind |= SB->getAssociatedOffloadKind();
3787
0
    }
3788
3789
    // Do not use unbundler if the Host does not depend on device action.
3790
0
    if (OffloadKind == Action::OFK_None && CanUseBundler)
3791
0
      if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3792
0
        HostAction = UA->getInputs().back();
3793
3794
0
    return false;
3795
0
  }
3796
3797
  /// Add the offloading top level actions to the provided action list. This
3798
  /// function can replace the host action by a bundling action if the
3799
  /// programming models allow it.
3800
  bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3801
0
                             const Arg *InputArg) {
3802
0
    if (HostAction)
3803
0
      recordHostAction(HostAction, InputArg);
3804
3805
    // Get the device actions to be appended.
3806
0
    ActionList OffloadAL;
3807
0
    for (auto *SB : SpecializedBuilders) {
3808
0
      if (!SB->isValid())
3809
0
        continue;
3810
0
      SB->appendTopLevelActions(OffloadAL);
3811
0
    }
3812
3813
    // If we can use the bundler, replace the host action by the bundling one in
3814
    // the resulting list. Otherwise, just append the device actions. For
3815
    // device only compilation, HostAction is a null pointer, therefore only do
3816
    // this when HostAction is not a null pointer.
3817
0
    if (CanUseBundler && HostAction &&
3818
0
        HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) {
3819
      // Add the host action to the list in order to create the bundling action.
3820
0
      OffloadAL.push_back(HostAction);
3821
3822
      // We expect that the host action was just appended to the action list
3823
      // before this method was called.
3824
0
      assert(HostAction == AL.back() && "Host action not in the list??");
3825
0
      HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3826
0
      recordHostAction(HostAction, InputArg);
3827
0
      AL.back() = HostAction;
3828
0
    } else
3829
0
      AL.append(OffloadAL.begin(), OffloadAL.end());
3830
3831
    // Propagate to the current host action (if any) the offload information
3832
    // associated with the current input.
3833
0
    if (HostAction)
3834
0
      HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3835
0
                                           /*BoundArch=*/nullptr);
3836
0
    return false;
3837
0
  }
3838
3839
0
  void appendDeviceLinkActions(ActionList &AL) {
3840
0
    for (DeviceActionBuilder *SB : SpecializedBuilders) {
3841
0
      if (!SB->isValid())
3842
0
        continue;
3843
0
      SB->appendLinkDeviceActions(AL);
3844
0
    }
3845
0
  }
3846
3847
0
  Action *makeHostLinkAction() {
3848
    // Build a list of device linking actions.
3849
0
    ActionList DeviceAL;
3850
0
    appendDeviceLinkActions(DeviceAL);
3851
0
    if (DeviceAL.empty())
3852
0
      return nullptr;
3853
3854
    // Let builders add host linking actions.
3855
0
    Action* HA = nullptr;
3856
0
    for (DeviceActionBuilder *SB : SpecializedBuilders) {
3857
0
      if (!SB->isValid())
3858
0
        continue;
3859
0
      HA = SB->appendLinkHostActions(DeviceAL);
3860
      // This created host action has no originating input argument, therefore
3861
      // needs to set its offloading kind directly.
3862
0
      if (HA)
3863
0
        HA->propagateHostOffloadInfo(SB->getAssociatedOffloadKind(),
3864
0
                                     /*BoundArch=*/nullptr);
3865
0
    }
3866
0
    return HA;
3867
0
  }
3868
3869
  /// Processes the host linker action. This currently consists of replacing it
3870
  /// with an offload action if there are device link objects and propagate to
3871
  /// the host action all the offload kinds used in the current compilation. The
3872
  /// resulting action is returned.
3873
0
  Action *processHostLinkAction(Action *HostAction) {
3874
    // Add all the dependences from the device linking actions.
3875
0
    OffloadAction::DeviceDependences DDeps;
3876
0
    for (auto *SB : SpecializedBuilders) {
3877
0
      if (!SB->isValid())
3878
0
        continue;
3879
3880
0
      SB->appendLinkDependences(DDeps);
3881
0
    }
3882
3883
    // Calculate all the offload kinds used in the current compilation.
3884
0
    unsigned ActiveOffloadKinds = 0u;
3885
0
    for (auto &I : InputArgToOffloadKindMap)
3886
0
      ActiveOffloadKinds |= I.second;
3887
3888
    // If we don't have device dependencies, we don't have to create an offload
3889
    // action.
3890
0
    if (DDeps.getActions().empty()) {
3891
      // Set all the active offloading kinds to the link action. Given that it
3892
      // is a link action it is assumed to depend on all actions generated so
3893
      // far.
3894
0
      HostAction->setHostOffloadInfo(ActiveOffloadKinds,
3895
0
                                     /*BoundArch=*/nullptr);
3896
      // Propagate active offloading kinds for each input to the link action.
3897
      // Each input may have different active offloading kind.
3898
0
      for (auto *A : HostAction->inputs()) {
3899
0
        auto ArgLoc = HostActionToInputArgMap.find(A);
3900
0
        if (ArgLoc == HostActionToInputArgMap.end())
3901
0
          continue;
3902
0
        auto OFKLoc = InputArgToOffloadKindMap.find(ArgLoc->second);
3903
0
        if (OFKLoc == InputArgToOffloadKindMap.end())
3904
0
          continue;
3905
0
        A->propagateHostOffloadInfo(OFKLoc->second, /*BoundArch=*/nullptr);
3906
0
      }
3907
0
      return HostAction;
3908
0
    }
3909
3910
    // Create the offload action with all dependences. When an offload action
3911
    // is created the kinds are propagated to the host action, so we don't have
3912
    // to do that explicitly here.
3913
0
    OffloadAction::HostDependence HDep(
3914
0
        *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3915
0
        /*BoundArch*/ nullptr, ActiveOffloadKinds);
3916
0
    return C.MakeAction<OffloadAction>(HDep, DDeps);
3917
0
  }
3918
};
3919
} // anonymous namespace.
3920
3921
void Driver::handleArguments(Compilation &C, DerivedArgList &Args,
3922
                             const InputList &Inputs,
3923
0
                             ActionList &Actions) const {
3924
3925
  // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
3926
0
  Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3927
0
  Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
3928
0
  if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3929
0
    Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3930
0
    Args.eraseArg(options::OPT__SLASH_Yc);
3931
0
    Args.eraseArg(options::OPT__SLASH_Yu);
3932
0
    YcArg = YuArg = nullptr;
3933
0
  }
3934
0
  if (YcArg && Inputs.size() > 1) {
3935
0
    Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3936
0
    Args.eraseArg(options::OPT__SLASH_Yc);
3937
0
    YcArg = nullptr;
3938
0
  }
3939
3940
0
  Arg *FinalPhaseArg;
3941
0
  phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
3942
3943
0
  if (FinalPhase == phases::Link) {
3944
0
    if (Args.hasArgNoClaim(options::OPT_hipstdpar)) {
3945
0
      Args.AddFlagArg(nullptr, getOpts().getOption(options::OPT_hip_link));
3946
0
      Args.AddFlagArg(nullptr,
3947
0
                      getOpts().getOption(options::OPT_frtlib_add_rpath));
3948
0
    }
3949
    // Emitting LLVM while linking disabled except in HIPAMD Toolchain
3950
0
    if (Args.hasArg(options::OPT_emit_llvm) && !Args.hasArg(options::OPT_hip_link))
3951
0
      Diag(clang::diag::err_drv_emit_llvm_link);
3952
0
    if (IsCLMode() && LTOMode != LTOK_None &&
3953
0
        !Args.getLastArgValue(options::OPT_fuse_ld_EQ)
3954
0
             .equals_insensitive("lld"))
3955
0
      Diag(clang::diag::err_drv_lto_without_lld);
3956
3957
    // If -dumpdir is not specified, give a default prefix derived from the link
3958
    // output filename. For example, `clang -g -gsplit-dwarf a.c -o x` passes
3959
    // `-dumpdir x-` to cc1. If -o is unspecified, use
3960
    // stem(getDefaultImageName()) (usually stem("a.out") = "a").
3961
0
    if (!Args.hasArg(options::OPT_dumpdir)) {
3962
0
      Arg *FinalOutput = Args.getLastArg(options::OPT_o, options::OPT__SLASH_o);
3963
0
      Arg *Arg = Args.MakeSeparateArg(
3964
0
          nullptr, getOpts().getOption(options::OPT_dumpdir),
3965
0
          Args.MakeArgString(
3966
0
              (FinalOutput ? FinalOutput->getValue()
3967
0
                           : llvm::sys::path::stem(getDefaultImageName())) +
3968
0
              "-"));
3969
0
      Arg->claim();
3970
0
      Args.append(Arg);
3971
0
    }
3972
0
  }
3973
3974
0
  if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3975
    // If only preprocessing or /Y- is used, all pch handling is disabled.
3976
    // Rather than check for it everywhere, just remove clang-cl pch-related
3977
    // flags here.
3978
0
    Args.eraseArg(options::OPT__SLASH_Fp);
3979
0
    Args.eraseArg(options::OPT__SLASH_Yc);
3980
0
    Args.eraseArg(options::OPT__SLASH_Yu);
3981
0
    YcArg = YuArg = nullptr;
3982
0
  }
3983
3984
0
  unsigned LastPLSize = 0;
3985
0
  for (auto &I : Inputs) {
3986
0
    types::ID InputType = I.first;
3987
0
    const Arg *InputArg = I.second;
3988
3989
0
    auto PL = types::getCompilationPhases(InputType);
3990
0
    LastPLSize = PL.size();
3991
3992
    // If the first step comes after the final phase we are doing as part of
3993
    // this compilation, warn the user about it.
3994
0
    phases::ID InitialPhase = PL[0];
3995
0
    if (InitialPhase > FinalPhase) {
3996
0
      if (InputArg->isClaimed())
3997
0
        continue;
3998
3999
      // Claim here to avoid the more general unused warning.
4000
0
      InputArg->claim();
4001
4002
      // Suppress all unused style warnings with -Qunused-arguments
4003
0
      if (Args.hasArg(options::OPT_Qunused_arguments))
4004
0
        continue;
4005
4006
      // Special case when final phase determined by binary name, rather than
4007
      // by a command-line argument with a corresponding Arg.
4008
0
      if (CCCIsCPP())
4009
0
        Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
4010
0
            << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
4011
      // Special case '-E' warning on a previously preprocessed file to make
4012
      // more sense.
4013
0
      else if (InitialPhase == phases::Compile &&
4014
0
               (Args.getLastArg(options::OPT__SLASH_EP,
4015
0
                                options::OPT__SLASH_P) ||
4016
0
                Args.getLastArg(options::OPT_E) ||
4017
0
                Args.getLastArg(options::OPT_M, options::OPT_MM)) &&
4018
0
               getPreprocessedType(InputType) == types::TY_INVALID)
4019
0
        Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
4020
0
            << InputArg->getAsString(Args) << !!FinalPhaseArg
4021
0
            << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
4022
0
      else
4023
0
        Diag(clang::diag::warn_drv_input_file_unused)
4024
0
            << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
4025
0
            << !!FinalPhaseArg
4026
0
            << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
4027
0
      continue;
4028
0
    }
4029
4030
0
    if (YcArg) {
4031
      // Add a separate precompile phase for the compile phase.
4032
0
      if (FinalPhase >= phases::Compile) {
4033
0
        const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
4034
        // Build the pipeline for the pch file.
4035
0
        Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType);
4036
0
        for (phases::ID Phase : types::getCompilationPhases(HeaderType))
4037
0
          ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
4038
0
        assert(ClangClPch);
4039
0
        Actions.push_back(ClangClPch);
4040
        // The driver currently exits after the first failed command.  This
4041
        // relies on that behavior, to make sure if the pch generation fails,
4042
        // the main compilation won't run.
4043
        // FIXME: If the main compilation fails, the PCH generation should
4044
        // probably not be considered successful either.
4045
0
      }
4046
0
    }
4047
0
  }
4048
4049
  // If we are linking, claim any options which are obviously only used for
4050
  // compilation.
4051
  // FIXME: Understand why the last Phase List length is used here.
4052
0
  if (FinalPhase == phases::Link && LastPLSize == 1) {
4053
0
    Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
4054
0
    Args.ClaimAllArgs(options::OPT_cl_compile_Group);
4055
0
  }
4056
0
}
4057
4058
void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
4059
0
                          const InputList &Inputs, ActionList &Actions) const {
4060
0
  llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
4061
4062
0
  if (!SuppressMissingInputWarning && Inputs.empty()) {
4063
0
    Diag(clang::diag::err_drv_no_input_files);
4064
0
    return;
4065
0
  }
4066
4067
  // Diagnose misuse of /Fo.
4068
0
  if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
4069
0
    StringRef V = A->getValue();
4070
0
    if (Inputs.size() > 1 && !V.empty() &&
4071
0
        !llvm::sys::path::is_separator(V.back())) {
4072
      // Check whether /Fo tries to name an output file for multiple inputs.
4073
0
      Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
4074
0
          << A->getSpelling() << V;
4075
0
      Args.eraseArg(options::OPT__SLASH_Fo);
4076
0
    }
4077
0
  }
4078
4079
  // Diagnose misuse of /Fa.
4080
0
  if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
4081
0
    StringRef V = A->getValue();
4082
0
    if (Inputs.size() > 1 && !V.empty() &&
4083
0
        !llvm::sys::path::is_separator(V.back())) {
4084
      // Check whether /Fa tries to name an asm file for multiple inputs.
4085
0
      Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
4086
0
          << A->getSpelling() << V;
4087
0
      Args.eraseArg(options::OPT__SLASH_Fa);
4088
0
    }
4089
0
  }
4090
4091
  // Diagnose misuse of /o.
4092
0
  if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
4093
0
    if (A->getValue()[0] == '\0') {
4094
      // It has to have a value.
4095
0
      Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
4096
0
      Args.eraseArg(options::OPT__SLASH_o);
4097
0
    }
4098
0
  }
4099
4100
0
  handleArguments(C, Args, Inputs, Actions);
4101
4102
0
  bool UseNewOffloadingDriver =
4103
0
      C.isOffloadingHostKind(Action::OFK_OpenMP) ||
4104
0
      Args.hasFlag(options::OPT_offload_new_driver,
4105
0
                   options::OPT_no_offload_new_driver, false);
4106
4107
  // Builder to be used to build offloading actions.
4108
0
  std::unique_ptr<OffloadingActionBuilder> OffloadBuilder =
4109
0
      !UseNewOffloadingDriver
4110
0
          ? std::make_unique<OffloadingActionBuilder>(C, Args, Inputs)
4111
0
          : nullptr;
4112
4113
  // Construct the actions to perform.
4114
0
  ExtractAPIJobAction *ExtractAPIAction = nullptr;
4115
0
  ActionList LinkerInputs;
4116
0
  ActionList MergerInputs;
4117
4118
0
  for (auto &I : Inputs) {
4119
0
    types::ID InputType = I.first;
4120
0
    const Arg *InputArg = I.second;
4121
4122
0
    auto PL = types::getCompilationPhases(*this, Args, InputType);
4123
0
    if (PL.empty())
4124
0
      continue;
4125
4126
0
    auto FullPL = types::getCompilationPhases(InputType);
4127
4128
    // Build the pipeline for this file.
4129
0
    Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
4130
4131
    // Use the current host action in any of the offloading actions, if
4132
    // required.
4133
0
    if (!UseNewOffloadingDriver)
4134
0
      if (OffloadBuilder->addHostDependenceToDeviceActions(Current, InputArg))
4135
0
        break;
4136
4137
0
    for (phases::ID Phase : PL) {
4138
4139
      // Add any offload action the host action depends on.
4140
0
      if (!UseNewOffloadingDriver)
4141
0
        Current = OffloadBuilder->addDeviceDependencesToHostAction(
4142
0
            Current, InputArg, Phase, PL.back(), FullPL);
4143
0
      if (!Current)
4144
0
        break;
4145
4146
      // Queue linker inputs.
4147
0
      if (Phase == phases::Link) {
4148
0
        assert(Phase == PL.back() && "linking must be final compilation step.");
4149
        // We don't need to generate additional link commands if emitting AMD
4150
        // bitcode or compiling only for the offload device
4151
0
        if (!(C.getInputArgs().hasArg(options::OPT_hip_link) &&
4152
0
              (C.getInputArgs().hasArg(options::OPT_emit_llvm))) &&
4153
0
            !offloadDeviceOnly())
4154
0
          LinkerInputs.push_back(Current);
4155
0
        Current = nullptr;
4156
0
        break;
4157
0
      }
4158
4159
      // TODO: Consider removing this because the merged may not end up being
4160
      // the final Phase in the pipeline. Perhaps the merged could just merge
4161
      // and then pass an artifact of some sort to the Link Phase.
4162
      // Queue merger inputs.
4163
0
      if (Phase == phases::IfsMerge) {
4164
0
        assert(Phase == PL.back() && "merging must be final compilation step.");
4165
0
        MergerInputs.push_back(Current);
4166
0
        Current = nullptr;
4167
0
        break;
4168
0
      }
4169
4170
0
      if (Phase == phases::Precompile && ExtractAPIAction) {
4171
0
        ExtractAPIAction->addHeaderInput(Current);
4172
0
        Current = nullptr;
4173
0
        break;
4174
0
      }
4175
4176
      // FIXME: Should we include any prior module file outputs as inputs of
4177
      // later actions in the same command line?
4178
4179
      // Otherwise construct the appropriate action.
4180
0
      Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
4181
4182
      // We didn't create a new action, so we will just move to the next phase.
4183
0
      if (NewCurrent == Current)
4184
0
        continue;
4185
4186
0
      if (auto *EAA = dyn_cast<ExtractAPIJobAction>(NewCurrent))
4187
0
        ExtractAPIAction = EAA;
4188
4189
0
      Current = NewCurrent;
4190
4191
      // Try to build the offloading actions and add the result as a dependency
4192
      // to the host.
4193
0
      if (UseNewOffloadingDriver)
4194
0
        Current = BuildOffloadingActions(C, Args, I, Current);
4195
      // Use the current host action in any of the offloading actions, if
4196
      // required.
4197
0
      else if (OffloadBuilder->addHostDependenceToDeviceActions(Current,
4198
0
                                                                InputArg))
4199
0
        break;
4200
4201
0
      if (Current->getType() == types::TY_Nothing)
4202
0
        break;
4203
0
    }
4204
4205
    // If we ended with something, add to the output list.
4206
0
    if (Current)
4207
0
      Actions.push_back(Current);
4208
4209
    // Add any top level actions generated for offloading.
4210
0
    if (!UseNewOffloadingDriver)
4211
0
      OffloadBuilder->appendTopLevelActions(Actions, Current, InputArg);
4212
0
    else if (Current)
4213
0
      Current->propagateHostOffloadInfo(C.getActiveOffloadKinds(),
4214
0
                                        /*BoundArch=*/nullptr);
4215
0
  }
4216
4217
  // Add a link action if necessary.
4218
4219
0
  if (LinkerInputs.empty()) {
4220
0
    Arg *FinalPhaseArg;
4221
0
    if (getFinalPhase(Args, &FinalPhaseArg) == phases::Link)
4222
0
      if (!UseNewOffloadingDriver)
4223
0
        OffloadBuilder->appendDeviceLinkActions(Actions);
4224
0
  }
4225
4226
0
  if (!LinkerInputs.empty()) {
4227
0
    if (!UseNewOffloadingDriver)
4228
0
      if (Action *Wrapper = OffloadBuilder->makeHostLinkAction())
4229
0
        LinkerInputs.push_back(Wrapper);
4230
0
    Action *LA;
4231
    // Check if this Linker Job should emit a static library.
4232
0
    if (ShouldEmitStaticLibrary(Args)) {
4233
0
      LA = C.MakeAction<StaticLibJobAction>(LinkerInputs, types::TY_Image);
4234
0
    } else if (UseNewOffloadingDriver ||
4235
0
               Args.hasArg(options::OPT_offload_link)) {
4236
0
      LA = C.MakeAction<LinkerWrapperJobAction>(LinkerInputs, types::TY_Image);
4237
0
      LA->propagateHostOffloadInfo(C.getActiveOffloadKinds(),
4238
0
                                   /*BoundArch=*/nullptr);
4239
0
    } else {
4240
0
      LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
4241
0
    }
4242
0
    if (!UseNewOffloadingDriver)
4243
0
      LA = OffloadBuilder->processHostLinkAction(LA);
4244
0
    Actions.push_back(LA);
4245
0
  }
4246
4247
  // Add an interface stubs merge action if necessary.
4248
0
  if (!MergerInputs.empty())
4249
0
    Actions.push_back(
4250
0
        C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
4251
4252
0
  if (Args.hasArg(options::OPT_emit_interface_stubs)) {
4253
0
    auto PhaseList = types::getCompilationPhases(
4254
0
        types::TY_IFS_CPP,
4255
0
        Args.hasArg(options::OPT_c) ? phases::Compile : phases::IfsMerge);
4256
4257
0
    ActionList MergerInputs;
4258
4259
0
    for (auto &I : Inputs) {
4260
0
      types::ID InputType = I.first;
4261
0
      const Arg *InputArg = I.second;
4262
4263
      // Currently clang and the llvm assembler do not support generating symbol
4264
      // stubs from assembly, so we skip the input on asm files. For ifs files
4265
      // we rely on the normal pipeline setup in the pipeline setup code above.
4266
0
      if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm ||
4267
0
          InputType == types::TY_Asm)
4268
0
        continue;
4269
4270
0
      Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
4271
4272
0
      for (auto Phase : PhaseList) {
4273
0
        switch (Phase) {
4274
0
        default:
4275
0
          llvm_unreachable(
4276
0
              "IFS Pipeline can only consist of Compile followed by IfsMerge.");
4277
0
        case phases::Compile: {
4278
          // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs
4279
          // files where the .o file is located. The compile action can not
4280
          // handle this.
4281
0
          if (InputType == types::TY_Object)
4282
0
            break;
4283
4284
0
          Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP);
4285
0
          break;
4286
0
        }
4287
0
        case phases::IfsMerge: {
4288
0
          assert(Phase == PhaseList.back() &&
4289
0
                 "merging must be final compilation step.");
4290
0
          MergerInputs.push_back(Current);
4291
0
          Current = nullptr;
4292
0
          break;
4293
0
        }
4294
0
        }
4295
0
      }
4296
4297
      // If we ended with something, add to the output list.
4298
0
      if (Current)
4299
0
        Actions.push_back(Current);
4300
0
    }
4301
4302
    // Add an interface stubs merge action if necessary.
4303
0
    if (!MergerInputs.empty())
4304
0
      Actions.push_back(
4305
0
          C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
4306
0
  }
4307
4308
0
  for (auto Opt : {options::OPT_print_supported_cpus,
4309
0
                   options::OPT_print_supported_extensions}) {
4310
    // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a
4311
    // custom Compile phase that prints out supported cpu models and quits.
4312
    //
4313
    // If --print-supported-extensions is specified, call the helper function
4314
    // RISCVMarchHelp in RISCVISAInfo.cpp that prints out supported extensions
4315
    // and quits.
4316
0
    if (Arg *A = Args.getLastArg(Opt)) {
4317
0
      if (Opt == options::OPT_print_supported_extensions &&
4318
0
          !C.getDefaultToolChain().getTriple().isRISCV() &&
4319
0
          !C.getDefaultToolChain().getTriple().isAArch64() &&
4320
0
          !C.getDefaultToolChain().getTriple().isARM()) {
4321
0
        C.getDriver().Diag(diag::err_opt_not_valid_on_target)
4322
0
            << "--print-supported-extensions";
4323
0
        return;
4324
0
      }
4325
4326
      // Use the -mcpu=? flag as the dummy input to cc1.
4327
0
      Actions.clear();
4328
0
      Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C);
4329
0
      Actions.push_back(
4330
0
          C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing));
4331
0
      for (auto &I : Inputs)
4332
0
        I.second->claim();
4333
0
    }
4334
0
  }
4335
4336
  // Call validator for dxil when -Vd not in Args.
4337
0
  if (C.getDefaultToolChain().getTriple().isDXIL()) {
4338
    // Only add action when needValidation.
4339
0
    const auto &TC =
4340
0
        static_cast<const toolchains::HLSLToolChain &>(C.getDefaultToolChain());
4341
0
    if (TC.requiresValidation(Args)) {
4342
0
      Action *LastAction = Actions.back();
4343
0
      Actions.push_back(C.MakeAction<BinaryAnalyzeJobAction>(
4344
0
          LastAction, types::TY_DX_CONTAINER));
4345
0
    }
4346
0
  }
4347
4348
  // Claim ignored clang-cl options.
4349
0
  Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
4350
0
}
4351
4352
/// Returns the canonical name for the offloading architecture when using a HIP
4353
/// or CUDA architecture.
4354
static StringRef getCanonicalArchString(Compilation &C,
4355
                                        const llvm::opt::DerivedArgList &Args,
4356
                                        StringRef ArchStr,
4357
                                        const llvm::Triple &Triple,
4358
0
                                        bool SuppressError = false) {
4359
  // Lookup the CUDA / HIP architecture string. Only report an error if we were
4360
  // expecting the triple to be only NVPTX / AMDGPU.
4361
0
  CudaArch Arch = StringToCudaArch(getProcessorFromTargetID(Triple, ArchStr));
4362
0
  if (!SuppressError && Triple.isNVPTX() &&
4363
0
      (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch))) {
4364
0
    C.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch)
4365
0
        << "CUDA" << ArchStr;
4366
0
    return StringRef();
4367
0
  } else if (!SuppressError && Triple.isAMDGPU() &&
4368
0
             (Arch == CudaArch::UNKNOWN || !IsAMDGpuArch(Arch))) {
4369
0
    C.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch)
4370
0
        << "HIP" << ArchStr;
4371
0
    return StringRef();
4372
0
  }
4373
4374
0
  if (IsNVIDIAGpuArch(Arch))
4375
0
    return Args.MakeArgStringRef(CudaArchToString(Arch));
4376
4377
0
  if (IsAMDGpuArch(Arch)) {
4378
0
    llvm::StringMap<bool> Features;
4379
0
    auto HIPTriple = getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs());
4380
0
    if (!HIPTriple)
4381
0
      return StringRef();
4382
0
    auto Arch = parseTargetID(*HIPTriple, ArchStr, &Features);
4383
0
    if (!Arch) {
4384
0
      C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << ArchStr;
4385
0
      C.setContainsError();
4386
0
      return StringRef();
4387
0
    }
4388
0
    return Args.MakeArgStringRef(getCanonicalTargetID(*Arch, Features));
4389
0
  }
4390
4391
  // If the input isn't CUDA or HIP just return the architecture.
4392
0
  return ArchStr;
4393
0
}
4394
4395
/// Checks if the set offloading architectures does not conflict. Returns the
4396
/// incompatible pair if a conflict occurs.
4397
static std::optional<std::pair<llvm::StringRef, llvm::StringRef>>
4398
getConflictOffloadArchCombination(const llvm::DenseSet<StringRef> &Archs,
4399
0
                                  llvm::Triple Triple) {
4400
0
  if (!Triple.isAMDGPU())
4401
0
    return std::nullopt;
4402
4403
0
  std::set<StringRef> ArchSet;
4404
0
  llvm::copy(Archs, std::inserter(ArchSet, ArchSet.begin()));
4405
0
  return getConflictTargetIDCombination(ArchSet);
4406
0
}
4407
4408
llvm::DenseSet<StringRef>
4409
Driver::getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args,
4410
                        Action::OffloadKind Kind, const ToolChain *TC,
4411
0
                        bool SuppressError) const {
4412
0
  if (!TC)
4413
0
    TC = &C.getDefaultToolChain();
4414
4415
  // --offload and --offload-arch options are mutually exclusive.
4416
0
  if (Args.hasArgNoClaim(options::OPT_offload_EQ) &&
4417
0
      Args.hasArgNoClaim(options::OPT_offload_arch_EQ,
4418
0
                         options::OPT_no_offload_arch_EQ)) {
4419
0
    C.getDriver().Diag(diag::err_opt_not_valid_with_opt)
4420
0
        << "--offload"
4421
0
        << (Args.hasArgNoClaim(options::OPT_offload_arch_EQ)
4422
0
                ? "--offload-arch"
4423
0
                : "--no-offload-arch");
4424
0
  }
4425
4426
0
  if (KnownArchs.contains(TC))
4427
0
    return KnownArchs.lookup(TC);
4428
4429
0
  llvm::DenseSet<StringRef> Archs;
4430
0
  for (auto *Arg : Args) {
4431
    // Extract any '--[no-]offload-arch' arguments intended for this toolchain.
4432
0
    std::unique_ptr<llvm::opt::Arg> ExtractedArg = nullptr;
4433
0
    if (Arg->getOption().matches(options::OPT_Xopenmp_target_EQ) &&
4434
0
        ToolChain::getOpenMPTriple(Arg->getValue(0)) == TC->getTriple()) {
4435
0
      Arg->claim();
4436
0
      unsigned Index = Args.getBaseArgs().MakeIndex(Arg->getValue(1));
4437
0
      ExtractedArg = getOpts().ParseOneArg(Args, Index);
4438
0
      Arg = ExtractedArg.get();
4439
0
    }
4440
4441
    // Add or remove the seen architectures in order of appearance. If an
4442
    // invalid architecture is given we simply exit.
4443
0
    if (Arg->getOption().matches(options::OPT_offload_arch_EQ)) {
4444
0
      for (StringRef Arch : llvm::split(Arg->getValue(), ",")) {
4445
0
        if (Arch == "native" || Arch.empty()) {
4446
0
          auto GPUsOrErr = TC->getSystemGPUArchs(Args);
4447
0
          if (!GPUsOrErr) {
4448
0
            if (SuppressError)
4449
0
              llvm::consumeError(GPUsOrErr.takeError());
4450
0
            else
4451
0
              TC->getDriver().Diag(diag::err_drv_undetermined_gpu_arch)
4452
0
                  << llvm::Triple::getArchTypeName(TC->getArch())
4453
0
                  << llvm::toString(GPUsOrErr.takeError()) << "--offload-arch";
4454
0
            continue;
4455
0
          }
4456
4457
0
          for (auto ArchStr : *GPUsOrErr) {
4458
0
            Archs.insert(
4459
0
                getCanonicalArchString(C, Args, Args.MakeArgString(ArchStr),
4460
0
                                       TC->getTriple(), SuppressError));
4461
0
          }
4462
0
        } else {
4463
0
          StringRef ArchStr = getCanonicalArchString(
4464
0
              C, Args, Arch, TC->getTriple(), SuppressError);
4465
0
          if (ArchStr.empty())
4466
0
            return Archs;
4467
0
          Archs.insert(ArchStr);
4468
0
        }
4469
0
      }
4470
0
    } else if (Arg->getOption().matches(options::OPT_no_offload_arch_EQ)) {
4471
0
      for (StringRef Arch : llvm::split(Arg->getValue(), ",")) {
4472
0
        if (Arch == "all") {
4473
0
          Archs.clear();
4474
0
        } else {
4475
0
          StringRef ArchStr = getCanonicalArchString(
4476
0
              C, Args, Arch, TC->getTriple(), SuppressError);
4477
0
          if (ArchStr.empty())
4478
0
            return Archs;
4479
0
          Archs.erase(ArchStr);
4480
0
        }
4481
0
      }
4482
0
    }
4483
0
  }
4484
4485
0
  if (auto ConflictingArchs =
4486
0
          getConflictOffloadArchCombination(Archs, TC->getTriple())) {
4487
0
    C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo)
4488
0
        << ConflictingArchs->first << ConflictingArchs->second;
4489
0
    C.setContainsError();
4490
0
  }
4491
4492
  // Skip filling defaults if we're just querying what is availible.
4493
0
  if (SuppressError)
4494
0
    return Archs;
4495
4496
0
  if (Archs.empty()) {
4497
0
    if (Kind == Action::OFK_Cuda)
4498
0
      Archs.insert(CudaArchToString(CudaArch::CudaDefault));
4499
0
    else if (Kind == Action::OFK_HIP)
4500
0
      Archs.insert(CudaArchToString(CudaArch::HIPDefault));
4501
0
    else if (Kind == Action::OFK_OpenMP)
4502
0
      Archs.insert(StringRef());
4503
0
  } else {
4504
0
    Args.ClaimAllArgs(options::OPT_offload_arch_EQ);
4505
0
    Args.ClaimAllArgs(options::OPT_no_offload_arch_EQ);
4506
0
  }
4507
4508
0
  return Archs;
4509
0
}
4510
4511
Action *Driver::BuildOffloadingActions(Compilation &C,
4512
                                       llvm::opt::DerivedArgList &Args,
4513
                                       const InputTy &Input,
4514
0
                                       Action *HostAction) const {
4515
  // Don't build offloading actions if explicitly disabled or we do not have a
4516
  // valid source input and compile action to embed it in. If preprocessing only
4517
  // ignore embedding.
4518
0
  if (offloadHostOnly() || !types::isSrcFile(Input.first) ||
4519
0
      !(isa<CompileJobAction>(HostAction) ||
4520
0
        getFinalPhase(Args) == phases::Preprocess))
4521
0
    return HostAction;
4522
4523
0
  ActionList OffloadActions;
4524
0
  OffloadAction::DeviceDependences DDeps;
4525
4526
0
  const Action::OffloadKind OffloadKinds[] = {
4527
0
      Action::OFK_OpenMP, Action::OFK_Cuda, Action::OFK_HIP};
4528
4529
0
  for (Action::OffloadKind Kind : OffloadKinds) {
4530
0
    SmallVector<const ToolChain *, 2> ToolChains;
4531
0
    ActionList DeviceActions;
4532
4533
0
    auto TCRange = C.getOffloadToolChains(Kind);
4534
0
    for (auto TI = TCRange.first, TE = TCRange.second; TI != TE; ++TI)
4535
0
      ToolChains.push_back(TI->second);
4536
4537
0
    if (ToolChains.empty())
4538
0
      continue;
4539
4540
0
    types::ID InputType = Input.first;
4541
0
    const Arg *InputArg = Input.second;
4542
4543
    // The toolchain can be active for unsupported file types.
4544
0
    if ((Kind == Action::OFK_Cuda && !types::isCuda(InputType)) ||
4545
0
        (Kind == Action::OFK_HIP && !types::isHIP(InputType)))
4546
0
      continue;
4547
4548
    // Get the product of all bound architectures and toolchains.
4549
0
    SmallVector<std::pair<const ToolChain *, StringRef>> TCAndArchs;
4550
0
    for (const ToolChain *TC : ToolChains)
4551
0
      for (StringRef Arch : getOffloadArchs(C, Args, Kind, TC))
4552
0
        TCAndArchs.push_back(std::make_pair(TC, Arch));
4553
4554
0
    for (unsigned I = 0, E = TCAndArchs.size(); I != E; ++I)
4555
0
      DeviceActions.push_back(C.MakeAction<InputAction>(*InputArg, InputType));
4556
4557
0
    if (DeviceActions.empty())
4558
0
      return HostAction;
4559
4560
0
    auto PL = types::getCompilationPhases(*this, Args, InputType);
4561
4562
0
    for (phases::ID Phase : PL) {
4563
0
      if (Phase == phases::Link) {
4564
0
        assert(Phase == PL.back() && "linking must be final compilation step.");
4565
0
        break;
4566
0
      }
4567
4568
0
      auto TCAndArch = TCAndArchs.begin();
4569
0
      for (Action *&A : DeviceActions) {
4570
0
        if (A->getType() == types::TY_Nothing)
4571
0
          continue;
4572
4573
        // Propagate the ToolChain so we can use it in ConstructPhaseAction.
4574
0
        A->propagateDeviceOffloadInfo(Kind, TCAndArch->second.data(),
4575
0
                                      TCAndArch->first);
4576
0
        A = ConstructPhaseAction(C, Args, Phase, A, Kind);
4577
4578
0
        if (isa<CompileJobAction>(A) && isa<CompileJobAction>(HostAction) &&
4579
0
            Kind == Action::OFK_OpenMP &&
4580
0
            HostAction->getType() != types::TY_Nothing) {
4581
          // OpenMP offloading has a dependency on the host compile action to
4582
          // identify which declarations need to be emitted. This shouldn't be
4583
          // collapsed with any other actions so we can use it in the device.
4584
0
          HostAction->setCannotBeCollapsedWithNextDependentAction();
4585
0
          OffloadAction::HostDependence HDep(
4586
0
              *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4587
0
              TCAndArch->second.data(), Kind);
4588
0
          OffloadAction::DeviceDependences DDep;
4589
0
          DDep.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4590
0
          A = C.MakeAction<OffloadAction>(HDep, DDep);
4591
0
        }
4592
4593
0
        ++TCAndArch;
4594
0
      }
4595
0
    }
4596
4597
    // Compiling HIP in non-RDC mode requires linking each action individually.
4598
0
    for (Action *&A : DeviceActions) {
4599
0
      if ((A->getType() != types::TY_Object &&
4600
0
           A->getType() != types::TY_LTO_BC) ||
4601
0
          Kind != Action::OFK_HIP ||
4602
0
          Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
4603
0
        continue;
4604
0
      ActionList LinkerInput = {A};
4605
0
      A = C.MakeAction<LinkJobAction>(LinkerInput, types::TY_Image);
4606
0
    }
4607
4608
0
    auto TCAndArch = TCAndArchs.begin();
4609
0
    for (Action *A : DeviceActions) {
4610
0
      DDeps.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4611
0
      OffloadAction::DeviceDependences DDep;
4612
0
      DDep.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4613
0
      OffloadActions.push_back(C.MakeAction<OffloadAction>(DDep, A->getType()));
4614
0
      ++TCAndArch;
4615
0
    }
4616
0
  }
4617
4618
0
  if (offloadDeviceOnly())
4619
0
    return C.MakeAction<OffloadAction>(DDeps, types::TY_Nothing);
4620
4621
0
  if (OffloadActions.empty())
4622
0
    return HostAction;
4623
4624
0
  OffloadAction::DeviceDependences DDep;
4625
0
  if (C.isOffloadingHostKind(Action::OFK_Cuda) &&
4626
0
      !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) {
4627
    // If we are not in RDC-mode we just emit the final CUDA fatbinary for
4628
    // each translation unit without requiring any linking.
4629
0
    Action *FatbinAction =
4630
0
        C.MakeAction<LinkJobAction>(OffloadActions, types::TY_CUDA_FATBIN);
4631
0
    DDep.add(*FatbinAction, *C.getSingleOffloadToolChain<Action::OFK_Cuda>(),
4632
0
             nullptr, Action::OFK_Cuda);
4633
0
  } else if (C.isOffloadingHostKind(Action::OFK_HIP) &&
4634
0
             !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4635
0
                           false)) {
4636
    // If we are not in RDC-mode we just emit the final HIP fatbinary for each
4637
    // translation unit, linking each input individually.
4638
0
    Action *FatbinAction =
4639
0
        C.MakeAction<LinkJobAction>(OffloadActions, types::TY_HIP_FATBIN);
4640
0
    DDep.add(*FatbinAction, *C.getSingleOffloadToolChain<Action::OFK_HIP>(),
4641
0
             nullptr, Action::OFK_HIP);
4642
0
  } else {
4643
    // Package all the offloading actions into a single output that can be
4644
    // embedded in the host and linked.
4645
0
    Action *PackagerAction =
4646
0
        C.MakeAction<OffloadPackagerJobAction>(OffloadActions, types::TY_Image);
4647
0
    DDep.add(*PackagerAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4648
0
             nullptr, C.getActiveOffloadKinds());
4649
0
  }
4650
4651
  // If we are unable to embed a single device output into the host, we need to
4652
  // add each device output as a host dependency to ensure they are still built.
4653
0
  bool SingleDeviceOutput = !llvm::any_of(OffloadActions, [](Action *A) {
4654
0
    return A->getType() == types::TY_Nothing;
4655
0
  }) && isa<CompileJobAction>(HostAction);
4656
0
  OffloadAction::HostDependence HDep(
4657
0
      *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4658
0
      /*BoundArch=*/nullptr, SingleDeviceOutput ? DDep : DDeps);
4659
0
  return C.MakeAction<OffloadAction>(HDep, SingleDeviceOutput ? DDep : DDeps);
4660
0
}
4661
4662
Action *Driver::ConstructPhaseAction(
4663
    Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
4664
0
    Action::OffloadKind TargetDeviceOffloadKind) const {
4665
0
  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
4666
4667
  // Some types skip the assembler phase (e.g., llvm-bc), but we can't
4668
  // encode this in the steps because the intermediate type depends on
4669
  // arguments. Just special case here.
4670
0
  if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
4671
0
    return Input;
4672
4673
  // Build the appropriate action.
4674
0
  switch (Phase) {
4675
0
  case phases::Link:
4676
0
    llvm_unreachable("link action invalid here.");
4677
0
  case phases::IfsMerge:
4678
0
    llvm_unreachable("ifsmerge action invalid here.");
4679
0
  case phases::Preprocess: {
4680
0
    types::ID OutputTy;
4681
    // -M and -MM specify the dependency file name by altering the output type,
4682
    // -if -MD and -MMD are not specified.
4683
0
    if (Args.hasArg(options::OPT_M, options::OPT_MM) &&
4684
0
        !Args.hasArg(options::OPT_MD, options::OPT_MMD)) {
4685
0
      OutputTy = types::TY_Dependencies;
4686
0
    } else {
4687
0
      OutputTy = Input->getType();
4688
      // For these cases, the preprocessor is only translating forms, the Output
4689
      // still needs preprocessing.
4690
0
      if (!Args.hasFlag(options::OPT_frewrite_includes,
4691
0
                        options::OPT_fno_rewrite_includes, false) &&
4692
0
          !Args.hasFlag(options::OPT_frewrite_imports,
4693
0
                        options::OPT_fno_rewrite_imports, false) &&
4694
0
          !Args.hasFlag(options::OPT_fdirectives_only,
4695
0
                        options::OPT_fno_directives_only, false) &&
4696
0
          !CCGenDiagnostics)
4697
0
        OutputTy = types::getPreprocessedType(OutputTy);
4698
0
      assert(OutputTy != types::TY_INVALID &&
4699
0
             "Cannot preprocess this input type!");
4700
0
    }
4701
0
    return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
4702
0
  }
4703
0
  case phases::Precompile: {
4704
    // API extraction should not generate an actual precompilation action.
4705
0
    if (Args.hasArg(options::OPT_extract_api))
4706
0
      return C.MakeAction<ExtractAPIJobAction>(Input, types::TY_API_INFO);
4707
4708
0
    types::ID OutputTy = getPrecompiledType(Input->getType());
4709
0
    assert(OutputTy != types::TY_INVALID &&
4710
0
           "Cannot precompile this input type!");
4711
4712
    // If we're given a module name, precompile header file inputs as a
4713
    // module, not as a precompiled header.
4714
0
    const char *ModName = nullptr;
4715
0
    if (OutputTy == types::TY_PCH) {
4716
0
      if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
4717
0
        ModName = A->getValue();
4718
0
      if (ModName)
4719
0
        OutputTy = types::TY_ModuleFile;
4720
0
    }
4721
4722
0
    if (Args.hasArg(options::OPT_fsyntax_only)) {
4723
      // Syntax checks should not emit a PCH file
4724
0
      OutputTy = types::TY_Nothing;
4725
0
    }
4726
4727
0
    return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
4728
0
  }
4729
0
  case phases::Compile: {
4730
0
    if (Args.hasArg(options::OPT_fsyntax_only))
4731
0
      return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
4732
0
    if (Args.hasArg(options::OPT_rewrite_objc))
4733
0
      return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
4734
0
    if (Args.hasArg(options::OPT_rewrite_legacy_objc))
4735
0
      return C.MakeAction<CompileJobAction>(Input,
4736
0
                                            types::TY_RewrittenLegacyObjC);
4737
0
    if (Args.hasArg(options::OPT__analyze))
4738
0
      return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
4739
0
    if (Args.hasArg(options::OPT__migrate))
4740
0
      return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
4741
0
    if (Args.hasArg(options::OPT_emit_ast))
4742
0
      return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
4743
0
    if (Args.hasArg(options::OPT_module_file_info))
4744
0
      return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
4745
0
    if (Args.hasArg(options::OPT_verify_pch))
4746
0
      return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
4747
0
    if (Args.hasArg(options::OPT_extract_api))
4748
0
      return C.MakeAction<ExtractAPIJobAction>(Input, types::TY_API_INFO);
4749
0
    return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
4750
0
  }
4751
0
  case phases::Backend: {
4752
0
    if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
4753
0
      types::ID Output;
4754
0
      if (Args.hasArg(options::OPT_S))
4755
0
        Output = types::TY_LTO_IR;
4756
0
      else if (Args.hasArg(options::OPT_ffat_lto_objects))
4757
0
        Output = types::TY_PP_Asm;
4758
0
      else
4759
0
        Output = types::TY_LTO_BC;
4760
0
      return C.MakeAction<BackendJobAction>(Input, Output);
4761
0
    }
4762
0
    if (isUsingLTO(/* IsOffload */ true) &&
4763
0
        TargetDeviceOffloadKind != Action::OFK_None) {
4764
0
      types::ID Output =
4765
0
          Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
4766
0
      return C.MakeAction<BackendJobAction>(Input, Output);
4767
0
    }
4768
0
    if (Args.hasArg(options::OPT_emit_llvm) ||
4769
0
        (((Input->getOffloadingToolChain() &&
4770
0
           Input->getOffloadingToolChain()->getTriple().isAMDGPU()) ||
4771
0
          TargetDeviceOffloadKind == Action::OFK_HIP) &&
4772
0
         (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4773
0
                       false) ||
4774
0
          TargetDeviceOffloadKind == Action::OFK_OpenMP))) {
4775
0
      types::ID Output =
4776
0
          Args.hasArg(options::OPT_S) &&
4777
0
                  (TargetDeviceOffloadKind == Action::OFK_None ||
4778
0
                   offloadDeviceOnly() ||
4779
0
                   (TargetDeviceOffloadKind == Action::OFK_HIP &&
4780
0
                    !Args.hasFlag(options::OPT_offload_new_driver,
4781
0
                                  options::OPT_no_offload_new_driver, false)))
4782
0
              ? types::TY_LLVM_IR
4783
0
              : types::TY_LLVM_BC;
4784
0
      return C.MakeAction<BackendJobAction>(Input, Output);
4785
0
    }
4786
0
    return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
4787
0
  }
4788
0
  case phases::Assemble:
4789
0
    return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
4790
0
  }
4791
4792
0
  llvm_unreachable("invalid phase in ConstructPhaseAction");
4793
0
}
4794
4795
0
void Driver::BuildJobs(Compilation &C) const {
4796
0
  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
4797
4798
0
  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4799
4800
  // It is an error to provide a -o option if we are making multiple output
4801
  // files. There are exceptions:
4802
  //
4803
  // IfsMergeJob: when generating interface stubs enabled we want to be able to
4804
  // generate the stub file at the same time that we generate the real
4805
  // library/a.out. So when a .o, .so, etc are the output, with clang interface
4806
  // stubs there will also be a .ifs and .ifso at the same location.
4807
  //
4808
  // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled
4809
  // and -c is passed, we still want to be able to generate a .ifs file while
4810
  // we are also generating .o files. So we allow more than one output file in
4811
  // this case as well.
4812
  //
4813
  // OffloadClass of type TY_Nothing: device-only output will place many outputs
4814
  // into a single offloading action. We should count all inputs to the action
4815
  // as outputs. Also ignore device-only outputs if we're compiling with
4816
  // -fsyntax-only.
4817
0
  if (FinalOutput) {
4818
0
    unsigned NumOutputs = 0;
4819
0
    unsigned NumIfsOutputs = 0;
4820
0
    for (const Action *A : C.getActions()) {
4821
0
      if (A->getType() != types::TY_Nothing &&
4822
0
          A->getType() != types::TY_DX_CONTAINER &&
4823
0
          !(A->getKind() == Action::IfsMergeJobClass ||
4824
0
            (A->getType() == clang::driver::types::TY_IFS_CPP &&
4825
0
             A->getKind() == clang::driver::Action::CompileJobClass &&
4826
0
             0 == NumIfsOutputs++) ||
4827
0
            (A->getKind() == Action::BindArchClass && A->getInputs().size() &&
4828
0
             A->getInputs().front()->getKind() == Action::IfsMergeJobClass)))
4829
0
        ++NumOutputs;
4830
0
      else if (A->getKind() == Action::OffloadClass &&
4831
0
               A->getType() == types::TY_Nothing &&
4832
0
               !C.getArgs().hasArg(options::OPT_fsyntax_only))
4833
0
        NumOutputs += A->size();
4834
0
    }
4835
4836
0
    if (NumOutputs > 1) {
4837
0
      Diag(clang::diag::err_drv_output_argument_with_multiple_files);
4838
0
      FinalOutput = nullptr;
4839
0
    }
4840
0
  }
4841
4842
0
  const llvm::Triple &RawTriple = C.getDefaultToolChain().getTriple();
4843
4844
  // Collect the list of architectures.
4845
0
  llvm::StringSet<> ArchNames;
4846
0
  if (RawTriple.isOSBinFormatMachO())
4847
0
    for (const Arg *A : C.getArgs())
4848
0
      if (A->getOption().matches(options::OPT_arch))
4849
0
        ArchNames.insert(A->getValue());
4850
4851
  // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
4852
0
  std::map<std::pair<const Action *, std::string>, InputInfoList> CachedResults;
4853
0
  for (Action *A : C.getActions()) {
4854
    // If we are linking an image for multiple archs then the linker wants
4855
    // -arch_multiple and -final_output <final image name>. Unfortunately, this
4856
    // doesn't fit in cleanly because we have to pass this information down.
4857
    //
4858
    // FIXME: This is a hack; find a cleaner way to integrate this into the
4859
    // process.
4860
0
    const char *LinkingOutput = nullptr;
4861
0
    if (isa<LipoJobAction>(A)) {
4862
0
      if (FinalOutput)
4863
0
        LinkingOutput = FinalOutput->getValue();
4864
0
      else
4865
0
        LinkingOutput = getDefaultImageName();
4866
0
    }
4867
4868
0
    BuildJobsForAction(C, A, &C.getDefaultToolChain(),
4869
0
                       /*BoundArch*/ StringRef(),
4870
0
                       /*AtTopLevel*/ true,
4871
0
                       /*MultipleArchs*/ ArchNames.size() > 1,
4872
0
                       /*LinkingOutput*/ LinkingOutput, CachedResults,
4873
0
                       /*TargetDeviceOffloadKind*/ Action::OFK_None);
4874
0
  }
4875
4876
  // If we have more than one job, then disable integrated-cc1 for now. Do this
4877
  // also when we need to report process execution statistics.
4878
0
  if (C.getJobs().size() > 1 || CCPrintProcessStats)
4879
0
    for (auto &J : C.getJobs())
4880
0
      J.InProcess = false;
4881
4882
0
  if (CCPrintProcessStats) {
4883
0
    C.setPostCallback([=](const Command &Cmd, int Res) {
4884
0
      std::optional<llvm::sys::ProcessStatistics> ProcStat =
4885
0
          Cmd.getProcessStatistics();
4886
0
      if (!ProcStat)
4887
0
        return;
4888
4889
0
      const char *LinkingOutput = nullptr;
4890
0
      if (FinalOutput)
4891
0
        LinkingOutput = FinalOutput->getValue();
4892
0
      else if (!Cmd.getOutputFilenames().empty())
4893
0
        LinkingOutput = Cmd.getOutputFilenames().front().c_str();
4894
0
      else
4895
0
        LinkingOutput = getDefaultImageName();
4896
4897
0
      if (CCPrintStatReportFilename.empty()) {
4898
0
        using namespace llvm;
4899
        // Human readable output.
4900
0
        outs() << sys::path::filename(Cmd.getExecutable()) << ": "
4901
0
               << "output=" << LinkingOutput;
4902
0
        outs() << ", total="
4903
0
               << format("%.3f", ProcStat->TotalTime.count() / 1000.) << " ms"
4904
0
               << ", user="
4905
0
               << format("%.3f", ProcStat->UserTime.count() / 1000.) << " ms"
4906
0
               << ", mem=" << ProcStat->PeakMemory << " Kb\n";
4907
0
      } else {
4908
        // CSV format.
4909
0
        std::string Buffer;
4910
0
        llvm::raw_string_ostream Out(Buffer);
4911
0
        llvm::sys::printArg(Out, llvm::sys::path::filename(Cmd.getExecutable()),
4912
0
                            /*Quote*/ true);
4913
0
        Out << ',';
4914
0
        llvm::sys::printArg(Out, LinkingOutput, true);
4915
0
        Out << ',' << ProcStat->TotalTime.count() << ','
4916
0
            << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory
4917
0
            << '\n';
4918
0
        Out.flush();
4919
0
        std::error_code EC;
4920
0
        llvm::raw_fd_ostream OS(CCPrintStatReportFilename, EC,
4921
0
                                llvm::sys::fs::OF_Append |
4922
0
                                    llvm::sys::fs::OF_Text);
4923
0
        if (EC)
4924
0
          return;
4925
0
        auto L = OS.lock();
4926
0
        if (!L) {
4927
0
          llvm::errs() << "ERROR: Cannot lock file "
4928
0
                       << CCPrintStatReportFilename << ": "
4929
0
                       << toString(L.takeError()) << "\n";
4930
0
          return;
4931
0
        }
4932
0
        OS << Buffer;
4933
0
        OS.flush();
4934
0
      }
4935
0
    });
4936
0
  }
4937
4938
  // If the user passed -Qunused-arguments or there were errors, don't warn
4939
  // about any unused arguments.
4940
0
  if (Diags.hasErrorOccurred() ||
4941
0
      C.getArgs().hasArg(options::OPT_Qunused_arguments))
4942
0
    return;
4943
4944
  // Claim -fdriver-only here.
4945
0
  (void)C.getArgs().hasArg(options::OPT_fdriver_only);
4946
  // Claim -### here.
4947
0
  (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
4948
4949
  // Claim --driver-mode, --rsp-quoting, it was handled earlier.
4950
0
  (void)C.getArgs().hasArg(options::OPT_driver_mode);
4951
0
  (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
4952
4953
0
  bool HasAssembleJob = llvm::any_of(C.getJobs(), [](auto &J) {
4954
    // Match ClangAs and other derived assemblers of Tool. ClangAs uses a
4955
    // longer ShortName "clang integrated assembler" while other assemblers just
4956
    // use "assembler".
4957
0
    return strstr(J.getCreator().getShortName(), "assembler");
4958
0
  });
4959
0
  for (Arg *A : C.getArgs()) {
4960
    // FIXME: It would be nice to be able to send the argument to the
4961
    // DiagnosticsEngine, so that extra values, position, and so on could be
4962
    // printed.
4963
0
    if (!A->isClaimed()) {
4964
0
      if (A->getOption().hasFlag(options::NoArgumentUnused))
4965
0
        continue;
4966
4967
      // Suppress the warning automatically if this is just a flag, and it is an
4968
      // instance of an argument we already claimed.
4969
0
      const Option &Opt = A->getOption();
4970
0
      if (Opt.getKind() == Option::FlagClass) {
4971
0
        bool DuplicateClaimed = false;
4972
4973
0
        for (const Arg *AA : C.getArgs().filtered(&Opt)) {
4974
0
          if (AA->isClaimed()) {
4975
0
            DuplicateClaimed = true;
4976
0
            break;
4977
0
          }
4978
0
        }
4979
4980
0
        if (DuplicateClaimed)
4981
0
          continue;
4982
0
      }
4983
4984
      // In clang-cl, don't mention unknown arguments here since they have
4985
      // already been warned about.
4986
0
      if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN)) {
4987
0
        if (A->getOption().hasFlag(options::TargetSpecific) &&
4988
0
            !A->isIgnoredTargetSpecific() && !HasAssembleJob &&
4989
            // When for example -### or -v is used
4990
            // without a file, target specific options are not
4991
            // consumed/validated.
4992
            // Instead emitting an error emit a warning instead.
4993
0
            !C.getActions().empty()) {
4994
0
          Diag(diag::err_drv_unsupported_opt_for_target)
4995
0
              << A->getSpelling() << getTargetTriple();
4996
0
        } else {
4997
0
          Diag(clang::diag::warn_drv_unused_argument)
4998
0
              << A->getAsString(C.getArgs());
4999
0
        }
5000
0
      }
5001
0
    }
5002
0
  }
5003
0
}
5004
5005
namespace {
5006
/// Utility class to control the collapse of dependent actions and select the
5007
/// tools accordingly.
5008
class ToolSelector final {
5009
  /// The tool chain this selector refers to.
5010
  const ToolChain &TC;
5011
5012
  /// The compilation this selector refers to.
5013
  const Compilation &C;
5014
5015
  /// The base action this selector refers to.
5016
  const JobAction *BaseAction;
5017
5018
  /// Set to true if the current toolchain refers to host actions.
5019
  bool IsHostSelector;
5020
5021
  /// Set to true if save-temps and embed-bitcode functionalities are active.
5022
  bool SaveTemps;
5023
  bool EmbedBitcode;
5024
5025
  /// Get previous dependent action or null if that does not exist. If
5026
  /// \a CanBeCollapsed is false, that action must be legal to collapse or
5027
  /// null will be returned.
5028
  const JobAction *getPrevDependentAction(const ActionList &Inputs,
5029
                                          ActionList &SavedOffloadAction,
5030
0
                                          bool CanBeCollapsed = true) {
5031
    // An option can be collapsed only if it has a single input.
5032
0
    if (Inputs.size() != 1)
5033
0
      return nullptr;
5034
5035
0
    Action *CurAction = *Inputs.begin();
5036
0
    if (CanBeCollapsed &&
5037
0
        !CurAction->isCollapsingWithNextDependentActionLegal())
5038
0
      return nullptr;
5039
5040
    // If the input action is an offload action. Look through it and save any
5041
    // offload action that can be dropped in the event of a collapse.
5042
0
    if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
5043
      // If the dependent action is a device action, we will attempt to collapse
5044
      // only with other device actions. Otherwise, we would do the same but
5045
      // with host actions only.
5046
0
      if (!IsHostSelector) {
5047
0
        if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
5048
0
          CurAction =
5049
0
              OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
5050
0
          if (CanBeCollapsed &&
5051
0
              !CurAction->isCollapsingWithNextDependentActionLegal())
5052
0
            return nullptr;
5053
0
          SavedOffloadAction.push_back(OA);
5054
0
          return dyn_cast<JobAction>(CurAction);
5055
0
        }
5056
0
      } else if (OA->hasHostDependence()) {
5057
0
        CurAction = OA->getHostDependence();
5058
0
        if (CanBeCollapsed &&
5059
0
            !CurAction->isCollapsingWithNextDependentActionLegal())
5060
0
          return nullptr;
5061
0
        SavedOffloadAction.push_back(OA);
5062
0
        return dyn_cast<JobAction>(CurAction);
5063
0
      }
5064
0
      return nullptr;
5065
0
    }
5066
5067
0
    return dyn_cast<JobAction>(CurAction);
5068
0
  }
5069
5070
  /// Return true if an assemble action can be collapsed.
5071
0
  bool canCollapseAssembleAction() const {
5072
0
    return TC.useIntegratedAs() && !SaveTemps &&
5073
0
           !C.getArgs().hasArg(options::OPT_via_file_asm) &&
5074
0
           !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
5075
0
           !C.getArgs().hasArg(options::OPT__SLASH_Fa) &&
5076
0
           !C.getArgs().hasArg(options::OPT_dxc_Fc);
5077
0
  }
5078
5079
  /// Return true if a preprocessor action can be collapsed.
5080
0
  bool canCollapsePreprocessorAction() const {
5081
0
    return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
5082
0
           !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
5083
0
           !C.getArgs().hasArg(options::OPT_rewrite_objc);
5084
0
  }
5085
5086
  /// Struct that relates an action with the offload actions that would be
5087
  /// collapsed with it.
5088
  struct JobActionInfo final {
5089
    /// The action this info refers to.
5090
    const JobAction *JA = nullptr;
5091
    /// The offload actions we need to take care off if this action is
5092
    /// collapsed.
5093
    ActionList SavedOffloadAction;
5094
  };
5095
5096
  /// Append collapsed offload actions from the give nnumber of elements in the
5097
  /// action info array.
5098
  static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
5099
                                           ArrayRef<JobActionInfo> &ActionInfo,
5100
0
                                           unsigned ElementNum) {
5101
0
    assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
5102
0
    for (unsigned I = 0; I < ElementNum; ++I)
5103
0
      CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
5104
0
                                    ActionInfo[I].SavedOffloadAction.end());
5105
0
  }
5106
5107
  /// Functions that attempt to perform the combining. They detect if that is
5108
  /// legal, and if so they update the inputs \a Inputs and the offload action
5109
  /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
5110
  /// the combined action is returned. If the combining is not legal or if the
5111
  /// tool does not exist, null is returned.
5112
  /// Currently three kinds of collapsing are supported:
5113
  ///  - Assemble + Backend + Compile;
5114
  ///  - Assemble + Backend ;
5115
  ///  - Backend + Compile.
5116
  const Tool *
5117
  combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
5118
                                ActionList &Inputs,
5119
0
                                ActionList &CollapsedOffloadAction) {
5120
0
    if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
5121
0
      return nullptr;
5122
0
    auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
5123
0
    auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
5124
0
    auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
5125
0
    if (!AJ || !BJ || !CJ)
5126
0
      return nullptr;
5127
5128
    // Get compiler tool.
5129
0
    const Tool *T = TC.SelectTool(*CJ);
5130
0
    if (!T)
5131
0
      return nullptr;
5132
5133
    // Can't collapse if we don't have codegen support unless we are
5134
    // emitting LLVM IR.
5135
0
    bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType());
5136
0
    if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR()))
5137
0
      return nullptr;
5138
5139
    // When using -fembed-bitcode, it is required to have the same tool (clang)
5140
    // for both CompilerJA and BackendJA. Otherwise, combine two stages.
5141
0
    if (EmbedBitcode) {
5142
0
      const Tool *BT = TC.SelectTool(*BJ);
5143
0
      if (BT == T)
5144
0
        return nullptr;
5145
0
    }
5146
5147
0
    if (!T->hasIntegratedAssembler())
5148
0
      return nullptr;
5149
5150
0
    Inputs = CJ->getInputs();
5151
0
    AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
5152
0
                                 /*NumElements=*/3);
5153
0
    return T;
5154
0
  }
5155
  const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
5156
                                     ActionList &Inputs,
5157
0
                                     ActionList &CollapsedOffloadAction) {
5158
0
    if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
5159
0
      return nullptr;
5160
0
    auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
5161
0
    auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
5162
0
    if (!AJ || !BJ)
5163
0
      return nullptr;
5164
5165
    // Get backend tool.
5166
0
    const Tool *T = TC.SelectTool(*BJ);
5167
0
    if (!T)
5168
0
      return nullptr;
5169
5170
0
    if (!T->hasIntegratedAssembler())
5171
0
      return nullptr;
5172
5173
0
    Inputs = BJ->getInputs();
5174
0
    AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
5175
0
                                 /*NumElements=*/2);
5176
0
    return T;
5177
0
  }
5178
  const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
5179
                                    ActionList &Inputs,
5180
0
                                    ActionList &CollapsedOffloadAction) {
5181
0
    if (ActionInfo.size() < 2)
5182
0
      return nullptr;
5183
0
    auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
5184
0
    auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
5185
0
    if (!BJ || !CJ)
5186
0
      return nullptr;
5187
5188
    // Check if the initial input (to the compile job or its predessor if one
5189
    // exists) is LLVM bitcode. In that case, no preprocessor step is required
5190
    // and we can still collapse the compile and backend jobs when we have
5191
    // -save-temps. I.e. there is no need for a separate compile job just to
5192
    // emit unoptimized bitcode.
5193
0
    bool InputIsBitcode = true;
5194
0
    for (size_t i = 1; i < ActionInfo.size(); i++)
5195
0
      if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
5196
0
          ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
5197
0
        InputIsBitcode = false;
5198
0
        break;
5199
0
      }
5200
0
    if (!InputIsBitcode && !canCollapsePreprocessorAction())
5201
0
      return nullptr;
5202
5203
    // Get compiler tool.
5204
0
    const Tool *T = TC.SelectTool(*CJ);
5205
0
    if (!T)
5206
0
      return nullptr;
5207
5208
    // Can't collapse if we don't have codegen support unless we are
5209
    // emitting LLVM IR.
5210
0
    bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType());
5211
0
    if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR()))
5212
0
      return nullptr;
5213
5214
0
    if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
5215
0
      return nullptr;
5216
5217
0
    Inputs = CJ->getInputs();
5218
0
    AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
5219
0
                                 /*NumElements=*/2);
5220
0
    return T;
5221
0
  }
5222
5223
  /// Updates the inputs if the obtained tool supports combining with
5224
  /// preprocessor action, and the current input is indeed a preprocessor
5225
  /// action. If combining results in the collapse of offloading actions, those
5226
  /// are appended to \a CollapsedOffloadAction.
5227
  void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
5228
0
                               ActionList &CollapsedOffloadAction) {
5229
0
    if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
5230
0
      return;
5231
5232
    // Attempt to get a preprocessor action dependence.
5233
0
    ActionList PreprocessJobOffloadActions;
5234
0
    ActionList NewInputs;
5235
0
    for (Action *A : Inputs) {
5236
0
      auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
5237
0
      if (!PJ || !isa<PreprocessJobAction>(PJ)) {
5238
0
        NewInputs.push_back(A);
5239
0
        continue;
5240
0
      }
5241
5242
      // This is legal to combine. Append any offload action we found and add the
5243
      // current input to preprocessor inputs.
5244
0
      CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
5245
0
                                    PreprocessJobOffloadActions.end());
5246
0
      NewInputs.append(PJ->input_begin(), PJ->input_end());
5247
0
    }
5248
0
    Inputs = NewInputs;
5249
0
  }
5250
5251
public:
5252
  ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
5253
               const Compilation &C, bool SaveTemps, bool EmbedBitcode)
5254
      : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
5255
0
        EmbedBitcode(EmbedBitcode) {
5256
0
    assert(BaseAction && "Invalid base action.");
5257
0
    IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
5258
0
  }
5259
5260
  /// Check if a chain of actions can be combined and return the tool that can
5261
  /// handle the combination of actions. The pointer to the current inputs \a
5262
  /// Inputs and the list of offload actions \a CollapsedOffloadActions
5263
  /// connected to collapsed actions are updated accordingly. The latter enables
5264
  /// the caller of the selector to process them afterwards instead of just
5265
  /// dropping them. If no suitable tool is found, null will be returned.
5266
  const Tool *getTool(ActionList &Inputs,
5267
0
                      ActionList &CollapsedOffloadAction) {
5268
    //
5269
    // Get the largest chain of actions that we could combine.
5270
    //
5271
5272
0
    SmallVector<JobActionInfo, 5> ActionChain(1);
5273
0
    ActionChain.back().JA = BaseAction;
5274
0
    while (ActionChain.back().JA) {
5275
0
      const Action *CurAction = ActionChain.back().JA;
5276
5277
      // Grow the chain by one element.
5278
0
      ActionChain.resize(ActionChain.size() + 1);
5279
0
      JobActionInfo &AI = ActionChain.back();
5280
5281
      // Attempt to fill it with the
5282
0
      AI.JA =
5283
0
          getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
5284
0
    }
5285
5286
    // Pop the last action info as it could not be filled.
5287
0
    ActionChain.pop_back();
5288
5289
    //
5290
    // Attempt to combine actions. If all combining attempts failed, just return
5291
    // the tool of the provided action. At the end we attempt to combine the
5292
    // action with any preprocessor action it may depend on.
5293
    //
5294
5295
0
    const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
5296
0
                                                  CollapsedOffloadAction);
5297
0
    if (!T)
5298
0
      T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
5299
0
    if (!T)
5300
0
      T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
5301
0
    if (!T) {
5302
0
      Inputs = BaseAction->getInputs();
5303
0
      T = TC.SelectTool(*BaseAction);
5304
0
    }
5305
5306
0
    combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
5307
0
    return T;
5308
0
  }
5309
};
5310
}
5311
5312
/// Return a string that uniquely identifies the result of a job. The bound arch
5313
/// is not necessarily represented in the toolchain's triple -- for example,
5314
/// armv7 and armv7s both map to the same triple -- so we need both in our map.
5315
/// Also, we need to add the offloading device kind, as the same tool chain can
5316
/// be used for host and device for some programming models, e.g. OpenMP.
5317
static std::string GetTriplePlusArchString(const ToolChain *TC,
5318
                                           StringRef BoundArch,
5319
0
                                           Action::OffloadKind OffloadKind) {
5320
0
  std::string TriplePlusArch = TC->getTriple().normalize();
5321
0
  if (!BoundArch.empty()) {
5322
0
    TriplePlusArch += "-";
5323
0
    TriplePlusArch += BoundArch;
5324
0
  }
5325
0
  TriplePlusArch += "-";
5326
0
  TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
5327
0
  return TriplePlusArch;
5328
0
}
5329
5330
InputInfoList Driver::BuildJobsForAction(
5331
    Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
5332
    bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
5333
    std::map<std::pair<const Action *, std::string>, InputInfoList>
5334
        &CachedResults,
5335
0
    Action::OffloadKind TargetDeviceOffloadKind) const {
5336
0
  std::pair<const Action *, std::string> ActionTC = {
5337
0
      A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
5338
0
  auto CachedResult = CachedResults.find(ActionTC);
5339
0
  if (CachedResult != CachedResults.end()) {
5340
0
    return CachedResult->second;
5341
0
  }
5342
0
  InputInfoList Result = BuildJobsForActionNoCache(
5343
0
      C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
5344
0
      CachedResults, TargetDeviceOffloadKind);
5345
0
  CachedResults[ActionTC] = Result;
5346
0
  return Result;
5347
0
}
5348
5349
static void handleTimeTrace(Compilation &C, const ArgList &Args,
5350
                            const JobAction *JA, const char *BaseInput,
5351
0
                            const InputInfo &Result) {
5352
0
  Arg *A =
5353
0
      Args.getLastArg(options::OPT_ftime_trace, options::OPT_ftime_trace_EQ);
5354
0
  if (!A)
5355
0
    return;
5356
0
  SmallString<128> Path;
5357
0
  if (A->getOption().matches(options::OPT_ftime_trace_EQ)) {
5358
0
    Path = A->getValue();
5359
0
    if (llvm::sys::fs::is_directory(Path)) {
5360
0
      SmallString<128> Tmp(Result.getFilename());
5361
0
      llvm::sys::path::replace_extension(Tmp, "json");
5362
0
      llvm::sys::path::append(Path, llvm::sys::path::filename(Tmp));
5363
0
    }
5364
0
  } else {
5365
0
    if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
5366
      // The trace file is ${dumpdir}${basename}.json. Note that dumpdir may not
5367
      // end with a path separator.
5368
0
      Path = DumpDir->getValue();
5369
0
      Path += llvm::sys::path::filename(BaseInput);
5370
0
    } else {
5371
0
      Path = Result.getFilename();
5372
0
    }
5373
0
    llvm::sys::path::replace_extension(Path, "json");
5374
0
  }
5375
0
  const char *ResultFile = C.getArgs().MakeArgString(Path);
5376
0
  C.addTimeTraceFile(ResultFile, JA);
5377
0
  C.addResultFile(ResultFile, JA);
5378
0
}
5379
5380
InputInfoList Driver::BuildJobsForActionNoCache(
5381
    Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
5382
    bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
5383
    std::map<std::pair<const Action *, std::string>, InputInfoList>
5384
        &CachedResults,
5385
0
    Action::OffloadKind TargetDeviceOffloadKind) const {
5386
0
  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
5387
5388
0
  InputInfoList OffloadDependencesInputInfo;
5389
0
  bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
5390
0
  if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
5391
    // The 'Darwin' toolchain is initialized only when its arguments are
5392
    // computed. Get the default arguments for OFK_None to ensure that
5393
    // initialization is performed before processing the offload action.
5394
    // FIXME: Remove when darwin's toolchain is initialized during construction.
5395
0
    C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
5396
5397
    // The offload action is expected to be used in four different situations.
5398
    //
5399
    // a) Set a toolchain/architecture/kind for a host action:
5400
    //    Host Action 1 -> OffloadAction -> Host Action 2
5401
    //
5402
    // b) Set a toolchain/architecture/kind for a device action;
5403
    //    Device Action 1 -> OffloadAction -> Device Action 2
5404
    //
5405
    // c) Specify a device dependence to a host action;
5406
    //    Device Action 1  _
5407
    //                      \
5408
    //      Host Action 1  ---> OffloadAction -> Host Action 2
5409
    //
5410
    // d) Specify a host dependence to a device action.
5411
    //      Host Action 1  _
5412
    //                      \
5413
    //    Device Action 1  ---> OffloadAction -> Device Action 2
5414
    //
5415
    // For a) and b), we just return the job generated for the dependences. For
5416
    // c) and d) we override the current action with the host/device dependence
5417
    // if the current toolchain is host/device and set the offload dependences
5418
    // info with the jobs obtained from the device/host dependence(s).
5419
5420
    // If there is a single device option or has no host action, just generate
5421
    // the job for it.
5422
0
    if (OA->hasSingleDeviceDependence() || !OA->hasHostDependence()) {
5423
0
      InputInfoList DevA;
5424
0
      OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
5425
0
                                       const char *DepBoundArch) {
5426
0
        DevA.append(BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
5427
0
                                       /*MultipleArchs*/ !!DepBoundArch,
5428
0
                                       LinkingOutput, CachedResults,
5429
0
                                       DepA->getOffloadingDeviceKind()));
5430
0
      });
5431
0
      return DevA;
5432
0
    }
5433
5434
    // If 'Action 2' is host, we generate jobs for the device dependences and
5435
    // override the current action with the host dependence. Otherwise, we
5436
    // generate the host dependences and override the action with the device
5437
    // dependence. The dependences can't therefore be a top-level action.
5438
0
    OA->doOnEachDependence(
5439
0
        /*IsHostDependence=*/BuildingForOffloadDevice,
5440
0
        [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
5441
0
          OffloadDependencesInputInfo.append(BuildJobsForAction(
5442
0
              C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
5443
0
              /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
5444
0
              DepA->getOffloadingDeviceKind()));
5445
0
        });
5446
5447
0
    A = BuildingForOffloadDevice
5448
0
            ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
5449
0
            : OA->getHostDependence();
5450
5451
    // We may have already built this action as a part of the offloading
5452
    // toolchain, return the cached input if so.
5453
0
    std::pair<const Action *, std::string> ActionTC = {
5454
0
        OA->getHostDependence(),
5455
0
        GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
5456
0
    if (CachedResults.find(ActionTC) != CachedResults.end()) {
5457
0
      InputInfoList Inputs = CachedResults[ActionTC];
5458
0
      Inputs.append(OffloadDependencesInputInfo);
5459
0
      return Inputs;
5460
0
    }
5461
0
  }
5462
5463
0
  if (const InputAction *IA = dyn_cast<InputAction>(A)) {
5464
    // FIXME: It would be nice to not claim this here; maybe the old scheme of
5465
    // just using Args was better?
5466
0
    const Arg &Input = IA->getInputArg();
5467
0
    Input.claim();
5468
0
    if (Input.getOption().matches(options::OPT_INPUT)) {
5469
0
      const char *Name = Input.getValue();
5470
0
      return {InputInfo(A, Name, /* _BaseInput = */ Name)};
5471
0
    }
5472
0
    return {InputInfo(A, &Input, /* _BaseInput = */ "")};
5473
0
  }
5474
5475
0
  if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
5476
0
    const ToolChain *TC;
5477
0
    StringRef ArchName = BAA->getArchName();
5478
5479
0
    if (!ArchName.empty())
5480
0
      TC = &getToolChain(C.getArgs(),
5481
0
                         computeTargetTriple(*this, TargetTriple,
5482
0
                                             C.getArgs(), ArchName));
5483
0
    else
5484
0
      TC = &C.getDefaultToolChain();
5485
5486
0
    return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
5487
0
                              MultipleArchs, LinkingOutput, CachedResults,
5488
0
                              TargetDeviceOffloadKind);
5489
0
  }
5490
5491
5492
0
  ActionList Inputs = A->getInputs();
5493
5494
0
  const JobAction *JA = cast<JobAction>(A);
5495
0
  ActionList CollapsedOffloadActions;
5496
5497
0
  ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
5498
0
                  embedBitcodeInObject() && !isUsingLTO());
5499
0
  const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
5500
5501
0
  if (!T)
5502
0
    return {InputInfo()};
5503
5504
  // If we've collapsed action list that contained OffloadAction we
5505
  // need to build jobs for host/device-side inputs it may have held.
5506
0
  for (const auto *OA : CollapsedOffloadActions)
5507
0
    cast<OffloadAction>(OA)->doOnEachDependence(
5508
0
        /*IsHostDependence=*/BuildingForOffloadDevice,
5509
0
        [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
5510
0
          OffloadDependencesInputInfo.append(BuildJobsForAction(
5511
0
              C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
5512
0
              /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
5513
0
              DepA->getOffloadingDeviceKind()));
5514
0
        });
5515
5516
  // Only use pipes when there is exactly one input.
5517
0
  InputInfoList InputInfos;
5518
0
  for (const Action *Input : Inputs) {
5519
    // Treat dsymutil and verify sub-jobs as being at the top-level too, they
5520
    // shouldn't get temporary output names.
5521
    // FIXME: Clean this up.
5522
0
    bool SubJobAtTopLevel =
5523
0
        AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
5524
0
    InputInfos.append(BuildJobsForAction(
5525
0
        C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
5526
0
        CachedResults, A->getOffloadingDeviceKind()));
5527
0
  }
5528
5529
  // Always use the first file input as the base input.
5530
0
  const char *BaseInput = InputInfos[0].getBaseInput();
5531
0
  for (auto &Info : InputInfos) {
5532
0
    if (Info.isFilename()) {
5533
0
      BaseInput = Info.getBaseInput();
5534
0
      break;
5535
0
    }
5536
0
  }
5537
5538
  // ... except dsymutil actions, which use their actual input as the base
5539
  // input.
5540
0
  if (JA->getType() == types::TY_dSYM)
5541
0
    BaseInput = InputInfos[0].getFilename();
5542
5543
  // Append outputs of offload device jobs to the input list
5544
0
  if (!OffloadDependencesInputInfo.empty())
5545
0
    InputInfos.append(OffloadDependencesInputInfo.begin(),
5546
0
                      OffloadDependencesInputInfo.end());
5547
5548
  // Set the effective triple of the toolchain for the duration of this job.
5549
0
  llvm::Triple EffectiveTriple;
5550
0
  const ToolChain &ToolTC = T->getToolChain();
5551
0
  const ArgList &Args =
5552
0
      C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
5553
0
  if (InputInfos.size() != 1) {
5554
0
    EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
5555
0
  } else {
5556
    // Pass along the input type if it can be unambiguously determined.
5557
0
    EffectiveTriple = llvm::Triple(
5558
0
        ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
5559
0
  }
5560
0
  RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
5561
5562
  // Determine the place to write output to, if any.
5563
0
  InputInfo Result;
5564
0
  InputInfoList UnbundlingResults;
5565
0
  if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
5566
    // If we have an unbundling job, we need to create results for all the
5567
    // outputs. We also update the results cache so that other actions using
5568
    // this unbundling action can get the right results.
5569
0
    for (auto &UI : UA->getDependentActionsInfo()) {
5570
0
      assert(UI.DependentOffloadKind != Action::OFK_None &&
5571
0
             "Unbundling with no offloading??");
5572
5573
      // Unbundling actions are never at the top level. When we generate the
5574
      // offloading prefix, we also do that for the host file because the
5575
      // unbundling action does not change the type of the output which can
5576
      // cause a overwrite.
5577
0
      std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
5578
0
          UI.DependentOffloadKind,
5579
0
          UI.DependentToolChain->getTriple().normalize(),
5580
0
          /*CreatePrefixForHost=*/true);
5581
0
      auto CurI = InputInfo(
5582
0
          UA,
5583
0
          GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
5584
0
                             /*AtTopLevel=*/false,
5585
0
                             MultipleArchs ||
5586
0
                                 UI.DependentOffloadKind == Action::OFK_HIP,
5587
0
                             OffloadingPrefix),
5588
0
          BaseInput);
5589
      // Save the unbundling result.
5590
0
      UnbundlingResults.push_back(CurI);
5591
5592
      // Get the unique string identifier for this dependence and cache the
5593
      // result.
5594
0
      StringRef Arch;
5595
0
      if (TargetDeviceOffloadKind == Action::OFK_HIP) {
5596
0
        if (UI.DependentOffloadKind == Action::OFK_Host)
5597
0
          Arch = StringRef();
5598
0
        else
5599
0
          Arch = UI.DependentBoundArch;
5600
0
      } else
5601
0
        Arch = BoundArch;
5602
5603
0
      CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
5604
0
                                                UI.DependentOffloadKind)}] = {
5605
0
          CurI};
5606
0
    }
5607
5608
    // Now that we have all the results generated, select the one that should be
5609
    // returned for the current depending action.
5610
0
    std::pair<const Action *, std::string> ActionTC = {
5611
0
        A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
5612
0
    assert(CachedResults.find(ActionTC) != CachedResults.end() &&
5613
0
           "Result does not exist??");
5614
0
    Result = CachedResults[ActionTC].front();
5615
0
  } else if (JA->getType() == types::TY_Nothing)
5616
0
    Result = {InputInfo(A, BaseInput)};
5617
0
  else {
5618
    // We only have to generate a prefix for the host if this is not a top-level
5619
    // action.
5620
0
    std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
5621
0
        A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
5622
0
        /*CreatePrefixForHost=*/isa<OffloadPackagerJobAction>(A) ||
5623
0
            !(A->getOffloadingHostActiveKinds() == Action::OFK_None ||
5624
0
              AtTopLevel));
5625
0
    Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
5626
0
                                             AtTopLevel, MultipleArchs,
5627
0
                                             OffloadingPrefix),
5628
0
                       BaseInput);
5629
0
    if (T->canEmitIR() && OffloadingPrefix.empty())
5630
0
      handleTimeTrace(C, Args, JA, BaseInput, Result);
5631
0
  }
5632
5633
0
  if (CCCPrintBindings && !CCGenDiagnostics) {
5634
0
    llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
5635
0
                 << " - \"" << T->getName() << "\", inputs: [";
5636
0
    for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
5637
0
      llvm::errs() << InputInfos[i].getAsString();
5638
0
      if (i + 1 != e)
5639
0
        llvm::errs() << ", ";
5640
0
    }
5641
0
    if (UnbundlingResults.empty())
5642
0
      llvm::errs() << "], output: " << Result.getAsString() << "\n";
5643
0
    else {
5644
0
      llvm::errs() << "], outputs: [";
5645
0
      for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
5646
0
        llvm::errs() << UnbundlingResults[i].getAsString();
5647
0
        if (i + 1 != e)
5648
0
          llvm::errs() << ", ";
5649
0
      }
5650
0
      llvm::errs() << "] \n";
5651
0
    }
5652
0
  } else {
5653
0
    if (UnbundlingResults.empty())
5654
0
      T->ConstructJob(
5655
0
          C, *JA, Result, InputInfos,
5656
0
          C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
5657
0
          LinkingOutput);
5658
0
    else
5659
0
      T->ConstructJobMultipleOutputs(
5660
0
          C, *JA, UnbundlingResults, InputInfos,
5661
0
          C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
5662
0
          LinkingOutput);
5663
0
  }
5664
0
  return {Result};
5665
0
}
5666
5667
0
const char *Driver::getDefaultImageName() const {
5668
0
  llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
5669
0
  return Target.isOSWindows() ? "a.exe" : "a.out";
5670
0
}
5671
5672
/// Create output filename based on ArgValue, which could either be a
5673
/// full filename, filename without extension, or a directory. If ArgValue
5674
/// does not provide a filename, then use BaseName, and use the extension
5675
/// suitable for FileType.
5676
static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
5677
                                        StringRef BaseName,
5678
0
                                        types::ID FileType) {
5679
0
  SmallString<128> Filename = ArgValue;
5680
5681
0
  if (ArgValue.empty()) {
5682
    // If the argument is empty, output to BaseName in the current dir.
5683
0
    Filename = BaseName;
5684
0
  } else if (llvm::sys::path::is_separator(Filename.back())) {
5685
    // If the argument is a directory, output to BaseName in that dir.
5686
0
    llvm::sys::path::append(Filename, BaseName);
5687
0
  }
5688
5689
0
  if (!llvm::sys::path::has_extension(ArgValue)) {
5690
    // If the argument didn't provide an extension, then set it.
5691
0
    const char *Extension = types::getTypeTempSuffix(FileType, true);
5692
5693
0
    if (FileType == types::TY_Image &&
5694
0
        Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
5695
      // The output file is a dll.
5696
0
      Extension = "dll";
5697
0
    }
5698
5699
0
    llvm::sys::path::replace_extension(Filename, Extension);
5700
0
  }
5701
5702
0
  return Args.MakeArgString(Filename.c_str());
5703
0
}
5704
5705
0
static bool HasPreprocessOutput(const Action &JA) {
5706
0
  if (isa<PreprocessJobAction>(JA))
5707
0
    return true;
5708
0
  if (isa<OffloadAction>(JA) && isa<PreprocessJobAction>(JA.getInputs()[0]))
5709
0
    return true;
5710
0
  if (isa<OffloadBundlingJobAction>(JA) &&
5711
0
      HasPreprocessOutput(*(JA.getInputs()[0])))
5712
0
    return true;
5713
0
  return false;
5714
0
}
5715
5716
const char *Driver::CreateTempFile(Compilation &C, StringRef Prefix,
5717
                                   StringRef Suffix, bool MultipleArchs,
5718
                                   StringRef BoundArch,
5719
0
                                   bool NeedUniqueDirectory) const {
5720
0
  SmallString<128> TmpName;
5721
0
  Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
5722
0
  std::optional<std::string> CrashDirectory =
5723
0
      CCGenDiagnostics && A
5724
0
          ? std::string(A->getValue())
5725
0
          : llvm::sys::Process::GetEnv("CLANG_CRASH_DIAGNOSTICS_DIR");
5726
0
  if (CrashDirectory) {
5727
0
    if (!getVFS().exists(*CrashDirectory))
5728
0
      llvm::sys::fs::create_directories(*CrashDirectory);
5729
0
    SmallString<128> Path(*CrashDirectory);
5730
0
    llvm::sys::path::append(Path, Prefix);
5731
0
    const char *Middle = !Suffix.empty() ? "-%%%%%%." : "-%%%%%%";
5732
0
    if (std::error_code EC =
5733
0
            llvm::sys::fs::createUniqueFile(Path + Middle + Suffix, TmpName)) {
5734
0
      Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5735
0
      return "";
5736
0
    }
5737
0
  } else {
5738
0
    if (MultipleArchs && !BoundArch.empty()) {
5739
0
      if (NeedUniqueDirectory) {
5740
0
        TmpName = GetTemporaryDirectory(Prefix);
5741
0
        llvm::sys::path::append(TmpName,
5742
0
                                Twine(Prefix) + "-" + BoundArch + "." + Suffix);
5743
0
      } else {
5744
0
        TmpName =
5745
0
            GetTemporaryPath((Twine(Prefix) + "-" + BoundArch).str(), Suffix);
5746
0
      }
5747
5748
0
    } else {
5749
0
      TmpName = GetTemporaryPath(Prefix, Suffix);
5750
0
    }
5751
0
  }
5752
0
  return C.addTempFile(C.getArgs().MakeArgString(TmpName));
5753
0
}
5754
5755
// Calculate the output path of the module file when compiling a module unit
5756
// with the `-fmodule-output` option or `-fmodule-output=` option specified.
5757
// The behavior is:
5758
// - If `-fmodule-output=` is specfied, then the module file is
5759
//   writing to the value.
5760
// - Otherwise if the output object file of the module unit is specified, the
5761
// output path
5762
//   of the module file should be the same with the output object file except
5763
//   the corresponding suffix. This requires both `-o` and `-c` are specified.
5764
// - Otherwise, the output path of the module file will be the same with the
5765
//   input with the corresponding suffix.
5766
static const char *GetModuleOutputPath(Compilation &C, const JobAction &JA,
5767
0
                                       const char *BaseInput) {
5768
0
  assert(isa<PrecompileJobAction>(JA) && JA.getType() == types::TY_ModuleFile &&
5769
0
         (C.getArgs().hasArg(options::OPT_fmodule_output) ||
5770
0
          C.getArgs().hasArg(options::OPT_fmodule_output_EQ)));
5771
5772
0
  if (Arg *ModuleOutputEQ =
5773
0
          C.getArgs().getLastArg(options::OPT_fmodule_output_EQ))
5774
0
    return C.addResultFile(ModuleOutputEQ->getValue(), &JA);
5775
5776
0
  SmallString<64> OutputPath;
5777
0
  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
5778
0
  if (FinalOutput && C.getArgs().hasArg(options::OPT_c))
5779
0
    OutputPath = FinalOutput->getValue();
5780
0
  else
5781
0
    OutputPath = BaseInput;
5782
5783
0
  const char *Extension = types::getTypeTempSuffix(JA.getType());
5784
0
  llvm::sys::path::replace_extension(OutputPath, Extension);
5785
0
  return C.addResultFile(C.getArgs().MakeArgString(OutputPath.c_str()), &JA);
5786
0
}
5787
5788
const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
5789
                                       const char *BaseInput,
5790
                                       StringRef OrigBoundArch, bool AtTopLevel,
5791
                                       bool MultipleArchs,
5792
0
                                       StringRef OffloadingPrefix) const {
5793
0
  std::string BoundArch = OrigBoundArch.str();
5794
0
  if (is_style_windows(llvm::sys::path::Style::native)) {
5795
    // BoundArch may contains ':', which is invalid in file names on Windows,
5796
    // therefore replace it with '%'.
5797
0
    std::replace(BoundArch.begin(), BoundArch.end(), ':', '@');
5798
0
  }
5799
5800
0
  llvm::PrettyStackTraceString CrashInfo("Computing output path");
5801
  // Output to a user requested destination?
5802
0
  if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
5803
0
    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
5804
0
      return C.addResultFile(FinalOutput->getValue(), &JA);
5805
0
  }
5806
5807
  // For /P, preprocess to file named after BaseInput.
5808
0
  if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
5809
0
    assert(AtTopLevel && isa<PreprocessJobAction>(JA));
5810
0
    StringRef BaseName = llvm::sys::path::filename(BaseInput);
5811
0
    StringRef NameArg;
5812
0
    if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
5813
0
      NameArg = A->getValue();
5814
0
    return C.addResultFile(
5815
0
        MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
5816
0
        &JA);
5817
0
  }
5818
5819
  // Default to writing to stdout?
5820
0
  if (AtTopLevel && !CCGenDiagnostics && HasPreprocessOutput(JA)) {
5821
0
    return "-";
5822
0
  }
5823
5824
0
  if (JA.getType() == types::TY_ModuleFile &&
5825
0
      C.getArgs().getLastArg(options::OPT_module_file_info)) {
5826
0
    return "-";
5827
0
  }
5828
5829
0
  if (JA.getType() == types::TY_PP_Asm &&
5830
0
      C.getArgs().hasArg(options::OPT_dxc_Fc)) {
5831
0
    StringRef FcValue = C.getArgs().getLastArgValue(options::OPT_dxc_Fc);
5832
    // TODO: Should we use `MakeCLOutputFilename` here? If so, we can probably
5833
    // handle this as part of the SLASH_Fa handling below.
5834
0
    return C.addResultFile(C.getArgs().MakeArgString(FcValue.str()), &JA);
5835
0
  }
5836
5837
0
  if (JA.getType() == types::TY_Object &&
5838
0
      C.getArgs().hasArg(options::OPT_dxc_Fo)) {
5839
0
    StringRef FoValue = C.getArgs().getLastArgValue(options::OPT_dxc_Fo);
5840
    // TODO: Should we use `MakeCLOutputFilename` here? If so, we can probably
5841
    // handle this as part of the SLASH_Fo handling below.
5842
0
    return C.addResultFile(C.getArgs().MakeArgString(FoValue.str()), &JA);
5843
0
  }
5844
5845
  // Is this the assembly listing for /FA?
5846
0
  if (JA.getType() == types::TY_PP_Asm &&
5847
0
      (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
5848
0
       C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
5849
    // Use /Fa and the input filename to determine the asm file name.
5850
0
    StringRef BaseName = llvm::sys::path::filename(BaseInput);
5851
0
    StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
5852
0
    return C.addResultFile(
5853
0
        MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
5854
0
        &JA);
5855
0
  }
5856
5857
  // DXC defaults to standard out when generating assembly. We check this after
5858
  // any DXC flags that might specify a file.
5859
0
  if (AtTopLevel && JA.getType() == types::TY_PP_Asm && IsDXCMode())
5860
0
    return "-";
5861
5862
0
  bool SpecifiedModuleOutput =
5863
0
      C.getArgs().hasArg(options::OPT_fmodule_output) ||
5864
0
      C.getArgs().hasArg(options::OPT_fmodule_output_EQ);
5865
0
  if (MultipleArchs && SpecifiedModuleOutput)
5866
0
    Diag(clang::diag::err_drv_module_output_with_multiple_arch);
5867
5868
  // If we're emitting a module output with the specified option
5869
  // `-fmodule-output`.
5870
0
  if (!AtTopLevel && isa<PrecompileJobAction>(JA) &&
5871
0
      JA.getType() == types::TY_ModuleFile && SpecifiedModuleOutput)
5872
0
    return GetModuleOutputPath(C, JA, BaseInput);
5873
5874
  // Output to a temporary file?
5875
0
  if ((!AtTopLevel && !isSaveTempsEnabled() &&
5876
0
       !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
5877
0
      CCGenDiagnostics) {
5878
0
    StringRef Name = llvm::sys::path::filename(BaseInput);
5879
0
    std::pair<StringRef, StringRef> Split = Name.split('.');
5880
0
    const char *Suffix =
5881
0
        types::getTypeTempSuffix(JA.getType(), IsCLMode() || IsDXCMode());
5882
    // The non-offloading toolchain on Darwin requires deterministic input
5883
    // file name for binaries to be deterministic, therefore it needs unique
5884
    // directory.
5885
0
    llvm::Triple Triple(C.getDriver().getTargetTriple());
5886
0
    bool NeedUniqueDirectory =
5887
0
        (JA.getOffloadingDeviceKind() == Action::OFK_None ||
5888
0
         JA.getOffloadingDeviceKind() == Action::OFK_Host) &&
5889
0
        Triple.isOSDarwin();
5890
0
    return CreateTempFile(C, Split.first, Suffix, MultipleArchs, BoundArch,
5891
0
                          NeedUniqueDirectory);
5892
0
  }
5893
5894
0
  SmallString<128> BasePath(BaseInput);
5895
0
  SmallString<128> ExternalPath("");
5896
0
  StringRef BaseName;
5897
5898
  // Dsymutil actions should use the full path.
5899
0
  if (isa<DsymutilJobAction>(JA) && C.getArgs().hasArg(options::OPT_dsym_dir)) {
5900
0
    ExternalPath += C.getArgs().getLastArg(options::OPT_dsym_dir)->getValue();
5901
    // We use posix style here because the tests (specifically
5902
    // darwin-dsymutil.c) demonstrate that posix style paths are acceptable
5903
    // even on Windows and if we don't then the similar test covering this
5904
    // fails.
5905
0
    llvm::sys::path::append(ExternalPath, llvm::sys::path::Style::posix,
5906
0
                            llvm::sys::path::filename(BasePath));
5907
0
    BaseName = ExternalPath;
5908
0
  } else if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
5909
0
    BaseName = BasePath;
5910
0
  else
5911
0
    BaseName = llvm::sys::path::filename(BasePath);
5912
5913
  // Determine what the derived output name should be.
5914
0
  const char *NamedOutput;
5915
5916
0
  if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
5917
0
      C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
5918
    // The /Fo or /o flag decides the object filename.
5919
0
    StringRef Val =
5920
0
        C.getArgs()
5921
0
            .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
5922
0
            ->getValue();
5923
0
    NamedOutput =
5924
0
        MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
5925
0
  } else if (JA.getType() == types::TY_Image &&
5926
0
             C.getArgs().hasArg(options::OPT__SLASH_Fe,
5927
0
                                options::OPT__SLASH_o)) {
5928
    // The /Fe or /o flag names the linked file.
5929
0
    StringRef Val =
5930
0
        C.getArgs()
5931
0
            .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
5932
0
            ->getValue();
5933
0
    NamedOutput =
5934
0
        MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
5935
0
  } else if (JA.getType() == types::TY_Image) {
5936
0
    if (IsCLMode()) {
5937
      // clang-cl uses BaseName for the executable name.
5938
0
      NamedOutput =
5939
0
          MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
5940
0
    } else {
5941
0
      SmallString<128> Output(getDefaultImageName());
5942
      // HIP image for device compilation with -fno-gpu-rdc is per compilation
5943
      // unit.
5944
0
      bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
5945
0
                        !C.getArgs().hasFlag(options::OPT_fgpu_rdc,
5946
0
                                             options::OPT_fno_gpu_rdc, false);
5947
0
      bool UseOutExtension = IsHIPNoRDC || isa<OffloadPackagerJobAction>(JA);
5948
0
      if (UseOutExtension) {
5949
0
        Output = BaseName;
5950
0
        llvm::sys::path::replace_extension(Output, "");
5951
0
      }
5952
0
      Output += OffloadingPrefix;
5953
0
      if (MultipleArchs && !BoundArch.empty()) {
5954
0
        Output += "-";
5955
0
        Output.append(BoundArch);
5956
0
      }
5957
0
      if (UseOutExtension)
5958
0
        Output += ".out";
5959
0
      NamedOutput = C.getArgs().MakeArgString(Output.c_str());
5960
0
    }
5961
0
  } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
5962
0
    NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
5963
0
  } else if ((JA.getType() == types::TY_Plist || JA.getType() == types::TY_AST) &&
5964
0
             C.getArgs().hasArg(options::OPT__SLASH_o)) {
5965
0
    StringRef Val =
5966
0
        C.getArgs()
5967
0
            .getLastArg(options::OPT__SLASH_o)
5968
0
            ->getValue();
5969
0
    NamedOutput =
5970
0
        MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
5971
0
  } else {
5972
0
    const char *Suffix =
5973
0
        types::getTypeTempSuffix(JA.getType(), IsCLMode() || IsDXCMode());
5974
0
    assert(Suffix && "All types used for output should have a suffix.");
5975
5976
0
    std::string::size_type End = std::string::npos;
5977
0
    if (!types::appendSuffixForType(JA.getType()))
5978
0
      End = BaseName.rfind('.');
5979
0
    SmallString<128> Suffixed(BaseName.substr(0, End));
5980
0
    Suffixed += OffloadingPrefix;
5981
0
    if (MultipleArchs && !BoundArch.empty()) {
5982
0
      Suffixed += "-";
5983
0
      Suffixed.append(BoundArch);
5984
0
    }
5985
    // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
5986
    // the unoptimized bitcode so that it does not get overwritten by the ".bc"
5987
    // optimized bitcode output.
5988
0
    auto IsAMDRDCInCompilePhase = [](const JobAction &JA,
5989
0
                                     const llvm::opt::DerivedArgList &Args) {
5990
      // The relocatable compilation in HIP and OpenMP implies -emit-llvm.
5991
      // Similarly, use a ".tmp.bc" suffix for the unoptimized bitcode
5992
      // (generated in the compile phase.)
5993
0
      const ToolChain *TC = JA.getOffloadingToolChain();
5994
0
      return isa<CompileJobAction>(JA) &&
5995
0
             ((JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
5996
0
               Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
5997
0
                            false)) ||
5998
0
              (JA.getOffloadingDeviceKind() == Action::OFK_OpenMP && TC &&
5999
0
               TC->getTriple().isAMDGPU()));
6000
0
    };
6001
0
    if (!AtTopLevel && JA.getType() == types::TY_LLVM_BC &&
6002
0
        (C.getArgs().hasArg(options::OPT_emit_llvm) ||
6003
0
         IsAMDRDCInCompilePhase(JA, C.getArgs())))
6004
0
      Suffixed += ".tmp";
6005
0
    Suffixed += '.';
6006
0
    Suffixed += Suffix;
6007
0
    NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
6008
0
  }
6009
6010
  // Prepend object file path if -save-temps=obj
6011
0
  if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
6012
0
      JA.getType() != types::TY_PCH) {
6013
0
    Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
6014
0
    SmallString<128> TempPath(FinalOutput->getValue());
6015
0
    llvm::sys::path::remove_filename(TempPath);
6016
0
    StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
6017
0
    llvm::sys::path::append(TempPath, OutputFileName);
6018
0
    NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
6019
0
  }
6020
6021
  // If we're saving temps and the temp file conflicts with the input file,
6022
  // then avoid overwriting input file.
6023
0
  if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
6024
0
    bool SameFile = false;
6025
0
    SmallString<256> Result;
6026
0
    llvm::sys::fs::current_path(Result);
6027
0
    llvm::sys::path::append(Result, BaseName);
6028
0
    llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
6029
    // Must share the same path to conflict.
6030
0
    if (SameFile) {
6031
0
      StringRef Name = llvm::sys::path::filename(BaseInput);
6032
0
      std::pair<StringRef, StringRef> Split = Name.split('.');
6033
0
      std::string TmpName = GetTemporaryPath(
6034
0
          Split.first,
6035
0
          types::getTypeTempSuffix(JA.getType(), IsCLMode() || IsDXCMode()));
6036
0
      return C.addTempFile(C.getArgs().MakeArgString(TmpName));
6037
0
    }
6038
0
  }
6039
6040
  // As an annoying special case, PCH generation doesn't strip the pathname.
6041
0
  if (JA.getType() == types::TY_PCH && !IsCLMode()) {
6042
0
    llvm::sys::path::remove_filename(BasePath);
6043
0
    if (BasePath.empty())
6044
0
      BasePath = NamedOutput;
6045
0
    else
6046
0
      llvm::sys::path::append(BasePath, NamedOutput);
6047
0
    return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
6048
0
  }
6049
6050
0
  return C.addResultFile(NamedOutput, &JA);
6051
0
}
6052
6053
0
std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
6054
  // Search for Name in a list of paths.
6055
0
  auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
6056
0
      -> std::optional<std::string> {
6057
    // Respect a limited subset of the '-Bprefix' functionality in GCC by
6058
    // attempting to use this prefix when looking for file paths.
6059
0
    for (const auto &Dir : P) {
6060
0
      if (Dir.empty())
6061
0
        continue;
6062
0
      SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
6063
0
      llvm::sys::path::append(P, Name);
6064
0
      if (llvm::sys::fs::exists(Twine(P)))
6065
0
        return std::string(P);
6066
0
    }
6067
0
    return std::nullopt;
6068
0
  };
6069
6070
0
  if (auto P = SearchPaths(PrefixDirs))
6071
0
    return *P;
6072
6073
0
  SmallString<128> R(ResourceDir);
6074
0
  llvm::sys::path::append(R, Name);
6075
0
  if (llvm::sys::fs::exists(Twine(R)))
6076
0
    return std::string(R.str());
6077
6078
0
  SmallString<128> P(TC.getCompilerRTPath());
6079
0
  llvm::sys::path::append(P, Name);
6080
0
  if (llvm::sys::fs::exists(Twine(P)))
6081
0
    return std::string(P.str());
6082
6083
0
  SmallString<128> D(Dir);
6084
0
  llvm::sys::path::append(D, "..", Name);
6085
0
  if (llvm::sys::fs::exists(Twine(D)))
6086
0
    return std::string(D.str());
6087
6088
0
  if (auto P = SearchPaths(TC.getLibraryPaths()))
6089
0
    return *P;
6090
6091
0
  if (auto P = SearchPaths(TC.getFilePaths()))
6092
0
    return *P;
6093
6094
0
  return std::string(Name);
6095
0
}
6096
6097
void Driver::generatePrefixedToolNames(
6098
    StringRef Tool, const ToolChain &TC,
6099
0
    SmallVectorImpl<std::string> &Names) const {
6100
  // FIXME: Needs a better variable than TargetTriple
6101
0
  Names.emplace_back((TargetTriple + "-" + Tool).str());
6102
0
  Names.emplace_back(Tool);
6103
0
}
6104
6105
0
static bool ScanDirForExecutable(SmallString<128> &Dir, StringRef Name) {
6106
0
  llvm::sys::path::append(Dir, Name);
6107
0
  if (llvm::sys::fs::can_execute(Twine(Dir)))
6108
0
    return true;
6109
0
  llvm::sys::path::remove_filename(Dir);
6110
0
  return false;
6111
0
}
6112
6113
0
std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
6114
0
  SmallVector<std::string, 2> TargetSpecificExecutables;
6115
0
  generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
6116
6117
  // Respect a limited subset of the '-Bprefix' functionality in GCC by
6118
  // attempting to use this prefix when looking for program paths.
6119
0
  for (const auto &PrefixDir : PrefixDirs) {
6120
0
    if (llvm::sys::fs::is_directory(PrefixDir)) {
6121
0
      SmallString<128> P(PrefixDir);
6122
0
      if (ScanDirForExecutable(P, Name))
6123
0
        return std::string(P.str());
6124
0
    } else {
6125
0
      SmallString<128> P((PrefixDir + Name).str());
6126
0
      if (llvm::sys::fs::can_execute(Twine(P)))
6127
0
        return std::string(P.str());
6128
0
    }
6129
0
  }
6130
6131
0
  const ToolChain::path_list &List = TC.getProgramPaths();
6132
0
  for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) {
6133
    // For each possible name of the tool look for it in
6134
    // program paths first, then the path.
6135
    // Higher priority names will be first, meaning that
6136
    // a higher priority name in the path will be found
6137
    // instead of a lower priority name in the program path.
6138
    // E.g. <triple>-gcc on the path will be found instead
6139
    // of gcc in the program path
6140
0
    for (const auto &Path : List) {
6141
0
      SmallString<128> P(Path);
6142
0
      if (ScanDirForExecutable(P, TargetSpecificExecutable))
6143
0
        return std::string(P.str());
6144
0
    }
6145
6146
    // Fall back to the path
6147
0
    if (llvm::ErrorOr<std::string> P =
6148
0
            llvm::sys::findProgramByName(TargetSpecificExecutable))
6149
0
      return *P;
6150
0
  }
6151
6152
0
  return std::string(Name);
6153
0
}
6154
6155
0
std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
6156
0
  SmallString<128> Path;
6157
0
  std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
6158
0
  if (EC) {
6159
0
    Diag(clang::diag::err_unable_to_make_temp) << EC.message();
6160
0
    return "";
6161
0
  }
6162
6163
0
  return std::string(Path.str());
6164
0
}
6165
6166
0
std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
6167
0
  SmallString<128> Path;
6168
0
  std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
6169
0
  if (EC) {
6170
0
    Diag(clang::diag::err_unable_to_make_temp) << EC.message();
6171
0
    return "";
6172
0
  }
6173
6174
0
  return std::string(Path.str());
6175
0
}
6176
6177
0
std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
6178
0
  SmallString<128> Output;
6179
0
  if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
6180
    // FIXME: If anybody needs it, implement this obscure rule:
6181
    // "If you specify a directory without a file name, the default file name
6182
    // is VCx0.pch., where x is the major version of Visual C++ in use."
6183
0
    Output = FpArg->getValue();
6184
6185
    // "If you do not specify an extension as part of the path name, an
6186
    // extension of .pch is assumed. "
6187
0
    if (!llvm::sys::path::has_extension(Output))
6188
0
      Output += ".pch";
6189
0
  } else {
6190
0
    if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
6191
0
      Output = YcArg->getValue();
6192
0
    if (Output.empty())
6193
0
      Output = BaseName;
6194
0
    llvm::sys::path::replace_extension(Output, ".pch");
6195
0
  }
6196
0
  return std::string(Output.str());
6197
0
}
6198
6199
const ToolChain &Driver::getToolChain(const ArgList &Args,
6200
0
                                      const llvm::Triple &Target) const {
6201
6202
0
  auto &TC = ToolChains[Target.str()];
6203
0
  if (!TC) {
6204
0
    switch (Target.getOS()) {
6205
0
    case llvm::Triple::AIX:
6206
0
      TC = std::make_unique<toolchains::AIX>(*this, Target, Args);
6207
0
      break;
6208
0
    case llvm::Triple::Haiku:
6209
0
      TC = std::make_unique<toolchains::Haiku>(*this, Target, Args);
6210
0
      break;
6211
0
    case llvm::Triple::Darwin:
6212
0
    case llvm::Triple::MacOSX:
6213
0
    case llvm::Triple::IOS:
6214
0
    case llvm::Triple::TvOS:
6215
0
    case llvm::Triple::WatchOS:
6216
0
    case llvm::Triple::DriverKit:
6217
0
      TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args);
6218
0
      break;
6219
0
    case llvm::Triple::DragonFly:
6220
0
      TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args);
6221
0
      break;
6222
0
    case llvm::Triple::OpenBSD:
6223
0
      TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args);
6224
0
      break;
6225
0
    case llvm::Triple::NetBSD:
6226
0
      TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args);
6227
0
      break;
6228
0
    case llvm::Triple::FreeBSD:
6229
0
      if (Target.isPPC())
6230
0
        TC = std::make_unique<toolchains::PPCFreeBSDToolChain>(*this, Target,
6231
0
                                                               Args);
6232
0
      else
6233
0
        TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args);
6234
0
      break;
6235
0
    case llvm::Triple::Linux:
6236
0
    case llvm::Triple::ELFIAMCU:
6237
0
      if (Target.getArch() == llvm::Triple::hexagon)
6238
0
        TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
6239
0
                                                             Args);
6240
0
      else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
6241
0
               !Target.hasEnvironment())
6242
0
        TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
6243
0
                                                              Args);
6244
0
      else if (Target.isPPC())
6245
0
        TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
6246
0
                                                              Args);
6247
0
      else if (Target.getArch() == llvm::Triple::ve)
6248
0
        TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
6249
0
      else if (Target.isOHOSFamily())
6250
0
        TC = std::make_unique<toolchains::OHOS>(*this, Target, Args);
6251
0
      else
6252
0
        TC = std::make_unique<toolchains::Linux>(*this, Target, Args);
6253
0
      break;
6254
0
    case llvm::Triple::NaCl:
6255
0
      TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
6256
0
      break;
6257
0
    case llvm::Triple::Fuchsia:
6258
0
      TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args);
6259
0
      break;
6260
0
    case llvm::Triple::Solaris:
6261
0
      TC = std::make_unique<toolchains::Solaris>(*this, Target, Args);
6262
0
      break;
6263
0
    case llvm::Triple::CUDA:
6264
0
      TC = std::make_unique<toolchains::NVPTXToolChain>(*this, Target, Args);
6265
0
      break;
6266
0
    case llvm::Triple::AMDHSA:
6267
0
      TC = std::make_unique<toolchains::ROCMToolChain>(*this, Target, Args);
6268
0
      break;
6269
0
    case llvm::Triple::AMDPAL:
6270
0
    case llvm::Triple::Mesa3D:
6271
0
      TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
6272
0
      break;
6273
0
    case llvm::Triple::Win32:
6274
0
      switch (Target.getEnvironment()) {
6275
0
      default:
6276
0
        if (Target.isOSBinFormatELF())
6277
0
          TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
6278
0
        else if (Target.isOSBinFormatMachO())
6279
0
          TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
6280
0
        else
6281
0
          TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
6282
0
        break;
6283
0
      case llvm::Triple::GNU:
6284
0
        TC = std::make_unique<toolchains::MinGW>(*this, Target, Args);
6285
0
        break;
6286
0
      case llvm::Triple::Itanium:
6287
0
        TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
6288
0
                                                                  Args);
6289
0
        break;
6290
0
      case llvm::Triple::MSVC:
6291
0
      case llvm::Triple::UnknownEnvironment:
6292
0
        if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
6293
0
                .starts_with_insensitive("bfd"))
6294
0
          TC = std::make_unique<toolchains::CrossWindowsToolChain>(
6295
0
              *this, Target, Args);
6296
0
        else
6297
0
          TC =
6298
0
              std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
6299
0
        break;
6300
0
      }
6301
0
      break;
6302
0
    case llvm::Triple::PS4:
6303
0
      TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args);
6304
0
      break;
6305
0
    case llvm::Triple::PS5:
6306
0
      TC = std::make_unique<toolchains::PS5CPU>(*this, Target, Args);
6307
0
      break;
6308
0
    case llvm::Triple::Hurd:
6309
0
      TC = std::make_unique<toolchains::Hurd>(*this, Target, Args);
6310
0
      break;
6311
0
    case llvm::Triple::LiteOS:
6312
0
      TC = std::make_unique<toolchains::OHOS>(*this, Target, Args);
6313
0
      break;
6314
0
    case llvm::Triple::ZOS:
6315
0
      TC = std::make_unique<toolchains::ZOS>(*this, Target, Args);
6316
0
      break;
6317
0
    case llvm::Triple::ShaderModel:
6318
0
      TC = std::make_unique<toolchains::HLSLToolChain>(*this, Target, Args);
6319
0
      break;
6320
0
    default:
6321
      // Of these targets, Hexagon is the only one that might have
6322
      // an OS of Linux, in which case it got handled above already.
6323
0
      switch (Target.getArch()) {
6324
0
      case llvm::Triple::tce:
6325
0
        TC = std::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
6326
0
        break;
6327
0
      case llvm::Triple::tcele:
6328
0
        TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
6329
0
        break;
6330
0
      case llvm::Triple::hexagon:
6331
0
        TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
6332
0
                                                             Args);
6333
0
        break;
6334
0
      case llvm::Triple::lanai:
6335
0
        TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
6336
0
        break;
6337
0
      case llvm::Triple::xcore:
6338
0
        TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
6339
0
        break;
6340
0
      case llvm::Triple::wasm32:
6341
0
      case llvm::Triple::wasm64:
6342
0
        TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args);
6343
0
        break;
6344
0
      case llvm::Triple::avr:
6345
0
        TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
6346
0
        break;
6347
0
      case llvm::Triple::msp430:
6348
0
        TC =
6349
0
            std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
6350
0
        break;
6351
0
      case llvm::Triple::riscv32:
6352
0
      case llvm::Triple::riscv64:
6353
0
        if (toolchains::RISCVToolChain::hasGCCToolchain(*this, Args))
6354
0
          TC =
6355
0
              std::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
6356
0
        else
6357
0
          TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
6358
0
        break;
6359
0
      case llvm::Triple::ve:
6360
0
        TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
6361
0
        break;
6362
0
      case llvm::Triple::spirv32:
6363
0
      case llvm::Triple::spirv64:
6364
0
        TC = std::make_unique<toolchains::SPIRVToolChain>(*this, Target, Args);
6365
0
        break;
6366
0
      case llvm::Triple::csky:
6367
0
        TC = std::make_unique<toolchains::CSKYToolChain>(*this, Target, Args);
6368
0
        break;
6369
0
      default:
6370
0
        if (toolchains::BareMetal::handlesTarget(Target))
6371
0
          TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
6372
0
        else if (Target.isOSBinFormatELF())
6373
0
          TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
6374
0
        else if (Target.isOSBinFormatMachO())
6375
0
          TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
6376
0
        else
6377
0
          TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
6378
0
      }
6379
0
    }
6380
0
  }
6381
6382
0
  return *TC;
6383
0
}
6384
6385
const ToolChain &Driver::getOffloadingDeviceToolChain(
6386
    const ArgList &Args, const llvm::Triple &Target, const ToolChain &HostTC,
6387
0
    const Action::OffloadKind &TargetDeviceOffloadKind) const {
6388
  // Use device / host triples as the key into the ToolChains map because the
6389
  // device ToolChain we create depends on both.
6390
0
  auto &TC = ToolChains[Target.str() + "/" + HostTC.getTriple().str()];
6391
0
  if (!TC) {
6392
    // Categorized by offload kind > arch rather than OS > arch like
6393
    // the normal getToolChain call, as it seems a reasonable way to categorize
6394
    // things.
6395
0
    switch (TargetDeviceOffloadKind) {
6396
0
    case Action::OFK_HIP: {
6397
0
      if (Target.getArch() == llvm::Triple::amdgcn &&
6398
0
          Target.getVendor() == llvm::Triple::AMD &&
6399
0
          Target.getOS() == llvm::Triple::AMDHSA)
6400
0
        TC = std::make_unique<toolchains::HIPAMDToolChain>(*this, Target,
6401
0
                                                           HostTC, Args);
6402
0
      else if (Target.getArch() == llvm::Triple::spirv64 &&
6403
0
               Target.getVendor() == llvm::Triple::UnknownVendor &&
6404
0
               Target.getOS() == llvm::Triple::UnknownOS)
6405
0
        TC = std::make_unique<toolchains::HIPSPVToolChain>(*this, Target,
6406
0
                                                           HostTC, Args);
6407
0
      break;
6408
0
    }
6409
0
    default:
6410
0
      break;
6411
0
    }
6412
0
  }
6413
6414
0
  return *TC;
6415
0
}
6416
6417
0
bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
6418
  // Say "no" if there is not exactly one input of a type clang understands.
6419
0
  if (JA.size() != 1 ||
6420
0
      !types::isAcceptedByClang((*JA.input_begin())->getType()))
6421
0
    return false;
6422
6423
  // And say "no" if this is not a kind of action clang understands.
6424
0
  if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
6425
0
      !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA) &&
6426
0
      !isa<ExtractAPIJobAction>(JA))
6427
0
    return false;
6428
6429
0
  return true;
6430
0
}
6431
6432
0
bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const {
6433
  // Say "no" if there is not exactly one input of a type flang understands.
6434
0
  if (JA.size() != 1 ||
6435
0
      !types::isAcceptedByFlang((*JA.input_begin())->getType()))
6436
0
    return false;
6437
6438
  // And say "no" if this is not a kind of action flang understands.
6439
0
  if (!isa<PreprocessJobAction>(JA) && !isa<CompileJobAction>(JA) &&
6440
0
      !isa<BackendJobAction>(JA))
6441
0
    return false;
6442
6443
0
  return true;
6444
0
}
6445
6446
0
bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const {
6447
  // Only emit static library if the flag is set explicitly.
6448
0
  if (Args.hasArg(options::OPT_emit_static_lib))
6449
0
    return true;
6450
0
  return false;
6451
0
}
6452
6453
/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
6454
/// grouped values as integers. Numbers which are not provided are set to 0.
6455
///
6456
/// \return True if the entire string was parsed (9.2), or all groups were
6457
/// parsed (10.3.5extrastuff).
6458
bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
6459
0
                               unsigned &Micro, bool &HadExtra) {
6460
0
  HadExtra = false;
6461
6462
0
  Major = Minor = Micro = 0;
6463
0
  if (Str.empty())
6464
0
    return false;
6465
6466
0
  if (Str.consumeInteger(10, Major))
6467
0
    return false;
6468
0
  if (Str.empty())
6469
0
    return true;
6470
0
  if (Str[0] != '.')
6471
0
    return false;
6472
6473
0
  Str = Str.drop_front(1);
6474
6475
0
  if (Str.consumeInteger(10, Minor))
6476
0
    return false;
6477
0
  if (Str.empty())
6478
0
    return true;
6479
0
  if (Str[0] != '.')
6480
0
    return false;
6481
0
  Str = Str.drop_front(1);
6482
6483
0
  if (Str.consumeInteger(10, Micro))
6484
0
    return false;
6485
0
  if (!Str.empty())
6486
0
    HadExtra = true;
6487
0
  return true;
6488
0
}
6489
6490
/// Parse digits from a string \p Str and fulfill \p Digits with
6491
/// the parsed numbers. This method assumes that the max number of
6492
/// digits to look for is equal to Digits.size().
6493
///
6494
/// \return True if the entire string was parsed and there are
6495
/// no extra characters remaining at the end.
6496
bool Driver::GetReleaseVersion(StringRef Str,
6497
0
                               MutableArrayRef<unsigned> Digits) {
6498
0
  if (Str.empty())
6499
0
    return false;
6500
6501
0
  unsigned CurDigit = 0;
6502
0
  while (CurDigit < Digits.size()) {
6503
0
    unsigned Digit;
6504
0
    if (Str.consumeInteger(10, Digit))
6505
0
      return false;
6506
0
    Digits[CurDigit] = Digit;
6507
0
    if (Str.empty())
6508
0
      return true;
6509
0
    if (Str[0] != '.')
6510
0
      return false;
6511
0
    Str = Str.drop_front(1);
6512
0
    CurDigit++;
6513
0
  }
6514
6515
  // More digits than requested, bail out...
6516
0
  return false;
6517
0
}
6518
6519
llvm::opt::Visibility
6520
0
Driver::getOptionVisibilityMask(bool UseDriverMode) const {
6521
0
  if (!UseDriverMode)
6522
0
    return llvm::opt::Visibility(options::ClangOption);
6523
0
  if (IsCLMode())
6524
0
    return llvm::opt::Visibility(options::CLOption);
6525
0
  if (IsDXCMode())
6526
0
    return llvm::opt::Visibility(options::DXCOption);
6527
0
  if (IsFlangMode())  {
6528
0
    return llvm::opt::Visibility(options::FlangOption);
6529
0
  }
6530
0
  return llvm::opt::Visibility(options::ClangOption);
6531
0
}
6532
6533
0
const char *Driver::getExecutableForDriverMode(DriverMode Mode) {
6534
0
  switch (Mode) {
6535
0
  case GCCMode:
6536
0
    return "clang";
6537
0
  case GXXMode:
6538
0
    return "clang++";
6539
0
  case CPPMode:
6540
0
    return "clang-cpp";
6541
0
  case CLMode:
6542
0
    return "clang-cl";
6543
0
  case FlangMode:
6544
0
    return "flang";
6545
0
  case DXCMode:
6546
0
    return "clang-dxc";
6547
0
  }
6548
6549
0
  llvm_unreachable("Unhandled Mode");
6550
0
}
6551
6552
0
bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
6553
0
  return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
6554
0
}
6555
6556
0
bool clang::driver::willEmitRemarks(const ArgList &Args) {
6557
  // -fsave-optimization-record enables it.
6558
0
  if (Args.hasFlag(options::OPT_fsave_optimization_record,
6559
0
                   options::OPT_fno_save_optimization_record, false))
6560
0
    return true;
6561
6562
  // -fsave-optimization-record=<format> enables it as well.
6563
0
  if (Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
6564
0
                   options::OPT_fno_save_optimization_record, false))
6565
0
    return true;
6566
6567
  // -foptimization-record-file alone enables it too.
6568
0
  if (Args.hasFlag(options::OPT_foptimization_record_file_EQ,
6569
0
                   options::OPT_fno_save_optimization_record, false))
6570
0
    return true;
6571
6572
  // -foptimization-record-passes alone enables it too.
6573
0
  if (Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
6574
0
                   options::OPT_fno_save_optimization_record, false))
6575
0
    return true;
6576
0
  return false;
6577
0
}
6578
6579
llvm::StringRef clang::driver::getDriverMode(StringRef ProgName,
6580
0
                                             ArrayRef<const char *> Args) {
6581
0
  static StringRef OptName =
6582
0
      getDriverOptTable().getOption(options::OPT_driver_mode).getPrefixedName();
6583
0
  llvm::StringRef Opt;
6584
0
  for (StringRef Arg : Args) {
6585
0
    if (!Arg.starts_with(OptName))
6586
0
      continue;
6587
0
    Opt = Arg;
6588
0
  }
6589
0
  if (Opt.empty())
6590
0
    Opt = ToolChain::getTargetAndModeFromProgramName(ProgName).DriverMode;
6591
0
  return Opt.consume_front(OptName) ? Opt : "";
6592
0
}
6593
6594
0
bool driver::IsClangCL(StringRef DriverMode) { return DriverMode.equals("cl"); }
6595
6596
llvm::Error driver::expandResponseFiles(SmallVectorImpl<const char *> &Args,
6597
                                        bool ClangCLMode,
6598
                                        llvm::BumpPtrAllocator &Alloc,
6599
0
                                        llvm::vfs::FileSystem *FS) {
6600
  // Parse response files using the GNU syntax, unless we're in CL mode. There
6601
  // are two ways to put clang in CL compatibility mode: ProgName is either
6602
  // clang-cl or cl, or --driver-mode=cl is on the command line. The normal
6603
  // command line parsing can't happen until after response file parsing, so we
6604
  // have to manually search for a --driver-mode=cl argument the hard way.
6605
  // Finally, our -cc1 tools don't care which tokenization mode we use because
6606
  // response files written by clang will tokenize the same way in either mode.
6607
0
  enum { Default, POSIX, Windows } RSPQuoting = Default;
6608
0
  for (const char *F : Args) {
6609
0
    if (strcmp(F, "--rsp-quoting=posix") == 0)
6610
0
      RSPQuoting = POSIX;
6611
0
    else if (strcmp(F, "--rsp-quoting=windows") == 0)
6612
0
      RSPQuoting = Windows;
6613
0
  }
6614
6615
  // Determines whether we want nullptr markers in Args to indicate response
6616
  // files end-of-lines. We only use this for the /LINK driver argument with
6617
  // clang-cl.exe on Windows.
6618
0
  bool MarkEOLs = ClangCLMode;
6619
6620
0
  llvm::cl::TokenizerCallback Tokenizer;
6621
0
  if (RSPQuoting == Windows || (RSPQuoting == Default && ClangCLMode))
6622
0
    Tokenizer = &llvm::cl::TokenizeWindowsCommandLine;
6623
0
  else
6624
0
    Tokenizer = &llvm::cl::TokenizeGNUCommandLine;
6625
6626
0
  if (MarkEOLs && Args.size() > 1 && StringRef(Args[1]).starts_with("-cc1"))
6627
0
    MarkEOLs = false;
6628
6629
0
  llvm::cl::ExpansionContext ECtx(Alloc, Tokenizer);
6630
0
  ECtx.setMarkEOLs(MarkEOLs);
6631
0
  if (FS)
6632
0
    ECtx.setVFS(FS);
6633
6634
0
  if (llvm::Error Err = ECtx.expandResponseFiles(Args))
6635
0
    return Err;
6636
6637
  // If -cc1 came from a response file, remove the EOL sentinels.
6638
0
  auto FirstArg = llvm::find_if(llvm::drop_begin(Args),
6639
0
                                [](const char *A) { return A != nullptr; });
6640
0
  if (FirstArg != Args.end() && StringRef(*FirstArg).starts_with("-cc1")) {
6641
    // If -cc1 came from a response file, remove the EOL sentinels.
6642
0
    if (MarkEOLs) {
6643
0
      auto newEnd = std::remove(Args.begin(), Args.end(), nullptr);
6644
0
      Args.resize(newEnd - Args.begin());
6645
0
    }
6646
0
  }
6647
6648
0
  return llvm::Error::success();
6649
0
}