Coverage Report

Created: 2023-09-30 09:22

/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
101
                             const llvm::Triple &HostTriple) {
129
101
  if (!Args.hasArg(options::OPT_offload_EQ)) {
130
86
    return llvm::Triple(HostTriple.isArch64Bit() ? 
"nvptx64-nvidia-cuda"78
131
86
                                                 : 
"nvptx-nvidia-cuda"8
);
132
86
  }
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
907
getHIPOffloadTargetTriple(const Driver &D, const ArgList &Args) {
146
907
  if (!Args.hasArg(options::OPT_offload_EQ)) {
147
892
    return llvm::Triple("amdgcn-amd-amdhsa"); // Default HIP triple.
148
892
  }
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
93.6k
                                     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
93.6k
  std::string Dir = std::string(llvm::sys::path::parent_path(BinaryPath));
171
172
93.6k
  SmallString<128> P(Dir);
173
93.6k
  if (CustomResourceDir != "") {
174
0
    llvm::sys::path::append(P, CustomResourceDir);
175
93.6k
  } 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
93.6k
    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
93.6k
    llvm::sys::path::append(P, CLANG_INSTALL_LIBDIR_BASENAME, "clang",
185
93.6k
                            CLANG_VERSION_MAJOR_STRING);
186
93.6k
  }
187
188
93.6k
  return std::string(P.str());
189
93.6k
}
190
191
Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
192
               DiagnosticsEngine &Diags, std::string Title,
193
               IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
194
52.1k
    : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
195
52.1k
      SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
196
52.1k
      Offload(OffloadHostDevice), CXX20HeaderType(HeaderMode_None),
197
52.1k
      ModulesModeCXX20(false), LTOMode(LTOK_None),
198
52.1k
      ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
199
52.1k
      DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false),
200
52.1k
      CCLogDiagnostics(false), CCGenDiagnostics(false),
201
52.1k
      CCPrintProcessStats(false), CCPrintInternalStats(false),
202
52.1k
      TargetTriple(TargetTriple), Saver(Alloc), PrependArg(nullptr),
203
52.1k
      CheckInputsExist(true), ProbePrecompiled(true),
204
52.1k
      SuppressMissingInputWarning(false) {
205
  // Provide a sane fallback if no VFS is specified.
206
52.1k
  if (!this->VFS)
207
22.0k
    this->VFS = llvm::vfs::getRealFileSystem();
208
209
52.1k
  Name = std::string(llvm::sys::path::filename(ClangExecutable));
210
52.1k
  Dir = std::string(llvm::sys::path::parent_path(ClangExecutable));
211
52.1k
  InstalledDir = Dir; // Provide a sensible default installed dir.
212
213
52.1k
  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.1k
  ResourceDir = GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
233
52.1k
}
234
235
5.27k
void Driver::setDriverMode(StringRef Value) {
236
5.27k
  static StringRef OptName =
237
5.27k
      getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
238
5.27k
  if (auto M = llvm::StringSwitch<std::optional<DriverMode>>(Value)
239
5.27k
                   .Case("gcc", GCCMode)
240
5.27k
                   .Case("g++", GXXMode)
241
5.27k
                   .Case("cpp", CPPMode)
242
5.27k
                   .Case("cl", CLMode)
243
5.27k
                   .Case("flang", FlangMode)
244
5.27k
                   .Case("dxc", DXCMode)
245
5.27k
                   .Default(std::nullopt))
246
5.27k
    Mode = *M;
247
1
  else
248
1
    Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
249
5.27k
}
250
251
InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
252
52.2k
                                     bool UseDriverMode, bool &ContainsError) {
253
52.2k
  llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
254
52.2k
  ContainsError = false;
255
256
52.2k
  llvm::opt::Visibility VisibilityMask = getOptionVisibilityMask(UseDriverMode);
257
52.2k
  unsigned MissingArgIndex, MissingArgCount;
258
52.2k
  InputArgList Args = getOpts().ParseArgs(ArgStrings, MissingArgIndex,
259
52.2k
                                          MissingArgCount, VisibilityMask);
260
261
  // Check for missing argument error.
262
52.2k
  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
729k
  for (const Arg *A : Args) {
272
729k
    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
729k
    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
729k
  }
288
289
52.2k
  for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
290
1.30k
    unsigned DiagID;
291
1.30k
    auto ArgString = A->getAsString(Args);
292
1.30k
    std::string Nearest;
293
1.30k
    if (getOpts().findNearest(ArgString, Nearest, VisibilityMask) > 1) {
294
69
      if (!IsCLMode() &&
295
69
          getOpts().findExact(ArgString, Nearest,
296
46
                              llvm::opt::Visibility(options::CC1Option))) {
297
9
        DiagID = diag::err_drv_unknown_argument_with_suggestion;
298
9
        Diags.Report(DiagID) << ArgString << "-Xclang " + Nearest;
299
60
      } else {
300
60
        DiagID = IsCLMode() ? 
diag::warn_drv_unknown_argument_clang_cl23
301
60
                            : 
diag::err_drv_unknown_argument37
;
302
60
        Diags.Report(DiagID) << ArgString;
303
60
      }
304
1.23k
    } else {
305
1.23k
      DiagID = IsCLMode()
306
1.23k
                   ? 
diag::warn_drv_unknown_argument_clang_cl_with_suggestion2
307
1.23k
                   : 
diag::err_drv_unknown_argument_with_suggestion1.23k
;
308
1.23k
      Diags.Report(DiagID) << ArgString << Nearest;
309
1.23k
    }
310
1.30k
    ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
311
1.30k
                     DiagnosticsEngine::Warning;
312
1.30k
  }
313
314
52.2k
  for (const Arg *A : Args.filtered(options::OPT_o)) {
315
8.76k
    if (ArgStrings[A->getIndex()] == A->getSpelling())
316
8.73k
      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.2k
  return Args;
327
52.2k
}
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
150k
                                 Arg **FinalPhaseArg) const {
334
150k
  Arg *PhaseArg = nullptr;
335
150k
  phases::ID FinalPhase;
336
337
  // -{E,EP,P,M,MM} only run the preprocessor.
338
150k
  if (CCCIsCPP() || 
(PhaseArg = DAL.getLastArg(options::OPT_E))150k
||
339
150k
      
(PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP))145k
||
340
150k
      
(PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM))145k
||
341
150k
      
(PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))145k
||
342
150k
      
CCGenDiagnostics145k
) {
343
5.64k
    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
144k
  } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile)) ||
349
144k
             
(PhaseArg = DAL.getLastArg(options::OPT_extract_api))144k
||
350
144k
             (PhaseArg = DAL.getLastArg(options::OPT_fmodule_header,
351
144k
                                        options::OPT_fmodule_header_EQ))) {
352
119
    FinalPhase = phases::Precompile;
353
    // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
354
144k
  } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
355
144k
             
(PhaseArg = DAL.getLastArg(options::OPT_print_supported_cpus))49.0k
||
356
144k
             
(PhaseArg = DAL.getLastArg(options::OPT_module_file_info))49.0k
||
357
144k
             
(PhaseArg = DAL.getLastArg(options::OPT_verify_pch))49.0k
||
358
144k
             
(PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc))49.0k
||
359
144k
             
(PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc))49.0k
||
360
144k
             
(PhaseArg = DAL.getLastArg(options::OPT__migrate))49.0k
||
361
144k
             
(PhaseArg = DAL.getLastArg(options::OPT__analyze))49.0k
||
362
144k
             
(PhaseArg = DAL.getLastArg(options::OPT_emit_ast))48.8k
) {
363
95.9k
    FinalPhase = phases::Compile;
364
365
  // -S only runs up to the backend.
366
95.9k
  } else 
if (48.8k
(PhaseArg = DAL.getLastArg(options::OPT_S))48.8k
) {
367
4.80k
    FinalPhase = phases::Backend;
368
369
  // -c compilation only runs up to the assembler.
370
44.0k
  } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
371
22.7k
    FinalPhase = phases::Assemble;
372
373
22.7k
  } else 
if (21.2k
(PhaseArg = DAL.getLastArg(options::OPT_emit_interface_stubs))21.2k
) {
374
49
    FinalPhase = phases::IfsMerge;
375
376
  // Otherwise do everything.
377
49
  } else
378
21.2k
    FinalPhase = phases::Link;
379
380
150k
  if (FinalPhaseArg)
381
93.6k
    *FinalPhaseArg = PhaseArg;
382
383
150k
  return FinalPhase;
384
150k
}
385
386
static Arg *MakeInputArg(DerivedArgList &Args, const OptTable &Opts,
387
718
                         StringRef Value, bool Claim = true) {
388
718
  Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
389
718
                   Args.getBaseArgs().MakeIndex(Value), Value.data());
390
718
  Args.AddSynthesizedArg(A);
391
718
  if (Claim)
392
27
    A->claim();
393
718
  return A;
394
718
}
395
396
52.1k
DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
397
52.1k
  const llvm::opt::OptTable &Opts = getOpts();
398
52.1k
  DerivedArgList *DAL = new DerivedArgList(Args);
399
400
52.1k
  bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
401
52.1k
  bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
402
52.1k
  bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
403
52.1k
  bool IgnoreUnused = false;
404
729k
  for (Arg *A : Args) {
405
729k
    if (IgnoreUnused)
406
6
      A->claim();
407
408
729k
    if (A->getOption().matches(options::OPT_start_no_unused_arguments)) {
409
3
      IgnoreUnused = true;
410
3
      continue;
411
3
    }
412
729k
    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
729k
    if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
424
729k
         
A->getOption().matches(options::OPT_Xlinker)727k
) &&
425
729k
        
A->containsValue("--no-demangle")2.58k
) {
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
729k
    if (A->getOption().matches(options::OPT_Wp_COMMA) &&
441
729k
        
(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
729k
    if (A->getOption().matches(options::OPT_l)) {
455
3.05k
      StringRef Value = A->getValue();
456
457
      // Rewrite unless -nostdlib is present.
458
3.05k
      if (!HasNostdlib && 
!HasNodefaultlib3.05k
&&
!HasNostdlibxx3.05k
&&
459
3.05k
          
Value == "stdc++"3.05k
) {
460
4
        DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_stdcxx));
461
4
        continue;
462
4
      }
463
464
      // Rewrite unconditionally.
465
3.05k
      if (Value == "cc_kext") {
466
2
        DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_cckext));
467
2
        continue;
468
2
      }
469
3.05k
    }
470
471
    // Pick up inputs via the -- option.
472
729k
    if (A->getOption().matches(options::OPT__DASH_DASH)) {
473
676
      A->claim();
474
676
      for (StringRef Val : A->getValues())
475
691
        DAL->append(MakeInputArg(*DAL, Opts, Val, false));
476
676
      continue;
477
676
    }
478
479
729k
    DAL->append(A);
480
729k
  }
481
482
  // DXC mode quits before assembly if an output object file isn't specified.
483
52.1k
  if (IsDXCMode() && 
!Args.hasArg(options::OPT_dxc_Fo)63
)
484
52
    DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_S));
485
486
  // Enforce -static if -miamcu is present.
487
52.1k
  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.1k
#if defined(HOST_LINK_VERSION)
493
52.1k
  if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
494
52.1k
      
strlen(51.9k
HOST_LINK_VERSION51.9k
) > 0) {
495
51.9k
    DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ),
496
51.9k
                      HOST_LINK_VERSION);
497
51.9k
    DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
498
51.9k
  }
499
52.1k
#endif
500
501
52.1k
  return DAL;
502
52.1k
}
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
79.6k
                                        StringRef DarwinArchName = "") {
512
  // FIXME: Already done in Compilation *Driver::BuildCompilation
513
79.6k
  if (const Arg *A = Args.getLastArg(options::OPT_target))
514
34.2k
    TargetTriple = A->getValue();
515
516
79.6k
  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
79.6k
  if (TargetTriple.contains("-unknown-gnu") || 
TargetTriple.contains("-pc-gnu")79.6k
)
522
2
    Target.setOSName("hurd");
523
524
  // Handle Apple-specific options available here.
525
79.6k
  if (Target.isOSBinFormatMachO()) {
526
    // If an explicit Darwin arch name is given, that trumps all.
527
49.5k
    if (!DarwinArchName.empty()) {
528
20.6k
      tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName,
529
20.6k
                                                   Args);
530
20.6k
      return Target;
531
20.6k
    }
532
533
    // Handle the Darwin '-arch' flag.
534
28.9k
    if (Arg *A = Args.getLastArg(options::OPT_arch)) {
535
10.6k
      StringRef ArchName = A->getValue();
536
10.6k
      tools::darwin::setTripleTypeForMachOArchName(Target, ArchName, Args);
537
10.6k
    }
538
28.9k
  }
539
540
  // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
541
  // '-mbig-endian'/'-EB'.
542
59.0k
  if (Arg *A = Args.getLastArgNoClaim(options::OPT_mlittle_endian,
543
59.0k
                                      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.0k
  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.0k
  if (Target.isOSAIX()) {
559
265
    if (std::optional<std::string> ObjectModeValue =
560
265
            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
265
  }
576
577
  // The `-maix[32|64]` flags are only valid for AIX targets.
578
59.0k
  if (Arg *A = Args.getLastArgNoClaim(options::OPT_maix32, options::OPT_maix64);
579
59.0k
      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.0k
  Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
585
59.0k
                           options::OPT_m32, options::OPT_m16,
586
59.0k
                           options::OPT_maix32, options::OPT_maix64);
587
59.0k
  if (A) {
588
360
    llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
589
590
360
    if (A->getOption().matches(options::OPT_m64) ||
591
360
        
A->getOption().matches(options::OPT_maix64)177
) {
592
185
      AT = Target.get64BitArchVariant().getArch();
593
185
      if (Target.getEnvironment() == llvm::Triple::GNUX32)
594
1
        Target.setEnvironment(llvm::Triple::GNU);
595
184
      else if (Target.getEnvironment() == llvm::Triple::MuslX32)
596
0
        Target.setEnvironment(llvm::Triple::Musl);
597
185
    } else 
if (175
A->getOption().matches(options::OPT_mx32)175
&&
598
175
               
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
172
    } else if (A->getOption().matches(options::OPT_m32) ||
605
172
               
A->getOption().matches(options::OPT_maix32)3
) {
606
171
      AT = Target.get32BitArchVariant().getArch();
607
171
      if (Target.getEnvironment() == llvm::Triple::GNUX32)
608
1
        Target.setEnvironment(llvm::Triple::GNU);
609
170
      else if (Target.getEnvironment() == llvm::Triple::MuslX32)
610
0
        Target.setEnvironment(llvm::Triple::Musl);
611
171
    } 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
360
    if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) {
618
172
      Target.setArch(AT);
619
172
      if (Target.isWindowsGNUEnvironment())
620
1
        toolchains::MinGW::fixTripleArch(D, Target, Args);
621
172
    }
622
360
  }
623
624
  // Handle -miamcu flag.
625
59.0k
  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.0k
  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.0k
  if (Target.isRISCV()) {
670
757
    if (Args.hasArg(options::OPT_march_EQ) ||
671
757
        
Args.hasArg(options::OPT_mcpu_EQ)298
) {
672
487
      StringRef ArchName = tools::riscv::getRISCVArch(Args, Target);
673
487
      if (ArchName.starts_with_insensitive("rv32"))
674
281
        Target.setArch(llvm::Triple::riscv32);
675
206
      else if (ArchName.starts_with_insensitive("rv64"))
676
205
        Target.setArch(llvm::Triple::riscv64);
677
487
    }
678
757
  }
679
680
59.0k
  return Target;
681
59.0k
}
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
103k
    return LTOK_None;
690
691
319
  const Arg *A = Args.getLastArg(OptEq);
692
319
  StringRef LTOName = A->getValue();
693
694
319
  driver::LTOKind LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
695
319
                                .Case("full", LTOK_Full)
696
319
                                .Case("thin", LTOK_Thin)
697
319
                                .Default(LTOK_Unknown);
698
699
319
  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
318
  return LTOMode;
705
319
}
706
707
// Parse the LTO options.
708
52.1k
void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
709
52.1k
  LTOMode =
710
52.1k
      parseLTOMode(*this, Args, options::OPT_flto_EQ, options::OPT_fno_lto);
711
712
52.1k
  OffloadLTOMode = parseLTOMode(*this, Args, options::OPT_foffload_lto_EQ,
713
52.1k
                                options::OPT_fno_offload_lto);
714
715
  // Try to enable `-foffload-lto=full` if `-fopenmp-target-jit` is on.
716
52.1k
  if (Args.hasFlag(options::OPT_fopenmp_target_jit,
717
52.1k
                   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.1k
}
726
727
/// Compute the desired OpenMP runtime from the flags provided.
728
757
Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
729
757
  StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
730
731
757
  const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
732
757
  if (A)
733
686
    RuntimeName = A->getValue();
734
735
757
  auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
736
757
                .Case("libomp", OMPRT_OMP)
737
757
                .Case("libgomp", OMPRT_GOMP)
738
757
                .Case("libiomp5", OMPRT_IOMP5)
739
757
                .Default(OMPRT_Unknown);
740
741
757
  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
757
  return RT;
751
757
}
752
753
void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
754
50.4k
                                              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.4k
  bool IsCuda =
762
56.7k
      llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
763
56.7k
        return types::isCuda(I.first);
764
56.7k
      });
765
50.4k
  bool IsHIP =
766
50.4k
      llvm::any_of(Inputs,
767
56.7k
                   [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
768
56.7k
                     return types::isHIP(I.first);
769
56.7k
                   }) ||
770
50.4k
      
C.getInputArgs().hasArg(options::OPT_hip_link)50.1k
;
771
50.4k
  if (IsCuda && 
IsHIP98
) {
772
2
    Diag(clang::diag::err_drv_mix_cuda_hip);
773
2
    return;
774
2
  }
775
50.4k
  if (IsCuda) {
776
96
    const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
777
96
    const llvm::Triple &HostTriple = HostTC->getTriple();
778
96
    auto OFK = Action::OFK_Cuda;
779
96
    auto CudaTriple =
780
96
        getNVIDIAOffloadTargetTriple(*this, C.getInputArgs(), HostTriple);
781
96
    if (!CudaTriple)
782
0
      return;
783
    // Use the CUDA and host triples as the key into the ToolChains map,
784
    // because the device toolchain we create depends on both.
785
96
    auto &CudaTC = ToolChains[CudaTriple->str() + "/" + HostTriple.str()];
786
96
    if (!CudaTC) {
787
96
      CudaTC = std::make_unique<toolchains::CudaToolChain>(
788
96
          *this, *CudaTriple, *HostTC, C.getInputArgs());
789
790
      // Emit a warning if the detected CUDA version is too new.
791
96
      CudaInstallationDetector &CudaInstallation =
792
96
          static_cast<toolchains::CudaToolChain &>(*CudaTC).CudaInstallation;
793
96
      if (CudaInstallation.isValid())
794
18
        CudaInstallation.WarnIfUnsupportedVersion();
795
96
    }
796
96
    C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
797
50.3k
  } else if (IsHIP) {
798
390
    if (auto *OMPTargetArg =
799
390
            C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
800
1
      Diag(clang::diag::err_drv_unsupported_opt_for_language_mode)
801
1
          << OMPTargetArg->getSpelling() << "HIP";
802
1
      return;
803
1
    }
804
389
    const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
805
389
    auto OFK = Action::OFK_HIP;
806
389
    auto HIPTriple = getHIPOffloadTargetTriple(*this, C.getInputArgs());
807
389
    if (!HIPTriple)
808
4
      return;
809
385
    auto *HIPTC = &getOffloadingDeviceToolChain(C.getInputArgs(), *HIPTriple,
810
385
                                                *HostTC, OFK);
811
385
    assert(HIPTC && "Could not create offloading device tool chain.");
812
385
    C.addOffloadDeviceToolChain(HIPTC, OFK);
813
385
  }
814
815
  //
816
  // OpenMP
817
  //
818
  // We need to generate an OpenMP toolchain if the user specified targets with
819
  // the -fopenmp-targets option or used --offload-arch with OpenMP enabled.
820
50.4k
  bool IsOpenMPOffloading =
821
50.4k
      C.getInputArgs().hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
822
50.4k
                               options::OPT_fno_openmp, false) &&
823
50.4k
      
(652
C.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ)652
||
824
652
       
C.getInputArgs().hasArg(options::OPT_offload_arch_EQ)644
);
825
50.4k
  if (IsOpenMPOffloading) {
826
    // We expect that -fopenmp-targets is always used in conjunction with the
827
    // option -fopenmp specifying a valid runtime with offloading support, i.e.
828
    // libomp or libiomp.
829
14
    OpenMPRuntimeKind RuntimeKind = getOpenMPRuntime(C.getInputArgs());
830
14
    if (RuntimeKind != OMPRT_OMP && 
RuntimeKind != OMPRT_IOMP50
) {
831
0
      Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
832
0
      return;
833
0
    }
834
835
14
    llvm::StringMap<llvm::DenseSet<StringRef>> DerivedArchs;
836
14
    llvm::StringMap<StringRef> FoundNormalizedTriples;
837
14
    std::multiset<StringRef> OpenMPTriples;
838
839
    // If the user specified -fopenmp-targets= we create a toolchain for each
840
    // valid triple. Otherwise, if only --offload-arch= was specified we instead
841
    // attempt to derive the appropriate toolchains from the arguments.
842
14
    if (Arg *OpenMPTargets =
843
14
            C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
844
8
      if (OpenMPTargets && !OpenMPTargets->getNumValues()) {
845
0
        Diag(clang::diag::warn_drv_empty_joined_argument)
846
0
            << OpenMPTargets->getAsString(C.getInputArgs());
847
0
        return;
848
0
      }
849
8
      for (StringRef T : OpenMPTargets->getValues())
850
8
        OpenMPTriples.insert(T);
851
8
    } else 
if (6
C.getInputArgs().hasArg(options::OPT_offload_arch_EQ)6
&&
852
6
               !IsHIP && 
!IsCuda5
) {
853
5
      const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
854
5
      auto AMDTriple = getHIPOffloadTargetTriple(*this, C.getInputArgs());
855
5
      auto NVPTXTriple = getNVIDIAOffloadTargetTriple(*this, C.getInputArgs(),
856
5
                                                      HostTC->getTriple());
857
858
      // Attempt to deduce the offloading triple from the set of architectures.
859
      // We can only correctly deduce NVPTX / AMDGPU triples currently. We need
860
      // to temporarily create these toolchains so that we can access tools for
861
      // inferring architectures.
862
5
      llvm::DenseSet<StringRef> Archs;
863
5
      if (NVPTXTriple) {
864
5
        auto TempTC = std::make_unique<toolchains::CudaToolChain>(
865
5
            *this, *NVPTXTriple, *HostTC, C.getInputArgs());
866
5
        for (StringRef Arch : getOffloadArchs(
867
5
                 C, C.getArgs(), Action::OFK_OpenMP, &*TempTC, true))
868
6
          Archs.insert(Arch);
869
5
      }
870
5
      if (AMDTriple) {
871
5
        auto TempTC = std::make_unique<toolchains::AMDGPUOpenMPToolChain>(
872
5
            *this, *AMDTriple, *HostTC, C.getInputArgs());
873
5
        for (StringRef Arch : getOffloadArchs(
874
5
                 C, C.getArgs(), Action::OFK_OpenMP, &*TempTC, true))
875
6
          Archs.insert(Arch);
876
5
      }
877
5
      if (!AMDTriple && 
!NVPTXTriple0
) {
878
0
        for (StringRef Arch :
879
0
             getOffloadArchs(C, C.getArgs(), Action::OFK_OpenMP, nullptr, true))
880
0
          Archs.insert(Arch);
881
0
      }
882
883
6
      for (StringRef Arch : Archs) {
884
6
        if (NVPTXTriple && IsNVIDIAGpuArch(StringToCudaArch(
885
6
                               getProcessorFromTargetID(*NVPTXTriple, Arch)))) {
886
0
          DerivedArchs[NVPTXTriple->getTriple()].insert(Arch);
887
6
        } else if (AMDTriple &&
888
6
                   IsAMDGpuArch(StringToCudaArch(
889
6
                       getProcessorFromTargetID(*AMDTriple, Arch)))) {
890
6
          DerivedArchs[AMDTriple->getTriple()].insert(Arch);
891
6
        } else {
892
0
          Diag(clang::diag::err_drv_failed_to_deduce_target_from_arch) << Arch;
893
0
          return;
894
0
        }
895
6
      }
896
897
      // If the set is empty then we failed to find a native architecture.
898
5
      if (Archs.empty()) {
899
0
        Diag(clang::diag::err_drv_failed_to_deduce_target_from_arch)
900
0
            << "native";
901
0
        return;
902
0
      }
903
904
5
      for (const auto &TripleAndArchs : DerivedArchs)
905
5
        OpenMPTriples.insert(TripleAndArchs.first());
906
5
    }
907
908
14
    for (StringRef Val : OpenMPTriples) {
909
13
      llvm::Triple TT(ToolChain::getOpenMPTriple(Val));
910
13
      std::string NormalizedName = TT.normalize();
911
912
      // Make sure we don't have a duplicate triple.
913
13
      auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
914
13
      if (Duplicate != FoundNormalizedTriples.end()) {
915
0
        Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
916
0
            << Val << Duplicate->second;
917
0
        continue;
918
0
      }
919
920
      // Store the current triple so that we can check for duplicates in the
921
      // following iterations.
922
13
      FoundNormalizedTriples[NormalizedName] = Val;
923
924
      // If the specified target is invalid, emit a diagnostic.
925
13
      if (TT.getArch() == llvm::Triple::UnknownArch)
926
0
        Diag(clang::diag::err_drv_invalid_omp_target) << Val;
927
13
      else {
928
13
        const ToolChain *TC;
929
        // Device toolchains have to be selected differently. They pair host
930
        // and device in their implementation.
931
13
        if (TT.isNVPTX() || TT.isAMDGCN()) {
932
13
          const ToolChain *HostTC =
933
13
              C.getSingleOffloadToolChain<Action::OFK_Host>();
934
13
          assert(HostTC && "Host toolchain should be always defined.");
935
13
          auto &DeviceTC =
936
13
              ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
937
13
          if (!DeviceTC) {
938
13
            if (TT.isNVPTX())
939
0
              DeviceTC = std::make_unique<toolchains::CudaToolChain>(
940
0
                  *this, TT, *HostTC, C.getInputArgs());
941
13
            else if (TT.isAMDGCN())
942
13
              DeviceTC = std::make_unique<toolchains::AMDGPUOpenMPToolChain>(
943
13
                  *this, TT, *HostTC, C.getInputArgs());
944
0
            else
945
0
              assert(DeviceTC && "Device toolchain not defined.");
946
13
          }
947
948
13
          TC = DeviceTC.get();
949
13
        } else
950
0
          TC = &getToolChain(C.getInputArgs(), TT);
951
13
        C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
952
13
        if (DerivedArchs.contains(TT.getTriple()))
953
5
          KnownArchs[TC] = DerivedArchs[TT.getTriple()];
954
13
      }
955
13
    }
956
50.4k
  } else if (C.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ)) {
957
0
    Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
958
0
    return;
959
0
  }
960
961
  //
962
  // TODO: Add support for other offloading programming models here.
963
  //
964
50.4k
}
965
966
static void appendOneArg(InputArgList &Args, const Arg *Opt,
967
436
                         const Arg *BaseArg) {
968
  // The args for config files or /clang: flags belong to different InputArgList
969
  // objects than Args. This copies an Arg from one of those other InputArgLists
970
  // to the ownership of Args.
971
436
  unsigned Index = Args.MakeIndex(Opt->getSpelling());
972
436
  Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Args.getArgString(Index),
973
436
                                 Index, BaseArg);
