Coverage Report

Created: 2021-01-16 07:00

/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 "InputInfo.h"
11
#include "ToolChains/AIX.h"
12
#include "ToolChains/AMDGPU.h"
13
#include "ToolChains/AVR.h"
14
#include "ToolChains/Ananas.h"
15
#include "ToolChains/BareMetal.h"
16
#include "ToolChains/Clang.h"
17
#include "ToolChains/CloudABI.h"
18
#include "ToolChains/Contiki.h"
19
#include "ToolChains/CrossWindows.h"
20
#include "ToolChains/Cuda.h"
21
#include "ToolChains/Darwin.h"
22
#include "ToolChains/DragonFly.h"
23
#include "ToolChains/FreeBSD.h"
24
#include "ToolChains/Fuchsia.h"
25
#include "ToolChains/Gnu.h"
26
#include "ToolChains/HIP.h"
27
#include "ToolChains/Haiku.h"
28
#include "ToolChains/Hexagon.h"
29
#include "ToolChains/Hurd.h"
30
#include "ToolChains/Lanai.h"
31
#include "ToolChains/Linux.h"
32
#include "ToolChains/MSP430.h"
33
#include "ToolChains/MSVC.h"
34
#include "ToolChains/MinGW.h"
35
#include "ToolChains/Minix.h"
36
#include "ToolChains/MipsLinux.h"
37
#include "ToolChains/Myriad.h"
38
#include "ToolChains/NaCl.h"
39
#include "ToolChains/NetBSD.h"
40
#include "ToolChains/OpenBSD.h"
41
#include "ToolChains/PPCLinux.h"
42
#include "ToolChains/PS4CPU.h"
43
#include "ToolChains/RISCVToolchain.h"
44
#include "ToolChains/Solaris.h"
45
#include "ToolChains/TCE.h"
46
#include "ToolChains/VEToolchain.h"
47
#include "ToolChains/WebAssembly.h"
48
#include "ToolChains/XCore.h"
49
#include "ToolChains/ZOS.h"
50
#include "clang/Basic/TargetID.h"
51
#include "clang/Basic/Version.h"
52
#include "clang/Config/config.h"
53
#include "clang/Driver/Action.h"
54
#include "clang/Driver/Compilation.h"
55
#include "clang/Driver/DriverDiagnostic.h"
56
#include "clang/Driver/Job.h"
57
#include "clang/Driver/Options.h"
58
#include "clang/Driver/SanitizerArgs.h"
59
#include "clang/Driver/Tool.h"
60
#include "clang/Driver/ToolChain.h"
61
#include "llvm/ADT/ArrayRef.h"
62
#include "llvm/ADT/STLExtras.h"
63
#include "llvm/ADT/SmallSet.h"
64
#include "llvm/ADT/StringExtras.h"
65
#include "llvm/ADT/StringSet.h"
66
#include "llvm/ADT/StringSwitch.h"
67
#include "llvm/Config/llvm-config.h"
68
#include "llvm/Option/Arg.h"
69
#include "llvm/Option/ArgList.h"
70
#include "llvm/Option/OptSpecifier.h"
71
#include "llvm/Option/OptTable.h"
72
#include "llvm/Option/Option.h"
73
#include "llvm/Support/CommandLine.h"
74
#include "llvm/Support/ErrorHandling.h"
75
#include "llvm/Support/ExitCodes.h"
76
#include "llvm/Support/FileSystem.h"
77
#include "llvm/Support/FormatVariadic.h"
78
#include "llvm/Support/Host.h"
79
#include "llvm/Support/Path.h"
80
#include "llvm/Support/PrettyStackTrace.h"
81
#include "llvm/Support/Process.h"
82
#include "llvm/Support/Program.h"
83
#include "llvm/Support/StringSaver.h"
84
#include "llvm/Support/TargetRegistry.h"
85
#include "llvm/Support/VirtualFileSystem.h"
86
#include "llvm/Support/raw_ostream.h"
87
#include <map>
88
#include <memory>
89
#include <utility>
90
#if LLVM_ON_UNIX
91
#include <unistd.h> // getpid
92
#endif
93
94
using namespace clang::driver;
95
using namespace clang;
96
using namespace llvm::opt;
97
98
433
static llvm::Triple getHIPOffloadTargetTriple() {
99
433
  static const llvm::Triple T("amdgcn-amd-amdhsa");
100
433
  return T;
101
433
}
102
103
// static
104
std::string Driver::GetResourcesPath(StringRef BinaryPath,
105
81.1k
                                     StringRef CustomResourceDir) {
106
  // Since the resource directory is embedded in the module hash, it's important
107
  // that all places that need it call this function, so that they get the
108
  // exact same string ("a/../b/" and "b/" get different hashes, for example).
109
110
  // Dir is bin/ or lib/, depending on where BinaryPath is.
111
81.1k
  std::string Dir = std::string(llvm::sys::path::parent_path(BinaryPath));
112
113
81.1k
  SmallString<128> P(Dir);
114
81.1k
  if (CustomResourceDir != "") {
115
0
    llvm::sys::path::append(P, CustomResourceDir);
116
81.1k
  } else {
117
    // On Windows, libclang.dll is in bin/.
118
    // On non-Windows, libclang.so/.dylib is in lib/.
119
    // With a static-library build of libclang, LibClangPath will contain the
120
    // path of the embedding binary, which for LLVM binaries will be in bin/.
121
    // ../lib gets us to lib/ in both cases.
122
81.1k
    P = llvm::sys::path::parent_path(Dir);
123
81.1k
    llvm::sys::path::append(P, Twine("lib") + CLANG_LIBDIR_SUFFIX, "clang",
124
81.1k
                            CLANG_VERSION_STRING);
125
81.1k
  }
126
127
81.1k
  return std::string(P.str());
128
81.1k
}
129
130
Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
131
               DiagnosticsEngine &Diags, std::string Title,
132
               IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
133
    : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
134
      SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None),
135
      ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
136
      DriverTitle(Title), CCPrintOptionsFilename(nullptr),
137
      CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
138
      CCCPrintBindings(false), CCPrintOptions(false), CCPrintHeaders(false),
139
      CCLogDiagnostics(false), CCGenDiagnostics(false),
140
      TargetTriple(TargetTriple), CCCGenericGCCName(""), Saver(Alloc),
141
      CheckInputsExist(true), GenReproducer(false),
142
47.9k
      SuppressMissingInputWarning(false) {
143
  // Provide a sane fallback if no VFS is specified.
144
47.9k
  if (!this->VFS)
145
23.1k
    this->VFS = llvm::vfs::getRealFileSystem();
146
147
47.9k
  Name = std::string(llvm::sys::path::filename(ClangExecutable));
148
47.9k
  Dir = std::string(llvm::sys::path::parent_path(ClangExecutable));
149
47.9k
  InstalledDir = Dir; // Provide a sensible default installed dir.
150
151
47.9k
  if ((!SysRoot.empty()) && 
llvm::sys::path::is_relative(SysRoot)0
) {
152
    // Prepend InstalledDir if SysRoot is relative
153
0
    SmallString<128> P(InstalledDir);
154
0
    llvm::sys::path::append(P, SysRoot);
155
0
    SysRoot = std::string(P);
156
0
  }
157
158
#if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
159
  SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
160
#endif
161
#if defined(CLANG_CONFIG_FILE_USER_DIR)
162
  UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
163
#endif
164
165
  // Compute the path to the resource directory.
166
47.9k
  ResourceDir = GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
167
47.9k
}
168
169
void Driver::ParseDriverMode(StringRef ProgramName,
170
47.9k
                             ArrayRef<const char *> Args) {
171
47.9k
  if (ClangNameParts.isEmpty())
172
27.1k
    ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
173
47.9k
  setDriverModeFromOption(ClangNameParts.DriverMode);
174
175
818k
  for (const char *ArgPtr : Args) {
176
    // Ignore nullptrs, they are the response file's EOL markers.
177
818k
    if (ArgPtr == nullptr)
178
2
      continue;
179
818k
    const StringRef Arg = ArgPtr;
180
818k
    setDriverModeFromOption(Arg);
181
818k
  }
182
47.9k
}
183
184
866k
void Driver::setDriverModeFromOption(StringRef Opt) {
185
866k
  const std::string OptName =
186
866k
      getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
187
866k
  if (!Opt.startswith(OptName))
188
859k
    return;
189
7.11k
  StringRef Value = Opt.drop_front(OptName.size());
190
191
7.11k
  if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
192
7.13k
                   .Case("gcc", GCCMode)
193
7.13k
                   .Case("g++", GXXMode)
194
7.13k
                   .Case("cpp", CPPMode)
195
7.13k
                   .Case("cl", CLMode)
196
7.13k
                   .Case("flang", FlangMode)
197
7.13k
                   .Default(None))
198
7.13k
    Mode = *M;
199
18.4E
  else
200
18.4E
    Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
201
7.11k
}
202
203
InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
204
                                     bool IsClCompatMode,
205
47.9k
                                     bool &ContainsError) {
206
47.9k
  llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
207
47.9k
  ContainsError = false;
208
209
47.9k
  unsigned IncludedFlagsBitmask;
210
47.9k
  unsigned ExcludedFlagsBitmask;
211
47.9k
  std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
212
47.9k
      getIncludeExcludeOptionFlagMasks(IsClCompatMode);
213
214
  // Make sure that Flang-only options don't pollute the Clang output
215
  // TODO: Make sure that Clang-only options don't pollute Flang output
216
47.9k
  if (!IsFlangMode())
217
47.9k
    ExcludedFlagsBitmask |= options::FlangOnlyOption;
218
219
47.9k
  unsigned MissingArgIndex, MissingArgCount;
220
47.9k
  InputArgList Args =
221
47.9k
      getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
222
47.9k
                          IncludedFlagsBitmask, ExcludedFlagsBitmask);
223
224
  // Check for missing argument error.
225
47.9k
  if (MissingArgCount) {
226
4
    Diag(diag::err_drv_missing_argument)
227
4
        << Args.getArgString(MissingArgIndex) << MissingArgCount;
228
4
    ContainsError |=
229
4
        Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
230
4
                                 SourceLocation()) > DiagnosticsEngine::Warning;
231
4
  }
232
233
  // Check for unsupported options.
234
737k
  for (const Arg *A : Args) {
235
737k
    if (A->getOption().hasFlag(options::Unsupported)) {
236
16
      unsigned DiagID;
237
16
      auto ArgString = A->getAsString(Args);
238
16
      std::string Nearest;
239
16
      if (getOpts().findNearest(
240
16
            ArgString, Nearest, IncludedFlagsBitmask,
241
15
            ExcludedFlagsBitmask | options::Unsupported) > 1) {
242
15
        DiagID = diag::err_drv_unsupported_opt;
243
15
        Diag(DiagID) << ArgString;
244
1
      } else {
245
1
        DiagID = diag::err_drv_unsupported_opt_with_suggestion;
246
1
        Diag(DiagID) << ArgString << Nearest;
247
1
      }
248
16
      ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
249
16
                       DiagnosticsEngine::Warning;
250
16
      continue;
251
16
    }
252
253
    // Warn about -mcpu= without an argument.
254
737k
    if (A->getOption().matches(options::OPT_mcpu_EQ) && 
A->containsValue("")1.27k
) {
255
0
      Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
256
0
      ContainsError |= Diags.getDiagnosticLevel(
257
0
                           diag::warn_drv_empty_joined_argument,
258
0
                           SourceLocation()) > DiagnosticsEngine::Warning;
259
0
    }
260
737k
  }
261
262
56
  for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
263
56
    unsigned DiagID;
264
56
    auto ArgString = A->getAsString(Args);
265
56
    std::string Nearest;
266
56
    if (getOpts().findNearest(
267
50
          ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
268
33
      DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
269
17
                          : diag::err_drv_unknown_argument;
270
50
      Diags.Report(DiagID) << ArgString;
271
6
    } else {
272
6
      DiagID = IsCLMode()
273
2
                   ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
274
4
                   : diag::err_drv_unknown_argument_with_suggestion;
275
6
      Diags.Report(DiagID) << ArgString << Nearest;
276
6
    }
277
56
    ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
278
56
                     DiagnosticsEngine::Warning;
279
56
  }
280
281
47.9k
  return Args;
282
47.9k
}
283
284
// Determine which compilation mode we are in. We look for options which
285
// affect the phase, starting with the earliest phases, and record which
286
// option we used to determine the final phase.
287
phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
288
46.6k
                                 Arg **FinalPhaseArg) const {
289
46.6k
  Arg *PhaseArg = nullptr;
290
46.6k
  phases::ID FinalPhase;
291
292
  // -{E,EP,P,M,MM} only run the preprocessor.
293
46.6k
  if (CCCIsCPP() || 
(PhaseArg = DAL.getLastArg(options::OPT_E))46.6k
||
294
45.4k
      (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
295
45.4k
      (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
296
42.5k
      (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
297
4.15k
    FinalPhase = phases::Preprocess;
298
299
  // --precompile only runs up to precompilation.
300
42.5k
  } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
301
6
    FinalPhase = phases::Precompile;
302
303
  // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
304
42.5k
  } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
305
15.0k
             (PhaseArg = DAL.getLastArg(options::OPT_print_supported_cpus)) ||
306
15.0k
             (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
307
15.0k
             (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
308
15.0k
             (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
309
15.0k
             (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
310
15.0k
             (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
311
15.0k
             (PhaseArg = DAL.getLastArg(options::OPT__analyze)) ||
312
27.5k
             
(PhaseArg = DAL.getLastArg(options::OPT_emit_ast))14.9k
) {
313
27.5k
    FinalPhase = phases::Compile;
314
315
  // -S only runs up to the backend.
316
14.9k
  } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
317
1.20k
    FinalPhase = phases::Backend;
318
319
  // -c compilation only runs up to the assembler.
320
13.7k
  } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
321
6.87k
    FinalPhase = phases::Assemble;
322
323
  // Otherwise do everything.
324
6.87k
  } else
325
6.86k
    FinalPhase = phases::Link;
326
327
46.6k
  if (FinalPhaseArg)
328
46.6k
    *FinalPhaseArg = PhaseArg;
329
330
46.6k
  return FinalPhase;
331
46.6k
}
332
333
static Arg *MakeInputArg(DerivedArgList &Args, const OptTable &Opts,
334
531
                         StringRef Value, bool Claim = true) {
335
531
  Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
336
531
                   Args.getBaseArgs().MakeIndex(Value), Value.data());
337
531
  Args.AddSynthesizedArg(A);
338
531
  if (Claim)
339
18
    A->claim();
340
531
  return A;
341
531
}
342
343
47.9k
DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
344
47.9k
  const llvm::opt::OptTable &Opts = getOpts();
345
47.9k
  DerivedArgList *DAL = new DerivedArgList(Args);
346
347
47.9k
  bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
348
47.9k
  bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
349
47.9k
  bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
350
737k
  for (Arg *A : Args) {
351
    // Unfortunately, we have to parse some forwarding options (-Xassembler,
352
    // -Xlinker, -Xpreprocessor) because we either integrate their functionality
353
    // (assembler and preprocessor), or bypass a previous driver ('collect2').
354
355
    // Rewrite linker options, to replace --no-demangle with a custom internal
356
    // option.
357
737k
    if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
358
737k
         A->getOption().matches(options::OPT_Xlinker)) &&
359
92
        A->containsValue("--no-demangle")) {
360
      // Add the rewritten no-demangle argument.
361
5
      DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_Xlinker__no_demangle));
362
363
      // Add the remaining values as Xlinker arguments.
364
5
      for (StringRef Val : A->getValues())
365
9
        if (Val != "--no-demangle")
366
4
          DAL->AddSeparateArg(A, Opts.getOption(options::OPT_Xlinker), Val);
367
368
5
      continue;
369
5
    }
370
371
    // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
372
    // some build systems. We don't try to be complete here because we don't
373
    // care to encourage this usage model.
374
737k
    if (A->getOption().matches(options::OPT_Wp_COMMA) &&
375
3
        (A->getValue(0) == StringRef("-MD") ||
376
2
         A->getValue(0) == StringRef("-MMD"))) {
377
      // Rewrite to -MD/-MMD along with -MF.
378
2
      if (A->getValue(0) == StringRef("-MD"))
379
1
        DAL->AddFlagArg(A, Opts.getOption(options::OPT_MD));
380
1
      else
381
1
        DAL->AddFlagArg(A, Opts.getOption(options::OPT_MMD));
382
2
      if (A->getNumValues() == 2)
383
1
        DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue(1));
384
2
      continue;
385
2
    }
386
387
    // Rewrite reserved library names.
388
737k
    if (A->getOption().matches(options::OPT_l)) {
389
681
      StringRef Value = A->getValue();
390
391
      // Rewrite unless -nostdlib is present.
392
681
      if (!HasNostdlib && 
!HasNodefaultlib679
&&
!HasNostdlibxx678
&&
393
677
          Value == "stdc++") {
394
4
        DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_stdcxx));
395
4
        continue;
396
4
      }
397
398
      // Rewrite unconditionally.
399
677
      if (Value == "cc_kext") {
400
2
        DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_cckext));
401
2
        continue;
402
2
      }
403
737k
    }
404
405
    // Pick up inputs via the -- option.
406
737k
    if (A->getOption().matches(options::OPT__DASH_DASH)) {
407
500
      A->claim();
408
500
      for (StringRef Val : A->getValues())
409
513
        DAL->append(MakeInputArg(*DAL, Opts, Val, false));
410
500
      continue;
411
500
    }
412
413
736k
    DAL->append(A);
414
736k
  }
415
416
  // Enforce -static if -miamcu is present.
417
47.9k
  if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
418
8
    DAL->AddFlagArg(0, Opts.getOption(options::OPT_static));
419
420
// Add a default value of -mlinker-version=, if one was given and the user
421
// didn't specify one.
422
47.9k
#if defined(HOST_LINK_VERSION)
423
47.9k
  if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
424
47.7k
      strlen(HOST_LINK_VERSION) > 0) {
425
47.7k
    DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ),
426
47.7k
                      HOST_LINK_VERSION);
427
47.7k
    DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
428
47.7k
  }
429
47.9k
#endif
430
431
47.9k
  return DAL;
432
47.9k
}
433
434
/// Compute target triple from args.
435
///
436
/// This routine provides the logic to compute a target triple from various
437
/// args passed to the driver and the default triple string.
438
static llvm::Triple computeTargetTriple(const Driver &D,
439
                                        StringRef TargetTriple,
440
                                        const ArgList &Args,
441
69.2k
                                        StringRef DarwinArchName = "") {
442
  // FIXME: Already done in Compilation *Driver::BuildCompilation
443
69.2k
  if (const Arg *A = Args.getLastArg(options::OPT_target))
444
29.5k
    TargetTriple = A->getValue();
445
446
69.2k
  llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
447
448
  // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
449
  // -gnu* only, and we can not change this, so we have to detect that case as
450
  // being the Hurd OS.
451
69.2k
  if (TargetTriple.find("-unknown-gnu") != StringRef::npos ||
452
69.2k
      TargetTriple.find("-pc-gnu") != StringRef::npos)
453
6
    Target.setOSName("hurd");
454
455
  // Handle Apple-specific options available here.
456
69.2k
  if (Target.isOSBinFormatMachO()) {
457
    // If an explicit Darwin arch name is given, that trumps all.
458
43.7k
    if (!DarwinArchName.empty()) {
459
21.3k
      tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
460
21.3k
      return Target;
461
21.3k
    }
462
463
    // Handle the Darwin '-arch' flag.
464
22.4k
    if (Arg *A = Args.getLastArg(options::OPT_arch)) {
465
8.82k
      StringRef ArchName = A->getValue();
466
8.82k
      tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
467
8.82k
    }
468
22.4k
  }
469
470
  // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
471
  // '-mbig-endian'/'-EB'.
472
47.9k
  if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
473
511
                               options::OPT_mbig_endian)) {
474
511
    if (A->getOption().matches(options::OPT_mlittle_endian)) {
475
270
      llvm::Triple LE = Target.getLittleEndianArchVariant();
476
270
      if (LE.getArch() != llvm::Triple::UnknownArch)
477
265
        Target = std::move(LE);
478
241
    } else {
479
241
      llvm::Triple BE = Target.getBigEndianArchVariant();
480
241
      if (BE.getArch() != llvm::Triple::UnknownArch)
481
119
        Target = std::move(BE);
482
241
    }
483
511
  }
484
485
  // Skip further flag support on OSes which don't support '-m32' or '-m64'.
486
47.9k
  if (Target.getArch() == llvm::Triple::tce ||
487
47.9k
      Target.getOS() == llvm::Triple::Minix)
488
0
    return Target;
489
490
  // On AIX, the env OBJECT_MODE may affect the resulting arch variant.
491
47.9k
  if (Target.isOSAIX()) {
492
99
    if (Optional<std::string> ObjectModeValue =
493
5
            llvm::sys::Process::GetEnv("OBJECT_MODE")) {
494
5
      StringRef ObjectMode = *ObjectModeValue;
495
5
      llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
496
497
5
      if (ObjectMode.equals("64")) {
498
2
        AT = Target.get64BitArchVariant().getArch();
499
3
      } else if (ObjectMode.equals("32")) {
500
2
        AT = Target.get32BitArchVariant().getArch();
501
1
      } else {
502
1
        D.Diag(diag::err_drv_invalid_object_mode) << ObjectMode;
503
1
      }
504
505
5
      if (AT != llvm::Triple::UnknownArch && 
AT != Target.getArch()4
)
506
2
        Target.setArch(AT);
507
5
    }
508
99
  }
509
510
  // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
511
47.9k
  Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
512
47.9k
                           options::OPT_m32, options::OPT_m16);
513
47.9k
  if (A) {
514
277
    llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
515
516
277
    if (A->getOption().matches(options::OPT_m64)) {
517
125
      AT = Target.get64BitArchVariant().getArch();
518
125
      if (Target.getEnvironment() == llvm::Triple::GNUX32)
519
1
        Target.setEnvironment(llvm::Triple::GNU);
520
152
    } else if (A->getOption().matches(options::OPT_mx32) &&
521
2
               Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
522
2
      AT = llvm::Triple::x86_64;
523
2
      Target.setEnvironment(llvm::Triple::GNUX32);
524
150
    } else if (A->getOption().matches(options::OPT_m32)) {
525
149
      AT = Target.get32BitArchVariant().getArch();
526
149
      if (Target.getEnvironment() == llvm::Triple::GNUX32)
527
1
        Target.setEnvironment(llvm::Triple::GNU);
528
1
    } else if (A->getOption().matches(options::OPT_m16) &&
529
1
               Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
530
1
      AT = llvm::Triple::x86;
531
1
      Target.setEnvironment(llvm::Triple::CODE16);
532
1
    }
533
534
277
    if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
535
133
      Target.setArch(AT);
536
277
  }
537
538
  // Handle -miamcu flag.
539
47.9k
  if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
540
8
    if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
541
1
      D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
542
1
                                                       << Target.str();
543
544
8
    if (A && 
!A->getOption().matches(options::OPT_m32)2
)
545
1
      D.Diag(diag::err_drv_argument_not_allowed_with)
546
1
          << "-miamcu" << A->getBaseArg().getAsString(Args);
547
548
8
    Target.setArch(llvm::Triple::x86);
549
8
    Target.setArchName("i586");
550
8
    Target.setEnvironment(llvm::Triple::UnknownEnvironment);
551
8
    Target.setEnvironmentName("");
552
8
    Target.setOS(llvm::Triple::ELFIAMCU);
553
8
    Target.setVendor(llvm::Triple::UnknownVendor);
554
8
    Target.setVendorName("intel");
555
8
  }
556
557
  // If target is MIPS adjust the target triple
558
  // accordingly to provided ABI name.
559
47.9k
  A = Args.getLastArg(options::OPT_mabi_EQ);
560
47.9k
  if (A && 
Target.isMIPS()165
) {
561
108
    StringRef ABIName = A->getValue();
562
108
    if (ABIName == "32") {
563
12
      Target = Target.get32BitArchVariant();
564
12
      if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
565
11
          Target.getEnvironment() == llvm::Triple::GNUABIN32)
566
1
        Target.setEnvironment(llvm::Triple::GNU);
567
96
    } else if (ABIName == "n32") {
568
41
      Target = Target.get64BitArchVariant();
569
41
      if (Target.getEnvironment() == llvm::Triple::GNU ||
570
3
          Target.getEnvironment() == llvm::Triple::GNUABI64)
571
38
        Target.setEnvironment(llvm::Triple::GNUABIN32);
572
55
    } else if (ABIName == "64") {
573
42
      Target = Target.get64BitArchVariant();
574
42
      if (Target.getEnvironment() == llvm::Triple::GNU ||
575
3
          Target.getEnvironment() == llvm::Triple::GNUABIN32)
576
39
        Target.setEnvironment(llvm::Triple::GNUABI64);
577
42
    }
578
108
  }
579
580
  // If target is RISC-V adjust the target triple according to
581
  // provided architecture name
582
47.9k
  A = Args.getLastArg(options::OPT_march_EQ);
583
47.9k
  if (A && 
Target.isRISCV()1.58k
) {
584
162
    StringRef ArchName = A->getValue();
585
162
    if (ArchName.startswith_lower("rv32"))
586
107
      Target.setArch(llvm::Triple::riscv32);
587
55
    else if (ArchName.startswith_lower("rv64"))
588
54
      Target.setArch(llvm::Triple::riscv64);
589
162
  }
590
591
47.9k
  return Target;
592
47.9k
}
593
594
// Parse the LTO options and record the type of LTO compilation
595
// based on which -f(no-)?lto(=.*)? option occurs last.
596
47.8k
void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
597
47.8k
  LTOMode = LTOK_None;
598
47.8k
  if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
599
47.8k
                    options::OPT_fno_lto, false))
600
47.7k
    return;
601
602
177
  StringRef LTOName("full");
603
604
177
  const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
605
177
  if (A)
606
76
    LTOName = A->getValue();
607
608
177
  LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
609
177
                .Case("full", LTOK_Full)
610
177
                .Case("thin", LTOK_Thin)
611
177
                .Default(LTOK_Unknown);
612
613
177
  if (LTOMode == LTOK_Unknown) {
614
2
    assert(A);
615
2
    Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
616
2
                                                    << A->getValue();
617
2
  }
618
177
}
619
620
/// Compute the desired OpenMP runtime from the flags provided.
621
1.16k
Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
622
1.16k
  StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
623
624
1.16k
  const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
625
1.16k
  if (A)
626
1.14k
    RuntimeName = A->getValue();
627
628
1.16k
  auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
629
1.16k
                .Case("libomp", OMPRT_OMP)
630
1.16k
                .Case("libgomp", OMPRT_GOMP)
631
1.16k
                .Case("libiomp5", OMPRT_IOMP5)
632
1.16k
                .Default(OMPRT_Unknown);
633
634
1.16k
  if (RT == OMPRT_Unknown) {
635
4
    if (A)
636
4
      Diag(diag::err_drv_unsupported_option_argument)
637
4
          << A->getOption().getName() << A->getValue();
638
0
    else
639
      // FIXME: We could use a nicer diagnostic here.
640
0
      Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
641
4
  }
642
643
1.16k
  return RT;
644
1.16k
}
645
646
void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
647
46.6k
                                              InputList &Inputs) {
648
649
  //
650
  // CUDA/HIP
651
  //
652
  // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
653
  // or HIP type. However, mixed CUDA/HIP compilation is not supported.
654
46.6k
  bool IsCuda =
655
48.2k
      llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
656
48.2k
        return types::isCuda(I.first);
657
48.2k
      });
658
46.6k
  bool IsHIP =
659
46.6k
      llvm::any_of(Inputs,
660
48.2k
                   [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
661
48.2k
                     return types::isHIP(I.first);
662
48.2k
                   }) ||
663
46.5k
      C.getInputArgs().hasArg(options::OPT_hip_link);
664
46.6k
  if (IsCuda && 
IsHIP299
) {
665
2
    Diag(clang::diag::err_drv_mix_cuda_hip);
666
2
    return;
667
2
  }
