Coverage Report

Created: 2020-02-25 14:32

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