974
436
  Copy->getValues() = Opt->getValues();
975
436
  if (Opt->isClaimed())
976
110
    Copy->claim();
977
436
  Copy->setOwnsValues(Opt->getOwnsValues());
978
436
  Opt->setOwnsValues(false);
979
436
  Args.append(Copy);
980
436
}
981
982
bool Driver::readConfigFile(StringRef FileName,
983
63
                            llvm::cl::ExpansionContext &ExpCtx) {
984
  // Try opening the given file.
985
63
  auto Status = getVFS().status(FileName);
986
63
  if (!Status) {
987
2
    Diag(diag::err_drv_cannot_open_config_file)
988
2
        << FileName << Status.getError().message();
989
2
    return true;
990
2
  }
991
61
  if (Status->getType() != llvm::sys::fs::file_type::regular_file) {
992
1
    Diag(diag::err_drv_cannot_open_config_file)
993
1
        << FileName << "not a regular file";
994
1
    return true;
995
1
  }
996
997
  // Try reading the given file.
998
60
  SmallVector<const char *, 32> NewCfgArgs;
999
60
  if (llvm::Error Err = ExpCtx.readConfigFile(FileName, NewCfgArgs)) {
1000
3
    Diag(diag::err_drv_cannot_read_config_file)
1001
3
        << FileName << toString(std::move(Err));
1002
3
    return true;
1003
3
  }
1004
1005
  // Read options from config file.
1006
57
  llvm::SmallString<128> CfgFileName(FileName);
1007
57
  llvm::sys::path::native(CfgFileName);
1008
57
  bool ContainErrors;
1009
57
  std::unique_ptr<InputArgList> NewOptions = std::make_unique<InputArgList>(
1010
57
      ParseArgStrings(NewCfgArgs, /*UseDriverMode=*/true, ContainErrors));
1011
57
  if (ContainErrors)
1012
1
    return true;
1013
1014
  // Claim all arguments that come from a configuration file so that the driver
1015
  // does not warn on any that is unused.
1016
56
  for (Arg *A : *NewOptions)
1017
32
    A->claim();
1018
1019
56
  if (!CfgOptions)
1020
47
    CfgOptions = std::move(NewOptions);
1021
9
  else {
1022
    // If this is a subsequent config file, append options to the previous one.
1023
9
    for (auto *Opt : *NewOptions) {
1024
2
      const Arg *BaseArg = &Opt->getBaseArg();
1025
2
      if (BaseArg == Opt)
1026
2
        BaseArg = nullptr;
1027
2
      appendOneArg(*CfgOptions, Opt, BaseArg);
1028
2
    }
1029
9
  }
1030
56
  ConfigFiles.push_back(std::string(CfgFileName));
1031
56
  return false;
1032
57
}
1033
1034
50.8k
bool Driver::loadConfigFiles() {
1035
50.8k
  llvm::cl::ExpansionContext ExpCtx(Saver.getAllocator(),
1036
50.8k
                                    llvm::cl::tokenizeConfigFile);
1037
50.8k
  ExpCtx.setVFS(&getVFS());
1038
1039
  // Process options that change search path for config files.
1040
50.8k
  if (
CLOptions50.8k
) {
1041
50.8k
    if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
1042
49
      SmallString<128> CfgDir;
1043
49
      CfgDir.append(
1044
49
          CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
1045
49
      if (CfgDir.empty() || 
getVFS().makeAbsolute(CfgDir)17
)
1046
32
        SystemConfigDir.clear();
1047
17
      else
1048
17
        SystemConfigDir = static_cast<std::string>(CfgDir);
1049
49
    }
1050
50.8k
    if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
1051
50
      SmallString<128> CfgDir;
1052
50
      llvm::sys::fs::expand_tilde(
1053
50
          CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ), CfgDir);
1054
50
      if (CfgDir.empty() || 
getVFS().makeAbsolute(CfgDir)11
)
1055
39
        UserConfigDir.clear();
1056
11
      else
1057
11
        UserConfigDir = static_cast<std::string>(CfgDir);
1058
50
    }
1059
50.8k
  }
1060
1061
  // Prepare list of directories where config file is searched for.
1062
50.8k
  StringRef CfgFileSearchDirs[] = {UserConfigDir, SystemConfigDir, Dir};
1063
50.8k
  ExpCtx.setSearchDirs(CfgFileSearchDirs);
1064
1065
  // First try to load configuration from the default files, return on error.
1066
50.8k
  if (loadDefaultConfigFiles(ExpCtx))
1067
0
    return true;
1068
1069
  // Then load configuration files specified explicitly.
1070
50.8k
  SmallString<128> CfgFilePath;
1071
50.8k
  if (
CLOptions50.8k
) {
1072
50.8k
    for (auto CfgFileName : CLOptions->getAllArgValues(options::OPT_config)) {
1073
      // If argument contains directory separator, treat it as a path to
1074
      // configuration file.
1075
37
      if (llvm::sys::path::has_parent_path(CfgFileName)) {
1076
15
        CfgFilePath.assign(CfgFileName);
1077
15
        if (llvm::sys::path::is_relative(CfgFilePath)) {
1078
4
          if (getVFS().makeAbsolute(CfgFilePath)) {
1079
1
            Diag(diag::err_drv_cannot_open_config_file)
1080
1
                << CfgFilePath << "cannot get absolute path";
1081
1
            return true;
1082
1
          }
1083
4
        }
1084
22
      } else if (!ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) {
1085
        // Report an error that the config file could not be found.
1086
5
        Diag(diag::err_drv_config_file_not_found) << CfgFileName;
1087
5
        for (const StringRef &SearchDir : CfgFileSearchDirs)
1088
15
          if (!SearchDir.empty())
1089
9
            Diag(diag::note_drv_config_file_searched_in) << SearchDir;
1090
5
        return true;
1091
5
      }
1092
1093
      // Try to read the config file, return on error.
1094
31
      if (readConfigFile(CfgFilePath, ExpCtx))
1095
7
        return true;
1096
31
    }
1097
50.8k
  }
1098
1099
  // No error occurred.
1100
50.8k
  return false;
1101
50.8k
}
1102
1103
50.8k
bool Driver::loadDefaultConfigFiles(llvm::cl::ExpansionContext &ExpCtx) {
1104
  // Disable default config if CLANG_NO_DEFAULT_CONFIG is set to a non-empty
1105
  // value.
1106
50.8k
  if (const char *NoConfigEnv = ::getenv("CLANG_NO_DEFAULT_CONFIG")) {
1107
43.9k
    if (*NoConfigEnv)
1108
43.9k
      return false;
1109
43.9k
  }
1110
6.90k
  
if (6.89k
CLOptions6.89k
&& CLOptions->hasArg(options::OPT_no_default_config))
1111
2
    return false;
1112
1113
6.89k
  std::string RealMode = getExecutableForDriverMode(Mode);
1114
6.89k
  std::string Triple;
1115
1116
  // If name prefix is present, no --target= override was passed via CLOptions
1117
  // and the name prefix is not a valid triple, force it for backwards
1118
  // compatibility.
1119
6.89k
  if (!ClangNameParts.TargetPrefix.empty() &&
1120
6.89k
      computeTargetTriple(*this, "/invalid/", *CLOptions).str() ==
1121
26
          "/invalid/") {
1122
4
    llvm::Triple PrefixTriple{ClangNameParts.TargetPrefix};
1123
4
    if (PrefixTriple.getArch() == llvm::Triple::UnknownArch ||
1124
4
        
PrefixTriple.isOSUnknown()0
)
1125
4
      Triple = PrefixTriple.str();
1126
4
  }
1127
1128
  // Otherwise, use the real triple as used by the driver.
1129
6.89k
  if (Triple.empty()) {
1130
6.89k
    llvm::Triple RealTriple =
1131
6.89k
        computeTargetTriple(*this, TargetTriple, *CLOptions);
1132
6.89k
    Triple = RealTriple.str();
1133
6.89k
    assert(!Triple.empty());
1134
6.89k
  }
1135
1136
  // Search for config files in the following order:
1137
  // 1. <triple>-<mode>.cfg using real driver mode
1138
  //    (e.g. i386-pc-linux-gnu-clang++.cfg).
1139
  // 2. <triple>-<mode>.cfg using executable suffix
1140
  //    (e.g. i386-pc-linux-gnu-clang-g++.cfg for *clang-g++).
1141
  // 3. <triple>.cfg + <mode>.cfg using real driver mode
1142
  //    (e.g. i386-pc-linux-gnu.cfg + clang++.cfg).
1143
  // 4. <triple>.cfg + <mode>.cfg using executable suffix
1144
  //    (e.g. i386-pc-linux-gnu.cfg + clang-g++.cfg for *clang-g++).
1145
1146
  // Try loading <triple>-<mode>.cfg, and return if we find a match.
1147
6.89k
  SmallString<128> CfgFilePath;
1148
6.89k
  std::string CfgFileName = Triple + '-' + RealMode + ".cfg";
1149
6.89k
  if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath))
1150
13
    return readConfigFile(CfgFilePath, ExpCtx);
1151
1152
6.88k
  bool TryModeSuffix = !ClangNameParts.ModeSuffix.empty() &&
1153
6.88k
                       ClangNameParts.ModeSuffix != RealMode;
1154
6.88k
  if (TryModeSuffix) {
1155
4.15k
    CfgFileName = Triple + '-' + ClangNameParts.ModeSuffix + ".cfg";
1156
4.15k
    if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath))
1157
3
      return readConfigFile(CfgFilePath, ExpCtx);
1158
4.15k
  }
1159
1160
  // Try loading <mode>.cfg, and return if loading failed.  If a matching file
1161
  // was not found, still proceed on to try <triple>.cfg.
1162
6.87k
  CfgFileName = RealMode + ".cfg";
1163
6.87k
  if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) {
1164
6
    if (readConfigFile(CfgFilePath, ExpCtx))
1165
0
      return true;
1166
6.87k
  } else if (TryModeSuffix) {
1167
4.14k
    CfgFileName = ClangNameParts.ModeSuffix + ".cfg";
1168
4.14k
    if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath) &&
1169
4.14k
        
readConfigFile(CfgFilePath, ExpCtx)3
)
1170
0
      return true;
1171
4.14k
  }
1172
1173
  // Try loading <triple>.cfg and return if we find a match.
1174
6.87k
  CfgFileName = Triple + ".cfg";
1175
6.87k
  if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath))
1176
7
    return readConfigFile(CfgFilePath, ExpCtx);
1177
1178
  // If we were unable to find a config file deduced from executable name,
1179
  // that is not an error.
1180
6.87k
  return false;
1181
6.87k
}
1182
1183
52.1k
Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
1184
52.1k
  llvm::PrettyStackTraceString CrashInfo("Compilation construction");
1185
1186
  // FIXME: Handle environment options which affect driver behavior, somewhere
1187
  // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
1188
1189
  // We look for the driver mode option early, because the mode can affect
1190
  // how other options are parsed.
1191
1192
52.1k
  auto DriverMode = getDriverMode(ClangExecutable, ArgList.slice(1));
1193
52.1k
  if (!DriverMode.empty())
1194
5.27k
    setDriverMode(DriverMode);
1195
1196
  // FIXME: What are we going to do with -V and -b?
1197
1198
  // Arguments specified in command line.
1199
52.1k
  bool ContainsError;
1200
52.1k
  CLOptions = std::make_unique<InputArgList>(
1201
52.1k
      ParseArgStrings(ArgList.slice(1), /*UseDriverMode=*/true, ContainsError));
1202
1203
  // Try parsing configuration file.
1204
52.1k
  if (!ContainsError)
1205
50.8k
    ContainsError = loadConfigFiles();
1206
52.1k
  bool HasConfigFile = !ContainsError && 
(CfgOptions.get() != nullptr)50.8k
;
1207
1208
  // All arguments, from both config file and command line.
1209
52.1k
  InputArgList Args = std::move(HasConfigFile ? 
std::move(*CfgOptions)46
1210
52.1k
                                              : 
std::move(*CLOptions)52.0k
);
1211
1212
52.1k
  if (HasConfigFile)
1213
270
    
for (auto *Opt : *CLOptions)46
{
1214
270
      if (Opt->getOption().matches(options::OPT_config))
1215
23
        continue;
1216
247
      const Arg *BaseArg = &Opt->getBaseArg();
1217
247
      if (BaseArg == Opt)
1218
247
        BaseArg = nullptr;
1219
247
      appendOneArg(Args, Opt, BaseArg);
1220
247
    }
1221
1222
  // In CL mode, look for any pass-through arguments
1223
52.1k
  if (IsCLMode() && 
!ContainsError697
) {
1224
693
    SmallVector<const char *, 16> CLModePassThroughArgList;
1225
693
    for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
1226
223
      A->claim();
1227
223
      CLModePassThroughArgList.push_back(A->getValue());
1228
223
    }
1229
1230
693
    if (!CLModePassThroughArgList.empty()) {
1231
      // Parse any pass through args using default clang processing rather
1232
      // than clang-cl processing.
1233
55
      auto CLModePassThroughOptions = std::make_unique<InputArgList>(
1234
55
          ParseArgStrings(CLModePassThroughArgList, /*UseDriverMode=*/false,
1235
55
                          ContainsError));
1236
1237
55
      if (!ContainsError)
1238
187
        
for (auto *Opt : *CLModePassThroughOptions)55
{
1239
187
          appendOneArg(Args, Opt, nullptr);
1240
187
        }
1241
55
    }
1242
693
  }
1243
1244
  // Check for working directory option before accessing any files
1245
52.1k
  if (Arg *WD = Args.getLastArg(options::OPT_working_directory))
1246
19
    if (VFS->setCurrentWorkingDirectory(WD->getValue()))
1247
1
      Diag(diag::err_drv_unable_to_set_working_directory) << WD->getValue();
1248
1249
  // FIXME: This stuff needs to go into the Compilation, not the driver.
1250
52.1k
  bool CCCPrintPhases;
1251
1252
  // -canonical-prefixes, -no-canonical-prefixes are used very early in main.
1253
52.1k
  Args.ClaimAllArgs(options::OPT_canonical_prefixes);
1254
52.1k
  Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
1255
1256
  // f(no-)integated-cc1 is also used very early in main.
1257
52.1k
  Args.ClaimAllArgs(options::OPT_fintegrated_cc1);
1258
52.1k
  Args.ClaimAllArgs(options::OPT_fno_integrated_cc1);
1259
1260
  // Ignore -pipe.
1261
52.1k
  Args.ClaimAllArgs(options::OPT_pipe);
1262
1263
  // Extract -ccc args.
1264
  //
1265
  // FIXME: We need to figure out where this behavior should live. Most of it
1266
  // should be outside in the client; the parts that aren't should have proper
1267
  // options, either by introducing new ones or by overloading gcc ones like -V
1268
  // or -b.
1269
52.1k
  CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
1270
52.1k
  CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
1271
52.1k
  if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
1272
0
    CCCGenericGCCName = A->getValue();
1273
1274
  // Process -fproc-stat-report options.
1275
52.1k
  if (const Arg *A = Args.getLastArg(options::OPT_fproc_stat_report_EQ)) {
1276
1
    CCPrintProcessStats = true;
1277
1
    CCPrintStatReportFilename = A->getValue();
1278
1
  }
1279
52.1k
  if (Args.hasArg(options::OPT_fproc_stat_report))
1280
1
    CCPrintProcessStats = true;
1281
1282
  // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
1283
  // and getToolChain is const.
1284
52.1k
  if (IsCLMode()) {
1285
    // clang-cl targets MSVC-style Win32.
1286
696
    llvm::Triple T(TargetTriple);
1287
696
    T.setOS(llvm::Triple::Win32);
1288
696
    T.setVendor(llvm::Triple::PC);
1289
696
    T.setEnvironment(llvm::Triple::MSVC);
1290
696
    T.setObjectFormat(llvm::Triple::COFF);
1291
696
    if (Args.hasArg(options::OPT__SLASH_arm64EC))
1292
2
      T.setArch(llvm::Triple::aarch64, llvm::Triple::AArch64SubArch_arm64ec);
1293
696
    TargetTriple = T.str();
1294
51.4k
  } else if (IsDXCMode()) {
1295
    // Build TargetTriple from target_profile option for clang-dxc.
1296
63
    if (const Arg *A = Args.getLastArg(options::OPT_target_profile)) {
1297
62
      StringRef TargetProfile = A->getValue();
1298
62
      if (auto Triple =
1299
62
              toolchains::HLSLToolChain::parseTargetProfile(TargetProfile))
1300
58
        TargetTriple = *Triple;
1301
4
      else
1302
4
        Diag(diag::err_drv_invalid_directx_shader_module) << TargetProfile;
1303
1304
62
      A->claim();
1305
62
    } else {
1306
1
      Diag(diag::err_drv_dxc_missing_target_profile);
1307
1
    }
1308
63
  }
1309
1310
52.1k
  if (const Arg *A = Args.getLastArg(options::OPT_target))
1311
31.7k
    TargetTriple = A->getValue();
1312
52.1k
  if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
1313
137
    Dir = InstalledDir = A->getValue();
1314
52.1k
  for (const Arg *A : Args.filtered(options::OPT_B)) {
1315
67
    A->claim();
1316
67
    PrefixDirs.push_back(A->getValue(0));
1317
67
  }
1318
52.1k
  if (std::optional<std::string> CompilerPathValue =
1319
52.1k
          llvm::sys::Process::GetEnv("COMPILER_PATH")) {
1320
4
    StringRef CompilerPath = *CompilerPathValue;
1321
8
    while (!CompilerPath.empty()) {
1322
4
      std::pair<StringRef, StringRef> Split =
1323
4
          CompilerPath.split(llvm::sys::EnvPathSeparator);
1324
4
      PrefixDirs.push_back(std::string(Split.first));
1325
4
      CompilerPath = Split.second;
1326
4
    }
1327
4
  }
1328
52.1k
  if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
1329
1.06k
    SysRoot = A->getValue();
1330
52.1k
  if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
1331
3
    DyldPrefix = A->getValue();
1332
1333
52.1k
  if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
1334
2.03k
    ResourceDir = A->getValue();
1335
1336
52.1k
  if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
1337
82
    SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1338
82
                    .Case("cwd", SaveTempsCwd)
1339
82
                    .Case("obj", SaveTempsObj)
1340
82
                    .Default(SaveTempsCwd);
1341
82
  }
1342
1343
52.1k
  if (const Arg *A = Args.getLastArg(options::OPT_offload_host_only,
1344
52.1k
                                     options::OPT_offload_device_only,
1345
52.1k
                                     options::OPT_offload_host_device)) {
1346
150
    if (A->getOption().matches(options::OPT_offload_host_only))
1347
31
      Offload = OffloadHost;
1348
119
    else if (A->getOption().matches(options::OPT_offload_device_only))
1349
119
      Offload = OffloadDevice;
1350
0
    else
1351
0
      Offload = OffloadHostDevice;
1352
150
  }
1353
1354
52.1k
  setLTOMode(Args);
1355
1356
  // Process -fembed-bitcode= flags.
1357
52.1k
  if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1358
26
    StringRef Name = A->getValue();
1359
26
    unsigned Model = llvm::StringSwitch<unsigned>(Name)
1360
26
        .Case("off", EmbedNone)
1361
26
        .Case("all", EmbedBitcode)
1362
26
        .Case("bitcode", EmbedBitcode)
1363
26
        .Case("marker", EmbedMarker)
1364
26
        .Default(~0U);
1365
26
    if (Model == ~0U) {
1366
0
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1367
0
                                                << Name;
1368
0
    } else
1369
26
      BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
1370
26
  }
1371
1372
  // Remove existing compilation database so that each job can append to it.
1373
52.1k
  if (Arg *A = Args.getLastArg(options::OPT_MJ))
1374
6
    llvm::sys::fs::remove(A->getValue());
1375
1376
  // Setting up the jobs for some precompile cases depends on whether we are
1377
  // treating them as PCH, implicit modules or C++20 ones.
1378
  // TODO: inferring the mode like this seems fragile (it meets the objective
1379
  // of not requiring anything new for operation, however).
1380
52.1k
  const Arg *Std = Args.getLastArg(options::OPT_std_EQ);
1381
52.1k
  ModulesModeCXX20 =
1382
52.1k
      !Args.hasArg(options::OPT_fmodules) && 
Std50.5k
&&
1383
52.1k
      
(28.2k
Std->containsValue("c++20")28.2k
||
Std->containsValue("c++2a")25.0k
||
1384
28.2k
       
Std->containsValue("c++23")25.0k
||
Std->containsValue("c++2b")25.0k
||
1385
28.2k
       
Std->containsValue("c++26")25.0k
||
Std->containsValue("c++2c")25.0k
||
1386
28.2k
       
Std->containsValue("c++latest")25.0k
);
1387
1388
  // Process -fmodule-header{=} flags.
1389
52.1k
  if (Arg *A = Args.getLastArg(options::OPT_fmodule_header_EQ,
1390
52.1k
                               options::OPT_fmodule_header)) {
1391
    // These flags force C++20 handling of headers.
1392
7
    ModulesModeCXX20 = true;
1393
7
    if (A->getOption().matches(options::OPT_fmodule_header))
1394
1
      CXX20HeaderType = HeaderMode_Default;
1395
6
    else {
1396
6
      StringRef ArgName = A->getValue();
1397
6
      unsigned Kind = llvm::StringSwitch<unsigned>(ArgName)
1398
6
                          .Case("user", HeaderMode_User)
1399
6
                          .Case("system", HeaderMode_System)
1400
6
                          .Default(~0U);
1401
6
      if (Kind == ~0U) {
1402
0
        Diags.Report(diag::err_drv_invalid_value)
1403
0
            << A->getAsString(Args) << ArgName;
1404
0
      } else
1405
6
        CXX20HeaderType = static_cast<ModuleHeaderMode>(Kind);
1406
6
    }
1407
7
  }
1408
1409
52.1k
  std::unique_ptr<llvm::opt::InputArgList> UArgs =
1410
52.1k
      std::make_unique<InputArgList>(std::move(Args));
1411
1412
  // Perform the default argument translations.
1413
52.1k
  DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
1414
1415
  // Owned by the host.
1416
52.1k
  const ToolChain &TC = getToolChain(
1417
52.1k
      *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
1418
1419
  // Report warning when arm64EC option is overridden by specified target
1420
52.1k
  if ((TC.getTriple().getArch() != llvm::Triple::aarch64 ||
1421
52.1k
       
TC.getTriple().getSubArch() != llvm::Triple::AArch64SubArch_arm64ec1.66k
) &&
1422
52.1k
      UArgs->hasArg(options::OPT__SLASH_arm64EC)) {
1423
1
    getDiags().Report(clang::diag::warn_target_override_arm64ec)
1424
1
        << TC.getTriple().str();
1425
1
  }
1426
1427
  // A common user mistake is specifying a target of aarch64-none-eabi or
1428
  // arm-none-elf whereas the correct names are aarch64-none-elf &
1429
  // arm-none-eabi. Detect these cases and issue a warning.
1430
52.1k
  if (TC.getTriple().getOS() == llvm::Triple::UnknownOS &&
1431
52.1k
      
TC.getTriple().getVendor() == llvm::Triple::UnknownVendor14.5k
) {
1432
14.5k
    switch (TC.getTriple().getArch()) {
1433
1.06k
    case llvm::Triple::arm:
1434
1.17k
    case llvm::Triple::armeb:
1435
1.20k
    case llvm::Triple::thumb:
1436
1.20k
    case llvm::Triple::thumbeb:
1437
1.20k
      if (TC.getTriple().getEnvironmentName() == "elf") {
1438
4
        Diag(diag::warn_target_unrecognized_env)
1439
4
            << TargetTriple
1440
4
            << (TC.getTriple().getArchName().str() + "-none-eabi");
1441
4
      }
1442
1.20k
      break;
1443
889
    case llvm::Triple::aarch64:
1444
1.09k
    case llvm::Triple::aarch64_be:
1445
1.09k
    case llvm::Triple::aarch64_32:
1446
1.09k
      if (TC.getTriple().getEnvironmentName().startswith("eabi")) {
1447
4
        Diag(diag::warn_target_unrecognized_env)
1448
4
            << TargetTriple
1449
4
            << (TC.getTriple().getArchName().str() + "-none-elf");
1450
4
      }
1451
1.09k
      break;
1452
12.2k
    default:
1453
12.2k
      break;
1454
14.5k
    }
1455
14.5k
  }
1456
1457
  // The compilation takes ownership of Args.
1458
52.1k
  Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1459
52.1k
                                   ContainsError);
1460
1461
52.1k
  if (!HandleImmediateArgs(*C))
1462
1.65k
    return C;
1463
1464
  // Construct the list of inputs.
1465
50.4k
  InputList Inputs;
1466
50.4k
  BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
1467
1468
  // Populate the tool chains for the offloading devices, if any.
1469
50.4k
  CreateOffloadingDeviceToolChains(*C, Inputs);
1470
1471
  // Construct the list of abstract actions to perform for this compilation. On
1472
  // MachO targets this uses the driver-driver and universal actions.
1473
50.4k
  if (TC.getTriple().isOSBinFormatMachO())
1474
20.5k
    BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
1475
29.9k
  else
1476
29.9k
    BuildActions(*C, C->getArgs(), Inputs, C->getActions());
1477
1478
50.4k
  if (CCCPrintPhases) {
1479
87
    PrintActions(*C);
1480
87
    return C;
1481
87
  }
1482
1483
50.3k
  BuildJobs(*C);
1484
1485
50.3k
  return C;
1486
50.4k
}
1487
1488
42
static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1489
42
  llvm::opt::ArgStringList ASL;
1490
344
  for (const auto *A : Args) {
1491
    // Use user's original spelling of flags. For example, use
1492
    // `/source-charset:utf-8` instead of `-finput-charset=utf-8` if the user
1493
    // wrote the former.
1494
351
    while (A->getAlias())
1495
7
      A = A->getAlias();
1496
344
    A->render(Args, ASL);
1497
344
  }
1498
1499
561
  for (auto I = ASL.begin(), E = ASL.end(); I != E; 
++I519
) {
1500
519
    if (I != ASL.begin())
1501
477
      OS << ' ';
1502
519
    llvm::sys::printArg(OS, *I, true);
1503
519
  }
1504
42
  OS << '\n';
1505
42
}
1506
1507
bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1508
42
                                    SmallString<128> &CrashDiagDir) {
1509
42
  using namespace llvm::sys;
1510
42
  assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1511
42
         "Only knows about .crash files on Darwin");
1512
1513
  // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1514
  // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1515
  // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1516
42
  path::home_directory(CrashDiagDir);
1517
42
  if (CrashDiagDir.startswith("/var/root"))
1518
0
    CrashDiagDir = "/";
1519
42
  path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1520
42
  int PID =
1521
42
#if LLVM_ON_UNIX
1522
42
      getpid();
1523
#else
1524
      0;
1525
#endif
1526
42
  std::error_code EC;
1527
42
  fs::file_status FileStatus;
1528
42
  TimePoint<> LastAccessTime;
1529
42
  SmallString<128> CrashFilePath;
1530
  // Lookup the .crash files and get the one generated by a subprocess spawned
1531
  // by this driver invocation.
1532
42
  for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1533
210
       File != FileEnd && 