668
46.6k
  if (IsCuda) {
669
297
    const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
670
297
    const llvm::Triple &HostTriple = HostTC->getTriple();
671
297
    StringRef DeviceTripleStr;
672
297
    auto OFK = Action::OFK_Cuda;
673
297
    DeviceTripleStr =
674
263
        HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" : 
"nvptx-nvidia-cuda"34
;
675
297
    llvm::Triple CudaTriple(DeviceTripleStr);
676
    // Use the CUDA and host triples as the key into the ToolChains map,
677
    // because the device toolchain we create depends on both.
678
297
    auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
679
297
    if (!CudaTC) {
680
297
      CudaTC = std::make_unique<toolchains::CudaToolChain>(
681
297
          *this, CudaTriple, *HostTC, C.getInputArgs(), OFK);
682
297
    }
683
297
    C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
684
46.3k
  } else if (IsHIP) {
685
184
    const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
686
184
    const llvm::Triple &HostTriple = HostTC->getTriple();
687
184
    auto OFK = Action::OFK_HIP;
688
184
    llvm::Triple HIPTriple = getHIPOffloadTargetTriple();
689
    // Use the HIP and host triples as the key into the ToolChains map,
690
    // because the device toolchain we create depends on both.
691
184
    auto &HIPTC = ToolChains[HIPTriple.str() + "/" + HostTriple.str()];
692
184
    if (!HIPTC) {
693
184
      HIPTC = std::make_unique<toolchains::HIPToolChain>(
694
184
          *this, HIPTriple, *HostTC, C.getInputArgs());
695
184
    }
696
184
    C.addOffloadDeviceToolChain(HIPTC.get(), OFK);
697
184
  }
698
699
  //
700
  // OpenMP
701
  //
702
  // We need to generate an OpenMP toolchain if the user specified targets with
703
  // the -fopenmp-targets option.
704
46.6k
  if (Arg *OpenMPTargets =
705
84
          C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
706
84
    if (OpenMPTargets->getNumValues()) {
707
      // We expect that -fopenmp-targets is always used in conjunction with the
708
      // option -fopenmp specifying a valid runtime with offloading support,
709
      // i.e. libomp or libiomp.
710
83
      bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
711
83
          options::OPT_fopenmp, options::OPT_fopenmp_EQ,
712
83
          options::OPT_fno_openmp, false);
713
83
      if (HasValidOpenMPRuntime) {
714
82
        OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
715
82
        HasValidOpenMPRuntime =
716
82
            OpenMPKind == OMPRT_OMP || 
OpenMPKind == OMPRT_IOMP51
;
717
82
      }
718
719
83
      if (HasValidOpenMPRuntime) {
720
81
        llvm::StringMap<const char *> FoundNormalizedTriples;
721
99
        for (const char *Val : OpenMPTargets->getValues()) {
722
99
          llvm::Triple TT(Val);
723
99
          std::string NormalizedName = TT.normalize();
724
725
          // Make sure we don't have a duplicate triple.
726
99
          auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
727
99
          if (Duplicate != FoundNormalizedTriples.end()) {
728
1
            Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
729
1
                << Val << Duplicate->second;
730
1
            continue;
731
1
          }
732
733
          // Store the current triple so that we can check for duplicates in the
734
          // following iterations.
735
98
          FoundNormalizedTriples[NormalizedName] = Val;
736
737
          // If the specified target is invalid, emit a diagnostic.
738
98
          if (TT.getArch() == llvm::Triple::UnknownArch)
739
1
            Diag(clang::diag::err_drv_invalid_omp_target) << Val;
740
97
          else {
741
97
            const ToolChain *TC;
742
            // CUDA toolchains have to be selected differently. They pair host
743
            // and device in their implementation.
744
97
            if (TT.isNVPTX()) {
745
47
              const ToolChain *HostTC =
746
47
                  C.getSingleOffloadToolChain<Action::OFK_Host>();
747
47
              assert(HostTC && "Host toolchain should be always defined.");
748
47
              auto &CudaTC =
749
47
                  ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
750
47
              if (!CudaTC)
751
46
                CudaTC = std::make_unique<toolchains::CudaToolChain>(
752
46
                    *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
753
47
              TC = CudaTC.get();
754
47
            } else
755
50
              TC = &getToolChain(C.getInputArgs(), TT);
756
97
            C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
757
97
          }
758
98
        }
759
81
      } else
760
2
        Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
761
83
    } else
762
1
      Diag(clang::diag::warn_drv_empty_joined_argument)
763
1
          << OpenMPTargets->getAsString(C.getInputArgs());
764
84
  }
765
766
  //
767
  // TODO: Add support for other offloading programming models here.
768
  //
769
46.6k
}
770
771
/// Looks the given directories for the specified file.
772
///
773
/// \param[out] FilePath File path, if the file was found.
774
/// \param[in]  Dirs Directories used for the search.
775
/// \param[in]  FileName Name of the file to search for.
776
/// \return True if file was found.
777
///
778
/// Looks for file specified by FileName sequentially in directories specified
779
/// by Dirs.
780
///
781
static bool searchForFile(SmallVectorImpl<char> &FilePath,
782
60
                          ArrayRef<StringRef> Dirs, StringRef FileName) {
783
60
  SmallString<128> WPath;
784
157
  for (const StringRef &Dir : Dirs) {
785
157
    if (Dir.empty())
786
86
      continue;
787
71
    WPath.clear();
788
71
    llvm::sys::path::append(WPath, Dir, FileName);
789
71
    llvm::sys::path::native(WPath);
790
71
    if (llvm::sys::fs::is_regular_file(WPath)) {
791
24
      FilePath = std::move(WPath);
792
24
      return true;
793
24
    }
794
71
  }
795
36
  return false;
796
60
}
797
798
32
bool Driver::readConfigFile(StringRef FileName) {
799
  // Try reading the given file.
800
32
  SmallVector<const char *, 32> NewCfgArgs;
801
32
  if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
802
0
    Diag(diag::err_drv_cannot_read_config_file) << FileName;
803
0
    return true;
804
0
  }
805
806
  // Read options from config file.
807
32
  llvm::SmallString<128> CfgFileName(FileName);
808
32
  llvm::sys::path::native(CfgFileName);
809
32
  ConfigFile = std::string(CfgFileName);
810
32
  bool ContainErrors;
811
32
  CfgOptions = std::make_unique<InputArgList>(
812
32
      ParseArgStrings(NewCfgArgs, IsCLMode(), ContainErrors));
813
32
  if (ContainErrors) {
814
1
    CfgOptions.reset();
815
1
    return true;
816
1
  }
817
818
31
  if (CfgOptions->hasArg(options::OPT_config)) {
819
1
    CfgOptions.reset();
820
1
    Diag(diag::err_drv_nested_config_file);
821
1
    return true;
822
1
  }
823
824
  // Claim all arguments that come from a configuration file so that the driver
825
  // does not warn on any that is unused.
826
30
  for (Arg *A : *CfgOptions)
827
35
    A->claim();
828
30
  return false;
829
30
}
830
831
47.8k
bool Driver::loadConfigFile() {
832
47.8k
  std::string CfgFileName;
833
47.8k
  bool FileSpecifiedExplicitly = false;
834
835
  // Process options that change search path for config files.
836
47.8k
  if (CLOptions) {
837
47.8k
    if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
838
29
      SmallString<128> CfgDir;
839
29
      CfgDir.append(
840
29
          CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
841
29
      if (!CfgDir.empty()) {
842
21
        if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
843
0
          SystemConfigDir.clear();
844
21
        else
845
21
          SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
846
21
      }
847
29
    }
848
47.8k
    if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
849
29
      SmallString<128> CfgDir;
850
29
      CfgDir.append(
851
29
          CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
852
29
      if (!CfgDir.empty()) {
853
7
        if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
854
0
          UserConfigDir.clear();
855
7
        else
856
7
          UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
857
7
      }
858
29
    }
859
47.8k
  }
860
861
  // First try to find config file specified in command line.
862
47.8k
  if (CLOptions) {
863
47.8k
    std::vector<std::string> ConfigFiles =
864
47.8k
        CLOptions->getAllArgValues(options::OPT_config);
865
47.8k
    if (ConfigFiles.size() > 1) {
866
2
      if (!std::all_of(ConfigFiles.begin(), ConfigFiles.end(),
867
4
                       [ConfigFiles](const std::string &s) {
868
4
                         return s == ConfigFiles[0];
869
1
                       })) {
870
1
        Diag(diag::err_drv_duplicate_config);
871
1
        return true;
872
1
      }
873
47.8k
    }
874
875
47.8k
    if (!ConfigFiles.empty()) {
876
32
      CfgFileName = ConfigFiles.front();
877
32
      assert(!CfgFileName.empty());
878
879
      // If argument contains directory separator, treat it as a path to
880
      // configuration file.
881
32
      if (llvm::sys::path::has_parent_path(CfgFileName)) {
882
9
        SmallString<128> CfgFilePath;
883
9
        if (llvm::sys::path::is_relative(CfgFileName))
884
2
          llvm::sys::fs::current_path(CfgFilePath);
885
9
        llvm::sys::path::append(CfgFilePath, CfgFileName);
886
9
        if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
887
1
          Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
888
1
          return true;
889
1
        }
890
8
        return readConfigFile(CfgFilePath);
891
8
      }
892
893
23
      FileSpecifiedExplicitly = true;
894
23
    }
895
47.8k
  }
896
897
  // If config file is not specified explicitly, try to deduce configuration
898
  // from executable name. For instance, an executable 'armv7l-clang' will
899
  // search for config file 'armv7l-clang.cfg'.
900
47.8k
  if (CfgFileName.empty() && 
!ClangNameParts.TargetPrefix.empty()47.8k
)
901
16
    CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
902
903
47.8k
  if (CfgFileName.empty())
904
47.8k
    return false;
905
906
  // Determine architecture part of the file name, if it is present.
907
45
  StringRef CfgFileArch = CfgFileName;
908
45
  size_t ArchPrefixLen = CfgFileArch.find('-');
909
45
  if (ArchPrefixLen == StringRef::npos)
910
1
    ArchPrefixLen = CfgFileArch.size();
911
45
  llvm::Triple CfgTriple;
912
45
  CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
913
45
  CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
914
45
  if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
915
23
    ArchPrefixLen = 0;
916
917
45
  if (!StringRef(CfgFileName).endswith(".cfg"))
918
33
    CfgFileName += ".cfg";
919
920
  // If config file starts with architecture name and command line options
921
  // redefine architecture (with options like -m32 -LE etc), try finding new
922
  // config file with that architecture.
923
45
  SmallString<128> FixedConfigFile;
924
45
  size_t FixedArchPrefixLen = 0;
925
45
  if (ArchPrefixLen) {
926
    // Get architecture name from config file name like 'i386.cfg' or
927
    // 'armv7l-clang.cfg'.
928
    // Check if command line options changes effective triple.
929
16
    llvm::Triple EffectiveTriple = computeTargetTriple(*this,
930
16
                                             CfgTriple.getTriple(), *CLOptions);
931
16
    if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
932
10
      FixedConfigFile = EffectiveTriple.getArchName();
933
10
      FixedArchPrefixLen = FixedConfigFile.size();
934
      // Append the rest of original file name so that file name transforms
935
      // like: i386-clang.cfg -> x86_64-clang.cfg.
936
10
      if (ArchPrefixLen < CfgFileName.size())
937
10
        FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
938
10
    }
939
16
  }
940
941
  // Prepare list of directories where config file is searched for.
942
45
  StringRef CfgFileSearchDirs[] = {UserConfigDir, SystemConfigDir, Dir};
943
944
  // Try to find config file. First try file with corrected architecture.
945
45
  llvm::SmallString<128> CfgFilePath;
946
45
  if (!FixedConfigFile.empty()) {
947
10
    if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
948
4
      return readConfigFile(CfgFilePath);
949
    // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
950
6
    FixedConfigFile.resize(FixedArchPrefixLen);
951
6
    FixedConfigFile.append(".cfg");
952
6
    if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
953
3
      return readConfigFile(CfgFilePath);
954
38
  }
955
956
  // Then try original file name.
957
38
  if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
958
16
    return readConfigFile(CfgFilePath);
959
960
  // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
961
22
  if (!ClangNameParts.ModeSuffix.empty() &&
962
16
      !ClangNameParts.TargetPrefix.empty()) {
963
12
    CfgFileName.assign(ClangNameParts.TargetPrefix);
964
12
    CfgFileName.append(".cfg");
965
12
    if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
966
1
      return readConfigFile(CfgFilePath);
967
21
  }
968
969
  // Report error but only if config file was specified explicitly, by option
970
  // --config. If it was deduced from executable name, it is not an error.
971
21
  if (FileSpecifiedExplicitly) {
972
4
    Diag(diag::err_drv_config_file_not_found) << CfgFileName;
973
4
    for (const StringRef &SearchDir : CfgFileSearchDirs)
974
12
      if (!SearchDir.empty())
975
8
        Diag(diag::note_drv_config_file_searched_in) << SearchDir;
976
4
    return true;
977
4
  }
978
979
17
  return false;
980
17
}
981
982
47.8k
Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
983
47.8k
  llvm::PrettyStackTraceString CrashInfo("Compilation construction");
984
985
  // FIXME: Handle environment options which affect driver behavior, somewhere
986
  // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
987
988
  // We look for the driver mode option early, because the mode can affect
989
  // how other options are parsed.
990
47.8k
  ParseDriverMode(ClangExecutable, ArgList.slice(1));
991
992
  // FIXME: What are we going to do with -V and -b?
993
994
  // Arguments specified in command line.
995
47.8k
  bool ContainsError;
996
47.8k
  CLOptions = std::make_unique<InputArgList>(
997
47.8k
      ParseArgStrings(ArgList.slice(1), IsCLMode(), ContainsError));
998
999
  // Try parsing configuration file.
1000
47.8k
  if (!ContainsError)
1001
47.8k
    ContainsError = loadConfigFile();
1002
47.8k
  bool HasConfigFile = !ContainsError && 
(CfgOptions.get() != nullptr)47.8k
;
1003
1004
  // All arguments, from both config file and command line.
1005
30
  InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
1006
47.8k
                                              : std::move(*CLOptions));
1007
1008
  // The args for config files or /clang: flags belong to different InputArgList
1009
  // objects than Args. This copies an Arg from one of those other InputArgLists
1010
  // to the ownership of Args.
1011
200
  auto appendOneArg = [&Args](const Arg *Opt, const Arg *BaseArg) {
1012
200
    unsigned Index = Args.MakeIndex(Opt->getSpelling());
1013
200
    Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Args.getArgString(Index),
1014
200
                                   Index, BaseArg);
1015
200
    Copy->getValues() = Opt->getValues();
1016
200
    if (Opt->isClaimed())
1017
62
      Copy->claim();
1018
200
    Copy->setOwnsValues(Opt->getOwnsValues());
1019
200
    Opt->setOwnsValues(false);
1020
200
    Args.append(Copy);
1021
200
  };
1022
1023
47.8k
  if (HasConfigFile)
1024
215
    
for (auto *Opt : *CLOptions)30
{
1025
215
      if (Opt->getOption().matches(options::OPT_config))
1026
26
        continue;
1027
189
      const Arg *BaseArg = &Opt->getBaseArg();
1028
189
      if (BaseArg == Opt)
1029
189
        BaseArg = nullptr;
1030
189
      appendOneArg(Opt, BaseArg);
1031
189
    }
1032
1033
  // In CL mode, look for any pass-through arguments
1034
47.8k
  if (IsCLMode() && 
!ContainsError523
) {
1035
519
    SmallVector<const char *, 16> CLModePassThroughArgList;
1036
12
    for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
1037
12
      A->claim();
1038
12
      CLModePassThroughArgList.push_back(A->getValue());
1039
12
    }
1040
1041
519
    if (!CLModePassThroughArgList.empty()) {
1042
      // Parse any pass through args using default clang processing rather
1043
      // than clang-cl processing.
1044
8
      auto CLModePassThroughOptions = std::make_unique<InputArgList>(
1045
8
          ParseArgStrings(CLModePassThroughArgList, false, ContainsError));
1046
1047
8
      if (!ContainsError)
1048
11
        
for (auto *Opt : *CLModePassThroughOptions)8
{
1049
11
          appendOneArg(Opt, nullptr);
1050
11
        }
1051
8
    }
1052
519
  }
1053
1054
  // Check for working directory option before accessing any files
1055
47.8k
  if (Arg *WD = Args.getLastArg(options::OPT_working_directory))
1056
8
    if (VFS->setCurrentWorkingDirectory(WD->getValue()))
1057
1
      Diag(diag::err_drv_unable_to_set_working_directory) << WD->getValue();
1058
1059
  // FIXME: This stuff needs to go into the Compilation, not the driver.
1060
47.8k
  bool CCCPrintPhases;
1061
1062
  // Silence driver warnings if requested
1063
47.8k
  Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
1064
1065
  // -no-canonical-prefixes is used very early in main.
1066
47.8k
  Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
1067
1068
  // f(no-)integated-cc1 is also used very early in main.
1069
47.8k
  Args.ClaimAllArgs(options::OPT_fintegrated_cc1);
1070
47.8k
  Args.ClaimAllArgs(options::OPT_fno_integrated_cc1);
1071
1072
  // Ignore -pipe.
1073
47.8k
  Args.ClaimAllArgs(options::OPT_pipe);
1074
1075
  // Extract -ccc args.
1076
  //
1077
  // FIXME: We need to figure out where this behavior should live. Most of it
1078
  // should be outside in the client; the parts that aren't should have proper
1079
  // options, either by introducing new ones or by overloading gcc ones like -V
1080
  // or -b.
1081
47.8k
  CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
1082
47.8k
  CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
1083
47.8k
  if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
1084
0
    CCCGenericGCCName = A->getValue();
1085
47.8k
  GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
1086
47.8k
                               options::OPT_fno_crash_diagnostics,
1087
47.8k
                               !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
1088
  // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
1089
  // and getToolChain is const.
1090
47.8k
  if (IsCLMode()) {
1091
    // clang-cl targets MSVC-style Win32.
1092
523
    llvm::Triple T(TargetTriple);
1093
523
    T.setOS(llvm::Triple::Win32);
1094
523
    T.setVendor(llvm::Triple::PC);
1095
523
    T.setEnvironment(llvm::Triple::MSVC);
1096
523
    T.setObjectFormat(llvm::Triple::COFF);
1097
523
    TargetTriple = T.str();
1098
523
  }
1099
47.8k
  if (const Arg *A = Args.getLastArg(options::OPT_target))
1100
27.3k
    TargetTriple = A->getValue();
1101
47.8k
  if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
1102
127
    Dir = InstalledDir = A->getValue();
1103
65
  for (const Arg *A : Args.filtered(options::OPT_B)) {
1104
65
    A->claim();
1105
65
    PrefixDirs.push_back(A->getValue(0));
1106
65
  }
1107
47.8k
  if (Optional<std::string> CompilerPathValue =
1108
4
          llvm::sys::Process::GetEnv("COMPILER_PATH")) {
1109
4
    StringRef CompilerPath = *CompilerPathValue;
1110
8
    while (!CompilerPath.empty()) {
1111
4
      std::pair<StringRef, StringRef> Split =
1112
4
          CompilerPath.split(llvm::sys::EnvPathSeparator);
1113
4
      PrefixDirs.push_back(std::string(Split.first));
1114
4
      CompilerPath = Split.second;
1115
4
    }
1116
4
  }
1117
47.8k
  if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
1118
852
    SysRoot = A->getValue();
1119
47.8k
  if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
1120
3
    DyldPrefix = A->getValue();
1121
1122
47.8k
  if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
1123
1.94k
    ResourceDir = A->getValue();
1124
1125
47.8k
  if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
1126
92
    SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1127
92
                    .Case("cwd", SaveTempsCwd)
1128
92
                    .Case("obj", SaveTempsObj)
1129
92
                    .Default(SaveTempsCwd);
1130
92
  }
1131
1132
47.8k
  setLTOMode(Args);
1133
1134
  // Process -fembed-bitcode= flags.
1135
47.8k
  if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1136
26
    StringRef Name = A->getValue();
1137
26
    unsigned Model = llvm::StringSwitch<unsigned>(Name)
1138
26
        .Case("off", EmbedNone)
1139
26
        .Case("all", EmbedBitcode)
1140
26
        .Case("bitcode", EmbedBitcode)
1141
26
        .Case("marker", EmbedMarker)
1142
26
        .Default(~0U);
1143
26
    if (Model == ~0U) {
1144
0
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1145
0
                                                << Name;
1146
0
    } else
1147
26
      BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
1148
26
  }
1149
1150
47.8k
  std::unique_ptr<llvm::opt::InputArgList> UArgs =
1151
47.8k
      std::make_unique<InputArgList>(std::move(Args));
1152
1153
  // Perform the default argument translations.
1154
47.8k
  DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
1155
1156
  // Owned by the host.
1157
47.8k
  const ToolChain &TC = getToolChain(
1158
47.8k
      *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
1159
1160
  // The compilation takes ownership of Args.
1161
47.8k
  Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1162
47.8k
                                   ContainsError);
1163
1164
47.8k
  if (!HandleImmediateArgs(*C))
1165
1.21k
    return C;
1166
1167
  // Construct the list of inputs.
1168
46.6k
  InputList Inputs;
1169
46.6k
  BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
1170
1171
  // Populate the tool chains for the offloading devices, if any.
1172
46.6k
  CreateOffloadingDeviceToolChains(*C, Inputs);
1173
1174
  // Construct the list of abstract actions to perform for this compilation. On
1175
  // MachO targets this uses the driver-driver and universal actions.
1176
46.6k
  if (TC.getTriple().isOSBinFormatMachO())
1177
21.2k
    BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
1178
25.4k
  else
1179
25.4k
    BuildActions(*C, C->getArgs(), Inputs, C->getActions());
1180
1181
46.6k
  if (CCCPrintPhases) {
1182
64
    PrintActions(*C);
1183
64
    return C;
1184
64
  }
1185
1186
46.6k
  BuildJobs(*C);
1187
1188
46.6k
  return C;
1189
46.6k
}
1190
1191
27
static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1192
27
  llvm::opt::ArgStringList ASL;
1193
27
  for (const auto *A : Args)
1194
220
    A->render(Args, ASL);
1195
1196
364
  for (auto I = ASL.begin(), E = ASL.end(); I != E; 
++I337
) {
1197
337
    if (I != ASL.begin())
1198
310
      OS << ' ';
1199
337
    llvm::sys::printArg(OS, *I, true);
1200
337
  }
1201
27
  OS << '\n';
1202
27
}
1203
1204
bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1205
27
                                    SmallString<128> &CrashDiagDir) {
1206
27
  using namespace llvm::sys;
1207
27
  assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1208
27
         "Only knows about .crash files on Darwin");
1209
1210
  // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1211
  // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1212
  // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1213
27
  path::home_directory(CrashDiagDir);
1214
27
  if (CrashDiagDir.startswith("/var/root"))
1215
0
    CrashDiagDir = "/";
1216
27
  path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1217
27
  int PID =
1218
27
#if LLVM_ON_UNIX
1219
27
      getpid();
1220
#else
1221
      0;
1222
#endif
1223
27
  std::error_code EC;
1224
27
  fs::file_status FileStatus;
1225
27
  TimePoint<> LastAccessTime;
1226
27
  SmallString<128> CrashFilePath;
1227
  // Lookup the .crash files and get the one generated by a subprocess spawned
1228
  // by this driver invocation.
1229
27
  for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1230
135
       File != FileEnd && 
!EC108
;
File.increment(EC)108
) {
1231
108
    StringRef FileName = path::filename(File->path());
1232
108
    if (!FileName.startswith(Name))
1233
108
      continue;
1234
0
    if (fs::status(File->path(), FileStatus))
1235
0
      continue;
1236
0
    llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1237
0
        llvm::MemoryBuffer::getFile(File->path());
1238
0
    if (!CrashFile)
1239
0
      continue;
1240
    // The first line should start with "Process:", otherwise this isn't a real
1241
    // .crash file.
1242
0
    StringRef Data = CrashFile.get()->getBuffer();
1243
0
    if (!Data.startswith("Process:"))
1244
0
      continue;
1245
    // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1246
0
    size_t ParentProcPos = Data.find("Parent Process:");
1247
0
    if (ParentProcPos == StringRef::npos)
1248
0
      continue;
1249
0
    size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1250
0
    if (LineEnd == StringRef::npos)
1251
0
      continue;
1252
0
    StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1253
0
    int OpenBracket = -1, CloseBracket = -1;
1254
0
    for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1255
0
      if (ParentProcess[i] == '[')
1256
0
        OpenBracket = i;
1257
0
      if (ParentProcess[i] == ']')
1258
0
        CloseBracket = i;
1259
0
    }
1260
    // Extract the parent process PID from the .crash file and check whether
1261
    // it matches this driver invocation pid.
1262
0
    int CrashPID;
1263
0
    if (OpenBracket < 0 || CloseBracket < 0 ||
1264
0
        ParentProcess.slice(OpenBracket + 1, CloseBracket)
1265
0
            .getAsInteger(10, CrashPID) || CrashPID != PID) {
1266
0
      continue;
1267
0
    }
1268
1269
    // Found a .crash file matching the driver pid. To avoid getting an older
1270
    // and misleading crash file, continue looking for the most recent.
1271
    // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1272
    // multiple crashes poiting to the same parent process. Since the driver
1273
    // does not collect pid information for the dispatched invocation there's
1274
    // currently no way to distinguish among them.
1275
0
    const auto FileAccessTime = FileStatus.getLastModificationTime();
1276
0
    if (FileAccessTime > LastAccessTime) {
1277
0
      CrashFilePath.assign(File->path());
1278
0
      LastAccessTime = FileAccessTime;
1279
0
    }
1280
0
  }
1281
1282
  // If found, copy it over to the location of other reproducer files.
1283
27
  if (!CrashFilePath.empty()) {
1284
0
    EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1285
0
    if (EC)
1286
0
      return false;
1287
0
    return true;
1288
0
  }
1289
1290
27
  return false;
1291
27
}
1292
1293
// When clang crashes, produce diagnostic information including the fully
1294
// preprocessed source file(s).  Request that the developer attach the
1295
// diagnostic information to a bug report.
1296
void Driver::generateCompilationDiagnostics(
1297
    Compilation &C, const Command &FailingCommand,
1298
30
    StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
1299
30
  if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
1300
0
    return;
1301
1302
  // Don't try to generate diagnostics for link or dsymutil jobs.
1303
30
  if (FailingCommand.getCreator().isLinkJob() ||
1304
30
      FailingCommand.getCreator().isDsymutilJob())
1305
0
    return;
1306
1307
  // Print the version of the compiler.
1308
30
  PrintVersion(C, llvm::errs());
1309
1310
  // Suppress driver output and emit preprocessor output to temp file.
1311
30
  Mode = CPPMode;
1312
30
  CCGenDiagnostics = true;
1313
1314
  // Save the original job command(s).
1315
30
  Command Cmd = FailingCommand;
1316
1317
  // Keep track of whether we produce any errors while trying to produce
1318
  // preprocessed sources.
1319
30
  DiagnosticErrorTrap Trap(Diags);
1320
1321
  // Suppress tool output.
1322
30
  C.initCompilationForDiagnostics();
1323
1324
  // Construct the list of inputs.
1325
30
  InputList Inputs;
1326
30
  BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
1327
1328
63
  for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
1329
33
    bool IgnoreInput = false;
1330
1331
    // Ignore input from stdin or any inputs that cannot be preprocessed.
1332
    // Check type first as not all linker inputs have a value.
1333
33
    if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
1334
2
      IgnoreInput = true;
1335
31
    } else if (!strcmp(it->second->getValue(), "-")) {
1336
0
      Diag(clang::diag::note_drv_command_failed_diag_msg)
1337
0
          << "Error generating preprocessed source(s) - "
1338
0
             "ignoring input from stdin.";
1339
0
      IgnoreInput = true;
1340
0
    }
1341
1342
33
    if (IgnoreInput) {
1343
2
      it = Inputs.erase(it);
1344
2
      ie = Inputs.end();
1345
31
    } else {
1346
31
      ++it;
1347
31
    }
