Coverage Report

Created: 2023-11-11 10:31

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