!EC168
;
File.increment(EC)168
) {
1534
168
    StringRef FileName = path::filename(File->path());
1535
168
    if (!FileName.startswith(Name))
1536
168
      continue;
1537
0
    if (fs::status(File->path(), FileStatus))
1538
0
      continue;
1539
0
    llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1540
0
        llvm::MemoryBuffer::getFile(File->path());
1541
0
    if (!CrashFile)
1542
0
      continue;
1543
    // The first line should start with "Process:", otherwise this isn't a real
1544
    // .crash file.
1545
0
    StringRef Data = CrashFile.get()->getBuffer();
1546
0
    if (!Data.startswith("Process:"))
1547
0
      continue;
1548
    // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1549
0
    size_t ParentProcPos = Data.find("Parent Process:");
1550
0
    if (ParentProcPos == StringRef::npos)
1551
0
      continue;
1552
0
    size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1553
0
    if (LineEnd == StringRef::npos)
1554
0
      continue;
1555
0
    StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1556
0
    int OpenBracket = -1, CloseBracket = -1;
1557
0
    for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1558
0
      if (ParentProcess[i] == '[')
1559
0
        OpenBracket = i;
1560
0
      if (ParentProcess[i] == ']')
1561
0
        CloseBracket = i;
1562
0
    }
1563
    // Extract the parent process PID from the .crash file and check whether
1564
    // it matches this driver invocation pid.
1565
0
    int CrashPID;
1566
0
    if (OpenBracket < 0 || CloseBracket < 0 ||
1567
0
        ParentProcess.slice(OpenBracket + 1, CloseBracket)
1568
0
            .getAsInteger(10, CrashPID) || CrashPID != PID) {
1569
0
      continue;
1570
0
    }
1571
1572
    // Found a .crash file matching the driver pid. To avoid getting an older
1573
    // and misleading crash file, continue looking for the most recent.
1574
    // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1575
    // multiple crashes poiting to the same parent process. Since the driver
1576
    // does not collect pid information for the dispatched invocation there's
1577
    // currently no way to distinguish among them.
1578
0
    const auto FileAccessTime = FileStatus.getLastModificationTime();
1579
0
    if (FileAccessTime > LastAccessTime) {
1580
0
      CrashFilePath.assign(File->path());
1581
0
      LastAccessTime = FileAccessTime;
1582
0
    }
1583
0
  }
1584
1585
  // If found, copy it over to the location of other reproducer files.
1586
42
  if (!CrashFilePath.empty()) {
1587
0
    EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1588
0
    if (EC)
1589
0
      return false;
1590
0
    return true;
1591
0
  }
1592
1593
42
  return false;
1594
42
}
1595
1596
static const char BugReporMsg[] =
1597
    "\n********************\n\n"
1598
    "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1599
    "Preprocessed source(s) and associated run script(s) are located at:";
1600
1601
// When clang crashes, produce diagnostic information including the fully
1602
// preprocessed source file(s).  Request that the developer attach the
1603
// diagnostic information to a bug report.
1604
void Driver::generateCompilationDiagnostics(
1605
    Compilation &C, const Command &FailingCommand,
1606
45
    StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
1607
45
  if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
1608
0
    return;
1609
1610
45
  unsigned Level = 1;
1611
45
  if (Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_EQ)) {
1612
3
    Level = llvm::StringSwitch<unsigned>(A->getValue())
1613
3
                .Case("off", 0)
1614
3
                .Case("compiler", 1)
1615
3
                .Case("all", 2)
1616
3
                .Default(1);
1617
3
  }
1618
45
  if (!Level)
1619
0
    return;
1620
1621
  // Don't try to generate diagnostics for dsymutil jobs.
1622
45
  if (FailingCommand.getCreator().isDsymutilJob())
1623
0
    return;
1624
1625
45
  bool IsLLD = false;
1626
45
  ArgStringList SavedTemps;
1627
45
  if (FailingCommand.getCreator().isLinkJob()) {
1628
0
    C.getDefaultToolChain().GetLinkerPath(&IsLLD);
1629
0
    if (!IsLLD || Level < 2)
1630
0
      return;
1631
1632
    // If lld crashed, we will re-run the same command with the input it used
1633
    // to have. In that case we should not remove temp files in
1634
    // initCompilationForDiagnostics yet. They will be added back and removed
1635
    // later.
1636
0
    SavedTemps = std::move(C.getTempFiles());
1637
0
    assert(!C.getTempFiles().size());
1638
0
  }
1639
1640
  // Print the version of the compiler.
1641
45
  PrintVersion(C, llvm::errs());
1642
1643
  // Suppress driver output and emit preprocessor output to temp file.
1644
45
  CCGenDiagnostics = true;
1645
1646
  // Save the original job command(s).
1647
45
  Command Cmd = FailingCommand;
1648
1649
  // Keep track of whether we produce any errors while trying to produce
1650
  // preprocessed sources.
1651
45
  DiagnosticErrorTrap Trap(Diags);
1652
1653
  // Suppress tool output.
1654
45
  C.initCompilationForDiagnostics();
1655
1656
  // If lld failed, rerun it again with --reproduce.
1657
45
  if (IsLLD) {
1658
0
    const char *TmpName = CreateTempFile(C, "linker-crash", "tar");
1659
0
    Command NewLLDInvocation = Cmd;
1660
0
    llvm::opt::ArgStringList ArgList = NewLLDInvocation.getArguments();
1661
0
    StringRef ReproduceOption =
1662
0
        C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment()
1663
0
            ? "/reproduce:"
1664
0
            : "--reproduce=";
1665
0
    ArgList.push_back(Saver.save(Twine(ReproduceOption) + TmpName).data());
1666
0
    NewLLDInvocation.replaceArguments(std::move(ArgList));
1667
1668
    // Redirect stdout/stderr to /dev/null.
1669
0
    NewLLDInvocation.Execute({std::nullopt, {""}, {""}}, nullptr, nullptr);
1670
0
    Diag(clang::diag::note_drv_command_failed_diag_msg) << BugReporMsg;
1671
0
    Diag(clang::diag::note_drv_command_failed_diag_msg) << TmpName;
1672
0
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1673
0
        << "\n\n********************";
1674
0
    if (Report)
1675
0
      Report->TemporaryFiles.push_back(TmpName);
1676
0
    return;
1677
0
  }
1678
1679
  // Construct the list of inputs.
1680
45
  InputList Inputs;
1681
45
  BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
1682
1683
94
  for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
1684
49
    bool IgnoreInput = false;
1685
1686
    // Ignore input from stdin or any inputs that cannot be preprocessed.
1687
    // Check type first as not all linker inputs have a value.
1688
49
    if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
1689
3
      IgnoreInput = true;
1690
46
    } else if (!strcmp(it->second->getValue(), "-")) {
1691
0
      Diag(clang::diag::note_drv_command_failed_diag_msg)
1692
0
          << "Error generating preprocessed source(s) - "
1693
0
             "ignoring input from stdin.";
1694
0
      IgnoreInput = true;
1695
0
    }
1696
1697
49
    if (IgnoreInput) {
1698
3
      it = Inputs.erase(it);
1699
3
      ie = Inputs.end();
1700
46
    } else {
1701
46
      ++it;
1702
46
    }
1703
49
  }
1704
1705
45
  if (Inputs.empty()) {
1706
1
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1707
1
        << "Error generating preprocessed source(s) - "
1708
1
           "no preprocessable inputs.";
1709
1
    return;
1710
1
  }
1711
1712
  // Don't attempt to generate preprocessed files if multiple -arch options are
1713
  // used, unless they're all duplicates.
1714
44
  llvm::StringSet<> ArchNames;
1715
393
  for (const Arg *A : C.getArgs()) {
1716
393
    if (A->getOption().matches(options::OPT_arch)) {
1717
0
      StringRef ArchName = A->getValue();
1718
0
      ArchNames.insert(ArchName);
1719
0
    }
1720
393
  }
1721
44
  if (ArchNames.size() > 1) {
1722
0
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1723
0
        << "Error generating preprocessed source(s) - cannot generate "
1724
0
           "preprocessed source with multiple -arch options.";
1725
0
    return;
1726
0
  }
1727
1728
  // Construct the list of abstract actions to perform for this compilation. On
1729
  // Darwin OSes this uses the driver-driver and builds universal actions.
1730
44
  const ToolChain &TC = C.getDefaultToolChain();
1731
44
  if (TC.getTriple().isOSBinFormatMachO())
1732
37
    BuildUniversalActions(C, TC, Inputs);
1733
7
  else
1734
7
    BuildActions(C, C.getArgs(), Inputs, C.getActions());
1735
1736
44
  BuildJobs(C);
1737
1738
  // If there were errors building the compilation, quit now.
1739
44
  if (Trap.hasErrorOccurred()) {
1740
0
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1741
0
        << "Error generating preprocessed source(s).";
1742
0
    return;
1743
0
  }
1744
1745
  // Generate preprocessed output.
1746
44
  SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
1747
44
  C.ExecuteJobs(C.getJobs(), FailingCommands);
1748
1749
  // If any of the preprocessing commands failed, clean up and exit.
1750
44
  if (!FailingCommands.empty()) {
1751
2
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1752
2
        << "Error generating preprocessed source(s).";
1753
2
    return;
1754
2
  }
1755
1756
42
  const ArgStringList &TempFiles = C.getTempFiles();
1757
42
  if (TempFiles.empty()) {
1758
0
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1759
0
        << "Error generating preprocessed source(s).";
1760
0
    return;
1761
0
  }
1762
1763
42
  Diag(clang::diag::note_drv_command_failed_diag_msg) << BugReporMsg;
1764
1765
42
  SmallString<128> VFS;
1766
42
  SmallString<128> ReproCrashFilename;
1767
56
  for (const char *TempFile : TempFiles) {
1768
56
    Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
1769
56
    if (Report)
1770
3
      Report->TemporaryFiles.push_back(TempFile);
1771
56
    if (ReproCrashFilename.empty()) {
1772
42
      ReproCrashFilename = TempFile;
1773
42
      llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1774
42
    }
1775
56
    if (StringRef(TempFile).endswith(".cache")) {
1776
      // In some cases (modules) we'll dump extra data to help with reproducing
1777
      // the crash into a directory next to the output.
1778
14
      VFS = llvm::sys::path::filename(TempFile);
1779
14
      llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1780
14
    }
1781
56
  }
1782
1783
42
  for (const char *TempFile : SavedTemps)
1784
0
    C.addTempFile(TempFile);
1785
1786
  // Assume associated files are based off of the first temporary file.
1787
42
  CrashReportInfo CrashInfo(TempFiles[0], VFS);
1788
1789
42
  llvm::SmallString<128> Script(CrashInfo.Filename);
1790
42
  llvm::sys::path::replace_extension(Script, "sh");
1791
42
  std::error_code EC;
1792
42
  llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew,
1793
42
                                llvm::sys::fs::FA_Write,
1794
42
                                llvm::sys::fs::OF_Text);
1795
42
  if (EC) {
1796
0
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1797
0
        << "Error generating run script: " << Script << " " << EC.message();
1798
42
  } else {
1799
42
    ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
1800
42
             << "# Driver args: ";
1801
42
    printArgList(ScriptOS, C.getInputArgs());
1802
42
    ScriptOS << "# Original command: ";
1803
42
    Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
1804
42
    Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
1805
42
    if (!AdditionalInformation.empty())
1806
3
      ScriptOS << "\n# Additional information: " << AdditionalInformation
1807
3
               << "\n";
1808
42
    if (Report)
1809
3
      Report->TemporaryFiles.push_back(std::string(Script.str()));
1810
42
    Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
1811
42
  }
1812
1813
  // On darwin, provide information about the .crash diagnostic report.
1814
42
  if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1815
42
    SmallString<128> CrashDiagDir;
1816
42
    if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1817
0
      Diag(clang::diag::note_drv_command_failed_diag_msg)
1818
0
          << ReproCrashFilename.str();
1819
42
    } else { // Suggest a directory for the user to look for .crash files.
1820
42
      llvm::sys::path::append(CrashDiagDir, Name);
1821
42
      CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1822
42
      Diag(clang::diag::note_drv_command_failed_diag_msg)
1823
42
          << "Crash backtrace is located in";
1824
42
      Diag(clang::diag::note_drv_command_failed_diag_msg)
1825
42
          << CrashDiagDir.str();
1826
42
      Diag(clang::diag::note_drv_command_failed_diag_msg)
1827
42
          << "(choose the .crash file that corresponds to your crash)";
1828
42
    }
1829
42
  }
1830
1831
42
  Diag(clang::diag::note_drv_command_failed_diag_msg)
1832
42
      << "\n\n********************";
1833
42
}
1834
1835
8.74k
void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1836
  // Since commandLineFitsWithinSystemLimits() may underestimate system's
1837
  // capacity if the tool does not support response files, there is a chance/
1838
  // that things will just work without a response file, so we silently just
1839
  // skip it.
1840
8.74k
  if (Cmd.getResponseFileSupport().ResponseKind ==
1841
8.74k
          ResponseFileSupport::RF_None ||
1842
8.74k
      llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(),
1843
8.68k
                                                   Cmd.getArguments()))
1844
8.74k
    return;
1845
1846
1
  std::string TmpName = GetTemporaryPath("response", "txt");
1847
1
  Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1848
1
}
1849
1850
int Driver::ExecuteCompilation(
1851
    Compilation &C,
1852
20.4k
    SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1853
20.4k
  if (C.getArgs().hasArg(options::OPT_fdriver_only)) {
1854
17
    if (C.getArgs().hasArg(options::OPT_v))
1855
2
      C.getJobs().Print(llvm::errs(), "\n", true);
1856
1857
17
    C.ExecuteJobs(C.getJobs(), FailingCommands, /*LogOnly=*/true);
1858
1859
    // If there were errors building the compilation, quit now.
1860
17
    if (!FailingCommands.empty() || Diags.hasErrorOccurred())
1861
1
      return 1;
1862
1863
16
    return 0;
1864
17
  }
1865
1866
  // Just print if -### was present.
1867
20.4k
  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1868
10.0k
    C.getJobs().Print(llvm::errs(), "\n", true);
1869
10.0k
    return Diags.hasErrorOccurred() ? 
1709
:
09.35k
;
1870
10.0k
  }
1871
1872
  // If there were errors building the compilation, quit now.
1873
10.3k
  if (Diags.hasErrorOccurred())
1874
129
    return 1;
1875
1876
  // Set up response file names for each command, if necessary.
1877
10.2k
  for (auto &Job : C.getJobs())
1878
8.74k
    setUpResponseFiles(C, Job);
1879
1880
10.2k
  C.ExecuteJobs(C.getJobs(), FailingCommands);
1881
1882
  // If the command succeeded, we are done.
1883
10.2k
  if (FailingCommands.empty())
1884
9.95k
    return 0;
1885
1886
  // Otherwise, remove result files and print extra information about abnormal
1887
  // failures.
1888
301
  int Res = 0;
1889
312
  for (const auto &CmdPair : FailingCommands) {
1890
312
    int CommandRes = CmdPair.first;
1891
312
    const Command *FailingCommand = CmdPair.second;
1892
1893
    // Remove result files if we're not saving temps.
1894
312
    if (!isSaveTempsEnabled()) {
1895
312
      const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1896
312
      C.CleanupFileMap(C.getResultFiles(), JA, true);
1897
1898
      // Failure result files are valid unless we crashed.
1899
312
      if (CommandRes < 0)
1900
0
        C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1901
312
    }
1902
1903
    // llvm/lib/Support/*/Signals.inc will exit with a special return code
1904
    // for SIGPIPE. Do not print diagnostics for this case.
1905
312
    if (CommandRes == EX_IOERR) {
1906
0
      Res = CommandRes;
1907
0
      continue;
1908
0
    }
1909
1910
    // Print extra information about abnormal failures, if possible.
1911
    //
1912
    // This is ad-hoc, but we don't want to be excessively noisy. If the result
1913
    // status was 1, assume the command failed normally. In particular, if it
1914
    // was the compiler then assume it gave a reasonable error code. Failures
1915
    // in other tools are less common, and they generally have worse
1916
    // diagnostics, so always print the diagnostic there.
1917
312
    const Tool &FailingTool = FailingCommand->getCreator();
1918
1919
312
    if (!FailingCommand->getCreator().hasGoodDiagnostics() || 
CommandRes != 1272
) {
1920
      // FIXME: See FIXME above regarding result code interpretation.
1921
61
      if (CommandRes < 0)
1922
0
        Diag(clang::diag::err_drv_command_signalled)
1923
0
            << FailingTool.getShortName();
1924
61
      else
1925
61
        Diag(clang::diag::err_drv_command_failed)
1926
61
            << FailingTool.getShortName() << CommandRes;
1927
61
    }
1928
312
  }
1929
301
  return Res;
1930
10.2k
}
1931
1932
1.14k
void Driver::PrintHelp(bool ShowHidden) const {
1933
1.14k
  llvm::opt::Visibility VisibilityMask = getOptionVisibilityMask();
1934
1935
  // TODO: We're overriding the mask for flang here to keep this NFC for the
1936
  // option refactoring, but what we really need to do is annotate the flags
1937
  // that Flang uses.
1938
1.14k
  if (IsFlangMode())
1939
0
    VisibilityMask = llvm::opt::Visibility(options::FlangOption);
1940
1941
1.14k
  std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1942
1.14k
  getOpts().printHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
1943
1.14k
                      ShowHidden, /*ShowAllAliases=*/false,
1944
1.14k
                      VisibilityMask);
1945
1.14k
}
1946
1947
10.5k
void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1948
10.5k
  if (IsFlangMode()) {
1949
14
    OS << getClangToolFullVersion("flang-new") << '\n';
1950
10.5k
  } else {
1951
    // FIXME: The following handlers should use a callback mechanism, we don't
1952
    // know what the client would like to do.
1953
10.5k
    OS << getClangFullVersion() << '\n';
1954
10.5k
  }
1955
10.5k
  const ToolChain &TC = C.getDefaultToolChain();
1956
10.5k
  OS << "Target: " << TC.getTripleString() << '\n';
1957
1958
  // Print the threading model.
1959
10.5k
  if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1960
    // Don't print if the ToolChain would have barfed on it already
1961
8
    if (TC.isThreadModelSupported(A->getValue()))
1962
6
      OS << "Thread model: " << A->getValue();
1963
8
  } else
1964
10.5k
    OS << "Thread model: " << TC.getThreadModel();
1965
10.5k
  OS << '\n';
1966
1967
  // Print out the install directory.
1968
10.5k
  OS << "InstalledDir: " << InstalledDir << '\n';
1969
1970
  // If configuration files were used, print their paths.
1971
10.5k
  for (auto ConfigFile : ConfigFiles)
1972
50
    OS << "Configuration file: " << ConfigFile << '\n';
1973
10.5k
}
1974
1975
/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1976
/// option.
1977
0
static void PrintDiagnosticCategories(raw_ostream &OS) {
1978
  // Skip the empty category.
1979
0
  for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1980
0
       ++i)
1981
0
    OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1982
0
}
1983
1984
38
void Driver::HandleAutocompletions(StringRef PassedFlags) const {
1985
38
  if (PassedFlags == "")
1986
1
    return;
1987
  // Print out all options that start with a given argument. This is used for
1988
  // shell autocompletion.
1989
37
  std::vector<std::string> SuggestedCompletions;
1990
37
  std::vector<std::string> Flags;
1991
1992
37
  llvm::opt::Visibility VisibilityMask(options::ClangOption);
1993
1994
  // Make sure that Flang-only options don't pollute the Clang output
1995
  // TODO: Make sure that Clang-only options don't pollute Flang output
1996
37
  if (IsFlangMode())
1997
0
    VisibilityMask = llvm::opt::Visibility(options::FlangOption);
1998
1999
  // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
2000
  // because the latter indicates that the user put space before pushing tab
2001
  // which should end up in a file completion.
2002
37
  const bool HasSpace = PassedFlags.endswith(",");
2003
2004
  // Parse PassedFlags by "," as all the command-line flags are passed to this
2005
  // function separated by ","
2006
37
  StringRef TargetFlags = PassedFlags;
2007
89
  while (TargetFlags != "") {
2008
52
    StringRef CurFlag;
2009
52
    std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
2010
52
    Flags.push_back(std::string(CurFlag));
2011
52
  }
2012
2013
  // We want to show cc1-only options only when clang is invoked with -cc1 or
2014
  // -Xclang.
2015
37
  if (llvm::is_contained(Flags, "-Xclang") || 
llvm::is_contained(Flags, "-cc1")36
)
2016
2
    VisibilityMask = llvm::opt::Visibility(options::CC1Option);
2017
2018
37
  const llvm::opt::OptTable &Opts = getOpts();
2019
37
  StringRef Cur;
2020
37
  Cur = Flags.at(Flags.size() - 1);
2021
37
  StringRef Prev;
2022
37
  if (Flags.size() >= 2) {
2023
9
    Prev = Flags.at(Flags.size() - 2);
2024
9
    SuggestedCompletions = Opts.suggestValueCompletions(Prev, Cur);
2025
9
  }
2026
2027
37
  if (SuggestedCompletions.empty())
2028
32
    SuggestedCompletions = Opts.suggestValueCompletions(Cur, "");
2029
2030
  // If Flags were empty, it means the user typed `clang [tab]` where we should
2031
  // list all possible flags. If there was no value completion and the user
2032
  // pressed tab after a space, we should fall back to a file completion.
2033
  // We're printing a newline to be consistent with what we print at the end of
2034
  // this function.
2035
37
  if (SuggestedCompletions.empty() && 
HasSpace17
&&
!Flags.empty()3
) {
2036
3
    llvm::outs() << '\n';
2037
3
    return;
2038
3
  }
2039
2040
  // When flag ends with '=' and there was no value completion, return empty
2041
  // string and fall back to the file autocompletion.
2042
34
  if (SuggestedCompletions.empty() && 
!Cur.endswith("=")14
) {
2043
    // If the flag is in the form of "--autocomplete=-foo",
2044
    // we were requested to print out all option names that start with "-foo".
2045
    // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
2046
12
    SuggestedCompletions = Opts.findByPrefix(
2047
12
        Cur, VisibilityMask,
2048
12
        /*DisableFlags=*/options::Unsupported | options::Ignored);
2049
2050
    // We have to query the -W flags manually as they're not in the OptTable.
2051
    // TODO: Find a good way to add them to OptTable instead and them remove
2052
    // this code.
2053
12
    for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
2054
23.9k
      if (S.startswith(Cur))
2055
2.00k
        SuggestedCompletions.push_back(std::string(S));
2056
12
  }
2057
2058
  // Sort the autocomplete candidates so that shells print them out in a
2059
  // deterministic order. We could sort in any way, but we chose
2060
  // case-insensitive sorting for consistency with the -help option
2061
  // which prints out options in the case-insensitive alphabetical order.
2062
50.9k
  llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
2063
50.9k
    if (int X = A.compare_insensitive(B))
2064
49.5k
      return X < 0;
2065
1.34k
    return A.compare(B) > 0;
2066
50.9k
  });
2067
2068
34
  llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
2069
34
}
2070
2071
52.1k
bool Driver::HandleImmediateArgs(const Compilation &C) {
2072
  // The order these options are handled in gcc is all over the place, but we
2073
  // don't expect inconsistencies w.r.t. that to matter in practice.
2074
2075
52.1k
  if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
2076
3
    llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
2077
3
    return false;
2078
3
  }
2079
2080
52.1k
  if (C.getArgs().hasArg(options::OPT_dumpversion)) {
2081
    // Since -dumpversion is only implemented for pedantic GCC compatibility, we
2082
    // return an answer which matches our definition of __VERSION__.
2083
1
    llvm::outs() << CLANG_VERSION_STRING << "\n";
2084
1
    return false;
2085
1
  }
2086
2087
52.1k
  if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
2088
0
    PrintDiagnosticCategories(llvm::outs());
2089
0
    return false;
2090
0
  }
2091
2092
52.1k
  if (C.getArgs().hasArg(options::OPT_help) ||
2093
52.1k
      
C.getArgs().hasArg(options::OPT__help_hidden)50.9k
) {
2094
1.14k
    PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
2095
1.14k
    return false;
2096
1.14k
  }
2097
2098
50.9k
  if (C.getArgs().hasArg(options::OPT__version)) {
2099
    // Follow gcc behavior and use stdout for --version and stderr for -v.
2100
323
    PrintVersion(C, llvm::outs());
2101
323
    return false;
2102
323
  }
2103
2104
50.6k
  if (C.getArgs().hasArg(options::OPT_v) ||
2105
50.6k
      
C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)50.5k
||
2106
50.6k
      
C.getArgs().hasArg(options::OPT_print_supported_cpus)40.4k
||
2107
50.6k
      
C.getArgs().hasArg(options::OPT_print_supported_extensions)40.4k
) {
2108
10.1k
    PrintVersion(C, llvm::errs());
2109
10.1k
    SuppressMissingInputWarning = true;
2110
10.1k
  }
2111
2112
50.6k
  if (C.getArgs().hasArg(options::OPT_v)) {
2113
149
    if (!SystemConfigDir.empty())
2114
4
      llvm::errs() << "System configuration file directory: "
2115
4
                   << SystemConfigDir << "\n";
2116
149
    if (!UserConfigDir.empty())
2117
3
      llvm::errs() << "User configuration file directory: "
2118
3
                   << UserConfigDir << "\n";
2119
149
  }
2120
2121
50.6k
  const ToolChain &TC = C.getDefaultToolChain();
2122
2123
50.6k
  if (C.getArgs().hasArg(options::OPT_v))
2124
149
    TC.printVerboseInfo(llvm::errs());
2125
2126
50.6k
  if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
2127
3
    llvm::outs() << ResourceDir << '\n';
2128
3
    return false;
2129
3
  }
2130
2131
50.6k
  if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
2132
4
    llvm::outs() << "programs: =";
2133
4
    bool separator = false;
2134
    // Print -B and COMPILER_PATH.
2135
5
    for (const std::string &Path : PrefixDirs) {
2136
5
      if (separator)
2137
3
        llvm::outs() << llvm::sys::EnvPathSeparator;
2138
5
      llvm::outs() << Path;
2139
5
      separator = true;
2140
5
    }
2141
4
    for (const std::string &Path : TC.getProgramPaths()) {
2142
4
      if (separator)
2143
2
        llvm::outs() << llvm::sys::EnvPathSeparator;
2144
4
      llvm::outs() << Path;
2145
4
      separator = true;
2146
4
    }
2147
4
    llvm::outs() << "\n";
2148
4
    llvm::outs() << "libraries: =" << ResourceDir;
2149
2150
4
    StringRef sysroot = C.getSysRoot();
2151
2152
4
    for (const std::string &Path : TC.getFilePaths()) {
2153
      // Always print a separator. ResourceDir was the first item shown.
2154
4
      llvm::outs() << llvm::sys::EnvPathSeparator;
2155
      // Interpretation of leading '=' is needed only for NetBSD.
2156
4
      if (Path[0] == '=')
2157
0
        llvm::outs() << sysroot << Path.substr(1);
2158
4
      else
2159
4
        llvm::outs() << Path;
2160
4
    }
2161
4
    llvm::outs() << "\n";
2162
4
    return false;
2163
4
  }
2164
2165
50.6k
  if (C.getArgs().hasArg(options::OPT_print_runtime_dir)) {
2166
15
    if (std::optional<std::string> RuntimePath = TC.getRuntimePath())
2167
9
      llvm::outs() << *RuntimePath << '\n';
2168
6
    else
2169
6
      llvm::outs() << TC.getCompilerRTPath() << '\n';
2170
15
    return false;
2171
15
  }
2172
2173
50.6k
  if (C.getArgs().hasArg(options::OPT_print_diagnostic_options)) {
2174
1
    std::vector<std::string> Flags = DiagnosticIDs::getDiagnosticFlags();
2175
999
    for (std::size_t I = 0; I != Flags.size(); 
I += 2998
)
2176
998
      llvm::outs() << "  " << Flags[I] << "\n  " << Flags[I + 1] << "\n\n";
2177
1
    return false;
2178
1
  }
2179
2180
  // FIXME: The following handlers should use a callback mechanism, we don't