1348
33
  }
1349
1350
30
  if (Inputs.empty()) {
1351
1
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1352
1
        << "Error generating preprocessed source(s) - "
1353
1
           "no preprocessable inputs.";
1354
1
    return;
1355
1
  }
1356
1357
  // Don't attempt to generate preprocessed files if multiple -arch options are
1358
  // used, unless they're all duplicates.
1359
29
  llvm::StringSet<> ArchNames;
1360
252
  for (const Arg *A : C.getArgs()) {
1361
252
    if (A->getOption().matches(options::OPT_arch)) {
1362
0
      StringRef ArchName = A->getValue();
1363
0
      ArchNames.insert(ArchName);
1364
0
    }
1365
252
  }
1366
29
  if (ArchNames.size() > 1) {
1367
0
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1368
0
        << "Error generating preprocessed source(s) - cannot generate "
1369
0
           "preprocessed source with multiple -arch options.";
1370
0
    return;
1371
0
  }
1372
1373
  // Construct the list of abstract actions to perform for this compilation. On
1374
  // Darwin OSes this uses the driver-driver and builds universal actions.
1375
29
  const ToolChain &TC = C.getDefaultToolChain();
1376
29
  if (TC.getTriple().isOSBinFormatMachO())
1377
29
    BuildUniversalActions(C, TC, Inputs);
1378
0
  else
1379
0
    BuildActions(C, C.getArgs(), Inputs, C.getActions());
1380
1381
29
  BuildJobs(C);
1382
1383
  // If there were errors building the compilation, quit now.
1384
29
  if (Trap.hasErrorOccurred()) {
1385
0
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1386
0
        << "Error generating preprocessed source(s).";
1387
0
    return;
1388
0
  }
1389
1390
  // Generate preprocessed output.
1391
29
  SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
1392
29
  C.ExecuteJobs(C.getJobs(), FailingCommands);
1393
1394
  // If any of the preprocessing commands failed, clean up and exit.
1395
29
  if (!FailingCommands.empty()) {
1396
2
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1397
2
        << "Error generating preprocessed source(s).";
1398
2
    return;
1399
2
  }
1400
1401
27
  const ArgStringList &TempFiles = C.getTempFiles();
1402
27
  if (TempFiles.empty()) {
1403
0
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1404
0
        << "Error generating preprocessed source(s).";
1405
0
    return;
1406
0
  }
1407
1408
27
  Diag(clang::diag::note_drv_command_failed_diag_msg)
1409
27
      << "\n********************\n\n"
1410
27
         "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1411
27
         "Preprocessed source(s) and associated run script(s) are located at:";
1412
1413
27
  SmallString<128> VFS;
1414
27
  SmallString<128> ReproCrashFilename;
1415
41
  for (const char *TempFile : TempFiles) {
1416
41
    Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
1417
41
    if (Report)
1418
3
      Report->TemporaryFiles.push_back(TempFile);
1419
41
    if (ReproCrashFilename.empty()) {
1420
27
      ReproCrashFilename = TempFile;
1421
27
      llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1422
27
    }
1423
41
    if (StringRef(TempFile).endswith(".cache")) {
1424
      // In some cases (modules) we'll dump extra data to help with reproducing
1425
      // the crash into a directory next to the output.
1426
14
      VFS = llvm::sys::path::filename(TempFile);
1427
14
      llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1428
14
    }
1429
41
  }
1430
1431
  // Assume associated files are based off of the first temporary file.
1432
27
  CrashReportInfo CrashInfo(TempFiles[0], VFS);
1433
1434
27
  llvm::SmallString<128> Script(CrashInfo.Filename);
1435
27
  llvm::sys::path::replace_extension(Script, "sh");
1436
27
  std::error_code EC;
1437
27
  llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew);
1438
27
  if (EC) {
1439
0
    Diag(clang::diag::note_drv_command_failed_diag_msg)
1440
0
        << "Error generating run script: " << Script << " " << EC.message();
1441
27
  } else {
1442
27
    ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
1443
27
             << "# Driver args: ";
1444
27
    printArgList(ScriptOS, C.getInputArgs());
1445
27
    ScriptOS << "# Original command: ";
1446
27
    Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
1447
27
    Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
1448
27
    if (!AdditionalInformation.empty())
1449
3
      ScriptOS << "\n# Additional information: " << AdditionalInformation
1450
3
               << "\n";
1451
27
    if (Report)
1452
3
      Report->TemporaryFiles.push_back(std::string(Script.str()));
1453
27
    Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
1454
27
  }
1455
1456
  // On darwin, provide information about the .crash diagnostic report.
1457
27
  if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1458
27
    SmallString<128> CrashDiagDir;
1459
27
    if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1460
0
      Diag(clang::diag::note_drv_command_failed_diag_msg)
1461
0
          << ReproCrashFilename.str();
1462
27
    } else { // Suggest a directory for the user to look for .crash files.
1463
27
      llvm::sys::path::append(CrashDiagDir, Name);
1464
27
      CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1465
27
      Diag(clang::diag::note_drv_command_failed_diag_msg)
1466
27
          << "Crash backtrace is located in";
1467
27
      Diag(clang::diag::note_drv_command_failed_diag_msg)
1468
27
          << CrashDiagDir.str();
1469
27
      Diag(clang::diag::note_drv_command_failed_diag_msg)
1470
27
          << "(choose the .crash file that corresponds to your crash)";
1471
27
    }
1472
27
  }
1473
1474
27
  for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1475
27
                                            options::OPT_frewrite_map_file_EQ))
1476
1
    Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1477
1478
27
  Diag(clang::diag::note_drv_command_failed_diag_msg)
1479
27
      << "\n\n********************";
1480
27
}
1481
1482
11.3k
void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1483
  // Since commandLineFitsWithinSystemLimits() may underestimate system's
1484
  // capacity if the tool does not support response files, there is a chance/
1485
  // that things will just work without a response file, so we silently just
1486
  // skip it.
1487
11.3k
  if (Cmd.getResponseFileSupport().ResponseKind ==
1488
11.3k
          ResponseFileSupport::RF_None ||
1489
11.2k
      llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(),
1490
11.2k
                                                   Cmd.getArguments()))
1491
11.3k
    return;
1492
1493
1
  std::string TmpName = GetTemporaryPath("response", "txt");
1494
1
  Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1495
1
}
1496
1497
int Driver::ExecuteCompilation(
1498
    Compilation &C,
1499
20.6k
    SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1500
  // Just print if -### was present.
1501
20.6k
  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1502
8.16k
    C.getJobs().Print(llvm::errs(), "\n", true);
1503
8.16k
    return 0;
1504
8.16k
  }
1505
1506
  // If there were errors building the compilation, quit now.
1507
12.4k
  if (Diags.hasErrorOccurred())
1508
102
    return 1;
1509
1510
  // Set up response file names for each command, if necessary
1511
12.3k
  for (auto &Job : C.getJobs())
1512
11.3k
    setUpResponseFiles(C, Job);
1513
1514
12.3k
  C.ExecuteJobs(C.getJobs(), FailingCommands);
1515
1516
  // If the command succeeded, we are done.
1517
12.3k
  if (FailingCommands.empty())
1518
12.1k
    return 0;
1519
1520
  // Otherwise, remove result files and print extra information about abnormal
1521
  // failures.
1522
246
  int Res = 0;
1523
256
  for (const auto &CmdPair : FailingCommands) {
1524
256
    int CommandRes = CmdPair.first;
1525
256
    const Command *FailingCommand = CmdPair.second;
1526
1527
    // Remove result files if we're not saving temps.
1528
256
    if (!isSaveTempsEnabled()) {
1529
256
      const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1530
256
      C.CleanupFileMap(C.getResultFiles(), JA, true);
1531
1532
      // Failure result files are valid unless we crashed.
1533
256
      if (CommandRes < 0)
1534
0
        C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1535
256
    }
1536
1537
256
#if LLVM_ON_UNIX
1538
    // llvm/lib/Support/Unix/Signals.inc will exit with a special return code
1539
    // for SIGPIPE. Do not print diagnostics for this case.
1540
256
    if (CommandRes == EX_IOERR) {
1541
0
      Res = CommandRes;
1542
0
      continue;
1543
0
    }
1544
256
#endif
1545
1546
    // Print extra information about abnormal failures, if possible.
1547
    //
1548
    // This is ad-hoc, but we don't want to be excessively noisy. If the result
1549
    // status was 1, assume the command failed normally. In particular, if it
1550
    // was the compiler then assume it gave a reasonable error code. Failures
1551
    // in other tools are less common, and they generally have worse
1552
    // diagnostics, so always print the diagnostic there.
1553
256
    const Tool &FailingTool = FailingCommand->getCreator();
1554
1555
256
    if (!FailingCommand->getCreator().hasGoodDiagnostics() || 
CommandRes != 1206
) {
1556
      // FIXME: See FIXME above regarding result code interpretation.
1557
60
      if (CommandRes < 0)
1558
0
        Diag(clang::diag::err_drv_command_signalled)
1559
0
            << FailingTool.getShortName();
1560
60
      else
1561
60
        Diag(clang::diag::err_drv_command_failed)
1562
60
            << FailingTool.getShortName() << CommandRes;
1563
60
    }
1564
256
  }
1565
246
  return Res;
1566
246
}
1567
1568
915
void Driver::PrintHelp(bool ShowHidden) const {
1569
915
  unsigned IncludedFlagsBitmask;
1570
915
  unsigned ExcludedFlagsBitmask;
1571
915
  std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1572
915
      getIncludeExcludeOptionFlagMasks(IsCLMode());
1573
1574
915
  ExcludedFlagsBitmask |= options::NoDriverOption;
1575
915
  if (!ShowHidden)
1576
914
    ExcludedFlagsBitmask |= HelpHidden;
1577
1578
915
  if (IsFlangMode())
1579
0
    IncludedFlagsBitmask |= options::FlangOption;
1580
915
  else
1581
915
    ExcludedFlagsBitmask |= options::FlangOnlyOption;
1582
1583
915
  std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1584
915
  getOpts().PrintHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
1585
915
                      IncludedFlagsBitmask, ExcludedFlagsBitmask,
1586
915
                      /*ShowAllAliases=*/false);
1587
915
}
1588
1589
8.51k
void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1590
8.51k
  if (IsFlangMode()) {
1591
16
    OS << getClangToolFullVersion("flang-new") << '\n';
1592
8.49k
  } else {
1593
    // FIXME: The following handlers should use a callback mechanism, we don't
1594
    // know what the client would like to do.
1595
8.49k
    OS << getClangFullVersion() << '\n';
1596
8.49k
  }
1597
8.51k
  const ToolChain &TC = C.getDefaultToolChain();
1598
8.51k
  OS << "Target: " << TC.getTripleString() << '\n';
1599
1600
  // Print the threading model.
1601
8.51k
  if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1602
    // Don't print if the ToolChain would have barfed on it already
1603
8
    if (TC.isThreadModelSupported(A->getValue()))
1604
6
      OS << "Thread model: " << A->getValue();
1605
8
  } else
1606
8.50k
    OS << "Thread model: " << TC.getThreadModel();
1607
8.51k
  OS << '\n';
1608
1609
  // Print out the install directory.
1610
8.51k
  OS << "InstalledDir: " << InstalledDir << '\n';
1611
1612
  // If configuration file was used, print its path.
1613
8.51k
  if (!ConfigFile.empty())
1614
30
    OS << "Configuration file: " << ConfigFile << '\n';
1615
8.51k
}
1616
1617
/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1618
/// option.
1619
0
static void PrintDiagnosticCategories(raw_ostream &OS) {
1620
  // Skip the empty category.
1621
0
  for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1622
0
       ++i)
1623
0
    OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1624
0
}
1625
1626
38
void Driver::HandleAutocompletions(StringRef PassedFlags) const {
1627
38
  if (PassedFlags == "")
1628
1
    return;
1629
  // Print out all options that start with a given argument. This is used for
1630
  // shell autocompletion.
1631
37
  std::vector<std::string> SuggestedCompletions;
1632
37
  std::vector<std::string> Flags;
1633
1634
37
  unsigned int DisableFlags =
1635
37
      options::NoDriverOption | options::Unsupported | options::Ignored;
1636
1637
  // Make sure that Flang-only options don't pollute the Clang output
1638
  // TODO: Make sure that Clang-only options don't pollute Flang output
1639
37
  if (!IsFlangMode())
1640
37
    DisableFlags |= options::FlangOnlyOption;
1641
1642
  // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
1643
  // because the latter indicates that the user put space before pushing tab
1644
  // which should end up in a file completion.
1645
37
  const bool HasSpace = PassedFlags.endswith(",");
1646
1647
  // Parse PassedFlags by "," as all the command-line flags are passed to this
1648
  // function separated by ","
1649
37
  StringRef TargetFlags = PassedFlags;
1650
89
  while (TargetFlags != "") {
1651
52
    StringRef CurFlag;
1652
52
    std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1653
52
    Flags.push_back(std::string(CurFlag));
1654
52
  }
1655
1656
  // We want to show cc1-only options only when clang is invoked with -cc1 or
1657
  // -Xclang.
1658
37
  if (llvm::is_contained(Flags, "-Xclang") || 
llvm::is_contained(Flags, "-cc1")36
)
1659
2
    DisableFlags &= ~options::NoDriverOption;
1660
1661
37
  const llvm::opt::OptTable &Opts = getOpts();
1662
37
  StringRef Cur;
1663
37
  Cur = Flags.at(Flags.size() - 1);
1664
37
  StringRef Prev;
1665
37
  if (Flags.size() >= 2) {
1666
9
    Prev = Flags.at(Flags.size() - 2);
1667
9
    SuggestedCompletions = Opts.suggestValueCompletions(Prev, Cur);
1668
9
  }
1669
1670
37
  if (SuggestedCompletions.empty())
1671
32
    SuggestedCompletions = Opts.suggestValueCompletions(Cur, "");
1672
1673
  // If Flags were empty, it means the user typed `clang [tab]` where we should
1674
  // list all possible flags. If there was no value completion and the user
1675
  // pressed tab after a space, we should fall back to a file completion.
1676
  // We're printing a newline to be consistent with what we print at the end of
1677
  // this function.
1678
37
  if (SuggestedCompletions.empty() && 
HasSpace17
&&
!Flags.empty()3
) {
1679
3
    llvm::outs() << '\n';
1680
3
    return;
1681
3
  }
1682
1683
  // When flag ends with '=' and there was no value completion, return empty
1684
  // string and fall back to the file autocompletion.
1685
34
  if (SuggestedCompletions.empty() && 
!Cur.endswith("=")14
) {
1686
    // If the flag is in the form of "--autocomplete=-foo",
1687
    // we were requested to print out all option names that start with "-foo".
1688
    // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
1689
12
    SuggestedCompletions = Opts.findByPrefix(Cur, DisableFlags);
1690
1691
    // We have to query the -W flags manually as they're not in the OptTable.
1692
    // TODO: Find a good way to add them to OptTable instead and them remove
1693
    // this code.
1694
12
    for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
1695
20.8k
      if (S.startswith(Cur))
1696
1.74k
        SuggestedCompletions.push_back(std::string(S));
1697
12
  }
1698
1699
  // Sort the autocomplete candidates so that shells print them out in a
1700
  // deterministic order. We could sort in any way, but we chose
1701
  // case-insensitive sorting for consistency with the -help option
1702
  // which prints out options in the case-insensitive alphabetical order.
1703
47.0k
  llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
1704
47.0k
    if (int X = A.compare_lower(B))
1705
45.8k
      return X < 0;
1706
1.23k
    return A.compare(B) > 0;
1707
1.23k
  });
1708
1709
34
  llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1710
34
}
1711
1712
47.8k
bool Driver::HandleImmediateArgs(const Compilation &C) {
1713
  // The order these options are handled in gcc is all over the place, but we
1714
  // don't expect inconsistencies w.r.t. that to matter in practice.
1715
1716
47.8k
  if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1717
0
    llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1718
0
    return false;
1719
0
  }
1720
1721
47.8k
  if (C.getArgs().hasArg(options::OPT_dumpversion)) {
1722
    // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1723
    // return an answer which matches our definition of __VERSION__.
1724
1
    llvm::outs() << CLANG_VERSION_STRING << "\n";
1725
1
    return false;
1726
1
  }
1727
1728
47.8k
  if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1729
0
    PrintDiagnosticCategories(llvm::outs());
1730
0
    return false;
1731
0
  }
1732
1733
47.8k
  if (C.getArgs().hasArg(options::OPT_help) ||
1734
46.9k
      C.getArgs().hasArg(options::OPT__help_hidden)) {
1735
915
    PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
1736
915
    return false;
1737
915
  }
1738
1739
46.9k
  if (C.getArgs().hasArg(options::OPT__version)) {
1740
    // Follow gcc behavior and use stdout for --version and stderr for -v.
1741
191
    PrintVersion(C, llvm::outs());
1742
191
    return false;
1743
191
  }
1744
1745
46.7k
  if (C.getArgs().hasArg(options::OPT_v) ||
1746
46.5k
      C.getArgs().hasArg(options::OPT__HASH_HASH_HASH) ||
1747
38.5k
      C.getArgs().hasArg(options::OPT_print_supported_cpus)) {
1748
8.29k
    PrintVersion(C, llvm::errs());
1749
8.29k
    SuppressMissingInputWarning = true;
1750
8.29k
  }
1751
1752
46.7k
  if (C.getArgs().hasArg(options::OPT_v)) {
1753
204
    if (!SystemConfigDir.empty())
1754
4
      llvm::errs() << "System configuration file directory: "
1755
4
                   << SystemConfigDir << "\n";
1756
204
    if (!UserConfigDir.empty())
1757
3
      llvm::errs() << "User configuration file directory: "
1758
3
                   << UserConfigDir << "\n";
1759
204
  }
1760
1761
46.7k
  const ToolChain &TC = C.getDefaultToolChain();
1762
1763
46.7k
  if (C.getArgs().hasArg(options::OPT_v))
1764
204
    TC.printVerboseInfo(llvm::errs());
1765
1766
46.7k
  if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
1767
1
    llvm::outs() << ResourceDir << '\n';
1768
1
    return false;
1769
1
  }
1770
1771
46.7k
  if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1772
4
    llvm::outs() << "programs: =";
1773
4
    bool separator = false;
1774
    // Print -B and COMPILER_PATH.
1775
5
    for (const std::string &Path : PrefixDirs) {
1776
5
      if (separator)
1777
3
        llvm::outs() << llvm::sys::EnvPathSeparator;
1778
5
      llvm::outs() << Path;
1779
5
      separator = true;
1780
5
    }
1781
4
    for (const std::string &Path : TC.getProgramPaths()) {
1782
4
      if (separator)
1783
2
        llvm::outs() << llvm::sys::EnvPathSeparator;
1784
4
      llvm::outs() << Path;
1785
4
      separator = true;
1786
4
    }
1787
4
    llvm::outs() << "\n";
1788
4
    llvm::outs() << "libraries: =" << ResourceDir;
1789
1790
4
    StringRef sysroot = C.getSysRoot();
1791
1792
5
    for (const std::string &Path : TC.getFilePaths()) {
1793
      // Always print a separator. ResourceDir was the first item shown.
1794
5
      llvm::outs() << llvm::sys::EnvPathSeparator;
1795
      // Interpretation of leading '=' is needed only for NetBSD.
1796
5
      if (Path[0] == '=')
1797
0
        llvm::outs() << sysroot << Path.substr(1);
1798
5
      else
1799
5
        llvm::outs() << Path;
1800
5
    }
1801
4
    llvm::outs() << "\n";
1802
4
    return false;
1803
4
  }
1804
1805
  // FIXME: The following handlers should use a callback mechanism, we don't
1806
  // know what the client would like to do.
1807
46.7k
  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
1808
30
    llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
1809
30
    return false;
1810
30
  }
1811
1812
46.7k
  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
1813
1
    StringRef ProgName = A->getValue();
1814
1815
    // Null program name cannot have a path.
1816
1
    if (! ProgName.empty())
1817
0
      llvm::outs() << GetProgramPath(ProgName, TC);
1818
1819
1
    llvm::outs() << "\n";
1820
1
    return false;
1821
1
  }
1822
1823
46.7k
  if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
1824
38
    StringRef PassedFlags = A->getValue();
1825
38
    HandleAutocompletions(PassedFlags);
1826
38
    return false;
1827
38
  }
1828
1829
46.7k
  if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
1830
12
    ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1831
12
    const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1832
12
    RegisterEffectiveTriple TripleRAII(TC, Triple);
1833
12
    switch (RLT) {
1834
11
    case ToolChain::RLT_CompilerRT:
1835
11
      llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1836
11
      break;
1837
1
    case ToolChain::RLT_Libgcc:
1838
1
      llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1839
1
      break;
1840
12
    }
1841
12
    return false;
1842
12
  }
1843
1844
46.7k
  if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
1845
1
    for (const Multilib &Multilib : TC.getMultilibs())
1846
4
      llvm::outs() << Multilib << "\n";
1847
1
    return false;
1848
1
  }
1849
1850
46.7k
  if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
1851
3
    const Multilib &Multilib = TC.getMultilib();
1852
3
    if (Multilib.gccSuffix().empty())
1853
1
      llvm::outs() << ".\n";
1854
2
    else {
1855
2
      StringRef Suffix(Multilib.gccSuffix());
1856
2
      assert(Suffix.front() == '/');
1857
2
      llvm::outs() << Suffix.substr(1) << "\n";
1858
2
    }
1859
3
    return false;
1860
3
  }
1861
1862
46.7k
  if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
1863
5
    llvm::outs() << TC.getTripleString() << "\n";
1864
5
    return false;
1865
5
  }
1866
1867
46.6k
  if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
1868
14
    const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1869
14
    llvm::outs() << Triple.getTriple() << "\n";
1870
14
    return false;
1871
14
  }
1872
1873
46.6k
  if (C.getArgs().hasArg(options::OPT_print_targets)) {
1874
0
    llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
1875
0
    return false;
1876
0
  }
1877
1878
46.6k
  return true;
1879
46.6k
}
1880
1881
enum {
1882
  TopLevelAction = 0,
1883
  HeadSibAction = 1,
1884
  OtherSibAction = 2,
1885
};
1886
1887
// Display an action graph human-readably.  Action A is the "sink" node
1888
// and latest-occuring action. Traversal is in pre-order, visiting the
1889
// inputs to each action before printing the action itself.
1890
static unsigned PrintActions1(const Compilation &C, Action *A,
1891
                              std::map<Action *, unsigned> &Ids,
1892
767
                              Twine Indent = {}, int Kind = TopLevelAction) {
1893
767
  if (Ids.count(A)) // A was already visited.
1894
35
    return Ids[A];
1895
1896
732
  std::string str;
1897
732
  llvm::raw_string_ostream os(str);
1898
1899
732
  auto getSibIndent = [](int K) -> Twine {
1900
575
    return (K == HeadSibAction) ? "   " : 
(K == OtherSibAction) 157
?
"| "85
:
""72
;
1901
732
  };
1902
1903
732
  Twine SibIndent = Indent + getSibIndent(Kind);
1904
732
  int SibKind = HeadSibAction;
1905
732
  os << Action::getClassName(A->getKind()) << ", ";
1906
732
  if (InputAction *IA = dyn_cast<InputAction>(A)) {
1907
124
    os << "\"" << IA->getInputArg().getValue() << "\"";
1908
608
  } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1909
22
    os << '"' << BIA->getArchName() << '"' << ", {"
1910
22
       << PrintActions1(C, *BIA->input_begin(), Ids, SibIndent, SibKind) << "}";
1911
586
  } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1912
93
    bool IsFirst = true;
1913
93
    OA->doOnEachDependence(
1914
120
        [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1915
120
          assert(TC && "Unknown host toolchain");
1916
          // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1917
          // sm_35 this will generate:
1918
          // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1919
          // (nvptx64-nvidia-cuda:sm_35) {#ID}
1920
120
          if (!IsFirst)
1921
27
            os << ", ";
1922
120
          os << '"';
1923
120
          os << A->getOffloadingKindPrefix();
1924
120
          os << " (";
1925
120
          os << TC->getTriple().normalize();
1926
120
          if (BoundArch)
1927
50
            os << ":" << BoundArch;
1928
120
          os << ")";
1929
120
          os << '"';
1930
120
          os << " {" << PrintActions1(C, A, Ids, SibIndent, SibKind) << "}";
1931
120
          IsFirst = false;
1932
120
          SibKind = OtherSibAction;
1933
120
        });
1934
493
  } else {
1935
493
    const ActionList *AL = &A->getInputs();
1936
1937
493
    if (AL->size()) {
1938
493
      const char *Prefix = "{";
1939
553
      for (Action *PreRequisite : *AL) {
1940
553
        os << Prefix << PrintActions1(C, PreRequisite, Ids, SibIndent, SibKind);
1941
553
        Prefix = ", ";
1942
553
        SibKind = OtherSibAction;
1943
553
      }
1944
493
      os << "}";
1945
493
    } else
1946
0
      os << "{}";
1947
493
  }
1948
1949
  // Append offload info for all options other than the offloading action
1950
  // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1951
732
  std::string offload_str;
1952
732
  llvm::raw_string_ostream offload_os(offload_str);
1953
732
  if (!isa<OffloadAction>(A)) {
1954
639
    auto S = A->getOffloadingKindPrefix();
1955
639
    if (!S.empty()) {
1956
502
      offload_os << ", (" << S;
1957
502
      if (A->getOffloadingArch())
1958
190
        offload_os << ", " << A->getOffloadingArch();
1959
502
      offload_os << ")";
1960
502
    }
1961
639
  }
1962
1963
732
  auto getSelfIndent = [](int K) -> Twine {
1964
575
    return (K == HeadSibAction) ? "+- " : 
(K == OtherSibAction) 157
?
"|- "85
:
""72
;
1965
732
  };
1966
1967
732
  unsigned Id = Ids.size();
1968
732
  Ids[A] = Id;
1969
732
  llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", "
1970
732
               << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1971
1972
732
  return Id;