2181
  // know what the client would like to do.
2182
50.6k
  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
2183
71
    llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
2184
71
    return false;
2185
71
  }
2186
2187
50.5k
  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
2188
1
    StringRef ProgName = A->getValue();
2189
2190
    // Null program name cannot have a path.
2191
1
    if (! ProgName.empty())
2192
0
      llvm::outs() << GetProgramPath(ProgName, TC);
2193
2194
1
    llvm::outs() << "\n";
2195
1
    return false;
2196
1
  }
2197
2198
50.5k
  if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
2199
38
    StringRef PassedFlags = A->getValue();
2200
38
    HandleAutocompletions(PassedFlags);
2201
38
    return false;
2202
38
  }
2203
2204
50.5k
  if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
2205
13
    ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
2206
13
    const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
2207
13
    RegisterEffectiveTriple TripleRAII(TC, Triple);
2208
13
    switch (RLT) {
2209
12
    case ToolChain::RLT_CompilerRT:
2210
12
      llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
2211
12
      break;
2212
1
    case ToolChain::RLT_Libgcc:
2213
1
      llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
2214
1
      break;
2215
13
    }
2216
13
    return false;
2217
13
  }
2218
2219
50.5k
  if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
2220
2
    for (const Multilib &Multilib : TC.getMultilibs())
2221
15
      llvm::outs() << Multilib << "\n";
2222
2
    return false;
2223
2
  }
2224
2225
50.5k
  if (C.getArgs().hasArg(options::OPT_print_multi_flags)) {
2226
11
    Multilib::flags_list ArgFlags = TC.getMultilibFlags(C.getArgs());
2227
11
    llvm::StringSet<> ExpandedFlags = TC.getMultilibs().expandFlags(ArgFlags);
2228
11
    std::set<llvm::StringRef> SortedFlags;
2229
11
    for (const auto &FlagEntry : ExpandedFlags)
2230
34
      SortedFlags.insert(FlagEntry.getKey());
2231
11
    for (auto Flag : SortedFlags)
2232
34
      llvm::outs() << Flag << '\n';
2233
11
    return false;
2234
11
  }
2235
2236
50.4k
  if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
2237
7
    for (const Multilib &Multilib : TC.getSelectedMultilibs()) {
2238
7
      if (Multilib.gccSuffix().empty())
2239
1
        llvm::outs() << ".\n";
2240
6
      else {
2241
6
        StringRef Suffix(Multilib.gccSuffix());
2242
6
        assert(Suffix.front() == '/');
2243
6
        llvm::outs() << Suffix.substr(1) << "\n";
2244
6
      }
2245
7
    }
2246
6
    return false;
2247
6
  }
2248
2249
50.4k
  if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
2250
5
    llvm::outs() << TC.getTripleString() << "\n";
2251
5
    return false;
2252
5
  }
2253
2254
50.4k
  if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
2255
14
    const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
2256
14
    llvm::outs() << Triple.getTriple() << "\n";
2257
14
    return false;
2258
14
  }
2259
2260
50.4k
  if (C.getArgs().hasArg(options::OPT_print_targets)) {
2261
0
    llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
2262
0
    return false;
2263
0
  }
2264
2265
50.4k
  return true;
2266
50.4k
}
2267
2268
enum {
2269
  TopLevelAction = 0,
2270
  HeadSibAction = 1,
2271
  OtherSibAction = 2,
2272
};
2273
2274
// Display an action graph human-readably.  Action A is the "sink" node
2275
// and latest-occuring action. Traversal is in pre-order, visiting the
2276
// inputs to each action before printing the action itself.
2277
static unsigned PrintActions1(const Compilation &C, Action *A,
2278
                              std::map<Action *, unsigned> &Ids,
2279
1.05k
                              Twine Indent = {}, int Kind = TopLevelAction) {
2280
1.05k
  if (Ids.count(A)) // A was already visited.
2281
19
    return Ids[A];
2282
2283
1.03k
  std::string str;
2284
1.03k
  llvm::raw_string_ostream os(str);
2285
2286
1.03k
  auto getSibIndent = [](int K) -> Twine {
2287
1.03k
    return (K == HeadSibAction) ? 
" "842
:
(K == OtherSibAction)190
?
"| "89
:
""101
;
2288
1.03k
  };
2289
2290
1.03k
  Twine SibIndent = Indent + getSibIndent(Kind);
2291
1.03k
  int SibKind = HeadSibAction;
2292
1.03k
  os << Action::getClassName(A->getKind()) << ", ";
2293
1.03k
  if (InputAction *IA = dyn_cast<InputAction>(A)) {
2294
177
    os << "\"" << IA->getInputArg().getValue() << "\"";
2295
855
  } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
2296
18
    os << '"' << BIA->getArchName() << '"' << ", {"
2297
18
       << PrintActions1(C, *BIA->input_begin(), Ids, SibIndent, SibKind) << "}";
2298
837
  } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
2299
136
    bool IsFirst = true;
2300
136
    OA->doOnEachDependence(
2301
159
        [&](Action *A, const ToolChain *TC, const char *BoundArch) {
2302
159
          assert(TC && "Unknown host toolchain");
2303
          // E.g. for two CUDA device dependences whose bound arch is sm_20 and
2304
          // sm_35 this will generate:
2305
          // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
2306
          // (nvptx64-nvidia-cuda:sm_35) {#ID}
2307
159
          if (!IsFirst)
2308
23
            os << ", ";
2309
159
          os << '"';
2310
159
          os << A->getOffloadingKindPrefix();
2311
159
          os << " (";
2312
159
          os << TC->getTriple().normalize();
2313
159
          if (BoundArch)
2314
105
            os << ":" << BoundArch;
2315
159
          os << ")";
2316
159
          os << '"';
2317
159
          os << " {" << PrintActions1(C, A, Ids, SibIndent, SibKind) << "}";
2318
159
          IsFirst = false;
2319
159
          SibKind = OtherSibAction;
2320
159
        });
2321
701
  } else {
2322
701
    const ActionList *AL = &A->getInputs();
2323
2324
701
    if (AL->size()) {
2325
701
      const char *Prefix = "{";
2326
773
      for (Action *PreRequisite : *AL) {
2327
773
        os << Prefix << PrintActions1(C, PreRequisite, Ids, SibIndent, SibKind);
2328
773
        Prefix = ", ";
2329
773
        SibKind = OtherSibAction;
2330
773
      }
2331
701
      os << "}";
2332
701
    } else
2333
0
      os << "{}";
2334
701
  }
2335
2336
  // Append offload info for all options other than the offloading action
2337
  // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
2338
1.03k
  std::string offload_str;
2339
1.03k
  llvm::raw_string_ostream offload_os(offload_str);
2340
1.03k
  if (!isa<OffloadAction>(A)) {
2341
896
    auto S = A->getOffloadingKindPrefix();
2342
896
    if (!S.empty()) {
2343
659
      offload_os << ", (" << S;
2344
659
      if (A->getOffloadingArch())
2345
439
        offload_os << ", " << A->getOffloadingArch();
2346
659
      offload_os << ")";
2347
659
    }
2348
896
  }
2349
2350
1.03k
  auto getSelfIndent = [](int K) -> Twine {
2351
1.03k
    return (K == HeadSibAction) ? 
"+- "842
:
(K == OtherSibAction)190
?
"|- "89
:
""101
;
2352
1.03k
  };
2353
2354
1.03k
  unsigned Id = Ids.size();
2355
1.03k
  Ids[A] = Id;
2356
1.03k
  llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", "
2357
1.03k
               << types::getTypeName(A->getType()) << offload_os.str() << "\n";
2358
2359
1.03k
  return Id;
2360
1.05k
}
2361
2362
// Print the action graphs in a compilation C.
2363
// For example "clang -c file1.c file2.c" is composed of two subgraphs.
2364
87
void Driver::PrintActions(const Compilation &C) const {
2365
87
  std::map<Action *, unsigned> Ids;
2366
87
  for (Action *A : C.getActions())
2367
101
    PrintActions1(C, A, Ids);
2368
87
}
2369
2370
/// Check whether the given input tree contains any compilation or
2371
/// assembly actions.
2372
19.6k
static bool ContainsCompileOrAssembleAction(const Action *A) {
2373
19.6k
  if (isa<CompileJobAction>(A) || 
isa<BackendJobAction>(A)19.6k
||
2374
19.6k
      
isa<AssembleJobAction>(A)19.5k
)
2375
3.05k
    return true;
2376
2377
16.6k
  return llvm::any_of(A->inputs(), ContainsCompileOrAssembleAction);
2378
19.6k
}
2379
2380
void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
2381
20.5k
                                   const InputList &BAInputs) const {
2382
20.5k
  DerivedArgList &Args = C.getArgs();
2383
20.5k
  ActionList &Actions = C.getActions();
2384
20.5k
  llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
2385
  // Collect the list of architectures. Duplicates are allowed, but should only
2386
  // be handled once (in the order seen).
2387
20.5k
  llvm::StringSet<> ArchNames;
2388
20.5k
  SmallVector<const char *, 4> Archs;
2389
505k
  for (Arg *A : Args) {
2390
505k
    if (A->getOption().matches(options::OPT_arch)) {
2391
      // Validate the option here; we don't save the type here because its
2392
      // particular spelling may participate in other driver choices.
2393
5.48k
      llvm::Triple::ArchType Arch =
2394
5.48k
          tools::darwin::getArchTypeForMachOArchName(A->getValue());
2395
5.48k
      if (Arch == llvm::Triple::UnknownArch) {
2396
0
        Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
2397
0
        continue;
2398
0
      }
2399
2400
5.48k
      A->claim();
2401
5.48k
      if (ArchNames.insert(A->getValue()).second)
2402
5.47k
        Archs.push_back(A->getValue());
2403
5.48k
    }
2404
505k
  }
2405
2406
  // When there is no explicit arch for this platform, make sure we still bind
2407
  // the architecture (to the default) so that -Xarch_ is handled correctly.
2408
20.5k
  if (!Archs.size())
2409
15.1k
    Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
2410
2411
20.5k
  ActionList SingleActions;
2412
20.5k
  BuildActions(C, Args, BAInputs, SingleActions);
2413
2414
  // Add in arch bindings for every top level action, as well as lipo and
2415
  // dsymutil steps if needed.
2416
20.6k
  for (Action* Act : SingleActions) {
2417
    // Make sure we can lipo this kind of output. If not (and it is an actual
2418
    // output) then we disallow, since we can't create an output file with the
2419
    // right name without overwriting it. We could remove this oddity by just
2420
    // changing the output names to include the arch, which would also fix
2421
    // -save-temps. Compatibility wins for now.
2422
2423
20.6k
    if (Archs.size() > 1 && 
!types::canLipoType(Act->getType())30
)
2424
0
      Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
2425
0
          << types::getTypeName(Act->getType());
2426
2427
20.6k
    ActionList Inputs;
2428
41.2k
    for (unsigned i = 0, e = Archs.size(); i != e; 
++i20.6k
)
2429
20.6k
      Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
2430
2431
    // Lipo if necessary, we do it this way because we need to set the arch flag
2432
    // so that -Xarch_ gets overwritten.
2433
20.6k
    if (Inputs.size() == 1 || 
Act->getType() == types::TY_Nothing30
)
2434
20.5k
      Actions.append(Inputs.begin(), Inputs.end());
2435
30
    else
2436
30
      Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
2437
2438
    // Handle debug info queries.
2439
20.6k
    Arg *A = Args.getLastArg(options::OPT_g_Group);
2440
20.6k
    bool enablesDebugInfo = A && 
!A->getOption().matches(options::OPT_g0)5.52k
&&
2441
20.6k
                            
!A->getOption().matches(options::OPT_gstabs)5.50k
;
2442
20.6k
    if ((enablesDebugInfo || 
willEmitRemarks(Args)15.1k
) &&
2443
20.6k
        
ContainsCompileOrAssembleAction(Actions.back())5.53k
) {
2444
2445
      // Add a 'dsymutil' step if necessary, when debug info is enabled and we
2446
      // have a compile input. We need to run 'dsymutil' ourselves in such cases
2447
      // because the debug info will refer to a temporary object file which
2448
      // will be removed at the end of the compilation process.
2449
3.05k
      if (Act->getType() == types::TY_Image) {
2450
71
        ActionList Inputs;
2451
71
        Inputs.push_back(Actions.back());
2452
71
        Actions.pop_back();
2453
71
        Actions.push_back(
2454
71
            C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
2455
71
      }
2456
2457
      // Verify the debug info output.
2458
3.05k
      if (Args.hasArg(options::OPT_verify_debug_info)) {
2459
3
        Action* LastAction = Actions.back();
2460
3
        Actions.pop_back();
2461
3
        Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
2462
3
            LastAction, types::TY_Nothing));
2463
3
      }
2464
3.05k
    }
2465
20.6k
  }
2466
20.5k
}
2467
2468
bool Driver::DiagnoseInputExistence(const DerivedArgList &Args, StringRef Value,
2469
50.9k
                                    types::ID Ty, bool TypoCorrect) const {
2470
50.9k
  if (!getCheckInputsExist())
2471
4.79k
    return true;
2472
2473
  // stdin always exists.
2474
46.1k
  if (Value == "-")
2475
126
    return true;
2476
2477
  // If it's a header to be found in the system or user search path, then defer
2478
  // complaints about its absence until those searches can be done.  When we
2479
  // are definitely processing headers for C++20 header units, extend this to
2480
  // allow the user to put "-fmodule-header -xc++-header vector" for example.
2481
46.0k
  if (Ty == types::TY_CXXSHeader || 
Ty == types::TY_CXXUHeader46.0k
||
2482
46.0k
      
(46.0k
ModulesModeCXX2046.0k
&&
Ty == types::TY_CXXHeader2.83k
))
2483
9
    return true;
2484
2485
46.0k
  if (getVFS().exists(Value))
2486
45.9k
    return true;
2487
2488
44
  
if (34
TypoCorrect34
) {
2489
    // Check if the filename is a typo for an option flag. OptTable thinks
2490
    // that all args that are not known options and that start with / are
2491
    // filenames, but e.g. `/diagnostic:caret` is more likely a typo for
2492
    // the option `/diagnostics:caret` than a reference to a file in the root
2493
    // directory.
2494
44
    std::string Nearest;
2495
44
    if (getOpts().findNearest(Value, Nearest, getOptionVisibilityMask()) <= 1) {
2496
3
      Diag(clang::diag::err_drv_no_such_file_with_suggestion)
2497
3
          << Value << Nearest;
2498
3
      return false;
2499
3
    }
2500
44
  }
2501
2502
  // In CL mode, don't error on apparently non-existent linker inputs, because
2503
  // they can be influenced by linker flags the clang driver might not
2504
  // understand.
2505
  // Examples:
2506
  // - `clang-cl main.cc ole32.lib` in a non-MSVC shell will make the driver
2507
  //   module look for an MSVC installation in the registry. (We could ask
2508
  //   the MSVCToolChain object if it can find `ole32.lib`, but the logic to
2509
  //   look in the registry might move into lld-link in the future so that
2510
  //   lld-link invocations in non-MSVC shells just work too.)
2511
  // - `clang-cl ... /link ...` can pass arbitrary flags to the linker,
2512
  //   including /libpath:, which is used to find .lib and .obj files.
2513
  // So do not diagnose this on the driver level. Rely on the linker diagnosing
2514
  // it. (If we don't end up invoking the linker, this means we'll emit a
2515
  // "'linker' input unused [-Wunused-command-line-argument]" warning instead
2516
  // of an error.)
2517
  //
2518
  // Only do this skip after the typo correction step above. `/Brepo` is treated
2519
  // as TY_Object, but it's clearly a typo for `/Brepro`. It seems fine to emit
2520
  // an error if we have a flag that's within an edit distance of 1 from a
2521
  // flag. (Users can use `-Wl,` or `/linker` to launder the flag past the
2522
  // driver in the unlikely case they run into this.)
2523
  //
2524
  // Don't do this for inputs that start with a '/', else we'd pass options
2525
  // like /libpath: through to the linker silently.
2526
  //
2527
  // Emitting an error for linker inputs can also cause incorrect diagnostics
2528
  // with the gcc driver. The command
2529
  //     clang -fuse-ld=lld -Wl,--chroot,some/dir /file.o
2530
  // will make lld look for some/dir/file.o, while we will diagnose here that
2531
  // `/file.o` does not exist. However, configure scripts check if
2532
  // `clang /GR-` compiles without error to see if the compiler is cl.exe,
2533
  // so we can't downgrade diagnostics for `/GR-` from an error to a warning
2534
  // in cc mode. (We can in cl mode because cl.exe itself only warns on
2535
  // unknown flags.)
2536
31
  if (IsCLMode() && 
Ty == types::TY_Object13
&&
!Value.startswith("/")13
)
2537
10
    return true;
2538
2539
21
  Diag(clang::diag::err_drv_no_such_file) << Value;
2540
21
  return false;
2541
31
}
2542
2543
// Get the C++20 Header Unit type corresponding to the input type.
2544
6
static types::ID CXXHeaderUnitType(ModuleHeaderMode HM) {
2545
6
  switch (HM) {
2546
3
  case HeaderMode_User:
2547
3
    return types::TY_CXXUHeader;
2548
2
  case HeaderMode_System:
2549
2
    return types::TY_CXXSHeader;
2550
1
  case HeaderMode_Default:
2551
1
    break;
2552
0
  case HeaderMode_None:
2553
0
    llvm_unreachable("should not be called in this case");
2554
6
  }
2555
1
  return types::TY_CXXHUHeader;
2556
6
}
2557
2558
// Construct a the list of inputs and their types.
2559
void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
2560
50.5k
                         InputList &Inputs) const {
2561
50.5k
  const llvm::opt::OptTable &Opts = getOpts();
2562
  // Track the current user specified (-x) input. We also explicitly track the
2563
  // argument used to set the type; we only want to claim the type when we
2564
  // actually use it, so we warn about unused -x arguments.
2565
50.5k
  types::ID InputType = types::TY_Nothing;
2566
50.5k
  Arg *InputTypeArg = nullptr;
2567
2568
  // The last /TC or /TP option sets the input type to C or C++ globally.
2569
50.5k
  if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
2570
50.5k
                                         options::OPT__SLASH_TP)) {
2571
21
    InputTypeArg = TCTP;
2572
21
    InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
2573
21
                    ? 
types::TY_C6
2574
21
                    : 
types::TY_CXX15
;
2575
2576
21
    Arg *Previous = nullptr;
2577
21
    bool ShowNote = false;
2578
21
    for (Arg *A :
2579
23
         Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
2580
23
      if (Previous) {
2581
2
        Diag(clang::diag::warn_drv_overriding_option)
2582
2
            << Previous->getSpelling() << A->getSpelling();
2583
2
        ShowNote = true;
2584
2
      }
2585
23
      Previous = A;
2586
23
    }
2587
21
    if (ShowNote)
2588
1
      Diag(clang::diag::note_drv_t_option_is_global);
2589
21
  }
2590
2591
  // Warn -x after last input file has no effect
2592
50.5k
  if (!IsCLMode()) {
2593
49.8k
    Arg *LastXArg = Args.getLastArgNoClaim(options::OPT_x);
2594
49.8k
    Arg *LastInputArg = Args.getLastArgNoClaim(options::OPT_INPUT);
2595
49.8k
    if (LastXArg && 
LastInputArg5.30k
&&
2596
49.8k
        
LastInputArg->getIndex() < LastXArg->getIndex()5.30k
)
2597
15
      Diag(clang::diag::warn_drv_unused_x) << LastXArg->getValue();
2598
49.8k
  } else {
2599
    // In CL mode suggest /TC or /TP since -x doesn't make sense if passed via
2600
    // /clang:.
2601
697
    if (auto *A = Args.getLastArg(options::OPT_x))
2602
2
      Diag(diag::err_drv_unsupported_opt_with_suggestion)
2603
2
          << A->getAsString(Args) << "/TC' or '/TP";
2604
697
  }
2605
2606
778k
  for (Arg *A : Args) {
2607
778k
    if (A->getOption().getKind() == Option::InputClass) {
2608
50.9k
      const char *Value = A->getValue();
2609
50.9k
      types::ID Ty = types::TY_INVALID;
2610
2611
      // Infer the input type if necessary.
2612
50.9k
      if (InputType == types::TY_Nothing) {
2613
        // If there was an explicit arg for this, claim it.
2614
45.5k
        if (InputTypeArg)
2615
1
          InputTypeArg->claim();
2616
2617
        // stdin must be handled specially.
2618
45.5k
        if (memcmp(Value, "-", 2) == 0) {
2619
11
          if (IsFlangMode()) {
2620
0
            Ty = types::TY_Fortran;
2621
11
          } else if (IsDXCMode()) {
2622
1
            Ty = types::TY_HLSL;
2623
10
          } else {
2624
            // If running with -E, treat as a C input (this changes the
2625
            // builtin macros, for example). This may be overridden by -ObjC
2626
            // below.
2627
            //
2628
            // Otherwise emit an error but still use a valid type to avoid
2629
            // spurious errors (e.g., no inputs).
2630
10
            assert(!CCGenDiagnostics && "stdin produces no crash reproducer");
2631
10
            if (!Args.hasArgNoClaim(options::OPT_E) && 
!CCCIsCPP()1
)
2632
1
              Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2633
1
                              : 
clang::diag::err_drv_unknown_stdin_type0
);
2634
10
            Ty = types::TY_C;
2635
10
          }
2636
45.5k
        } else {
2637
          // Otherwise lookup by extension.
2638
          // Fallback is C if invoked as C preprocessor, C++ if invoked with
2639
          // clang-cl /E, or Object otherwise.
2640
          // We use a host hook here because Darwin at least has its own
2641
          // idea of what .s is.
2642
45.5k
          if (const char *Ext = strrchr(Value, '.'))
2643
45.5k
            Ty = TC.LookupTypeForExtension(Ext + 1);
2644
2645
45.5k
          if (Ty == types::TY_INVALID) {
2646
79
            if (IsCLMode() && 
(6
Args.hasArgNoClaim(options::OPT_E)6
||
CCGenDiagnostics5
))
2647
1
              Ty = types::TY_CXX;
2648
78
            else if (CCCIsCPP() || CCGenDiagnostics)
2649
0
              Ty = types::TY_C;
2650
78
            else
2651
78
              Ty = types::TY_Object;
2652
79
          }
2653
2654
          // If the driver is invoked as C++ compiler (like clang++ or c++) it
2655
          // should autodetect some input files as C++ for g++ compatibility.
2656
45.5k
          if (CCCIsCXX()) {
2657
4.75k
            types::ID OldTy = Ty;
2658
4.75k
            Ty = types::lookupCXXTypeForCType(Ty);
2659
2660
            // Do not complain about foo.h, when we are known to be processing
2661
            // it as a C++20 header unit.
2662
4.75k
            if (Ty != OldTy && 
!(71
OldTy == types::TY_CHeader71
&&
hasHeaderMode()0
))
2663
71
              Diag(clang::diag::warn_drv_treating_input_as_cxx)
2664
71
                  << getTypeName(OldTy) << getTypeName(Ty);
2665
4.75k
          }
2666
2667
          // If running with -fthinlto-index=, extensions that normally identify
2668
          // native object files actually identify LLVM bitcode files.
2669
45.5k
          if (Args.hasArgNoClaim(options::OPT_fthinlto_index_EQ) &&
2670
45.5k
              
Ty == types::TY_Object5
)
2671
3
            Ty = types::TY_LLVM_BC;
2672
45.5k
        }
2673
2674
        // -ObjC and -ObjC++ override the default language, but only for "source
2675
        // files". We just treat everything that isn't a linker input as a
2676
        // source file.
2677
        //
2678
        // FIXME: Clean this up if we move the phase sequence into the type.
2679
45.5k
        if (Ty != types::TY_Object) {
2680
42.5k
          if (Args.hasArg(options::OPT_ObjC))
2681
21
            Ty = types::TY_ObjC;
2682
42.4k
          else if (Args.hasArg(options::OPT_ObjCXX))
2683
1
            Ty = types::TY_ObjCXX;
2684
42.5k
        }
2685
2686
        // Disambiguate headers that are meant to be header units from those
2687
        // intended to be PCH.  Avoid missing '.h' cases that are counted as
2688
        // C headers by default - we know we are in C++ mode and we do not
2689
        // want to issue a complaint about compiling things in the wrong mode.
2690
45.5k
        if ((Ty == types::TY_CXXHeader || 
Ty == types::TY_CHeader45.5k
) &&
2691
45.5k
            
hasHeaderMode()34
)
2692
5
          Ty = CXXHeaderUnitType(CXX20HeaderType);
2693
45.5k
      } else {
2694
5.35k
        assert(InputTypeArg && "InputType set w/o InputTypeArg");
2695
5.35k
        if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2696
          // If emulating cl.exe, make sure that /TC and /TP don't affect input
2697
          // object files.
2698
21
          const char *Ext = strrchr(Value, '.');
2699
21
          if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2700
2
            Ty = types::TY_Object;
2701
21
        }
2702
5.35k
        if (Ty == types::TY_INVALID) {
2703
5.34k
          Ty = InputType;
2704
5.34k
          InputTypeArg->claim();
2705
5.34k
        }
2706
5.35k
      }
2707
2708
50.9k
      if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true))
2709
50.9k
        Inputs.push_back(std::make_pair(Ty, A));
2710
2711
727k
    } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2712
24
      StringRef Value = A->getValue();
2713
24
      if (DiagnoseInputExistence(Args, Value, types::TY_C,
2714
24
                                 /*TypoCorrect=*/false)) {
2715
24
        Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2716
24
        Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2717
24
      }
2718
24
      A->claim();
2719
727k
    } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2720
3
      StringRef Value = A->getValue();
2721
3
      if (DiagnoseInputExistence(Args, Value, types::TY_CXX,
2722
3
                                 /*TypoCorrect=*/false)) {
2723
3
        Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2724
3
        Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2725
3
      }
2726
3
      A->claim();
2727
727k
    } else if (A->getOption().hasFlag(options::LinkerInput)) {
2728
      // Just treat as object type, we could make a special type for this if
2729
      // necessary.
2730
5.92k
      Inputs.push_back(std::make_pair(types::TY_Object, A));
2731
2732
721k
    } else if (A->getOption().matches(options::OPT_x)) {
2733
5.32k
      InputTypeArg = A;
2734
5.32k
      InputType = types::lookupTypeForTypeSpecifier(A->getValue());
2735
5.32k
      A->claim();
2736
2737
      // Follow gcc behavior and treat as linker input for invalid -x
2738
      // options. Its not clear why we shouldn't just revert to unknown; but
2739
      // this isn't very important, we might as well be bug compatible.
2740
5.32k
      if (!InputType) {
2741
0
        Diag(clang::diag::err_drv_unknown_language) << A->getValue();
2742
0
        InputType = types::TY_Object;
2743
0
      }
2744
2745
      // If the user has put -fmodule-header{,=} then we treat C++ headers as
2746
      // header unit inputs.  So we 'promote' -xc++-header appropriately.
2747
5.32k
      if (InputType == types::TY_CXXHeader && 
hasHeaderMode()15
)
2748
1
        InputType = CXXHeaderUnitType(CXX20HeaderType);
2749
716k
    } else if (A->getOption().getID() == options::OPT_U) {
2750
9
      assert(A->getNumValues() == 1 && "The /U option has one value.");
2751
9
      StringRef Val = A->getValue(0);
2752
9
      if (Val.find_first_of("/\\") != StringRef::npos) {
2753
        // Warn about e.g. "/Users/me/myfile.c".
2754
2
        Diag(diag::warn_slash_u_filename) << Val;
2755
2
        Diag(diag::note_use_dashdash);
2756
2
      }
2757
9
    }
2758
778k
  }
2759
50.5k
  if (CCCIsCPP() && 
Inputs.empty()3
) {
2760
    // If called as standalone preprocessor, stdin is processed
2761
    // if no other input is present.
2762
0
    Arg *A = MakeInputArg(Args, Opts, "-");
2763
0
    Inputs.push_back(std::make_pair(types::TY_C, A));
2764
0
  }
2765
50.5k
}
2766
2767
namespace {
2768
/// Provides a convenient interface for different programming models to generate
2769
/// the required device actions.
2770
class OffloadingActionBuilder final {
2771
  /// Flag used to trace errors in the builder.
2772
  bool IsValid = false;
2773
2774
  /// The compilation that is using this builder.
2775
  Compilation &C;
2776
2777
  /// Map between an input argument and the offload kinds used to process it.
2778
  std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2779
2780
  /// Map between a host action and its originating input argument.
2781
  std::map<Action *, const Arg *> HostActionToInputArgMap;
2782
2783
  /// Builder interface. It doesn't build anything or keep any state.
2784
  class DeviceActionBuilder {
2785
  public:
2786
    typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy;
2787
2788
    enum ActionBuilderReturnCode {
2789
      // The builder acted successfully on the current action.
2790
      ABRT_Success,
2791
      // The builder didn't have to act on the current action.
2792
      ABRT_Inactive,
2793
      // The builder was successful and requested the host action to not be
2794
      // generated.
2795
      ABRT_Ignore_Host,
2796
    };
2797
2798
  protected:
2799
    /// Compilation associated with this builder.
2800
    Compilation &C;
2801
2802
    /// Tool chains associated with this builder. The same programming
2803
    /// model may have associated one or more tool chains.
2804
    SmallVector<const ToolChain *, 2> ToolChains;
2805
2806
    /// The derived arguments associated with this builder.
2807
    DerivedArgList &Args;
2808
2809
    /// The inputs associated with this builder.
2810
    const Driver::InputList &Inputs;
2811
2812
    /// The associated offload kind.
2813
    Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2814
2815
  public:
2816
    DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2817
                        const Driver::InputList &Inputs,
2818
                        Action::OffloadKind AssociatedOffloadKind)
2819
100k
        : C(C), Args(Args), Inputs(Inputs),
2820
100k
          AssociatedOffloadKind(AssociatedOffloadKind) {}
2821
100k
    virtual ~DeviceActionBuilder() {}
2822
2823
    /// Fill up the array \a DA with all the device dependences that should be
2824
    /// added to the provided host action \a HostAction. By default it is
2825
    /// inactive.
2826
    virtual ActionBuilderReturnCode
2827
    getDeviceDependences(OffloadAction::DeviceDependences &DA,
2828
                         phases::ID CurPhase, phases::ID FinalPhase,
2829
0
                         PhasesTy &Phases) {
2830
0
      return ABRT_Inactive;
2831
0
    }
2832
2833
    /// Update the state to include the provided host action \a HostAction as a
2834
    /// dependency of the current device action. By default it is inactive.
2835
0
    virtual ActionBuilderReturnCode addDeviceDependences(Action *HostAction) {
2836
0
      return ABRT_Inactive;
2837
0
    }
2838
2839
    /// Append top level actions generated by the builder.
2840
0
    virtual void appendTopLevelActions(ActionList &AL) {}
2841
2842
    /// Append linker device actions generated by the builder.
2843
5
    virtual void appendLinkDeviceActions(ActionList &AL) {}
2844
2845
    /// Append linker host action generated by the builder.
2846
0
    virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; }
2847
2848
    /// Append linker actions generated by the builder.
2849
5
    virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2850
2851
    /// Initialize the builder. Return true if any initialization errors are
2852
    /// found.
2853
0
    virtual bool initialize() { return false; }
2854
2855
    /// Return true if the builder can use bundling/unbundling.
2856
96
    virtual bool canUseBundlerUnbundler() const { return false; }
2857
2858
    /// Return true if this builder is valid. We have a valid builder if we have
2859
    /// associated device tool chains.
2860
857k
    bool isValid() { return !ToolChains.empty(); }
2861
2862
    /// Return the associated offload kind.
2863
3.72k
    Action::OffloadKind getAssociatedOffloadKind() {
2864
3.72k
      return AssociatedOffloadKind;
2865
3.72k
    }
2866
  };
2867
2868
  /// Base class for CUDA/HIP action builder. It injects device code in
2869
  /// the host backend action.
2870
  class CudaActionBuilderBase : public DeviceActionBuilder {
2871
  protected:
2872
    /// Flags to signal if the user requested host-only or device-only
2873
    /// compilation.
2874
    bool CompileHostOnly = false;
2875
    bool CompileDeviceOnly = false;
2876
    bool EmitLLVM = false;
2877
    bool EmitAsm = false;
2878
2879
    /// ID to identify each device compilation. For CUDA it is simply the
2880
    /// GPU arch string. For HIP it is either the GPU arch string or GPU
2881
    /// arch string plus feature strings delimited by a plus sign, e.g.
2882
    /// gfx906+xnack.
2883
    struct TargetID {
2884
      /// Target ID string which is persistent throughout the compilation.
2885
      const char *ID;
2886
121
      TargetID(CudaArch Arch) { ID = CudaArchToString(Arch); }
2887
510
      TargetID(const char *ID) : ID(ID) {}
2888
656
      operator const char *() { return ID; }
2889
66
      operator StringRef() { return StringRef(ID); }
2890
    };
2891
    /// List of GPU architectures to use in this compilation.
2892
    SmallVector<TargetID, 4> GpuArchList;
2893
2894
    /// The CUDA actions for the current input.
2895
    ActionList CudaDeviceActions;
2896
2897
    /// The CUDA fat binary if it was generated for the current input.
2898
    Action *CudaFatBinary = nullptr;
2899
2900
    /// Flag that is set to true if this builder acted on the current input.
2901
    bool IsActive = false;
2902
2903
    /// Flag for -fgpu-rdc.
2904
    bool Relocatable = false;
2905
2906
    /// Default GPU architecture if there's no one specified.
2907
    CudaArch DefaultCudaArch = CudaArch::UNKNOWN;
2908
2909
    /// Method to generate compilation unit ID specified by option
2910
    /// '-fuse-cuid='.
2911
    enum UseCUIDKind { CUID_Hash, CUID_Random, CUID_None, CUID_Invalid };
2912
    UseCUIDKind UseCUID = CUID_Hash;
2913
2914
    /// Compilation unit ID specified by option '-cuid='.
2915
    StringRef FixedCUID;
2916
2917
  public:
2918
    CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2919
                          const Driver::InputList &Inputs,
2920
                          Action::OffloadKind OFKind)
2921
100k
        : DeviceActionBuilder(C, Args, Inputs, OFKind) {
2922
2923
100k
      CompileDeviceOnly = C.getDriver().offloadDeviceOnly();
2924
100k
      Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2925
100k
                                 options::OPT_fno_gpu_rdc, /*Default=*/false);
2926
100k
    }
2927
2928
1.97k
    ActionBuilderReturnCode addDeviceDependences(Action *HostAction) override {
2929
      // While generating code for CUDA, we only depend on the host input action
2930
      // to trigger the creation of all the CUDA device actions.
2931
2932
      // If we are dealing with an input action, replicate it for each GPU
2933
      // architecture. If we are in host-only mode we return 'success' so that
2934
      // the host uses the CUDA offload kind.
2935
1.97k
      if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2936
479
        assert(!GpuArchList.empty() &&
2937
479
               "We should have at least one GPU architecture.");
2938
2939
        // If the host input is not CUDA or HIP, we don't need to bother about
2940
        // this input.
2941
479
        if (!(IA->getType() == types::TY_CUDA ||
2942
479
              
IA->getType() == types::TY_HIP384
||
2943
479
              
IA->getType() == types::TY_PP_HIP25
)) {
2944
          // The builder will ignore this input.
2945
25
          IsActive = false;
2946
25
          return ABRT_Inactive;
2947
25
        }
2948
2949
        // Set the flag to true, so that the builder acts on the current input.
2950
454
        IsActive = true;
2951
2952
454
        if (CompileHostOnly)
2953
31
          return ABRT_Success;
2954
2955
        // Replicate inputs for each GPU architecture.
2956
423
        auto Ty = IA->getType() == types::TY_HIP ? 
types::TY_HIP_DEVICE352
2957
423
                                                 : 
types::TY_CUDA_DEVICE71
;
2958
423
        std::string CUID = FixedCUID.str();
2959
423
        if (CUID.empty()) {
2960
419
          if (UseCUID == CUID_Random)
2961
2
            CUID = llvm::utohexstr(llvm::sys::Process::GetRandomNumber(),
2962
2
                                   /*LowerCase=*/true);
2963
417
          else if (UseCUID == CUID_Hash) {
2964
417
            llvm::MD5 Hasher;
2965
417
            llvm::MD5::MD5Result Hash;
2966
417
            SmallString<256> RealPath;
2967
417
            llvm::sys::fs::real_path(IA->getInputArg().getValue(), RealPath,
2968
417
                                     /*expand_tilde=*/true);
2969
417
            Hasher.update(RealPath);
2970
4.06k
            for (auto *A : Args) {
2971
4.06k
              if (A->getOption().matches(options::OPT_INPUT))
2972
476
                continue;
2973
3.58k
              Hasher.update(A->getAsString(Args));
2974
3.58k
            }
2975
417
            Hasher.final(Hash);
2976
417
            CUID = llvm::utohexstr(Hash.low(), /*LowerCase=*/true);
2977
417
          }
2978
419
        }
2979
423
        IA->setId(CUID);
2980
2981
971
        for (unsigned I = 0, E = GpuArchList.size(); I != E; 
++I548
) {
2982
548
          CudaDeviceActions.push_back(
2983
548
              C.MakeAction<InputAction>(IA->getInputArg(), Ty, IA->getId()));
2984
548
        }
2985
2986
423
        return ABRT_Success;
2987
454
      }
2988
2989
      // If this is an unbundling action use it as is for each CUDA toolchain.
2990
1.49k
      if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2991
2992
        // If -fgpu-rdc is disabled, should not unbundle since there is no
2993
        // device code to link.
2994
54
        if (UA->getType() == types::TY_Object && 
!Relocatable45
)
2995
13
          return ABRT_Inactive;
2996
2997
41
        CudaDeviceActions.clear();
2998
41
        auto *IA = cast<InputAction>(UA->getInputs().back());
2999
41
        std::string FileName = IA->getInputArg().getAsString(Args);
3000
        // Check if the type of the file is the same as the action. Do not
3001
        // unbundle it if it is not. Do not unbundle .so files, for example,
3002
        // which are not object files. Files with extension ".lib" is classified
3003
        // as TY_Object but they are actually archives, therefore should not be
3004
        // unbundled here as objects. They will be handled at other places.
3005
41
        const StringRef LibFileExt = ".lib";
3006
41
        if (IA->getType() == types::TY_Object &&
3007
41
            
(32
!llvm::sys::path::has_extension(FileName)32
||
3008
32
             types::lookupTypeForExtension(
3009
32
                 llvm::sys::path::extension(FileName).drop_front()) !=
3010
32
                 types::TY_Object ||
3011
32
             
llvm::sys::path::extension(FileName) == LibFileExt29
))
3012
4
          return ABRT_Inactive;
3013
3014
66
        
for (auto Arch : GpuArchList)37
{
3015
66
          CudaDeviceActions.push_back(UA);
3016
66
          UA->registerDependentActionInfo(ToolChains[0], Arch,
3017
66
                                          AssociatedOffloadKind);
3018
66
        }
3019
37
        IsActive = true;
3020
37
        return ABRT_Success;
3021
41
      }
3022
3023
1.44k
      return IsActive ? 
ABRT_Success1.41k
:
ABRT_Inactive33
;
3024
1.49k
    }
3025
3026
533
    void appendTopLevelActions(ActionList &AL) override {
3027
      // Utility to append actions to the top level list.
3028
533
      auto AddTopLevel = [&](Action *A, TargetID TargetID) {
3029
167
        OffloadAction::DeviceDependences Dep;
3030
167
        Dep.add(*A, *ToolChains.front(), TargetID, AssociatedOffloadKind);
3031
167
        AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
3032
167
      };
3033
3034
      // If we have a fat binary, add it to the list.
3035
533
      if (CudaFatBinary) {
3036
33
        AddTopLevel(CudaFatBinary, CudaArch::UNUSED);
3037
33
        CudaDeviceActions.clear();
3038
33
        CudaFatBinary = nullptr;
3039
33
        return;
3040
33
      }
3041
3042
500
      if (CudaDeviceActions.empty())
3043
391
        return;
3044
3045
      // If we have CUDA actions at this point, that's because we have a have
3046
      // partial compilation, so we should have an action for each GPU
3047
      // architecture.
3048
109
      assert(CudaDeviceActions.size() == GpuArchList.size() &&
3049
109
             "Expecting one action per GPU architecture.");
3050
109
      assert(ToolChains.size() == 1 &&
3051
109
             "Expecting to have a single CUDA toolchain.");
3052
243
      
for (unsigned I = 0, E = GpuArchList.size(); 109
I != E;
++I134
)
3053
134
        AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
3054
3055
109
      CudaDeviceActions.clear();
3056
109
    }
3057
3058
    /// Get canonicalized offload arch option. \returns empty StringRef if the
3059
    /// option is invalid.
3060
    virtual StringRef getCanonicalOffloadArch(StringRef Arch) = 0;
3061
3062
    virtual std::optional<std::pair<llvm::StringRef, llvm::StringRef>>
3063
    getConflictOffloadArchCombination(const std::set<StringRef> &GpuArchs) = 0;
3064
3065
100k
    bool initialize() override {
3066
100k
      assert(AssociatedOffloadKind == Action::OFK_Cuda ||
3067
100k
             AssociatedOffloadKind == Action::OFK_HIP);
3068
3069
      // We don't need to support CUDA.
3070
100k
      if (AssociatedOffloadKind == Action::OFK_Cuda &&
3071
100k
          
!C.hasOffloadToolChain<Action::OFK_Cuda>()50.4k
)
3072
50.3k
        return false;
3073
3074
      // We don't need to support HIP.
3075
50.5k
      if (AssociatedOffloadKind == Action::OFK_HIP &&
3076
50.5k
          
!C.hasOffloadToolChain<Action::OFK_HIP>()50.4k
)
3077
50.0k
        return false;
3078
3079
493
      const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
3080
493
      assert(HostTC && "No toolchain for host compilation.");
3081
493
      if (HostTC->getTriple().isNVPTX() ||
3082
493
          
HostTC->getTriple().getArch() == llvm::Triple::amdgcn472
) {
3083
        // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
3084
        // an error and abort pipeline construction early so we don't trip
3085
        // asserts that assume device-side compilation.
3086
0
        C.getDriver().Diag(diag::err_drv_cuda_host_arch)
3087
0
            << HostTC->getTriple().getArchName();
3088
0
        return true;
3089
0
      }
3090
3091
493
      ToolChains.push_back(
3092
493
          AssociatedOffloadKind == Action::OFK_Cuda
3093
493
              ? 
C.getSingleOffloadToolChain<Action::OFK_Cuda>()96
3094
493
              : 
C.getSingleOffloadToolChain<Action::OFK_HIP>()397
);
3095
3096
493
      CompileHostOnly = C.getDriver().offloadHostOnly();
3097
493
      EmitLLVM = Args.getLastArg(options::OPT_emit_llvm);
3098
493
      EmitAsm = Args.getLastArg(options::OPT_S);
3099
493
      FixedCUID = Args.getLastArgValue(options::OPT_cuid_EQ);
3100
493
      if (Arg *A = Args.getLastArg(options::OPT_fuse_cuid_EQ)) {
3101
8
        StringRef UseCUIDStr = A->getValue();
3102
8
        UseCUID = llvm::StringSwitch<UseCUIDKind>(UseCUIDStr)
3103
8
                      .Case("hash", CUID_Hash)
3104
8
                      .Case("random", CUID_Random)
3105
8
                      .Case("none", CUID_None)
3106
8
                      .Default(CUID_Invalid);
3107
8
        if (UseCUID == CUID_Invalid) {
3108
1
          C.getDriver().Diag(diag::err_drv_invalid_value)
3109
1
              << A->getAsString(Args) << UseCUIDStr;
3110
1
          C.setContainsError();
3111
1
          return true;
3112
1
        }
3113
8
      }
3114
3115
      // --offload and --offload-arch options are mutually exclusive.
3116
492
      if (Args.hasArgNoClaim(options::OPT_offload_EQ) &&
3117
492
          Args.hasArgNoClaim(options::OPT_offload_arch_EQ,
3118
25
                             options::OPT_no_offload_arch_EQ)) {
3119
1
        C.getDriver().Diag(diag::err_opt_not_valid_with_opt) << "--offload-arch"
3120
1
                                                             << "--offload";
3121
1
      }
3122
3123
      // Collect all offload arch parameters, removing duplicates.
3124
492
      std::set<StringRef> GpuArchs;
3125
492
      bool Error = false;
3126
4.51k
      for (Arg *A : Args) {
3127
4.51k
        if (!(A->getOption().matches(options::OPT_offload_arch_EQ) ||
3128
4.51k
              
A->getOption().matches(options::OPT_no_offload_arch_EQ)3.98k
))
3129
3.98k
          continue;
3130
524
        A->claim();
3131
3132
524
        for (StringRef ArchStr : llvm::split(A->getValue(), ",")) {
3133
524
          if (A->getOption().matches(options::OPT_no_offload_arch_EQ) &&
3134
524
              
ArchStr == "all"0
) {
3135
0
            GpuArchs.clear();
3136
524
          } else if (ArchStr == "native") {
3137
0
            const ToolChain &TC = *ToolChains.front();
3138
0
            auto GPUsOrErr = ToolChains.front()->getSystemGPUArchs(Args);
3139
0
            if (!GPUsOrErr) {
3140
0
              TC.getDriver().Diag(diag::err_drv_undetermined_gpu_arch)
3141
0
                  << llvm::Triple::getArchTypeName(TC.getArch())
3142
0
                  << llvm::toString(GPUsOrErr.takeError()) << "--offload-arch";
3143
0
              continue;
3144
0
            }
3145
3146
0
            for (auto GPU : *GPUsOrErr) {
3147
0
              GpuArchs.insert(Args.MakeArgString(GPU));
3148
0
            }
3149
524
          } else {
3150
524
            ArchStr = getCanonicalOffloadArch(ArchStr);
3151
524
            if (ArchStr.empty()) {
3152
10
              Error = true;
3153
514
            } else if (A->getOption().matches(options::OPT_offload_arch_EQ))
3154
514
              GpuArchs.insert(ArchStr);
3155
0
            else if (A->getOption().matches(options::OPT_no_offload_arch_EQ))
3156
0
              GpuArchs.erase(ArchStr);
3157
0
            else
3158
0
              llvm_unreachable("Unexpected option.");
3159
524
          }
3160
524
        }
3161
524
      }
3162
3163
492
      auto &&ConflictingArchs = getConflictOffloadArchCombination(GpuArchs);
3164
492
      if (ConflictingArchs) {
3165
1
        C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo)
3166
1
            << ConflictingArchs->first << ConflictingArchs->second;
3167
1
        C.setContainsError();
3168
1
        return true;
3169
1
      }
3170
3171
      // Collect list of GPUs remaining in the set.
3172
491
      for (auto Arch : GpuArchs)
3173
510
        GpuArchList.push_back(Arch.data());
3174
3175
      // Default to sm_20 which is the lowest common denominator for
3176
      // supported GPUs.  sm_20 code should work correctly, if
3177
      // suboptimally, on all newer GPUs.
3178
491
      if (GpuArchList.empty()) {
3179
88
        if (ToolChains.front()->getTriple().isSPIRV())
3180
24
          GpuArchList.push_back(CudaArch::Generic);
3181
64
        else
3182
64
          GpuArchList.push_back(DefaultCudaArch);
3183
88
      }
3184
3185
491
      return Error;
3186
492
    }
3187
  };
3188
3189
  /// \brief CUDA action builder. It injects device code in the host backend
3190
  /// action.
3191
  class CudaActionBuilder final : public CudaActionBuilderBase {
3192
  public:
3193
    CudaActionBuilder(Compilation &C, DerivedArgList &Args,
3194
                      const Driver::InputList &Inputs)
3195
50.4k
        : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {
3196
50.4k
      DefaultCudaArch = CudaArch::SM_35;
3197
50.4k
    }
3198
3199
45
    StringRef getCanonicalOffloadArch(StringRef ArchStr) override {
3200
45
      CudaArch Arch = StringToCudaArch(ArchStr);
3201
45
      if (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch)) {
3202
0
        C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
3203
0
        return StringRef();
3204
0
      }
3205
45
      return CudaArchToString(Arch);
3206
45
    }
3207
3208
    std::optional<std::pair<llvm::StringRef, llvm::StringRef>>
3209
    getConflictOffloadArchCombination(
3210
96
        const std::set<StringRef> &GpuArchs) override {
3211
96
      return std::nullopt;
3212
96
    }
3213
3214
    ActionBuilderReturnCode
3215
    getDeviceDependences(OffloadAction::DeviceDependences &DA,
3216
                         phases::ID CurPhase, phases::ID FinalPhase,
3217
253
                         PhasesTy &Phases) override {
3218
253
      if (!IsActive)
3219
1
        return ABRT_Inactive;
3220
3221
      // If we don't have more CUDA actions, we don't have any dependences to
3222
      // create for the host.
3223
252
      if (CudaDeviceActions.empty())
3224
96
        return ABRT_Success;
3225
3226
156
      assert(CudaDeviceActions.size() == GpuArchList.size() &&
3227
156
             "Expecting one action per GPU architecture.");
3228
156
      assert(!CompileHostOnly &&
3229
156
             "Not expecting CUDA actions in host-only compilation.");
3230
3231
      // If we are generating code for the device or we are in a backend phase,
3232
      // we attempt to generate the fat binary. We compile each arch to ptx and
3233
      // assemble to cubin, then feed the cubin *and* the ptx into a device
3234
      // "link" action, which uses fatbinary to combine these cubins into one
3235
      // fatbin.  The fatbin is then an input to the host action if not in
3236
      // device-only mode.
3237
156
      if (CompileDeviceOnly || 
CurPhase == phases::Backend129
) {
3238
68
        ActionList DeviceActions;
3239
136
        for (unsigned I = 0, E = GpuArchList.size(); I != E; 
++I68
) {
3240
          // Produce the device action from the current phase up to the assemble
3241
          // phase.
3242
244
          for (auto Ph : Phases) {
3243
            // Skip the phases that were already dealt with.
3244
244
            if (Ph < CurPhase)
3245
82
              continue;
3246
            // We have to be consistent with the host final phase.
3247
162
            if (Ph > FinalPhase)
3248
16
              break;
3249
3250
146
            CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
3251
146
                C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
3252
3253
146
            if (Ph == phases::Assemble)
3254
52
              break;
3255
146
          }
3256
3257
          // If we didn't reach the assemble phase, we can't generate the fat
3258
          // binary. We don't need to generate the fat binary if we are not in
3259
          // device-only mode.
3260
68
          if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
3261
68
              
CompileDeviceOnly47
)
3262
28
            continue;
3263
3264
40
          Action *AssembleAction = CudaDeviceActions[I];
3265
40
          assert(AssembleAction->getType() == types::TY_Object);
3266
40
          assert(AssembleAction->getInputs().size() == 1);
3267
3268
40
          Action *BackendAction = AssembleAction->getInputs()[0];
3269
40
          assert(BackendAction->getType() == types::TY_PP_Asm);
3270
3271
80
          
for (auto &A : {AssembleAction, BackendAction})40
{
3272
80
            OffloadAction::DeviceDependences DDep;
3273
80
            DDep.add(*A, *ToolChains.front(), GpuArchList[I], Action::OFK_Cuda);
3274
80
            DeviceActions.push_back(
3275
80
                C.MakeAction<OffloadAction>(DDep, A->getType()));
3276
80
          }
3277
40
        }
3278
3279
        // We generate the fat binary if we have device input actions.
3280
68
        if (!DeviceActions.empty()) {
3281
40
          CudaFatBinary =
3282
40
              C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
3283
3284
40
          if (!CompileDeviceOnly) {
3285
40
            DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
3286
40
                   Action::OFK_Cuda);
3287
            // Clear the fat binary, it is already a dependence to an host
3288
            // action.
3289
40
            CudaFatBinary = nullptr;
3290
40
          }
3291
3292
          // Remove the CUDA actions as they are already connected to an host
3293
          // action or fat binary.
3294
40
          CudaDeviceActions.clear();
3295
40
        }
3296
3297
        // We avoid creating host action in device-only mode.
3298
68
        return CompileDeviceOnly ? 
ABRT_Ignore_Host27
:
ABRT_Success41
;
3299
88
      } else if (CurPhase > phases::Backend) {
3300
        // If we are past the backend phase and still have a device action, we
3301
        // don't have to do anything as this action is already a device
3302
        // top-level action.
3303
0
        return ABRT_Success;
3304
0
      }
3305
3306
88
      assert(CurPhase < phases::Backend && "Generating single CUDA "
3307
88
                                           "instructions should only occur "
3308
88
                                           "before the backend phase!");
3309
3310
      // By default, we produce an action for each device arch.
3311
88
      for (Action *&A : CudaDeviceActions)
3312
88
        A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
3313
3314
88
      return ABRT_Success;
3315
88
    }
3316
  };
3317
  /// \brief HIP action builder. It injects device code in the host backend
3318
  /// action.
3319
  class HIPActionBuilder final : public CudaActionBuilderBase {
3320
    /// The linker inputs obtained for each device arch.
3321
    SmallVector<ActionList, 8> DeviceLinkerInputs;
3322
    // The default bundling behavior depends on the type of output, therefore
3323
    // BundleOutput needs to be tri-value: None, true, or false.
3324
    // Bundle code objects except --no-gpu-output is specified for device
3325
    // only compilation. Bundle other type of output files only if
3326
    // --gpu-bundle-output is specified for device only compilation.
3327
    std::optional<bool> BundleOutput;
3328
    std::optional<bool> EmitReloc;
3329
3330
  public:
3331
    HIPActionBuilder(Compilation &C, DerivedArgList &Args,
3332
                     const Driver::InputList &Inputs)
3333
50.4k
        : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {
3334
3335
50.4k
      DefaultCudaArch = CudaArch::GFX906;
3336
3337
50.4k
      if (Args.hasArg(options::OPT_fhip_emit_relocatable,
3338
50.4k
                      options::OPT_fno_hip_emit_relocatable)) {
3339
8
        EmitReloc = Args.hasFlag(options::OPT_fhip_emit_relocatable,
3340
8
                                 options::OPT_fno_hip_emit_relocatable, false);
3341
3342
8
        if (*EmitReloc) {
3343
7
          if (Relocatable) {
3344
1
            C.getDriver().Diag(diag::err_opt_not_valid_with_opt)
3345
1
                << "-fhip-emit-relocatable"
3346
1
                << "-fgpu-rdc";
3347
1
          }
3348
3349
7
          if (!CompileDeviceOnly) {
3350
1
            C.getDriver().Diag(diag::err_opt_not_valid_without_opt)
3351
1
                << "-fhip-emit-relocatable"
3352
1
                << "--cuda-device-only";
3353
1
          }
3354
7
        }
3355
8
      }
3356
3357
50.4k
      if (Args.hasArg(options::OPT_gpu_bundle_output,
3358
50.4k
                      options::OPT_no_gpu_bundle_output))
3359
32
        BundleOutput = Args.hasFlag(options::OPT_gpu_bundle_output,
3360
32
                                    options::OPT_no_gpu_bundle_output, true) &&
3361
32
                       
(18
!EmitReloc18
||
!*EmitReloc3
);
3362
50.4k
    }
3363
3364
376
    bool canUseBundlerUnbundler() const override { return true; }
3365
3366
479
    StringRef getCanonicalOffloadArch(StringRef IdStr) override {
3367
479
      llvm::StringMap<bool> Features;
3368
      // getHIPOffloadTargetTriple() is known to return valid value as it has
3369
      // been called successfully in the CreateOffloadingDeviceToolChains().
3370
479
      auto ArchStr = parseTargetID(
3371
479
          *getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs()), IdStr,
3372
479
          &Features);
3373
479
      if (!ArchStr) {
3374
10
        C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << IdStr;
3375
10
        C.setContainsError();
3376
10
        return StringRef();
3377
10
      }
3378
469
      auto CanId = getCanonicalTargetID(*ArchStr, Features);
3379
469
      return Args.MakeArgStringRef(CanId);
3380
479
    };