1973
732
}
1974
1975
// Print the action graphs in a compilation C.
1976
// For example "clang -c file1.c file2.c" is composed of two subgraphs.
1977
64
void Driver::PrintActions(const Compilation &C) const {
1978
64
  std::map<Action *, unsigned> Ids;
1979
64
  for (Action *A : C.getActions())
1980
72
    PrintActions1(C, A, Ids);
1981
64
}
1982
1983
/// Check whether the given input tree contains any compilation or
1984
/// assembly actions.
1985
25.0k
static bool ContainsCompileOrAssembleAction(const Action *A) {
1986
25.0k
  if (isa<CompileJobAction>(A) || 
isa<BackendJobAction>(A)25.0k
||
1987
24.9k
      isa<AssembleJobAction>(A))
1988
3.39k
    return true;
1989
1990
21.6k
  for (const Action *Input : A->inputs())
1991
16.1k
    if (ContainsCompileOrAssembleAction(Input))
1992
3.49k
      return true;
1993
1994
18.2k
  return false;
1995
21.6k
}
1996
1997
void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1998
21.3k
                                   const InputList &BAInputs) const {
1999
21.3k
  DerivedArgList &Args = C.getArgs();
2000
21.3k
  ActionList &Actions = C.getActions();
2001
21.3k
  llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
2002
  // Collect the list of architectures. Duplicates are allowed, but should only
2003
  // be handled once (in the order seen).
2004
21.3k
  llvm::StringSet<> ArchNames;
2005
21.3k
  SmallVector<const char *, 4> Archs;
2006
547k
  for (Arg *A : Args) {
2007
547k
    if (A->getOption().matches(options::OPT_arch)) {
2008
      // Validate the option here; we don't save the type here because its
2009
      // particular spelling may participate in other driver choices.
2010
8.84k
      llvm::Triple::ArchType Arch =
2011
8.84k
          tools::darwin::getArchTypeForMachOArchName(A->getValue());
2012
8.84k
      if (Arch == llvm::Triple::UnknownArch) {
2013
0
        Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
2014
0
        continue;
2015
0
      }
2016
2017
8.84k
      A->claim();
2018
8.84k
      if (ArchNames.insert(A->getValue()).second)
2019
8.83k
        Archs.push_back(A->getValue());
2020
8.84k
    }
2021
547k
  }
2022
2023
  // When there is no explicit arch for this platform, make sure we still bind
2024
  // the architecture (to the default) so that -Xarch_ is handled correctly.
2025
21.3k
  if (!Archs.size())
2026
12.4k
    Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
2027
2028
21.3k
  ActionList SingleActions;
2029
21.3k
  BuildActions(C, Args, BAInputs, SingleActions);
2030
2031
  // Add in arch bindings for every top level action, as well as lipo and
2032
  // dsymutil steps if needed.
2033
21.3k
  for (Action* Act : SingleActions) {
2034
    // Make sure we can lipo this kind of output. If not (and it is an actual
2035
    // output) then we disallow, since we can't create an output file with the
2036
    // right name without overwriting it. We could remove this oddity by just
2037
    // changing the output names to include the arch, which would also fix
2038
    // -save-temps. Compatibility wins for now.
2039
2040
21.3k
    if (Archs.size() > 1 && 
!types::canLipoType(Act->getType())16
)
2041
0
      Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
2042
0
          << types::getTypeName(Act->getType());
2043
2044
21.3k
    ActionList Inputs;
2045
42.6k
    for (unsigned i = 0, e = Archs.size(); i != e; 
++i21.3k
)
2046
21.3k
      Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
2047
2048
    // Lipo if necessary, we do it this way because we need to set the arch flag
2049
    // so that -Xarch_ gets overwritten.
2050
21.3k
    if (Inputs.size() == 1 || 
Act->getType() == types::TY_Nothing16
)
2051
21.2k
      Actions.append(Inputs.begin(), Inputs.end());
2052
17
    else
2053
17
      Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
2054
2055
    // Handle debug info queries.
2056
21.3k
    Arg *A = Args.getLastArg(options::OPT_g_Group);
2057
21.3k
    bool enablesDebugInfo = A && 
!A->getOption().matches(options::OPT_g0)8.99k
&&
2058
8.96k
                            !A->getOption().matches(options::OPT_gstabs);
2059
21.3k
    if ((enablesDebugInfo || 
willEmitRemarks(Args)12.3k
) &&
2060
8.98k
        ContainsCompileOrAssembleAction(Actions.back())) {
2061
2062
      // Add a 'dsymutil' step if necessary, when debug info is enabled and we
2063
      // have a compile input. We need to run 'dsymutil' ourselves in such cases
2064
      // because the debug info will refer to a temporary object file which
2065
      // will be removed at the end of the compilation process.
2066
3.39k
      if (Act->getType() == types::TY_Image) {
2067
91
        ActionList Inputs;
2068
91
        Inputs.push_back(Actions.back());
2069
91
        Actions.pop_back();
2070
91
        Actions.push_back(
2071
91
            C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
2072
91
      }
2073
2074
      // Verify the debug info output.
2075
3.39k
      if (Args.hasArg(options::OPT_verify_debug_info)) {
2076
3
        Action* LastAction = Actions.back();
2077
3
        Actions.pop_back();
2078
3
        Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
2079
3
            LastAction, types::TY_Nothing));
2080
3
      }
2081
3.39k
    }
2082
21.3k
  }
2083
21.3k
}
2084
2085
bool Driver::DiagnoseInputExistence(const DerivedArgList &Args, StringRef Value,
2086
47.1k
                                    types::ID Ty, bool TypoCorrect) const {
2087
47.1k
  if (!getCheckInputsExist())
2088
4.70k
    return true;
2089
2090
  // stdin always exists.
2091
42.4k
  if (Value == "-")
2092
192
    return true;
2093
2094
42.2k
  if (getVFS().exists(Value))
2095
42.2k
    return true;
2096
2097
22
  if (IsCLMode()) {
2098
11
    if (!llvm::sys::path::is_absolute(Twine(Value)) &&
2099
8
        llvm::sys::Process::FindInEnvPath("LIB", Value, ';'))
2100
3
      return true;
2101
2102
8
    if (Args.hasArg(options::OPT__SLASH_link) && 
Ty == types::TY_Object2
) {
2103
      // Arguments to the /link flag might cause the linker to search for object
2104
      // and library files in paths we don't know about. Don't error in such
2105
      // cases.
2106
2
      return true;
2107
2
    }
2108
17
  }
2109
2110
20
  
if (17
TypoCorrect17
) {
2111
    // Check if the filename is a typo for an option flag. OptTable thinks
2112
    // that all args that are not known options and that start with / are
2113
    // filenames, but e.g. `/diagnostic:caret` is more likely a typo for
2114
    // the option `/diagnostics:caret` than a reference to a file in the root
2115
    // directory.
2116
20
    unsigned IncludedFlagsBitmask;
2117
20
    unsigned ExcludedFlagsBitmask;
2118
20
    std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
2119
20
        getIncludeExcludeOptionFlagMasks(IsCLMode());
2120
20
    std::string Nearest;
2121
20
    if (getOpts().findNearest(Value, Nearest, IncludedFlagsBitmask,
2122
2
                              ExcludedFlagsBitmask) <= 1) {
2123
2
      Diag(clang::diag::err_drv_no_such_file_with_suggestion)
2124
2
          << Value << Nearest;
2125
2
      return false;
2126
2
    }
2127
15
  }
2128
2129
15
  Diag(clang::diag::err_drv_no_such_file) << Value;
2130
15
  return false;
2131
15
}
2132
2133
// Construct a the list of inputs and their types.
2134
void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
2135
46.7k
                         InputList &Inputs) const {
2136
46.7k
  const llvm::opt::OptTable &Opts = getOpts();
2137
  // Track the current user specified (-x) input. We also explicitly track the
2138
  // argument used to set the type; we only want to claim the type when we
2139
  // actually use it, so we warn about unused -x arguments.
2140
46.7k
  types::ID InputType = types::TY_Nothing;
2141
46.7k
  Arg *InputTypeArg = nullptr;
2142
2143
  // The last /TC or /TP option sets the input type to C or C++ globally.
2144
46.7k
  if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
2145
19
                                         options::OPT__SLASH_TP)) {
2146
19
    InputTypeArg = TCTP;
2147
19
    InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
2148
5
                    ? types::TY_C
2149
14
                    : types::TY_CXX;
2150
2151
19
    Arg *Previous = nullptr;
2152
19
    bool ShowNote = false;
2153
19
    for (Arg *A :
2154
21
         Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
2155
21
      if (Previous) {
2156
2
        Diag(clang::diag::warn_drv_overriding_flag_option)
2157
2
          << Previous->getSpelling() << A->getSpelling();
2158
2
        ShowNote = true;
2159
2
      }
2160
21
      Previous = A;
2161
21
    }
2162
19
    if (ShowNote)
2163
1
      Diag(clang::diag::note_drv_t_option_is_global);
2164
2165
    // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
2166
19
    assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
2167
19
  }
2168
2169
782k
  for (Arg *A : Args) {
2170
782k
    if (A->getOption().getKind() == Option::InputClass) {
2171
47.1k
      const char *Value = A->getValue();
2172
47.1k
      types::ID Ty = types::TY_INVALID;
2173
2174
      // Infer the input type if necessary.
2175
47.1k
      if (InputType == types::TY_Nothing) {
2176
        // If there was an explicit arg for this, claim it.
2177
42.6k
        if (InputTypeArg)
2178
1
          InputTypeArg->claim();
2179
2180
        // stdin must be handled specially.
2181
42.6k
        if (memcmp(Value, "-", 2) == 0) {
2182
          // If running with -E, treat as a C input (this changes the builtin
2183
          // macros, for example). This may be overridden by -ObjC below.
2184
          //
2185
          // Otherwise emit an error but still use a valid type to avoid
2186
          // spurious errors (e.g., no inputs).
2187
10
          if (!Args.hasArgNoClaim(options::OPT_E) && 
!CCCIsCPP()1
)
2188
1
            Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2189
0
                            : clang::diag::err_drv_unknown_stdin_type);
2190
10
          Ty = types::TY_C;
2191
42.6k
        } else {
2192
          // Otherwise lookup by extension.
2193
          // Fallback is C if invoked as C preprocessor, C++ if invoked with
2194
          // clang-cl /E, or Object otherwise.
2195
          // We use a host hook here because Darwin at least has its own
2196
          // idea of what .s is.
2197
42.6k
          if (const char *Ext = strrchr(Value, '.'))
2198
42.5k
            Ty = TC.LookupTypeForExtension(Ext + 1);
2199
2200
42.6k
          if (Ty == types::TY_INVALID) {
2201
67
            if (CCCIsCPP())
2202
0
              Ty = types::TY_C;
2203
67
            else if (IsCLMode() && 
Args.hasArgNoClaim(options::OPT_E)6
)
2204
1
              Ty = types::TY_CXX;
2205
66
            else
2206
66
              Ty = types::TY_Object;
2207
67
          }
2208
2209
          // If the driver is invoked as C++ compiler (like clang++ or c++) it
2210
          // should autodetect some input files as C++ for g++ compatibility.
2211
42.6k
          if (CCCIsCXX()) {
2212
6.88k
            types::ID OldTy = Ty;
2213
6.88k
            Ty = types::lookupCXXTypeForCType(Ty);
2214
2215
6.88k
            if (Ty != OldTy)
2216
75
              Diag(clang::diag::warn_drv_treating_input_as_cxx)
2217
75
                  << getTypeName(OldTy) << getTypeName(Ty);
2218
6.88k
          }
2219
2220
          // If running with -fthinlto-index=, extensions that normally identify
2221
          // native object files actually identify LLVM bitcode files.
2222
42.6k
          if (Args.hasArgNoClaim(options::OPT_fthinlto_index_EQ) &&
2223
4
              Ty == types::TY_Object)
2224
2
            Ty = types::TY_LLVM_BC;
2225
42.6k
        }
2226
2227
        // -ObjC and -ObjC++ override the default language, but only for "source
2228
        // files". We just treat everything that isn't a linker input as a
2229
        // source file.
2230
        //
2231
        // FIXME: Clean this up if we move the phase sequence into the type.
2232
42.6k
        if (Ty != types::TY_Object) {
2233
39.2k
          if (Args.hasArg(options::OPT_ObjC))
2234
21
            Ty = types::TY_ObjC;
2235
39.2k
          else if (Args.hasArg(options::OPT_ObjCXX))
2236
1
            Ty = types::TY_ObjCXX;
2237
39.2k
        }
2238
4.53k
      } else {
2239
4.53k
        assert(InputTypeArg && "InputType set w/o InputTypeArg");
2240
4.53k
        if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2241
          // If emulating cl.exe, make sure that /TC and /TP don't affect input
2242
          // object files.
2243
19
          const char *Ext = strrchr(Value, '.');
2244
19
          if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2245
2
            Ty = types::TY_Object;
2246
19
        }
2247
4.53k
        if (Ty == types::TY_INVALID) {
2248
4.52k
          Ty = InputType;
2249
4.52k
          InputTypeArg->claim();
2250
4.52k
        }
2251
4.53k
      }
2252
2253
47.1k
      if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true))
2254
47.1k
        Inputs.push_back(std::make_pair(Ty, A));
2255
2256
735k
    } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2257
16
      StringRef Value = A->getValue();
2258
16
      if (DiagnoseInputExistence(Args, Value, types::TY_C,
2259
16
                                 /*TypoCorrect=*/false)) {
2260
16
        Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2261
16
        Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2262
16
      }
2263
16
      A->claim();
2264
735k
    } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2265
2
      StringRef Value = A->getValue();
2266
2
      if (DiagnoseInputExistence(Args, Value, types::TY_CXX,
2267
2
                                 /*TypoCorrect=*/false)) {
2268
2
        Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2269
2
        Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2270
2
      }
2271
2
      A->claim();
2272
735k
    } else if (A->getOption().hasFlag(options::LinkerInput)) {
2273
      // Just treat as object type, we could make a special type for this if
2274
      // necessary.
2275
1.15k
      Inputs.push_back(std::make_pair(types::TY_Object, A));
2276
2277
734k
    } else if (A->getOption().matches(options::OPT_x)) {
2278
4.51k
      InputTypeArg = A;
2279
4.51k
      InputType = types::lookupTypeForTypeSpecifier(A->getValue());
2280
4.51k
      A->claim();
2281
2282
      // Follow gcc behavior and treat as linker input for invalid -x
2283
      // options. Its not clear why we shouldn't just revert to unknown; but
2284
      // this isn't very important, we might as well be bug compatible.
2285
4.51k
      if (!InputType) {
2286
0
        Diag(clang::diag::err_drv_unknown_language) << A->getValue();
2287
0
        InputType = types::TY_Object;
2288
0
      }
2289
729k
    } else if (A->getOption().getID() == options::OPT_U) {
2290
9
      assert(A->getNumValues() == 1 && "The /U option has one value.");
2291
9
      StringRef Val = A->getValue(0);
2292
9
      if (Val.find_first_of("/\\") != StringRef::npos) {
2293
        // Warn about e.g. "/Users/me/myfile.c".
2294
2
        Diag(diag::warn_slash_u_filename) << Val;
2295
2
        Diag(diag::note_use_dashdash);
2296
2
      }
2297
9
    }
2298
782k
  }
2299
46.7k
  if (CCCIsCPP() && 
Inputs.empty()33
) {
2300
    // If called as standalone preprocessor, stdin is processed
2301
    // if no other input is present.
2302
0
    Arg *A = MakeInputArg(Args, Opts, "-");
2303
0
    Inputs.push_back(std::make_pair(types::TY_C, A));
2304
0
  }
2305
46.7k
}
2306
2307
namespace {
2308
/// Provides a convenient interface for different programming models to generate
2309
/// the required device actions.
2310
class OffloadingActionBuilder final {
2311
  /// Flag used to trace errors in the builder.
2312
  bool IsValid = false;
2313
2314
  /// The compilation that is using this builder.
2315
  Compilation &C;
2316
2317
  /// Map between an input argument and the offload kinds used to process it.
2318
  std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2319
2320
  /// Builder interface. It doesn't build anything or keep any state.
2321
  class DeviceActionBuilder {
2322
  public:
2323
    typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy;
2324
2325
    enum ActionBuilderReturnCode {
2326
      // The builder acted successfully on the current action.
2327
      ABRT_Success,
2328
      // The builder didn't have to act on the current action.
2329
      ABRT_Inactive,
2330
      // The builder was successful and requested the host action to not be
2331
      // generated.
2332
      ABRT_Ignore_Host,
2333
    };
2334
2335
  protected:
2336
    /// Compilation associated with this builder.
2337
    Compilation &C;
2338
2339
    /// Tool chains associated with this builder. The same programming
2340
    /// model may have associated one or more tool chains.
2341
    SmallVector<const ToolChain *, 2> ToolChains;
2342
2343
    /// The derived arguments associated with this builder.
2344
    DerivedArgList &Args;
2345
2346
    /// The inputs associated with this builder.
2347
    const Driver::InputList &Inputs;
2348
2349
    /// The associated offload kind.
2350
    Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2351
2352
  public:
2353
    DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2354
                        const Driver::InputList &Inputs,
2355
                        Action::OffloadKind AssociatedOffloadKind)
2356
        : C(C), Args(Args), Inputs(Inputs),
2357
140k
          AssociatedOffloadKind(AssociatedOffloadKind) {}
2358
140k
    virtual ~DeviceActionBuilder() {}
2359
2360
    /// Fill up the array \a DA with all the device dependences that should be
2361
    /// added to the provided host action \a HostAction. By default it is
2362
    /// inactive.
2363
    virtual ActionBuilderReturnCode
2364
    getDeviceDependences(OffloadAction::DeviceDependences &DA,
2365
                         phases::ID CurPhase, phases::ID FinalPhase,
2366
0
                         PhasesTy &Phases) {
2367
0
      return ABRT_Inactive;
2368
0
    }
2369
2370
    /// Update the state to include the provided host action \a HostAction as a
2371
    /// dependency of the current device action. By default it is inactive.
2372
0
    virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2373
0
      return ABRT_Inactive;
2374
0
    }
2375
2376
    /// Append top level actions generated by the builder.
2377
0
    virtual void appendTopLevelActions(ActionList &AL) {}
2378
2379
    /// Append linker device actions generated by the builder.
2380
78
    virtual void appendLinkDeviceActions(ActionList &AL) {}
2381
2382
    /// Append linker host action generated by the builder.
2383
1
    virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; }
2384
2385
    /// Append linker actions generated by the builder.
2386
78
    virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2387
2388
    /// Initialize the builder. Return true if any initialization errors are
2389
    /// found.
2390
0
    virtual bool initialize() { return false; }
2391
2392
    /// Return true if the builder can use bundling/unbundling.
2393
295
    virtual bool canUseBundlerUnbundler() const { return false; }
2394
2395
    /// Return true if this builder is valid. We have a valid builder if we have
2396
    /// associated device tool chains.
2397
1.12M
    bool isValid() { return !ToolChains.empty(); }
2398
2399
    /// Return the associated offload kind.
2400
4.45k
    Action::OffloadKind getAssociatedOffloadKind() {
2401
4.45k
      return AssociatedOffloadKind;
2402
4.45k
    }
2403
  };
2404
2405
  /// Base class for CUDA/HIP action builder. It injects device code in
2406
  /// the host backend action.
2407
  class CudaActionBuilderBase : public DeviceActionBuilder {
2408
  protected:
2409
    /// Flags to signal if the user requested host-only or device-only
2410
    /// compilation.
2411
    bool CompileHostOnly = false;
2412
    bool CompileDeviceOnly = false;
2413
    bool EmitLLVM = false;
2414
    bool EmitAsm = false;
2415
2416
    /// ID to identify each device compilation. For CUDA it is simply the
2417
    /// GPU arch string. For HIP it is either the GPU arch string or GPU
2418
    /// arch string plus feature strings delimited by a plus sign, e.g.
2419
    /// gfx906+xnack.
2420
    struct TargetID {
2421
      /// Target ID string which is persistent throughout the compilation.
2422
      const char *ID;
2423
145
      TargetID(CudaArch Arch) { ID = CudaArchToString(Arch); }
2424
452
      TargetID(const char *ID) : ID(ID) {}
2425
759
      operator const char *() { return ID; }
2426
34
      operator StringRef() { return StringRef(ID); }
2427
    };
2428
    /// List of GPU architectures to use in this compilation.
2429
    SmallVector<TargetID, 4> GpuArchList;
2430
2431
    /// The CUDA actions for the current input.
2432
    ActionList CudaDeviceActions;
2433
2434
    /// The CUDA fat binary if it was generated for the current input.
2435
    Action *CudaFatBinary = nullptr;
2436
2437
    /// Flag that is set to true if this builder acted on the current input.
2438
    bool IsActive = false;
2439
2440
    /// Flag for -fgpu-rdc.
2441
    bool Relocatable = false;
2442
2443
    /// Default GPU architecture if there's no one specified.
2444
    CudaArch DefaultCudaArch = CudaArch::UNKNOWN;
2445
2446
  public:
2447
    CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2448
                          const Driver::InputList &Inputs,
2449
                          Action::OffloadKind OFKind)
2450
93.3k
        : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
2451
2452
1.96k
    ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2453
      // While generating code for CUDA, we only depend on the host input action
2454
      // to trigger the creation of all the CUDA device actions.
2455
2456
      // If we are dealing with an input action, replicate it for each GPU
2457
      // architecture. If we are in host-only mode we return 'success' so that
2458
      // the host uses the CUDA offload kind.
2459
1.96k
      if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2460
466
        assert(!GpuArchList.empty() &&
2461
466
               "We should have at least one GPU architecture.");
2462
2463
        // If the host input is not CUDA or HIP, we don't need to bother about
2464
        // this input.
2465
466
        if (!(IA->getType() == types::TY_CUDA ||
2466
177
              IA->getType() == types::TY_HIP ||
2467
4
              IA->getType() == types::TY_PP_HIP)) {
2468
          // The builder will ignore this input.
2469
4
          IsActive = false;
2470
4
          return ABRT_Inactive;
2471
4
        }
2472
2473
        // Set the flag to true, so that the builder acts on the current input.
2474
462
        IsActive = true;
2475
2476
462
        if (CompileHostOnly)
2477
37
          return ABRT_Success;
2478
2479
        // Replicate inputs for each GPU architecture.
2480
425
        auto Ty = IA->getType() == types::TY_HIP ? 
types::TY_HIP_DEVICE166
2481
259
                                                 : types::TY_CUDA_DEVICE;
2482
948
        for (unsigned I = 0, E = GpuArchList.size(); I != E; 
++I523
) {
2483
523
          CudaDeviceActions.push_back(
2484
523
              C.MakeAction<InputAction>(IA->getInputArg(), Ty));
2485
523
        }
2486
2487
425
        return ABRT_Success;
2488
425
      }
2489
2490
      // If this is an unbundling action use it as is for each CUDA toolchain.
2491
1.49k
      if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2492
2493
        // If -fgpu-rdc is disabled, should not unbundle since there is no
2494
        // device code to link.
2495
25
        if (UA->getType() == types::TY_Object && 
!Relocatable23
)
2496
6
          return ABRT_Inactive;
2497
2498
19
        CudaDeviceActions.clear();
2499
19
        auto *IA = cast<InputAction>(UA->getInputs().back());
2500
19
        std::string FileName = IA->getInputArg().getAsString(Args);
2501
        // Check if the type of the file is the same as the action. Do not
2502
        // unbundle it if it is not. Do not unbundle .so files, for example,
2503
        // which are not object files.
2504
19
        if (IA->getType() == types::TY_Object &&
2505
17
            (!llvm::sys::path::has_extension(FileName) ||
2506
17
             types::lookupTypeForExtension(
2507
17
                 llvm::sys::path::extension(FileName).drop_front()) !=
2508
17
                 types::TY_Object))
2509
1
          return ABRT_Inactive;
2510
2511
34
        
for (auto Arch : GpuArchList)18
{
2512
34
          CudaDeviceActions.push_back(UA);
2513
34
          UA->registerDependentActionInfo(ToolChains[0], Arch,
2514
34
                                          AssociatedOffloadKind);
2515
34
        }
2516
18
        return ABRT_Success;
2517
18
      }
2518
2519
1.47k
      return IsActive ? 
ABRT_Success1.46k
:
ABRT_Inactive7
;
2520
1.47k
    }
2521
2522
491
    void appendTopLevelActions(ActionList &AL) override {
2523
      // Utility to append actions to the top level list.
2524
163
      auto AddTopLevel = [&](Action *A, TargetID TargetID) {
2525
163
        OffloadAction::DeviceDependences Dep;
2526
163
        Dep.add(*A, *ToolChains.front(), TargetID, AssociatedOffloadKind);
2527
163
        AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2528
163
      };
2529
2530
      // If we have a fat binary, add it to the list.
2531
491
      if (CudaFatBinary) {
2532
9
        AddTopLevel(CudaFatBinary, CudaArch::UNUSED);
2533
9
        CudaDeviceActions.clear();
2534
9
        CudaFatBinary = nullptr;
2535
9
        return;
2536
9
      }
2537
2538
482
      if (CudaDeviceActions.empty())
2539
373
        return;
2540
2541
      // If we have CUDA actions at this point, that's because we have a have
2542
      // partial compilation, so we should have an action for each GPU
2543
      // architecture.
2544
109
      assert(CudaDeviceActions.size() == GpuArchList.size() &&
2545
109
             "Expecting one action per GPU architecture.");
2546
109
      assert(ToolChains.size() == 1 &&
2547
109
             "Expecting to have a sing CUDA toolchain.");
2548
263
      for (unsigned I = 0, E = GpuArchList.size(); I != E; 
++I154
)
2549
154
        AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2550
2551
109
      CudaDeviceActions.clear();
2552
109
    }
2553
2554
    /// Get canonicalized offload arch option. \returns empty StringRef if the
2555
    /// option is invalid.
2556
    virtual StringRef getCanonicalOffloadArch(StringRef Arch) = 0;
2557
2558
    virtual llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>>
2559
    getConflictOffloadArchCombination(const std::set<StringRef> &GpuArchs) = 0;
2560
2561
93.3k
    bool initialize() override {
2562
93.3k
      assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2563
93.3k
             AssociatedOffloadKind == Action::OFK_HIP);
2564
2565
      // We don't need to support CUDA.
2566
93.3k
      if (AssociatedOffloadKind == Action::OFK_Cuda &&
2567
46.6k
          !C.hasOffloadToolChain<Action::OFK_Cuda>())
2568
46.3k
        return false;
2569
2570
      // We don't need to support HIP.
2571
46.9k
      if (AssociatedOffloadKind == Action::OFK_HIP &&
2572
46.6k
          !C.hasOffloadToolChain<Action::OFK_HIP>())
2573
46.5k
        return false;
2574
2575
497
      Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2576
497
          options::OPT_fno_gpu_rdc, /*Default=*/false);
2577
2578
497
      const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2579
497
      assert(HostTC && "No toolchain for host compilation.");
2580
497
      if (HostTC->getTriple().isNVPTX() ||
2581
480
          HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2582
        // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
2583
        // an error and abort pipeline construction early so we don't trip
2584
        // asserts that assume device-side compilation.
2585
2
        C.getDriver().Diag(diag::err_drv_cuda_host_arch)
2586
2
            << HostTC->getTriple().getArchName();
2587
2
        return true;
2588
2
      }
2589
2590
495
      ToolChains.push_back(
2591
495
          AssociatedOffloadKind == Action::OFK_Cuda
2592
295
              ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2593
200
              : C.getSingleOffloadToolChain<Action::OFK_HIP>());
2594
2595
495
      Arg *PartialCompilationArg = Args.getLastArg(
2596
495
          options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2597
495
          options::OPT_cuda_compile_host_device);
2598
495
      CompileHostOnly = PartialCompilationArg &&
2599
120
                        PartialCompilationArg->getOption().matches(
2600
120
                            options::OPT_cuda_host_only);
2601
495
      CompileDeviceOnly = PartialCompilationArg &&
2602
120
                          PartialCompilationArg->getOption().matches(
2603
120
                              options::OPT_cuda_device_only);
2604
495
      EmitLLVM = Args.getLastArg(options::OPT_emit_llvm);
2605
495
      EmitAsm = Args.getLastArg(options::OPT_S);
2606
2607
      // Collect all cuda_gpu_arch parameters, removing duplicates.
2608
495
      std::set<StringRef> GpuArchs;
2609
495
      bool Error = false;
2610
3.76k
      for (Arg *A : Args) {
2611
3.76k
        if (!(A->getOption().matches(options::OPT_offload_arch_EQ) ||
2612
3.27k
              A->getOption().matches(options::OPT_no_offload_arch_EQ)))
2613
3.25k
          continue;
2614
501
        A->claim();
2615
2616
501
        StringRef ArchStr = A->getValue();
2617
501
        if (A->getOption().matches(options::OPT_no_offload_arch_EQ) &&
2618
16
            ArchStr == "all") {
2619
2
          GpuArchs.clear();
2620
2
          continue;
2621
2
        }
2622
499
        ArchStr = getCanonicalOffloadArch(ArchStr);
2623
499
        if (ArchStr.empty()) {
2624
15
          Error = true;
2625
484
        } else if (A->getOption().matches(options::OPT_offload_arch_EQ))
2626
470
          GpuArchs.insert(ArchStr);
2627
14
        else if (A->getOption().matches(options::OPT_no_offload_arch_EQ))
2628
14
          GpuArchs.erase(ArchStr);
2629
14
        else
2630
0
          llvm_unreachable("Unexpected option.");
2631
499
      }
2632
2633
495
      auto &&ConflictingArchs = getConflictOffloadArchCombination(GpuArchs);
2634
495
      if (ConflictingArchs) {
2635
1
        C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo)
2636
1
            << ConflictingArchs.getValue().first
2637
1
            << ConflictingArchs.getValue().second;
2638
1
        C.setContainsError();
2639
1
        return true;
2640
1
      }
2641
2642
      // Collect list of GPUs remaining in the set.
2643
494
      for (auto Arch : GpuArchs)
2644
452
        GpuArchList.push_back(Arch.data());
2645
2646
      // Default to sm_20 which is the lowest common denominator for
2647
      // supported GPUs.  sm_20 code should work correctly, if
2648
      // suboptimally, on all newer GPUs.
2649
494
      if (GpuArchList.empty())
2650
136
        GpuArchList.push_back(DefaultCudaArch);
2651
2652
494
      return Error;
2653
494
    }
2654
  };
2655
2656
  /// \brief CUDA action builder. It injects device code in the host backend
2657
  /// action.
2658
  class CudaActionBuilder final : public CudaActionBuilderBase {
2659
  public:
2660
    CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2661
                      const Driver::InputList &Inputs)
2662
46.6k
        : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {
2663
46.6k
      DefaultCudaArch = CudaArch::SM_20;
2664
46.6k
    }
2665
2666
250
    StringRef getCanonicalOffloadArch(StringRef ArchStr) override {
2667
250
      CudaArch Arch = StringToCudaArch(ArchStr);
2668
250
      if (Arch == CudaArch::UNKNOWN) {
2669
5
        C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2670
5
        return StringRef();
2671
5
      }
2672
245
      return CudaArchToString(Arch);
2673
245
    }
2674
2675
    llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>>
2676
    getConflictOffloadArchCombination(
2677
295
        const std::set<StringRef> &GpuArchs) override {
2678
295
      return llvm::None;
2679
295
    }
2680
2681
    ActionBuilderReturnCode
2682
    getDeviceDependences(OffloadAction::DeviceDependences &DA,
2683
                         phases::ID CurPhase, phases::ID FinalPhase,
2684
1.02k
                         PhasesTy &Phases) override {
2685
1.02k
      if (!IsActive)
2686
1
        return ABRT_Inactive;
2687
2688
      // If we don't have more CUDA actions, we don't have any dependences to
2689
      // create for the host.
2690
1.02k
      if (CudaDeviceActions.empty())
2691
350
        return ABRT_Success;
2692
2693
670
      assert(CudaDeviceActions.size() == GpuArchList.size() &&
2694
670
             "Expecting one action per GPU architecture.");
2695
670
      assert(!CompileHostOnly &&
2696
670
             "Not expecting CUDA actions in host-only compilation.");
2697
2698
      // If we are generating code for the device or we are in a backend phase,
2699
      // we attempt to generate the fat binary. We compile each arch to ptx and
2700
      // assemble to cubin, then feed the cubin *and* the ptx into a device
2701
      // "link" action, which uses fatbinary to combine these cubins into one
2702
      // fatbin.  The fatbin is then an input to the host action if not in
2703
      // device-only mode.
2704
670
      if (CompileDeviceOnly || 
CurPhase == phases::Backend622
) {
2705
249
        ActionList DeviceActions;
2706
532
        for (unsigned I = 0, E = GpuArchList.size(); I != E; 
++I283
) {
2707
          // Produce the device action from the current phase up to the assemble
2708
          // phase.
2709
1.09k
          for (auto Ph : Phases) {
2710
            // Skip the phases that were already dealt with.
2711
1.09k
            if (Ph < CurPhase)
2712
442
              continue;
2713
            // We have to be consistent with the host final phase.
2714
656
            if (Ph > FinalPhase)
2715
45
              break;
2716
2717
611
            CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
2718
611
                C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
2719
2720
611
            if (Ph == phases::Assemble)
2721
238
              break;
2722
611
          }
2723
2724
          // If we didn't reach the assemble phase, we can't generate the fat
2725
          // binary. We don't need to generate the fat binary if we are not in
2726
          // device-only mode.
2727
283
          if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2728
238
              CompileDeviceOnly)
2729
74
            continue;
2730
2731
209
          Action *AssembleAction = CudaDeviceActions[I];
2732
209
          assert(AssembleAction->getType() == types::TY_Object);
2733
209
          assert(AssembleAction->getInputs().size() == 1);
2734
2735
209
          Action *BackendAction = AssembleAction->getInputs()[0];
2736
209
          assert(BackendAction->getType() == types::TY_PP_Asm);
2737
2738
418
          for (auto &A : {AssembleAction, BackendAction}) {
2739
418
            OffloadAction::DeviceDependences DDep;
2740
418
            DDep.add(*A, *ToolChains.front(), GpuArchList[I], Action::OFK_Cuda);
2741
418
            DeviceActions.push_back(
2742
418
                C.MakeAction<OffloadAction>(DDep, A->getType()));
2743
418
          }
2744
209
        }
2745
2746
        // We generate the fat binary if we have device input actions.
2747
249
        if (!DeviceActions.empty()) {
2748
191
          CudaFatBinary =
2749
191
              C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2750
2751
191
          if (!CompileDeviceOnly) {
2752
191
            DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2753
191
                   Action::OFK_Cuda);
2754
            // Clear the fat binary, it is already a dependence to an host
2755
            // action.
2756
191
            CudaFatBinary = nullptr;
2757
191
          }
2758
2759
          // Remove the CUDA actions as they are already connected to an host
2760
          // action or fat binary.
2761
191
          CudaDeviceActions.clear();
2762
191
        }
2763
2764
        // We avoid creating host action in device-only mode.
2765
201
        return CompileDeviceOnly ? 
ABRT_Ignore_Host48
: ABRT_Success;
2766
421
      } else if (CurPhase > phases::Backend) {
2767
        // If we are past the backend phase and still have a device action, we
2768
        // don't have to do anything as this action is already a device
2769
        // top-level action.
2770
0
        return ABRT_Success;
2771
0
      }
2772
2773
421
      assert(CurPhase < phases::Backend && "Generating single CUDA "
2774
421
                                           "instructions should only occur "
2775
421
                                           "before the backend phase!");
2776
2777
      // By default, we produce an action for each device arch.
2778
421
      for (Action *&A : CudaDeviceActions)
2779
471
        A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2780
2781
421
      return ABRT_Success;
2782
421
    }
2783
  };
2784
  /// \brief HIP action builder. It injects device code in the host backend
2785
  /// action.
2786
  class HIPActionBuilder final : public CudaActionBuilderBase {
2787
    /// The linker inputs obtained for each device arch.
2788
    SmallVector<ActionList, 8> DeviceLinkerInputs;
2789
2790
  public:
2791
    HIPActionBuilder(Compilation &C, DerivedArgList &Args,
2792
                     const Driver::InputList &Inputs)
2793
46.7k
        : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {
2794
46.7k
      DefaultCudaArch = CudaArch::GFX803;
2795
46.7k
    }
2796
2797
184
    bool canUseBundlerUnbundler() const override { return true; }
2798
2799
249
    StringRef getCanonicalOffloadArch(StringRef IdStr) override {
2800
249
      llvm::StringMap<bool> Features;
2801
249
      auto ArchStr =
2802
249
          parseTargetID(getHIPOffloadTargetTriple(), IdStr, &Features);
2803
249
      if (!ArchStr) {
2804
10
        C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << IdStr;
2805
10
        C.setContainsError();
2806
10
        return StringRef();
2807
10
      }
2808
239
      auto CanId = getCanonicalTargetID(ArchStr.getValue(), Features);
2809
239
      return Args.MakeArgStringRef(CanId);
2810
239
    };
2811
2812
    llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>>
2813
    getConflictOffloadArchCombination(
2814
184
        const std::set<StringRef> &GpuArchs) override {
2815
184
      return getConflictTargetIDCombination(GpuArchs);
2816
184
    }
2817
2818
    ActionBuilderReturnCode
2819
    getDeviceDependences(OffloadAction::DeviceDependences &DA,
2820
                         phases::ID CurPhase, phases::ID FinalPhase,
2821
736
                         PhasesTy &Phases) override {
2822
      // amdgcn does not support linking of object files, therefore we skip
2823
      // backend and assemble phases to output LLVM IR. Except for generating
2824
      // non-relocatable device coee, where we generate fat binary for device
2825
      // code and pass to host in Backend phase.
2826
736
      if (CudaDeviceActions.empty())
2827
188
        return ABRT_Success;
2828
2829
548
      assert(((CurPhase == phases::Link && Relocatable) ||
2830
548
              CudaDeviceActions.size() == GpuArchList.size()) &&
2831
548
             "Expecting one action per GPU architecture.");
2832
548
      assert(!CompileHostOnly &&
2833
548
             "Not expecting CUDA actions in host-only compilation.");
2834
2835
548
      if (!Relocatable && 
CurPhase == phases::Backend344
&&
!EmitLLVM109
&&
2836
107
          !EmitAsm) {
2837
        // If we are in backend phase, we attempt to generate the fat binary.
2838
        // We compile each arch to IR and use a link action to generate code
2839
        // object containing ISA. Then we use a special "link" action to create
2840
        // a fat binary containing all the code objects for different GPU's.
2841
        // The fat binary is then an input to the host action.
2842
229
        for (unsigned I = 0, E = GpuArchList.size(); I != E; 
++I127
) {
2843
127
          auto BackendAction = C.getDriver().ConstructPhaseAction(
2844
127
              C, Args, phases::Backend, CudaDeviceActions[I],
2845
127
              AssociatedOffloadKind);
2846
127
          auto AssembleAction = C.getDriver().ConstructPhaseAction(
2847
127
              C, Args, phases::Assemble, BackendAction, AssociatedOffloadKind);
2848
          // Create a link action to link device IR with device library
2849
          // and generate ISA.
2850
127
          ActionList AL;
2851
127
          AL.push_back(AssembleAction);
2852
127
          CudaDeviceActions[I] =
2853
127
              C.MakeAction<LinkJobAction>(AL, types::TY_Image);
2854
2855
          // OffloadingActionBuilder propagates device arch until an offload
2856
          // action. Since the next action for creating fatbin does
2857
          // not have device arch, whereas the above link action and its input
2858
          // have device arch, an offload action is needed to stop the null
2859
          // device arch of the next action being propagated to the above link
2860
          // action.
2861
127
          OffloadAction::DeviceDependences DDep;
2862
127
          DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I],
2863
127
                   AssociatedOffloadKind);
2864
127
          CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
2865
127
              DDep, CudaDeviceActions[I]->getType());
2866
127
        }
2867
        // Create HIP fat binary with a special "link" action.
2868
102
        CudaFatBinary =
2869
102
            C.MakeAction<LinkJobAction>(CudaDeviceActions,
2870
102
                types::TY_HIP_FATBIN);
2871
2872
102
        if (!CompileDeviceOnly) {
2873
93
          DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2874
93
                 AssociatedOffloadKind);
2875
          // Clear the fat binary, it is already a dependence to an host
2876
          // action.
2877
93
          CudaFatBinary = nullptr;
2878
93
        }
2879
2880
        // Remove the CUDA actions as they are already connected to an host
2881
        // action or fat binary.
2882
102
        CudaDeviceActions.clear();
2883
2884
93
        return CompileDeviceOnly ? 
ABRT_Ignore_Host9
: ABRT_Success;
2885
446
      } else if (CurPhase == phases::Link) {
2886
        // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
2887
        // This happens to each device action originated from each input file.
2888
        // Later on, device actions in DeviceLinkerInputs are used to create
2889
        // device link actions in appendLinkDependences and the created device
2890
        // link actions are passed to the offload action as device dependence.
2891
41
        DeviceLinkerInputs.resize(CudaDeviceActions.size());
2892
41
        auto LI = DeviceLinkerInputs.begin();
2893
67
        for (auto *A : CudaDeviceActions) {
2894
67
          LI->push_back(A);
2895
67
          ++LI;
2896
67
        }
2897
2898
        // We will pass the device action as a host dependence, so we don't
2899
        // need to do anything else with them.
2900
41
        CudaDeviceActions.clear();
2901
41
        return ABRT_Success;
2902
41
      }
2903
2904
      // By default, we produce an action for each device arch.
2905
405
      for (Action *&A : CudaDeviceActions)
2906
563
        A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
2907
563
                                               AssociatedOffloadKind);
2908
2909
405
      return (CompileDeviceOnly && 
CurPhase == FinalPhase74
) ?
ABRT_Ignore_Host24
2910
381
                                                           : ABRT_Success;
2911
405
    }
2912
2913
99
    void appendLinkDeviceActions(ActionList &AL) override {
2914
99
      if (DeviceLinkerInputs.size() == 0)
2915
66
        return;
2916
2917
33
      assert(DeviceLinkerInputs.size() == GpuArchList.size() &&
2918
33
             "Linker inputs and GPU arch list sizes do not match.");
2919
2920
      // Append a new link action for each device.
2921
33
      unsigned I = 0;
2922
51
      for (auto &LI : DeviceLinkerInputs) {
2923
        // Each entry in DeviceLinkerInputs corresponds to a GPU arch.
2924
51
        auto *DeviceLinkAction =
2925
51
            C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2926
        // Linking all inputs for the current GPU arch.
2927
        // LI contains all the inputs for the linker.
2928
51
        OffloadAction::DeviceDependences DeviceLinkDeps;
2929
51
        DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0],
2930
51
            GpuArchList[I], AssociatedOffloadKind);
2931
51
        AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps,
2932
51
            DeviceLinkAction->getType()));
2933
51
        ++I;
2934
51
      }
2935
33
      DeviceLinkerInputs.clear();
2936
2937
      // Create a host object from all the device images by embedding them
2938
      // in a fat binary.
2939
33
      OffloadAction::DeviceDependences DDeps;
2940
33
      auto *TopDeviceLinkAction =
2941
33
          C.MakeAction<LinkJobAction>(AL, types::TY_Object);
2942
33
      DDeps.add(*TopDeviceLinkAction, *ToolChains[0],
2943
33
          nullptr, AssociatedOffloadKind);
2944
2945
      // Offload the host object to the host linker.
2946
33
      AL.push_back(C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType()));
2947
33
    }
2948
2949
33
    Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); }
2950
2951
99
    void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
2952
  };
2953
2954
  /// OpenMP action builder. The host bitcode is passed to the device frontend
2955
  /// and all the device linked images are passed to the host link phase.
2956
  class OpenMPActionBuilder final : public DeviceActionBuilder {
2957
    /// The OpenMP actions for the current input.
2958
    ActionList OpenMPDeviceActions;
2959
2960
    /// The linker inputs obtained for each toolchain.
2961
    SmallVector<ActionList, 8> DeviceLinkerInputs;
2962
2963
  public:
2964
    OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2965
                        const Driver::InputList &Inputs)
2966
46.7k
        : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2967
2968
    ActionBuilderReturnCode
2969
    getDeviceDependences(OffloadAction::DeviceDependences &DA,
2970
                         phases::ID CurPhase, phases::ID FinalPhase,
2971
374
                         PhasesTy &Phases) override {
2972
374
      if (OpenMPDeviceActions.empty())
2973
2
        return ABRT_Inactive;
2974
2975
      // We should always have an action for each input.
2976
372
      assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2977
372
             "Number of OpenMP actions and toolchains do not match.");
2978
2979
      // The host only depends on device action in the linking phase, when all
2980
      // the device images have to be embedded in the host image.
2981
372
      if (CurPhase == phases::Link) {
2982
81
        assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2983
81
               "Toolchains and linker inputs sizes do not match.");
2984
81
        auto LI = DeviceLinkerInputs.begin();
2985
100
        for (auto *A : OpenMPDeviceActions) {
2986
100
          LI->push_back(A);
2987
100
          ++LI;
2988
100
        }
2989
2990
        // We passed the device action as a host dependence, so we don't need to
2991
        // do anything else with them.
2992
81
        OpenMPDeviceActions.clear();
2993
81
        return ABRT_Success;
2994
81
      }
2995
2996
      // By default, we produce an action for each device arch.
2997
291
      for (Action *&A : OpenMPDeviceActions)
2998
349
        A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2999
3000
291
      return ABRT_Success;
3001
291
    }
3002
3003
383
    ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
3004
3005
      // If this is an input action replicate it for each OpenMP toolchain.
3006
383
      if (auto *IA = dyn_cast<InputAction>(HostAction)) {
3007
76
        OpenMPDeviceActions.clear();
3008
169
        for (unsigned I = 0; I < ToolChains.size(); 
++I93
)
3009
93
          OpenMPDeviceActions.push_back(
3010
93
              C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
3011
76
        return ABRT_Success;
3012
76
      }
3013
3014
      // If this is an unbundling action use it as is for each OpenMP toolchain.
3015
307
      if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
3016
16
        OpenMPDeviceActions.clear();
3017
16
        auto *IA = cast<InputAction>(UA->getInputs().back());
3018
16
        std::string FileName = IA->getInputArg().getAsString(Args);
3019
        // Check if the type of the file is the same as the action. Do not
3020
        // unbundle it if it is not. Do not unbundle .so files, for example,
3021
        // which are not object files.
3022
16
        if (IA->getType() == types::TY_Object &&
3023
9
            (!llvm::sys::path::has_extension(FileName) ||
3024
9
             types::lookupTypeForExtension(
3025
9
                 llvm::sys::path::extension(FileName).drop_front()) !=
3026
9
                 types::TY_Object))
3027
2
          return ABRT_Inactive;
3028
36
        
for (unsigned I = 0; 14
I < ToolChains.size();
++I22
) {
3029
22
          OpenMPDeviceActions.push_back(UA);
3030
22
          UA->registerDependentActionInfo(
3031
22
              ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
3032
22
        }
3033
14
        return ABRT_Success;
3034
14
      }
3035
3036
      // When generating code for OpenMP we use the host compile phase result as
3037
      // a dependence to the device compile phase so that it can learn what
3038
      // declarations should be emitted. However, this is not the only use for
3039
      // the host action, so we prevent it from being collapsed.
3040
291
      if (isa<CompileJobAction>(HostAction)) {
3041
74
        HostAction->setCannotBeCollapsedWithNextDependentAction();
3042
74
        assert(ToolChains.size() == OpenMPDeviceActions.size() &&
3043
74
               "Toolchains and device action sizes do not match.");
3044
74
        OffloadAction::HostDependence HDep(
3045
74
            *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3046
74
            /*BoundArch=*/nullptr, Action::OFK_OpenMP);
3047
74
        auto TC = ToolChains.begin();
3048
90
        for (Action *&A : OpenMPDeviceActions) {
3049
90
          assert(isa<CompileJobAction>(A));
3050
90
          OffloadAction::DeviceDependences DDep;
3051
90
          DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
3052
90
          A = C.MakeAction<OffloadAction>(HDep, DDep);
3053
90
          ++TC;
3054
90
        }
3055
74
      }
3056
291
      return ABRT_Success;
3057
291
    }
3058
3059
92
    void appendTopLevelActions(ActionList &AL) override {
3060
92
      if (OpenMPDeviceActions.empty())
3061
83
        return;
3062
3063
      // We should always have an action for each input.
3064
9
      assert(OpenMPDeviceActions.size() == ToolChains.size() &&
3065
9
             "Number of OpenMP actions and toolchains do not match.");
3066
3067
      // Append all device actions followed by the proper offload action.
3068
9
      auto TI = ToolChains.begin();
3069
15
      for (auto *A : OpenMPDeviceActions) {
3070
15
        OffloadAction::DeviceDependences Dep;
3071
15
        Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
3072
15
        AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
3073
15
        ++TI;
3074
15
      }
3075
      // We no longer need the action stored in this builder.
3076
9
      OpenMPDeviceActions.clear();
3077
9
    }
3078
3079
71
    void appendLinkDeviceActions(ActionList &AL) override {
3080
71
      assert(ToolChains.size() == DeviceLinkerInputs.size() &&
3081
71
             "Toolchains and linker inputs sizes do not match.");
3082
3083
      // Append a new link action for each device.
3084
71
      auto TC = ToolChains.begin();
3085
82
      for (auto &LI : DeviceLinkerInputs) {
3086
82
        auto *DeviceLinkAction =
3087
82
            C.MakeAction<LinkJobAction>(LI, types::TY_Image);
3088
82
        OffloadAction::DeviceDependences DeviceLinkDeps;
3089
82
        DeviceLinkDeps.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
3090
82
            Action::OFK_OpenMP);
3091
82
        AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps,
3092
82
            DeviceLinkAction->getType()));
3093
82
        ++TC;
3094
82
      }
3095
71
      DeviceLinkerInputs.clear();
3096
71
    }
3097
3098
71
    Action* appendLinkHostActions(ActionList &AL) override {
3099
      // Create wrapper bitcode from the result of device link actions and compile
3100
      // it to an object which will be added to the host link command.
3101
71
      auto *BC = C.MakeAction<OffloadWrapperJobAction>(AL, types::TY_LLVM_BC);
3102
71
      auto *ASM = C.MakeAction<BackendJobAction>(BC, types::TY_PP_Asm);
3103
71
      return C.MakeAction<AssembleJobAction>(ASM, types::TY_Object);
3104
71
    }
3105
3106
71
    void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
3107
3108
46.6k
    bool initialize() override {
3109
      // Get the OpenMP toolchains. If we don't get any, the action builder will
3110
      // know there is nothing to do related to OpenMP offloading.
3111
46.6k
      auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
3112
46.7k
      for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
3113
97
           ++TI)
3114
97
        ToolChains.push_back(TI->second);
3115
3116
46.6k
      DeviceLinkerInputs.resize(ToolChains.size());
3117
46.6k
      return false;
3118
46.6k
    }
3119
3120
80
    bool canUseBundlerUnbundler() const override {
3121
      // OpenMP should use bundled files whenever possible.
3122
80
      return true;
3123
80
    }
3124
  };
3125
3126
  ///
3127
  /// TODO: Add the implementation for other specialized builders here.
3128
  ///
3129
3130
  /// Specialized builders being used by this offloading action builder.
3131
  SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
3132
3133
  /// Flag set to true if all valid builders allow file bundling/unbundling.
3134
  bool CanUseBundler;
3135
3136
public:
3137
  OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
3138
                          const Driver::InputList &Inputs)
3139
46.6k
      : C(C) {
3140
    // Create a specialized builder for each device toolchain.
3141
3142
46.6k
    IsValid = true;
3143
3144
    // Create a specialized builder for CUDA.
3145
46.6k
    SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
3146
3147
    // Create a specialized builder for HIP.
3148
46.6k
    SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
3149
3150
    // Create a specialized builder for OpenMP.
3151
46.6k
    SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
3152
3153
    //
3154
    // TODO: Build other specialized builders here.
3155
    //
3156
3157
    // Initialize all the builders, keeping track of errors. If all valid
3158
    // builders agree that we can use bundling, set the flag to true.
3159
46.6k
    unsigned ValidBuilders = 0u;
3160
46.6k
    unsigned ValidBuildersSupportingBundling = 0u;
3161
140k
    for (auto *SB : SpecializedBuilders) {
3162
140k
      IsValid = IsValid && 
!SB->initialize()140k
;
3163
3164
      // Update the counters if the builder is valid.
3165
140k
      if (SB->isValid()) {
3166
559
        ++ValidBuilders;
3167
559
        if (SB->canUseBundlerUnbundler())
3168
264
          ++ValidBuildersSupportingBundling;
3169
559
      }
3170
140k
    }
3171
46.6k
    CanUseBundler =
3172
46.6k
        ValidBuilders && 
ValidBuilders == ValidBuildersSupportingBundling558
;
3173
46.6k
  }
3174
3175
46.6k
  ~OffloadingActionBuilder() {
3176
46.6k
    for (auto *SB : SpecializedBuilders)
3177
140k
      delete SB;
3178
46.6k
  }
3179
3180
  /// Generate an action that adds device dependences (if any) to a host action.
3181
  /// If no device dependence actions exist, just return the host action \a
3182
  /// HostAction. If an error is found or if no builder requires the host action
3183
  /// to be generated, return nullptr.
3184
  Action *
3185
  addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
3186
                                   phases::ID CurPhase, phases::ID FinalPhase,
3187
113k
                                   DeviceActionBuilder::PhasesTy &Phases) {
3188
113k
    if (!IsValid)
3189
0
      return nullptr;
3190
3191
113k
    if (SpecializedBuilders.empty())
3192
0
      return HostAction;
3193
3194
113k
    assert(HostAction && "Invalid host action!");
3195
3196
113k
    OffloadAction::DeviceDependences DDeps;
3197
    // Check if all the programming models agree we should not emit the host
3198
    // action. Also, keep track of the offloading kinds employed.
3199
113k
    auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3200
113k
    unsigned InactiveBuilders = 0u;
3201
113k
    unsigned IgnoringBuilders = 0u;
3202
340k
    for (auto *SB : SpecializedBuilders) {
3203
340k
      if (!SB->isValid()) {
3204
338k
        ++InactiveBuilders;
3205
338k
        continue;
3206
338k
      }
3207
3208
2.12k
      auto RetCode =
3209
2.12k
          SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
3210
3211
      // If the builder explicitly says the host action should be ignored,
3212
      // we need to increment the variable that tracks the builders that request
3213
      // the host object to be ignored.
3214
2.12k
      if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
3215
81
        ++IgnoringBuilders;
3216
3217
      // Unless the builder was inactive for this action, we have to record the
3218
      // offload kind because the host will have to use it.
3219
2.12k
      if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3220
2.12k
        OffloadKind |= SB->getAssociatedOffloadKind();
3221
2.12k
    }
3222
3223
    // If all builders agree that the host object should be ignored, just return
3224
    // nullptr.
3225
113k
    if (IgnoringBuilders &&
3226
81
        SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
3227
81
      return nullptr;
3228
3229
113k
    if (DDeps.getActions().empty())
3230
113k
      return HostAction;
3231
3232
    // We have dependences we need to bundle together. We use an offload action
3233
    // for that.
3234
281
    OffloadAction::HostDependence HDep(
3235
281
        *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3236
281
        /*BoundArch=*/nullptr, DDeps);
3237
281
    return C.MakeAction<OffloadAction>(HDep, DDeps);
3238
281
  }
3239
3240
  /// Generate an action that adds a host dependence to a device action. The
3241
  /// results will be kept in this action builder. Return true if an error was
3242
  /// found.
3243
  bool addHostDependenceToDeviceActions(Action *&HostAction,
3244
153k
                                        const Arg *InputArg) {
3245
153k
    if (!IsValid)
3246
15
      return true;
3247
3248
    // If we are supporting bundling/unbundling and the current action is an
3249
    // input action of non-source file, we replace the host action by the
3250
    // unbundling action. The bundler tool has the logic to detect if an input
3251
    // is a bundle or not and if the input is not a bundle it assumes it is a
3252
    // host file. Therefore it is safe to create an unbundling action even if
3253
    // the input is not a bundle.
3254
153k
    if (CanUseBundler && 
isa<InputAction>(HostAction)1.16k
&&
3255
292
        InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
3256
282
        (!types::isSrcFile(HostAction->getType()) ||
3257
241
         HostAction->getType() == types::TY_PP_HIP)) {
3258
41
      auto UnbundlingHostAction =
3259
41
          C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
3260
41
      UnbundlingHostAction->registerDependentActionInfo(
3261
41
          C.getSingleOffloadToolChain<Action::OFK_Host>(),
3262
41
          /*BoundArch=*/StringRef(), Action::OFK_Host);
3263
41
      HostAction = UnbundlingHostAction;
3264
41
    }
3265
3266
153k
    assert(HostAction && "Invalid host action!");
3267
3268
    // Register the offload kinds that are used.
3269
153k
    auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3270
459k
    for (auto *SB : SpecializedBuilders) {
3271
459k
      if (!SB->isValid())
3272
457k
        continue;
3273
3274
2.33k
      auto RetCode = SB->addDeviceDepences(HostAction);
3275
3276
      // Host dependences for device actions are not compatible with that same
3277
      // action being ignored.
3278
2.33k
      assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
3279
2.33k
             "Host dependence not expected to be ignored.!");
3280
3281
      // Unless the builder was inactive for this action, we have to record the
3282
      // offload kind because the host will have to use it.
3283
2.33k
      if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3284
2.32k
        OffloadKind |= SB->getAssociatedOffloadKind();
3285
2.33k
    }
3286
3287
    // Do not use unbundler if the Host does not depend on device action.
3288
153k
    if (OffloadKind == Action::OFK_None && 
CanUseBundler150k
)
3289
12
      if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3290
9
        HostAction = UA->getInputs().back();
3291
3292
153k
    return false;
3293
153k
  }