3381
3382
    std::optional<std::pair<llvm::StringRef, llvm::StringRef>>
3383
    getConflictOffloadArchCombination(
3384
375
        const std::set<StringRef> &GpuArchs) override {
3385
375
      return getConflictTargetIDCombination(GpuArchs);
3386
375
    }
3387
3388
    ActionBuilderReturnCode
3389
    getDeviceDependences(OffloadAction::DeviceDependences &DA,
3390
                         phases::ID CurPhase, phases::ID FinalPhase,
3391
1.58k
                         PhasesTy &Phases) override {
3392
1.58k
      if (!IsActive)
3393
67
        return ABRT_Inactive;
3394
3395
      // amdgcn does not support linking of object files, therefore we skip
3396
      // backend and assemble phases to output LLVM IR. Except for generating
3397
      // non-relocatable device code, where we generate fat binary for device
3398
      // code and pass to host in Backend phase.
3399
1.51k
      if (CudaDeviceActions.empty())
3400
370
        return ABRT_Success;
3401
3402
1.14k
      assert(((CurPhase == phases::Link && Relocatable) ||
3403
1.14k
              CudaDeviceActions.size() == GpuArchList.size()) &&
3404
1.14k
             "Expecting one action per GPU architecture.");
3405
1.14k
      assert(!CompileHostOnly &&
3406
1.14k
             "Not expecting HIP actions in host-only compilation.");
3407
3408
1.14k
      bool ShouldLink = !EmitReloc || 
!*EmitReloc44
;
3409
3410
1.14k
      if (!Relocatable && 
CurPhase == phases::Backend781
&&
!EmitLLVM241
&&
3411
1.14k
          
!EmitAsm232
&&
ShouldLink217
) {
3412
        // If we are in backend phase, we attempt to generate the fat binary.
3413
        // We compile each arch to IR and use a link action to generate code
3414
        // object containing ISA. Then we use a special "link" action to create
3415
        // a fat binary containing all the code objects for different GPU's.
3416
        // The fat binary is then an input to the host action.
3417
477
        for (unsigned I = 0, E = GpuArchList.size(); I != E; 
++I267
) {
3418
267
          if (C.getDriver().isUsingLTO(/*IsOffload=*/true)) {
3419
            // When LTO is enabled, skip the backend and assemble phases and
3420
            // use lld to link the bitcode.
3421
1
            ActionList AL;
3422
1
            AL.push_back(CudaDeviceActions[I]);
3423
            // Create a link action to link device IR with device library
3424
            // and generate ISA.
3425
1
            CudaDeviceActions[I] =
3426
1
                C.MakeAction<LinkJobAction>(AL, types::TY_Image);
3427
266
          } else {
3428
            // When LTO is not enabled, we follow the conventional
3429
            // compiler phases, including backend and assemble phases.
3430
266
            ActionList AL;
3431
266
            Action *BackendAction = nullptr;
3432
266
            if (ToolChains.front()->getTriple().isSPIRV()) {
3433
              // Emit LLVM bitcode for SPIR-V targets. SPIR-V device tool chain
3434
              // (HIPSPVToolChain) runs post-link LLVM IR passes.
3435
8
              types::ID Output = Args.hasArg(options::OPT_S)
3436
8
                                     ? 
types::TY_LLVM_IR0
3437
8
                                     : types::TY_LLVM_BC;
3438
8
              BackendAction =
3439
8
                  C.MakeAction<BackendJobAction>(CudaDeviceActions[I], Output);
3440
8
            } else
3441
258
              BackendAction = C.getDriver().ConstructPhaseAction(
3442
258
                  C, Args, phases::Backend, CudaDeviceActions[I],
3443
258
                  AssociatedOffloadKind);
3444
266
            auto AssembleAction = C.getDriver().ConstructPhaseAction(
3445
266
                C, Args, phases::Assemble, BackendAction,
3446
266
                AssociatedOffloadKind);
3447
266
            AL.push_back(AssembleAction);
3448
            // Create a link action to link device IR with device library
3449
            // and generate ISA.
3450
266
            CudaDeviceActions[I] =
3451
266
                C.MakeAction<LinkJobAction>(AL, types::TY_Image);
3452
266
          }
3453
3454
          // OffloadingActionBuilder propagates device arch until an offload
3455
          // action. Since the next action for creating fatbin does
3456
          // not have device arch, whereas the above link action and its input
3457
          // have device arch, an offload action is needed to stop the null
3458
          // device arch of the next action being propagated to the above link
3459
          // action.
3460
267
          OffloadAction::DeviceDependences DDep;
3461
267
          DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I],
3462
267
                   AssociatedOffloadKind);
3463
267
          CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
3464
267
              DDep, CudaDeviceActions[I]->getType());
3465
267
        }
3466
3467
210
        if (!CompileDeviceOnly || 
!BundleOutput13
||
*BundleOutput2
) {
3468
          // Create HIP fat binary with a special "link" action.
3469
208
          CudaFatBinary = C.MakeAction<LinkJobAction>(CudaDeviceActions,
3470
208
                                                      types::TY_HIP_FATBIN);
3471
3472
208
          if (!CompileDeviceOnly) {
3473
197
            DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
3474
197
                   AssociatedOffloadKind);
3475
            // Clear the fat binary, it is already a dependence to an host
3476
            // action.
3477
197
            CudaFatBinary = nullptr;
3478
197
          }
3479
3480
          // Remove the CUDA actions as they are already connected to an host
3481
          // action or fat binary.
3482
208
          CudaDeviceActions.clear();
3483
208
        }
3484
3485
210
        return CompileDeviceOnly ? 
ABRT_Ignore_Host13
:
ABRT_Success197
;
3486
938
      } else if (CurPhase == phases::Link) {
3487
81
        if (!ShouldLink)
3488
0
          return ABRT_Success;
3489
        // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
3490
        // This happens to each device action originated from each input file.
3491
        // Later on, device actions in DeviceLinkerInputs are used to create
3492
        // device link actions in appendLinkDependences and the created device
3493
        // link actions are passed to the offload action as device dependence.
3494
81
        DeviceLinkerInputs.resize(CudaDeviceActions.size());
3495
81
        auto LI = DeviceLinkerInputs.begin();
3496
135
        for (auto *A : CudaDeviceActions) {
3497
135
          LI->push_back(A);
3498
135
          ++LI;
3499
135
        }
3500
3501
        // We will pass the device action as a host dependence, so we don't
3502
        // need to do anything else with them.
3503
81
        CudaDeviceActions.clear();
3504
81
        return CompileDeviceOnly ? 
ABRT_Ignore_Host17
:
ABRT_Success64
;
3505
81
      }
3506
3507
      // By default, we produce an action for each device arch.
3508
857
      for (Action *&A : CudaDeviceActions)
3509
1.20k
        A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
3510
1.20k
                                               AssociatedOffloadKind);
3511
3512
857
      if (CompileDeviceOnly && 
CurPhase == FinalPhase215
&&
BundleOutput71
&&
3513
857
          
*BundleOutput33
) {
3514
62
        for (unsigned I = 0, E = GpuArchList.size(); I != E; 
++I40
) {
3515
40
          OffloadAction::DeviceDependences DDep;
3516
40
          DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I],
3517
40
                   AssociatedOffloadKind);
3518
40
          CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
3519
40
              DDep, CudaDeviceActions[I]->getType());
3520
40
        }
3521
22
        CudaFatBinary =
3522
22
            C.MakeAction<OffloadBundlingJobAction>(CudaDeviceActions);
3523
22
        CudaDeviceActions.clear();
3524
22
      }
3525
3526
857
      return (CompileDeviceOnly &&
3527
857
              
(215
CurPhase == FinalPhase215
||
3528
215
               
(144
!ShouldLink144
&&
CurPhase == phases::Assemble25
)))
3529
857
                 ? 
ABRT_Ignore_Host75
3530
857
                 : 
ABRT_Success782
;
3531
1.14k
    }
3532
3533
238
    void appendLinkDeviceActions(ActionList &AL) override {
3534
238
      if (DeviceLinkerInputs.size() == 0)
3535
175
        return;
3536
3537
63
      assert(DeviceLinkerInputs.size() == GpuArchList.size() &&
3538
63
             "Linker inputs and GPU arch list sizes do not match.");
3539
3540
63
      ActionList Actions;
3541
63
      unsigned I = 0;
3542
      // Append a new link action for each device.
3543
      // Each entry in DeviceLinkerInputs corresponds to a GPU arch.
3544
102
      for (auto &LI : DeviceLinkerInputs) {
3545
3546
102
        types::ID Output = Args.hasArg(options::OPT_emit_llvm)
3547
102
                                   ? 
types::TY_LLVM_BC3
3548
102
                                   : 
types::TY_Image99
;
3549
3550
102
        auto *DeviceLinkAction = C.MakeAction<LinkJobAction>(LI, Output);
3551
        // Linking all inputs for the current GPU arch.
3552
        // LI contains all the inputs for the linker.
3553
102
        OffloadAction::DeviceDependences DeviceLinkDeps;
3554
102
        DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0],
3555
102
            GpuArchList[I], AssociatedOffloadKind);
3556
102
        Actions.push_back(C.MakeAction<OffloadAction>(
3557
102
            DeviceLinkDeps, DeviceLinkAction->getType()));
3558
102
        ++I;
3559
102
      }
3560
63
      DeviceLinkerInputs.clear();
3561
3562
      // If emitting LLVM, do not generate final host/device compilation action
3563
63
      if (Args.hasArg(options::OPT_emit_llvm)) {
3564
3
          AL.append(Actions);
3565
3
          return;
3566
3
      }
3567
3568
      // Create a host object from all the device images by embedding them
3569
      // in a fat binary for mixed host-device compilation. For device-only
3570
      // compilation, creates a fat binary.
3571
60
      OffloadAction::DeviceDependences DDeps;
3572
60
      if (!CompileDeviceOnly || 
!BundleOutput6
||
*BundleOutput3
) {
3573
57
        auto *TopDeviceLinkAction = C.MakeAction<LinkJobAction>(
3574
57
            Actions,
3575
57
            CompileDeviceOnly ? 
types::TY_HIP_FATBIN3
:
types::TY_Object54
);
3576
57
        DDeps.add(*TopDeviceLinkAction, *ToolChains[0], nullptr,
3577
57
                  AssociatedOffloadKind);
3578
        // Offload the host object to the host linker.
3579
57
        AL.push_back(
3580
57
            C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType()));
3581
57
      } else {
3582
3
        AL.append(Actions);
3583
3
      }
3584
60
    }
3585
3586
54
    Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); }
3587
3588
207
    void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
3589
  };
3590
3591
  ///
3592
  /// TODO: Add the implementation for other specialized builders here.
3593
  ///
3594
3595
  /// Specialized builders being used by this offloading action builder.
3596
  SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
3597
3598
  /// Flag set to true if all valid builders allow file bundling/unbundling.
3599
  bool CanUseBundler;
3600
3601
public:
3602
  OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
3603
                          const Driver::InputList &Inputs)
3604
50.4k
      : C(C) {
3605
    // Create a specialized builder for each device toolchain.
3606
3607
50.4k
    IsValid = true;
3608
3609
    // Create a specialized builder for CUDA.
3610
50.4k
    SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
3611
3612
    // Create a specialized builder for HIP.
3613
50.4k
    SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
3614
3615
    //
3616
    // TODO: Build other specialized builders here.
3617
    //
3618
3619
    // Initialize all the builders, keeping track of errors. If all valid
3620
    // builders agree that we can use bundling, set the flag to true.
3621
50.4k
    unsigned ValidBuilders = 0u;
3622
50.4k
    unsigned ValidBuildersSupportingBundling = 0u;
3623
100k
    for (auto *SB : SpecializedBuilders) {
3624
100k
      IsValid = IsValid && !SB->initialize();
3625
3626
      // Update the counters if the builder is valid.
3627
100k
      if (SB->isValid()) {
3628
472
        ++ValidBuilders;
3629
472
        if (SB->canUseBundlerUnbundler())
3630
376
          ++ValidBuildersSupportingBundling;
3631
472
      }
3632
100k
    }
3633
50.4k
    CanUseBundler =
3634
50.4k
        ValidBuilders && 
ValidBuilders == ValidBuildersSupportingBundling472
;
3635
50.4k
  }
3636
3637
50.4k
  ~OffloadingActionBuilder() {
3638
50.4k
    for (auto *SB : SpecializedBuilders)
3639
100k
      delete SB;
3640
50.4k
  }
3641
3642
  /// Record a host action and its originating input argument.
3643
350k
  void recordHostAction(Action *HostAction, const Arg *InputArg) {
3644
350k
    assert(HostAction && "Invalid host action");
3645
350k
    assert(InputArg && "Invalid input argument");
3646
350k
    auto Loc = HostActionToInputArgMap.find(HostAction);
3647
350k
    if (Loc == HostActionToInputArgMap.end())
3648
174k
      HostActionToInputArgMap[HostAction] = InputArg;
3649
350k
    assert(HostActionToInputArgMap[HostAction] == InputArg &&
3650
350k
           "host action mapped to multiple input arguments");
3651
350k
  }
3652
3653
  /// Generate an action that adds device dependences (if any) to a host action.
3654
  /// If no device dependence actions exist, just return the host action \a
3655
  /// HostAction. If an error is found or if no builder requires the host action
3656
  /// to be generated, return nullptr.
3657
  Action *
3658
  addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
3659
                                   phases::ID CurPhase, phases::ID FinalPhase,
3660
132k
                                   DeviceActionBuilder::PhasesTy &Phases) {
3661
132k
    if (!IsValid)
3662
0
      return nullptr;
3663
3664
132k
    if (SpecializedBuilders.empty())
3665
0
      return HostAction;
3666
3667
132k
    assert(HostAction && "Invalid host action!");
3668
132k
    recordHostAction(HostAction, InputArg);
3669
3670
132k
    OffloadAction::DeviceDependences DDeps;
3671
    // Check if all the programming models agree we should not emit the host
3672
    // action. Also, keep track of the offloading kinds employed.
3673
132k
    auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3674
132k
    unsigned InactiveBuilders = 0u;
3675
132k
    unsigned IgnoringBuilders = 0u;
3676
264k
    for (auto *SB : SpecializedBuilders) {
3677
264k
      if (!SB->isValid()) {
3678
262k
        ++InactiveBuilders;
3679
262k
        continue;
3680
262k
      }
3681
1.83k
      auto RetCode =
3682
1.83k
          SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
3683
3684
      // If the builder explicitly says the host action should be ignored,
3685
      // we need to increment the variable that tracks the builders that request
3686
      // the host object to be ignored.
3687
1.83k
      if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
3688
132
        ++IgnoringBuilders;
3689
3690
      // Unless the builder was inactive for this action, we have to record the
3691
      // offload kind because the host will have to use it.
3692
1.83k
      if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3693
1.77k
        OffloadKind |= SB->getAssociatedOffloadKind();
3694
1.83k
    }
3695
3696
    // If all builders agree that the host object should be ignored, just return
3697
    // nullptr.
3698
132k
    if (IgnoringBuilders &&
3699
132k
        
SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders)132
)
3700
132
      return nullptr;
3701
3702
131k
    if (DDeps.getActions().empty())
3703
131k
      return HostAction;
3704
3705
    // We have dependences we need to bundle together. We use an offload action
3706
    // for that.
3707
237
    OffloadAction::HostDependence HDep(
3708
237
        *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3709
237
        /*BoundArch=*/nullptr, DDeps);
3710
237
    return C.MakeAction<OffloadAction>(HDep, DDeps);
3711
131k
  }
3712
3713
  /// Generate an action that adds a host dependence to a device action. The
3714
  /// results will be kept in this action builder. Return true if an error was
3715
  /// found.
3716
  bool addHostDependenceToDeviceActions(Action *&HostAction,
3717
174k
                                        const Arg *InputArg) {
3718
174k
    if (!IsValid)
3719
9
      return true;
3720
3721
174k
    recordHostAction(HostAction, InputArg);
3722
3723
    // If we are supporting bundling/unbundling and the current action is an
3724
    // input action of non-source file, we replace the host action by the
3725
    // unbundling action. The bundler tool has the logic to detect if an input
3726
    // is a bundle or not and if the input is not a bundle it assumes it is a
3727
    // host file. Therefore it is safe to create an unbundling action even if
3728
    // the input is not a bundle.
3729
174k
    if (CanUseBundler && 
isa<InputAction>(HostAction)1.65k
&&
3730
174k
        
InputArg->getOption().getKind() == llvm::opt::Option::InputClass437
&&
3731
174k
        
(421
!types::isSrcFile(HostAction->getType())421
||
3732
421
         
HostAction->getType() == types::TY_PP_HIP367
)) {
3733
54
      auto UnbundlingHostAction =
3734
54
          C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
3735
54
      UnbundlingHostAction->registerDependentActionInfo(
3736
54
          C.getSingleOffloadToolChain<Action::OFK_Host>(),
3737
54
          /*BoundArch=*/StringRef(), Action::OFK_Host);
3738
54
      HostAction = UnbundlingHostAction;
3739
54
      recordHostAction(HostAction, InputArg);
3740
54
    }
3741
3742
174k
    assert(HostAction && "Invalid host action!");
3743
3744
    // Register the offload kinds that are used.
3745
174k
    auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3746
349k
    for (auto *SB : SpecializedBuilders) {
3747
349k
      if (!SB->isValid())
3748
347k
        continue;
3749
3750
1.97k
      auto RetCode = SB->addDeviceDependences(HostAction);
3751
3752
      // Host dependences for device actions are not compatible with that same
3753
      // action being ignored.
3754
1.97k
      assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
3755
1.97k
             "Host dependence not expected to be ignored.!");
3756
3757
      // Unless the builder was inactive for this action, we have to record the
3758
      // offload kind because the host will have to use it.
3759
1.97k
      if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3760
1.90k
        OffloadKind |= SB->getAssociatedOffloadKind();
3761
1.97k
    }
3762
3763
    // Do not use unbundler if the Host does not depend on device action.
3764
174k
    if (OffloadKind == Action::OFK_None && 
CanUseBundler172k
)
3765
73
      if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3766
17
        HostAction = UA->getInputs().back();
3767
3768
174k
    return false;
3769
174k
  }
3770
3771
  /// Add the offloading top level actions to the provided action list. This
3772
  /// function can replace the host action by a bundling action if the
3773
  /// programming models allow it.
3774
  bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3775
56.7k
                             const Arg *InputArg) {
3776
56.7k
    if (HostAction)
3777
43.0k
      recordHostAction(HostAction, InputArg);
3778
3779
    // Get the device actions to be appended.
3780
56.7k
    ActionList OffloadAL;
3781
113k
    for (auto *SB : SpecializedBuilders) {
3782
113k
      if (!SB->isValid())
3783
112k
        continue;
3784
531
      SB->appendTopLevelActions(OffloadAL);
3785
531
    }
3786
3787
    // If we can use the bundler, replace the host action by the bundling one in
3788
    // the resulting list. Otherwise, just append the device actions. For
3789
    // device only compilation, HostAction is a null pointer, therefore only do
3790
    // this when HostAction is not a null pointer.
3791
56.7k
    if (CanUseBundler && 
HostAction437
&&
3792
56.7k
        
HostAction->getType() != types::TY_Nothing80
&&
!OffloadAL.empty()78
) {
3793
      // Add the host action to the list in order to create the bundling action.
3794
21
      OffloadAL.push_back(HostAction);
3795
3796
      // We expect that the host action was just appended to the action list
3797
      // before this method was called.
3798
21
      assert(HostAction == AL.back() && "Host action not in the list??");
3799
21
      HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3800
21
      recordHostAction(HostAction, InputArg);
3801
21
      AL.back() = HostAction;
3802
21
    } else
3803
56.7k
      AL.append(OffloadAL.begin(), OffloadAL.end());
3804
3805
    // Propagate to the current host action (if any) the offload information
3806
    // associated with the current input.
3807
56.7k
    if (HostAction)
3808
43.0k
      HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3809
43.0k
                                           /*BoundArch=*/nullptr);
3810
56.7k
    return false;
3811
56.7k
  }
3812
3813
7.41k
  void appendDeviceLinkActions(ActionList &AL) {
3814
14.8k
    for (DeviceActionBuilder *SB : SpecializedBuilders) {
3815
14.8k
      if (!SB->isValid())
3816
14.5k
        continue;
3817
243
      SB->appendLinkDeviceActions(AL);
3818
243
    }
3819
7.41k
  }
3820
3821
7.29k
  Action *makeHostLinkAction() {
3822
    // Build a list of device linking actions.
3823
7.29k
    ActionList DeviceAL;
3824
7.29k
    appendDeviceLinkActions(DeviceAL);
3825
7.29k
    if (DeviceAL.empty())
3826
7.23k
      return nullptr;
3827
3828
    // Let builders add host linking actions.
3829
54
    Action* HA = nullptr;
3830
108
    for (DeviceActionBuilder *SB : SpecializedBuilders) {
3831
108
      if (!SB->isValid())
3832
54
        continue;
3833
54
      HA = SB->appendLinkHostActions(DeviceAL);
3834
      // This created host action has no originating input argument, therefore
3835
      // needs to set its offloading kind directly.
3836
54
      if (HA)
3837
54
        HA->propagateHostOffloadInfo(SB->getAssociatedOffloadKind(),
3838
54
                                     /*BoundArch=*/nullptr);
3839
54
    }
3840
54
    return HA;
3841
7.29k
  }
3842
3843
  /// Processes the host linker action. This currently consists of replacing it
3844
  /// with an offload action if there are device link objects and propagate to
3845
  /// the host action all the offload kinds used in the current compilation. The
3846
  /// resulting action is returned.
3847
7.29k
  Action *processHostLinkAction(Action *HostAction) {
3848
    // Add all the dependences from the device linking actions.
3849
7.29k
    OffloadAction::DeviceDependences DDeps;
3850
14.5k
    for (auto *SB : SpecializedBuilders) {
3851
14.5k
      if (!SB->isValid())
3852
14.3k
        continue;
3853
3854
212
      SB->appendLinkDependences(DDeps);
3855
212
    }
3856
3857
    // Calculate all the offload kinds used in the current compilation.
3858
7.29k
    unsigned ActiveOffloadKinds = 0u;
3859
7.29k
    for (auto &I : InputArgToOffloadKindMap)
3860
13.5k
      ActiveOffloadKinds |= I.second;
3861
3862
    // If we don't have device dependencies, we don't have to create an offload
3863
    // action.
3864
7.29k
    if (DDeps.getActions().empty()) {
3865
      // Set all the active offloading kinds to the link action. Given that it
3866
      // is a link action it is assumed to depend on all actions generated so
3867
      // far.
3868
7.29k
      HostAction->setHostOffloadInfo(ActiveOffloadKinds,
3869
7.29k
                                     /*BoundArch=*/nullptr);
3870
      // Propagate active offloading kinds for each input to the link action.
3871
      // Each input may have different active offloading kind.
3872
13.6k
      for (auto *A : HostAction->inputs()) {
3873
13.6k
        auto ArgLoc = HostActionToInputArgMap.find(A);
3874
13.6k
        if (ArgLoc == HostActionToInputArgMap.end())
3875
54
          continue;
3876
13.5k
        auto OFKLoc = InputArgToOffloadKindMap.find(ArgLoc->second);
3877
13.5k
        if (OFKLoc == InputArgToOffloadKindMap.end())
3878
0
          continue;
3879
13.5k
        A->propagateHostOffloadInfo(OFKLoc->second, /*BoundArch=*/nullptr);
3880
13.5k
      }
3881
7.29k
      return HostAction;
3882
7.29k
    }
3883
3884
    // Create the offload action with all dependences. When an offload action
3885
    // is created the kinds are propagated to the host action, so we don't have
3886
    // to do that explicitly here.
3887
0
    OffloadAction::HostDependence HDep(
3888
0
        *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3889
0
        /*BoundArch*/ nullptr, ActiveOffloadKinds);
3890
0
    return C.MakeAction<OffloadAction>(HDep, DDeps);
3891
7.29k
  }