3294
3295
  /// Add the offloading top level actions to the provided action list. This
3296
  /// function can replace the host action by a bundling action if the
3297
  /// programming models allow it.
3298
  bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3299
48.2k
                             const Arg *InputArg) {
3300
    // Get the device actions to be appended.
3301
48.2k
    ActionList OffloadAL;
3302
144k
    for (auto *SB : SpecializedBuilders) {
3303
144k
      if (!SB->isValid())
3304
144k
        continue;
3305
580
      SB->appendTopLevelActions(OffloadAL);
3306
580
    }
3307
3308
    // If we can use the bundler, replace the host action by the bundling one in
3309
    // the resulting list. Otherwise, just append the device actions. For
3310
    // device only compilation, HostAction is a null pointer, therefore only do
3311
    // this when HostAction is not a null pointer.
3312
48.2k
    if (CanUseBundler && 
HostAction292
&&
3313
61
        HostAction->getType() != types::TY_Nothing && 
!OffloadAL.empty()59
) {
3314
      // Add the host action to the list in order to create the bundling action.
3315
24
      OffloadAL.push_back(HostAction);
3316
3317
      // We expect that the host action was just appended to the action list
3318
      // before this method was called.
3319
24
      assert(HostAction == AL.back() && "Host action not in the list??");
3320
24
      HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3321
24
      AL.back() = HostAction;
3322
24
    } else
3323
48.2k
      AL.append(OffloadAL.begin(), OffloadAL.end());
3324
3325
    // Propagate to the current host action (if any) the offload information
3326
    // associated with the current input.
3327
48.2k
    if (HostAction)
3328
39.8k
      HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3329
39.8k
                                           /*BoundArch=*/nullptr);
3330
48.2k
    return false;
3331
48.2k
  }
3332
3333
6.74k
  Action* makeHostLinkAction() {
3334
    // Build a list of device linking actions.
3335
6.74k
    ActionList DeviceAL;
3336
20.2k
    for (DeviceActionBuilder *SB : SpecializedBuilders) {
3337
20.2k
      if (!SB->isValid())
3338
19.9k
        continue;
3339
248
      SB->appendLinkDeviceActions(DeviceAL);
3340
248
    }
3341
3342
6.74k
    if (DeviceAL.empty())
3343
6.64k
      return nullptr;
3344
3345
    // Let builders add host linking actions.
3346
104
    Action* HA;
3347
312
    for (DeviceActionBuilder *SB : SpecializedBuilders) {
3348
312
      if (!SB->isValid())
3349
207
        continue;
3350
105
      HA = SB->appendLinkHostActions(DeviceAL);
3351
105
    }
3352
104
    return HA;
3353
104
  }
3354
3355
  /// Processes the host linker action. This currently consists of replacing it
3356
  /// with an offload action if there are device link objects and propagate to
3357
  /// the host action all the offload kinds used in the current compilation. The
3358
  /// resulting action is returned.
3359
6.74k
  Action *processHostLinkAction(Action *HostAction) {
3360
    // Add all the dependences from the device linking actions.
3361
6.74k
    OffloadAction::DeviceDependences DDeps;
3362
20.2k
    for (auto *SB : SpecializedBuilders) {
3363
20.2k
      if (!SB->isValid())
3364
19.9k
        continue;
3365
3366
248
      SB->appendLinkDependences(DDeps);
3367
248
    }
3368
3369
    // Calculate all the offload kinds used in the current compilation.
3370
6.74k
    unsigned ActiveOffloadKinds = 0u;
3371
6.74k
    for (auto &I : InputArgToOffloadKindMap)
3372
8.31k
      ActiveOffloadKinds |= I.second;
3373
3374
    // If we don't have device dependencies, we don't have to create an offload
3375
    // action.
3376
6.74k
    if (DDeps.getActions().empty()) {
3377
      // Propagate all the active kinds to host action. Given that it is a link
3378
      // action it is assumed to depend on all actions generated so far.
3379
6.74k
      HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
3380
6.74k
                                           /*BoundArch=*/nullptr);
3381
6.74k
      return HostAction;
3382
6.74k
    }
3383
3384
    // Create the offload action with all dependences. When an offload action
3385
    // is created the kinds are propagated to the host action, so we don't have
3386
    // to do that explicitly here.
3387
0
    OffloadAction::HostDependence HDep(
3388
0
        *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3389
0
        /*BoundArch*/ nullptr, ActiveOffloadKinds);
3390
0
    return C.MakeAction<OffloadAction>(HDep, DDeps);
3391
0
  }
3392
};
3393
} // anonymous namespace.
3394
3395
void Driver::handleArguments(Compilation &C, DerivedArgList &Args,
3396
                             const InputList &Inputs,
3397
46.7k
                             ActionList &Actions) const {
3398
3399
  // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
3400
46.7k
  Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3401
46.7k
  Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
3402
46.7k
  if (YcArg && 
YuArg29
&&
strcmp(YcArg->getValue(), YuArg->getValue()) != 04
) {
3403
1
    Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3404
1
    Args.eraseArg(options::OPT__SLASH_Yc);
3405
1
    Args.eraseArg(options::OPT__SLASH_Yu);
3406
1
    YcArg = YuArg = nullptr;
3407
1
  }
3408
46.7k
  if (YcArg && 
Inputs.size() > 128
) {
3409
1
    Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3410
1
    Args.eraseArg(options::OPT__SLASH_Yc);
3411
1
    YcArg = nullptr;
3412
1
  }
3413
3414
46.7k
  Arg *FinalPhaseArg;
3415
46.7k
  phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
3416
3417
46.7k
  if (FinalPhase == phases::Link) {
3418
6.86k
    if (Args.hasArg(options::OPT_emit_llvm))
3419
5
      Diag(clang::diag::err_drv_emit_llvm_link);
3420
6.86k
    if (IsCLMode() && 
LTOMode != LTOK_None315
&&
3421
4
        !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
3422
4
      Diag(clang::diag::err_drv_lto_without_lld);
3423
6.86k
  }
3424
3425
46.7k
  if (FinalPhase == phases::Preprocess || 
Args.hasArg(options::OPT__SLASH_Y_)42.5k
) {
3426
    // If only preprocessing or /Y- is used, all pch handling is disabled.
3427
    // Rather than check for it everywhere, just remove clang-cl pch-related
3428
    // flags here.
3429
4.16k
    Args.eraseArg(options::OPT__SLASH_Fp);
3430
4.16k
    Args.eraseArg(options::OPT__SLASH_Yc);
3431
4.16k
    Args.eraseArg(options::OPT__SLASH_Yu);
3432
4.16k
    YcArg = YuArg = nullptr;
3433
4.16k
  }
3434
3435
46.7k
  unsigned LastPLSize = 0;
3436
48.3k
  for (auto &I : Inputs) {
3437
48.3k
    types::ID InputType = I.first;
3438
48.3k
    const Arg *InputArg = I.second;
3439
3440
48.3k
    auto PL = types::getCompilationPhases(InputType);
3441
48.3k
    LastPLSize = PL.size();
3442
3443
    // If the first step comes after the final phase we are doing as part of
3444
    // this compilation, warn the user about it.
3445
48.3k
    phases::ID InitialPhase = PL[0];
3446
48.3k
    if (InitialPhase > FinalPhase) {
3447
55
      if (InputArg->isClaimed())
3448
1
        continue;
3449
3450
      // Claim here to avoid the more general unused warning.
3451
54
      InputArg->claim();
3452
3453
      // Suppress all unused style warnings with -Qunused-arguments
3454
54
      if (Args.hasArg(options::OPT_Qunused_arguments))
3455
0
        continue;
3456
3457
      // Special case when final phase determined by binary name, rather than
3458
      // by a command-line argument with a corresponding Arg.
3459
54
      if (CCCIsCPP())
3460
1
        Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
3461
1
            << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
3462
      // Special case '-E' warning on a previously preprocessed file to make
3463
      // more sense.
3464
53
      else if (InitialPhase == phases::Compile &&
3465
0
               (Args.getLastArg(options::OPT__SLASH_EP,
3466
0
                                options::OPT__SLASH_P) ||
3467
0
                Args.getLastArg(options::OPT_E) ||
3468
0
                Args.getLastArg(options::OPT_M, options::OPT_MM)) &&
3469
0
               getPreprocessedType(InputType) == types::TY_INVALID)
3470
0
        Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
3471
0
            << InputArg->getAsString(Args) << !!FinalPhaseArg
3472
0
            << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3473
53
      else
3474
53
        Diag(clang::diag::warn_drv_input_file_unused)
3475
53
            << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3476
53
            << !!FinalPhaseArg
3477
43
            << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : 
""10
);
3478
54
      continue;
3479
54
    }
3480
3481
48.2k
    if (YcArg) {
3482
      // Add a separate precompile phase for the compile phase.
3483
19
      if (FinalPhase >= phases::Compile) {
3484
19
        const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
3485
        // Build the pipeline for the pch file.
3486
19
        Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType);
3487
19
        for (phases::ID Phase : types::getCompilationPhases(HeaderType))
3488
38
          ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3489
19
        assert(ClangClPch);
3490
19
        Actions.push_back(ClangClPch);
3491
        // The driver currently exits after the first failed command.  This
3492
        // relies on that behavior, to make sure if the pch generation fails,
3493
        // the main compilation won't run.
3494
        // FIXME: If the main compilation fails, the PCH generation should
3495
        // probably not be considered successful either.
3496
19
      }
3497
19
    }
3498
48.2k
  }
3499
3500
  // If we are linking, claim any options which are obviously only used for
3501
  // compilation.
3502
  // FIXME: Understand why the last Phase List length is used here.
3503
46.7k
  if (FinalPhase == phases::Link && 
LastPLSize == 16.86k
) {
3504
2.94k
    Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
3505
2.94k
    Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3506
2.94k
  }
3507
46.7k
}
3508
3509
void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
3510
46.7k
                          const InputList &Inputs, ActionList &Actions) const {
3511
46.7k
  llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
3512
3513
46.7k
  if (!SuppressMissingInputWarning && 
Inputs.empty()38.4k
) {
3514
15
    Diag(clang::diag::err_drv_no_input_files);
3515
15
    return;
3516
15
  }
3517
3518
  // Reject -Z* at the top level, these options should never have been exposed
3519
  // by gcc.
3520
46.7k
  if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
3521
0
    Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
3522
3523
  // Diagnose misuse of /Fo.
3524
46.7k
  if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
3525
41
    StringRef V = A->getValue();
3526
41
    if (Inputs.size() > 1 && 
!V.empty()4
&&
3527
3
        !llvm::sys::path::is_separator(V.back())) {
3528
      // Check whether /Fo tries to name an output file for multiple inputs.
3529
1
      Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3530
1
          << A->getSpelling() << V;
3531
1
      Args.eraseArg(options::OPT__SLASH_Fo);
3532
1
    }
3533
41
  }
3534
3535
  // Diagnose misuse of /Fa.
3536
46.7k
  if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
3537
10
    StringRef V = A->getValue();
3538
10
    if (Inputs.size() > 1 && 
!V.empty()2
&&
3539
1
        !llvm::sys::path::is_separator(V.back())) {
3540
      // Check whether /Fa tries to name an asm file for multiple inputs.
3541
1
      Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3542
1
          << A->getSpelling() << V;
3543
1
      Args.eraseArg(options::OPT__SLASH_Fa);
3544
1
    }
3545
10
  }
3546
3547
  // Diagnose misuse of /o.
3548
46.7k
  if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
3549
44
    if (A->getValue()[0] == '\0') {
3550
      // It has to have a value.
3551
0
      Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
3552
0
      Args.eraseArg(options::OPT__SLASH_o);
3553
0
    }
3554
44
  }
3555
3556
46.7k
  handleArguments(C, Args, Inputs, Actions);
3557
3558
  // Builder to be used to build offloading actions.
3559
46.7k
  OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
3560
3561
  // Construct the actions to perform.
3562
46.7k
  HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
3563
46.7k
  ActionList LinkerInputs;
3564
46.7k
  ActionList MergerInputs;
3565
3566
48.3k
  for (auto &I : Inputs) {
3567
48.3k
    types::ID InputType = I.first;
3568
48.3k
    const Arg *InputArg = I.second;
3569
3570
48.3k
    auto PL = types::getCompilationPhases(*this, Args, InputType);
3571
48.3k
    if (PL.empty())
3572
45
      continue;
3573
3574
48.2k
    auto FullPL = types::getCompilationPhases(InputType);
3575
3576
    // Build the pipeline for this file.
3577
48.2k
    Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3578
3579
    // Use the current host action in any of the offloading actions, if
3580
    // required.
3581
48.2k
    if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3582
15
      break;
3583
3584
113k
    
for (phases::ID Phase : PL)48.2k
{
3585
3586
      // Add any offload action the host action depends on.
3587
113k
      Current = OffloadBuilder.addDeviceDependencesToHostAction(
3588
113k
          Current, InputArg, Phase, PL.back(), FullPL);
3589
113k
      if (!Current)
3590
81
        break;
3591
3592
      // Queue linker inputs.
3593
113k
      if (Phase == phases::Link) {
3594
8.31k
        assert(Phase == PL.back() && "linking must be final compilation step.");
3595
8.31k
        LinkerInputs.push_back(Current);
3596
8.31k
        Current = nullptr;
3597
8.31k
        break;
3598
8.31k
      }
3599
3600
      // TODO: Consider removing this because the merged may not end up being
3601
      // the final Phase in the pipeline. Perhaps the merged could just merge
3602
      // and then pass an artifact of some sort to the Link Phase.
3603
      // Queue merger inputs.
3604
105k
      if (Phase == phases::IfsMerge) {
3605
10
        assert(Phase == PL.back() && "merging must be final compilation step.");
3606
10
        MergerInputs.push_back(Current);
3607
10
        Current = nullptr;
3608
10
        break;
3609
10
      }
3610
3611
      // Each precompiled header file after a module file action is a module
3612
      // header of that same module file, rather than being compiled to a
3613
      // separate PCH.
3614
105k
      if (Phase == phases::Precompile && 
HeaderModuleAction61
&&
3615
4
          getPrecompiledType(InputType) == types::TY_PCH) {
3616
4
        HeaderModuleAction->addModuleHeaderInput(Current);
3617
4
        Current = nullptr;
3618
4
        break;
3619
4
      }
3620
3621
      // FIXME: Should we include any prior module file outputs as inputs of
3622
      // later actions in the same command line?
3623
3624
      // Otherwise construct the appropriate action.
3625
105k
      Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
3626
3627
      // We didn't create a new action, so we will just move to the next phase.
3628
105k
      if (NewCurrent == Current)
3629
161
        continue;
3630
3631
104k
      if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
3632
3
        HeaderModuleAction = HMA;
3633
3634
104k
      Current = NewCurrent;
3635
3636
      // Use the current host action in any of the offloading actions, if
3637
      // required.
3638
104k
      if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3639
0
        break;
3640
3641
104k
      if (Current->getType() == types::TY_Nothing)
3642
27.5k
        break;
3643
104k
    }
3644
3645
    // If we ended with something, add to the output list.
3646
48.2k
    if (Current)
3647
39.8k
      Actions.push_back(Current);
3648
3649
    // Add any top level actions generated for offloading.
3650
48.2k
    OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
3651
48.2k
  }
3652
3653
  // Add a link action if necessary.
3654
46.7k
  if (!LinkerInputs.empty()) {
3655
6.74k
    if (Action *Wrapper = OffloadBuilder.makeHostLinkAction())
3656
104
      LinkerInputs.push_back(Wrapper);
3657
6.74k
    Action *LA;
3658
    // Check if this Linker Job should emit a static library.
3659
6.74k
    if (ShouldEmitStaticLibrary(Args)) {
3660
7
      LA = C.MakeAction<StaticLibJobAction>(LinkerInputs, types::TY_Image);
3661
6.73k
    } else {
3662
6.73k
      LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3663
6.73k
    }
3664
6.74k
    LA = OffloadBuilder.processHostLinkAction(LA);
3665
6.74k
    Actions.push_back(LA);
3666
6.74k
  }
3667
3668
  // Add an interface stubs merge action if necessary.
3669
46.7k
  if (!MergerInputs.empty())
3670
6
    Actions.push_back(
3671
6
        C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
3672
3673
46.7k
  if (Args.hasArg(options::OPT_emit_interface_stubs)) {
3674
25
    auto PhaseList = types::getCompilationPhases(
3675
25
        types::TY_IFS_CPP,
3676
23
        Args.hasArg(options::OPT_c) ? 
phases::Compile2
: phases::LastPhase);
3677
3678
25
    ActionList MergerInputs;
3679
3680
40
    for (auto &I : Inputs) {
3681
40
      types::ID InputType = I.first;
3682
40
      const Arg *InputArg = I.second;
3683
3684
      // Currently clang and the llvm assembler do not support generating symbol
3685
      // stubs from assembly, so we skip the input on asm files. For ifs files
3686
      // we rely on the normal pipeline setup in the pipeline setup code above.
3687
40
      if (InputType == types::TY_IFS || 
InputType == types::TY_PP_Asm30
||
3688
30
          InputType == types::TY_Asm)
3689
10
        continue;
3690
3691
30
      Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3692
3693
56
      for (auto Phase : PhaseList) {
3694
56
        switch (Phase) {
3695
0
        default:
3696
0
          llvm_unreachable(
3697
0
              "IFS Pipeline can only consist of Compile followed by IfsMerge.");
3698
30
        case phases::Compile: {
3699
          // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs
3700
          // files where the .o file is located. The compile action can not
3701
          // handle this.
3702
30
          if (InputType == types::TY_Object)
3703
4
            break;
3704
3705
26
          Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP);
3706
26
          break;
3707
26
        }
3708
26
        case phases::IfsMerge: {
3709
26
          assert(Phase == PhaseList.back() &&
3710
26
                 "merging must be final compilation step.");
3711
26
          MergerInputs.push_back(Current);
3712
26
          Current = nullptr;
3713
26
          break;
3714
26
        }
3715
56
        }
3716
56
      }
3717
3718
      // If we ended with something, add to the output list.
3719
30
      if (Current)
3720
4
        Actions.push_back(Current);
3721
30
    }
3722
3723
    // Add an interface stubs merge action if necessary.
3724
25
    if (!MergerInputs.empty())
3725
17
      Actions.push_back(
3726
17
          C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
3727
25
  }
3728
3729
  // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a custom
3730
  // Compile phase that prints out supported cpu models and quits.
3731
46.7k
  if (Arg *A = Args.getLastArg(options::OPT_print_supported_cpus)) {
3732
    // Use the -mcpu=? flag as the dummy input to cc1.
3733
4
    Actions.clear();
3734
4
    Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C);
3735
4
    Actions.push_back(
3736
4
        C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing));
3737
4
    for (auto &I : Inputs)
3738
0
      I.second->claim();
3739
4
  }
3740
3741
  // Claim ignored clang-cl options.
3742
46.7k
  Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
3743
3744
  // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3745
  // to non-CUDA compilations and should not trigger warnings there.
3746
46.7k
  Args.ClaimAllArgs(options::OPT_cuda_host_only);
3747
46.7k
  Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
3748
46.7k
}
3749
3750
Action *Driver::ConstructPhaseAction(
3751
    Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3752
107k
    Action::OffloadKind TargetDeviceOffloadKind) const {
3753
107k
  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
3754
3755
  // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3756
  // encode this in the steps because the intermediate type depends on
3757
  // arguments. Just special case here.
3758
107k
  if (Phase == phases::Assemble && 
Input->getType() != types::TY_PP_Asm11.2k
)
3759
214
    return Input;
3760
3761
  // Build the appropriate action.
3762
107k
  switch (Phase) {
3763
0
  case phases::Link:
3764
0
    llvm_unreachable("link action invalid here.");
3765
0
  case phases::IfsMerge:
3766
0
    llvm_unreachable("ifsmerge action invalid here.");
3767
44.0k
  case phases::Preprocess: {
3768
44.0k
    types::ID OutputTy;
3769
    // -M and -MM specify the dependency file name by altering the output type,
3770
    // -if -MD and -MMD are not specified.
3771
44.0k
    if (Args.hasArg(options::OPT_M, options::OPT_MM) &&
3772
2.99k
        !Args.hasArg(options::OPT_MD, options::OPT_MMD)) {
3773
2.98k
      OutputTy = types::TY_Dependencies;
3774
41.0k
    } else {
3775
41.0k
      OutputTy = Input->getType();
3776
41.0k
      if (!Args.hasFlag(options::OPT_frewrite_includes,
3777
41.0k
                        options::OPT_fno_rewrite_includes, false) &&
3778
41.0k
          !Args.hasFlag(options::OPT_frewrite_imports,
3779
41.0k
                        options::OPT_fno_rewrite_imports, false) &&
3780
41.0k
          !CCGenDiagnostics)
3781
41.0k
        OutputTy = types::getPreprocessedType(OutputTy);
3782
41.0k
      assert(OutputTy != types::TY_INVALID &&
3783
41.0k
             "Cannot preprocess this input type!");
3784
41.0k
    }
3785
44.0k
    return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
3786
0
  }
3787
76
  case phases::Precompile: {
3788
76
    types::ID OutputTy = getPrecompiledType(Input->getType());
3789
76
    assert(OutputTy != types::TY_INVALID &&
3790
76
           "Cannot precompile this input type!");
3791
3792
    // If we're given a module name, precompile header file inputs as a
3793
    // module, not as a precompiled header.
3794
76
    const char *ModName = nullptr;
3795
76
    if (OutputTy == types::TY_PCH) {
3796
70
      if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
3797
3
        ModName = A->getValue();
3798
70
      if (ModName)
3799
3
        OutputTy = types::TY_ModuleFile;
3800
70
    }
3801
3802
76
    if (Args.hasArg(options::OPT_fsyntax_only)) {
3803
      // Syntax checks should not emit a PCH file
3804
27
      OutputTy = types::TY_Nothing;
3805
27
    }
3806
3807
76
    if (ModName)
3808
3
      return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
3809
3
                                                           ModName);
3810
73
    return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
3811
73
  }
3812
39.8k
  case phases::Compile: {
3813
39.8k
    if (Args.hasArg(options::OPT_fsyntax_only))
3814
27.5k
      return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
3815
12.2k
    if (Args.hasArg(options::OPT_rewrite_objc))
3816
5
      return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
3817
12.2k
    if (Args.hasArg(options::OPT_rewrite_legacy_objc))
3818
3
      return C.MakeAction<CompileJobAction>(Input,
3819
3
                                            types::TY_RewrittenLegacyObjC);
3820
12.2k
    if (Args.hasArg(options::OPT__analyze))
3821
42
      return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
3822
12.2k
    if (Args.hasArg(options::OPT__migrate))
3823
0
      return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
3824
12.2k
    if (Args.hasArg(options::OPT_emit_ast))
3825
12
      return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
3826
12.2k
    if (Args.hasArg(options::OPT_module_file_info))
3827
0
      return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
3828
12.2k
    if (Args.hasArg(options::OPT_verify_pch))
3829
2
      return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3830
12.2k
    return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
3831
12.2k
  }
3832
12.2k
  case phases::Backend: {
3833
12.2k
    if (isUsingLTO() && 
TargetDeviceOffloadKind == Action::OFK_None180
) {
3834
169
      types::ID Output =
3835
161
          Args.hasArg(options::OPT_S) ? 
types::TY_LTO_IR8
: types::TY_LTO_BC;
3836
169
      return C.MakeAction<BackendJobAction>(Input, Output);
3837
169
    }
3838
12.0k
    if (Args.hasArg(options::OPT_emit_llvm) ||
3839
11.5k
        (TargetDeviceOffloadKind == Action::OFK_HIP &&
3840
195
         Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
3841
556
                      false))) {
3842
556
      types::ID Output =
3843
471
          Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : 
types::TY_LLVM_BC85
;
3844
556
      return C.MakeAction<BackendJobAction>(Input, Output);
3845
556
    }
3846
11.4k
    return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
3847
11.4k
  }
3848
11.0k
  case phases::Assemble:
3849
11.0k
    return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
3850
0
  }
3851
3852
0
  llvm_unreachable("invalid phase in ConstructPhaseAction");
3853
0
}
3854
3855
46.6k
void Driver::BuildJobs(Compilation &C) const {
3856
46.6k
  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3857
3858
46.6k
  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3859
3860
  // It is an error to provide a -o option if we are making multiple output
3861
  // files. There are exceptions:
3862
  //
3863
  // IfsMergeJob: when generating interface stubs enabled we want to be able to
3864
  // generate the stub file at the same time that we generate the real
3865
  // library/a.out. So when a .o, .so, etc are the output, with clang interface
3866
  // stubs there will also be a .ifs and .ifso at the same location.
3867
  //
3868
  // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled
3869
  // and -c is passed, we still want to be able to generate a .ifs file while
3870
  // we are also generating .o files. So we allow more than one output file in
3871
  // this case as well.
3872
  //
3873
46.6k
  if (FinalOutput) {
3874
9.17k
    unsigned NumOutputs = 0;
3875
9.17k
    unsigned NumIfsOutputs = 0;
3876
9.17k
    for (const Action *A : C.getActions())
3877
9.18k
      if (A->getType() != types::TY_Nothing &&
3878
9.17k
          !(A->getKind() == Action::IfsMergeJobClass ||
3879
9.17k
            (A->getType() == clang::driver::types::TY_IFS_CPP &&
3880
1
             A->getKind() == clang::driver::Action::CompileJobClass &&
3881
1
             0 == NumIfsOutputs++) ||
3882
9.17k
            (A->getKind() == Action::BindArchClass && 
A->getInputs().size()6.48k
&&
3883
6.48k
             A->getInputs().front()->getKind() == Action::IfsMergeJobClass)))
3884
9.16k
        ++NumOutputs;
3885
3886
9.17k
    if (NumOutputs > 1) {
3887
5
      Diag(clang::diag::err_drv_output_argument_with_multiple_files);
3888
5
      FinalOutput = nullptr;
3889
5
    }
3890
9.17k
  }
3891
3892
46.6k
  const llvm::Triple &RawTriple = C.getDefaultToolChain().getTriple();
3893
46.6k
  if (RawTriple.isOSAIX())
3894
93
    if (Arg *A = C.getArgs().getLastArg(options::OPT_G))
3895
10
      Diag(diag::err_drv_unsupported_opt_for_target)
3896
10
          << A->getSpelling() << RawTriple.str();
3897
3898
  // Collect the list of architectures.
3899
46.6k
  llvm::StringSet<> ArchNames;
3900
46.6k
  if (RawTriple.isOSBinFormatMachO())
3901
21.2k
    for (const Arg *A : C.getArgs())
3902
547k
      if (A->getOption().matches(options::OPT_arch))
3903
8.84k
        ArchNames.insert(A->getValue());
3904
3905
  // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3906
46.6k
  std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
3907
46.6k
  for (Action *A : C.getActions()) {
3908
    // If we are linking an image for multiple archs then the linker wants
3909
    // -arch_multiple and -final_output <final image name>. Unfortunately, this
3910
    // doesn't fit in cleanly because we have to pass this information down.
3911
    //
3912
    // FIXME: This is a hack; find a cleaner way to integrate this into the
3913
    // process.
3914
46.6k
    const char *LinkingOutput = nullptr;
3915
46.6k
    if (isa<LipoJobAction>(A)) {
3916
10
      if (FinalOutput)
3917
5
        LinkingOutput = FinalOutput->getValue();
3918
5
      else
3919
5
        LinkingOutput = getDefaultImageName();
3920
10
    }
3921
3922
46.6k
    BuildJobsForAction(C, A, &C.getDefaultToolChain(),
3923
46.6k
                       /*BoundArch*/ StringRef(),
3924
46.6k
                       /*AtTopLevel*/ true,
3925
46.6k
                       /*MultipleArchs*/ ArchNames.size() > 1,
3926
46.6k
                       /*LinkingOutput*/ LinkingOutput, CachedResults,
3927
46.6k
                       /*TargetDeviceOffloadKind*/ Action::OFK_None);
3928
46.6k
  }
3929
3930
46.6k
  StringRef StatReportFile;
3931
46.6k
  bool PrintProcessStat = false;
3932
46.6k
  if (const Arg *A = C.getArgs().getLastArg(options::OPT_fproc_stat_report_EQ))
3933
1
    StatReportFile = A->getValue();
3934
46.6k
  if (C.getArgs().hasArg(options::OPT_fproc_stat_report))
3935
1
    PrintProcessStat = true;
3936
3937
  // If we have more than one job, then disable integrated-cc1 for now. Do this
3938
  // also when we need to report process execution statistics.
3939
46.6k
  if (C.getJobs().size() > 1 || 
!StatReportFile.empty()42.2k
||
PrintProcessStat42.2k
)
3940
4.39k
    for (auto &J : C.getJobs())
3941
10.9k
      J.InProcess = false;
3942
3943
46.6k
  if (!StatReportFile.empty() || 
PrintProcessStat46.6k
) {
3944
2
    C.setPostCallback([=](const Command &Cmd, int Res) {
3945
2
      Optional<llvm::sys::ProcessStatistics> ProcStat =
3946
2
          Cmd.getProcessStatistics();
3947
2
      if (!ProcStat)
3948
0
        return;
3949
2
      if (PrintProcessStat) {
3950
1
        using namespace llvm;
3951
        // Human readable output.
3952
1
        outs() << sys::path::filename(Cmd.getExecutable()) << ": "
3953
1
               << "output=";
3954
1
        if (Cmd.getOutputFilenames().empty())
3955
0
          outs() << "\"\"";
3956
1
        else
3957
1
          outs() << Cmd.getOutputFilenames().front();
3958
1
        outs() << ", total="
3959
1
               << format("%.3f", ProcStat->TotalTime.count() / 1000.) << " ms"
3960
1
               << ", user="
3961
1
               << format("%.3f", ProcStat->UserTime.count() / 1000.) << " ms"
3962
1
               << ", mem=" << ProcStat->PeakMemory << " Kb\n";
3963
1
      }
3964
2
      if (!StatReportFile.empty()) {
3965
        // CSV format.
3966
1
        std::string Buffer;
3967
1
        llvm::raw_string_ostream Out(Buffer);
3968
1
        llvm::sys::printArg(Out, llvm::sys::path::filename(Cmd.getExecutable()),
3969
1
                            /*Quote*/ true);
3970
1
        Out << ',';
3971
1
        if (Cmd.getOutputFilenames().empty())
3972
0
          Out << "\"\"";
3973
1
        else
3974
1
          llvm::sys::printArg(Out, Cmd.getOutputFilenames().front(), true);
3975
1
        Out << ',' << ProcStat->TotalTime.count() << ','
3976
1
            << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory
3977
1
            << '\n';
3978
1
        Out.flush();
3979
1
        std::error_code EC;
3980
1
        llvm::raw_fd_ostream OS(StatReportFile, EC, llvm::sys::fs::OF_Append);
3981
1
        if (EC)
3982
0
          return;
3983
1
        auto L = OS.lock();
3984
1
        if (!L) {
3985
0
          llvm::errs() << "ERROR: Cannot lock file " << StatReportFile << ": "
3986
0
                       << toString(L.takeError()) << "\n";
3987
0
          return;
3988
0
        }
3989
1
        OS << Buffer;
3990
1
      }
3991
2
    });
3992
2
  }
3993
3994
  // If the user passed -Qunused-arguments or there were errors, don't warn
3995
  // about any unused arguments.
3996
46.6k
  if (Diags.hasErrorOccurred() ||
3997
45.5k
      C.getArgs().hasArg(options::OPT_Qunused_arguments))
3998
1.12k
    return;
3999
4000
  // Claim -### here.
4001
45.5k
  (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
4002
4003
  // Claim --driver-mode, --rsp-quoting, it was handled earlier.
4004
45.5k
  (void)C.getArgs().hasArg(options::OPT_driver_mode);
4005
45.5k
  (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
4006
4007
774k
  for (Arg *A : C.getArgs()) {
4008
    // FIXME: It would be nice to be able to send the argument to the
4009
    // DiagnosticsEngine, so that extra values, position, and so on could be
4010
    // printed.
4011
774k
    if (!A->isClaimed()) {
4012
434
      if (A->getOption().hasFlag(options::NoArgumentUnused))
4013
15
        continue;
4014
4015
      // Suppress the warning automatically if this is just a flag, and it is an
4016
      // instance of an argument we already claimed.
4017
419
      const Option &Opt = A->getOption();
4018
419
      if (Opt.getKind() == Option::FlagClass) {
4019
151
        bool DuplicateClaimed = false;
4020
4021
152
        for (const Arg *AA : C.getArgs().filtered(&Opt)) {
4022
152
          if (AA->isClaimed()) {
4023
1
            DuplicateClaimed = true;
4024
1
            break;
4025
1
          }
4026
152
        }
4027
4028
151
        if (DuplicateClaimed)
4029
1
          continue;
4030
418
      }
4031
4032
      // In clang-cl, don't mention unknown arguments here since they have
4033
      // already been warned about.
4034
418
      if (!IsCLMode() || 
!A->getOption().matches(options::OPT_UNKNOWN)114
)
4035
402
        Diag(clang::diag::warn_drv_unused_argument)
4036
402
            << A->getAsString(C.getArgs());
4037
418
    }
4038
774k
  }
4039
45.5k
}
4040
4041
namespace {
4042
/// Utility class to control the collapse of dependent actions and select the
4043
/// tools accordingly.
4044
class ToolSelector final {
4045
  /// The tool chain this selector refers to.
4046
  const ToolChain &TC;
4047
4048
  /// The compilation this selector refers to.
4049
  const Compilation &C;
4050
4051
  /// The base action this selector refers to.
4052
  const JobAction *BaseAction;
4053
4054
  /// Set to true if the current toolchain refers to host actions.
4055
  bool IsHostSelector;
4056
4057
  /// Set to true if save-temps and embed-bitcode functionalities are active.
4058
  bool SaveTemps;
4059
  bool EmbedBitcode;
4060
4061
  /// Get previous dependent action or null if that does not exist. If
4062
  /// \a CanBeCollapsed is false, that action must be legal to collapse or
4063
  /// null will be returned.
4064
  const JobAction *getPrevDependentAction(const ActionList &Inputs,
4065
                                          ActionList &SavedOffloadAction,
4066
177k
                                          bool CanBeCollapsed = true) {
4067
    // An option can be collapsed only if it has a single input.
4068
177k
    if (Inputs.size() != 1)
4069
1.18k
      return nullptr;
4070
4071
176k
    Action *CurAction = *Inputs.begin();
4072
176k
    if (CanBeCollapsed &&
4073
176k
        !CurAction->isCollapsingWithNextDependentActionLegal())
4074
129
      return nullptr;
4075
4076
    // If the input action is an offload action. Look through it and save any
4077
    // offload action that can be dropped in the event of a collapse.
4078
175k
    if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
4079
      // If the dependent action is a device action, we will attempt to collapse
4080
      // only with other device actions. Otherwise, we would do the same but
4081
      // with host actions only.
4082
797
      if (!IsHostSelector) {
4083
275
        if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
4084
275
          CurAction =
4085
275
              OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
4086
275
          if (CanBeCollapsed &&
4087
275
              !CurAction->isCollapsingWithNextDependentActionLegal())
4088
0
            return nullptr;
4089
275
          SavedOffloadAction.push_back(OA);
4090
275
          return dyn_cast<JobAction>(CurAction);
4091
275
        }
4092
522
      } else if (OA->hasHostDependence()) {
4093
399
        CurAction = OA->getHostDependence();
4094
399
        if (CanBeCollapsed &&
4095
399
            !CurAction->isCollapsingWithNextDependentActionLegal())
4096
0
          return nullptr;
4097
399
        SavedOffloadAction.push_back(OA);
4098
399
        return dyn_cast<JobAction>(CurAction);
4099
399
      }
4100
123
      return nullptr;
4101
123
    }
4102
4103
175k
    return dyn_cast<JobAction>(CurAction);
4104
175k
  }
4105
4106
  /// Return true if an assemble action can be collapsed.
4107
52.1k
  bool canCollapseAssembleAction() const {
4108
52.1k
    return TC.useIntegratedAs() && 
!SaveTemps48.2k
&&
4109
47.6k
           !C.getArgs().hasArg(options::OPT_via_file_asm) &&
4110
47.6k
           !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
4111
47.5k
           !C.getArgs().hasArg(options::OPT__SLASH_Fa);
4112
52.1k
  }
4113
4114
  /// Return true if a preprocessor action can be collapsed.
4115
55.4k
  bool canCollapsePreprocessorAction() const {
4116
55.4k
    return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
4117
55.4k
           
!C.getArgs().hasArg(options::OPT_traditional_cpp)55.4k
&& !SaveTemps &&
4118
54.7k
           !C.getArgs().hasArg(options::OPT_rewrite_objc);
4119
55.4k
  }
4120
4121
  /// Struct that relates an action with the offload actions that would be
4122
  /// collapsed with it.
4123
  struct JobActionInfo final {
4124
    /// The action this info refers to.
4125
    const JobAction *JA = nullptr;
4126
    /// The offload actions we need to take care off if this action is
4127
    /// collapsed.
4128
    ActionList SavedOffloadAction;
4129
  };
4130
4131
  /// Append collapsed offload actions from the give nnumber of elements in the
4132
  /// action info array.
4133
  static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
4134
                                           ArrayRef<JobActionInfo> &ActionInfo,
4135
12.0k
                                           unsigned ElementNum) {
4136
12.0k
    assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
4137
45.8k
    for (unsigned I = 0; I < ElementNum; 
++I33.8k
)
4138
33.8k
      CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
4139
33.8k
                                    ActionInfo[I].SavedOffloadAction.end());
4140
12.0k
  }
4141
4142
  /// Functions that attempt to perform the combining. They detect if that is
4143
  /// legal, and if so they update the inputs \a Inputs and the offload action
4144
  /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
4145
  /// the combined action is returned. If the combining is not legal or if the
4146
  /// tool does not exist, null is returned.
4147
  /// Currently three kinds of collapsing are supported:
4148
  ///  - Assemble + Backend + Compile;
4149
  ///  - Assemble + Backend ;
4150
  ///  - Backend + Compile.
4151
  const Tool *
4152
  combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
4153
                                ActionList &Inputs,
4154
53.1k
                                ActionList &CollapsedOffloadAction) {
4155
53.1k
    if (ActionInfo.size() < 3 || 
!canCollapseAssembleAction()16.8k
)
4156
38.4k
      return nullptr;
4157
14.6k
    auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
4158
14.6k
    auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
4159
14.6k
    auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
4160
14.6k
    if (!AJ || 
!BJ9.76k
||
!CJ9.76k
)
4161
4.95k
      return nullptr;
4162
4163
    // Get compiler tool.
4164
9.71k
    const Tool *T = TC.SelectTool(*CJ);
4165
9.71k
    if (!T)
4166
0
      return nullptr;
4167
4168
    // When using -fembed-bitcode, it is required to have the same tool (clang)
4169
    // for both CompilerJA and BackendJA. Otherwise, combine two stages.
4170
9.71k
    if (EmbedBitcode) {
4171
12
      const Tool *BT = TC.SelectTool(*BJ);
4172
12
      if (BT == T)
4173
12
        return nullptr;
4174
9.70k
    }
4175
4176
9.70k
    if (!T->hasIntegratedAssembler())
4177
0
      return nullptr;
4178
4179
9.70k
    Inputs = CJ->getInputs();
4180
9.70k
    AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4181
9.70k
                                 /*NumElements=*/3);
4182
9.70k
    return T;
4183
9.70k
  }
4184
  const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
4185
                                     ActionList &Inputs,
4186
43.4k
                                     ActionList &CollapsedOffloadAction) {
4187
43.4k
    if (ActionInfo.size() < 2 || 
!canCollapseAssembleAction()35.2k
)
4188
10.5k
      return nullptr;
4189
32.8k
    auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
4190
32.8k
    auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
4191
32.8k
    if (!AJ || 
!BJ153
)
4192
32.7k
      return nullptr;
4193
4194
    // Get backend tool.
4195
115
    const Tool *T = TC.SelectTool(*BJ);
4196
115
    if (!T)
4197
0
      return nullptr;
4198
4199
115
    if (!T->hasIntegratedAssembler())
4200
0
      return nullptr;
4201
4202
115
    Inputs = BJ->getInputs();
4203
115
    AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4204
115
                                 /*NumElements=*/2);
4205
115
    return T;
4206
115
  }
4207
  const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
4208
                                    ActionList &Inputs,
4209
43.3k
                                    ActionList &CollapsedOffloadAction) {
4210
43.3k
    if (ActionInfo.size() < 2)
4211
8.19k
      return nullptr;
4212
35.1k
    auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
4213
35.1k
    auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
4214
35.1k
    if (!BJ || 
!CJ2.33k
)
4215
32.7k
      return nullptr;
4216
4217
    // Check if the initial input (to the compile job or its predessor if one
4218
    // exists) is LLVM bitcode. In that case, no preprocessor step is required
4219
    // and we can still collapse the compile and backend jobs when we have
4220
    // -save-temps. I.e. there is no need for a separate compile job just to
4221
    // emit unoptimized bitcode.
4222
2.32k
    bool InputIsBitcode = true;
4223
4.65k
    for (size_t i = 1; i < ActionInfo.size(); 
i++2.32k
)
4224
4.62k
      if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
4225
2.30k
          ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
4226
2.30k
        InputIsBitcode = false;
4227
2.30k
        break;
4228
2.30k
      }
4229
2.32k
    if (!InputIsBitcode && 
!canCollapsePreprocessorAction()2.30k
)
4230
92
      return nullptr;
4231
4232
    // Get compiler tool.
4233
2.23k
    const Tool *T = TC.SelectTool(*CJ);
4234
2.23k
    if (!T)
4235
0
      return nullptr;
4236
4237
2.23k
    if (T->canEmitIR() && 
(2.22k
(2.22k
SaveTemps2.22k
&&
!InputIsBitcode11
) ||
EmbedBitcode2.22k
))
4238
0
      return nullptr;
4239
4240
2.23k
    Inputs = CJ->getInputs();
4241
2.23k
    AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4242
2.23k
                                 /*NumElements=*/2);
4243
2.23k
    return T;
4244
2.23k
  }
4245
4246
  /// Updates the inputs if the obtained tool supports combining with
4247
  /// preprocessor action, and the current input is indeed a preprocessor
4248
  /// action. If combining results in the collapse of offloading actions, those
4249
  /// are appended to \a CollapsedOffloadAction.
4250
  void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
4251
53.1k
                               ActionList &CollapsedOffloadAction) {
4252
53.1k
    if (!T || 
!canCollapsePreprocessorAction()53.1k
||
!T->hasIntegratedCPP()52.5k
)
4253
9.09k
      return;
4254
4255
    // Attempt to get a preprocessor action dependence.
4256
44.0k
    ActionList PreprocessJobOffloadActions;
4257
44.0k
    ActionList NewInputs;
4258
44.0k
    for (Action *A : Inputs) {
4259
44.0k
      auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
4260
44.0k
      if (!PJ || 
!isa<PreprocessJobAction>(PJ)39.7k
) {
4261
4.41k
        NewInputs.push_back(A);
4262
4.41k
        continue;
4263
4.41k
      }
4264
4265
      // This is legal to combine. Append any offload action we found and add the
4266
      // current input to preprocessor inputs.
4267
39.6k
      CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
4268
39.6k
                                    PreprocessJobOffloadActions.end());
4269
39.6k
      NewInputs.append(PJ->input_begin(), PJ->input_end());
4270
39.6k
    }
4271
44.0k
    Inputs = NewInputs;
4272
44.0k
  }
4273
4274
public:
4275
  ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
4276
               const Compilation &C, bool SaveTemps, bool EmbedBitcode)
4277
      : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
4278
53.1k
        EmbedBitcode(EmbedBitcode) {
4279
53.1k
    assert(BaseAction && "Invalid base action.");
4280
53.1k
    IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
4281
53.1k
  }
4282
4283
  /// Check if a chain of actions can be combined and return the tool that can
4284
  /// handle the combination of actions. The pointer to the current inputs \a
4285
  /// Inputs and the list of offload actions \a CollapsedOffloadActions
4286
  /// connected to collapsed actions are updated accordingly. The latter enables
4287
  /// the caller of the selector to process them afterwards instead of just
4288
  /// dropping them. If no suitable tool is found, null will be returned.
4289
  const Tool *getTool(ActionList &Inputs,
4290
53.1k
                      ActionList &CollapsedOffloadAction) {
4291
    //
4292
    // Get the largest chain of actions that we could combine.
4293
    //
4294
4295
53.1k
    SmallVector<JobActionInfo, 5> ActionChain(1);
4296
53.1k
    ActionChain.back().JA = BaseAction;
4297
186k
    while (ActionChain.back().JA) {
4298
133k
      const Action *CurAction = ActionChain.back().JA;
4299
4300
      // Grow the chain by one element.
4301
133k
      ActionChain.resize(ActionChain.size() + 1);
4302
133k
      JobActionInfo &AI = ActionChain.back();
4303
4304
      // Attempt to fill it with the
4305
133k
      AI.JA =
4306
133k
          getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
4307
133k
    }
4308
4309
    // Pop the last action info as it could not be filled.
4310
53.1k
    ActionChain.pop_back();
4311
4312
    //
4313
    // Attempt to combine actions. If all combining attempts failed, just return
4314
    // the tool of the provided action. At the end we attempt to combine the
4315
    // action with any preprocessor action it may depend on.
4316
    //
4317
4318
53.1k
    const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
4319
53.1k
                                                  CollapsedOffloadAction);
4320
53.1k
    if (!T)
4321
43.4k
      T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
4322
53.1k
    if (!T)
4323
43.3k
      T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
4324
53.1k
    if (!T) {
4325
41.0k
      Inputs = BaseAction->getInputs();
4326
41.0k
      T = TC.SelectTool(*BaseAction);
4327
41.0k
    }
4328
4329
53.1k
    combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
4330
53.1k
    return T;
4331
53.1k
  }
4332
};
4333
}
4334
4335
/// Return a string that uniquely identifies the result of a job. The bound arch
4336
/// is not necessarily represented in the toolchain's triple -- for example,
4337
/// armv7 and armv7s both map to the same triple -- so we need both in our map.
4338
/// Also, we need to add the offloading device kind, as the same tool chain can
4339
/// be used for host and device for some programming models, e.g. OpenMP.
4340
static std::string GetTriplePlusArchString(const ToolChain *TC,
4341
                                           StringRef BoundArch,
4342
124k
                                           Action::OffloadKind OffloadKind) {
4343
124k
  std::string TriplePlusArch = TC->getTriple().normalize();
4344
124k
  if (!BoundArch.empty()) {
4345
46.8k
    TriplePlusArch += "-";
4346
46.8k
    TriplePlusArch += BoundArch;
4347
46.8k
  }
4348
124k
  TriplePlusArch += "-";
4349
124k
  TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
4350
124k
  return TriplePlusArch;
4351
124k
}
4352
4353
InputInfo Driver::BuildJobsForAction(
4354
    Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
4355
    bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
4356
    std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
4357
124k
    Action::OffloadKind TargetDeviceOffloadKind) const {
4358
124k
  std::pair<const Action *, std::string> ActionTC = {
4359
124k
      A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4360
124k
  auto CachedResult = CachedResults.find(ActionTC);
4361
124k
  if (CachedResult != CachedResults.end()) {
4362
256
    return CachedResult->second;
4363
256
  }
4364
124k
  InputInfo Result = BuildJobsForActionNoCache(
4365
124k
      C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
4366
124k
      CachedResults, TargetDeviceOffloadKind);
4367
124k
  CachedResults[ActionTC] = Result;
4368
124k
  return Result;
4369
124k
}
4370
4371
InputInfo Driver::BuildJobsForActionNoCache(
4372
    Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
4373
    bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
4374
    std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
4375
124k
    Action::OffloadKind TargetDeviceOffloadKind) const {
4376
124k
  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
4377
4378
124k
  InputInfoList OffloadDependencesInputInfo;
4379
124k
  bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
4380
124k
  if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
4381
    // The 'Darwin' toolchain is initialized only when its arguments are
4382
    // computed. Get the default arguments for OFK_None to ensure that
4383
    // initialization is performed before processing the offload action.
4384
    // FIXME: Remove when darwin's toolchain is initialized during construction.
4385
849
    C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
4386
4387
    // The offload action is expected to be used in four different situations.
4388
    //
4389
    // a) Set a toolchain/architecture/kind for a host action:
4390
    //    Host Action 1 -> OffloadAction -> Host Action 2
4391
    //
4392
    // b) Set a toolchain/architecture/kind for a device action;
4393
    //    Device Action 1 -> OffloadAction -> Device Action 2
4394
    //
4395
    // c) Specify a device dependence to a host action;
4396
    //    Device Action 1  _
4397
    //                      \
4398
    //      Host Action 1  ---> OffloadAction -> Host Action 2
4399
    //
4400
    // d) Specify a host dependence to a device action.
4401
    //      Host Action 1  _
4402
    //                      \
4403
    //    Device Action 1  ---> OffloadAction -> Device Action 2
4404
    //
4405
    // For a) and b), we just return the job generated for the dependence. For
4406
    // c) and d) we override the current action with the host/device dependence
4407
    // if the current toolchain is host/device and set the offload dependences
4408
    // info with the jobs obtained from the device/host dependence(s).
4409
4410
    // If there is a single device option, just generate the job for it.
4411
849
    if (OA->hasSingleDeviceDependence()) {
4412
823
      InputInfo DevA;
4413
823
      OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
4414
823
                                       const char *DepBoundArch) {
4415
823
        DevA =
4416
823
            BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
4417
823
                               /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
4418
823
                               CachedResults, DepA->getOffloadingDeviceKind());
4419
823
      });
4420
823
      return DevA;
4421
823
    }
4422
4423
    // If 'Action 2' is host, we generate jobs for the device dependences and
4424
    // override the current action with the host dependence. Otherwise, we
4425
    // generate the host dependences and override the action with the device
4426
    // dependence. The dependences can't therefore be a top-level action.
4427
26
    OA->doOnEachDependence(
4428
26
        /*IsHostDependence=*/BuildingForOffloadDevice,
4429
26
        [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4430
26
          OffloadDependencesInputInfo.push_back(BuildJobsForAction(
4431
26
              C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
4432
26
              /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
4433
26
              DepA->getOffloadingDeviceKind()));
4434
26
        });
4435
4436
26
    A = BuildingForOffloadDevice
4437
17
            ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
4438
9
            : OA->getHostDependence();
4439
26
  }
4440
4441
123k
  if (const InputAction *IA = dyn_cast<InputAction>(A)) {
4442
    // FIXME: It would be nice to not claim this here; maybe the old scheme of
4443
    // just using Args was better?
4444
48.7k
    const Arg &Input = IA->getInputArg();
4445
48.7k
    Input.claim();
4446
48.7k
    if (Input.getOption().matches(options::OPT_INPUT)) {
4447
47.6k
      const char *Name = Input.getValue();
4448
47.6k
      return InputInfo(A, Name, /* _BaseInput = */ Name);
4449
47.6k
    }
4450
1.15k
    return InputInfo(A, &Input, /* _BaseInput = */ "");
4451
1.15k
  }
4452
4453
74.4k
  if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
4454
21.3k
    const ToolChain *TC;
4455
21.3k
    StringRef ArchName = BAA->getArchName();
4456
4457
21.3k
    if (!ArchName.empty())
4458
21.3k
      TC = &getToolChain(C.getArgs(),
4459
21.3k
                         computeTargetTriple(*this, TargetTriple,
4460
21.3k
                                             C.getArgs(), ArchName));
4461
1
    else
4462
1
      TC = &C.getDefaultToolChain();
4463
4464
21.3k
    return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
4465
21.3k
                              MultipleArchs, LinkingOutput, CachedResults,
4466
21.3k
                              TargetDeviceOffloadKind);
4467
21.3k
  }
4468
4469
4470
53.1k
  ActionList Inputs = A->getInputs();
4471
4472
53.1k
  const JobAction *JA = cast<JobAction>(A);
4473
53.1k
  ActionList CollapsedOffloadActions;
4474
4475
53.1k
  ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
4476
53.1k
                  embedBitcodeInObject() && 
!isUsingLTO()41
);
4477
53.1k
  const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
4478
4479
53.1k
  if (!T)
4480
1
    return InputInfo();
4481
4482
  // If we've collapsed action list that contained OffloadAction we
4483
  // need to build jobs for host/device-side inputs it may have held.
4484
53.1k
  for (const auto *OA : CollapsedOffloadActions)
4485
321
    cast<OffloadAction>(OA)->doOnEachDependence(
4486
321
        /*IsHostDependence=*/BuildingForOffloadDevice,
4487
321
        [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4488
321
          OffloadDependencesInputInfo.push_back(BuildJobsForAction(
4489
321
              C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
4490
321
              /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
4491
321
              DepA->getOffloadingDeviceKind()));
4492
321
        });
4493
4494
  // Only use pipes when there is exactly one input.
4495
53.1k
  InputInfoList InputInfos;
4496
55.1k
  for (const Action *Input : Inputs) {
4497
    // Treat dsymutil and verify sub-jobs as being at the top-level too, they
4498
    // shouldn't get temporary output names.
4499
    // FIXME: Clean this up.
4500
55.1k
    bool SubJobAtTopLevel =
4501
55.1k
        AtTopLevel && 
(48.4k
isa<DsymutilJobAction>(A)48.4k
||
isa<VerifyJobAction>(A)48.4k
);
4502
55.1k
    InputInfos.push_back(BuildJobsForAction(
4503
55.1k
        C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
4504
55.1k
        CachedResults, A->getOffloadingDeviceKind()));
4505
55.1k
  }
4506
4507
  // Always use the first input as the base input.
4508
53.1k
  const char *BaseInput = InputInfos[0].getBaseInput();
4509
4510
  // ... except dsymutil actions, which use their actual input as the base
4511
  // input.
4512
53.1k
  if (JA->getType() == types::TY_dSYM)
4513
89
    BaseInput = InputInfos[0].getFilename();
4514
4515
  // ... and in header module compilations, which use the module name.
4516
53.1k
  if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
4517
3
    BaseInput = ModuleJA->getModuleName();
4518
4519
  // Append outputs of offload device jobs to the input list
4520
53.1k
  if (!OffloadDependencesInputInfo.empty())
4521
347
    InputInfos.append(OffloadDependencesInputInfo.begin(),
4522
347
                      OffloadDependencesInputInfo.end());
4523
4524
  // Set the effective triple of the toolchain for the duration of this job.
4525
53.1k
  llvm::Triple EffectiveTriple;
4526
53.1k
  const ToolChain &ToolTC = T->getToolChain();
4527
53.1k
  const ArgList &Args =
4528
53.1k
      C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
4529
53.1k
  if (InputInfos.size() != 1) {
4530
1.51k
    EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
4531
51.6k
  } else {
4532
    // Pass along the input type if it can be unambiguously determined.
4533
51.6k
    EffectiveTriple = llvm::Triple(
4534
51.6k
        ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
4535
51.6k
  }
4536
53.1k
  RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
4537
4538
  // Determine the place to write output to, if any.
4539
53.1k
  InputInfo Result;
4540
53.1k
  InputInfoList UnbundlingResults;
4541
53.1k
  if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
4542
    // If we have an unbundling job, we need to create results for all the
4543
    // outputs. We also update the results cache so that other actions using
4544
    // this unbundling action can get the right results.
4545
124
    for (auto &UI : UA->getDependentActionsInfo()) {
4546
124
      assert(UI.DependentOffloadKind != Action::OFK_None &&
4547
124
             "Unbundling with no offloading??");
4548
4549
      // Unbundling actions are never at the top level. When we generate the
4550
      // offloading prefix, we also do that for the host file because the
4551
      // unbundling action does not change the type of the output which can
4552
      // cause a overwrite.
4553
124
      std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4554
124
          UI.DependentOffloadKind,
4555
124
          UI.DependentToolChain->getTriple().normalize(),
4556
124
          /*CreatePrefixForHost=*/true);
4557
124
      auto CurI = InputInfo(
4558
124
          UA,
4559
124
          GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
4560
124
                             /*AtTopLevel=*/false,
4561
124
                             MultipleArchs ||
4562
78
                                 UI.DependentOffloadKind == Action::OFK_HIP,
4563
124
                             OffloadingPrefix),
4564
124
          BaseInput);