3892
};
3893
} // anonymous namespace.
3894
3895
void Driver::handleArguments(Compilation &C, DerivedArgList &Args,
3896
                             const InputList &Inputs,
3897
50.4k
                             ActionList &Actions) const {
3898
3899
  // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
3900
50.4k
  Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3901
50.4k
  Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
3902
50.4k
  if (YcArg && 
YuArg28
&&
strcmp(YcArg->getValue(), YuArg->getValue()) != 04
) {
3903
1
    Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3904
1
    Args.eraseArg(options::OPT__SLASH_Yc);
3905
1
    Args.eraseArg(options::OPT__SLASH_Yu);
3906
1
    YcArg = YuArg = nullptr;
3907
1
  }
3908
50.4k
  if (YcArg && 
Inputs.size() > 127
) {
3909
1
    Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3910
1
    Args.eraseArg(options::OPT__SLASH_Yc);
3911
1
    YcArg = nullptr;
3912
1
  }
3913
3914
50.4k
  Arg *FinalPhaseArg;
3915
50.4k
  phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
3916
3917
50.4k
  if (FinalPhase == phases::Link) {
3918
    // Emitting LLVM while linking disabled except in HIPAMD Toolchain
3919
7.41k
    if (Args.hasArg(options::OPT_emit_llvm) && 
!Args.hasArg(options::OPT_hip_link)7
)
3920
4
      Diag(clang::diag::err_drv_emit_llvm_link);
3921
7.41k
    if (IsCLMode() && 
LTOMode != LTOK_None365
&&
3922
7.41k
        !Args.getLastArgValue(options::OPT_fuse_ld_EQ)
3923
5
             .equals_insensitive("lld"))
3924
4
      Diag(clang::diag::err_drv_lto_without_lld);
3925
3926
    // If -dumpdir is not specified, give a default prefix derived from the link
3927
    // output filename. For example, `clang -g -gsplit-dwarf a.c -o x` passes
3928
    // `-dumpdir x-` to cc1. If -o is unspecified, use
3929
    // stem(getDefaultImageName()) (usually stem("a.out") = "a").
3930
7.41k
    if (!Args.hasArg(options::OPT_dumpdir)) {
3931
7.40k
      Arg *FinalOutput = Args.getLastArg(options::OPT_o, options::OPT__SLASH_o);
3932
7.40k
      Arg *Arg = Args.MakeSeparateArg(
3933
7.40k
          nullptr, getOpts().getOption(options::OPT_dumpdir),
3934
7.40k
          Args.MakeArgString(
3935
7.40k
              (FinalOutput ? 
FinalOutput->getValue()3.14k
3936
7.40k
                           : 
llvm::sys::path::stem(getDefaultImageName())4.26k
) +
3937
7.40k
              "-"));
3938
7.40k
      Arg->claim();
3939
7.40k
      Args.append(Arg);
3940
7.40k
    }
3941
7.41k
  }
3942
3943
50.4k
  if (FinalPhase == phases::Preprocess || 
Args.hasArg(options::OPT__SLASH_Y_)48.6k
) {
3944
    // If only preprocessing or /Y- is used, all pch handling is disabled.
3945
    // Rather than check for it everywhere, just remove clang-cl pch-related
3946
    // flags here.
3947
1.88k
    Args.eraseArg(options::OPT__SLASH_Fp);
3948
1.88k
    Args.eraseArg(options::OPT__SLASH_Yc);
3949
1.88k
    Args.eraseArg(options::OPT__SLASH_Yu);
3950
1.88k
    YcArg = YuArg = nullptr;
3951
1.88k
  }
3952
3953
50.4k
  unsigned LastPLSize = 0;
3954
56.8k
  for (auto &I : Inputs) {
3955
56.8k
    types::ID InputType = I.first;
3956
56.8k
    const Arg *InputArg = I.second;
3957
3958
56.8k
    auto PL = types::getCompilationPhases(InputType);
3959
56.8k
    LastPLSize = PL.size();
3960
3961
    // If the first step comes after the final phase we are doing as part of
3962
    // this compilation, warn the user about it.
3963
56.8k
    phases::ID InitialPhase = PL[0];
3964
56.8k
    if (InitialPhase > FinalPhase) {
3965
60
      if (InputArg->isClaimed())
3966
2
        continue;
3967
3968
      // Claim here to avoid the more general unused warning.
3969
58
      InputArg->claim();
3970
3971
      // Suppress all unused style warnings with -Qunused-arguments
3972
58
      if (Args.hasArg(options::OPT_Qunused_arguments))
3973
1
        continue;
3974
3975
      // Special case when final phase determined by binary name, rather than
3976
      // by a command-line argument with a corresponding Arg.
3977
57
      if (CCCIsCPP())
3978
1
        Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
3979
1
            << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
3980
      // Special case '-E' warning on a previously preprocessed file to make
3981
      // more sense.
3982
56
      else if (InitialPhase == phases::Compile &&
3983
56
               
(0
Args.getLastArg(options::OPT__SLASH_EP,
3984
0
                                options::OPT__SLASH_P) ||
3985
0
                Args.getLastArg(options::OPT_E) ||
3986
0
                Args.getLastArg(options::OPT_M, options::OPT_MM)) &&
3987
56
               
getPreprocessedType(InputType) == types::TY_INVALID0
)
3988
0
        Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
3989
0
            << InputArg->getAsString(Args) << !!FinalPhaseArg
3990
0
            << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3991
56
      else
3992
56
        Diag(clang::diag::warn_drv_input_file_unused)
3993
56
            << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3994
56
            << !!FinalPhaseArg
3995
56
            << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : 
""0
);
3996
57
      continue;
3997
58
    }
3998
3999
56.7k
    if (YcArg) {
4000
      // Add a separate precompile phase for the compile phase.
4001
18
      if (FinalPhase >= phases::Compile) {
4002
18
        const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
4003
        // Build the pipeline for the pch file.
4004
18
        Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType);
4005
18
        for (phases::ID Phase : types::getCompilationPhases(HeaderType))
4006
36
          ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
4007
18
        assert(ClangClPch);
4008
18
        Actions.push_back(ClangClPch);
4009
        // The driver currently exits after the first failed command.  This
4010
        // relies on that behavior, to make sure if the pch generation fails,
4011
        // the main compilation won't run.
4012
        // FIXME: If the main compilation fails, the PCH generation should
4013
        // probably not be considered successful either.
4014
18
      }
4015
18
    }
4016
56.7k
  }
4017
4018
  // If we are linking, claim any options which are obviously only used for
4019
  // compilation.
4020
  // FIXME: Understand why the last Phase List length is used here.
4021
50.4k
  if (FinalPhase == phases::Link && 
LastPLSize == 17.41k
) {
4022
2.77k
    Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
4023
2.77k
    Args.ClaimAllArgs(options::OPT_cl_compile_Group);
4024
2.77k
  }
4025
50.4k
}
4026
4027
void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
4028
50.5k
                          const InputList &Inputs, ActionList &Actions) const {
4029
50.5k
  llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
4030
4031
50.5k
  if (!SuppressMissingInputWarning && 
Inputs.empty()40.3k
) {
4032
29
    Diag(clang::diag::err_drv_no_input_files);
4033
29
    return;
4034
29
  }
4035
4036
  // Diagnose misuse of /Fo.
4037
50.4k
  if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
4038
59
    StringRef V = A->getValue();
4039
59
    if (Inputs.size() > 1 && 
!V.empty()4
&&
4040
59
        
!llvm::sys::path::is_separator(V.back())3
) {
4041
      // Check whether /Fo tries to name an output file for multiple inputs.
4042
1
      Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
4043
1
          << A->getSpelling() << V;
4044
1
      Args.eraseArg(options::OPT__SLASH_Fo);
4045
1
    }
4046
59
  }
4047
4048
  // Diagnose misuse of /Fa.
4049
50.4k
  if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
4050
19
    StringRef V = A->getValue();
4051
19
    if (Inputs.size() > 1 && 
!V.empty()4
&&
4052
19
        
!llvm::sys::path::is_separator(V.back())2
) {
4053
      // Check whether /Fa tries to name an asm file for multiple inputs.
4054
2
      Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
4055
2
          << A->getSpelling() << V;
4056
2
      Args.eraseArg(options::OPT__SLASH_Fa);
4057
2
    }
4058
19
  }
4059
4060
  // Diagnose misuse of /o.
4061
50.4k
  if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
4062
74
    if (A->getValue()[0] == '\0') {
4063
      // It has to have a value.
4064
0
      Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
4065
0
      Args.eraseArg(options::OPT__SLASH_o);
4066
0
    }
4067
74
  }
4068
4069
50.4k
  handleArguments(C, Args, Inputs, Actions);
4070
4071
50.4k
  bool UseNewOffloadingDriver =
4072
50.4k
      C.isOffloadingHostKind(Action::OFK_OpenMP) ||
4073
50.4k
      Args.hasFlag(options::OPT_offload_new_driver,
4074
50.4k
                   options::OPT_no_offload_new_driver, false);
4075
4076
  // Builder to be used to build offloading actions.
4077
50.4k
  std::unique_ptr<OffloadingActionBuilder> OffloadBuilder =
4078
50.4k
      !UseNewOffloadingDriver
4079
50.4k
          ? 
std::make_unique<OffloadingActionBuilder>(C, Args, Inputs)50.4k
4080
50.4k
          : 
nullptr22
;
4081
4082
  // Construct the actions to perform.
4083
50.4k
  ExtractAPIJobAction *ExtractAPIAction = nullptr;
4084
50.4k
  ActionList LinkerInputs;
4085
50.4k
  ActionList MergerInputs;
4086
4087
56.8k
  for (auto &I : Inputs) {
4088
56.8k
    types::ID InputType = I.first;
4089
56.8k
    const Arg *InputArg = I.second;
4090
4091
56.8k
    auto PL = types::getCompilationPhases(*this, Args, InputType);
4092
56.8k
    if (PL.empty())
4093
60
      continue;
4094
4095
56.7k
    auto FullPL = types::getCompilationPhases(InputType);
4096
4097
    // Build the pipeline for this file.
4098
56.7k
    Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
4099
4100
    // Use the current host action in any of the offloading actions, if
4101
    // required.
4102
56.7k
    if (!UseNewOffloadingDriver)
4103
56.7k
      if (OffloadBuilder->addHostDependenceToDeviceActions(Current, InputArg))
4104
9
        break;
4105
4106
132k
    
for (phases::ID Phase : PL)56.7k
{
4107
4108
      // Add any offload action the host action depends on.
4109
132k
      if (!UseNewOffloadingDriver)
4110
132k
        Current = OffloadBuilder->addDeviceDependencesToHostAction(
4111
132k
            Current, InputArg, Phase, PL.back(), FullPL);
4112
132k
      if (!Current)
4113
132
        break;
4114
4115
      // Queue linker inputs.
4116
132k
      if (Phase == phases::Link) {
4117
13.5k
        assert(Phase == PL.back() && "linking must be final compilation step.");
4118
        // We don't need to generate additional link commands if emitting AMD
4119
        // bitcode or compiling only for the offload device
4120
13.5k
        if (!(C.getInputArgs().hasArg(options::OPT_hip_link) &&
4121
13.5k
              
(C.getInputArgs().hasArg(options::OPT_emit_llvm))41
) &&
4122
13.5k
            
!offloadDeviceOnly()13.5k
)
4123
13.5k
          LinkerInputs.push_back(Current);
4124
13.5k
        Current = nullptr;
4125
13.5k
        break;
4126
13.5k
      }
4127
4128
      // TODO: Consider removing this because the merged may not end up being
4129
      // the final Phase in the pipeline. Perhaps the merged could just merge
4130
      // and then pass an artifact of some sort to the Link Phase.
4131
      // Queue merger inputs.
4132
118k
      if (Phase == phases::IfsMerge) {
4133
10
        assert(Phase == PL.back() && "merging must be final compilation step.");
4134
10
        MergerInputs.push_back(Current);
4135
10
        Current = nullptr;
4136
10
        break;
4137
10
      }
4138
4139
118k
      if (Phase == phases::Precompile && 
ExtractAPIAction126
) {
4140
5
        ExtractAPIAction->addHeaderInput(Current);
4141
5
        Current = nullptr;
4142
5
        break;
4143
5
      }
4144
4145
      // FIXME: Should we include any prior module file outputs as inputs of
4146
      // later actions in the same command line?
4147
4148
      // Otherwise construct the appropriate action.
4149
118k
      Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
4150
4151
      // We didn't create a new action, so we will just move to the next phase.
4152
118k
      if (NewCurrent == Current)
4153
270
        continue;
4154
4155
118k
      if (auto *EAA = dyn_cast<ExtractAPIJobAction>(NewCurrent))
4156
22
        ExtractAPIAction = EAA;
4157
4158
118k
      Current = NewCurrent;
4159
4160
      // Try to build the offloading actions and add the result as a dependency
4161
      // to the host.
4162
118k
      if (UseNewOffloadingDriver)
4163
85
        Current = BuildOffloadingActions(C, Args, I, Current);
4164
      // Use the current host action in any of the offloading actions, if
4165
      // required.
4166
118k
      else if (OffloadBuilder->addHostDependenceToDeviceActions(Current,
4167
118k
                                                                InputArg))
4168
0
        break;
4169
4170
118k
      if (Current->getType() == types::TY_Nothing)
4171
31.9k
        break;
4172
118k
    }
4173
4174
    // If we ended with something, add to the output list.
4175
56.7k
    if (Current)
4176
43.0k
      Actions.push_back(Current);
4177
4178
    // Add any top level actions generated for offloading.
4179
56.7k
    if (!UseNewOffloadingDriver)
4180
56.7k
      OffloadBuilder->appendTopLevelActions(Actions, Current, InputArg);
4181
10
    else if (Current)
4182
10
      Current->propagateHostOffloadInfo(C.getActiveOffloadKinds(),
4183
10
                                        /*BoundArch=*/nullptr);
4184
56.7k
  }
4185
4186
  // Add a link action if necessary.
4187
4188
50.4k
  if (LinkerInputs.empty()) {
4189
43.1k
    Arg *FinalPhaseArg;
4190
43.1k
    if (getFinalPhase(Args, &FinalPhaseArg) == phases::Link)
4191
122
      if (!UseNewOffloadingDriver)
4192
122
        OffloadBuilder->appendDeviceLinkActions(Actions);
4193
43.1k
  }
4194
4195
50.4k
  if (!LinkerInputs.empty()) {
4196
7.30k
    if (!UseNewOffloadingDriver)
4197
7.29k
      if (Action *Wrapper = OffloadBuilder->makeHostLinkAction())
4198
54
        LinkerInputs.push_back(Wrapper);
4199
7.30k
    Action *LA;
4200
    // Check if this Linker Job should emit a static library.
4201
7.30k
    if (ShouldEmitStaticLibrary(Args)) {
4202
12
      LA = C.MakeAction<StaticLibJobAction>(LinkerInputs, types::TY_Image);
4203
7.29k
    } else if (UseNewOffloadingDriver ||
4204
7.29k
               
Args.hasArg(options::OPT_offload_link)7.27k
) {
4205
13
      LA = C.MakeAction<LinkerWrapperJobAction>(LinkerInputs, types::TY_Image);
4206
13
      LA->propagateHostOffloadInfo(C.getActiveOffloadKinds(),
4207
13
                                   /*BoundArch=*/nullptr);
4208
7.27k
    } else {
4209
7.27k
      LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
4210
7.27k
    }
4211
7.30k
    if (!UseNewOffloadingDriver)
4212
7.29k
      LA = OffloadBuilder->processHostLinkAction(LA);
4213
7.30k
    Actions.push_back(LA);
4214
7.30k
  }
4215
4216
  // Add an interface stubs merge action if necessary.
4217
50.4k
  if (!MergerInputs.empty())
4218
6
    Actions.push_back(
4219
6
        C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
4220
4221
50.4k
  if (Args.hasArg(options::OPT_emit_interface_stubs)) {
4222
25
    auto PhaseList = types::getCompilationPhases(
4223
25
        types::TY_IFS_CPP,
4224
25
        Args.hasArg(options::OPT_c) ? 
phases::Compile2
:
phases::IfsMerge23
);
4225
4226
25
    ActionList MergerInputs;
4227
4228
40
    for (auto &I : Inputs) {
4229
40
      types::ID InputType = I.first;
4230
40
      const Arg *InputArg = I.second;
4231
4232
      // Currently clang and the llvm assembler do not support generating symbol
4233
      // stubs from assembly, so we skip the input on asm files. For ifs files
4234
      // we rely on the normal pipeline setup in the pipeline setup code above.
4235
40
      if (InputType == types::TY_IFS || 
InputType == types::TY_PP_Asm30
||
4236
40
          
InputType == types::TY_Asm30
)
4237
10
        continue;
4238
4239
30
      Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
4240
4241
56
      for (auto Phase : PhaseList) {
4242
56
        switch (Phase) {
4243
0
        default:
4244
0
          llvm_unreachable(
4245
0
              "IFS Pipeline can only consist of Compile followed by IfsMerge.");
4246
30
        case phases::Compile: {
4247
          // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs
4248
          // files where the .o file is located. The compile action can not
4249
          // handle this.
4250
30
          if (InputType == types::TY_Object)
4251
4
            break;
4252
4253
26
          Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP);
4254
26
          break;
4255
30
        }
4256
26
        case phases::IfsMerge: {
4257
26
          assert(Phase == PhaseList.back() &&
4258
26
                 "merging must be final compilation step.");
4259
26
          MergerInputs.push_back(Current);
4260
26
          Current = nullptr;
4261
26
          break;
4262
26
        }
4263
56
        }
4264
56
      }
4265
4266
      // If we ended with something, add to the output list.
4267
30
      if (Current)
4268
4
        Actions.push_back(Current);
4269
30
    }
4270
4271
    // Add an interface stubs merge action if necessary.
4272
25
    if (!MergerInputs.empty())
4273
17
      Actions.push_back(
4274
17
          C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
4275
25
  }
4276
4277
50.4k
  for (auto Opt : {options::OPT_print_supported_cpus,
4278
100k
                   options::OPT_print_supported_extensions}) {
4279
    // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a
4280
    // custom Compile phase that prints out supported cpu models and quits.
4281
    //
4282
    // If --print-supported-extensions is specified, call the helper function
4283
    // RISCVMarchHelp in RISCVISAInfo.cpp that prints out supported extensions
4284
    // and quits.
4285
100k
    if (Arg *A = Args.getLastArg(Opt)) {
4286
7
      if (Opt == options::OPT_print_supported_extensions &&
4287
7
          
!C.getDefaultToolChain().getTriple().isRISCV()3
&&
4288
7
          
!C.getDefaultToolChain().getTriple().isAArch64()3
&&
4289
7
          
!C.getDefaultToolChain().getTriple().isARM()2
) {
4290
1
        C.getDriver().Diag(diag::err_opt_not_valid_on_target)
4291
1
            << "--print-supported-extensions";
4292
1
        return;
4293
1
      }
4294
4295
      // Use the -mcpu=? flag as the dummy input to cc1.
4296
6
      Actions.clear();
4297
6
      Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C);
4298
6
      Actions.push_back(
4299
6
          C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing));
4300
6
      for (auto &I : Inputs)
4301
0
        I.second->claim();
4302
6
    }
4303
100k
  }
4304
4305
  // Call validator for dxil when -Vd not in Args.
4306
50.4k
  if (C.getDefaultToolChain().getTriple().isDXIL()) {
4307
    // Only add action when needValidation.
4308
67
    const auto &TC =
4309
67
        static_cast<const toolchains::HLSLToolChain &>(C.getDefaultToolChain());
4310
67
    if (TC.requiresValidation(Args)) {
4311
3
      Action *LastAction = Actions.back();
4312
3
      Actions.push_back(C.MakeAction<BinaryAnalyzeJobAction>(
4313
3
          LastAction, types::TY_DX_CONTAINER));
4314
3
    }
4315
67
  }
4316
4317
  // Claim ignored clang-cl options.
4318
50.4k
  Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
4319
50.4k
}
4320
4321
/// Returns the canonical name for the offloading architecture when using a HIP
4322
/// or CUDA architecture.
4323
static StringRef getCanonicalArchString(Compilation &C,
4324
                                        const llvm::opt::DerivedArgList &Args,
4325
                                        StringRef ArchStr,
4326
                                        const llvm::Triple &Triple,
4327
34
                                        bool SuppressError = false) {
4328
  // Lookup the CUDA / HIP architecture string. Only report an error if we were
4329
  // expecting the triple to be only NVPTX / AMDGPU.
4330
34
  CudaArch Arch = StringToCudaArch(getProcessorFromTargetID(Triple, ArchStr));
4331
34
  if (!SuppressError && 
Triple.isNVPTX()22
&&
4332
34
      
(0
Arch == CudaArch::UNKNOWN0
||
!IsNVIDIAGpuArch(Arch)0
)) {
4333
0
    C.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch)
4334
0
        << "CUDA" << ArchStr;
4335
0
    return StringRef();
4336
34
  } else if (!SuppressError && 
Triple.isAMDGPU()22
&&
4337
34
             
(22
Arch == CudaArch::UNKNOWN22
||
!IsAMDGpuArch(Arch)22
)) {
4338
0
    C.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch)
4339
0
        << "HIP" << ArchStr;
4340
0
    return StringRef();
4341
0
  }
4342
4343
34
  if (IsNVIDIAGpuArch(Arch))
4344
0
    return Args.MakeArgStringRef(CudaArchToString(Arch));
4345
4346
34
  if (IsAMDGpuArch(Arch)) {
4347
34
    llvm::StringMap<bool> Features;
4348
34
    auto HIPTriple = getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs());
4349
34
    if (!HIPTriple)
4350
0
      return StringRef();
4351
34
    auto Arch = parseTargetID(*HIPTriple, ArchStr, &Features);
4352
34
    if (!Arch) {
4353
0
      C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << ArchStr;
4354
0
      C.setContainsError();
4355
0
      return StringRef();
4356
0
    }
4357
34
    return Args.MakeArgStringRef(getCanonicalTargetID(*Arch, Features));
4358
34
  }
4359
4360
  // If the input isn't CUDA or HIP just return the architecture.
4361
0
  return ArchStr;
4362
34
}
4363
4364
/// Checks if the set offloading architectures does not conflict. Returns the
4365
/// incompatible pair if a conflict occurs.
4366
static std::optional<std::pair<llvm::StringRef, llvm::StringRef>>
4367
getConflictOffloadArchCombination(const llvm::DenseSet<StringRef> &Archs,
4368
28
                                  llvm::Triple Triple) {
4369
28
  if (!Triple.isAMDGPU())
4370
5
    return std::nullopt;
4371
4372
23
  std::set<StringRef> ArchSet;
4373
23
  llvm::copy(Archs, std::inserter(ArchSet, ArchSet.begin()));
4374
23
  return getConflictTargetIDCombination(ArchSet);
4375
28
}
4376
4377
llvm::DenseSet<StringRef>
4378
Driver::getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args,
4379
                        Action::OffloadKind Kind, const ToolChain *TC,
4380
33
                        bool SuppressError) const {
4381
33
  if (!TC)
4382
0
    TC = &C.getDefaultToolChain();
4383
4384
  // --offload and --offload-arch options are mutually exclusive.
4385
33
  if (Args.hasArgNoClaim(options::OPT_offload_EQ) &&
4386
33
      Args.hasArgNoClaim(options::OPT_offload_arch_EQ,
4387
0
                         options::OPT_no_offload_arch_EQ)) {
4388
0
    C.getDriver().Diag(diag::err_opt_not_valid_with_opt)
4389
0
        << "--offload"
4390
0
        << (Args.hasArgNoClaim(options::OPT_offload_arch_EQ)
4391
0
                ? "--offload-arch"
4392
0
                : "--no-offload-arch");
4393
0
  }
4394
4395
33
  if (KnownArchs.contains(TC))
4396
5
    return KnownArchs.lookup(TC);
4397
4398
28
  llvm::DenseSet<StringRef> Archs;
4399
279
  for (auto *Arg : Args) {
4400
    // Extract any '--[no-]offload-arch' arguments intended for this toolchain.
4401
279
    std::unique_ptr<llvm::opt::Arg> ExtractedArg = nullptr;
4402
279
    if (Arg->getOption().matches(options::OPT_Xopenmp_target_EQ) &&
4403
279
        
ToolChain::getOpenMPTriple(Arg->getValue(0)) == TC->getTriple()5
) {
4404
5
      Arg->claim();
4405
5
      unsigned Index = Args.getBaseArgs().MakeIndex(Arg->getValue(1));
4406
5
      ExtractedArg = getOpts().ParseOneArg(Args, Index);
4407
5
      Arg = ExtractedArg.get();
4408
5
    }
4409
4410
    // Add or remove the seen architectures in order of appearance. If an
4411
    // invalid architecture is given we simply exit.
4412
279
    if (Arg->getOption().matches(options::OPT_offload_arch_EQ)) {
4413
34
      for (StringRef Arch : llvm::split(Arg->getValue(), ",")) {
4414
34
        if (Arch == "native" || Arch.empty()) {
4415
0
          auto GPUsOrErr = TC->getSystemGPUArchs(Args);
4416
0
          if (!GPUsOrErr) {
4417
0
            if (SuppressError)
4418
0
              llvm::consumeError(GPUsOrErr.takeError());
4419
0
            else
4420
0
              TC->getDriver().Diag(diag::err_drv_undetermined_gpu_arch)
4421
0
                  << llvm::Triple::getArchTypeName(TC->getArch())
4422
0
                  << llvm::toString(GPUsOrErr.takeError()) << "--offload-arch";
4423
0
            continue;
4424
0
          }
4425
4426
0
          for (auto ArchStr : *GPUsOrErr) {
4427
0
            Archs.insert(
4428
0
                getCanonicalArchString(C, Args, Args.MakeArgString(ArchStr),
4429
0
                                       TC->getTriple(), SuppressError));
4430
0
          }
4431
34
        } else {
4432
34
          StringRef ArchStr = getCanonicalArchString(
4433
34
              C, Args, Arch, TC->getTriple(), SuppressError);
4434
34
          if (ArchStr.empty())
4435
0
            return Archs;
4436
34
          Archs.insert(ArchStr);
4437
34
        }
4438
34
      }
4439
247
    } else if (Arg->getOption().matches(options::OPT_no_offload_arch_EQ)) {
4440
0
      for (StringRef Arch : llvm::split(Arg->getValue(), ",")) {
4441
0
        if (Arch == "all") {
4442
0
          Archs.clear();
4443
0
        } else {
4444
0
          StringRef ArchStr = getCanonicalArchString(
4445
0
              C, Args, Arch, TC->getTriple(), SuppressError);
4446
0
          if (ArchStr.empty())
4447
0
            return Archs;
4448
0
          Archs.erase(ArchStr);
4449
0
        }
4450
0
      }
4451
0
    }
4452
279
  }
4453
4454
28
  if (auto ConflictingArchs =
4455
28
          getConflictOffloadArchCombination(Archs, TC->getTriple())) {
4456
1
    C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo)
4457
1
        << ConflictingArchs->first << ConflictingArchs->second;
4458
1
    C.setContainsError();
4459
1
  }
4460
4461
  // Skip filling defaults if we're just querying what is availible.
4462
28
  if (SuppressError)
4463
10
    return Archs;
4464
4465
18
  if (Archs.empty()) {
4466
5
    if (Kind == Action::OFK_Cuda)
4467
0
      Archs.insert(CudaArchToString(CudaArch::CudaDefault));
4468
5
    else if (Kind == Action::OFK_HIP)
4469
0
      Archs.insert(CudaArchToString(CudaArch::HIPDefault));
4470
5
    else if (Kind == Action::OFK_OpenMP)
4471
5
      Archs.insert(StringRef());
4472
13
  } else {
4473
13
    Args.ClaimAllArgs(options::OPT_offload_arch_EQ);
4474
13
    Args.ClaimAllArgs(options::OPT_no_offload_arch_EQ);
4475
13
  }
4476
4477
18
  return Archs;
4478
28
}
4479
4480
Action *Driver::BuildOffloadingActions(Compilation &C,
4481
                                       llvm::opt::DerivedArgList &Args,
4482
                                       const InputTy &Input,
4483
85
                                       Action *HostAction) const {
4484
  // Don't build offloading actions if explicitly disabled or we do not have a
4485
  // valid source input and compile action to embed it in. If preprocessing only
4486
  // ignore embedding.
4487
85
  if (offloadHostOnly() || !types::isSrcFile(Input.first) ||
4488
85
      !(isa<CompileJobAction>(HostAction) ||
4489
85
        
getFinalPhase(Args) == phases::Preprocess62
))
4490
62
    return HostAction;
4491
4492
23
  ActionList OffloadActions;
4493
23
  OffloadAction::DeviceDependences DDeps;
4494
4495
23
  const Action::OffloadKind OffloadKinds[] = {
4496
23
      Action::OFK_OpenMP, Action::OFK_Cuda, Action::OFK_HIP};
4497
4498
69
  for (Action::OffloadKind Kind : OffloadKinds) {
4499
69
    SmallVector<const ToolChain *, 2> ToolChains;
4500
69
    ActionList DeviceActions;
4501
4502
69
    auto TCRange = C.getOffloadToolChains(Kind);
4503
92
    for (auto TI = TCRange.first, TE = TCRange.second; TI != TE; 
++TI23
)
4504
23
      ToolChains.push_back(TI->second);
4505
4506
69
    if (ToolChains.empty())
4507
46
      continue;
4508
4509
23
    types::ID InputType = Input.first;
4510
23
    const Arg *InputArg = Input.second;
4511
4512
    // The toolchain can be active for unsupported file types.
4513
23
    if ((Kind == Action::OFK_Cuda && 
!types::isCuda(InputType)0
) ||
4514
23
        (Kind == Action::OFK_HIP && 
!types::isHIP(InputType)10
))
4515
0
      continue;
4516
4517
    // Get the product of all bound architectures and toolchains.
4518
23
    SmallVector<std::pair<const ToolChain *, StringRef>> TCAndArchs;
4519
23
    for (const ToolChain *TC : ToolChains)
4520
23
      for (StringRef Arch : getOffloadArchs(C, Args, Kind, TC))
4521
33
        TCAndArchs.push_back(std::make_pair(TC, Arch));
4522
4523
56
    for (unsigned I = 0, E = TCAndArchs.size(); I != E; 
++I33
)
4524
33
      DeviceActions.push_back(C.MakeAction<InputAction>(*InputArg, InputType));
4525
4526
23
    if (DeviceActions.empty())
4527
0
      return HostAction;
4528
4529
23
    auto PL = types::getCompilationPhases(*this, Args, InputType);
4530
4531
102
    for (phases::ID Phase : PL) {
4532
102
      if (Phase == phases::Link) {
4533
13
        assert(Phase == PL.back() && "linking must be final compilation step.");
4534
13
        break;
4535
13
      }
4536
4537
89
      auto TCAndArch = TCAndArchs.begin();
4538
127
      for (Action *&A : DeviceActions) {
4539
127
        if (A->getType() == types::TY_Nothing)
4540
0
          continue;
4541
4542
        // Propagate the ToolChain so we can use it in ConstructPhaseAction.
4543
127
        A->propagateDeviceOffloadInfo(Kind, TCAndArch->second.data(),
4544
127
                                      TCAndArch->first);
4545
127
        A = ConstructPhaseAction(C, Args, Phase, A, Kind);
4546
4547
127
        if (isa<CompileJobAction>(A) && 
isa<CompileJobAction>(HostAction)33
&&
4548
127
            
Kind == Action::OFK_OpenMP33
&&
4549
127
            
HostAction->getType() != types::TY_Nothing14
) {
4550
          // OpenMP offloading has a dependency on the host compile action to
4551
          // identify which declarations need to be emitted. This shouldn't be
4552
          // collapsed with any other actions so we can use it in the device.
4553
14
          HostAction->setCannotBeCollapsedWithNextDependentAction();
4554
14
          OffloadAction::HostDependence HDep(
4555
14
              *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4556
14
              TCAndArch->second.data(), Kind);
4557
14
          OffloadAction::DeviceDependences DDep;
4558
14
          DDep.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4559
14
          A = C.MakeAction<OffloadAction>(HDep, DDep);
4560
14
        }
4561
4562
127
        ++TCAndArch;
4563
127
      }
4564
89
    }
4565
4566
    // Compiling HIP in non-RDC mode requires linking each action individually.
4567
33
    
for (Action *&A : DeviceActions)23
{
4568
33
      if ((A->getType() != types::TY_Object &&
4569
33
           
A->getType() != types::TY_LTO_BC22
) ||
4570
33
          
Kind != Action::OFK_HIP15
||
4571
33
          
Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)15
)
4572
20
        continue;
4573
13
      ActionList LinkerInput = {A};
4574
13
      A = C.MakeAction<LinkJobAction>(LinkerInput, types::TY_Image);
4575
13
    }
4576
4577
23
    auto TCAndArch = TCAndArchs.begin();
4578
33
    for (Action *A : DeviceActions) {
4579
33
      DDeps.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4580
33
      OffloadAction::DeviceDependences DDep;
4581
33
      DDep.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4582
33
      OffloadActions.push_back(C.MakeAction<OffloadAction>(DDep, A->getType()));
4583
33
      ++TCAndArch;
4584
33
    }
4585
23
  }
4586
4587
23
  if (offloadDeviceOnly())
4588
2
    return C.MakeAction<OffloadAction>(DDeps, types::TY_Nothing);
4589
4590
21
  if (OffloadActions.empty())
4591
0
    return HostAction;
4592
4593
21
  OffloadAction::DeviceDependences DDep;
4594
21
  if (C.isOffloadingHostKind(Action::OFK_Cuda) &&
4595
21
      
!Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)0
) {
4596
    // If we are not in RDC-mode we just emit the final CUDA fatbinary for
4597
    // each translation unit without requiring any linking.
4598
0
    Action *FatbinAction =
4599
0
        C.MakeAction<LinkJobAction>(OffloadActions, types::TY_CUDA_FATBIN);
4600
0
    DDep.add(*FatbinAction, *C.getSingleOffloadToolChain<Action::OFK_Cuda>(),
4601
0
             nullptr, Action::OFK_Cuda);
4602
21
  } else if (C.isOffloadingHostKind(Action::OFK_HIP) &&
4603
21
             !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4604
8
                           false)) {
4605
    // If we are not in RDC-mode we just emit the final HIP fatbinary for each
4606
    // translation unit, linking each input individually.
4607
6
    Action *FatbinAction =
4608
6
        C.MakeAction<LinkJobAction>(OffloadActions, types::TY_HIP_FATBIN);
4609
6
    DDep.add(*FatbinAction, *C.getSingleOffloadToolChain<Action::OFK_HIP>(),
4610
6
             nullptr, Action::OFK_HIP);
4611
15
  } else {
4612
    // Package all the offloading actions into a single output that can be
4613
    // embedded in the host and linked.
4614
15
    Action *PackagerAction =
4615
15
        C.MakeAction<OffloadPackagerJobAction>(OffloadActions, types::TY_Image);
4616
15
    DDep.add(*PackagerAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4617
15
             nullptr, C.getActiveOffloadKinds());
4618
15
  }
4619
4620
  // If we are unable to embed a single device output into the host, we need to
4621
  // add each device output as a host dependency to ensure they are still built.
4622
28
  bool SingleDeviceOutput = 
!llvm::any_of(OffloadActions, [](Action *A) 21
{
4623
28
    return A->getType() == types::TY_Nothing;
4624
28
  }) && 
isa<CompileJobAction>(HostAction)20
;
4625
21
  OffloadAction::HostDependence HDep(
4626
21
      *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4627
21
      /*BoundArch=*/nullptr, SingleDeviceOutput ? 
DDep20
:
DDeps1
);
4628
21
  return C.MakeAction<OffloadAction>(HDep, SingleDeviceOutput ? 
DDep20
:
DDeps1
);
4629
21
}
4630
4631
Action *Driver::ConstructPhaseAction(
4632
    Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
4633
120k
    Action::OffloadKind TargetDeviceOffloadKind) const {
4634
120k
  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
4635
4636
  // Some types skip the assembler phase (e.g., llvm-bc), but we can't
4637
  // encode this in the steps because the intermediate type depends on
4638
  // arguments. Just special case here.
4639
120k
  if (Phase == phases::Assemble && 
Input->getType() != types::TY_PP_Asm12.7k
)
4640
418
    return Input;
4641
4642
  // Build the appropriate action.
4643
120k
  switch (Phase) {
4644
0
  case phases::Link:
4645
0
    llvm_unreachable("link action invalid here.");
4646
0
  case phases::IfsMerge:
4647
0
    llvm_unreachable("ifsmerge action invalid here.");
4648
47.9k
  case phases::Preprocess: {
4649
47.9k
    types::ID OutputTy;
4650
    // -M and -MM specify the dependency file name by altering the output type,
4651
    // -if -MD and -MMD are not specified.
4652
47.9k
    if (Args.hasArg(options::OPT_M, options::OPT_MM) &&
4653
47.9k
        
!Args.hasArg(options::OPT_MD, options::OPT_MMD)15
) {
4654
14
      OutputTy = types::TY_Dependencies;
4655
47.9k
    } else {
4656
47.9k
      OutputTy = Input->getType();
4657
      // For these cases, the preprocessor is only translating forms, the Output
4658
      // still needs preprocessing.
4659
47.9k
      if (!Args.hasFlag(options::OPT_frewrite_includes,
4660
47.9k
                        options::OPT_fno_rewrite_includes, false) &&
4661
47.9k
          !Args.hasFlag(options::OPT_frewrite_imports,
4662
47.9k
                        options::OPT_fno_rewrite_imports, false) &&
4663
47.9k
          !Args.hasFlag(options::OPT_fdirectives_only,
4664
47.9k
                        options::OPT_fno_directives_only, false) &&
4665
47.9k
          !CCGenDiagnostics)
4666
47.8k
        OutputTy = types::getPreprocessedType(OutputTy);
4667
47.9k
      assert(OutputTy != types::TY_INVALID &&
4668
47.9k
             "Cannot preprocess this input type!");
4669
47.9k
    }
4670
47.9k
    return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
4671
47.9k
  }
4672
139
  case phases::Precompile: {
4673
    // API extraction should not generate an actual precompilation action.
4674
139
    if (Args.hasArg(options::OPT_extract_api))
4675
22
      return C.MakeAction<ExtractAPIJobAction>(Input, types::TY_API_INFO);
4676
4677
117
    types::ID OutputTy = getPrecompiledType(Input->getType());
4678
117
    assert(OutputTy != types::TY_INVALID &&
4679
117
           "Cannot precompile this input type!");
4680
4681
    // If we're given a module name, precompile header file inputs as a
4682
    // module, not as a precompiled header.
4683
117
    const char *ModName = nullptr;
4684
117
    if (OutputTy == types::TY_PCH) {
4685
75
      if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
4686
0
        ModName = A->getValue();
4687
75
      if (ModName)
4688
0
        OutputTy = types::TY_ModuleFile;
4689
75
    }
4690
4691
117
    if (Args.hasArg(options::OPT_fsyntax_only)) {
4692
      // Syntax checks should not emit a PCH file
4693
34
      OutputTy = types::TY_Nothing;
4694
34
    }
4695
4696
117
    return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
4697
117
  }
4698
45.9k
  case phases::Compile: {
4699
45.9k
    if (Args.hasArg(options::OPT_fsyntax_only))
4700
31.8k
      return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
4701
14.0k
    if (Args.hasArg(options::OPT_rewrite_objc))
4702
5
      return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
4703
14.0k
    if (Args.hasArg(options::OPT_rewrite_legacy_objc))
4704
3
      return C.MakeAction<CompileJobAction>(Input,
4705
3
                                            types::TY_RewrittenLegacyObjC);
4706
14.0k
    if (Args.hasArg(options::OPT__analyze))
4707
57
      return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
4708
13.9k
    if (Args.hasArg(options::OPT__migrate))
4709
0
      return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
4710
13.9k
    if (Args.hasArg(options::OPT_emit_ast))
4711
17
      return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
4712
13.9k
    if (Args.hasArg(options::OPT_module_file_info))
4713
2
      return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
4714
13.9k
    if (Args.hasArg(options::OPT_verify_pch))
4715
2
      return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
4716
13.9k
    if (Args.hasArg(options::OPT_extract_api))
4717
0
      return C.MakeAction<ExtractAPIJobAction>(Input, types::TY_API_INFO);
4718
13.9k
    return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
4719
13.9k
  }
4720
13.9k
  case phases::Backend: {
4721
13.9k
    if (isUsingLTO() && 
TargetDeviceOffloadKind == Action::OFK_None289
) {
4722
288
      types::ID Output;
4723
288
      if (Args.hasArg(options::OPT_S))
4724
46
        Output = types::TY_LTO_IR;
4725
242
      else if (Args.hasArg(options::OPT_ffat_lto_objects))
4726
2
        Output = types::TY_PP_Asm;
4727
240
      else
4728
240
        Output = types::TY_LTO_BC;
4729
288
      return C.MakeAction<BackendJobAction>(Input, Output);
4730
288
    }
4731
13.6k
    if (isUsingLTO(/* IsOffload */ true) &&
4732
13.6k
        
TargetDeviceOffloadKind != Action::OFK_None9
) {
4733
5
      types::ID Output =
4734
5
          Args.hasArg(options::OPT_S) ? 
types::TY_LTO_IR0
: types::TY_LTO_BC;
4735
5
      return C.MakeAction<BackendJobAction>(Input, Output);
4736
5
    }
4737
13.6k
    if (Args.hasArg(options::OPT_emit_llvm) ||
4738
13.6k
        
(12.8k
(12.8k
(12.8k
Input->getOffloadingToolChain()12.8k
&&
4739
12.8k
           
Input->getOffloadingToolChain()->getTriple().isAMDGPU()281
) ||
4740
12.8k
          
TargetDeviceOffloadKind == Action::OFK_HIP12.6k
) &&
4741
12.8k
         
(617
Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4742
617
                       false) ||
4743
842
          
TargetDeviceOffloadKind == Action::OFK_OpenMP506
))) {
4744
842
      types::ID Output =
4745
842
          Args.hasArg(options::OPT_S) &&
4746
842
                  
(670
TargetDeviceOffloadKind == Action::OFK_None670
||
4747
670
                   
offloadDeviceOnly()18
||
4748
670
                   
(1
TargetDeviceOffloadKind == Action::OFK_HIP1
&&
4749
1
                    !Args.hasFlag(options::OPT_offload_new_driver,
4750
0
                                  options::OPT_no_offload_new_driver, false)))
4751
842
              ? 
types::TY_LLVM_IR669
4752
842
              : 
types::TY_LLVM_BC173
;
4753
842
      return C.MakeAction<BackendJobAction>(Input, Output);
4754
842
    }
4755
12.7k
    return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
4756
13.6k
  }
4757
12.2k
  case phases::Assemble:
4758
12.2k
    return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
4759
120k
  }
4760
4761
0
  llvm_unreachable("invalid phase in ConstructPhaseAction");
4762
0
}
4763
4764
50.4k
void Driver::BuildJobs(Compilation &C) const {
4765
50.4k
  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
4766
4767
50.4k
  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4768
4769
  // It is an error to provide a -o option if we are making multiple output
4770
  // files. There are exceptions:
4771
  //
4772
  // IfsMergeJob: when generating interface stubs enabled we want to be able to
4773
  // generate the stub file at the same time that we generate the real
4774
  // library/a.out. So when a .o, .so, etc are the output, with clang interface
4775
  // stubs there will also be a .ifs and .ifso at the same location.
4776
  //
4777
  // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled
4778
  // and -c is passed, we still want to be able to generate a .ifs file while
4779
  // we are also generating .o files. So we allow more than one output file in
4780
  // this case as well.
4781
  //
4782
  // OffloadClass of type TY_Nothing: device-only output will place many outputs
4783
  // into a single offloading action. We should count all inputs to the action
4784
  // as outputs. Also ignore device-only outputs if we're compiling with
4785
  // -fsyntax-only.
4786
50.4k
  if (FinalOutput) {
4787
8.75k
    unsigned NumOutputs = 0;
4788
8.75k
    unsigned NumIfsOutputs = 0;
4789
8.75k
    for (const Action *A : C.getActions()) {
4790
8.75k
      if (A->getType() != types::TY_Nothing &&
4791
8.75k
          
A->getType() != types::TY_DX_CONTAINER8.72k
&&
4792
8.75k
          
!(8.72k
A->getKind() == Action::IfsMergeJobClass8.72k
||
4793
8.72k
            (A->getType() == clang::driver::types::TY_IFS_CPP &&
4794
8.72k
             
A->getKind() == clang::driver::Action::CompileJobClass1
&&
4795
8.72k
             
0 == NumIfsOutputs++1
) ||
4796
8.72k
            
(8.72k
A->getKind() == Action::BindArchClass8.72k
&&
A->getInputs().size()5.99k
&&
4797
8.72k
             
A->getInputs().front()->getKind() == Action::IfsMergeJobClass5.99k
)))
4798
8.71k
        ++NumOutputs;
4799
37
      else if (A->getKind() == Action::OffloadClass &&
4800
37
               
A->getType() == types::TY_Nothing1
&&
4801
37
               
!C.getArgs().hasArg(options::OPT_fsyntax_only)1
)
4802
1
        NumOutputs += A->size();
4803
8.75k
    }
4804
4805
8.75k
    if (NumOutputs > 1) {
4806
2
      Diag(clang::diag::err_drv_output_argument_with_multiple_files);
4807
2
      FinalOutput = nullptr;
4808
2
    }
4809
8.75k
  }
4810
4811
50.4k
  const llvm::Triple &RawTriple = C.getDefaultToolChain().getTriple();
4812
4813
  // Collect the list of architectures.
4814
50.4k
  llvm::StringSet<> ArchNames;
4815
50.4k
  if (RawTriple.isOSBinFormatMachO())
4816
20.5k
    for (const Arg *A : C.getArgs())
4817
508k
      if (A->getOption().matches(options::OPT_arch))
4818
5.47k
        ArchNames.insert(A->getValue());
4819
4820
  // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
4821
50.4k
  std::map<std::pair<const Action *, std::string>, InputInfoList> CachedResults;
4822
50.4k
  for (Action *A : C.getActions()) {
4823
    // If we are linking an image for multiple archs then the linker wants
4824
    // -arch_multiple and -final_output <final image name>. Unfortunately, this
4825
    // doesn't fit in cleanly because we have to pass this information down.
4826
    //
4827
    // FIXME: This is a hack; find a cleaner way to integrate this into the
4828
    // process.
4829
50.4k
    const char *LinkingOutput = nullptr;
4830
50.4k
    if (isa<LipoJobAction>(A)) {
4831
23
      if (FinalOutput)
4832
8
        LinkingOutput = FinalOutput->getValue();
4833
15
      else
4834
15
        LinkingOutput = getDefaultImageName();
4835
23
    }
4836
4837
50.4k
    BuildJobsForAction(C, A, &C.getDefaultToolChain(),
4838
50.4k
                       /*BoundArch*/ StringRef(),
4839
50.4k
                       /*AtTopLevel*/ true,
4840
50.4k
                       /*MultipleArchs*/ ArchNames.size() > 1,
4841
50.4k
                       /*LinkingOutput*/ LinkingOutput, CachedResults,
4842
50.4k
                       /*TargetDeviceOffloadKind*/ Action::OFK_None);
4843
50.4k
  }
4844
4845
  // If we have more than one job, then disable integrated-cc1 for now. Do this
4846
  // also when we need to report process execution statistics.
4847
50.4k
  if (C.getJobs().size() > 1 || 
CCPrintProcessStats45.3k
)
4848
5.09k
    for (auto &J : C.getJobs())
4849
11.8k
      J.InProcess = false;
4850
4851
50.4k
  if (CCPrintProcessStats) {
4852
4
    C.setPostCallback([=](const Command &Cmd, int Res) {
4853
4
      std::optional<llvm::sys::ProcessStatistics> ProcStat =
4854
4
          Cmd.getProcessStatistics();
4855
4
      if (!ProcStat)
4856
0
        return;
4857
4858
4
      const char *LinkingOutput = nullptr;
4859
4
      if (FinalOutput)
4860
4
        LinkingOutput = FinalOutput->getValue();
4861
0
      else if (!Cmd.getOutputFilenames().empty())
4862
0
        LinkingOutput = Cmd.getOutputFilenames().front().c_str();
4863
0
      else
4864
0
        LinkingOutput = getDefaultImageName();
4865
4866
4
      if (CCPrintStatReportFilename.empty()) {
4867
2
        using namespace llvm;
4868
        // Human readable output.
4869
2
        outs() << sys::path::filename(Cmd.getExecutable()) << ": "
4870
2
               << "output=" << LinkingOutput;
4871
2
        outs() << ", total="
4872
2
               << format("%.3f", ProcStat->TotalTime.count() / 1000.) << " ms"
4873
2
               << ", user="
4874
2
               << format("%.3f", ProcStat->UserTime.count() / 1000.) << " ms"
4875
2
               << ", mem=" << ProcStat->PeakMemory << " Kb\n";
4876
2
      } else {
4877
        // CSV format.
4878
2
        std::string Buffer;
4879
2
        llvm::raw_string_ostream Out(Buffer);
4880
2
        llvm::sys::printArg(Out, llvm::sys::path::filename(Cmd.getExecutable()),
4881
2
                            /*Quote*/ true);
4882
2
        Out << ',';
4883
2
        llvm::sys::printArg(Out, LinkingOutput, true);
4884
2
        Out << ',' << ProcStat->TotalTime.count() << ','
4885
2
            << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory
4886
2
            << '\n';
4887
2
        Out.flush();
4888
2
        std::error_code EC;
4889
2
        llvm::raw_fd_ostream OS(CCPrintStatReportFilename, EC,
4890
2
                                llvm::sys::fs::OF_Append |
4891
2
                                    llvm::sys::fs::OF_Text);
4892
2
        if (EC)
4893
0
          return;
4894
2
        auto L = OS.lock();
4895
2
        if (!L) {
4896
0
          llvm::errs() << "ERROR: Cannot lock file "
4897
0
                       << CCPrintStatReportFilename << ": "
4898
0
                       << toString(L.takeError()) << "\n";
4899
0
          return;
4900
0
        }
4901
2
        OS << Buffer;
4902
2
        OS.flush();
4903
2
      }
4904
4
    });
4905
4
  }
4906
4907
  // If the user passed -Qunused-arguments or there were errors, don't warn
4908
  // about any unused arguments.
4909
50.4k
  if (Diags.hasErrorOccurred() ||
4910
50.4k
      
C.getArgs().hasArg(options::OPT_Qunused_arguments)48.2k
)
4911
2.20k
    return;
4912
4913
  // Claim -fdriver-only here.
4914
48.2k
  (void)C.getArgs().hasArg(options::OPT_fdriver_only);
4915
  // Claim -### here.
4916
48.2k
  (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
4917
4918
  // Claim --driver-mode, --rsp-quoting, it was handled earlier.
4919
48.2k
  (void)C.getArgs().hasArg(options::OPT_driver_mode);
4920
48.2k
  (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
4921
4922
53.8k
  bool HasAssembleJob = llvm::any_of(C.getJobs(), [](auto &J) {
4923
    // Match ClangAs and other derived assemblers of Tool. ClangAs uses a
4924
    // longer ShortName "clang integrated assembler" while other assemblers just
4925
    // use "assembler".
4926
53.8k
    return strstr(J.getCreator().getShortName(), "assembler");
4927
53.8k
  });
4928
749k
  for (Arg *A : C.getArgs()) {
4929
    // FIXME: It would be nice to be able to send the argument to the
4930
    // DiagnosticsEngine, so that extra values, position, and so on could be
4931
    // printed.
4932
749k
    if (!A->isClaimed()) {
4933
500
      if (A->getOption().hasFlag(options::NoArgumentUnused))
4934
34
        continue;
4935
4936
      // Suppress the warning automatically if this is just a flag, and it is an
4937
      // instance of an argument we already claimed.
4938
466
      const Option &Opt = A->getOption();
4939
466
      if (Opt.getKind() == Option::FlagClass) {
4940
157
        bool DuplicateClaimed = false;
4941
4942
158
        for (const Arg *AA : C.getArgs().filtered(&Opt)) {
4943
158
          if (AA->isClaimed()) {
4944
1
            DuplicateClaimed = true;
4945
1
            break;
4946
1
          }
4947
158
        }
4948
4949
157
        if (DuplicateClaimed)
4950
1
          continue;
4951
157
      }
4952
4953
      // In clang-cl, don't mention unknown arguments here since they have
4954
      // already been warned about.
4955
465
      if (!IsCLMode() || 
!A->getOption().matches(options::OPT_UNKNOWN)111
) {
4956
449
        if (A->getOption().hasFlag(options::TargetSpecific) &&
4957
449
            
!A->isIgnoredTargetSpecific()52
&&
!HasAssembleJob45
&&
4958
            // When for example -### or -v is used
4959
            // without a file, target specific options are not
4960
            // consumed/validated.
4961
            // Instead emitting an error emit a warning instead.
4962
449
            
!C.getActions().empty()40
) {
4963
32
          Diag(diag::err_drv_unsupported_opt_for_target)
4964
32
              << A->getSpelling() << getTargetTriple();
4965
417
        } else {
4966
417
          Diag(clang::diag::warn_drv_unused_argument)
4967
417
              << A->getAsString(C.getArgs());
4968
417
        }
4969
449
      }
4970
465
    }
4971
749k
  }
4972
48.2k
}
4973
4974
namespace {
4975
/// Utility class to control the collapse of dependent actions and select the
4976
/// tools accordingly.
4977
class ToolSelector final {
4978
  /// The tool chain this selector refers to.
4979
  const ToolChain &TC;
4980
4981
  /// The compilation this selector refers to.
4982
  const Compilation &C;
4983
4984
  /// The base action this selector refers to.
4985
  const JobAction *BaseAction;
4986
4987
  /// Set to true if the current toolchain refers to host actions.
4988
  bool IsHostSelector;
4989
4990
  /// Set to true if save-temps and embed-bitcode functionalities are active.
4991
  bool SaveTemps;
4992
  bool EmbedBitcode;
4993
4994
  /// Get previous dependent action or null if that does not exist. If
4995
  /// \a CanBeCollapsed is false, that action must be legal to collapse or
4996
  /// null will be returned.
4997
  const JobAction *getPrevDependentAction(const ActionList &Inputs,
4998
                                          ActionList &SavedOffloadAction,
4999
196k
                                          bool CanBeCollapsed = true) {
5000
    // An option can be collapsed only if it has a single input.
5001
196k
    if (Inputs.size() != 1)
5002
2.85k
      return nullptr;
5003
5004
193k
    Action *CurAction = *Inputs.begin();
5005
193k
    if (CanBeCollapsed &&
5006
193k
        !CurAction->isCollapsingWithNextDependentActionLegal())
5007
0
      return nullptr;
5008
5009
    // If the input action is an offload action. Look through it and save any
5010
    // offload action that can be dropped in the event of a collapse.
5011
193k
    if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
5012
      // If the dependent action is a device action, we will attempt to collapse
5013
      // only with other device actions. Otherwise, we would do the same but
5014
      // with host actions only.
5015
610
      if (!IsHostSelector) {
5016
211
        if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
5017
211
          CurAction =
5018
211
              OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
5019
211
          if (CanBeCollapsed &&
5020
211
              !CurAction->isCollapsingWithNextDependentActionLegal())
5021
0
            return nullptr;
5022
211
          SavedOffloadAction.push_back(OA);
5023
211
          return dyn_cast<JobAction>(CurAction);
5024
211
        }
5025
399
      } else if (OA->hasHostDependence()) {
5026
399
        CurAction = OA->getHostDependence();
5027
399
        if (CanBeCollapsed &&
5028
399
            !CurAction->isCollapsingWithNextDependentActionLegal())
5029
35
          return nullptr;
5030
364
        SavedOffloadAction.push_back(OA);
5031
364
        return dyn_cast<JobAction>(CurAction);
5032
399
      }
5033
0
      return nullptr;
5034
610
    }
5035
5036
193k
    return dyn_cast<JobAction>(CurAction);
5037
193k
  }
5038
5039
  /// Return true if an assemble action can be collapsed.
5040
59.1k
  bool canCollapseAssembleAction() const {
5041
59.1k
    return TC.useIntegratedAs() && 
!SaveTemps57.5k
&&
5042
59.1k
           
!C.getArgs().hasArg(options::OPT_via_file_asm)57.0k
&&
5043
59.1k
           
!C.getArgs().hasArg(options::OPT__SLASH_FA)57.0k
&&
5044
59.1k
           
!C.getArgs().hasArg(options::OPT__SLASH_Fa)56.7k
&&
5045
59.1k
           
!C.getArgs().hasArg(options::OPT_dxc_Fc)56.7k
;
5046
59.1k
  }
5047
5048
  /// Return true if a preprocessor action can be collapsed.
5049
59.4k
  bool canCollapsePreprocessorAction() const {
5050
59.4k
    return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
5051
59.4k
           
!C.getArgs().hasArg(options::OPT_traditional_cpp)59.4k
&& !SaveTemps &&
5052
59.4k
           
!C.getArgs().hasArg(options::OPT_rewrite_objc)58.9k
;
5053
59.4k
  }
5054
5055
  /// Struct that relates an action with the offload actions that would be
5056
  /// collapsed with it.
5057
  struct JobActionInfo final {
5058
    /// The action this info refers to.
5059
    const JobAction *JA = nullptr;
5060
    /// The offload actions we need to take care off if this action is
5061
    /// collapsed.
5062
    ActionList SavedOffloadAction;
5063
  };
5064
5065
  /// Append collapsed offload actions from the give nnumber of elements in the
5066
  /// action info array.
5067
  static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
5068
                                           ArrayRef<JobActionInfo> &ActionInfo,