4565
      // Save the unbundling result.
4566
124
      UnbundlingResults.push_back(CurI);
4567
4568
      // Get the unique string identifier for this dependence and cache the
4569
      // result.
4570
124
      StringRef Arch;
4571
124
      if (TargetDeviceOffloadKind == Action::OFK_HIP) {
4572
46
        if (UI.DependentOffloadKind == Action::OFK_Host)
4573
16
          Arch = StringRef();
4574
30
        else
4575
30
          Arch = UI.DependentBoundArch;
4576
46
      } else
4577
78
        Arch = BoundArch;
4578
4579
124
      CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
4580
124
                                                UI.DependentOffloadKind)}] =
4581
124
          CurI;
4582
124
    }
4583
4584
    // Now that we have all the results generated, select the one that should be
4585
    // returned for the current depending action.
4586
45
    std::pair<const Action *, std::string> ActionTC = {
4587
45
        A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4588
45
    assert(CachedResults.find(ActionTC) != CachedResults.end() &&
4589
45
           "Result does not exist??");
4590
45
    Result = CachedResults[ActionTC];
4591
53.0k
  } else if (JA->getType() == types::TY_Nothing)
4592
27.5k
    Result = InputInfo(A, BaseInput);
4593
25.5k
  else {
4594
    // We only have to generate a prefix for the host if this is not a top-level
4595
    // action.
4596
25.5k
    std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4597
25.5k
        A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
4598
25.5k
        /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
4599
974
            !AtTopLevel);
4600
25.5k
    if (isa<OffloadWrapperJobAction>(JA)) {
4601
65
      OffloadingPrefix += "-wrapper";
4602
65
      if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
4603
6
        BaseInput = FinalOutput->getValue();
4604
59
      else
4605
59
        BaseInput = getDefaultImageName();
4606
65
    }
4607
25.5k
    Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
4608
25.5k
                                             AtTopLevel, MultipleArchs,
4609
25.5k
                                             OffloadingPrefix),
4610
25.5k
                       BaseInput);
4611
25.5k
  }
4612
4613
53.1k
  if (CCCPrintBindings && 
!CCGenDiagnostics104
) {
4614
104
    llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
4615
104
                 << " - \"" << T->getName() << "\", inputs: [";
4616
227
    for (unsigned i = 0, e = InputInfos.size(); i != e; 
++i123
) {
4617
123
      llvm::errs() << InputInfos[i].getAsString();
4618
123
      if (i + 1 != e)
4619
19
        llvm::errs() << ", ";
4620
123
    }
4621
104
    if (UnbundlingResults.empty())
4622
98
      llvm::errs() << "], output: " << Result.getAsString() << "\n";
4623
6
    else {
4624
6
      llvm::errs() << "], outputs: [";
4625
24
      for (unsigned i = 0, e = UnbundlingResults.size(); i != e; 
++i18
) {
4626
18
        llvm::errs() << UnbundlingResults[i].getAsString();
4627
18
        if (i + 1 != e)
4628
12
          llvm::errs() << ", ";
4629
18
      }
4630
6
      llvm::errs() << "] \n";
4631
6
    }
4632
53.0k
  } else {
4633
53.0k
    if (UnbundlingResults.empty())
4634
52.9k
      T->ConstructJob(
4635
52.9k
          C, *JA, Result, InputInfos,
4636
52.9k
          C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4637
52.9k
          LinkingOutput);
4638
40
    else
4639
40
      T->ConstructJobMultipleOutputs(
4640
40
          C, *JA, UnbundlingResults, InputInfos,
4641
40
          C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4642
40
          LinkingOutput);
4643
53.0k
  }
4644
53.1k
  return Result;
4645
53.1k
}
4646
4647
2.50k
const char *Driver::getDefaultImageName() const {
4648
2.50k
  llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
4649
2.39k
  return Target.isOSWindows() ? 
"a.exe"105
: "a.out";
4650
2.50k
}
4651
4652
/// Create output filename based on ArgValue, which could either be a
4653
/// full filename, filename without extension, or a directory. If ArgValue
4654
/// does not provide a filename, then use BaseName, and use the extension
4655
/// suitable for FileType.
4656
static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
4657
                                        StringRef BaseName,
4658
404
                                        types::ID FileType) {
4659
404
  SmallString<128> Filename = ArgValue;
4660
4661
404
  if (ArgValue.empty()) {
4662
    // If the argument is empty, output to BaseName in the current dir.
4663
295
    Filename = BaseName;
4664
109
  } else if (llvm::sys::path::is_separator(Filename.back())) {
4665
    // If the argument is a directory, output to BaseName in that dir.
4666
23
    llvm::sys::path::append(Filename, BaseName);
4667
23
  }
4668
4669
404
  if (!llvm::sys::path::has_extension(ArgValue)) {
4670
    // If the argument didn't provide an extension, then set it.
4671
353
    const char *Extension = types::getTypeTempSuffix(FileType, true);
4672
4673
353
    if (FileType == types::TY_Image &&
4674
298
        Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
4675
      // The output file is a dll.
4676
34
      Extension = "dll";
4677
34
    }
4678
4679
353
    llvm::sys::path::replace_extension(Filename, Extension);
4680
353
  }
4681
4682
404
  return Args.MakeArgString(Filename.c_str());
4683
404
}
4684
4685
10.0k
static bool HasPreprocessOutput(const Action &JA) {
4686
10.0k
  if (isa<PreprocessJobAction>(JA))
4687
3.14k
    return true;
4688
6.89k
  if (isa<OffloadAction>(JA) && 
isa<PreprocessJobAction>(JA.getInputs()[0])13
)
4689
2
    return true;
4690
6.88k
  if (isa<OffloadBundlingJobAction>(JA) &&
4691
13
      HasPreprocessOutput(*(JA.getInputs()[0])))
4692
2
    return true;
4693
6.88k
  return false;
4694
6.88k
}
4695
4696
const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
4697
                                       const char *BaseInput,
4698
                                       StringRef OrigBoundArch, bool AtTopLevel,
4699
                                       bool MultipleArchs,
4700
25.6k
                                       StringRef OffloadingPrefix) const {
4701
25.6k
  std::string BoundArch = OrigBoundArch.str();
4702
#if defined(_WIN32)
4703
  // BoundArch may contains ':', which is invalid in file names on Windows,
4704
  // therefore replace it with '%'.
4705
  std::replace(BoundArch.begin(), BoundArch.end(), ':', '@');
4706
#endif
4707
4708
25.6k
  llvm::PrettyStackTraceString CrashInfo("Computing output path");
4709
  // Output to a user requested destination?
4710
25.6k
  if (AtTopLevel && 
!isa<DsymutilJobAction>(JA)19.2k
&&
!isa<VerifyJobAction>(JA)19.1k
) {
4711
19.1k
    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
4712
9.17k
      return C.addResultFile(FinalOutput->getValue(), &JA);
4713
16.4k
  }
4714
4715
  // For /P, preprocess to file named after BaseInput.
4716
16.4k
  if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
4717
12
    assert(AtTopLevel && isa<PreprocessJobAction>(JA));
4718
12
    StringRef BaseName = llvm::sys::path::filename(BaseInput);
4719
12
    StringRef NameArg;
4720
12
    if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
4721
4
      NameArg = A->getValue();
4722
12
    return C.addResultFile(
4723
12
        MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
4724
12
        &JA);
4725
12
  }
4726
4727
  // Default to writing to stdout?
4728
16.4k
  if (AtTopLevel && 
!CCGenDiagnostics10.0k
&&
HasPreprocessOutput(JA)10.0k
) {
4729
3.14k
    return "-";
4730
3.14k
  }
4731
4732
  // Is this the assembly listing for /FA?
4733
13.3k
  if (JA.getType() == types::TY_PP_Asm &&
4734
1.44k
      (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
4735
1.43k
       C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
4736
    // Use /Fa and the input filename to determine the asm file name.
4737
18
    StringRef BaseName = llvm::sys::path::filename(BaseInput);
4738
18
    StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
4739
18
    return C.addResultFile(
4740
18
        MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
4741
18
        &JA);
4742
18
  }
4743
4744
  // Output to a temporary file?
4745
13.3k
  if ((!AtTopLevel && 
!isSaveTempsEnabled()6.40k
&&
4746
5.85k
       !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
4747
7.48k
      CCGenDiagnostics) {
4748
5.86k
    StringRef Name = llvm::sys::path::filename(BaseInput);
4749
5.86k
    std::pair<StringRef, StringRef> Split = Name.split('.');
4750
5.86k
    SmallString<128> TmpName;
4751
5.86k
    const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4752
5.86k
    Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
4753
5.86k
    if (CCGenDiagnostics && 
A37
) {
4754
1
      SmallString<128> CrashDirectory(A->getValue());
4755
1
      if (!getVFS().exists(CrashDirectory))
4756
1
        llvm::sys::fs::create_directories(CrashDirectory);
4757
1
      llvm::sys::path::append(CrashDirectory, Split.first);
4758
1
      const char *Middle = Suffix ? "-%%%%%%." : 
"-%%%%%%"0
;
4759
1
      std::error_code EC = llvm::sys::fs::createUniqueFile(
4760
1
          CrashDirectory + Middle + Suffix, TmpName);
4761
1
      if (EC) {
4762
0
        Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4763
0
        return "";
4764
0
      }
4765
5.86k
    } else {
4766
5.86k
      TmpName = GetTemporaryPath(Split.first, Suffix);
4767
5.86k
    }
4768
5.86k
    return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4769
7.44k
  }
4770
4771
7.44k
  SmallString<128> BasePath(BaseInput);
4772
7.44k
  SmallString<128> ExternalPath("");
4773
7.44k
  StringRef BaseName;
4774
4775
  // Dsymutil actions should use the full path.
4776
7.44k
  if (isa<DsymutilJobAction>(JA) && 
C.getArgs().hasArg(options::OPT_dsym_dir)89
) {
4777
1
    ExternalPath += C.getArgs().getLastArg(options::OPT_dsym_dir)->getValue();
4778
    // We use posix style here because the tests (specifically
4779
    // darwin-dsymutil.c) demonstrate that posix style paths are acceptable
4780
    // even on Windows and if we don't then the similar test covering this
4781
    // fails.
4782
1
    llvm::sys::path::append(ExternalPath, llvm::sys::path::Style::posix,
4783
1
                            llvm::sys::path::filename(BasePath));
4784
1
    BaseName = ExternalPath;
4785
7.44k
  } else if (isa<DsymutilJobAction>(JA) || 
isa<VerifyJobAction>(JA)7.35k
)
4786
88
    BaseName = BasePath;
4787
7.35k
  else
4788
7.35k
    BaseName = llvm::sys::path::filename(BasePath);
4789
4790
  // Determine what the derived output name should be.
4791
7.44k
  const char *NamedOutput;
4792
4793
7.44k
  if ((JA.getType() == types::TY_Object || 
JA.getType() == types::TY_LTO_BC3.89k
) &&
4794
3.59k
      C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
4795
    // The /Fo or /o flag decides the object filename.
4796
60
    StringRef Val =
4797
60
        C.getArgs()
4798
60
            .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
4799
60
            ->getValue();
4800
60
    NamedOutput =
4801
60
        MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
4802
7.38k
  } else if (JA.getType() == types::TY_Image &&
4803
2.75k
             C.getArgs().hasArg(options::OPT__SLASH_Fe,
4804
43
                                options::OPT__SLASH_o)) {
4805
    // The /Fe or /o flag names the linked file.
4806
43
    StringRef Val =
4807
43
        C.getArgs()
4808
43
            .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
4809
43
            ->getValue();
4810
43
    NamedOutput =
4811
43
        MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
4812
7.34k
  } else if (JA.getType() == types::TY_Image) {
4813
2.71k
    if (IsCLMode()) {
4814
      // clang-cl uses BaseName for the executable name.
4815
271
      NamedOutput =
4816
271
          MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
4817
2.44k
    } else {
4818
2.44k
      SmallString<128> Output(getDefaultImageName());
4819
      // HIP image for device compilation with -fno-gpu-rdc is per compilation
4820
      // unit.
4821
2.44k
      bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
4822
14
                        !C.getArgs().hasFlag(options::OPT_fgpu_rdc,
4823
14
                                             options::OPT_fno_gpu_rdc, false);
4824
2.44k
      if (IsHIPNoRDC) {
4825
5
        Output = BaseName;
4826
5
        llvm::sys::path::replace_extension(Output, "");
4827
5
      }
4828
2.44k
      Output += OffloadingPrefix;
4829
2.44k
      if (MultipleArchs && 
!BoundArch.empty()24
) {
4830
18
        Output += "-";
4831
18
        Output.append(BoundArch);
4832
18
      }
4833
2.44k
      if (IsHIPNoRDC)
4834
5
        Output += ".out";
4835
2.44k
      NamedOutput = C.getArgs().MakeArgString(Output.c_str());
4836
2.44k
    }
4837
4.63k
  } else if (JA.getType() == types::TY_PCH && 
IsCLMode()20
) {
4838
19
    NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
4839
4.61k
  } else {
4840
4.61k
    const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4841
4.61k
    assert(Suffix && "All types used for output should have a suffix.");
4842
4843
4.61k
    std::string::size_type End = std::string::npos;
4844
4.61k
    if (!types::appendSuffixForType(JA.getType()))
4845
4.51k
      End = BaseName.rfind('.');
4846
4.61k
    SmallString<128> Suffixed(BaseName.substr(0, End));
4847
4.61k
    Suffixed += OffloadingPrefix;
4848
4.61k
    if (MultipleArchs && 
!BoundArch.empty()181
) {
4849
165
      Suffixed += "-";
4850
165
      Suffixed.append(BoundArch);
4851
165
    }
4852
    // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
4853
    // the unoptimized bitcode so that it does not get overwritten by the ".bc"
4854
    // optimized bitcode output.
4855
4.61k
    auto IsHIPRDCInCompilePhase = [](const JobAction &JA,
4856
125
                                     const llvm::opt::DerivedArgList &Args) {
4857
      // The relocatable compilation in HIP implies -emit-llvm. Similarly, use a
4858
      // ".tmp.bc" suffix for the unoptimized bitcode (generated in the compile
4859
      // phase.)
4860
125
      return isa<CompileJobAction>(JA) &&
4861
111
             JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
4862
11
             Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4863
11
                          false);
4864
125
    };
4865
4.61k
    if (!AtTopLevel && 
JA.getType() == types::TY_LLVM_BC525
&&
4866
126
        (C.getArgs().hasArg(options::OPT_emit_llvm) ||
4867
125
         IsHIPRDCInCompilePhase(JA, C.getArgs())))
4868
7
      Suffixed += ".tmp";
4869
4.61k
    Suffixed += '.';
4870
4.61k
    Suffixed += Suffix;
4871
4.61k
    NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
4872
4.61k
  }
4873
4874
  // Prepend object file path if -save-temps=obj
4875
7.44k
  if (!AtTopLevel && 
isSaveTempsObj()572
&&
C.getArgs().hasArg(options::OPT_o)15
&&
4876
11
      JA.getType() != types::TY_PCH) {
4877
11
    Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4878
11
    SmallString<128> TempPath(FinalOutput->getValue());
4879
11
    llvm::sys::path::remove_filename(TempPath);
4880
11
    StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
4881
11
    llvm::sys::path::append(TempPath, OutputFileName);
4882
11
    NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
4883
11
  }
4884
4885
  // If we're saving temps and the temp file conflicts with the input file,
4886
  // then avoid overwriting input file.
4887
7.44k
  if (!AtTopLevel && 
isSaveTempsEnabled()572
&&
NamedOutput == BaseName558
) {
4888
0
    bool SameFile = false;
4889
0
    SmallString<256> Result;
4890
0
    llvm::sys::fs::current_path(Result);
4891
0
    llvm::sys::path::append(Result, BaseName);
4892
0
    llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
4893
    // Must share the same path to conflict.
4894
0
    if (SameFile) {
4895
0
      StringRef Name = llvm::sys::path::filename(BaseInput);
4896
0
      std::pair<StringRef, StringRef> Split = Name.split('.');
4897
0
      std::string TmpName = GetTemporaryPath(
4898
0
          Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
4899
0
      return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4900
0
    }
4901
7.44k
  }
4902
4903
  // As an annoying special case, PCH generation doesn't strip the pathname.
4904
7.44k
  if (JA.getType() == types::TY_PCH && 
!IsCLMode()20
) {
4905
1
    llvm::sys::path::remove_filename(BasePath);
4906
1
    if (BasePath.empty())
4907
0
      BasePath = NamedOutput;
4908
1
    else
4909
1
      llvm::sys::path::append(BasePath, NamedOutput);
4910
1
    return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
4911
7.44k
  } else {
4912
7.44k
    return C.addResultFile(NamedOutput, &JA);
4913
7.44k
  }
4914
7.44k
}
4915
4916
9.43k
std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
4917
  // Search for Name in a list of paths.
4918
9.43k
  auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
4919
28.2k
      -> llvm::Optional<std::string> {
4920
    // Respect a limited subset of the '-Bprefix' functionality in GCC by
4921
    // attempting to use this prefix when looking for file paths.
4922
21.9k
    for (const auto &Dir : P) {
4923
21.9k
      if (Dir.empty())
4924
165
        continue;
4925
21.8k
      SmallString<128> P(Dir[0] == '=' ? 
SysRoot + Dir.substr(1)1.05k
:
Dir20.7k
);
4926
21.8k
      llvm::sys::path::append(P, Name);
4927
21.8k
      if (llvm::sys::fs::exists(Twine(P)))
4928
2.12k
        return std::string(P);
4929
21.8k
    }
4930
26.1k
    return None;
4931
28.2k
  };
4932
4933
9.43k
  if (auto P = SearchPaths(PrefixDirs))
4934
0
    return *P;
4935
4936
9.43k
  SmallString<128> R(ResourceDir);
4937
9.43k
  llvm::sys::path::append(R, Name);
4938
9.43k
  if (llvm::sys::fs::exists(Twine(R)))
4939
27
    return std::string(R.str());
4940
4941
9.40k
  SmallString<128> P(TC.getCompilerRTPath());
4942
9.40k
  llvm::sys::path::append(P, Name);
4943
9.40k
  if (llvm::sys::fs::exists(Twine(P)))
4944
0
    return std::string(P.str());
4945
4946
9.40k
  SmallString<128> D(Dir);
4947
9.40k
  llvm::sys::path::append(D, "..", Name);
4948
9.40k
  if (llvm::sys::fs::exists(Twine(D)))
4949
1
    return std::string(D.str());
4950
4951
9.40k
  if (auto P = SearchPaths(TC.getLibraryPaths()))
4952
2
    return *P;
4953
4954
9.40k
  if (auto P = SearchPaths(TC.getFilePaths()))
4955
2.12k
    return *P;
4956
4957
7.28k
  return std::string(Name);
4958
7.28k
}
4959
4960
void Driver::generatePrefixedToolNames(
4961
    StringRef Tool, const ToolChain &TC,
4962
8.68k
    SmallVectorImpl<std::string> &Names) const {
4963
  // FIXME: Needs a better variable than TargetTriple
4964
8.68k
  Names.emplace_back((TargetTriple + "-" + Tool).str());
4965
8.68k
  Names.emplace_back(Tool);
4966
4967
  // Allow the discovery of tools prefixed with LLVM's default target triple.
4968
8.68k
  std::string DefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4969
8.68k
  if (DefaultTargetTriple != TargetTriple)
4970
5.21k
    Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
4971
8.68k
}
4972
4973
21.1k
static bool ScanDirForExecutable(SmallString<128> &Dir, StringRef Name) {
4974
21.1k
  llvm::sys::path::append(Dir, Name);
4975
21.1k
  if (llvm::sys::fs::can_execute(Twine(Dir)))
4976
560
    return true;
4977
20.6k
  llvm::sys::path::remove_filename(Dir);
4978
20.6k
  return false;
4979
20.6k
}
4980
4981
8.68k
std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
4982
8.68k
  SmallVector<std::string, 2> TargetSpecificExecutables;
4983
8.68k
  generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4984
4985
  // Respect a limited subset of the '-Bprefix' functionality in GCC by
4986
  // attempting to use this prefix when looking for program paths.
4987
66
  for (const auto &PrefixDir : PrefixDirs) {
4988
66
    if (llvm::sys::fs::is_directory(PrefixDir)) {
4989
57
      SmallString<128> P(PrefixDir);
4990
57
      if (ScanDirForExecutable(P, Name))
4991
30
        return std::string(P.str());
4992
9
    } else {
4993
9
      SmallString<128> P((PrefixDir + Name).str());
4994
9
      if (llvm::sys::fs::can_execute(Twine(P)))
4995
9
        return std::string(P.str());
4996
9
    }
4997
66
  }
4998
4999
8.64k
  const ToolChain::path_list &List = TC.getProgramPaths();
5000
19.0k
  for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) {
5001
    // For each possible name of the tool look for it in
5002
    // program paths first, then the path.
5003
    // Higher priority names will be first, meaning that
5004
    // a higher priority name in the path will be found
5005
    // instead of a lower priority name in the program path.
5006
    // E.g. <triple>-gcc on the path will be found instead
5007
    // of gcc in the program path
5008
21.1k
    for (const auto &Path : List) {
5009
21.1k
      SmallString<128> P(Path);
5010
21.1k
      if (ScanDirForExecutable(P, TargetSpecificExecutable))
5011
530
        return std::string(P.str());
5012
21.1k
    }
5013
5014
    // Fall back to the path
5015
18.4k
    if (llvm::ErrorOr<std::string> P =
5016
6.24k
            llvm::sys::findProgramByName(TargetSpecificExecutable))
5017
6.24k
      return *P;
5018
18.4k
  }
5019
5020
1.87k
  return std::string(Name);
5021
8.64k
}
5022
5023
5.92k
std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
5024
5.92k
  SmallString<128> Path;
5025
5.92k
  std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
5026
5.92k
  if (EC) {
5027
0
    Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5028
0
    return "";
5029
0
  }
5030
5031
5.92k
  return std::string(Path.str());
5032
5.92k
}
5033
5034
5
std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
5035
5
  SmallString<128> Path;
5036
5
  std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
5037
5
  if (EC) {
5038
0
    Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5039
0
    return "";
5040
0
  }
5041
5042
5
  return std::string(Path.str());
5043
5
}
5044
5045
52
std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
5046
52
  SmallString<128> Output;
5047
52
  if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
5048
    // FIXME: If anybody needs it, implement this obscure rule:
5049
    // "If you specify a directory without a file name, the default file name
5050
    // is VCx0.pch., where x is the major version of Visual C++ in use."
5051
25
    Output = FpArg->getValue();
5052
5053
    // "If you do not specify an extension as part of the path name, an
5054
    // extension of .pch is assumed. "
5055
25
    if (!llvm::sys::path::has_extension(Output))
5056
0
      Output += ".pch";
5057
27
  } else {
5058
27
    if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
5059
20
      Output = YcArg->getValue();
5060
27
    if (Output.empty())
5061
9
      Output = BaseName;
5062
27
    llvm::sys::path::replace_extension(Output, ".pch");
5063
27
  }
5064
52
  return std::string(Output.str());
5065
52
}
5066
5067
const ToolChain &Driver::getToolChain(const ArgList &Args,
5068
69.2k
                                      const llvm::Triple &Target) const {
5069
5070
69.2k
  auto &TC = ToolChains[Target.str()];
5071
69.2k
  if (!TC) {
5072
48.1k
    switch (Target.getOS()) {
5073
99
    case llvm::Triple::AIX:
5074
99
      TC = std::make_unique<toolchains::AIX>(*this, Target, Args);
5075
99
      break;
5076
0
    case llvm::Triple::Haiku:
5077
0
      TC = std::make_unique<toolchains::Haiku>(*this, Target, Args);
5078
0
      break;
5079
2
    case llvm::Triple::Ananas:
5080
2
      TC = std::make_unique<toolchains::Ananas>(*this, Target, Args);
5081
2
      break;
5082
14
    case llvm::Triple::CloudABI:
5083
14
      TC = std::make_unique<toolchains::CloudABI>(*this, Target, Args);
5084
14
      break;
5085
20.8k
    case llvm::Triple::Darwin:
5086
22.3k
    case llvm::Triple::MacOSX:
5087
22.5k
    case llvm::Triple::IOS:
5088
22.5k
    case llvm::Triple::TvOS:
5089
22.6k
    case llvm::Triple::WatchOS:
5090
22.6k
      TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args);
5091
22.6k
      break;
5092
2
    case llvm::Triple::DragonFly:
5093
2
      TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args);
5094
2
      break;
5095
87
    case llvm::Triple::OpenBSD:
5096
87
      TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args);
5097
87
      break;
5098
192
    case llvm::Triple::NetBSD:
5099
192
      TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args);
5100
192
      break;
5101
158
    case llvm::Triple::FreeBSD:
5102
158
      TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args);
5103
158
      break;
5104
0
    case llvm::Triple::Minix:
5105
0
      TC = std::make_unique<toolchains::Minix>(*this, Target, Args);
5106
0
      break;
5107
4.65k
    case llvm::Triple::Linux:
5108
4.66k
    case llvm::Triple::ELFIAMCU:
5109
4.66k
      if (Target.getArch() == llvm::Triple::hexagon)
5110
8
        TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
5111
8
                                                             Args);
5112
4.65k
      else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
5113
139
               !Target.hasEnvironment())
5114
2
        TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
5115
2
                                                              Args);
5116
4.65k
      else if (Target.isPPC())
5117
284
        TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
5118
284
                                                              Args);
5119
4.37k
      else if (Target.getArch() == llvm::Triple::ve)
5120
0
        TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
5121
5122
4.37k
      else
5123
4.37k
        TC = std::make_unique<toolchains::Linux>(*this, Target, Args);
5124
4.66k
      break;
5125
23
    case llvm::Triple::NaCl:
5126
23
      TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
5127
23
      break;
5128
42
    case llvm::Triple::Fuchsia:
5129
42
      TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args);
5130
42
      break;
5131
36
    case llvm::Triple::Solaris:
5132
36
      TC = std::make_unique<toolchains::Solaris>(*this, Target, Args);
5133
36
      break;
5134
101
    case llvm::Triple::AMDHSA:
5135
101
      TC = std::make_unique<toolchains::ROCMToolChain>(*this, Target, Args);
5136
101
      break;
5137
11
    case llvm::Triple::AMDPAL:
5138
23
    case llvm::Triple::Mesa3D:
5139
23
      TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
5140
23
      break;
5141
7.89k
    case llvm::Triple::Win32:
5142
7.89k
      switch (Target.getEnvironment()) {
5143
9
      default:
5144
9
        if (Target.isOSBinFormatELF())
5145
0
          TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
5146
9
        else if (Target.isOSBinFormatMachO())
5147
0
          TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
5148
9
        else
5149
9
          TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
5150
9
        break;
5151
99
      case llvm::Triple::GNU:
5152
99
        TC = std::make_unique<toolchains::MinGW>(*this, Target, Args);
5153
99
        break;
5154
57
      case llvm::Triple::Itanium:
5155
57
        TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
5156
57
                                                                  Args);
5157
57
        break;
5158
7.72k
      case llvm::Triple::MSVC:
5159
7.72k
      case llvm::Triple::UnknownEnvironment:
5160
7.72k
        if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
5161
7.72k
                .startswith_lower("bfd"))
5162
1
          TC = std::make_unique<toolchains::CrossWindowsToolChain>(
5163
1
              *this, Target, Args);
5164
7.72k
        else
5165
7.72k
          TC =
5166
7.72k
              std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
5167
7.72k
        break;
5168
7.89k
      }
5169
7.89k
      break;
5170
138
    case llvm::Triple::PS4:
5171
138
      TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args);
5172
138
      break;
5173
1
    case llvm::Triple::Contiki: