1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "clang/Driver/Driver.h"
10 #include "ToolChains/AIX.h"
11 #include "ToolChains/AMDGPU.h"
12 #include "ToolChains/AMDGPUOpenMP.h"
13 #include "ToolChains/AVR.h"
14 #include "ToolChains/Ananas.h"
15 #include "ToolChains/BareMetal.h"
16 #include "ToolChains/CSKYToolChain.h"
17 #include "ToolChains/Clang.h"
18 #include "ToolChains/CloudABI.h"
19 #include "ToolChains/Contiki.h"
20 #include "ToolChains/CrossWindows.h"
21 #include "ToolChains/Cuda.h"
22 #include "ToolChains/Darwin.h"
23 #include "ToolChains/DragonFly.h"
24 #include "ToolChains/FreeBSD.h"
25 #include "ToolChains/Fuchsia.h"
26 #include "ToolChains/Gnu.h"
27 #include "ToolChains/HIPAMD.h"
28 #include "ToolChains/HIPSPV.h"
29 #include "ToolChains/HLSL.h"
30 #include "ToolChains/Haiku.h"
31 #include "ToolChains/Hexagon.h"
32 #include "ToolChains/Hurd.h"
33 #include "ToolChains/Lanai.h"
34 #include "ToolChains/Linux.h"
35 #include "ToolChains/MSP430.h"
36 #include "ToolChains/MSVC.h"
37 #include "ToolChains/MinGW.h"
38 #include "ToolChains/Minix.h"
39 #include "ToolChains/MipsLinux.h"
40 #include "ToolChains/Myriad.h"
41 #include "ToolChains/NaCl.h"
42 #include "ToolChains/NetBSD.h"
43 #include "ToolChains/OpenBSD.h"
44 #include "ToolChains/PPCFreeBSD.h"
45 #include "ToolChains/PPCLinux.h"
46 #include "ToolChains/PS4CPU.h"
47 #include "ToolChains/RISCVToolchain.h"
48 #include "ToolChains/SPIRV.h"
49 #include "ToolChains/Solaris.h"
50 #include "ToolChains/TCE.h"
51 #include "ToolChains/VEToolchain.h"
52 #include "ToolChains/WebAssembly.h"
53 #include "ToolChains/XCore.h"
54 #include "ToolChains/ZOS.h"
55 #include "clang/Basic/TargetID.h"
56 #include "clang/Basic/Version.h"
57 #include "clang/Config/config.h"
58 #include "clang/Driver/Action.h"
59 #include "clang/Driver/Compilation.h"
60 #include "clang/Driver/DriverDiagnostic.h"
61 #include "clang/Driver/InputInfo.h"
62 #include "clang/Driver/Job.h"
63 #include "clang/Driver/Options.h"
64 #include "clang/Driver/Phases.h"
65 #include "clang/Driver/SanitizerArgs.h"
66 #include "clang/Driver/Tool.h"
67 #include "clang/Driver/ToolChain.h"
68 #include "clang/Driver/Types.h"
69 #include "llvm/ADT/ArrayRef.h"
70 #include "llvm/ADT/STLExtras.h"
71 #include "llvm/ADT/SmallSet.h"
72 #include "llvm/ADT/StringExtras.h"
73 #include "llvm/ADT/StringRef.h"
74 #include "llvm/ADT/StringSet.h"
75 #include "llvm/ADT/StringSwitch.h"
76 #include "llvm/Config/llvm-config.h"
77 #include "llvm/MC/TargetRegistry.h"
78 #include "llvm/Option/Arg.h"
79 #include "llvm/Option/ArgList.h"
80 #include "llvm/Option/OptSpecifier.h"
81 #include "llvm/Option/OptTable.h"
82 #include "llvm/Option/Option.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/ErrorHandling.h"
85 #include "llvm/Support/ExitCodes.h"
86 #include "llvm/Support/FileSystem.h"
87 #include "llvm/Support/FormatVariadic.h"
88 #include "llvm/Support/MD5.h"
89 #include "llvm/Support/Path.h"
90 #include "llvm/Support/PrettyStackTrace.h"
91 #include "llvm/Support/Process.h"
92 #include "llvm/Support/Program.h"
93 #include "llvm/Support/StringSaver.h"
94 #include "llvm/Support/VirtualFileSystem.h"
95 #include "llvm/Support/raw_ostream.h"
96 #include "llvm/TargetParser/Host.h"
97 #include <cstdlib> // ::getenv
103 #include <unistd.h> // getpid
106 using namespace clang::driver
;
107 using namespace clang
;
108 using namespace llvm::opt
;
110 static std::optional
<llvm::Triple
> getOffloadTargetTriple(const Driver
&D
,
111 const ArgList
&Args
) {
112 auto OffloadTargets
= Args
.getAllArgValues(options::OPT_offload_EQ
);
113 // Offload compilation flow does not support multiple targets for now. We
114 // need the HIPActionBuilder (and possibly the CudaActionBuilder{,Base}too)
115 // to support multiple tool chains first.
116 switch (OffloadTargets
.size()) {
118 D
.Diag(diag::err_drv_only_one_offload_target_supported
);
121 D
.Diag(diag::err_drv_invalid_or_unsupported_offload_target
) << "";
126 return llvm::Triple(OffloadTargets
[0]);
129 static std::optional
<llvm::Triple
>
130 getNVIDIAOffloadTargetTriple(const Driver
&D
, const ArgList
&Args
,
131 const llvm::Triple
&HostTriple
) {
132 if (!Args
.hasArg(options::OPT_offload_EQ
)) {
133 return llvm::Triple(HostTriple
.isArch64Bit() ? "nvptx64-nvidia-cuda"
134 : "nvptx-nvidia-cuda");
136 auto TT
= getOffloadTargetTriple(D
, Args
);
137 if (TT
&& (TT
->getArch() == llvm::Triple::spirv32
||
138 TT
->getArch() == llvm::Triple::spirv64
)) {
139 if (Args
.hasArg(options::OPT_emit_llvm
))
141 D
.Diag(diag::err_drv_cuda_offload_only_emit_bc
);
144 D
.Diag(diag::err_drv_invalid_or_unsupported_offload_target
) << TT
->str();
147 static std::optional
<llvm::Triple
>
148 getHIPOffloadTargetTriple(const Driver
&D
, const ArgList
&Args
) {
149 if (!Args
.hasArg(options::OPT_offload_EQ
)) {
150 return llvm::Triple("amdgcn-amd-amdhsa"); // Default HIP triple.
152 auto TT
= getOffloadTargetTriple(D
, Args
);
155 if (TT
->getArch() == llvm::Triple::amdgcn
&&
156 TT
->getVendor() == llvm::Triple::AMD
&&
157 TT
->getOS() == llvm::Triple::AMDHSA
)
159 if (TT
->getArch() == llvm::Triple::spirv64
)
161 D
.Diag(diag::err_drv_invalid_or_unsupported_offload_target
) << TT
->str();
166 std::string
Driver::GetResourcesPath(StringRef BinaryPath
,
167 StringRef CustomResourceDir
) {
168 // Since the resource directory is embedded in the module hash, it's important
169 // that all places that need it call this function, so that they get the
170 // exact same string ("a/../b/" and "b/" get different hashes, for example).
172 // Dir is bin/ or lib/, depending on where BinaryPath is.
173 std::string Dir
= std::string(llvm::sys::path::parent_path(BinaryPath
));
175 SmallString
<128> P(Dir
);
176 if (CustomResourceDir
!= "") {
177 llvm::sys::path::append(P
, CustomResourceDir
);
179 // On Windows, libclang.dll is in bin/.
180 // On non-Windows, libclang.so/.dylib is in lib/.
181 // With a static-library build of libclang, LibClangPath will contain the
182 // path of the embedding binary, which for LLVM binaries will be in bin/.
183 // ../lib gets us to lib/ in both cases.
184 P
= llvm::sys::path::parent_path(Dir
);
185 llvm::sys::path::append(P
, CLANG_INSTALL_LIBDIR_BASENAME
, "clang",
186 CLANG_VERSION_MAJOR_STRING
);
189 return std::string(P
.str());
192 Driver::Driver(StringRef ClangExecutable
, StringRef TargetTriple
,
193 DiagnosticsEngine
&Diags
, std::string Title
,
194 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> VFS
)
195 : Diags(Diags
), VFS(std::move(VFS
)), Mode(GCCMode
),
196 SaveTemps(SaveTempsNone
), BitcodeEmbed(EmbedNone
),
197 Offload(OffloadHostDevice
), CXX20HeaderType(HeaderMode_None
),
198 ModulesModeCXX20(false), LTOMode(LTOK_None
),
199 ClangExecutable(ClangExecutable
), SysRoot(DEFAULT_SYSROOT
),
200 DriverTitle(Title
), CCCPrintBindings(false), CCPrintOptions(false),
201 CCLogDiagnostics(false), CCGenDiagnostics(false),
202 CCPrintProcessStats(false), TargetTriple(TargetTriple
), Saver(Alloc
),
203 PrependArg(nullptr), CheckInputsExist(true), ProbePrecompiled(true),
204 SuppressMissingInputWarning(false) {
205 // Provide a sane fallback if no VFS is specified.
207 this->VFS
= llvm::vfs::getRealFileSystem();
209 Name
= std::string(llvm::sys::path::filename(ClangExecutable
));
210 Dir
= std::string(llvm::sys::path::parent_path(ClangExecutable
));
211 InstalledDir
= Dir
; // Provide a sensible default installed dir.
213 if ((!SysRoot
.empty()) && llvm::sys::path::is_relative(SysRoot
)) {
214 // Prepend InstalledDir if SysRoot is relative
215 SmallString
<128> P(InstalledDir
);
216 llvm::sys::path::append(P
, SysRoot
);
217 SysRoot
= std::string(P
);
220 #if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
221 SystemConfigDir
= CLANG_CONFIG_FILE_SYSTEM_DIR
;
223 #if defined(CLANG_CONFIG_FILE_USER_DIR)
226 llvm::sys::fs::expand_tilde(CLANG_CONFIG_FILE_USER_DIR
, P
);
227 UserConfigDir
= static_cast<std::string
>(P
);
231 // Compute the path to the resource directory.
232 ResourceDir
= GetResourcesPath(ClangExecutable
, CLANG_RESOURCE_DIR
);
235 void Driver::setDriverMode(StringRef Value
) {
236 static const std::string OptName
=
237 getOpts().getOption(options::OPT_driver_mode
).getPrefixedName();
238 if (auto M
= llvm::StringSwitch
<std::optional
<DriverMode
>>(Value
)
239 .Case("gcc", GCCMode
)
240 .Case("g++", GXXMode
)
241 .Case("cpp", CPPMode
)
243 .Case("flang", FlangMode
)
244 .Case("dxc", DXCMode
)
245 .Default(std::nullopt
))
248 Diag(diag::err_drv_unsupported_option_argument
) << OptName
<< Value
;
251 InputArgList
Driver::ParseArgStrings(ArrayRef
<const char *> ArgStrings
,
253 bool &ContainsError
) {
254 llvm::PrettyStackTraceString
CrashInfo("Command line argument parsing");
255 ContainsError
= false;
257 unsigned IncludedFlagsBitmask
;
258 unsigned ExcludedFlagsBitmask
;
259 std::tie(IncludedFlagsBitmask
, ExcludedFlagsBitmask
) =
260 getIncludeExcludeOptionFlagMasks(IsClCompatMode
);
262 // Make sure that Flang-only options don't pollute the Clang output
263 // TODO: Make sure that Clang-only options don't pollute Flang output
265 ExcludedFlagsBitmask
|= options::FlangOnlyOption
;
267 unsigned MissingArgIndex
, MissingArgCount
;
269 getOpts().ParseArgs(ArgStrings
, MissingArgIndex
, MissingArgCount
,
270 IncludedFlagsBitmask
, ExcludedFlagsBitmask
);
272 // Check for missing argument error.
273 if (MissingArgCount
) {
274 Diag(diag::err_drv_missing_argument
)
275 << Args
.getArgString(MissingArgIndex
) << MissingArgCount
;
277 Diags
.getDiagnosticLevel(diag::err_drv_missing_argument
,
278 SourceLocation()) > DiagnosticsEngine::Warning
;
281 // Check for unsupported options.
282 for (const Arg
*A
: Args
) {
283 if (A
->getOption().hasFlag(options::Unsupported
)) {
285 auto ArgString
= A
->getAsString(Args
);
287 if (getOpts().findNearest(
288 ArgString
, Nearest
, IncludedFlagsBitmask
,
289 ExcludedFlagsBitmask
| options::Unsupported
) > 1) {
290 DiagID
= diag::err_drv_unsupported_opt
;
291 Diag(DiagID
) << ArgString
;
293 DiagID
= diag::err_drv_unsupported_opt_with_suggestion
;
294 Diag(DiagID
) << ArgString
<< Nearest
;
296 ContainsError
|= Diags
.getDiagnosticLevel(DiagID
, SourceLocation()) >
297 DiagnosticsEngine::Warning
;
301 // Warn about -mcpu= without an argument.
302 if (A
->getOption().matches(options::OPT_mcpu_EQ
) && A
->containsValue("")) {
303 Diag(diag::warn_drv_empty_joined_argument
) << A
->getAsString(Args
);
304 ContainsError
|= Diags
.getDiagnosticLevel(
305 diag::warn_drv_empty_joined_argument
,
306 SourceLocation()) > DiagnosticsEngine::Warning
;
310 for (const Arg
*A
: Args
.filtered(options::OPT_UNKNOWN
)) {
312 auto ArgString
= A
->getAsString(Args
);
314 if (getOpts().findNearest(ArgString
, Nearest
, IncludedFlagsBitmask
,
315 ExcludedFlagsBitmask
) > 1) {
317 getOpts().findExact(ArgString
, Nearest
, options::CC1Option
)) {
318 DiagID
= diag::err_drv_unknown_argument_with_suggestion
;
319 Diags
.Report(DiagID
) << ArgString
<< "-Xclang " + Nearest
;
321 DiagID
= IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
322 : diag::err_drv_unknown_argument
;
323 Diags
.Report(DiagID
) << ArgString
;
327 ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
328 : diag::err_drv_unknown_argument_with_suggestion
;
329 Diags
.Report(DiagID
) << ArgString
<< Nearest
;
331 ContainsError
|= Diags
.getDiagnosticLevel(DiagID
, SourceLocation()) >
332 DiagnosticsEngine::Warning
;
335 for (const Arg
*A
: Args
.filtered(options::OPT_o
)) {
336 if (ArgStrings
[A
->getIndex()] == A
->getSpelling())
339 // Warn on joined arguments that are similar to a long argument.
340 std::string ArgString
= ArgStrings
[A
->getIndex()];
342 if (getOpts().findExact("-" + ArgString
, Nearest
, IncludedFlagsBitmask
,
343 ExcludedFlagsBitmask
))
344 Diags
.Report(diag::warn_drv_potentially_misspelled_joined_argument
)
345 << A
->getAsString(Args
) << Nearest
;
351 // Determine which compilation mode we are in. We look for options which
352 // affect the phase, starting with the earliest phases, and record which
353 // option we used to determine the final phase.
354 phases::ID
Driver::getFinalPhase(const DerivedArgList
&DAL
,
355 Arg
**FinalPhaseArg
) const {
356 Arg
*PhaseArg
= nullptr;
357 phases::ID FinalPhase
;
359 // -{E,EP,P,M,MM} only run the preprocessor.
360 if (CCCIsCPP() || (PhaseArg
= DAL
.getLastArg(options::OPT_E
)) ||
361 (PhaseArg
= DAL
.getLastArg(options::OPT__SLASH_EP
)) ||
362 (PhaseArg
= DAL
.getLastArg(options::OPT_M
, options::OPT_MM
)) ||
363 (PhaseArg
= DAL
.getLastArg(options::OPT__SLASH_P
)) ||
365 FinalPhase
= phases::Preprocess
;
367 // --precompile only runs up to precompilation.
368 // Options that cause the output of C++20 compiled module interfaces or
369 // header units have the same effect.
370 } else if ((PhaseArg
= DAL
.getLastArg(options::OPT__precompile
)) ||
371 (PhaseArg
= DAL
.getLastArg(options::OPT_extract_api
)) ||
372 (PhaseArg
= DAL
.getLastArg(options::OPT_fmodule_header
,
373 options::OPT_fmodule_header_EQ
))) {
374 FinalPhase
= phases::Precompile
;
375 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
376 } else if ((PhaseArg
= DAL
.getLastArg(options::OPT_fsyntax_only
)) ||
377 (PhaseArg
= DAL
.getLastArg(options::OPT_print_supported_cpus
)) ||
378 (PhaseArg
= DAL
.getLastArg(options::OPT_module_file_info
)) ||
379 (PhaseArg
= DAL
.getLastArg(options::OPT_verify_pch
)) ||
380 (PhaseArg
= DAL
.getLastArg(options::OPT_rewrite_objc
)) ||
381 (PhaseArg
= DAL
.getLastArg(options::OPT_rewrite_legacy_objc
)) ||
382 (PhaseArg
= DAL
.getLastArg(options::OPT__migrate
)) ||
383 (PhaseArg
= DAL
.getLastArg(options::OPT__analyze
)) ||
384 (PhaseArg
= DAL
.getLastArg(options::OPT_emit_ast
))) {
385 FinalPhase
= phases::Compile
;
387 // -S only runs up to the backend.
388 } else if ((PhaseArg
= DAL
.getLastArg(options::OPT_S
))) {
389 FinalPhase
= phases::Backend
;
391 // -c compilation only runs up to the assembler.
392 } else if ((PhaseArg
= DAL
.getLastArg(options::OPT_c
))) {
393 FinalPhase
= phases::Assemble
;
395 } else if ((PhaseArg
= DAL
.getLastArg(options::OPT_emit_interface_stubs
))) {
396 FinalPhase
= phases::IfsMerge
;
398 // Otherwise do everything.
400 FinalPhase
= phases::Link
;
403 *FinalPhaseArg
= PhaseArg
;
408 static Arg
*MakeInputArg(DerivedArgList
&Args
, const OptTable
&Opts
,
409 StringRef Value
, bool Claim
= true) {
410 Arg
*A
= new Arg(Opts
.getOption(options::OPT_INPUT
), Value
,
411 Args
.getBaseArgs().MakeIndex(Value
), Value
.data());
412 Args
.AddSynthesizedArg(A
);
418 DerivedArgList
*Driver::TranslateInputArgs(const InputArgList
&Args
) const {
419 const llvm::opt::OptTable
&Opts
= getOpts();
420 DerivedArgList
*DAL
= new DerivedArgList(Args
);
422 bool HasNostdlib
= Args
.hasArg(options::OPT_nostdlib
);
423 bool HasNostdlibxx
= Args
.hasArg(options::OPT_nostdlibxx
);
424 bool HasNodefaultlib
= Args
.hasArg(options::OPT_nodefaultlibs
);
425 bool IgnoreUnused
= false;
426 for (Arg
*A
: Args
) {
430 if (A
->getOption().matches(options::OPT_start_no_unused_arguments
)) {
434 if (A
->getOption().matches(options::OPT_end_no_unused_arguments
)) {
435 IgnoreUnused
= false;
439 // Unfortunately, we have to parse some forwarding options (-Xassembler,
440 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
441 // (assembler and preprocessor), or bypass a previous driver ('collect2').
443 // Rewrite linker options, to replace --no-demangle with a custom internal
445 if ((A
->getOption().matches(options::OPT_Wl_COMMA
) ||
446 A
->getOption().matches(options::OPT_Xlinker
)) &&
447 A
->containsValue("--no-demangle")) {
448 // Add the rewritten no-demangle argument.
449 DAL
->AddFlagArg(A
, Opts
.getOption(options::OPT_Z_Xlinker__no_demangle
));
451 // Add the remaining values as Xlinker arguments.
452 for (StringRef Val
: A
->getValues())
453 if (Val
!= "--no-demangle")
454 DAL
->AddSeparateArg(A
, Opts
.getOption(options::OPT_Xlinker
), Val
);
459 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
460 // some build systems. We don't try to be complete here because we don't
461 // care to encourage this usage model.
462 if (A
->getOption().matches(options::OPT_Wp_COMMA
) &&
463 (A
->getValue(0) == StringRef("-MD") ||
464 A
->getValue(0) == StringRef("-MMD"))) {
465 // Rewrite to -MD/-MMD along with -MF.
466 if (A
->getValue(0) == StringRef("-MD"))
467 DAL
->AddFlagArg(A
, Opts
.getOption(options::OPT_MD
));
469 DAL
->AddFlagArg(A
, Opts
.getOption(options::OPT_MMD
));
470 if (A
->getNumValues() == 2)
471 DAL
->AddSeparateArg(A
, Opts
.getOption(options::OPT_MF
), A
->getValue(1));
475 // Rewrite reserved library names.
476 if (A
->getOption().matches(options::OPT_l
)) {
477 StringRef Value
= A
->getValue();
479 // Rewrite unless -nostdlib is present.
480 if (!HasNostdlib
&& !HasNodefaultlib
&& !HasNostdlibxx
&&
482 DAL
->AddFlagArg(A
, Opts
.getOption(options::OPT_Z_reserved_lib_stdcxx
));
486 // Rewrite unconditionally.
487 if (Value
== "cc_kext") {
488 DAL
->AddFlagArg(A
, Opts
.getOption(options::OPT_Z_reserved_lib_cckext
));
493 // Pick up inputs via the -- option.
494 if (A
->getOption().matches(options::OPT__DASH_DASH
)) {
496 for (StringRef Val
: A
->getValues())
497 DAL
->append(MakeInputArg(*DAL
, Opts
, Val
, false));
504 // Enforce -static if -miamcu is present.
505 if (Args
.hasFlag(options::OPT_miamcu
, options::OPT_mno_iamcu
, false))
506 DAL
->AddFlagArg(nullptr, Opts
.getOption(options::OPT_static
));
508 // Add a default value of -mlinker-version=, if one was given and the user
509 // didn't specify one.
510 #if defined(HOST_LINK_VERSION)
511 if (!Args
.hasArg(options::OPT_mlinker_version_EQ
) &&
512 strlen(HOST_LINK_VERSION
) > 0) {
513 DAL
->AddJoinedArg(0, Opts
.getOption(options::OPT_mlinker_version_EQ
),
515 DAL
->getLastArg(options::OPT_mlinker_version_EQ
)->claim();
522 /// Compute target triple from args.
524 /// This routine provides the logic to compute a target triple from various
525 /// args passed to the driver and the default triple string.
526 static llvm::Triple
computeTargetTriple(const Driver
&D
,
527 StringRef TargetTriple
,
529 StringRef DarwinArchName
= "") {
530 // FIXME: Already done in Compilation *Driver::BuildCompilation
531 if (const Arg
*A
= Args
.getLastArg(options::OPT_target
))
532 TargetTriple
= A
->getValue();
534 llvm::Triple
Target(llvm::Triple::normalize(TargetTriple
));
536 // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
537 // -gnu* only, and we can not change this, so we have to detect that case as
538 // being the Hurd OS.
539 if (TargetTriple
.contains("-unknown-gnu") || TargetTriple
.contains("-pc-gnu"))
540 Target
.setOSName("hurd");
542 // Handle Apple-specific options available here.
543 if (Target
.isOSBinFormatMachO()) {
544 // If an explicit Darwin arch name is given, that trumps all.
545 if (!DarwinArchName
.empty()) {
546 tools::darwin::setTripleTypeForMachOArchName(Target
, DarwinArchName
);
550 // Handle the Darwin '-arch' flag.
551 if (Arg
*A
= Args
.getLastArg(options::OPT_arch
)) {
552 StringRef ArchName
= A
->getValue();
553 tools::darwin::setTripleTypeForMachOArchName(Target
, ArchName
);
557 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
558 // '-mbig-endian'/'-EB'.
559 if (Arg
*A
= Args
.getLastArg(options::OPT_mlittle_endian
,
560 options::OPT_mbig_endian
)) {
561 if (A
->getOption().matches(options::OPT_mlittle_endian
)) {
562 llvm::Triple LE
= Target
.getLittleEndianArchVariant();
563 if (LE
.getArch() != llvm::Triple::UnknownArch
)
564 Target
= std::move(LE
);
566 llvm::Triple BE
= Target
.getBigEndianArchVariant();
567 if (BE
.getArch() != llvm::Triple::UnknownArch
)
568 Target
= std::move(BE
);
572 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
573 if (Target
.getArch() == llvm::Triple::tce
||
574 Target
.getOS() == llvm::Triple::Minix
)
577 // On AIX, the env OBJECT_MODE may affect the resulting arch variant.
578 if (Target
.isOSAIX()) {
579 if (std::optional
<std::string
> ObjectModeValue
=
580 llvm::sys::Process::GetEnv("OBJECT_MODE")) {
581 StringRef ObjectMode
= *ObjectModeValue
;
582 llvm::Triple::ArchType AT
= llvm::Triple::UnknownArch
;
584 if (ObjectMode
.equals("64")) {
585 AT
= Target
.get64BitArchVariant().getArch();
586 } else if (ObjectMode
.equals("32")) {
587 AT
= Target
.get32BitArchVariant().getArch();
589 D
.Diag(diag::err_drv_invalid_object_mode
) << ObjectMode
;
592 if (AT
!= llvm::Triple::UnknownArch
&& AT
!= Target
.getArch())
597 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
598 Arg
*A
= Args
.getLastArg(options::OPT_m64
, options::OPT_mx32
,
599 options::OPT_m32
, options::OPT_m16
);
601 llvm::Triple::ArchType AT
= llvm::Triple::UnknownArch
;
603 if (A
->getOption().matches(options::OPT_m64
)) {
604 AT
= Target
.get64BitArchVariant().getArch();
605 if (Target
.getEnvironment() == llvm::Triple::GNUX32
)
606 Target
.setEnvironment(llvm::Triple::GNU
);
607 else if (Target
.getEnvironment() == llvm::Triple::MuslX32
)
608 Target
.setEnvironment(llvm::Triple::Musl
);
609 } else if (A
->getOption().matches(options::OPT_mx32
) &&
610 Target
.get64BitArchVariant().getArch() == llvm::Triple::x86_64
) {
611 AT
= llvm::Triple::x86_64
;
612 if (Target
.getEnvironment() == llvm::Triple::Musl
)
613 Target
.setEnvironment(llvm::Triple::MuslX32
);
615 Target
.setEnvironment(llvm::Triple::GNUX32
);
616 } else if (A
->getOption().matches(options::OPT_m32
)) {
617 AT
= Target
.get32BitArchVariant().getArch();
618 if (Target
.getEnvironment() == llvm::Triple::GNUX32
)
619 Target
.setEnvironment(llvm::Triple::GNU
);
620 else if (Target
.getEnvironment() == llvm::Triple::MuslX32
)
621 Target
.setEnvironment(llvm::Triple::Musl
);
622 } else if (A
->getOption().matches(options::OPT_m16
) &&
623 Target
.get32BitArchVariant().getArch() == llvm::Triple::x86
) {
624 AT
= llvm::Triple::x86
;
625 Target
.setEnvironment(llvm::Triple::CODE16
);
628 if (AT
!= llvm::Triple::UnknownArch
&& AT
!= Target
.getArch()) {
630 if (Target
.isWindowsGNUEnvironment())
631 toolchains::MinGW::fixTripleArch(D
, Target
, Args
);
635 // Handle -miamcu flag.
636 if (Args
.hasFlag(options::OPT_miamcu
, options::OPT_mno_iamcu
, false)) {
637 if (Target
.get32BitArchVariant().getArch() != llvm::Triple::x86
)
638 D
.Diag(diag::err_drv_unsupported_opt_for_target
) << "-miamcu"
641 if (A
&& !A
->getOption().matches(options::OPT_m32
))
642 D
.Diag(diag::err_drv_argument_not_allowed_with
)
643 << "-miamcu" << A
->getBaseArg().getAsString(Args
);
645 Target
.setArch(llvm::Triple::x86
);
646 Target
.setArchName("i586");
647 Target
.setEnvironment(llvm::Triple::UnknownEnvironment
);
648 Target
.setEnvironmentName("");
649 Target
.setOS(llvm::Triple::ELFIAMCU
);
650 Target
.setVendor(llvm::Triple::UnknownVendor
);
651 Target
.setVendorName("intel");
654 // If target is MIPS adjust the target triple
655 // accordingly to provided ABI name.
656 if (Target
.isMIPS()) {
657 if ((A
= Args
.getLastArg(options::OPT_mabi_EQ
))) {
658 StringRef ABIName
= A
->getValue();
659 if (ABIName
== "32") {
660 Target
= Target
.get32BitArchVariant();
661 if (Target
.getEnvironment() == llvm::Triple::GNUABI64
||
662 Target
.getEnvironment() == llvm::Triple::GNUABIN32
)
663 Target
.setEnvironment(llvm::Triple::GNU
);
664 } else if (ABIName
== "n32") {
665 Target
= Target
.get64BitArchVariant();
666 if (Target
.getEnvironment() == llvm::Triple::GNU
||
667 Target
.getEnvironment() == llvm::Triple::GNUABI64
)
668 Target
.setEnvironment(llvm::Triple::GNUABIN32
);
669 } else if (ABIName
== "64") {
670 Target
= Target
.get64BitArchVariant();
671 if (Target
.getEnvironment() == llvm::Triple::GNU
||
672 Target
.getEnvironment() == llvm::Triple::GNUABIN32
)
673 Target
.setEnvironment(llvm::Triple::GNUABI64
);
678 // If target is RISC-V adjust the target triple according to
679 // provided architecture name
680 if (Target
.isRISCV()) {
681 if ((A
= Args
.getLastArg(options::OPT_march_EQ
))) {
682 StringRef ArchName
= A
->getValue();
683 if (ArchName
.startswith_insensitive("rv32"))
684 Target
.setArch(llvm::Triple::riscv32
);
685 else if (ArchName
.startswith_insensitive("rv64"))
686 Target
.setArch(llvm::Triple::riscv64
);
693 // Parse the LTO options and record the type of LTO compilation
694 // based on which -f(no-)?lto(=.*)? or -f(no-)?offload-lto(=.*)?
695 // option occurs last.
696 static driver::LTOKind
parseLTOMode(Driver
&D
, const llvm::opt::ArgList
&Args
,
697 OptSpecifier OptEq
, OptSpecifier OptNeg
) {
698 if (!Args
.hasFlag(OptEq
, OptNeg
, false))
701 const Arg
*A
= Args
.getLastArg(OptEq
);
702 StringRef LTOName
= A
->getValue();
704 driver::LTOKind LTOMode
= llvm::StringSwitch
<LTOKind
>(LTOName
)
705 .Case("full", LTOK_Full
)
706 .Case("thin", LTOK_Thin
)
707 .Default(LTOK_Unknown
);
709 if (LTOMode
== LTOK_Unknown
) {
710 D
.Diag(diag::err_drv_unsupported_option_argument
)
711 << A
->getSpelling() << A
->getValue();
717 // Parse the LTO options.
718 void Driver::setLTOMode(const llvm::opt::ArgList
&Args
) {
720 parseLTOMode(*this, Args
, options::OPT_flto_EQ
, options::OPT_fno_lto
);
722 OffloadLTOMode
= parseLTOMode(*this, Args
, options::OPT_foffload_lto_EQ
,
723 options::OPT_fno_offload_lto
);
725 // Try to enable `-foffload-lto=full` if `-fopenmp-target-jit` is on.
726 if (Args
.hasFlag(options::OPT_fopenmp_target_jit
,
727 options::OPT_fno_openmp_target_jit
, false)) {
728 if (Arg
*A
= Args
.getLastArg(options::OPT_foffload_lto_EQ
,
729 options::OPT_fno_offload_lto
))
730 if (OffloadLTOMode
!= LTOK_Full
)
731 Diag(diag::err_drv_incompatible_options
)
732 << A
->getSpelling() << "-fopenmp-target-jit";
733 OffloadLTOMode
= LTOK_Full
;
737 /// Compute the desired OpenMP runtime from the flags provided.
738 Driver::OpenMPRuntimeKind
Driver::getOpenMPRuntime(const ArgList
&Args
) const {
739 StringRef
RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME
);
741 const Arg
*A
= Args
.getLastArg(options::OPT_fopenmp_EQ
);
743 RuntimeName
= A
->getValue();
745 auto RT
= llvm::StringSwitch
<OpenMPRuntimeKind
>(RuntimeName
)
746 .Case("libomp", OMPRT_OMP
)
747 .Case("libgomp", OMPRT_GOMP
)
748 .Case("libiomp5", OMPRT_IOMP5
)
749 .Default(OMPRT_Unknown
);
751 if (RT
== OMPRT_Unknown
) {
753 Diag(diag::err_drv_unsupported_option_argument
)
754 << A
->getSpelling() << A
->getValue();
756 // FIXME: We could use a nicer diagnostic here.
757 Diag(diag::err_drv_unsupported_opt
) << "-fopenmp";
763 void Driver::CreateOffloadingDeviceToolChains(Compilation
&C
,
769 // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
770 // or HIP type. However, mixed CUDA/HIP compilation is not supported.
772 llvm::any_of(Inputs
, [](std::pair
<types::ID
, const llvm::opt::Arg
*> &I
) {
773 return types::isCuda(I
.first
);
777 [](std::pair
<types::ID
, const llvm::opt::Arg
*> &I
) {
778 return types::isHIP(I
.first
);
780 C
.getInputArgs().hasArg(options::OPT_hip_link
);
781 if (IsCuda
&& IsHIP
) {
782 Diag(clang::diag::err_drv_mix_cuda_hip
);
786 const ToolChain
*HostTC
= C
.getSingleOffloadToolChain
<Action::OFK_Host
>();
787 const llvm::Triple
&HostTriple
= HostTC
->getTriple();
788 auto OFK
= Action::OFK_Cuda
;
790 getNVIDIAOffloadTargetTriple(*this, C
.getInputArgs(), HostTriple
);
793 // Use the CUDA and host triples as the key into the ToolChains map,
794 // because the device toolchain we create depends on both.
795 auto &CudaTC
= ToolChains
[CudaTriple
->str() + "/" + HostTriple
.str()];
797 CudaTC
= std::make_unique
<toolchains::CudaToolChain
>(
798 *this, *CudaTriple
, *HostTC
, C
.getInputArgs());
800 C
.addOffloadDeviceToolChain(CudaTC
.get(), OFK
);
802 if (auto *OMPTargetArg
=
803 C
.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ
)) {
804 Diag(clang::diag::err_drv_unsupported_opt_for_language_mode
)
805 << OMPTargetArg
->getSpelling() << "HIP";
808 const ToolChain
*HostTC
= C
.getSingleOffloadToolChain
<Action::OFK_Host
>();
809 auto OFK
= Action::OFK_HIP
;
810 auto HIPTriple
= getHIPOffloadTargetTriple(*this, C
.getInputArgs());
813 auto *HIPTC
= &getOffloadingDeviceToolChain(C
.getInputArgs(), *HIPTriple
,
815 assert(HIPTC
&& "Could not create offloading device tool chain.");
816 C
.addOffloadDeviceToolChain(HIPTC
, OFK
);
822 // We need to generate an OpenMP toolchain if the user specified targets with
823 // the -fopenmp-targets option or used --offload-arch with OpenMP enabled.
824 bool IsOpenMPOffloading
=
825 C
.getInputArgs().hasFlag(options::OPT_fopenmp
, options::OPT_fopenmp_EQ
,
826 options::OPT_fno_openmp
, false) &&
827 (C
.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ
) ||
828 C
.getInputArgs().hasArg(options::OPT_offload_arch_EQ
));
829 if (IsOpenMPOffloading
) {
830 // We expect that -fopenmp-targets is always used in conjunction with the
831 // option -fopenmp specifying a valid runtime with offloading support, i.e.
832 // libomp or libiomp.
833 OpenMPRuntimeKind RuntimeKind
= getOpenMPRuntime(C
.getInputArgs());
834 if (RuntimeKind
!= OMPRT_OMP
&& RuntimeKind
!= OMPRT_IOMP5
) {
835 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets
);
839 llvm::StringMap
<llvm::DenseSet
<StringRef
>> DerivedArchs
;
840 llvm::StringMap
<StringRef
> FoundNormalizedTriples
;
841 llvm::SmallVector
<StringRef
, 4> OpenMPTriples
;
843 // If the user specified -fopenmp-targets= we create a toolchain for each
844 // valid triple. Otherwise, if only --offload-arch= was specified we instead
845 // attempt to derive the appropriate toolchains from the arguments.
846 if (Arg
*OpenMPTargets
=
847 C
.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ
)) {
848 if (OpenMPTargets
&& !OpenMPTargets
->getNumValues()) {
849 Diag(clang::diag::warn_drv_empty_joined_argument
)
850 << OpenMPTargets
->getAsString(C
.getInputArgs());
853 llvm::copy(OpenMPTargets
->getValues(), std::back_inserter(OpenMPTriples
));
854 } else if (C
.getInputArgs().hasArg(options::OPT_offload_arch_EQ
) &&
856 const ToolChain
*HostTC
= C
.getSingleOffloadToolChain
<Action::OFK_Host
>();
857 auto AMDTriple
= getHIPOffloadTargetTriple(*this, C
.getInputArgs());
858 auto NVPTXTriple
= getNVIDIAOffloadTargetTriple(*this, C
.getInputArgs(),
859 HostTC
->getTriple());
861 // Attempt to deduce the offloading triple from the set of architectures.
862 // We can only correctly deduce NVPTX / AMDGPU triples currently. We need
863 // to temporarily create these toolchains so that we can access tools for
864 // inferring architectures.
865 llvm::DenseSet
<StringRef
> Archs
;
867 auto TempTC
= std::make_unique
<toolchains::CudaToolChain
>(
868 *this, *NVPTXTriple
, *HostTC
, C
.getInputArgs());
869 for (StringRef Arch
: getOffloadArchs(
870 C
, C
.getArgs(), Action::OFK_OpenMP
, &*TempTC
, true))
874 auto TempTC
= std::make_unique
<toolchains::AMDGPUOpenMPToolChain
>(
875 *this, *AMDTriple
, *HostTC
, C
.getInputArgs());
876 for (StringRef Arch
: getOffloadArchs(
877 C
, C
.getArgs(), Action::OFK_OpenMP
, &*TempTC
, true))
880 if (!AMDTriple
&& !NVPTXTriple
) {
881 for (StringRef Arch
:
882 getOffloadArchs(C
, C
.getArgs(), Action::OFK_OpenMP
, nullptr, true))
886 for (StringRef Arch
: Archs
) {
887 if (NVPTXTriple
&& IsNVIDIAGpuArch(StringToCudaArch(
888 getProcessorFromTargetID(*NVPTXTriple
, Arch
)))) {
889 DerivedArchs
[NVPTXTriple
->getTriple()].insert(Arch
);
890 } else if (AMDTriple
&&
891 IsAMDGpuArch(StringToCudaArch(
892 getProcessorFromTargetID(*AMDTriple
, Arch
)))) {
893 DerivedArchs
[AMDTriple
->getTriple()].insert(Arch
);
895 Diag(clang::diag::err_drv_failed_to_deduce_target_from_arch
) << Arch
;
900 // If the set is empty then we failed to find a native architecture.
902 Diag(clang::diag::err_drv_failed_to_deduce_target_from_arch
)
907 for (const auto &TripleAndArchs
: DerivedArchs
)
908 OpenMPTriples
.push_back(TripleAndArchs
.first());
911 for (StringRef Val
: OpenMPTriples
) {
912 llvm::Triple
TT(ToolChain::getOpenMPTriple(Val
));
913 std::string NormalizedName
= TT
.normalize();
915 // Make sure we don't have a duplicate triple.
916 auto Duplicate
= FoundNormalizedTriples
.find(NormalizedName
);
917 if (Duplicate
!= FoundNormalizedTriples
.end()) {
918 Diag(clang::diag::warn_drv_omp_offload_target_duplicate
)
919 << Val
<< Duplicate
->second
;
923 // Store the current triple so that we can check for duplicates in the
924 // following iterations.
925 FoundNormalizedTriples
[NormalizedName
] = Val
;
927 // If the specified target is invalid, emit a diagnostic.
928 if (TT
.getArch() == llvm::Triple::UnknownArch
)
929 Diag(clang::diag::err_drv_invalid_omp_target
) << Val
;
932 // Device toolchains have to be selected differently. They pair host
933 // and device in their implementation.
934 if (TT
.isNVPTX() || TT
.isAMDGCN()) {
935 const ToolChain
*HostTC
=
936 C
.getSingleOffloadToolChain
<Action::OFK_Host
>();
937 assert(HostTC
&& "Host toolchain should be always defined.");
939 ToolChains
[TT
.str() + "/" + HostTC
->getTriple().normalize()];
942 DeviceTC
= std::make_unique
<toolchains::CudaToolChain
>(
943 *this, TT
, *HostTC
, C
.getInputArgs());
944 else if (TT
.isAMDGCN())
945 DeviceTC
= std::make_unique
<toolchains::AMDGPUOpenMPToolChain
>(
946 *this, TT
, *HostTC
, C
.getInputArgs());
948 assert(DeviceTC
&& "Device toolchain not defined.");
953 TC
= &getToolChain(C
.getInputArgs(), TT
);
954 C
.addOffloadDeviceToolChain(TC
, Action::OFK_OpenMP
);
955 if (DerivedArchs
.find(TT
.getTriple()) != DerivedArchs
.end())
956 KnownArchs
[TC
] = DerivedArchs
[TT
.getTriple()];
959 } else if (C
.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ
)) {
960 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets
);
965 // TODO: Add support for other offloading programming models here.
969 static void appendOneArg(InputArgList
&Args
, const Arg
*Opt
,
970 const Arg
*BaseArg
) {
971 // The args for config files or /clang: flags belong to different InputArgList
972 // objects than Args. This copies an Arg from one of those other InputArgLists
973 // to the ownership of Args.
974 unsigned Index
= Args
.MakeIndex(Opt
->getSpelling());
975 Arg
*Copy
= new llvm::opt::Arg(Opt
->getOption(), Args
.getArgString(Index
),
977 Copy
->getValues() = Opt
->getValues();
978 if (Opt
->isClaimed())
980 Copy
->setOwnsValues(Opt
->getOwnsValues());
981 Opt
->setOwnsValues(false);
985 bool Driver::readConfigFile(StringRef FileName
,
986 llvm::cl::ExpansionContext
&ExpCtx
) {
987 // Try opening the given file.
988 auto Status
= getVFS().status(FileName
);
990 Diag(diag::err_drv_cannot_open_config_file
)
991 << FileName
<< Status
.getError().message();
994 if (Status
->getType() != llvm::sys::fs::file_type::regular_file
) {
995 Diag(diag::err_drv_cannot_open_config_file
)
996 << FileName
<< "not a regular file";
1000 // Try reading the given file.
1001 SmallVector
<const char *, 32> NewCfgArgs
;
1002 if (llvm::Error Err
= ExpCtx
.readConfigFile(FileName
, NewCfgArgs
)) {
1003 Diag(diag::err_drv_cannot_read_config_file
)
1004 << FileName
<< toString(std::move(Err
));
1008 // Read options from config file.
1009 llvm::SmallString
<128> CfgFileName(FileName
);
1010 llvm::sys::path::native(CfgFileName
);
1012 std::unique_ptr
<InputArgList
> NewOptions
= std::make_unique
<InputArgList
>(
1013 ParseArgStrings(NewCfgArgs
, IsCLMode(), ContainErrors
));
1017 // Claim all arguments that come from a configuration file so that the driver
1018 // does not warn on any that is unused.
1019 for (Arg
*A
: *NewOptions
)
1023 CfgOptions
= std::move(NewOptions
);
1025 // If this is a subsequent config file, append options to the previous one.
1026 for (auto *Opt
: *NewOptions
) {
1027 const Arg
*BaseArg
= &Opt
->getBaseArg();
1030 appendOneArg(*CfgOptions
, Opt
, BaseArg
);
1033 ConfigFiles
.push_back(std::string(CfgFileName
));
1037 bool Driver::loadConfigFiles() {
1038 llvm::cl::ExpansionContext
ExpCtx(Saver
.getAllocator(),
1039 llvm::cl::tokenizeConfigFile
);
1040 ExpCtx
.setVFS(&getVFS());
1042 // Process options that change search path for config files.
1044 if (CLOptions
->hasArg(options::OPT_config_system_dir_EQ
)) {
1045 SmallString
<128> CfgDir
;
1047 CLOptions
->getLastArgValue(options::OPT_config_system_dir_EQ
));
1048 if (CfgDir
.empty() || getVFS().makeAbsolute(CfgDir
))
1049 SystemConfigDir
.clear();
1051 SystemConfigDir
= static_cast<std::string
>(CfgDir
);
1053 if (CLOptions
->hasArg(options::OPT_config_user_dir_EQ
)) {
1054 SmallString
<128> CfgDir
;
1055 llvm::sys::fs::expand_tilde(
1056 CLOptions
->getLastArgValue(options::OPT_config_user_dir_EQ
), CfgDir
);
1057 if (CfgDir
.empty() || getVFS().makeAbsolute(CfgDir
))
1058 UserConfigDir
.clear();
1060 UserConfigDir
= static_cast<std::string
>(CfgDir
);
1064 // Prepare list of directories where config file is searched for.
1065 StringRef CfgFileSearchDirs
[] = {UserConfigDir
, SystemConfigDir
, Dir
};
1066 ExpCtx
.setSearchDirs(CfgFileSearchDirs
);
1068 // First try to load configuration from the default files, return on error.
1069 if (loadDefaultConfigFiles(ExpCtx
))
1072 // Then load configuration files specified explicitly.
1073 SmallString
<128> CfgFilePath
;
1075 for (auto CfgFileName
: CLOptions
->getAllArgValues(options::OPT_config
)) {
1076 // If argument contains directory separator, treat it as a path to
1077 // configuration file.
1078 if (llvm::sys::path::has_parent_path(CfgFileName
)) {
1079 CfgFilePath
.assign(CfgFileName
);
1080 if (llvm::sys::path::is_relative(CfgFilePath
)) {
1081 if (getVFS().makeAbsolute(CfgFilePath
)) {
1082 Diag(diag::err_drv_cannot_open_config_file
)
1083 << CfgFilePath
<< "cannot get absolute path";
1087 } else if (!ExpCtx
.findConfigFile(CfgFileName
, CfgFilePath
)) {
1088 // Report an error that the config file could not be found.
1089 Diag(diag::err_drv_config_file_not_found
) << CfgFileName
;
1090 for (const StringRef
&SearchDir
: CfgFileSearchDirs
)
1091 if (!SearchDir
.empty())
1092 Diag(diag::note_drv_config_file_searched_in
) << SearchDir
;
1096 // Try to read the config file, return on error.
1097 if (readConfigFile(CfgFilePath
, ExpCtx
))
1102 // No error occurred.
1106 bool Driver::loadDefaultConfigFiles(llvm::cl::ExpansionContext
&ExpCtx
) {
1107 // Disable default config if CLANG_NO_DEFAULT_CONFIG is set to a non-empty
1109 if (const char *NoConfigEnv
= ::getenv("CLANG_NO_DEFAULT_CONFIG")) {
1113 if (CLOptions
&& CLOptions
->hasArg(options::OPT_no_default_config
))
1116 std::string RealMode
= getExecutableForDriverMode(Mode
);
1119 // If name prefix is present, no --target= override was passed via CLOptions
1120 // and the name prefix is not a valid triple, force it for backwards
1122 if (!ClangNameParts
.TargetPrefix
.empty() &&
1123 computeTargetTriple(*this, "/invalid/", *CLOptions
).str() ==
1125 llvm::Triple PrefixTriple
{ClangNameParts
.TargetPrefix
};
1126 if (PrefixTriple
.getArch() == llvm::Triple::UnknownArch
||
1127 PrefixTriple
.isOSUnknown())
1128 Triple
= PrefixTriple
.str();
1131 // Otherwise, use the real triple as used by the driver.
1132 if (Triple
.empty()) {
1133 llvm::Triple RealTriple
=
1134 computeTargetTriple(*this, TargetTriple
, *CLOptions
);
1135 Triple
= RealTriple
.str();
1136 assert(!Triple
.empty());
1139 // Search for config files in the following order:
1140 // 1. <triple>-<mode>.cfg using real driver mode
1141 // (e.g. i386-pc-linux-gnu-clang++.cfg).
1142 // 2. <triple>-<mode>.cfg using executable suffix
1143 // (e.g. i386-pc-linux-gnu-clang-g++.cfg for *clang-g++).
1144 // 3. <triple>.cfg + <mode>.cfg using real driver mode
1145 // (e.g. i386-pc-linux-gnu.cfg + clang++.cfg).
1146 // 4. <triple>.cfg + <mode>.cfg using executable suffix
1147 // (e.g. i386-pc-linux-gnu.cfg + clang-g++.cfg for *clang-g++).
1149 // Try loading <triple>-<mode>.cfg, and return if we find a match.
1150 SmallString
<128> CfgFilePath
;
1151 std::string CfgFileName
= Triple
+ '-' + RealMode
+ ".cfg";
1152 if (ExpCtx
.findConfigFile(CfgFileName
, CfgFilePath
))
1153 return readConfigFile(CfgFilePath
, ExpCtx
);
1155 bool TryModeSuffix
= !ClangNameParts
.ModeSuffix
.empty() &&
1156 ClangNameParts
.ModeSuffix
!= RealMode
;
1157 if (TryModeSuffix
) {
1158 CfgFileName
= Triple
+ '-' + ClangNameParts
.ModeSuffix
+ ".cfg";
1159 if (ExpCtx
.findConfigFile(CfgFileName
, CfgFilePath
))
1160 return readConfigFile(CfgFilePath
, ExpCtx
);
1163 // Try loading <mode>.cfg, and return if loading failed. If a matching file
1164 // was not found, still proceed on to try <triple>.cfg.
1165 CfgFileName
= RealMode
+ ".cfg";
1166 if (ExpCtx
.findConfigFile(CfgFileName
, CfgFilePath
)) {
1167 if (readConfigFile(CfgFilePath
, ExpCtx
))
1169 } else if (TryModeSuffix
) {
1170 CfgFileName
= ClangNameParts
.ModeSuffix
+ ".cfg";
1171 if (ExpCtx
.findConfigFile(CfgFileName
, CfgFilePath
) &&
1172 readConfigFile(CfgFilePath
, ExpCtx
))
1176 // Try loading <triple>.cfg and return if we find a match.
1177 CfgFileName
= Triple
+ ".cfg";
1178 if (ExpCtx
.findConfigFile(CfgFileName
, CfgFilePath
))
1179 return readConfigFile(CfgFilePath
, ExpCtx
);
1181 // If we were unable to find a config file deduced from executable name,
1182 // that is not an error.
1186 Compilation
*Driver::BuildCompilation(ArrayRef
<const char *> ArgList
) {
1187 llvm::PrettyStackTraceString
CrashInfo("Compilation construction");
1189 // FIXME: Handle environment options which affect driver behavior, somewhere
1190 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
1192 // We look for the driver mode option early, because the mode can affect
1193 // how other options are parsed.
1195 auto DriverMode
= getDriverMode(ClangExecutable
, ArgList
.slice(1));
1196 if (!DriverMode
.empty())
1197 setDriverMode(DriverMode
);
1199 // FIXME: What are we going to do with -V and -b?
1201 // Arguments specified in command line.
1203 CLOptions
= std::make_unique
<InputArgList
>(
1204 ParseArgStrings(ArgList
.slice(1), IsCLMode(), ContainsError
));
1206 // Try parsing configuration file.
1208 ContainsError
= loadConfigFiles();
1209 bool HasConfigFile
= !ContainsError
&& (CfgOptions
.get() != nullptr);
1211 // All arguments, from both config file and command line.
1212 InputArgList Args
= std::move(HasConfigFile
? std::move(*CfgOptions
)
1213 : std::move(*CLOptions
));
1216 for (auto *Opt
: *CLOptions
) {
1217 if (Opt
->getOption().matches(options::OPT_config
))
1219 const Arg
*BaseArg
= &Opt
->getBaseArg();
1222 appendOneArg(Args
, Opt
, BaseArg
);
1225 // In CL mode, look for any pass-through arguments
1226 if (IsCLMode() && !ContainsError
) {
1227 SmallVector
<const char *, 16> CLModePassThroughArgList
;
1228 for (const auto *A
: Args
.filtered(options::OPT__SLASH_clang
)) {
1230 CLModePassThroughArgList
.push_back(A
->getValue());
1233 if (!CLModePassThroughArgList
.empty()) {
1234 // Parse any pass through args using default clang processing rather
1235 // than clang-cl processing.
1236 auto CLModePassThroughOptions
= std::make_unique
<InputArgList
>(
1237 ParseArgStrings(CLModePassThroughArgList
, false, ContainsError
));
1240 for (auto *Opt
: *CLModePassThroughOptions
) {
1241 appendOneArg(Args
, Opt
, nullptr);
1246 // Check for working directory option before accessing any files
1247 if (Arg
*WD
= Args
.getLastArg(options::OPT_working_directory
))
1248 if (VFS
->setCurrentWorkingDirectory(WD
->getValue()))
1249 Diag(diag::err_drv_unable_to_set_working_directory
) << WD
->getValue();
1251 // FIXME: This stuff needs to go into the Compilation, not the driver.
1252 bool CCCPrintPhases
;
1254 // -canonical-prefixes, -no-canonical-prefixes are used very early in main.
1255 Args
.ClaimAllArgs(options::OPT_canonical_prefixes
);
1256 Args
.ClaimAllArgs(options::OPT_no_canonical_prefixes
);
1258 // f(no-)integated-cc1 is also used very early in main.
1259 Args
.ClaimAllArgs(options::OPT_fintegrated_cc1
);
1260 Args
.ClaimAllArgs(options::OPT_fno_integrated_cc1
);
1263 Args
.ClaimAllArgs(options::OPT_pipe
);
1265 // Extract -ccc args.
1267 // FIXME: We need to figure out where this behavior should live. Most of it
1268 // should be outside in the client; the parts that aren't should have proper
1269 // options, either by introducing new ones or by overloading gcc ones like -V
1271 CCCPrintPhases
= Args
.hasArg(options::OPT_ccc_print_phases
);
1272 CCCPrintBindings
= Args
.hasArg(options::OPT_ccc_print_bindings
);
1273 if (const Arg
*A
= Args
.getLastArg(options::OPT_ccc_gcc_name
))
1274 CCCGenericGCCName
= A
->getValue();
1276 // Process -fproc-stat-report options.
1277 if (const Arg
*A
= Args
.getLastArg(options::OPT_fproc_stat_report_EQ
)) {
1278 CCPrintProcessStats
= true;
1279 CCPrintStatReportFilename
= A
->getValue();
1281 if (Args
.hasArg(options::OPT_fproc_stat_report
))
1282 CCPrintProcessStats
= true;
1284 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
1285 // and getToolChain is const.
1287 // clang-cl targets MSVC-style Win32.
1288 llvm::Triple
T(TargetTriple
);
1289 T
.setOS(llvm::Triple::Win32
);
1290 T
.setVendor(llvm::Triple::PC
);
1291 T
.setEnvironment(llvm::Triple::MSVC
);
1292 T
.setObjectFormat(llvm::Triple::COFF
);
1293 if (Args
.hasArg(options::OPT__SLASH_arm64EC
))
1294 T
.setArch(llvm::Triple::aarch64
, llvm::Triple::AArch64SubArch_arm64ec
);
1295 TargetTriple
= T
.str();
1296 } else if (IsDXCMode()) {
1297 // Build TargetTriple from target_profile option for clang-dxc.
1298 if (const Arg
*A
= Args
.getLastArg(options::OPT_target_profile
)) {
1299 StringRef TargetProfile
= A
->getValue();
1301 toolchains::HLSLToolChain::parseTargetProfile(TargetProfile
))
1302 TargetTriple
= *Triple
;
1304 Diag(diag::err_drv_invalid_directx_shader_module
) << TargetProfile
;
1308 Diag(diag::err_drv_dxc_missing_target_profile
);
1312 if (const Arg
*A
= Args
.getLastArg(options::OPT_target
))
1313 TargetTriple
= A
->getValue();
1314 if (const Arg
*A
= Args
.getLastArg(options::OPT_ccc_install_dir
))
1315 Dir
= InstalledDir
= A
->getValue();
1316 for (const Arg
*A
: Args
.filtered(options::OPT_B
)) {
1318 PrefixDirs
.push_back(A
->getValue(0));
1320 if (std::optional
<std::string
> CompilerPathValue
=
1321 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
1322 StringRef CompilerPath
= *CompilerPathValue
;
1323 while (!CompilerPath
.empty()) {
1324 std::pair
<StringRef
, StringRef
> Split
=
1325 CompilerPath
.split(llvm::sys::EnvPathSeparator
);
1326 PrefixDirs
.push_back(std::string(Split
.first
));
1327 CompilerPath
= Split
.second
;
1330 if (const Arg
*A
= Args
.getLastArg(options::OPT__sysroot_EQ
))
1331 SysRoot
= A
->getValue();
1332 if (const Arg
*A
= Args
.getLastArg(options::OPT__dyld_prefix_EQ
))
1333 DyldPrefix
= A
->getValue();
1335 if (const Arg
*A
= Args
.getLastArg(options::OPT_resource_dir
))
1336 ResourceDir
= A
->getValue();
1338 if (const Arg
*A
= Args
.getLastArg(options::OPT_save_temps_EQ
)) {
1339 SaveTemps
= llvm::StringSwitch
<SaveTempsMode
>(A
->getValue())
1340 .Case("cwd", SaveTempsCwd
)
1341 .Case("obj", SaveTempsObj
)
1342 .Default(SaveTempsCwd
);
1345 if (const Arg
*A
= Args
.getLastArg(options::OPT_offload_host_only
,
1346 options::OPT_offload_device_only
,
1347 options::OPT_offload_host_device
)) {
1348 if (A
->getOption().matches(options::OPT_offload_host_only
))
1349 Offload
= OffloadHost
;
1350 else if (A
->getOption().matches(options::OPT_offload_device_only
))
1351 Offload
= OffloadDevice
;
1353 Offload
= OffloadHostDevice
;
1358 // Process -fembed-bitcode= flags.
1359 if (Arg
*A
= Args
.getLastArg(options::OPT_fembed_bitcode_EQ
)) {
1360 StringRef Name
= A
->getValue();
1361 unsigned Model
= llvm::StringSwitch
<unsigned>(Name
)
1362 .Case("off", EmbedNone
)
1363 .Case("all", EmbedBitcode
)
1364 .Case("bitcode", EmbedBitcode
)
1365 .Case("marker", EmbedMarker
)
1368 Diags
.Report(diag::err_drv_invalid_value
) << A
->getAsString(Args
)
1371 BitcodeEmbed
= static_cast<BitcodeEmbedMode
>(Model
);
1374 // Remove existing compilation database so that each job can append to it.
1375 if (Arg
*A
= Args
.getLastArg(options::OPT_MJ
))
1376 llvm::sys::fs::remove(A
->getValue());
1378 // Setting up the jobs for some precompile cases depends on whether we are
1379 // treating them as PCH, implicit modules or C++20 ones.
1380 // TODO: inferring the mode like this seems fragile (it meets the objective
1381 // of not requiring anything new for operation, however).
1382 const Arg
*Std
= Args
.getLastArg(options::OPT_std_EQ
);
1384 !Args
.hasArg(options::OPT_fmodules
) && Std
&&
1385 (Std
->containsValue("c++20") || Std
->containsValue("c++2b") ||
1386 Std
->containsValue("c++2a") || Std
->containsValue("c++latest"));
1388 // Process -fmodule-header{=} flags.
1389 if (Arg
*A
= Args
.getLastArg(options::OPT_fmodule_header_EQ
,
1390 options::OPT_fmodule_header
)) {
1391 // These flags force C++20 handling of headers.
1392 ModulesModeCXX20
= true;
1393 if (A
->getOption().matches(options::OPT_fmodule_header
))
1394 CXX20HeaderType
= HeaderMode_Default
;
1396 StringRef ArgName
= A
->getValue();
1397 unsigned Kind
= llvm::StringSwitch
<unsigned>(ArgName
)
1398 .Case("user", HeaderMode_User
)
1399 .Case("system", HeaderMode_System
)
1402 Diags
.Report(diag::err_drv_invalid_value
)
1403 << A
->getAsString(Args
) << ArgName
;
1405 CXX20HeaderType
= static_cast<ModuleHeaderMode
>(Kind
);
1409 std::unique_ptr
<llvm::opt::InputArgList
> UArgs
=
1410 std::make_unique
<InputArgList
>(std::move(Args
));
1412 // Perform the default argument translations.
1413 DerivedArgList
*TranslatedArgs
= TranslateInputArgs(*UArgs
);
1415 // Owned by the host.
1416 const ToolChain
&TC
= getToolChain(
1417 *UArgs
, computeTargetTriple(*this, TargetTriple
, *UArgs
));
1419 // Report warning when arm64EC option is overridden by specified target
1420 if ((TC
.getTriple().getArch() != llvm::Triple::aarch64
||
1421 TC
.getTriple().getSubArch() != llvm::Triple::AArch64SubArch_arm64ec
) &&
1422 UArgs
->hasArg(options::OPT__SLASH_arm64EC
)) {
1423 getDiags().Report(clang::diag::warn_target_override_arm64ec
)
1424 << TC
.getTriple().str();
1427 // The compilation takes ownership of Args.
1428 Compilation
*C
= new Compilation(*this, TC
, UArgs
.release(), TranslatedArgs
,
1431 if (!HandleImmediateArgs(*C
))
1434 // Construct the list of inputs.
1436 BuildInputs(C
->getDefaultToolChain(), *TranslatedArgs
, Inputs
);
1438 // Populate the tool chains for the offloading devices, if any.
1439 CreateOffloadingDeviceToolChains(*C
, Inputs
);
1441 // Construct the list of abstract actions to perform for this compilation. On
1442 // MachO targets this uses the driver-driver and universal actions.
1443 if (TC
.getTriple().isOSBinFormatMachO())
1444 BuildUniversalActions(*C
, C
->getDefaultToolChain(), Inputs
);
1446 BuildActions(*C
, C
->getArgs(), Inputs
, C
->getActions());
1448 if (CCCPrintPhases
) {
1458 static void printArgList(raw_ostream
&OS
, const llvm::opt::ArgList
&Args
) {
1459 llvm::opt::ArgStringList ASL
;
1460 for (const auto *A
: Args
) {
1461 // Use user's original spelling of flags. For example, use
1462 // `/source-charset:utf-8` instead of `-finput-charset=utf-8` if the user
1463 // wrote the former.
1464 while (A
->getAlias())
1466 A
->render(Args
, ASL
);
1469 for (auto I
= ASL
.begin(), E
= ASL
.end(); I
!= E
; ++I
) {
1470 if (I
!= ASL
.begin())
1472 llvm::sys::printArg(OS
, *I
, true);
1477 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename
,
1478 SmallString
<128> &CrashDiagDir
) {
1479 using namespace llvm::sys
;
1480 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1481 "Only knows about .crash files on Darwin");
1483 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1484 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1485 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1486 path::home_directory(CrashDiagDir
);
1487 if (CrashDiagDir
.startswith("/var/root"))
1489 path::append(CrashDiagDir
, "Library/Logs/DiagnosticReports");
1497 fs::file_status FileStatus
;
1498 TimePoint
<> LastAccessTime
;
1499 SmallString
<128> CrashFilePath
;
1500 // Lookup the .crash files and get the one generated by a subprocess spawned
1501 // by this driver invocation.
1502 for (fs::directory_iterator
File(CrashDiagDir
, EC
), FileEnd
;
1503 File
!= FileEnd
&& !EC
; File
.increment(EC
)) {
1504 StringRef FileName
= path::filename(File
->path());
1505 if (!FileName
.startswith(Name
))
1507 if (fs::status(File
->path(), FileStatus
))
1509 llvm::ErrorOr
<std::unique_ptr
<llvm::MemoryBuffer
>> CrashFile
=
1510 llvm::MemoryBuffer::getFile(File
->path());
1513 // The first line should start with "Process:", otherwise this isn't a real
1515 StringRef Data
= CrashFile
.get()->getBuffer();
1516 if (!Data
.startswith("Process:"))
1518 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1519 size_t ParentProcPos
= Data
.find("Parent Process:");
1520 if (ParentProcPos
== StringRef::npos
)
1522 size_t LineEnd
= Data
.find_first_of("\n", ParentProcPos
);
1523 if (LineEnd
== StringRef::npos
)
1525 StringRef ParentProcess
= Data
.slice(ParentProcPos
+15, LineEnd
).trim();
1526 int OpenBracket
= -1, CloseBracket
= -1;
1527 for (size_t i
= 0, e
= ParentProcess
.size(); i
< e
; ++i
) {
1528 if (ParentProcess
[i
] == '[')
1530 if (ParentProcess
[i
] == ']')
1533 // Extract the parent process PID from the .crash file and check whether
1534 // it matches this driver invocation pid.
1536 if (OpenBracket
< 0 || CloseBracket
< 0 ||
1537 ParentProcess
.slice(OpenBracket
+ 1, CloseBracket
)
1538 .getAsInteger(10, CrashPID
) || CrashPID
!= PID
) {
1542 // Found a .crash file matching the driver pid. To avoid getting an older
1543 // and misleading crash file, continue looking for the most recent.
1544 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1545 // multiple crashes poiting to the same parent process. Since the driver
1546 // does not collect pid information for the dispatched invocation there's
1547 // currently no way to distinguish among them.
1548 const auto FileAccessTime
= FileStatus
.getLastModificationTime();
1549 if (FileAccessTime
> LastAccessTime
) {
1550 CrashFilePath
.assign(File
->path());
1551 LastAccessTime
= FileAccessTime
;
1555 // If found, copy it over to the location of other reproducer files.
1556 if (!CrashFilePath
.empty()) {
1557 EC
= fs::copy_file(CrashFilePath
, ReproCrashFilename
);
1566 static const char BugReporMsg
[] =
1567 "\n********************\n\n"
1568 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1569 "Preprocessed source(s) and associated run script(s) are located at:";
1571 // When clang crashes, produce diagnostic information including the fully
1572 // preprocessed source file(s). Request that the developer attach the
1573 // diagnostic information to a bug report.
1574 void Driver::generateCompilationDiagnostics(
1575 Compilation
&C
, const Command
&FailingCommand
,
1576 StringRef AdditionalInformation
, CompilationDiagnosticReport
*Report
) {
1577 if (C
.getArgs().hasArg(options::OPT_fno_crash_diagnostics
))
1581 if (Arg
*A
= C
.getArgs().getLastArg(options::OPT_fcrash_diagnostics_EQ
)) {
1582 Level
= llvm::StringSwitch
<unsigned>(A
->getValue())
1584 .Case("compiler", 1)
1591 // Don't try to generate diagnostics for dsymutil jobs.
1592 if (FailingCommand
.getCreator().isDsymutilJob())
1596 ArgStringList SavedTemps
;
1597 if (FailingCommand
.getCreator().isLinkJob()) {
1598 C
.getDefaultToolChain().GetLinkerPath(&IsLLD
);
1599 if (!IsLLD
|| Level
< 2)
1602 // If lld crashed, we will re-run the same command with the input it used
1603 // to have. In that case we should not remove temp files in
1604 // initCompilationForDiagnostics yet. They will be added back and removed
1606 SavedTemps
= std::move(C
.getTempFiles());
1607 assert(!C
.getTempFiles().size());
1610 // Print the version of the compiler.
1611 PrintVersion(C
, llvm::errs());
1613 // Suppress driver output and emit preprocessor output to temp file.
1614 CCGenDiagnostics
= true;
1616 // Save the original job command(s).
1617 Command Cmd
= FailingCommand
;
1619 // Keep track of whether we produce any errors while trying to produce
1620 // preprocessed sources.
1621 DiagnosticErrorTrap
Trap(Diags
);
1623 // Suppress tool output.
1624 C
.initCompilationForDiagnostics();
1626 // If lld failed, rerun it again with --reproduce.
1628 const char *TmpName
= CreateTempFile(C
, "linker-crash", "tar");
1629 Command NewLLDInvocation
= Cmd
;
1630 llvm::opt::ArgStringList ArgList
= NewLLDInvocation
.getArguments();
1631 StringRef ReproduceOption
=
1632 C
.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment()
1635 ArgList
.push_back(Saver
.save(Twine(ReproduceOption
) + TmpName
).data());
1636 NewLLDInvocation
.replaceArguments(std::move(ArgList
));
1638 // Redirect stdout/stderr to /dev/null.
1639 NewLLDInvocation
.Execute({std::nullopt
, {""}, {""}}, nullptr, nullptr);
1640 Diag(clang::diag::note_drv_command_failed_diag_msg
) << BugReporMsg
;
1641 Diag(clang::diag::note_drv_command_failed_diag_msg
) << TmpName
;
1642 Diag(clang::diag::note_drv_command_failed_diag_msg
)
1643 << "\n\n********************";
1645 Report
->TemporaryFiles
.push_back(TmpName
);
1649 // Construct the list of inputs.
1651 BuildInputs(C
.getDefaultToolChain(), C
.getArgs(), Inputs
);
1653 for (InputList::iterator it
= Inputs
.begin(), ie
= Inputs
.end(); it
!= ie
;) {
1654 bool IgnoreInput
= false;
1656 // Ignore input from stdin or any inputs that cannot be preprocessed.
1657 // Check type first as not all linker inputs have a value.
1658 if (types::getPreprocessedType(it
->first
) == types::TY_INVALID
) {
1660 } else if (!strcmp(it
->second
->getValue(), "-")) {
1661 Diag(clang::diag::note_drv_command_failed_diag_msg
)
1662 << "Error generating preprocessed source(s) - "
1663 "ignoring input from stdin.";
1668 it
= Inputs
.erase(it
);
1675 if (Inputs
.empty()) {
1676 Diag(clang::diag::note_drv_command_failed_diag_msg
)
1677 << "Error generating preprocessed source(s) - "
1678 "no preprocessable inputs.";
1682 // Don't attempt to generate preprocessed files if multiple -arch options are
1683 // used, unless they're all duplicates.
1684 llvm::StringSet
<> ArchNames
;
1685 for (const Arg
*A
: C
.getArgs()) {
1686 if (A
->getOption().matches(options::OPT_arch
)) {
1687 StringRef ArchName
= A
->getValue();
1688 ArchNames
.insert(ArchName
);
1691 if (ArchNames
.size() > 1) {
1692 Diag(clang::diag::note_drv_command_failed_diag_msg
)
1693 << "Error generating preprocessed source(s) - cannot generate "
1694 "preprocessed source with multiple -arch options.";
1698 // Construct the list of abstract actions to perform for this compilation. On
1699 // Darwin OSes this uses the driver-driver and builds universal actions.
1700 const ToolChain
&TC
= C
.getDefaultToolChain();
1701 if (TC
.getTriple().isOSBinFormatMachO())
1702 BuildUniversalActions(C
, TC
, Inputs
);
1704 BuildActions(C
, C
.getArgs(), Inputs
, C
.getActions());
1708 // If there were errors building the compilation, quit now.
1709 if (Trap
.hasErrorOccurred()) {
1710 Diag(clang::diag::note_drv_command_failed_diag_msg
)
1711 << "Error generating preprocessed source(s).";
1715 // Generate preprocessed output.
1716 SmallVector
<std::pair
<int, const Command
*>, 4> FailingCommands
;
1717 C
.ExecuteJobs(C
.getJobs(), FailingCommands
);
1719 // If any of the preprocessing commands failed, clean up and exit.
1720 if (!FailingCommands
.empty()) {
1721 Diag(clang::diag::note_drv_command_failed_diag_msg
)
1722 << "Error generating preprocessed source(s).";
1726 const ArgStringList
&TempFiles
= C
.getTempFiles();
1727 if (TempFiles
.empty()) {
1728 Diag(clang::diag::note_drv_command_failed_diag_msg
)
1729 << "Error generating preprocessed source(s).";
1733 Diag(clang::diag::note_drv_command_failed_diag_msg
) << BugReporMsg
;
1735 SmallString
<128> VFS
;
1736 SmallString
<128> ReproCrashFilename
;
1737 for (const char *TempFile
: TempFiles
) {
1738 Diag(clang::diag::note_drv_command_failed_diag_msg
) << TempFile
;
1740 Report
->TemporaryFiles
.push_back(TempFile
);
1741 if (ReproCrashFilename
.empty()) {
1742 ReproCrashFilename
= TempFile
;
1743 llvm::sys::path::replace_extension(ReproCrashFilename
, ".crash");
1745 if (StringRef(TempFile
).endswith(".cache")) {
1746 // In some cases (modules) we'll dump extra data to help with reproducing
1747 // the crash into a directory next to the output.
1748 VFS
= llvm::sys::path::filename(TempFile
);
1749 llvm::sys::path::append(VFS
, "vfs", "vfs.yaml");
1753 for (const char *TempFile
: SavedTemps
)
1754 C
.addTempFile(TempFile
);
1756 // Assume associated files are based off of the first temporary file.
1757 CrashReportInfo
CrashInfo(TempFiles
[0], VFS
);
1759 llvm::SmallString
<128> Script(CrashInfo
.Filename
);
1760 llvm::sys::path::replace_extension(Script
, "sh");
1762 llvm::raw_fd_ostream
ScriptOS(Script
, EC
, llvm::sys::fs::CD_CreateNew
,
1763 llvm::sys::fs::FA_Write
,
1764 llvm::sys::fs::OF_Text
);
1766 Diag(clang::diag::note_drv_command_failed_diag_msg
)
1767 << "Error generating run script: " << Script
<< " " << EC
.message();
1769 ScriptOS
<< "# Crash reproducer for " << getClangFullVersion() << "\n"
1770 << "# Driver args: ";
1771 printArgList(ScriptOS
, C
.getInputArgs());
1772 ScriptOS
<< "# Original command: ";
1773 Cmd
.Print(ScriptOS
, "\n", /*Quote=*/true);
1774 Cmd
.Print(ScriptOS
, "\n", /*Quote=*/true, &CrashInfo
);
1775 if (!AdditionalInformation
.empty())
1776 ScriptOS
<< "\n# Additional information: " << AdditionalInformation
1779 Report
->TemporaryFiles
.push_back(std::string(Script
.str()));
1780 Diag(clang::diag::note_drv_command_failed_diag_msg
) << Script
;
1783 // On darwin, provide information about the .crash diagnostic report.
1784 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1785 SmallString
<128> CrashDiagDir
;
1786 if (getCrashDiagnosticFile(ReproCrashFilename
, CrashDiagDir
)) {
1787 Diag(clang::diag::note_drv_command_failed_diag_msg
)
1788 << ReproCrashFilename
.str();
1789 } else { // Suggest a directory for the user to look for .crash files.
1790 llvm::sys::path::append(CrashDiagDir
, Name
);
1791 CrashDiagDir
+= "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1792 Diag(clang::diag::note_drv_command_failed_diag_msg
)
1793 << "Crash backtrace is located in";
1794 Diag(clang::diag::note_drv_command_failed_diag_msg
)
1795 << CrashDiagDir
.str();
1796 Diag(clang::diag::note_drv_command_failed_diag_msg
)
1797 << "(choose the .crash file that corresponds to your crash)";
1801 for (const auto &A
: C
.getArgs().filtered(options::OPT_frewrite_map_file_EQ
))
1802 Diag(clang::diag::note_drv_command_failed_diag_msg
) << A
->getValue();
1804 Diag(clang::diag::note_drv_command_failed_diag_msg
)
1805 << "\n\n********************";
1808 void Driver::setUpResponseFiles(Compilation
&C
, Command
&Cmd
) {
1809 // Since commandLineFitsWithinSystemLimits() may underestimate system's
1810 // capacity if the tool does not support response files, there is a chance/
1811 // that things will just work without a response file, so we silently just
1813 if (Cmd
.getResponseFileSupport().ResponseKind
==
1814 ResponseFileSupport::RF_None
||
1815 llvm::sys::commandLineFitsWithinSystemLimits(Cmd
.getExecutable(),
1816 Cmd
.getArguments()))
1819 std::string TmpName
= GetTemporaryPath("response", "txt");
1820 Cmd
.setResponseFile(C
.addTempFile(C
.getArgs().MakeArgString(TmpName
)));
1823 int Driver::ExecuteCompilation(
1825 SmallVectorImpl
<std::pair
<int, const Command
*>> &FailingCommands
) {
1826 if (C
.getArgs().hasArg(options::OPT_fdriver_only
)) {
1827 if (C
.getArgs().hasArg(options::OPT_v
))
1828 C
.getJobs().Print(llvm::errs(), "\n", true);
1830 C
.ExecuteJobs(C
.getJobs(), FailingCommands
, /*LogOnly=*/true);
1832 // If there were errors building the compilation, quit now.
1833 if (!FailingCommands
.empty() || Diags
.hasErrorOccurred())
1839 // Just print if -### was present.
1840 if (C
.getArgs().hasArg(options::OPT__HASH_HASH_HASH
)) {
1841 C
.getJobs().Print(llvm::errs(), "\n", true);
1845 // If there were errors building the compilation, quit now.
1846 if (Diags
.hasErrorOccurred())
1849 // Set up response file names for each command, if necessary.
1850 for (auto &Job
: C
.getJobs())
1851 setUpResponseFiles(C
, Job
);
1853 C
.ExecuteJobs(C
.getJobs(), FailingCommands
);
1855 // If the command succeeded, we are done.
1856 if (FailingCommands
.empty())
1859 // Otherwise, remove result files and print extra information about abnormal
1862 for (const auto &CmdPair
: FailingCommands
) {
1863 int CommandRes
= CmdPair
.first
;
1864 const Command
*FailingCommand
= CmdPair
.second
;
1866 // Remove result files if we're not saving temps.
1867 if (!isSaveTempsEnabled()) {
1868 const JobAction
*JA
= cast
<JobAction
>(&FailingCommand
->getSource());
1869 C
.CleanupFileMap(C
.getResultFiles(), JA
, true);
1871 // Failure result files are valid unless we crashed.
1873 C
.CleanupFileMap(C
.getFailureResultFiles(), JA
, true);
1876 // llvm/lib/Support/*/Signals.inc will exit with a special return code
1877 // for SIGPIPE. Do not print diagnostics for this case.
1878 if (CommandRes
== EX_IOERR
) {
1883 // Print extra information about abnormal failures, if possible.
1885 // This is ad-hoc, but we don't want to be excessively noisy. If the result
1886 // status was 1, assume the command failed normally. In particular, if it
1887 // was the compiler then assume it gave a reasonable error code. Failures
1888 // in other tools are less common, and they generally have worse
1889 // diagnostics, so always print the diagnostic there.
1890 const Tool
&FailingTool
= FailingCommand
->getCreator();
1892 if (!FailingCommand
->getCreator().hasGoodDiagnostics() || CommandRes
!= 1) {
1893 // FIXME: See FIXME above regarding result code interpretation.
1895 Diag(clang::diag::err_drv_command_signalled
)
1896 << FailingTool
.getShortName();
1898 Diag(clang::diag::err_drv_command_failed
)
1899 << FailingTool
.getShortName() << CommandRes
;
1905 void Driver::PrintHelp(bool ShowHidden
) const {
1906 unsigned IncludedFlagsBitmask
;
1907 unsigned ExcludedFlagsBitmask
;
1908 std::tie(IncludedFlagsBitmask
, ExcludedFlagsBitmask
) =
1909 getIncludeExcludeOptionFlagMasks(IsCLMode());
1911 ExcludedFlagsBitmask
|= options::NoDriverOption
;
1913 ExcludedFlagsBitmask
|= HelpHidden
;
1916 IncludedFlagsBitmask
|= options::FlangOption
;
1918 ExcludedFlagsBitmask
|= options::FlangOnlyOption
;
1920 std::string Usage
= llvm::formatv("{0} [options] file...", Name
).str();
1921 getOpts().printHelp(llvm::outs(), Usage
.c_str(), DriverTitle
.c_str(),
1922 IncludedFlagsBitmask
, ExcludedFlagsBitmask
,
1923 /*ShowAllAliases=*/false);
1926 void Driver::PrintVersion(const Compilation
&C
, raw_ostream
&OS
) const {
1927 if (IsFlangMode()) {
1928 OS
<< getClangToolFullVersion("flang-new") << '\n';
1930 // FIXME: The following handlers should use a callback mechanism, we don't
1931 // know what the client would like to do.
1932 OS
<< getClangFullVersion() << '\n';
1934 const ToolChain
&TC
= C
.getDefaultToolChain();
1935 OS
<< "Target: " << TC
.getTripleString() << '\n';
1937 // Print the threading model.
1938 if (Arg
*A
= C
.getArgs().getLastArg(options::OPT_mthread_model
)) {
1939 // Don't print if the ToolChain would have barfed on it already
1940 if (TC
.isThreadModelSupported(A
->getValue()))
1941 OS
<< "Thread model: " << A
->getValue();
1943 OS
<< "Thread model: " << TC
.getThreadModel();
1946 // Print out the install directory.
1947 OS
<< "InstalledDir: " << InstalledDir
<< '\n';
1949 // If configuration files were used, print their paths.
1950 for (auto ConfigFile
: ConfigFiles
)
1951 OS
<< "Configuration file: " << ConfigFile
<< '\n';
1954 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1956 static void PrintDiagnosticCategories(raw_ostream
&OS
) {
1957 // Skip the empty category.
1958 for (unsigned i
= 1, max
= DiagnosticIDs::getNumberOfCategories(); i
!= max
;
1960 OS
<< i
<< ',' << DiagnosticIDs::getCategoryNameFromID(i
) << '\n';
1963 void Driver::HandleAutocompletions(StringRef PassedFlags
) const {
1964 if (PassedFlags
== "")
1966 // Print out all options that start with a given argument. This is used for
1967 // shell autocompletion.
1968 std::vector
<std::string
> SuggestedCompletions
;
1969 std::vector
<std::string
> Flags
;
1971 unsigned int DisableFlags
=
1972 options::NoDriverOption
| options::Unsupported
| options::Ignored
;
1974 // Make sure that Flang-only options don't pollute the Clang output
1975 // TODO: Make sure that Clang-only options don't pollute Flang output
1977 DisableFlags
|= options::FlangOnlyOption
;
1979 // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
1980 // because the latter indicates that the user put space before pushing tab
1981 // which should end up in a file completion.
1982 const bool HasSpace
= PassedFlags
.endswith(",");
1984 // Parse PassedFlags by "," as all the command-line flags are passed to this
1985 // function separated by ","
1986 StringRef TargetFlags
= PassedFlags
;
1987 while (TargetFlags
!= "") {
1989 std::tie(CurFlag
, TargetFlags
) = TargetFlags
.split(",");
1990 Flags
.push_back(std::string(CurFlag
));
1993 // We want to show cc1-only options only when clang is invoked with -cc1 or
1995 if (llvm::is_contained(Flags
, "-Xclang") || llvm::is_contained(Flags
, "-cc1"))
1996 DisableFlags
&= ~options::NoDriverOption
;
1998 const llvm::opt::OptTable
&Opts
= getOpts();
2000 Cur
= Flags
.at(Flags
.size() - 1);
2002 if (Flags
.size() >= 2) {
2003 Prev
= Flags
.at(Flags
.size() - 2);
2004 SuggestedCompletions
= Opts
.suggestValueCompletions(Prev
, Cur
);
2007 if (SuggestedCompletions
.empty())
2008 SuggestedCompletions
= Opts
.suggestValueCompletions(Cur
, "");
2010 // If Flags were empty, it means the user typed `clang [tab]` where we should
2011 // list all possible flags. If there was no value completion and the user
2012 // pressed tab after a space, we should fall back to a file completion.
2013 // We're printing a newline to be consistent with what we print at the end of
2015 if (SuggestedCompletions
.empty() && HasSpace
&& !Flags
.empty()) {
2016 llvm::outs() << '\n';
2020 // When flag ends with '=' and there was no value completion, return empty
2021 // string and fall back to the file autocompletion.
2022 if (SuggestedCompletions
.empty() && !Cur
.endswith("=")) {
2023 // If the flag is in the form of "--autocomplete=-foo",
2024 // we were requested to print out all option names that start with "-foo".
2025 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
2026 SuggestedCompletions
= Opts
.findByPrefix(Cur
, DisableFlags
);
2028 // We have to query the -W flags manually as they're not in the OptTable.
2029 // TODO: Find a good way to add them to OptTable instead and them remove
2031 for (StringRef S
: DiagnosticIDs::getDiagnosticFlags())
2032 if (S
.startswith(Cur
))
2033 SuggestedCompletions
.push_back(std::string(S
));
2036 // Sort the autocomplete candidates so that shells print them out in a
2037 // deterministic order. We could sort in any way, but we chose
2038 // case-insensitive sorting for consistency with the -help option
2039 // which prints out options in the case-insensitive alphabetical order.
2040 llvm::sort(SuggestedCompletions
, [](StringRef A
, StringRef B
) {
2041 if (int X
= A
.compare_insensitive(B
))
2043 return A
.compare(B
) > 0;
2046 llvm::outs() << llvm::join(SuggestedCompletions
, "\n") << '\n';
2049 bool Driver::HandleImmediateArgs(const Compilation
&C
) {
2050 // The order these options are handled in gcc is all over the place, but we
2051 // don't expect inconsistencies w.r.t. that to matter in practice.
2053 if (C
.getArgs().hasArg(options::OPT_dumpmachine
)) {
2054 llvm::outs() << C
.getDefaultToolChain().getTripleString() << '\n';
2058 if (C
.getArgs().hasArg(options::OPT_dumpversion
)) {
2059 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
2060 // return an answer which matches our definition of __VERSION__.
2061 llvm::outs() << CLANG_VERSION_STRING
<< "\n";
2065 if (C
.getArgs().hasArg(options::OPT__print_diagnostic_categories
)) {
2066 PrintDiagnosticCategories(llvm::outs());
2070 if (C
.getArgs().hasArg(options::OPT_help
) ||
2071 C
.getArgs().hasArg(options::OPT__help_hidden
)) {
2072 PrintHelp(C
.getArgs().hasArg(options::OPT__help_hidden
));
2076 if (C
.getArgs().hasArg(options::OPT__version
)) {
2077 // Follow gcc behavior and use stdout for --version and stderr for -v.
2078 PrintVersion(C
, llvm::outs());
2082 if (C
.getArgs().hasArg(options::OPT_v
) ||
2083 C
.getArgs().hasArg(options::OPT__HASH_HASH_HASH
) ||
2084 C
.getArgs().hasArg(options::OPT_print_supported_cpus
)) {
2085 PrintVersion(C
, llvm::errs());
2086 SuppressMissingInputWarning
= true;
2089 if (C
.getArgs().hasArg(options::OPT_v
)) {
2090 if (!SystemConfigDir
.empty())
2091 llvm::errs() << "System configuration file directory: "
2092 << SystemConfigDir
<< "\n";
2093 if (!UserConfigDir
.empty())
2094 llvm::errs() << "User configuration file directory: "
2095 << UserConfigDir
<< "\n";
2098 const ToolChain
&TC
= C
.getDefaultToolChain();
2100 if (C
.getArgs().hasArg(options::OPT_v
))
2101 TC
.printVerboseInfo(llvm::errs());
2103 if (C
.getArgs().hasArg(options::OPT_print_resource_dir
)) {
2104 llvm::outs() << ResourceDir
<< '\n';
2108 if (C
.getArgs().hasArg(options::OPT_print_search_dirs
)) {
2109 llvm::outs() << "programs: =";
2110 bool separator
= false;
2111 // Print -B and COMPILER_PATH.
2112 for (const std::string
&Path
: PrefixDirs
) {
2114 llvm::outs() << llvm::sys::EnvPathSeparator
;
2115 llvm::outs() << Path
;
2118 for (const std::string
&Path
: TC
.getProgramPaths()) {
2120 llvm::outs() << llvm::sys::EnvPathSeparator
;
2121 llvm::outs() << Path
;
2124 llvm::outs() << "\n";
2125 llvm::outs() << "libraries: =" << ResourceDir
;
2127 StringRef sysroot
= C
.getSysRoot();
2129 for (const std::string
&Path
: TC
.getFilePaths()) {
2130 // Always print a separator. ResourceDir was the first item shown.
2131 llvm::outs() << llvm::sys::EnvPathSeparator
;
2132 // Interpretation of leading '=' is needed only for NetBSD.
2134 llvm::outs() << sysroot
<< Path
.substr(1);
2136 llvm::outs() << Path
;
2138 llvm::outs() << "\n";
2142 if (C
.getArgs().hasArg(options::OPT_print_runtime_dir
)) {
2143 std::string RuntimePath
;
2144 // Get the first existing path, if any.
2145 for (auto Path
: TC
.getRuntimePaths()) {
2146 if (getVFS().exists(Path
)) {
2151 if (!RuntimePath
.empty())
2152 llvm::outs() << RuntimePath
<< '\n';
2154 llvm::outs() << TC
.getCompilerRTPath() << '\n';
2158 if (C
.getArgs().hasArg(options::OPT_print_diagnostic_options
)) {
2159 std::vector
<std::string
> Flags
= DiagnosticIDs::getDiagnosticFlags();
2160 for (std::size_t I
= 0; I
!= Flags
.size(); I
+= 2)
2161 llvm::outs() << " " << Flags
[I
] << "\n " << Flags
[I
+ 1] << "\n\n";
2165 // FIXME: The following handlers should use a callback mechanism, we don't
2166 // know what the client would like to do.
2167 if (Arg
*A
= C
.getArgs().getLastArg(options::OPT_print_file_name_EQ
)) {
2168 llvm::outs() << GetFilePath(A
->getValue(), TC
) << "\n";
2172 if (Arg
*A
= C
.getArgs().getLastArg(options::OPT_print_prog_name_EQ
)) {
2173 StringRef ProgName
= A
->getValue();
2175 // Null program name cannot have a path.
2176 if (! ProgName
.empty())
2177 llvm::outs() << GetProgramPath(ProgName
, TC
);
2179 llvm::outs() << "\n";
2183 if (Arg
*A
= C
.getArgs().getLastArg(options::OPT_autocomplete
)) {
2184 StringRef PassedFlags
= A
->getValue();
2185 HandleAutocompletions(PassedFlags
);
2189 if (C
.getArgs().hasArg(options::OPT_print_libgcc_file_name
)) {
2190 ToolChain::RuntimeLibType RLT
= TC
.GetRuntimeLibType(C
.getArgs());
2191 const llvm::Triple
Triple(TC
.ComputeEffectiveClangTriple(C
.getArgs()));
2192 RegisterEffectiveTriple
TripleRAII(TC
, Triple
);
2194 case ToolChain::RLT_CompilerRT
:
2195 llvm::outs() << TC
.getCompilerRT(C
.getArgs(), "builtins") << "\n";
2197 case ToolChain::RLT_Libgcc
:
2198 llvm::outs() << GetFilePath("libgcc.a", TC
) << "\n";
2204 if (C
.getArgs().hasArg(options::OPT_print_multi_lib
)) {
2205 for (const Multilib
&Multilib
: TC
.getMultilibs())
2206 llvm::outs() << Multilib
<< "\n";
2210 if (C
.getArgs().hasArg(options::OPT_print_multi_directory
)) {
2211 const Multilib
&Multilib
= TC
.getMultilib();
2212 if (Multilib
.gccSuffix().empty())
2213 llvm::outs() << ".\n";
2215 StringRef
Suffix(Multilib
.gccSuffix());
2216 assert(Suffix
.front() == '/');
2217 llvm::outs() << Suffix
.substr(1) << "\n";
2222 if (C
.getArgs().hasArg(options::OPT_print_target_triple
)) {
2223 llvm::outs() << TC
.getTripleString() << "\n";
2227 if (C
.getArgs().hasArg(options::OPT_print_effective_triple
)) {
2228 const llvm::Triple
Triple(TC
.ComputeEffectiveClangTriple(C
.getArgs()));
2229 llvm::outs() << Triple
.getTriple() << "\n";
2233 if (C
.getArgs().hasArg(options::OPT_print_targets
)) {
2234 llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
2247 // Display an action graph human-readably. Action A is the "sink" node
2248 // and latest-occuring action. Traversal is in pre-order, visiting the
2249 // inputs to each action before printing the action itself.
2250 static unsigned PrintActions1(const Compilation
&C
, Action
*A
,
2251 std::map
<Action
*, unsigned> &Ids
,
2252 Twine Indent
= {}, int Kind
= TopLevelAction
) {
2253 if (Ids
.count(A
)) // A was already visited.
2257 llvm::raw_string_ostream
os(str
);
2259 auto getSibIndent
= [](int K
) -> Twine
{
2260 return (K
== HeadSibAction
) ? " " : (K
== OtherSibAction
) ? "| " : "";
2263 Twine SibIndent
= Indent
+ getSibIndent(Kind
);
2264 int SibKind
= HeadSibAction
;
2265 os
<< Action::getClassName(A
->getKind()) << ", ";
2266 if (InputAction
*IA
= dyn_cast
<InputAction
>(A
)) {
2267 os
<< "\"" << IA
->getInputArg().getValue() << "\"";
2268 } else if (BindArchAction
*BIA
= dyn_cast
<BindArchAction
>(A
)) {
2269 os
<< '"' << BIA
->getArchName() << '"' << ", {"
2270 << PrintActions1(C
, *BIA
->input_begin(), Ids
, SibIndent
, SibKind
) << "}";
2271 } else if (OffloadAction
*OA
= dyn_cast
<OffloadAction
>(A
)) {
2272 bool IsFirst
= true;
2273 OA
->doOnEachDependence(
2274 [&](Action
*A
, const ToolChain
*TC
, const char *BoundArch
) {
2275 assert(TC
&& "Unknown host toolchain");
2276 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
2277 // sm_35 this will generate:
2278 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
2279 // (nvptx64-nvidia-cuda:sm_35) {#ID}
2283 os
<< A
->getOffloadingKindPrefix();
2285 os
<< TC
->getTriple().normalize();
2287 os
<< ":" << BoundArch
;
2290 os
<< " {" << PrintActions1(C
, A
, Ids
, SibIndent
, SibKind
) << "}";
2292 SibKind
= OtherSibAction
;
2295 const ActionList
*AL
= &A
->getInputs();
2298 const char *Prefix
= "{";
2299 for (Action
*PreRequisite
: *AL
) {
2300 os
<< Prefix
<< PrintActions1(C
, PreRequisite
, Ids
, SibIndent
, SibKind
);
2302 SibKind
= OtherSibAction
;
2309 // Append offload info for all options other than the offloading action
2310 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
2311 std::string offload_str
;
2312 llvm::raw_string_ostream
offload_os(offload_str
);
2313 if (!isa
<OffloadAction
>(A
)) {
2314 auto S
= A
->getOffloadingKindPrefix();
2316 offload_os
<< ", (" << S
;
2317 if (A
->getOffloadingArch())
2318 offload_os
<< ", " << A
->getOffloadingArch();
2323 auto getSelfIndent
= [](int K
) -> Twine
{
2324 return (K
== HeadSibAction
) ? "+- " : (K
== OtherSibAction
) ? "|- " : "";
2327 unsigned Id
= Ids
.size();
2329 llvm::errs() << Indent
+ getSelfIndent(Kind
) << Id
<< ": " << os
.str() << ", "
2330 << types::getTypeName(A
->getType()) << offload_os
.str() << "\n";
2335 // Print the action graphs in a compilation C.
2336 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
2337 void Driver::PrintActions(const Compilation
&C
) const {
2338 std::map
<Action
*, unsigned> Ids
;
2339 for (Action
*A
: C
.getActions())
2340 PrintActions1(C
, A
, Ids
);
2343 /// Check whether the given input tree contains any compilation or
2344 /// assembly actions.
2345 static bool ContainsCompileOrAssembleAction(const Action
*A
) {
2346 if (isa
<CompileJobAction
>(A
) || isa
<BackendJobAction
>(A
) ||
2347 isa
<AssembleJobAction
>(A
))
2350 return llvm::any_of(A
->inputs(), ContainsCompileOrAssembleAction
);
2353 void Driver::BuildUniversalActions(Compilation
&C
, const ToolChain
&TC
,
2354 const InputList
&BAInputs
) const {
2355 DerivedArgList
&Args
= C
.getArgs();
2356 ActionList
&Actions
= C
.getActions();
2357 llvm::PrettyStackTraceString
CrashInfo("Building universal build actions");
2358 // Collect the list of architectures. Duplicates are allowed, but should only
2359 // be handled once (in the order seen).
2360 llvm::StringSet
<> ArchNames
;
2361 SmallVector
<const char *, 4> Archs
;
2362 for (Arg
*A
: Args
) {
2363 if (A
->getOption().matches(options::OPT_arch
)) {
2364 // Validate the option here; we don't save the type here because its
2365 // particular spelling may participate in other driver choices.
2366 llvm::Triple::ArchType Arch
=
2367 tools::darwin::getArchTypeForMachOArchName(A
->getValue());
2368 if (Arch
== llvm::Triple::UnknownArch
) {
2369 Diag(clang::diag::err_drv_invalid_arch_name
) << A
->getAsString(Args
);
2374 if (ArchNames
.insert(A
->getValue()).second
)
2375 Archs
.push_back(A
->getValue());
2379 // When there is no explicit arch for this platform, make sure we still bind
2380 // the architecture (to the default) so that -Xarch_ is handled correctly.
2382 Archs
.push_back(Args
.MakeArgString(TC
.getDefaultUniversalArchName()));
2384 ActionList SingleActions
;
2385 BuildActions(C
, Args
, BAInputs
, SingleActions
);
2387 // Add in arch bindings for every top level action, as well as lipo and
2388 // dsymutil steps if needed.
2389 for (Action
* Act
: SingleActions
) {
2390 // Make sure we can lipo this kind of output. If not (and it is an actual
2391 // output) then we disallow, since we can't create an output file with the
2392 // right name without overwriting it. We could remove this oddity by just
2393 // changing the output names to include the arch, which would also fix
2394 // -save-temps. Compatibility wins for now.
2396 if (Archs
.size() > 1 && !types::canLipoType(Act
->getType()))
2397 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs
)
2398 << types::getTypeName(Act
->getType());
2401 for (unsigned i
= 0, e
= Archs
.size(); i
!= e
; ++i
)
2402 Inputs
.push_back(C
.MakeAction
<BindArchAction
>(Act
, Archs
[i
]));
2404 // Lipo if necessary, we do it this way because we need to set the arch flag
2405 // so that -Xarch_ gets overwritten.
2406 if (Inputs
.size() == 1 || Act
->getType() == types::TY_Nothing
)
2407 Actions
.append(Inputs
.begin(), Inputs
.end());
2409 Actions
.push_back(C
.MakeAction
<LipoJobAction
>(Inputs
, Act
->getType()));
2411 // Handle debug info queries.
2412 Arg
*A
= Args
.getLastArg(options::OPT_g_Group
);
2413 bool enablesDebugInfo
= A
&& !A
->getOption().matches(options::OPT_g0
) &&
2414 !A
->getOption().matches(options::OPT_gstabs
);
2415 if ((enablesDebugInfo
|| willEmitRemarks(Args
)) &&
2416 ContainsCompileOrAssembleAction(Actions
.back())) {
2418 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
2419 // have a compile input. We need to run 'dsymutil' ourselves in such cases
2420 // because the debug info will refer to a temporary object file which
2421 // will be removed at the end of the compilation process.
2422 if (Act
->getType() == types::TY_Image
) {
2424 Inputs
.push_back(Actions
.back());
2427 C
.MakeAction
<DsymutilJobAction
>(Inputs
, types::TY_dSYM
));
2430 // Verify the debug info output.
2431 if (Args
.hasArg(options::OPT_verify_debug_info
)) {
2432 Action
* LastAction
= Actions
.back();
2434 Actions
.push_back(C
.MakeAction
<VerifyDebugInfoJobAction
>(
2435 LastAction
, types::TY_Nothing
));
2441 bool Driver::DiagnoseInputExistence(const DerivedArgList
&Args
, StringRef Value
,
2442 types::ID Ty
, bool TypoCorrect
) const {
2443 if (!getCheckInputsExist())
2446 // stdin always exists.
2450 // If it's a header to be found in the system or user search path, then defer
2451 // complaints about its absence until those searches can be done. When we
2452 // are definitely processing headers for C++20 header units, extend this to
2453 // allow the user to put "-fmodule-header -xc++-header vector" for example.
2454 if (Ty
== types::TY_CXXSHeader
|| Ty
== types::TY_CXXUHeader
||
2455 (ModulesModeCXX20
&& Ty
== types::TY_CXXHeader
))
2458 if (getVFS().exists(Value
))
2462 // Check if the filename is a typo for an option flag. OptTable thinks
2463 // that all args that are not known options and that start with / are
2464 // filenames, but e.g. `/diagnostic:caret` is more likely a typo for
2465 // the option `/diagnostics:caret` than a reference to a file in the root
2467 unsigned IncludedFlagsBitmask
;
2468 unsigned ExcludedFlagsBitmask
;
2469 std::tie(IncludedFlagsBitmask
, ExcludedFlagsBitmask
) =
2470 getIncludeExcludeOptionFlagMasks(IsCLMode());
2471 std::string Nearest
;
2472 if (getOpts().findNearest(Value
, Nearest
, IncludedFlagsBitmask
,
2473 ExcludedFlagsBitmask
) <= 1) {
2474 Diag(clang::diag::err_drv_no_such_file_with_suggestion
)
2475 << Value
<< Nearest
;
2480 // In CL mode, don't error on apparently non-existent linker inputs, because
2481 // they can be influenced by linker flags the clang driver might not
2484 // - `clang-cl main.cc ole32.lib` in a non-MSVC shell will make the driver
2485 // module look for an MSVC installation in the registry. (We could ask
2486 // the MSVCToolChain object if it can find `ole32.lib`, but the logic to
2487 // look in the registry might move into lld-link in the future so that
2488 // lld-link invocations in non-MSVC shells just work too.)
2489 // - `clang-cl ... /link ...` can pass arbitrary flags to the linker,
2490 // including /libpath:, which is used to find .lib and .obj files.
2491 // So do not diagnose this on the driver level. Rely on the linker diagnosing
2492 // it. (If we don't end up invoking the linker, this means we'll emit a
2493 // "'linker' input unused [-Wunused-command-line-argument]" warning instead
2496 // Only do this skip after the typo correction step above. `/Brepo` is treated
2497 // as TY_Object, but it's clearly a typo for `/Brepro`. It seems fine to emit
2498 // an error if we have a flag that's within an edit distance of 1 from a
2499 // flag. (Users can use `-Wl,` or `/linker` to launder the flag past the
2500 // driver in the unlikely case they run into this.)
2502 // Don't do this for inputs that start with a '/', else we'd pass options
2503 // like /libpath: through to the linker silently.
2505 // Emitting an error for linker inputs can also cause incorrect diagnostics
2506 // with the gcc driver. The command
2507 // clang -fuse-ld=lld -Wl,--chroot,some/dir /file.o
2508 // will make lld look for some/dir/file.o, while we will diagnose here that
2509 // `/file.o` does not exist. However, configure scripts check if
2510 // `clang /GR-` compiles without error to see if the compiler is cl.exe,
2511 // so we can't downgrade diagnostics for `/GR-` from an error to a warning
2512 // in cc mode. (We can in cl mode because cl.exe itself only warns on
2514 if (IsCLMode() && Ty
== types::TY_Object
&& !Value
.startswith("/"))
2517 Diag(clang::diag::err_drv_no_such_file
) << Value
;
2521 // Get the C++20 Header Unit type corresponding to the input type.
2522 static types::ID
CXXHeaderUnitType(ModuleHeaderMode HM
) {
2524 case HeaderMode_User
:
2525 return types::TY_CXXUHeader
;
2526 case HeaderMode_System
:
2527 return types::TY_CXXSHeader
;
2528 case HeaderMode_Default
:
2530 case HeaderMode_None
:
2531 llvm_unreachable("should not be called in this case");
2533 return types::TY_CXXHUHeader
;
2536 // Construct a the list of inputs and their types.
2537 void Driver::BuildInputs(const ToolChain
&TC
, DerivedArgList
&Args
,
2538 InputList
&Inputs
) const {
2539 const llvm::opt::OptTable
&Opts
= getOpts();
2540 // Track the current user specified (-x) input. We also explicitly track the
2541 // argument used to set the type; we only want to claim the type when we
2542 // actually use it, so we warn about unused -x arguments.
2543 types::ID InputType
= types::TY_Nothing
;
2544 Arg
*InputTypeArg
= nullptr;
2546 // The last /TC or /TP option sets the input type to C or C++ globally.
2547 if (Arg
*TCTP
= Args
.getLastArgNoClaim(options::OPT__SLASH_TC
,
2548 options::OPT__SLASH_TP
)) {
2549 InputTypeArg
= TCTP
;
2550 InputType
= TCTP
->getOption().matches(options::OPT__SLASH_TC
)
2554 Arg
*Previous
= nullptr;
2555 bool ShowNote
= false;
2557 Args
.filtered(options::OPT__SLASH_TC
, options::OPT__SLASH_TP
)) {
2559 Diag(clang::diag::warn_drv_overriding_flag_option
)
2560 << Previous
->getSpelling() << A
->getSpelling();
2566 Diag(clang::diag::note_drv_t_option_is_global
);
2569 // Warn -x after last input file has no effect
2571 Arg
*LastXArg
= Args
.getLastArgNoClaim(options::OPT_x
);
2572 Arg
*LastInputArg
= Args
.getLastArgNoClaim(options::OPT_INPUT
);
2573 if (LastXArg
&& LastInputArg
&&
2574 LastInputArg
->getIndex() < LastXArg
->getIndex())
2575 Diag(clang::diag::warn_drv_unused_x
) << LastXArg
->getValue();
2577 // In CL mode suggest /TC or /TP since -x doesn't make sense if passed via
2579 if (auto *A
= Args
.getLastArg(options::OPT_x
))
2580 Diag(diag::err_drv_unsupported_opt_with_suggestion
)
2581 << A
->getAsString(Args
) << "/TC' or '/TP";
2584 for (Arg
*A
: Args
) {
2585 if (A
->getOption().getKind() == Option::InputClass
) {
2586 const char *Value
= A
->getValue();
2587 types::ID Ty
= types::TY_INVALID
;
2589 // Infer the input type if necessary.
2590 if (InputType
== types::TY_Nothing
) {
2591 // If there was an explicit arg for this, claim it.
2593 InputTypeArg
->claim();
2595 // stdin must be handled specially.
2596 if (memcmp(Value
, "-", 2) == 0) {
2597 if (IsFlangMode()) {
2598 Ty
= types::TY_Fortran
;
2600 // If running with -E, treat as a C input (this changes the
2601 // builtin macros, for example). This may be overridden by -ObjC
2604 // Otherwise emit an error but still use a valid type to avoid
2605 // spurious errors (e.g., no inputs).
2606 assert(!CCGenDiagnostics
&& "stdin produces no crash reproducer");
2607 if (!Args
.hasArgNoClaim(options::OPT_E
) && !CCCIsCPP())
2608 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2609 : clang::diag::err_drv_unknown_stdin_type
);
2613 // Otherwise lookup by extension.
2614 // Fallback is C if invoked as C preprocessor, C++ if invoked with
2615 // clang-cl /E, or Object otherwise.
2616 // We use a host hook here because Darwin at least has its own
2617 // idea of what .s is.
2618 if (const char *Ext
= strrchr(Value
, '.'))
2619 Ty
= TC
.LookupTypeForExtension(Ext
+ 1);
2621 if (Ty
== types::TY_INVALID
) {
2622 if (IsCLMode() && (Args
.hasArgNoClaim(options::OPT_E
) || CCGenDiagnostics
))
2624 else if (CCCIsCPP() || CCGenDiagnostics
)
2627 Ty
= types::TY_Object
;
2630 // If the driver is invoked as C++ compiler (like clang++ or c++) it
2631 // should autodetect some input files as C++ for g++ compatibility.
2633 types::ID OldTy
= Ty
;
2634 Ty
= types::lookupCXXTypeForCType(Ty
);
2636 // Do not complain about foo.h, when we are known to be processing
2637 // it as a C++20 header unit.
2638 if (Ty
!= OldTy
&& !(OldTy
== types::TY_CHeader
&& hasHeaderMode()))
2639 Diag(clang::diag::warn_drv_treating_input_as_cxx
)
2640 << getTypeName(OldTy
) << getTypeName(Ty
);
2643 // If running with -fthinlto-index=, extensions that normally identify
2644 // native object files actually identify LLVM bitcode files.
2645 if (Args
.hasArgNoClaim(options::OPT_fthinlto_index_EQ
) &&
2646 Ty
== types::TY_Object
)
2647 Ty
= types::TY_LLVM_BC
;
2650 // -ObjC and -ObjC++ override the default language, but only for "source
2651 // files". We just treat everything that isn't a linker input as a
2654 // FIXME: Clean this up if we move the phase sequence into the type.
2655 if (Ty
!= types::TY_Object
) {
2656 if (Args
.hasArg(options::OPT_ObjC
))
2657 Ty
= types::TY_ObjC
;
2658 else if (Args
.hasArg(options::OPT_ObjCXX
))
2659 Ty
= types::TY_ObjCXX
;
2662 // Disambiguate headers that are meant to be header units from those
2663 // intended to be PCH. Avoid missing '.h' cases that are counted as
2664 // C headers by default - we know we are in C++ mode and we do not
2665 // want to issue a complaint about compiling things in the wrong mode.
2666 if ((Ty
== types::TY_CXXHeader
|| Ty
== types::TY_CHeader
) &&
2668 Ty
= CXXHeaderUnitType(CXX20HeaderType
);
2670 assert(InputTypeArg
&& "InputType set w/o InputTypeArg");
2671 if (!InputTypeArg
->getOption().matches(options::OPT_x
)) {
2672 // If emulating cl.exe, make sure that /TC and /TP don't affect input
2674 const char *Ext
= strrchr(Value
, '.');
2675 if (Ext
&& TC
.LookupTypeForExtension(Ext
+ 1) == types::TY_Object
)
2676 Ty
= types::TY_Object
;
2678 if (Ty
== types::TY_INVALID
) {
2680 InputTypeArg
->claim();
2684 if (DiagnoseInputExistence(Args
, Value
, Ty
, /*TypoCorrect=*/true))
2685 Inputs
.push_back(std::make_pair(Ty
, A
));
2687 } else if (A
->getOption().matches(options::OPT__SLASH_Tc
)) {
2688 StringRef Value
= A
->getValue();
2689 if (DiagnoseInputExistence(Args
, Value
, types::TY_C
,
2690 /*TypoCorrect=*/false)) {
2691 Arg
*InputArg
= MakeInputArg(Args
, Opts
, A
->getValue());
2692 Inputs
.push_back(std::make_pair(types::TY_C
, InputArg
));
2695 } else if (A
->getOption().matches(options::OPT__SLASH_Tp
)) {
2696 StringRef Value
= A
->getValue();
2697 if (DiagnoseInputExistence(Args
, Value
, types::TY_CXX
,
2698 /*TypoCorrect=*/false)) {
2699 Arg
*InputArg
= MakeInputArg(Args
, Opts
, A
->getValue());
2700 Inputs
.push_back(std::make_pair(types::TY_CXX
, InputArg
));
2703 } else if (A
->getOption().hasFlag(options::LinkerInput
)) {
2704 // Just treat as object type, we could make a special type for this if
2706 Inputs
.push_back(std::make_pair(types::TY_Object
, A
));
2708 } else if (A
->getOption().matches(options::OPT_x
)) {
2710 InputType
= types::lookupTypeForTypeSpecifier(A
->getValue());
2713 // Follow gcc behavior and treat as linker input for invalid -x
2714 // options. Its not clear why we shouldn't just revert to unknown; but
2715 // this isn't very important, we might as well be bug compatible.
2717 Diag(clang::diag::err_drv_unknown_language
) << A
->getValue();
2718 InputType
= types::TY_Object
;
2721 // If the user has put -fmodule-header{,=} then we treat C++ headers as
2722 // header unit inputs. So we 'promote' -xc++-header appropriately.
2723 if (InputType
== types::TY_CXXHeader
&& hasHeaderMode())
2724 InputType
= CXXHeaderUnitType(CXX20HeaderType
);
2725 } else if (A
->getOption().getID() == options::OPT_U
) {
2726 assert(A
->getNumValues() == 1 && "The /U option has one value.");
2727 StringRef Val
= A
->getValue(0);
2728 if (Val
.find_first_of("/\\") != StringRef::npos
) {
2729 // Warn about e.g. "/Users/me/myfile.c".
2730 Diag(diag::warn_slash_u_filename
) << Val
;
2731 Diag(diag::note_use_dashdash
);
2735 if (CCCIsCPP() && Inputs
.empty()) {
2736 // If called as standalone preprocessor, stdin is processed
2737 // if no other input is present.
2738 Arg
*A
= MakeInputArg(Args
, Opts
, "-");
2739 Inputs
.push_back(std::make_pair(types::TY_C
, A
));
2744 /// Provides a convenient interface for different programming models to generate
2745 /// the required device actions.
2746 class OffloadingActionBuilder final
{
2747 /// Flag used to trace errors in the builder.
2748 bool IsValid
= false;
2750 /// The compilation that is using this builder.
2753 /// Map between an input argument and the offload kinds used to process it.
2754 std::map
<const Arg
*, unsigned> InputArgToOffloadKindMap
;
2756 /// Map between a host action and its originating input argument.
2757 std::map
<Action
*, const Arg
*> HostActionToInputArgMap
;
2759 /// Builder interface. It doesn't build anything or keep any state.
2760 class DeviceActionBuilder
{
2762 typedef const llvm::SmallVectorImpl
<phases::ID
> PhasesTy
;
2764 enum ActionBuilderReturnCode
{
2765 // The builder acted successfully on the current action.
2767 // The builder didn't have to act on the current action.
2769 // The builder was successful and requested the host action to not be
2775 /// Compilation associated with this builder.
2778 /// Tool chains associated with this builder. The same programming
2779 /// model may have associated one or more tool chains.
2780 SmallVector
<const ToolChain
*, 2> ToolChains
;
2782 /// The derived arguments associated with this builder.
2783 DerivedArgList
&Args
;
2785 /// The inputs associated with this builder.
2786 const Driver::InputList
&Inputs
;
2788 /// The associated offload kind.
2789 Action::OffloadKind AssociatedOffloadKind
= Action::OFK_None
;
2792 DeviceActionBuilder(Compilation
&C
, DerivedArgList
&Args
,
2793 const Driver::InputList
&Inputs
,
2794 Action::OffloadKind AssociatedOffloadKind
)
2795 : C(C
), Args(Args
), Inputs(Inputs
),
2796 AssociatedOffloadKind(AssociatedOffloadKind
) {}
2797 virtual ~DeviceActionBuilder() {}
2799 /// Fill up the array \a DA with all the device dependences that should be
2800 /// added to the provided host action \a HostAction. By default it is
2802 virtual ActionBuilderReturnCode
2803 getDeviceDependences(OffloadAction::DeviceDependences
&DA
,
2804 phases::ID CurPhase
, phases::ID FinalPhase
,
2806 return ABRT_Inactive
;
2809 /// Update the state to include the provided host action \a HostAction as a
2810 /// dependency of the current device action. By default it is inactive.
2811 virtual ActionBuilderReturnCode
addDeviceDependences(Action
*HostAction
) {
2812 return ABRT_Inactive
;
2815 /// Append top level actions generated by the builder.
2816 virtual void appendTopLevelActions(ActionList
&AL
) {}
2818 /// Append linker device actions generated by the builder.
2819 virtual void appendLinkDeviceActions(ActionList
&AL
) {}
2821 /// Append linker host action generated by the builder.
2822 virtual Action
* appendLinkHostActions(ActionList
&AL
) { return nullptr; }
2824 /// Append linker actions generated by the builder.
2825 virtual void appendLinkDependences(OffloadAction::DeviceDependences
&DA
) {}
2827 /// Initialize the builder. Return true if any initialization errors are
2829 virtual bool initialize() { return false; }
2831 /// Return true if the builder can use bundling/unbundling.
2832 virtual bool canUseBundlerUnbundler() const { return false; }
2834 /// Return true if this builder is valid. We have a valid builder if we have
2835 /// associated device tool chains.
2836 bool isValid() { return !ToolChains
.empty(); }
2838 /// Return the associated offload kind.
2839 Action::OffloadKind
getAssociatedOffloadKind() {
2840 return AssociatedOffloadKind
;
2844 /// Base class for CUDA/HIP action builder. It injects device code in
2845 /// the host backend action.
2846 class CudaActionBuilderBase
: public DeviceActionBuilder
{
2848 /// Flags to signal if the user requested host-only or device-only
2850 bool CompileHostOnly
= false;
2851 bool CompileDeviceOnly
= false;
2852 bool EmitLLVM
= false;
2853 bool EmitAsm
= false;
2855 /// ID to identify each device compilation. For CUDA it is simply the
2856 /// GPU arch string. For HIP it is either the GPU arch string or GPU
2857 /// arch string plus feature strings delimited by a plus sign, e.g.
2860 /// Target ID string which is persistent throughout the compilation.
2862 TargetID(CudaArch Arch
) { ID
= CudaArchToString(Arch
); }
2863 TargetID(const char *ID
) : ID(ID
) {}
2864 operator const char *() { return ID
; }
2865 operator StringRef() { return StringRef(ID
); }
2867 /// List of GPU architectures to use in this compilation.
2868 SmallVector
<TargetID
, 4> GpuArchList
;
2870 /// The CUDA actions for the current input.
2871 ActionList CudaDeviceActions
;
2873 /// The CUDA fat binary if it was generated for the current input.
2874 Action
*CudaFatBinary
= nullptr;
2876 /// Flag that is set to true if this builder acted on the current input.
2877 bool IsActive
= false;
2879 /// Flag for -fgpu-rdc.
2880 bool Relocatable
= false;
2882 /// Default GPU architecture if there's no one specified.
2883 CudaArch DefaultCudaArch
= CudaArch::UNKNOWN
;
2885 /// Method to generate compilation unit ID specified by option
2887 enum UseCUIDKind
{ CUID_Hash
, CUID_Random
, CUID_None
, CUID_Invalid
};
2888 UseCUIDKind UseCUID
= CUID_Hash
;
2890 /// Compilation unit ID specified by option '-cuid='.
2891 StringRef FixedCUID
;
2894 CudaActionBuilderBase(Compilation
&C
, DerivedArgList
&Args
,
2895 const Driver::InputList
&Inputs
,
2896 Action::OffloadKind OFKind
)
2897 : DeviceActionBuilder(C
, Args
, Inputs
, OFKind
) {}
2899 ActionBuilderReturnCode
addDeviceDependences(Action
*HostAction
) override
{
2900 // While generating code for CUDA, we only depend on the host input action
2901 // to trigger the creation of all the CUDA device actions.
2903 // If we are dealing with an input action, replicate it for each GPU
2904 // architecture. If we are in host-only mode we return 'success' so that
2905 // the host uses the CUDA offload kind.
2906 if (auto *IA
= dyn_cast
<InputAction
>(HostAction
)) {
2907 assert(!GpuArchList
.empty() &&
2908 "We should have at least one GPU architecture.");
2910 // If the host input is not CUDA or HIP, we don't need to bother about
2912 if (!(IA
->getType() == types::TY_CUDA
||
2913 IA
->getType() == types::TY_HIP
||
2914 IA
->getType() == types::TY_PP_HIP
)) {
2915 // The builder will ignore this input.
2917 return ABRT_Inactive
;
2920 // Set the flag to true, so that the builder acts on the current input.
2923 if (CompileHostOnly
)
2924 return ABRT_Success
;
2926 // Replicate inputs for each GPU architecture.
2927 auto Ty
= IA
->getType() == types::TY_HIP
? types::TY_HIP_DEVICE
2928 : types::TY_CUDA_DEVICE
;
2929 std::string CUID
= FixedCUID
.str();
2931 if (UseCUID
== CUID_Random
)
2932 CUID
= llvm::utohexstr(llvm::sys::Process::GetRandomNumber(),
2933 /*LowerCase=*/true);
2934 else if (UseCUID
== CUID_Hash
) {
2936 llvm::MD5::MD5Result Hash
;
2937 SmallString
<256> RealPath
;
2938 llvm::sys::fs::real_path(IA
->getInputArg().getValue(), RealPath
,
2939 /*expand_tilde=*/true);
2940 Hasher
.update(RealPath
);
2941 for (auto *A
: Args
) {
2942 if (A
->getOption().matches(options::OPT_INPUT
))
2944 Hasher
.update(A
->getAsString(Args
));
2947 CUID
= llvm::utohexstr(Hash
.low(), /*LowerCase=*/true);
2952 for (unsigned I
= 0, E
= GpuArchList
.size(); I
!= E
; ++I
) {
2953 CudaDeviceActions
.push_back(
2954 C
.MakeAction
<InputAction
>(IA
->getInputArg(), Ty
, IA
->getId()));
2957 return ABRT_Success
;
2960 // If this is an unbundling action use it as is for each CUDA toolchain.
2961 if (auto *UA
= dyn_cast
<OffloadUnbundlingJobAction
>(HostAction
)) {
2963 // If -fgpu-rdc is disabled, should not unbundle since there is no
2964 // device code to link.
2965 if (UA
->getType() == types::TY_Object
&& !Relocatable
)
2966 return ABRT_Inactive
;
2968 CudaDeviceActions
.clear();
2969 auto *IA
= cast
<InputAction
>(UA
->getInputs().back());
2970 std::string FileName
= IA
->getInputArg().getAsString(Args
);
2971 // Check if the type of the file is the same as the action. Do not
2972 // unbundle it if it is not. Do not unbundle .so files, for example,
2973 // which are not object files. Files with extension ".lib" is classified
2974 // as TY_Object but they are actually archives, therefore should not be
2975 // unbundled here as objects. They will be handled at other places.
2976 const StringRef LibFileExt
= ".lib";
2977 if (IA
->getType() == types::TY_Object
&&
2978 (!llvm::sys::path::has_extension(FileName
) ||
2979 types::lookupTypeForExtension(
2980 llvm::sys::path::extension(FileName
).drop_front()) !=
2982 llvm::sys::path::extension(FileName
) == LibFileExt
))
2983 return ABRT_Inactive
;
2985 for (auto Arch
: GpuArchList
) {
2986 CudaDeviceActions
.push_back(UA
);
2987 UA
->registerDependentActionInfo(ToolChains
[0], Arch
,
2988 AssociatedOffloadKind
);
2991 return ABRT_Success
;
2994 return IsActive
? ABRT_Success
: ABRT_Inactive
;
2997 void appendTopLevelActions(ActionList
&AL
) override
{
2998 // Utility to append actions to the top level list.
2999 auto AddTopLevel
= [&](Action
*A
, TargetID TargetID
) {
3000 OffloadAction::DeviceDependences Dep
;
3001 Dep
.add(*A
, *ToolChains
.front(), TargetID
, AssociatedOffloadKind
);
3002 AL
.push_back(C
.MakeAction
<OffloadAction
>(Dep
, A
->getType()));
3005 // If we have a fat binary, add it to the list.
3006 if (CudaFatBinary
) {
3007 AddTopLevel(CudaFatBinary
, CudaArch::UNUSED
);
3008 CudaDeviceActions
.clear();
3009 CudaFatBinary
= nullptr;
3013 if (CudaDeviceActions
.empty())
3016 // If we have CUDA actions at this point, that's because we have a have
3017 // partial compilation, so we should have an action for each GPU
3019 assert(CudaDeviceActions
.size() == GpuArchList
.size() &&
3020 "Expecting one action per GPU architecture.");
3021 assert(ToolChains
.size() == 1 &&
3022 "Expecting to have a single CUDA toolchain.");
3023 for (unsigned I
= 0, E
= GpuArchList
.size(); I
!= E
; ++I
)
3024 AddTopLevel(CudaDeviceActions
[I
], GpuArchList
[I
]);
3026 CudaDeviceActions
.clear();
3029 /// Get canonicalized offload arch option. \returns empty StringRef if the
3030 /// option is invalid.
3031 virtual StringRef
getCanonicalOffloadArch(StringRef Arch
) = 0;
3033 virtual std::optional
<std::pair
<llvm::StringRef
, llvm::StringRef
>>
3034 getConflictOffloadArchCombination(const std::set
<StringRef
> &GpuArchs
) = 0;
3036 bool initialize() override
{
3037 assert(AssociatedOffloadKind
== Action::OFK_Cuda
||
3038 AssociatedOffloadKind
== Action::OFK_HIP
);
3040 // We don't need to support CUDA.
3041 if (AssociatedOffloadKind
== Action::OFK_Cuda
&&
3042 !C
.hasOffloadToolChain
<Action::OFK_Cuda
>())
3045 // We don't need to support HIP.
3046 if (AssociatedOffloadKind
== Action::OFK_HIP
&&
3047 !C
.hasOffloadToolChain
<Action::OFK_HIP
>())
3050 Relocatable
= Args
.hasFlag(options::OPT_fgpu_rdc
,
3051 options::OPT_fno_gpu_rdc
, /*Default=*/false);
3053 const ToolChain
*HostTC
= C
.getSingleOffloadToolChain
<Action::OFK_Host
>();
3054 assert(HostTC
&& "No toolchain for host compilation.");
3055 if (HostTC
->getTriple().isNVPTX() ||
3056 HostTC
->getTriple().getArch() == llvm::Triple::amdgcn
) {
3057 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
3058 // an error and abort pipeline construction early so we don't trip
3059 // asserts that assume device-side compilation.
3060 C
.getDriver().Diag(diag::err_drv_cuda_host_arch
)
3061 << HostTC
->getTriple().getArchName();
3065 ToolChains
.push_back(
3066 AssociatedOffloadKind
== Action::OFK_Cuda
3067 ? C
.getSingleOffloadToolChain
<Action::OFK_Cuda
>()
3068 : C
.getSingleOffloadToolChain
<Action::OFK_HIP
>());
3070 CompileHostOnly
= C
.getDriver().offloadHostOnly();
3071 CompileDeviceOnly
= C
.getDriver().offloadDeviceOnly();
3072 EmitLLVM
= Args
.getLastArg(options::OPT_emit_llvm
);
3073 EmitAsm
= Args
.getLastArg(options::OPT_S
);
3074 FixedCUID
= Args
.getLastArgValue(options::OPT_cuid_EQ
);
3075 if (Arg
*A
= Args
.getLastArg(options::OPT_fuse_cuid_EQ
)) {
3076 StringRef UseCUIDStr
= A
->getValue();
3077 UseCUID
= llvm::StringSwitch
<UseCUIDKind
>(UseCUIDStr
)
3078 .Case("hash", CUID_Hash
)
3079 .Case("random", CUID_Random
)
3080 .Case("none", CUID_None
)
3081 .Default(CUID_Invalid
);
3082 if (UseCUID
== CUID_Invalid
) {
3083 C
.getDriver().Diag(diag::err_drv_invalid_value
)
3084 << A
->getAsString(Args
) << UseCUIDStr
;
3085 C
.setContainsError();
3090 // --offload and --offload-arch options are mutually exclusive.
3091 if (Args
.hasArgNoClaim(options::OPT_offload_EQ
) &&
3092 Args
.hasArgNoClaim(options::OPT_offload_arch_EQ
,
3093 options::OPT_no_offload_arch_EQ
)) {
3094 C
.getDriver().Diag(diag::err_opt_not_valid_with_opt
) << "--offload-arch"
3098 // Collect all offload arch parameters, removing duplicates.
3099 std::set
<StringRef
> GpuArchs
;
3101 for (Arg
*A
: Args
) {
3102 if (!(A
->getOption().matches(options::OPT_offload_arch_EQ
) ||
3103 A
->getOption().matches(options::OPT_no_offload_arch_EQ
)))
3107 for (StringRef ArchStr
: llvm::split(A
->getValue(), ",")) {
3108 if (A
->getOption().matches(options::OPT_no_offload_arch_EQ
) &&
3111 } else if (ArchStr
== "native") {
3112 const ToolChain
&TC
= *ToolChains
.front();
3113 auto GPUsOrErr
= ToolChains
.front()->getSystemGPUArchs(Args
);
3115 TC
.getDriver().Diag(diag::err_drv_undetermined_gpu_arch
)
3116 << llvm::Triple::getArchTypeName(TC
.getArch())
3117 << llvm::toString(GPUsOrErr
.takeError()) << "--offload-arch";
3121 for (auto GPU
: *GPUsOrErr
) {
3122 GpuArchs
.insert(Args
.MakeArgString(GPU
));
3125 ArchStr
= getCanonicalOffloadArch(ArchStr
);
3126 if (ArchStr
.empty()) {
3128 } else if (A
->getOption().matches(options::OPT_offload_arch_EQ
))
3129 GpuArchs
.insert(ArchStr
);
3130 else if (A
->getOption().matches(options::OPT_no_offload_arch_EQ
))
3131 GpuArchs
.erase(ArchStr
);
3133 llvm_unreachable("Unexpected option.");
3138 auto &&ConflictingArchs
= getConflictOffloadArchCombination(GpuArchs
);
3139 if (ConflictingArchs
) {
3140 C
.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo
)
3141 << ConflictingArchs
->first
<< ConflictingArchs
->second
;
3142 C
.setContainsError();
3146 // Collect list of GPUs remaining in the set.
3147 for (auto Arch
: GpuArchs
)
3148 GpuArchList
.push_back(Arch
.data());
3150 // Default to sm_20 which is the lowest common denominator for
3151 // supported GPUs. sm_20 code should work correctly, if
3152 // suboptimally, on all newer GPUs.
3153 if (GpuArchList
.empty()) {
3154 if (ToolChains
.front()->getTriple().isSPIRV())
3155 GpuArchList
.push_back(CudaArch::Generic
);
3157 GpuArchList
.push_back(DefaultCudaArch
);
3164 /// \brief CUDA action builder. It injects device code in the host backend
3166 class CudaActionBuilder final
: public CudaActionBuilderBase
{
3168 CudaActionBuilder(Compilation
&C
, DerivedArgList
&Args
,
3169 const Driver::InputList
&Inputs
)
3170 : CudaActionBuilderBase(C
, Args
, Inputs
, Action::OFK_Cuda
) {
3171 DefaultCudaArch
= CudaArch::SM_35
;
3174 StringRef
getCanonicalOffloadArch(StringRef ArchStr
) override
{
3175 CudaArch Arch
= StringToCudaArch(ArchStr
);
3176 if (Arch
== CudaArch::UNKNOWN
|| !IsNVIDIAGpuArch(Arch
)) {
3177 C
.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch
) << ArchStr
;
3180 return CudaArchToString(Arch
);
3183 std::optional
<std::pair
<llvm::StringRef
, llvm::StringRef
>>
3184 getConflictOffloadArchCombination(
3185 const std::set
<StringRef
> &GpuArchs
) override
{
3186 return std::nullopt
;
3189 ActionBuilderReturnCode
3190 getDeviceDependences(OffloadAction::DeviceDependences
&DA
,
3191 phases::ID CurPhase
, phases::ID FinalPhase
,
3192 PhasesTy
&Phases
) override
{
3194 return ABRT_Inactive
;
3196 // If we don't have more CUDA actions, we don't have any dependences to
3197 // create for the host.
3198 if (CudaDeviceActions
.empty())
3199 return ABRT_Success
;
3201 assert(CudaDeviceActions
.size() == GpuArchList
.size() &&
3202 "Expecting one action per GPU architecture.");
3203 assert(!CompileHostOnly
&&
3204 "Not expecting CUDA actions in host-only compilation.");
3206 // If we are generating code for the device or we are in a backend phase,
3207 // we attempt to generate the fat binary. We compile each arch to ptx and
3208 // assemble to cubin, then feed the cubin *and* the ptx into a device
3209 // "link" action, which uses fatbinary to combine these cubins into one
3210 // fatbin. The fatbin is then an input to the host action if not in
3211 // device-only mode.
3212 if (CompileDeviceOnly
|| CurPhase
== phases::Backend
) {
3213 ActionList DeviceActions
;
3214 for (unsigned I
= 0, E
= GpuArchList
.size(); I
!= E
; ++I
) {
3215 // Produce the device action from the current phase up to the assemble
3217 for (auto Ph
: Phases
) {
3218 // Skip the phases that were already dealt with.
3221 // We have to be consistent with the host final phase.
3222 if (Ph
> FinalPhase
)
3225 CudaDeviceActions
[I
] = C
.getDriver().ConstructPhaseAction(
3226 C
, Args
, Ph
, CudaDeviceActions
[I
], Action::OFK_Cuda
);
3228 if (Ph
== phases::Assemble
)
3232 // If we didn't reach the assemble phase, we can't generate the fat
3233 // binary. We don't need to generate the fat binary if we are not in
3234 // device-only mode.
3235 if (!isa
<AssembleJobAction
>(CudaDeviceActions
[I
]) ||
3239 Action
*AssembleAction
= CudaDeviceActions
[I
];
3240 assert(AssembleAction
->getType() == types::TY_Object
);
3241 assert(AssembleAction
->getInputs().size() == 1);
3243 Action
*BackendAction
= AssembleAction
->getInputs()[0];
3244 assert(BackendAction
->getType() == types::TY_PP_Asm
);
3246 for (auto &A
: {AssembleAction
, BackendAction
}) {
3247 OffloadAction::DeviceDependences DDep
;
3248 DDep
.add(*A
, *ToolChains
.front(), GpuArchList
[I
], Action::OFK_Cuda
);
3249 DeviceActions
.push_back(
3250 C
.MakeAction
<OffloadAction
>(DDep
, A
->getType()));
3254 // We generate the fat binary if we have device input actions.
3255 if (!DeviceActions
.empty()) {
3257 C
.MakeAction
<LinkJobAction
>(DeviceActions
, types::TY_CUDA_FATBIN
);
3259 if (!CompileDeviceOnly
) {
3260 DA
.add(*CudaFatBinary
, *ToolChains
.front(), /*BoundArch=*/nullptr,
3262 // Clear the fat binary, it is already a dependence to an host
3264 CudaFatBinary
= nullptr;
3267 // Remove the CUDA actions as they are already connected to an host
3268 // action or fat binary.
3269 CudaDeviceActions
.clear();
3272 // We avoid creating host action in device-only mode.
3273 return CompileDeviceOnly
? ABRT_Ignore_Host
: ABRT_Success
;
3274 } else if (CurPhase
> phases::Backend
) {
3275 // If we are past the backend phase and still have a device action, we
3276 // don't have to do anything as this action is already a device
3277 // top-level action.
3278 return ABRT_Success
;
3281 assert(CurPhase
< phases::Backend
&& "Generating single CUDA "
3282 "instructions should only occur "
3283 "before the backend phase!");
3285 // By default, we produce an action for each device arch.
3286 for (Action
*&A
: CudaDeviceActions
)
3287 A
= C
.getDriver().ConstructPhaseAction(C
, Args
, CurPhase
, A
);
3289 return ABRT_Success
;
3292 /// \brief HIP action builder. It injects device code in the host backend
3294 class HIPActionBuilder final
: public CudaActionBuilderBase
{
3295 /// The linker inputs obtained for each device arch.
3296 SmallVector
<ActionList
, 8> DeviceLinkerInputs
;
3297 // The default bundling behavior depends on the type of output, therefore
3298 // BundleOutput needs to be tri-value: None, true, or false.
3299 // Bundle code objects except --no-gpu-output is specified for device
3300 // only compilation. Bundle other type of output files only if
3301 // --gpu-bundle-output is specified for device only compilation.
3302 std::optional
<bool> BundleOutput
;
3305 HIPActionBuilder(Compilation
&C
, DerivedArgList
&Args
,
3306 const Driver::InputList
&Inputs
)
3307 : CudaActionBuilderBase(C
, Args
, Inputs
, Action::OFK_HIP
) {
3308 DefaultCudaArch
= CudaArch::GFX906
;
3309 if (Args
.hasArg(options::OPT_gpu_bundle_output
,
3310 options::OPT_no_gpu_bundle_output
))
3311 BundleOutput
= Args
.hasFlag(options::OPT_gpu_bundle_output
,
3312 options::OPT_no_gpu_bundle_output
, true);
3315 bool canUseBundlerUnbundler() const override
{ return true; }
3317 StringRef
getCanonicalOffloadArch(StringRef IdStr
) override
{
3318 llvm::StringMap
<bool> Features
;
3319 // getHIPOffloadTargetTriple() is known to return valid value as it has
3320 // been called successfully in the CreateOffloadingDeviceToolChains().
3321 auto ArchStr
= parseTargetID(
3322 *getHIPOffloadTargetTriple(C
.getDriver(), C
.getInputArgs()), IdStr
,
3325 C
.getDriver().Diag(clang::diag::err_drv_bad_target_id
) << IdStr
;
3326 C
.setContainsError();
3329 auto CanId
= getCanonicalTargetID(*ArchStr
, Features
);
3330 return Args
.MakeArgStringRef(CanId
);
3333 std::optional
<std::pair
<llvm::StringRef
, llvm::StringRef
>>
3334 getConflictOffloadArchCombination(
3335 const std::set
<StringRef
> &GpuArchs
) override
{
3336 return getConflictTargetIDCombination(GpuArchs
);
3339 ActionBuilderReturnCode
3340 getDeviceDependences(OffloadAction::DeviceDependences
&DA
,
3341 phases::ID CurPhase
, phases::ID FinalPhase
,
3342 PhasesTy
&Phases
) override
{
3344 return ABRT_Inactive
;
3346 // amdgcn does not support linking of object files, therefore we skip
3347 // backend and assemble phases to output LLVM IR. Except for generating
3348 // non-relocatable device code, where we generate fat binary for device
3349 // code and pass to host in Backend phase.
3350 if (CudaDeviceActions
.empty())
3351 return ABRT_Success
;
3353 assert(((CurPhase
== phases::Link
&& Relocatable
) ||
3354 CudaDeviceActions
.size() == GpuArchList
.size()) &&
3355 "Expecting one action per GPU architecture.");
3356 assert(!CompileHostOnly
&&
3357 "Not expecting HIP actions in host-only compilation.");
3359 if (!Relocatable
&& CurPhase
== phases::Backend
&& !EmitLLVM
&&
3361 // If we are in backend phase, we attempt to generate the fat binary.
3362 // We compile each arch to IR and use a link action to generate code
3363 // object containing ISA. Then we use a special "link" action to create
3364 // a fat binary containing all the code objects for different GPU's.
3365 // The fat binary is then an input to the host action.
3366 for (unsigned I
= 0, E
= GpuArchList
.size(); I
!= E
; ++I
) {
3367 if (C
.getDriver().isUsingLTO(/*IsOffload=*/true)) {
3368 // When LTO is enabled, skip the backend and assemble phases and
3369 // use lld to link the bitcode.
3371 AL
.push_back(CudaDeviceActions
[I
]);
3372 // Create a link action to link device IR with device library
3373 // and generate ISA.
3374 CudaDeviceActions
[I
] =
3375 C
.MakeAction
<LinkJobAction
>(AL
, types::TY_Image
);
3377 // When LTO is not enabled, we follow the conventional
3378 // compiler phases, including backend and assemble phases.
3380 Action
*BackendAction
= nullptr;
3381 if (ToolChains
.front()->getTriple().isSPIRV()) {
3382 // Emit LLVM bitcode for SPIR-V targets. SPIR-V device tool chain
3383 // (HIPSPVToolChain) runs post-link LLVM IR passes.
3384 types::ID Output
= Args
.hasArg(options::OPT_S
)
3386 : types::TY_LLVM_BC
;
3388 C
.MakeAction
<BackendJobAction
>(CudaDeviceActions
[I
], Output
);
3390 BackendAction
= C
.getDriver().ConstructPhaseAction(
3391 C
, Args
, phases::Backend
, CudaDeviceActions
[I
],
3392 AssociatedOffloadKind
);
3393 auto AssembleAction
= C
.getDriver().ConstructPhaseAction(
3394 C
, Args
, phases::Assemble
, BackendAction
,
3395 AssociatedOffloadKind
);
3396 AL
.push_back(AssembleAction
);
3397 // Create a link action to link device IR with device library
3398 // and generate ISA.
3399 CudaDeviceActions
[I
] =
3400 C
.MakeAction
<LinkJobAction
>(AL
, types::TY_Image
);
3403 // OffloadingActionBuilder propagates device arch until an offload
3404 // action. Since the next action for creating fatbin does
3405 // not have device arch, whereas the above link action and its input
3406 // have device arch, an offload action is needed to stop the null
3407 // device arch of the next action being propagated to the above link
3409 OffloadAction::DeviceDependences DDep
;
3410 DDep
.add(*CudaDeviceActions
[I
], *ToolChains
.front(), GpuArchList
[I
],
3411 AssociatedOffloadKind
);
3412 CudaDeviceActions
[I
] = C
.MakeAction
<OffloadAction
>(
3413 DDep
, CudaDeviceActions
[I
]->getType());
3416 if (!CompileDeviceOnly
|| !BundleOutput
|| *BundleOutput
) {
3417 // Create HIP fat binary with a special "link" action.
3418 CudaFatBinary
= C
.MakeAction
<LinkJobAction
>(CudaDeviceActions
,
3419 types::TY_HIP_FATBIN
);
3421 if (!CompileDeviceOnly
) {
3422 DA
.add(*CudaFatBinary
, *ToolChains
.front(), /*BoundArch=*/nullptr,
3423 AssociatedOffloadKind
);
3424 // Clear the fat binary, it is already a dependence to an host
3426 CudaFatBinary
= nullptr;
3429 // Remove the CUDA actions as they are already connected to an host
3430 // action or fat binary.
3431 CudaDeviceActions
.clear();
3434 return CompileDeviceOnly
? ABRT_Ignore_Host
: ABRT_Success
;
3435 } else if (CurPhase
== phases::Link
) {
3436 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
3437 // This happens to each device action originated from each input file.
3438 // Later on, device actions in DeviceLinkerInputs are used to create
3439 // device link actions in appendLinkDependences and the created device
3440 // link actions are passed to the offload action as device dependence.
3441 DeviceLinkerInputs
.resize(CudaDeviceActions
.size());
3442 auto LI
= DeviceLinkerInputs
.begin();
3443 for (auto *A
: CudaDeviceActions
) {
3448 // We will pass the device action as a host dependence, so we don't
3449 // need to do anything else with them.
3450 CudaDeviceActions
.clear();
3451 return CompileDeviceOnly
? ABRT_Ignore_Host
: ABRT_Success
;
3454 // By default, we produce an action for each device arch.
3455 for (Action
*&A
: CudaDeviceActions
)
3456 A
= C
.getDriver().ConstructPhaseAction(C
, Args
, CurPhase
, A
,
3457 AssociatedOffloadKind
);
3459 if (CompileDeviceOnly
&& CurPhase
== FinalPhase
&& BundleOutput
&&
3461 for (unsigned I
= 0, E
= GpuArchList
.size(); I
!= E
; ++I
) {
3462 OffloadAction::DeviceDependences DDep
;
3463 DDep
.add(*CudaDeviceActions
[I
], *ToolChains
.front(), GpuArchList
[I
],
3464 AssociatedOffloadKind
);
3465 CudaDeviceActions
[I
] = C
.MakeAction
<OffloadAction
>(
3466 DDep
, CudaDeviceActions
[I
]->getType());
3469 C
.MakeAction
<OffloadBundlingJobAction
>(CudaDeviceActions
);
3470 CudaDeviceActions
.clear();
3473 return (CompileDeviceOnly
&& CurPhase
== FinalPhase
) ? ABRT_Ignore_Host
3477 void appendLinkDeviceActions(ActionList
&AL
) override
{
3478 if (DeviceLinkerInputs
.size() == 0)
3481 assert(DeviceLinkerInputs
.size() == GpuArchList
.size() &&
3482 "Linker inputs and GPU arch list sizes do not match.");
3486 // Append a new link action for each device.
3487 // Each entry in DeviceLinkerInputs corresponds to a GPU arch.
3488 for (auto &LI
: DeviceLinkerInputs
) {
3490 types::ID Output
= Args
.hasArg(options::OPT_emit_llvm
)
3494 auto *DeviceLinkAction
= C
.MakeAction
<LinkJobAction
>(LI
, Output
);
3495 // Linking all inputs for the current GPU arch.
3496 // LI contains all the inputs for the linker.
3497 OffloadAction::DeviceDependences DeviceLinkDeps
;
3498 DeviceLinkDeps
.add(*DeviceLinkAction
, *ToolChains
[0],
3499 GpuArchList
[I
], AssociatedOffloadKind
);
3500 Actions
.push_back(C
.MakeAction
<OffloadAction
>(
3501 DeviceLinkDeps
, DeviceLinkAction
->getType()));
3504 DeviceLinkerInputs
.clear();
3506 // If emitting LLVM, do not generate final host/device compilation action
3507 if (Args
.hasArg(options::OPT_emit_llvm
)) {
3512 // Create a host object from all the device images by embedding them
3513 // in a fat binary for mixed host-device compilation. For device-only
3514 // compilation, creates a fat binary.
3515 OffloadAction::DeviceDependences DDeps
;
3516 if (!CompileDeviceOnly
|| !BundleOutput
|| *BundleOutput
) {
3517 auto *TopDeviceLinkAction
= C
.MakeAction
<LinkJobAction
>(
3519 CompileDeviceOnly
? types::TY_HIP_FATBIN
: types::TY_Object
);
3520 DDeps
.add(*TopDeviceLinkAction
, *ToolChains
[0], nullptr,
3521 AssociatedOffloadKind
);
3522 // Offload the host object to the host linker.
3524 C
.MakeAction
<OffloadAction
>(DDeps
, TopDeviceLinkAction
->getType()));
3530 Action
* appendLinkHostActions(ActionList
&AL
) override
{ return AL
.back(); }
3532 void appendLinkDependences(OffloadAction::DeviceDependences
&DA
) override
{}
3536 /// TODO: Add the implementation for other specialized builders here.
3539 /// Specialized builders being used by this offloading action builder.
3540 SmallVector
<DeviceActionBuilder
*, 4> SpecializedBuilders
;
3542 /// Flag set to true if all valid builders allow file bundling/unbundling.
3546 OffloadingActionBuilder(Compilation
&C
, DerivedArgList
&Args
,
3547 const Driver::InputList
&Inputs
)
3549 // Create a specialized builder for each device toolchain.
3553 // Create a specialized builder for CUDA.
3554 SpecializedBuilders
.push_back(new CudaActionBuilder(C
, Args
, Inputs
));
3556 // Create a specialized builder for HIP.
3557 SpecializedBuilders
.push_back(new HIPActionBuilder(C
, Args
, Inputs
));
3560 // TODO: Build other specialized builders here.
3563 // Initialize all the builders, keeping track of errors. If all valid
3564 // builders agree that we can use bundling, set the flag to true.
3565 unsigned ValidBuilders
= 0u;
3566 unsigned ValidBuildersSupportingBundling
= 0u;
3567 for (auto *SB
: SpecializedBuilders
) {
3568 IsValid
= IsValid
&& !SB
->initialize();
3570 // Update the counters if the builder is valid.
3571 if (SB
->isValid()) {
3573 if (SB
->canUseBundlerUnbundler())
3574 ++ValidBuildersSupportingBundling
;
3578 ValidBuilders
&& ValidBuilders
== ValidBuildersSupportingBundling
;
3581 ~OffloadingActionBuilder() {
3582 for (auto *SB
: SpecializedBuilders
)
3586 /// Record a host action and its originating input argument.
3587 void recordHostAction(Action
*HostAction
, const Arg
*InputArg
) {
3588 assert(HostAction
&& "Invalid host action");
3589 assert(InputArg
&& "Invalid input argument");
3590 auto Loc
= HostActionToInputArgMap
.find(HostAction
);
3591 if (Loc
== HostActionToInputArgMap
.end())
3592 HostActionToInputArgMap
[HostAction
] = InputArg
;
3593 assert(HostActionToInputArgMap
[HostAction
] == InputArg
&&
3594 "host action mapped to multiple input arguments");
3597 /// Generate an action that adds device dependences (if any) to a host action.
3598 /// If no device dependence actions exist, just return the host action \a
3599 /// HostAction. If an error is found or if no builder requires the host action
3600 /// to be generated, return nullptr.
3602 addDeviceDependencesToHostAction(Action
*HostAction
, const Arg
*InputArg
,
3603 phases::ID CurPhase
, phases::ID FinalPhase
,
3604 DeviceActionBuilder::PhasesTy
&Phases
) {
3608 if (SpecializedBuilders
.empty())
3611 assert(HostAction
&& "Invalid host action!");
3612 recordHostAction(HostAction
, InputArg
);
3614 OffloadAction::DeviceDependences DDeps
;
3615 // Check if all the programming models agree we should not emit the host
3616 // action. Also, keep track of the offloading kinds employed.
3617 auto &OffloadKind
= InputArgToOffloadKindMap
[InputArg
];
3618 unsigned InactiveBuilders
= 0u;
3619 unsigned IgnoringBuilders
= 0u;
3620 for (auto *SB
: SpecializedBuilders
) {
3621 if (!SB
->isValid()) {
3627 SB
->getDeviceDependences(DDeps
, CurPhase
, FinalPhase
, Phases
);
3629 // If the builder explicitly says the host action should be ignored,
3630 // we need to increment the variable that tracks the builders that request
3631 // the host object to be ignored.
3632 if (RetCode
== DeviceActionBuilder::ABRT_Ignore_Host
)
3635 // Unless the builder was inactive for this action, we have to record the
3636 // offload kind because the host will have to use it.
3637 if (RetCode
!= DeviceActionBuilder::ABRT_Inactive
)
3638 OffloadKind
|= SB
->getAssociatedOffloadKind();
3641 // If all builders agree that the host object should be ignored, just return
3643 if (IgnoringBuilders
&&
3644 SpecializedBuilders
.size() == (InactiveBuilders
+ IgnoringBuilders
))
3647 if (DDeps
.getActions().empty())
3650 // We have dependences we need to bundle together. We use an offload action
3652 OffloadAction::HostDependence
HDep(
3653 *HostAction
, *C
.getSingleOffloadToolChain
<Action::OFK_Host
>(),
3654 /*BoundArch=*/nullptr, DDeps
);
3655 return C
.MakeAction
<OffloadAction
>(HDep
, DDeps
);
3658 /// Generate an action that adds a host dependence to a device action. The
3659 /// results will be kept in this action builder. Return true if an error was
3661 bool addHostDependenceToDeviceActions(Action
*&HostAction
,
3662 const Arg
*InputArg
) {
3666 recordHostAction(HostAction
, InputArg
);
3668 // If we are supporting bundling/unbundling and the current action is an
3669 // input action of non-source file, we replace the host action by the
3670 // unbundling action. The bundler tool has the logic to detect if an input
3671 // is a bundle or not and if the input is not a bundle it assumes it is a
3672 // host file. Therefore it is safe to create an unbundling action even if
3673 // the input is not a bundle.
3674 if (CanUseBundler
&& isa
<InputAction
>(HostAction
) &&
3675 InputArg
->getOption().getKind() == llvm::opt::Option::InputClass
&&
3676 (!types::isSrcFile(HostAction
->getType()) ||
3677 HostAction
->getType() == types::TY_PP_HIP
)) {
3678 auto UnbundlingHostAction
=
3679 C
.MakeAction
<OffloadUnbundlingJobAction
>(HostAction
);
3680 UnbundlingHostAction
->registerDependentActionInfo(
3681 C
.getSingleOffloadToolChain
<Action::OFK_Host
>(),
3682 /*BoundArch=*/StringRef(), Action::OFK_Host
);
3683 HostAction
= UnbundlingHostAction
;
3684 recordHostAction(HostAction
, InputArg
);
3687 assert(HostAction
&& "Invalid host action!");
3689 // Register the offload kinds that are used.
3690 auto &OffloadKind
= InputArgToOffloadKindMap
[InputArg
];
3691 for (auto *SB
: SpecializedBuilders
) {
3695 auto RetCode
= SB
->addDeviceDependences(HostAction
);
3697 // Host dependences for device actions are not compatible with that same
3698 // action being ignored.
3699 assert(RetCode
!= DeviceActionBuilder::ABRT_Ignore_Host
&&
3700 "Host dependence not expected to be ignored.!");
3702 // Unless the builder was inactive for this action, we have to record the
3703 // offload kind because the host will have to use it.
3704 if (RetCode
!= DeviceActionBuilder::ABRT_Inactive
)
3705 OffloadKind
|= SB
->getAssociatedOffloadKind();
3708 // Do not use unbundler if the Host does not depend on device action.
3709 if (OffloadKind
== Action::OFK_None
&& CanUseBundler
)
3710 if (auto *UA
= dyn_cast
<OffloadUnbundlingJobAction
>(HostAction
))
3711 HostAction
= UA
->getInputs().back();
3716 /// Add the offloading top level actions to the provided action list. This
3717 /// function can replace the host action by a bundling action if the
3718 /// programming models allow it.
3719 bool appendTopLevelActions(ActionList
&AL
, Action
*HostAction
,
3720 const Arg
*InputArg
) {
3722 recordHostAction(HostAction
, InputArg
);
3724 // Get the device actions to be appended.
3725 ActionList OffloadAL
;
3726 for (auto *SB
: SpecializedBuilders
) {
3729 SB
->appendTopLevelActions(OffloadAL
);
3732 // If we can use the bundler, replace the host action by the bundling one in
3733 // the resulting list. Otherwise, just append the device actions. For
3734 // device only compilation, HostAction is a null pointer, therefore only do
3735 // this when HostAction is not a null pointer.
3736 if (CanUseBundler
&& HostAction
&&
3737 HostAction
->getType() != types::TY_Nothing
&& !OffloadAL
.empty()) {
3738 // Add the host action to the list in order to create the bundling action.
3739 OffloadAL
.push_back(HostAction
);
3741 // We expect that the host action was just appended to the action list
3742 // before this method was called.
3743 assert(HostAction
== AL
.back() && "Host action not in the list??");
3744 HostAction
= C
.MakeAction
<OffloadBundlingJobAction
>(OffloadAL
);
3745 recordHostAction(HostAction
, InputArg
);
3746 AL
.back() = HostAction
;
3748 AL
.append(OffloadAL
.begin(), OffloadAL
.end());
3750 // Propagate to the current host action (if any) the offload information
3751 // associated with the current input.
3753 HostAction
->propagateHostOffloadInfo(InputArgToOffloadKindMap
[InputArg
],
3754 /*BoundArch=*/nullptr);
3758 void appendDeviceLinkActions(ActionList
&AL
) {
3759 for (DeviceActionBuilder
*SB
: SpecializedBuilders
) {
3762 SB
->appendLinkDeviceActions(AL
);
3766 Action
*makeHostLinkAction() {
3767 // Build a list of device linking actions.
3768 ActionList DeviceAL
;
3769 appendDeviceLinkActions(DeviceAL
);
3770 if (DeviceAL
.empty())
3773 // Let builders add host linking actions.
3774 Action
* HA
= nullptr;
3775 for (DeviceActionBuilder
*SB
: SpecializedBuilders
) {
3778 HA
= SB
->appendLinkHostActions(DeviceAL
);
3779 // This created host action has no originating input argument, therefore
3780 // needs to set its offloading kind directly.
3782 HA
->propagateHostOffloadInfo(SB
->getAssociatedOffloadKind(),
3783 /*BoundArch=*/nullptr);
3788 /// Processes the host linker action. This currently consists of replacing it
3789 /// with an offload action if there are device link objects and propagate to
3790 /// the host action all the offload kinds used in the current compilation. The
3791 /// resulting action is returned.
3792 Action
*processHostLinkAction(Action
*HostAction
) {
3793 // Add all the dependences from the device linking actions.
3794 OffloadAction::DeviceDependences DDeps
;
3795 for (auto *SB
: SpecializedBuilders
) {
3799 SB
->appendLinkDependences(DDeps
);
3802 // Calculate all the offload kinds used in the current compilation.
3803 unsigned ActiveOffloadKinds
= 0u;
3804 for (auto &I
: InputArgToOffloadKindMap
)
3805 ActiveOffloadKinds
|= I
.second
;
3807 // If we don't have device dependencies, we don't have to create an offload
3809 if (DDeps
.getActions().empty()) {
3810 // Set all the active offloading kinds to the link action. Given that it
3811 // is a link action it is assumed to depend on all actions generated so
3813 HostAction
->setHostOffloadInfo(ActiveOffloadKinds
,
3814 /*BoundArch=*/nullptr);
3815 // Propagate active offloading kinds for each input to the link action.
3816 // Each input may have different active offloading kind.
3817 for (auto *A
: HostAction
->inputs()) {
3818 auto ArgLoc
= HostActionToInputArgMap
.find(A
);
3819 if (ArgLoc
== HostActionToInputArgMap
.end())
3821 auto OFKLoc
= InputArgToOffloadKindMap
.find(ArgLoc
->second
);
3822 if (OFKLoc
== InputArgToOffloadKindMap
.end())
3824 A
->propagateHostOffloadInfo(OFKLoc
->second
, /*BoundArch=*/nullptr);
3829 // Create the offload action with all dependences. When an offload action
3830 // is created the kinds are propagated to the host action, so we don't have
3831 // to do that explicitly here.
3832 OffloadAction::HostDependence
HDep(
3833 *HostAction
, *C
.getSingleOffloadToolChain
<Action::OFK_Host
>(),
3834 /*BoundArch*/ nullptr, ActiveOffloadKinds
);
3835 return C
.MakeAction
<OffloadAction
>(HDep
, DDeps
);
3838 } // anonymous namespace.
3840 void Driver::handleArguments(Compilation
&C
, DerivedArgList
&Args
,
3841 const InputList
&Inputs
,
3842 ActionList
&Actions
) const {
3844 // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
3845 Arg
*YcArg
= Args
.getLastArg(options::OPT__SLASH_Yc
);
3846 Arg
*YuArg
= Args
.getLastArg(options::OPT__SLASH_Yu
);
3847 if (YcArg
&& YuArg
&& strcmp(YcArg
->getValue(), YuArg
->getValue()) != 0) {
3848 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl
);
3849 Args
.eraseArg(options::OPT__SLASH_Yc
);
3850 Args
.eraseArg(options::OPT__SLASH_Yu
);
3851 YcArg
= YuArg
= nullptr;
3853 if (YcArg
&& Inputs
.size() > 1) {
3854 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl
);
3855 Args
.eraseArg(options::OPT__SLASH_Yc
);
3860 phases::ID FinalPhase
= getFinalPhase(Args
, &FinalPhaseArg
);
3862 if (FinalPhase
== phases::Link
) {
3863 // Emitting LLVM while linking disabled except in HIPAMD Toolchain
3864 if (Args
.hasArg(options::OPT_emit_llvm
) && !Args
.hasArg(options::OPT_hip_link
))
3865 Diag(clang::diag::err_drv_emit_llvm_link
);
3866 if (IsCLMode() && LTOMode
!= LTOK_None
&&
3867 !Args
.getLastArgValue(options::OPT_fuse_ld_EQ
)
3868 .equals_insensitive("lld"))
3869 Diag(clang::diag::err_drv_lto_without_lld
);
3872 if (FinalPhase
== phases::Preprocess
|| Args
.hasArg(options::OPT__SLASH_Y_
)) {
3873 // If only preprocessing or /Y- is used, all pch handling is disabled.
3874 // Rather than check for it everywhere, just remove clang-cl pch-related
3876 Args
.eraseArg(options::OPT__SLASH_Fp
);
3877 Args
.eraseArg(options::OPT__SLASH_Yc
);
3878 Args
.eraseArg(options::OPT__SLASH_Yu
);
3879 YcArg
= YuArg
= nullptr;
3882 unsigned LastPLSize
= 0;
3883 for (auto &I
: Inputs
) {
3884 types::ID InputType
= I
.first
;
3885 const Arg
*InputArg
= I
.second
;
3887 auto PL
= types::getCompilationPhases(InputType
);
3888 LastPLSize
= PL
.size();
3890 // If the first step comes after the final phase we are doing as part of
3891 // this compilation, warn the user about it.
3892 phases::ID InitialPhase
= PL
[0];
3893 if (InitialPhase
> FinalPhase
) {
3894 if (InputArg
->isClaimed())
3897 // Claim here to avoid the more general unused warning.
3900 // Suppress all unused style warnings with -Qunused-arguments
3901 if (Args
.hasArg(options::OPT_Qunused_arguments
))
3904 // Special case when final phase determined by binary name, rather than
3905 // by a command-line argument with a corresponding Arg.
3907 Diag(clang::diag::warn_drv_input_file_unused_by_cpp
)
3908 << InputArg
->getAsString(Args
) << getPhaseName(InitialPhase
);
3909 // Special case '-E' warning on a previously preprocessed file to make
3911 else if (InitialPhase
== phases::Compile
&&
3912 (Args
.getLastArg(options::OPT__SLASH_EP
,
3913 options::OPT__SLASH_P
) ||
3914 Args
.getLastArg(options::OPT_E
) ||
3915 Args
.getLastArg(options::OPT_M
, options::OPT_MM
)) &&
3916 getPreprocessedType(InputType
) == types::TY_INVALID
)
3917 Diag(clang::diag::warn_drv_preprocessed_input_file_unused
)
3918 << InputArg
->getAsString(Args
) << !!FinalPhaseArg
3919 << (FinalPhaseArg
? FinalPhaseArg
->getOption().getName() : "");
3921 Diag(clang::diag::warn_drv_input_file_unused
)
3922 << InputArg
->getAsString(Args
) << getPhaseName(InitialPhase
)
3924 << (FinalPhaseArg
? FinalPhaseArg
->getOption().getName() : "");
3929 // Add a separate precompile phase for the compile phase.
3930 if (FinalPhase
>= phases::Compile
) {
3931 const types::ID HeaderType
= lookupHeaderTypeForSourceType(InputType
);
3932 // Build the pipeline for the pch file.
3933 Action
*ClangClPch
= C
.MakeAction
<InputAction
>(*InputArg
, HeaderType
);
3934 for (phases::ID Phase
: types::getCompilationPhases(HeaderType
))
3935 ClangClPch
= ConstructPhaseAction(C
, Args
, Phase
, ClangClPch
);
3937 Actions
.push_back(ClangClPch
);
3938 // The driver currently exits after the first failed command. This
3939 // relies on that behavior, to make sure if the pch generation fails,
3940 // the main compilation won't run.
3941 // FIXME: If the main compilation fails, the PCH generation should
3942 // probably not be considered successful either.
3947 // If we are linking, claim any options which are obviously only used for
3949 // FIXME: Understand why the last Phase List length is used here.
3950 if (FinalPhase
== phases::Link
&& LastPLSize
== 1) {
3951 Args
.ClaimAllArgs(options::OPT_CompileOnly_Group
);
3952 Args
.ClaimAllArgs(options::OPT_cl_compile_Group
);
3956 void Driver::BuildActions(Compilation
&C
, DerivedArgList
&Args
,
3957 const InputList
&Inputs
, ActionList
&Actions
) const {
3958 llvm::PrettyStackTraceString
CrashInfo("Building compilation actions");
3960 if (!SuppressMissingInputWarning
&& Inputs
.empty()) {
3961 Diag(clang::diag::err_drv_no_input_files
);
3965 // Diagnose misuse of /Fo.
3966 if (Arg
*A
= Args
.getLastArg(options::OPT__SLASH_Fo
)) {
3967 StringRef V
= A
->getValue();
3968 if (Inputs
.size() > 1 && !V
.empty() &&
3969 !llvm::sys::path::is_separator(V
.back())) {
3970 // Check whether /Fo tries to name an output file for multiple inputs.
3971 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources
)
3972 << A
->getSpelling() << V
;
3973 Args
.eraseArg(options::OPT__SLASH_Fo
);
3977 // Diagnose misuse of /Fa.
3978 if (Arg
*A
= Args
.getLastArg(options::OPT__SLASH_Fa
)) {
3979 StringRef V
= A
->getValue();
3980 if (Inputs
.size() > 1 && !V
.empty() &&
3981 !llvm::sys::path::is_separator(V
.back())) {
3982 // Check whether /Fa tries to name an asm file for multiple inputs.
3983 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources
)
3984 << A
->getSpelling() << V
;
3985 Args
.eraseArg(options::OPT__SLASH_Fa
);
3989 // Diagnose misuse of /o.
3990 if (Arg
*A
= Args
.getLastArg(options::OPT__SLASH_o
)) {
3991 if (A
->getValue()[0] == '\0') {
3992 // It has to have a value.
3993 Diag(clang::diag::err_drv_missing_argument
) << A
->getSpelling() << 1;
3994 Args
.eraseArg(options::OPT__SLASH_o
);
3998 handleArguments(C
, Args
, Inputs
, Actions
);
4000 bool UseNewOffloadingDriver
=
4001 C
.isOffloadingHostKind(Action::OFK_OpenMP
) ||
4002 Args
.hasFlag(options::OPT_offload_new_driver
,
4003 options::OPT_no_offload_new_driver
, false);
4005 // Builder to be used to build offloading actions.
4006 std::unique_ptr
<OffloadingActionBuilder
> OffloadBuilder
=
4007 !UseNewOffloadingDriver
4008 ? std::make_unique
<OffloadingActionBuilder
>(C
, Args
, Inputs
)
4011 // Construct the actions to perform.
4012 ExtractAPIJobAction
*ExtractAPIAction
= nullptr;
4013 ActionList LinkerInputs
;
4014 ActionList MergerInputs
;
4016 for (auto &I
: Inputs
) {
4017 types::ID InputType
= I
.first
;
4018 const Arg
*InputArg
= I
.second
;
4020 auto PL
= types::getCompilationPhases(*this, Args
, InputType
);
4024 auto FullPL
= types::getCompilationPhases(InputType
);
4026 // Build the pipeline for this file.
4027 Action
*Current
= C
.MakeAction
<InputAction
>(*InputArg
, InputType
);
4029 // Use the current host action in any of the offloading actions, if
4031 if (!UseNewOffloadingDriver
)
4032 if (OffloadBuilder
->addHostDependenceToDeviceActions(Current
, InputArg
))
4035 for (phases::ID Phase
: PL
) {
4037 // Add any offload action the host action depends on.
4038 if (!UseNewOffloadingDriver
)
4039 Current
= OffloadBuilder
->addDeviceDependencesToHostAction(
4040 Current
, InputArg
, Phase
, PL
.back(), FullPL
);
4044 // Queue linker inputs.
4045 if (Phase
== phases::Link
) {
4046 assert(Phase
== PL
.back() && "linking must be final compilation step.");
4047 // We don't need to generate additional link commands if emitting AMD bitcode
4048 if (!(C
.getInputArgs().hasArg(options::OPT_hip_link
) &&
4049 (C
.getInputArgs().hasArg(options::OPT_emit_llvm
))))
4050 LinkerInputs
.push_back(Current
);
4055 // TODO: Consider removing this because the merged may not end up being
4056 // the final Phase in the pipeline. Perhaps the merged could just merge
4057 // and then pass an artifact of some sort to the Link Phase.
4058 // Queue merger inputs.
4059 if (Phase
== phases::IfsMerge
) {
4060 assert(Phase
== PL
.back() && "merging must be final compilation step.");
4061 MergerInputs
.push_back(Current
);
4066 if (Phase
== phases::Precompile
&& ExtractAPIAction
) {
4067 ExtractAPIAction
->addHeaderInput(Current
);
4072 // FIXME: Should we include any prior module file outputs as inputs of
4073 // later actions in the same command line?
4075 // Otherwise construct the appropriate action.
4076 Action
*NewCurrent
= ConstructPhaseAction(C
, Args
, Phase
, Current
);
4078 // We didn't create a new action, so we will just move to the next phase.
4079 if (NewCurrent
== Current
)
4082 if (auto *EAA
= dyn_cast
<ExtractAPIJobAction
>(NewCurrent
))
4083 ExtractAPIAction
= EAA
;
4085 Current
= NewCurrent
;
4087 // Use the current host action in any of the offloading actions, if
4089 if (!UseNewOffloadingDriver
)
4090 if (OffloadBuilder
->addHostDependenceToDeviceActions(Current
, InputArg
))
4093 // Try to build the offloading actions and add the result as a dependency
4095 if (UseNewOffloadingDriver
)
4096 Current
= BuildOffloadingActions(C
, Args
, I
, Current
);
4098 if (Current
->getType() == types::TY_Nothing
)
4102 // If we ended with something, add to the output list.
4104 Actions
.push_back(Current
);
4106 // Add any top level actions generated for offloading.
4107 if (!UseNewOffloadingDriver
)
4108 OffloadBuilder
->appendTopLevelActions(Actions
, Current
, InputArg
);
4110 Current
->propagateHostOffloadInfo(C
.getActiveOffloadKinds(),
4111 /*BoundArch=*/nullptr);
4114 // Add a link action if necessary.
4116 if (LinkerInputs
.empty()) {
4118 if (getFinalPhase(Args
, &FinalPhaseArg
) == phases::Link
)
4119 if (!UseNewOffloadingDriver
)
4120 OffloadBuilder
->appendDeviceLinkActions(Actions
);
4123 if (!LinkerInputs
.empty()) {
4124 if (!UseNewOffloadingDriver
)
4125 if (Action
*Wrapper
= OffloadBuilder
->makeHostLinkAction())
4126 LinkerInputs
.push_back(Wrapper
);
4128 // Check if this Linker Job should emit a static library.
4129 if (ShouldEmitStaticLibrary(Args
)) {
4130 LA
= C
.MakeAction
<StaticLibJobAction
>(LinkerInputs
, types::TY_Image
);
4131 } else if (UseNewOffloadingDriver
||
4132 Args
.hasArg(options::OPT_offload_link
)) {
4133 LA
= C
.MakeAction
<LinkerWrapperJobAction
>(LinkerInputs
, types::TY_Image
);
4134 LA
->propagateHostOffloadInfo(C
.getActiveOffloadKinds(),
4135 /*BoundArch=*/nullptr);
4137 LA
= C
.MakeAction
<LinkJobAction
>(LinkerInputs
, types::TY_Image
);
4139 if (!UseNewOffloadingDriver
)
4140 LA
= OffloadBuilder
->processHostLinkAction(LA
);
4141 Actions
.push_back(LA
);
4144 // Add an interface stubs merge action if necessary.
4145 if (!MergerInputs
.empty())
4147 C
.MakeAction
<IfsMergeJobAction
>(MergerInputs
, types::TY_Image
));
4149 if (Args
.hasArg(options::OPT_emit_interface_stubs
)) {
4150 auto PhaseList
= types::getCompilationPhases(
4152 Args
.hasArg(options::OPT_c
) ? phases::Compile
: phases::IfsMerge
);
4154 ActionList MergerInputs
;
4156 for (auto &I
: Inputs
) {
4157 types::ID InputType
= I
.first
;
4158 const Arg
*InputArg
= I
.second
;
4160 // Currently clang and the llvm assembler do not support generating symbol
4161 // stubs from assembly, so we skip the input on asm files. For ifs files
4162 // we rely on the normal pipeline setup in the pipeline setup code above.
4163 if (InputType
== types::TY_IFS
|| InputType
== types::TY_PP_Asm
||
4164 InputType
== types::TY_Asm
)
4167 Action
*Current
= C
.MakeAction
<InputAction
>(*InputArg
, InputType
);
4169 for (auto Phase
: PhaseList
) {
4173 "IFS Pipeline can only consist of Compile followed by IfsMerge.");
4174 case phases::Compile
: {
4175 // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs
4176 // files where the .o file is located. The compile action can not
4178 if (InputType
== types::TY_Object
)
4181 Current
= C
.MakeAction
<CompileJobAction
>(Current
, types::TY_IFS_CPP
);
4184 case phases::IfsMerge
: {
4185 assert(Phase
== PhaseList
.back() &&
4186 "merging must be final compilation step.");
4187 MergerInputs
.push_back(Current
);
4194 // If we ended with something, add to the output list.
4196 Actions
.push_back(Current
);
4199 // Add an interface stubs merge action if necessary.
4200 if (!MergerInputs
.empty())
4202 C
.MakeAction
<IfsMergeJobAction
>(MergerInputs
, types::TY_Image
));
4205 // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a custom
4206 // Compile phase that prints out supported cpu models and quits.
4207 if (Arg
*A
= Args
.getLastArg(options::OPT_print_supported_cpus
)) {
4208 // Use the -mcpu=? flag as the dummy input to cc1.
4210 Action
*InputAc
= C
.MakeAction
<InputAction
>(*A
, types::TY_C
);
4212 C
.MakeAction
<PrecompileJobAction
>(InputAc
, types::TY_Nothing
));
4213 for (auto &I
: Inputs
)
4217 // Call validator for dxil when -Vd not in Args.
4218 if (C
.getDefaultToolChain().getTriple().isDXIL()) {
4219 // Only add action when needValidation.
4221 static_cast<const toolchains::HLSLToolChain
&>(C
.getDefaultToolChain());
4222 if (TC
.requiresValidation(Args
)) {
4223 Action
*LastAction
= Actions
.back();
4224 Actions
.push_back(C
.MakeAction
<BinaryAnalyzeJobAction
>(
4225 LastAction
, types::TY_DX_CONTAINER
));
4229 // Claim ignored clang-cl options.
4230 Args
.ClaimAllArgs(options::OPT_cl_ignored_Group
);
4233 /// Returns the canonical name for the offloading architecture when using a HIP
4234 /// or CUDA architecture.
4235 static StringRef
getCanonicalArchString(Compilation
&C
,
4236 const llvm::opt::DerivedArgList
&Args
,
4238 const llvm::Triple
&Triple
,
4239 bool SuppressError
= false) {
4240 // Lookup the CUDA / HIP architecture string. Only report an error if we were
4241 // expecting the triple to be only NVPTX / AMDGPU.
4242 CudaArch Arch
= StringToCudaArch(getProcessorFromTargetID(Triple
, ArchStr
));
4243 if (!SuppressError
&& Triple
.isNVPTX() &&
4244 (Arch
== CudaArch::UNKNOWN
|| !IsNVIDIAGpuArch(Arch
))) {
4245 C
.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch
)
4246 << "CUDA" << ArchStr
;
4248 } else if (!SuppressError
&& Triple
.isAMDGPU() &&
4249 (Arch
== CudaArch::UNKNOWN
|| !IsAMDGpuArch(Arch
))) {
4250 C
.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch
)
4251 << "HIP" << ArchStr
;
4255 if (IsNVIDIAGpuArch(Arch
))
4256 return Args
.MakeArgStringRef(CudaArchToString(Arch
));
4258 if (IsAMDGpuArch(Arch
)) {
4259 llvm::StringMap
<bool> Features
;
4260 auto HIPTriple
= getHIPOffloadTargetTriple(C
.getDriver(), C
.getInputArgs());
4263 auto Arch
= parseTargetID(*HIPTriple
, ArchStr
, &Features
);
4265 C
.getDriver().Diag(clang::diag::err_drv_bad_target_id
) << ArchStr
;
4266 C
.setContainsError();
4269 return Args
.MakeArgStringRef(getCanonicalTargetID(*Arch
, Features
));
4272 // If the input isn't CUDA or HIP just return the architecture.
4276 /// Checks if the set offloading architectures does not conflict. Returns the
4277 /// incompatible pair if a conflict occurs.
4278 static std::optional
<std::pair
<llvm::StringRef
, llvm::StringRef
>>
4279 getConflictOffloadArchCombination(const llvm::DenseSet
<StringRef
> &Archs
,
4280 Action::OffloadKind Kind
) {
4281 if (Kind
!= Action::OFK_HIP
)
4282 return std::nullopt
;
4284 std::set
<StringRef
> ArchSet
;
4285 llvm::copy(Archs
, std::inserter(ArchSet
, ArchSet
.begin()));
4286 return getConflictTargetIDCombination(ArchSet
);
4289 llvm::DenseSet
<StringRef
>
4290 Driver::getOffloadArchs(Compilation
&C
, const llvm::opt::DerivedArgList
&Args
,
4291 Action::OffloadKind Kind
, const ToolChain
*TC
,
4292 bool SuppressError
) const {
4294 TC
= &C
.getDefaultToolChain();
4296 // --offload and --offload-arch options are mutually exclusive.
4297 if (Args
.hasArgNoClaim(options::OPT_offload_EQ
) &&
4298 Args
.hasArgNoClaim(options::OPT_offload_arch_EQ
,
4299 options::OPT_no_offload_arch_EQ
)) {
4300 C
.getDriver().Diag(diag::err_opt_not_valid_with_opt
)
4302 << (Args
.hasArgNoClaim(options::OPT_offload_arch_EQ
)
4304 : "--no-offload-arch");
4307 if (KnownArchs
.find(TC
) != KnownArchs
.end())
4308 return KnownArchs
.lookup(TC
);
4310 llvm::DenseSet
<StringRef
> Archs
;
4311 for (auto *Arg
: Args
) {
4312 // Extract any '--[no-]offload-arch' arguments intended for this toolchain.
4313 std::unique_ptr
<llvm::opt::Arg
> ExtractedArg
= nullptr;
4314 if (Arg
->getOption().matches(options::OPT_Xopenmp_target_EQ
) &&
4315 ToolChain::getOpenMPTriple(Arg
->getValue(0)) == TC
->getTriple()) {
4317 unsigned Index
= Args
.getBaseArgs().MakeIndex(Arg
->getValue(1));
4318 ExtractedArg
= getOpts().ParseOneArg(Args
, Index
);
4319 Arg
= ExtractedArg
.get();
4322 // Add or remove the seen architectures in order of appearance. If an
4323 // invalid architecture is given we simply exit.
4324 if (Arg
->getOption().matches(options::OPT_offload_arch_EQ
)) {
4325 for (StringRef Arch
: llvm::split(Arg
->getValue(), ",")) {
4326 if (Arch
== "native" || Arch
.empty()) {
4327 auto GPUsOrErr
= TC
->getSystemGPUArchs(Args
);
4330 llvm::consumeError(GPUsOrErr
.takeError());
4332 TC
->getDriver().Diag(diag::err_drv_undetermined_gpu_arch
)
4333 << llvm::Triple::getArchTypeName(TC
->getArch())
4334 << llvm::toString(GPUsOrErr
.takeError()) << "--offload-arch";
4338 for (auto ArchStr
: *GPUsOrErr
) {
4340 getCanonicalArchString(C
, Args
, Args
.MakeArgString(ArchStr
),
4341 TC
->getTriple(), SuppressError
));
4344 StringRef ArchStr
= getCanonicalArchString(
4345 C
, Args
, Arch
, TC
->getTriple(), SuppressError
);
4346 if (ArchStr
.empty())
4348 Archs
.insert(ArchStr
);
4351 } else if (Arg
->getOption().matches(options::OPT_no_offload_arch_EQ
)) {
4352 for (StringRef Arch
: llvm::split(Arg
->getValue(), ",")) {
4353 if (Arch
== "all") {
4356 StringRef ArchStr
= getCanonicalArchString(
4357 C
, Args
, Arch
, TC
->getTriple(), SuppressError
);
4358 if (ArchStr
.empty())
4360 Archs
.erase(ArchStr
);
4366 if (auto ConflictingArchs
= getConflictOffloadArchCombination(Archs
, Kind
)) {
4367 C
.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo
)
4368 << ConflictingArchs
->first
<< ConflictingArchs
->second
;
4369 C
.setContainsError();
4372 // Skip filling defaults if we're just querying what is availible.
4376 if (Archs
.empty()) {
4377 if (Kind
== Action::OFK_Cuda
)
4378 Archs
.insert(CudaArchToString(CudaArch::CudaDefault
));
4379 else if (Kind
== Action::OFK_HIP
)
4380 Archs
.insert(CudaArchToString(CudaArch::HIPDefault
));
4381 else if (Kind
== Action::OFK_OpenMP
)
4382 Archs
.insert(StringRef());
4384 Args
.ClaimAllArgs(options::OPT_offload_arch_EQ
);
4385 Args
.ClaimAllArgs(options::OPT_no_offload_arch_EQ
);
4391 Action
*Driver::BuildOffloadingActions(Compilation
&C
,
4392 llvm::opt::DerivedArgList
&Args
,
4393 const InputTy
&Input
,
4394 Action
*HostAction
) const {
4395 // Don't build offloading actions if explicitly disabled or we do not have a
4396 // valid source input and compile action to embed it in. If preprocessing only
4397 // ignore embedding.
4398 if (offloadHostOnly() || !types::isSrcFile(Input
.first
) ||
4399 !(isa
<CompileJobAction
>(HostAction
) ||
4400 getFinalPhase(Args
) == phases::Preprocess
))
4403 ActionList OffloadActions
;
4404 OffloadAction::DeviceDependences DDeps
;
4406 const Action::OffloadKind OffloadKinds
[] = {
4407 Action::OFK_OpenMP
, Action::OFK_Cuda
, Action::OFK_HIP
};
4409 for (Action::OffloadKind Kind
: OffloadKinds
) {
4410 SmallVector
<const ToolChain
*, 2> ToolChains
;
4411 ActionList DeviceActions
;
4413 auto TCRange
= C
.getOffloadToolChains(Kind
);
4414 for (auto TI
= TCRange
.first
, TE
= TCRange
.second
; TI
!= TE
; ++TI
)
4415 ToolChains
.push_back(TI
->second
);
4417 if (ToolChains
.empty())
4420 types::ID InputType
= Input
.first
;
4421 const Arg
*InputArg
= Input
.second
;
4423 // The toolchain can be active for unsupported file types.
4424 if ((Kind
== Action::OFK_Cuda
&& !types::isCuda(InputType
)) ||
4425 (Kind
== Action::OFK_HIP
&& !types::isHIP(InputType
)))
4428 // Get the product of all bound architectures and toolchains.
4429 SmallVector
<std::pair
<const ToolChain
*, StringRef
>> TCAndArchs
;
4430 for (const ToolChain
*TC
: ToolChains
)
4431 for (StringRef Arch
: getOffloadArchs(C
, Args
, Kind
, TC
))
4432 TCAndArchs
.push_back(std::make_pair(TC
, Arch
));
4434 for (unsigned I
= 0, E
= TCAndArchs
.size(); I
!= E
; ++I
)
4435 DeviceActions
.push_back(C
.MakeAction
<InputAction
>(*InputArg
, InputType
));
4437 if (DeviceActions
.empty())
4440 auto PL
= types::getCompilationPhases(*this, Args
, InputType
);
4442 for (phases::ID Phase
: PL
) {
4443 if (Phase
== phases::Link
) {
4444 assert(Phase
== PL
.back() && "linking must be final compilation step.");
4448 auto TCAndArch
= TCAndArchs
.begin();
4449 for (Action
*&A
: DeviceActions
) {
4450 if (A
->getType() == types::TY_Nothing
)
4453 // Propagate the ToolChain so we can use it in ConstructPhaseAction.
4454 A
->propagateDeviceOffloadInfo(Kind
, TCAndArch
->second
.data(),
4456 A
= ConstructPhaseAction(C
, Args
, Phase
, A
, Kind
);
4458 if (isa
<CompileJobAction
>(A
) && isa
<CompileJobAction
>(HostAction
) &&
4459 Kind
== Action::OFK_OpenMP
&&
4460 HostAction
->getType() != types::TY_Nothing
) {
4461 // OpenMP offloading has a dependency on the host compile action to
4462 // identify which declarations need to be emitted. This shouldn't be
4463 // collapsed with any other actions so we can use it in the device.
4464 HostAction
->setCannotBeCollapsedWithNextDependentAction();
4465 OffloadAction::HostDependence
HDep(
4466 *HostAction
, *C
.getSingleOffloadToolChain
<Action::OFK_Host
>(),
4467 TCAndArch
->second
.data(), Kind
);
4468 OffloadAction::DeviceDependences DDep
;
4469 DDep
.add(*A
, *TCAndArch
->first
, TCAndArch
->second
.data(), Kind
);
4470 A
= C
.MakeAction
<OffloadAction
>(HDep
, DDep
);
4477 // Compiling HIP in non-RDC mode requires linking each action individually.
4478 for (Action
*&A
: DeviceActions
) {
4479 if ((A
->getType() != types::TY_Object
&&
4480 A
->getType() != types::TY_LTO_BC
) ||
4481 Kind
!= Action::OFK_HIP
||
4482 Args
.hasFlag(options::OPT_fgpu_rdc
, options::OPT_fno_gpu_rdc
, false))
4484 ActionList LinkerInput
= {A
};
4485 A
= C
.MakeAction
<LinkJobAction
>(LinkerInput
, types::TY_Image
);
4488 auto TCAndArch
= TCAndArchs
.begin();
4489 for (Action
*A
: DeviceActions
) {
4490 DDeps
.add(*A
, *TCAndArch
->first
, TCAndArch
->second
.data(), Kind
);
4491 OffloadAction::DeviceDependences DDep
;
4492 DDep
.add(*A
, *TCAndArch
->first
, TCAndArch
->second
.data(), Kind
);
4493 OffloadActions
.push_back(C
.MakeAction
<OffloadAction
>(DDep
, A
->getType()));
4498 if (offloadDeviceOnly())
4499 return C
.MakeAction
<OffloadAction
>(DDeps
, types::TY_Nothing
);
4501 if (OffloadActions
.empty())
4504 OffloadAction::DeviceDependences DDep
;
4505 if (C
.isOffloadingHostKind(Action::OFK_Cuda
) &&
4506 !Args
.hasFlag(options::OPT_fgpu_rdc
, options::OPT_fno_gpu_rdc
, false)) {
4507 // If we are not in RDC-mode we just emit the final CUDA fatbinary for
4508 // each translation unit without requiring any linking.
4509 Action
*FatbinAction
=
4510 C
.MakeAction
<LinkJobAction
>(OffloadActions
, types::TY_CUDA_FATBIN
);
4511 DDep
.add(*FatbinAction
, *C
.getSingleOffloadToolChain
<Action::OFK_Cuda
>(),
4512 nullptr, Action::OFK_Cuda
);
4513 } else if (C
.isOffloadingHostKind(Action::OFK_HIP
) &&
4514 !Args
.hasFlag(options::OPT_fgpu_rdc
, options::OPT_fno_gpu_rdc
,
4516 // If we are not in RDC-mode we just emit the final HIP fatbinary for each
4517 // translation unit, linking each input individually.
4518 Action
*FatbinAction
=
4519 C
.MakeAction
<LinkJobAction
>(OffloadActions
, types::TY_HIP_FATBIN
);
4520 DDep
.add(*FatbinAction
, *C
.getSingleOffloadToolChain
<Action::OFK_HIP
>(),
4521 nullptr, Action::OFK_HIP
);
4523 // Package all the offloading actions into a single output that can be
4524 // embedded in the host and linked.
4525 Action
*PackagerAction
=
4526 C
.MakeAction
<OffloadPackagerJobAction
>(OffloadActions
, types::TY_Image
);
4527 DDep
.add(*PackagerAction
, *C
.getSingleOffloadToolChain
<Action::OFK_Host
>(),
4528 nullptr, C
.getActiveOffloadKinds());
4531 // If we are unable to embed a single device output into the host, we need to
4532 // add each device output as a host dependency to ensure they are still built.
4533 bool SingleDeviceOutput
= !llvm::any_of(OffloadActions
, [](Action
*A
) {
4534 return A
->getType() == types::TY_Nothing
;
4535 }) && isa
<CompileJobAction
>(HostAction
);
4536 OffloadAction::HostDependence
HDep(
4537 *HostAction
, *C
.getSingleOffloadToolChain
<Action::OFK_Host
>(),
4538 /*BoundArch=*/nullptr, SingleDeviceOutput
? DDep
: DDeps
);
4539 return C
.MakeAction
<OffloadAction
>(HDep
, SingleDeviceOutput
? DDep
: DDeps
);
4542 Action
*Driver::ConstructPhaseAction(
4543 Compilation
&C
, const ArgList
&Args
, phases::ID Phase
, Action
*Input
,
4544 Action::OffloadKind TargetDeviceOffloadKind
) const {
4545 llvm::PrettyStackTraceString
CrashInfo("Constructing phase actions");
4547 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
4548 // encode this in the steps because the intermediate type depends on
4549 // arguments. Just special case here.
4550 if (Phase
== phases::Assemble
&& Input
->getType() != types::TY_PP_Asm
)
4553 // Build the appropriate action.
4556 llvm_unreachable("link action invalid here.");
4557 case phases::IfsMerge
:
4558 llvm_unreachable("ifsmerge action invalid here.");
4559 case phases::Preprocess
: {
4561 // -M and -MM specify the dependency file name by altering the output type,
4562 // -if -MD and -MMD are not specified.
4563 if (Args
.hasArg(options::OPT_M
, options::OPT_MM
) &&
4564 !Args
.hasArg(options::OPT_MD
, options::OPT_MMD
)) {
4565 OutputTy
= types::TY_Dependencies
;
4567 OutputTy
= Input
->getType();
4568 // For these cases, the preprocessor is only translating forms, the Output
4569 // still needs preprocessing.
4570 if (!Args
.hasFlag(options::OPT_frewrite_includes
,
4571 options::OPT_fno_rewrite_includes
, false) &&
4572 !Args
.hasFlag(options::OPT_frewrite_imports
,
4573 options::OPT_fno_rewrite_imports
, false) &&
4574 !Args
.hasFlag(options::OPT_fdirectives_only
,
4575 options::OPT_fno_directives_only
, false) &&
4577 OutputTy
= types::getPreprocessedType(OutputTy
);
4578 assert(OutputTy
!= types::TY_INVALID
&&
4579 "Cannot preprocess this input type!");
4581 return C
.MakeAction
<PreprocessJobAction
>(Input
, OutputTy
);
4583 case phases::Precompile
: {
4584 // API extraction should not generate an actual precompilation action.
4585 if (Args
.hasArg(options::OPT_extract_api
))
4586 return C
.MakeAction
<ExtractAPIJobAction
>(Input
, types::TY_API_INFO
);
4588 types::ID OutputTy
= getPrecompiledType(Input
->getType());
4589 assert(OutputTy
!= types::TY_INVALID
&&
4590 "Cannot precompile this input type!");
4592 // If we're given a module name, precompile header file inputs as a
4593 // module, not as a precompiled header.
4594 const char *ModName
= nullptr;
4595 if (OutputTy
== types::TY_PCH
) {
4596 if (Arg
*A
= Args
.getLastArg(options::OPT_fmodule_name_EQ
))
4597 ModName
= A
->getValue();
4599 OutputTy
= types::TY_ModuleFile
;
4602 if (Args
.hasArg(options::OPT_fsyntax_only
)) {
4603 // Syntax checks should not emit a PCH file
4604 OutputTy
= types::TY_Nothing
;
4607 return C
.MakeAction
<PrecompileJobAction
>(Input
, OutputTy
);
4609 case phases::Compile
: {
4610 if (Args
.hasArg(options::OPT_fsyntax_only
))
4611 return C
.MakeAction
<CompileJobAction
>(Input
, types::TY_Nothing
);
4612 if (Args
.hasArg(options::OPT_rewrite_objc
))
4613 return C
.MakeAction
<CompileJobAction
>(Input
, types::TY_RewrittenObjC
);
4614 if (Args
.hasArg(options::OPT_rewrite_legacy_objc
))
4615 return C
.MakeAction
<CompileJobAction
>(Input
,
4616 types::TY_RewrittenLegacyObjC
);
4617 if (Args
.hasArg(options::OPT__analyze
))
4618 return C
.MakeAction
<AnalyzeJobAction
>(Input
, types::TY_Plist
);
4619 if (Args
.hasArg(options::OPT__migrate
))
4620 return C
.MakeAction
<MigrateJobAction
>(Input
, types::TY_Remap
);
4621 if (Args
.hasArg(options::OPT_emit_ast
))
4622 return C
.MakeAction
<CompileJobAction
>(Input
, types::TY_AST
);
4623 if (Args
.hasArg(options::OPT_module_file_info
))
4624 return C
.MakeAction
<CompileJobAction
>(Input
, types::TY_ModuleFile
);
4625 if (Args
.hasArg(options::OPT_verify_pch
))
4626 return C
.MakeAction
<VerifyPCHJobAction
>(Input
, types::TY_Nothing
);
4627 if (Args
.hasArg(options::OPT_extract_api
))
4628 return C
.MakeAction
<ExtractAPIJobAction
>(Input
, types::TY_API_INFO
);
4629 return C
.MakeAction
<CompileJobAction
>(Input
, types::TY_LLVM_BC
);
4631 case phases::Backend
: {
4632 if (isUsingLTO() && TargetDeviceOffloadKind
== Action::OFK_None
) {
4634 Args
.hasArg(options::OPT_S
) ? types::TY_LTO_IR
: types::TY_LTO_BC
;
4635 return C
.MakeAction
<BackendJobAction
>(Input
, Output
);
4637 if (isUsingLTO(/* IsOffload */ true) &&
4638 TargetDeviceOffloadKind
!= Action::OFK_None
) {
4640 Args
.hasArg(options::OPT_S
) ? types::TY_LTO_IR
: types::TY_LTO_BC
;
4641 return C
.MakeAction
<BackendJobAction
>(Input
, Output
);
4643 if (Args
.hasArg(options::OPT_emit_llvm
) ||
4644 (((Input
->getOffloadingToolChain() &&
4645 Input
->getOffloadingToolChain()->getTriple().isAMDGPU()) ||
4646 TargetDeviceOffloadKind
== Action::OFK_HIP
) &&
4647 (Args
.hasFlag(options::OPT_fgpu_rdc
, options::OPT_fno_gpu_rdc
,
4649 TargetDeviceOffloadKind
== Action::OFK_OpenMP
))) {
4651 Args
.hasArg(options::OPT_S
) &&
4652 (TargetDeviceOffloadKind
== Action::OFK_None
||
4653 offloadDeviceOnly() ||
4654 (TargetDeviceOffloadKind
== Action::OFK_HIP
&&
4655 !Args
.hasFlag(options::OPT_offload_new_driver
,
4656 options::OPT_no_offload_new_driver
, false)))
4658 : types::TY_LLVM_BC
;
4659 return C
.MakeAction
<BackendJobAction
>(Input
, Output
);
4661 return C
.MakeAction
<BackendJobAction
>(Input
, types::TY_PP_Asm
);
4663 case phases::Assemble
:
4664 return C
.MakeAction
<AssembleJobAction
>(std::move(Input
), types::TY_Object
);
4667 llvm_unreachable("invalid phase in ConstructPhaseAction");
4670 void Driver::BuildJobs(Compilation
&C
) const {
4671 llvm::PrettyStackTraceString
CrashInfo("Building compilation jobs");
4673 Arg
*FinalOutput
= C
.getArgs().getLastArg(options::OPT_o
);
4675 // It is an error to provide a -o option if we are making multiple output
4676 // files. There are exceptions:
4678 // IfsMergeJob: when generating interface stubs enabled we want to be able to
4679 // generate the stub file at the same time that we generate the real
4680 // library/a.out. So when a .o, .so, etc are the output, with clang interface
4681 // stubs there will also be a .ifs and .ifso at the same location.
4683 // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled
4684 // and -c is passed, we still want to be able to generate a .ifs file while
4685 // we are also generating .o files. So we allow more than one output file in
4686 // this case as well.
4688 // OffloadClass of type TY_Nothing: device-only output will place many outputs
4689 // into a single offloading action. We should count all inputs to the action
4690 // as outputs. Also ignore device-only outputs if we're compiling with
4693 unsigned NumOutputs
= 0;
4694 unsigned NumIfsOutputs
= 0;
4695 for (const Action
*A
: C
.getActions()) {
4696 if (A
->getType() != types::TY_Nothing
&&
4697 A
->getType() != types::TY_DX_CONTAINER
&&
4698 !(A
->getKind() == Action::IfsMergeJobClass
||
4699 (A
->getType() == clang::driver::types::TY_IFS_CPP
&&
4700 A
->getKind() == clang::driver::Action::CompileJobClass
&&
4701 0 == NumIfsOutputs
++) ||
4702 (A
->getKind() == Action::BindArchClass
&& A
->getInputs().size() &&
4703 A
->getInputs().front()->getKind() == Action::IfsMergeJobClass
)))
4705 else if (A
->getKind() == Action::OffloadClass
&&
4706 A
->getType() == types::TY_Nothing
&&
4707 !C
.getArgs().hasArg(options::OPT_fsyntax_only
))
4708 NumOutputs
+= A
->size();
4711 if (NumOutputs
> 1) {
4712 Diag(clang::diag::err_drv_output_argument_with_multiple_files
);
4713 FinalOutput
= nullptr;
4717 const llvm::Triple
&RawTriple
= C
.getDefaultToolChain().getTriple();
4718 if (RawTriple
.isOSAIX()) {
4719 if (Arg
*A
= C
.getArgs().getLastArg(options::OPT_G
))
4720 Diag(diag::err_drv_unsupported_opt_for_target
)
4721 << A
->getSpelling() << RawTriple
.str();
4722 if (LTOMode
== LTOK_Thin
)
4723 Diag(diag::err_drv_clang_unsupported
) << "thinLTO on AIX";
4726 // Collect the list of architectures.
4727 llvm::StringSet
<> ArchNames
;
4728 if (RawTriple
.isOSBinFormatMachO())
4729 for (const Arg
*A
: C
.getArgs())
4730 if (A
->getOption().matches(options::OPT_arch
))
4731 ArchNames
.insert(A
->getValue());
4733 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
4734 std::map
<std::pair
<const Action
*, std::string
>, InputInfoList
> CachedResults
;
4735 for (Action
*A
: C
.getActions()) {
4736 // If we are linking an image for multiple archs then the linker wants
4737 // -arch_multiple and -final_output <final image name>. Unfortunately, this
4738 // doesn't fit in cleanly because we have to pass this information down.
4740 // FIXME: This is a hack; find a cleaner way to integrate this into the
4742 const char *LinkingOutput
= nullptr;
4743 if (isa
<LipoJobAction
>(A
)) {
4745 LinkingOutput
= FinalOutput
->getValue();
4747 LinkingOutput
= getDefaultImageName();
4750 BuildJobsForAction(C
, A
, &C
.getDefaultToolChain(),
4751 /*BoundArch*/ StringRef(),
4752 /*AtTopLevel*/ true,
4753 /*MultipleArchs*/ ArchNames
.size() > 1,
4754 /*LinkingOutput*/ LinkingOutput
, CachedResults
,
4755 /*TargetDeviceOffloadKind*/ Action::OFK_None
);
4758 // If we have more than one job, then disable integrated-cc1 for now. Do this
4759 // also when we need to report process execution statistics.
4760 if (C
.getJobs().size() > 1 || CCPrintProcessStats
)
4761 for (auto &J
: C
.getJobs())
4762 J
.InProcess
= false;
4764 if (CCPrintProcessStats
) {
4765 C
.setPostCallback([=](const Command
&Cmd
, int Res
) {
4766 std::optional
<llvm::sys::ProcessStatistics
> ProcStat
=
4767 Cmd
.getProcessStatistics();
4771 const char *LinkingOutput
= nullptr;
4773 LinkingOutput
= FinalOutput
->getValue();
4774 else if (!Cmd
.getOutputFilenames().empty())
4775 LinkingOutput
= Cmd
.getOutputFilenames().front().c_str();
4777 LinkingOutput
= getDefaultImageName();
4779 if (CCPrintStatReportFilename
.empty()) {
4780 using namespace llvm
;
4781 // Human readable output.
4782 outs() << sys::path::filename(Cmd
.getExecutable()) << ": "
4783 << "output=" << LinkingOutput
;
4784 outs() << ", total="
4785 << format("%.3f", ProcStat
->TotalTime
.count() / 1000.) << " ms"
4787 << format("%.3f", ProcStat
->UserTime
.count() / 1000.) << " ms"
4788 << ", mem=" << ProcStat
->PeakMemory
<< " Kb\n";
4792 llvm::raw_string_ostream
Out(Buffer
);
4793 llvm::sys::printArg(Out
, llvm::sys::path::filename(Cmd
.getExecutable()),
4796 llvm::sys::printArg(Out
, LinkingOutput
, true);
4797 Out
<< ',' << ProcStat
->TotalTime
.count() << ','
4798 << ProcStat
->UserTime
.count() << ',' << ProcStat
->PeakMemory
4802 llvm::raw_fd_ostream
OS(CCPrintStatReportFilename
, EC
,
4803 llvm::sys::fs::OF_Append
|
4804 llvm::sys::fs::OF_Text
);
4809 llvm::errs() << "ERROR: Cannot lock file "
4810 << CCPrintStatReportFilename
<< ": "
4811 << toString(L
.takeError()) << "\n";
4820 // If the user passed -Qunused-arguments or there were errors, don't warn
4821 // about any unused arguments.
4822 if (Diags
.hasErrorOccurred() ||
4823 C
.getArgs().hasArg(options::OPT_Qunused_arguments
))
4826 // Claim -fdriver-only here.
4827 (void)C
.getArgs().hasArg(options::OPT_fdriver_only
);
4829 (void)C
.getArgs().hasArg(options::OPT__HASH_HASH_HASH
);
4831 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
4832 (void)C
.getArgs().hasArg(options::OPT_driver_mode
);
4833 (void)C
.getArgs().hasArg(options::OPT_rsp_quoting
);
4835 for (Arg
*A
: C
.getArgs()) {
4836 // FIXME: It would be nice to be able to send the argument to the
4837 // DiagnosticsEngine, so that extra values, position, and so on could be
4839 if (!A
->isClaimed()) {
4840 if (A
->getOption().hasFlag(options::NoArgumentUnused
))
4843 // Suppress the warning automatically if this is just a flag, and it is an
4844 // instance of an argument we already claimed.
4845 const Option
&Opt
= A
->getOption();
4846 if (Opt
.getKind() == Option::FlagClass
) {
4847 bool DuplicateClaimed
= false;
4849 for (const Arg
*AA
: C
.getArgs().filtered(&Opt
)) {
4850 if (AA
->isClaimed()) {
4851 DuplicateClaimed
= true;
4856 if (DuplicateClaimed
)
4860 // In clang-cl, don't mention unknown arguments here since they have
4861 // already been warned about.
4862 if (!IsCLMode() || !A
->getOption().matches(options::OPT_UNKNOWN
))
4863 Diag(clang::diag::warn_drv_unused_argument
)
4864 << A
->getAsString(C
.getArgs());
4870 /// Utility class to control the collapse of dependent actions and select the
4871 /// tools accordingly.
4872 class ToolSelector final
{
4873 /// The tool chain this selector refers to.
4874 const ToolChain
&TC
;
4876 /// The compilation this selector refers to.
4877 const Compilation
&C
;
4879 /// The base action this selector refers to.
4880 const JobAction
*BaseAction
;
4882 /// Set to true if the current toolchain refers to host actions.
4883 bool IsHostSelector
;
4885 /// Set to true if save-temps and embed-bitcode functionalities are active.
4889 /// Get previous dependent action or null if that does not exist. If
4890 /// \a CanBeCollapsed is false, that action must be legal to collapse or
4891 /// null will be returned.
4892 const JobAction
*getPrevDependentAction(const ActionList
&Inputs
,
4893 ActionList
&SavedOffloadAction
,
4894 bool CanBeCollapsed
= true) {
4895 // An option can be collapsed only if it has a single input.
4896 if (Inputs
.size() != 1)
4899 Action
*CurAction
= *Inputs
.begin();
4900 if (CanBeCollapsed
&&
4901 !CurAction
->isCollapsingWithNextDependentActionLegal())
4904 // If the input action is an offload action. Look through it and save any
4905 // offload action that can be dropped in the event of a collapse.
4906 if (auto *OA
= dyn_cast
<OffloadAction
>(CurAction
)) {
4907 // If the dependent action is a device action, we will attempt to collapse
4908 // only with other device actions. Otherwise, we would do the same but
4909 // with host actions only.
4910 if (!IsHostSelector
) {
4911 if (OA
->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
4913 OA
->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
4914 if (CanBeCollapsed
&&
4915 !CurAction
->isCollapsingWithNextDependentActionLegal())
4917 SavedOffloadAction
.push_back(OA
);
4918 return dyn_cast
<JobAction
>(CurAction
);
4920 } else if (OA
->hasHostDependence()) {
4921 CurAction
= OA
->getHostDependence();
4922 if (CanBeCollapsed
&&
4923 !CurAction
->isCollapsingWithNextDependentActionLegal())
4925 SavedOffloadAction
.push_back(OA
);
4926 return dyn_cast
<JobAction
>(CurAction
);
4931 return dyn_cast
<JobAction
>(CurAction
);
4934 /// Return true if an assemble action can be collapsed.
4935 bool canCollapseAssembleAction() const {
4936 return TC
.useIntegratedAs() && !SaveTemps
&&
4937 !C
.getArgs().hasArg(options::OPT_via_file_asm
) &&
4938 !C
.getArgs().hasArg(options::OPT__SLASH_FA
) &&
4939 !C
.getArgs().hasArg(options::OPT__SLASH_Fa
);
4942 /// Return true if a preprocessor action can be collapsed.
4943 bool canCollapsePreprocessorAction() const {
4944 return !C
.getArgs().hasArg(options::OPT_no_integrated_cpp
) &&
4945 !C
.getArgs().hasArg(options::OPT_traditional_cpp
) && !SaveTemps
&&
4946 !C
.getArgs().hasArg(options::OPT_rewrite_objc
);
4949 /// Struct that relates an action with the offload actions that would be
4950 /// collapsed with it.
4951 struct JobActionInfo final
{
4952 /// The action this info refers to.
4953 const JobAction
*JA
= nullptr;
4954 /// The offload actions we need to take care off if this action is
4956 ActionList SavedOffloadAction
;
4959 /// Append collapsed offload actions from the give nnumber of elements in the
4960 /// action info array.
4961 static void AppendCollapsedOffloadAction(ActionList
&CollapsedOffloadAction
,
4962 ArrayRef
<JobActionInfo
> &ActionInfo
,
4963 unsigned ElementNum
) {
4964 assert(ElementNum
<= ActionInfo
.size() && "Invalid number of elements.");
4965 for (unsigned I
= 0; I
< ElementNum
; ++I
)
4966 CollapsedOffloadAction
.append(ActionInfo
[I
].SavedOffloadAction
.begin(),
4967 ActionInfo
[I
].SavedOffloadAction
.end());
4970 /// Functions that attempt to perform the combining. They detect if that is
4971 /// legal, and if so they update the inputs \a Inputs and the offload action
4972 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
4973 /// the combined action is returned. If the combining is not legal or if the
4974 /// tool does not exist, null is returned.
4975 /// Currently three kinds of collapsing are supported:
4976 /// - Assemble + Backend + Compile;
4977 /// - Assemble + Backend ;
4978 /// - Backend + Compile.
4980 combineAssembleBackendCompile(ArrayRef
<JobActionInfo
> ActionInfo
,
4982 ActionList
&CollapsedOffloadAction
) {
4983 if (ActionInfo
.size() < 3 || !canCollapseAssembleAction())
4985 auto *AJ
= dyn_cast
<AssembleJobAction
>(ActionInfo
[0].JA
);
4986 auto *BJ
= dyn_cast
<BackendJobAction
>(ActionInfo
[1].JA
);
4987 auto *CJ
= dyn_cast
<CompileJobAction
>(ActionInfo
[2].JA
);
4988 if (!AJ
|| !BJ
|| !CJ
)
4991 // Get compiler tool.
4992 const Tool
*T
= TC
.SelectTool(*CJ
);
4996 // Can't collapse if we don't have codegen support unless we are
4997 // emitting LLVM IR.
4998 bool OutputIsLLVM
= types::isLLVMIR(ActionInfo
[0].JA
->getType());
4999 if (!T
->hasIntegratedBackend() && !(OutputIsLLVM
&& T
->canEmitIR()))
5002 // When using -fembed-bitcode, it is required to have the same tool (clang)
5003 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
5005 const Tool
*BT
= TC
.SelectTool(*BJ
);
5010 if (!T
->hasIntegratedAssembler())
5013 Inputs
= CJ
->getInputs();
5014 AppendCollapsedOffloadAction(CollapsedOffloadAction
, ActionInfo
,
5018 const Tool
*combineAssembleBackend(ArrayRef
<JobActionInfo
> ActionInfo
,
5020 ActionList
&CollapsedOffloadAction
) {
5021 if (ActionInfo
.size() < 2 || !canCollapseAssembleAction())
5023 auto *AJ
= dyn_cast
<AssembleJobAction
>(ActionInfo
[0].JA
);
5024 auto *BJ
= dyn_cast
<BackendJobAction
>(ActionInfo
[1].JA
);
5028 // Get backend tool.
5029 const Tool
*T
= TC
.SelectTool(*BJ
);
5033 if (!T
->hasIntegratedAssembler())
5036 Inputs
= BJ
->getInputs();
5037 AppendCollapsedOffloadAction(CollapsedOffloadAction
, ActionInfo
,
5041 const Tool
*combineBackendCompile(ArrayRef
<JobActionInfo
> ActionInfo
,
5043 ActionList
&CollapsedOffloadAction
) {
5044 if (ActionInfo
.size() < 2)
5046 auto *BJ
= dyn_cast
<BackendJobAction
>(ActionInfo
[0].JA
);
5047 auto *CJ
= dyn_cast
<CompileJobAction
>(ActionInfo
[1].JA
);
5051 // Check if the initial input (to the compile job or its predessor if one
5052 // exists) is LLVM bitcode. In that case, no preprocessor step is required
5053 // and we can still collapse the compile and backend jobs when we have
5054 // -save-temps. I.e. there is no need for a separate compile job just to
5055 // emit unoptimized bitcode.
5056 bool InputIsBitcode
= true;
5057 for (size_t i
= 1; i
< ActionInfo
.size(); i
++)
5058 if (ActionInfo
[i
].JA
->getType() != types::TY_LLVM_BC
&&
5059 ActionInfo
[i
].JA
->getType() != types::TY_LTO_BC
) {
5060 InputIsBitcode
= false;
5063 if (!InputIsBitcode
&& !canCollapsePreprocessorAction())
5066 // Get compiler tool.
5067 const Tool
*T
= TC
.SelectTool(*CJ
);
5071 // Can't collapse if we don't have codegen support unless we are
5072 // emitting LLVM IR.
5073 bool OutputIsLLVM
= types::isLLVMIR(ActionInfo
[0].JA
->getType());
5074 if (!T
->hasIntegratedBackend() && !(OutputIsLLVM
&& T
->canEmitIR()))
5077 if (T
->canEmitIR() && ((SaveTemps
&& !InputIsBitcode
) || EmbedBitcode
))
5080 Inputs
= CJ
->getInputs();
5081 AppendCollapsedOffloadAction(CollapsedOffloadAction
, ActionInfo
,
5086 /// Updates the inputs if the obtained tool supports combining with
5087 /// preprocessor action, and the current input is indeed a preprocessor
5088 /// action. If combining results in the collapse of offloading actions, those
5089 /// are appended to \a CollapsedOffloadAction.
5090 void combineWithPreprocessor(const Tool
*T
, ActionList
&Inputs
,
5091 ActionList
&CollapsedOffloadAction
) {
5092 if (!T
|| !canCollapsePreprocessorAction() || !T
->hasIntegratedCPP())
5095 // Attempt to get a preprocessor action dependence.
5096 ActionList PreprocessJobOffloadActions
;
5097 ActionList NewInputs
;
5098 for (Action
*A
: Inputs
) {
5099 auto *PJ
= getPrevDependentAction({A
}, PreprocessJobOffloadActions
);
5100 if (!PJ
|| !isa
<PreprocessJobAction
>(PJ
)) {
5101 NewInputs
.push_back(A
);
5105 // This is legal to combine. Append any offload action we found and add the
5106 // current input to preprocessor inputs.
5107 CollapsedOffloadAction
.append(PreprocessJobOffloadActions
.begin(),
5108 PreprocessJobOffloadActions
.end());
5109 NewInputs
.append(PJ
->input_begin(), PJ
->input_end());
5115 ToolSelector(const JobAction
*BaseAction
, const ToolChain
&TC
,
5116 const Compilation
&C
, bool SaveTemps
, bool EmbedBitcode
)
5117 : TC(TC
), C(C
), BaseAction(BaseAction
), SaveTemps(SaveTemps
),
5118 EmbedBitcode(EmbedBitcode
) {
5119 assert(BaseAction
&& "Invalid base action.");
5120 IsHostSelector
= BaseAction
->getOffloadingDeviceKind() == Action::OFK_None
;
5123 /// Check if a chain of actions can be combined and return the tool that can
5124 /// handle the combination of actions. The pointer to the current inputs \a
5125 /// Inputs and the list of offload actions \a CollapsedOffloadActions
5126 /// connected to collapsed actions are updated accordingly. The latter enables
5127 /// the caller of the selector to process them afterwards instead of just
5128 /// dropping them. If no suitable tool is found, null will be returned.
5129 const Tool
*getTool(ActionList
&Inputs
,
5130 ActionList
&CollapsedOffloadAction
) {
5132 // Get the largest chain of actions that we could combine.
5135 SmallVector
<JobActionInfo
, 5> ActionChain(1);
5136 ActionChain
.back().JA
= BaseAction
;
5137 while (ActionChain
.back().JA
) {
5138 const Action
*CurAction
= ActionChain
.back().JA
;
5140 // Grow the chain by one element.
5141 ActionChain
.resize(ActionChain
.size() + 1);
5142 JobActionInfo
&AI
= ActionChain
.back();
5144 // Attempt to fill it with the
5146 getPrevDependentAction(CurAction
->getInputs(), AI
.SavedOffloadAction
);
5149 // Pop the last action info as it could not be filled.
5150 ActionChain
.pop_back();
5153 // Attempt to combine actions. If all combining attempts failed, just return
5154 // the tool of the provided action. At the end we attempt to combine the
5155 // action with any preprocessor action it may depend on.
5158 const Tool
*T
= combineAssembleBackendCompile(ActionChain
, Inputs
,
5159 CollapsedOffloadAction
);
5161 T
= combineAssembleBackend(ActionChain
, Inputs
, CollapsedOffloadAction
);
5163 T
= combineBackendCompile(ActionChain
, Inputs
, CollapsedOffloadAction
);
5165 Inputs
= BaseAction
->getInputs();
5166 T
= TC
.SelectTool(*BaseAction
);
5169 combineWithPreprocessor(T
, Inputs
, CollapsedOffloadAction
);
5175 /// Return a string that uniquely identifies the result of a job. The bound arch
5176 /// is not necessarily represented in the toolchain's triple -- for example,
5177 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
5178 /// Also, we need to add the offloading device kind, as the same tool chain can
5179 /// be used for host and device for some programming models, e.g. OpenMP.
5180 static std::string
GetTriplePlusArchString(const ToolChain
*TC
,
5181 StringRef BoundArch
,
5182 Action::OffloadKind OffloadKind
) {
5183 std::string TriplePlusArch
= TC
->getTriple().normalize();
5184 if (!BoundArch
.empty()) {
5185 TriplePlusArch
+= "-";
5186 TriplePlusArch
+= BoundArch
;
5188 TriplePlusArch
+= "-";
5189 TriplePlusArch
+= Action::GetOffloadKindName(OffloadKind
);
5190 return TriplePlusArch
;
5193 InputInfoList
Driver::BuildJobsForAction(
5194 Compilation
&C
, const Action
*A
, const ToolChain
*TC
, StringRef BoundArch
,
5195 bool AtTopLevel
, bool MultipleArchs
, const char *LinkingOutput
,
5196 std::map
<std::pair
<const Action
*, std::string
>, InputInfoList
>
5198 Action::OffloadKind TargetDeviceOffloadKind
) const {
5199 std::pair
<const Action
*, std::string
> ActionTC
= {
5200 A
, GetTriplePlusArchString(TC
, BoundArch
, TargetDeviceOffloadKind
)};
5201 auto CachedResult
= CachedResults
.find(ActionTC
);
5202 if (CachedResult
!= CachedResults
.end()) {
5203 return CachedResult
->second
;
5205 InputInfoList Result
= BuildJobsForActionNoCache(
5206 C
, A
, TC
, BoundArch
, AtTopLevel
, MultipleArchs
, LinkingOutput
,
5207 CachedResults
, TargetDeviceOffloadKind
);
5208 CachedResults
[ActionTC
] = Result
;
5212 InputInfoList
Driver::BuildJobsForActionNoCache(
5213 Compilation
&C
, const Action
*A
, const ToolChain
*TC
, StringRef BoundArch
,
5214 bool AtTopLevel
, bool MultipleArchs
, const char *LinkingOutput
,
5215 std::map
<std::pair
<const Action
*, std::string
>, InputInfoList
>
5217 Action::OffloadKind TargetDeviceOffloadKind
) const {
5218 llvm::PrettyStackTraceString
CrashInfo("Building compilation jobs");
5220 InputInfoList OffloadDependencesInputInfo
;
5221 bool BuildingForOffloadDevice
= TargetDeviceOffloadKind
!= Action::OFK_None
;
5222 if (const OffloadAction
*OA
= dyn_cast
<OffloadAction
>(A
)) {
5223 // The 'Darwin' toolchain is initialized only when its arguments are
5224 // computed. Get the default arguments for OFK_None to ensure that
5225 // initialization is performed before processing the offload action.
5226 // FIXME: Remove when darwin's toolchain is initialized during construction.
5227 C
.getArgsForToolChain(TC
, BoundArch
, Action::OFK_None
);
5229 // The offload action is expected to be used in four different situations.
5231 // a) Set a toolchain/architecture/kind for a host action:
5232 // Host Action 1 -> OffloadAction -> Host Action 2
5234 // b) Set a toolchain/architecture/kind for a device action;
5235 // Device Action 1 -> OffloadAction -> Device Action 2
5237 // c) Specify a device dependence to a host action;
5238 // Device Action 1 _
5240 // Host Action 1 ---> OffloadAction -> Host Action 2
5242 // d) Specify a host dependence to a device action.
5245 // Device Action 1 ---> OffloadAction -> Device Action 2
5247 // For a) and b), we just return the job generated for the dependences. For
5248 // c) and d) we override the current action with the host/device dependence
5249 // if the current toolchain is host/device and set the offload dependences
5250 // info with the jobs obtained from the device/host dependence(s).
5252 // If there is a single device option or has no host action, just generate
5254 if (OA
->hasSingleDeviceDependence() || !OA
->hasHostDependence()) {
5256 OA
->doOnEachDeviceDependence([&](Action
*DepA
, const ToolChain
*DepTC
,
5257 const char *DepBoundArch
) {
5258 DevA
.append(BuildJobsForAction(C
, DepA
, DepTC
, DepBoundArch
, AtTopLevel
,
5259 /*MultipleArchs*/ !!DepBoundArch
,
5260 LinkingOutput
, CachedResults
,
5261 DepA
->getOffloadingDeviceKind()));
5266 // If 'Action 2' is host, we generate jobs for the device dependences and
5267 // override the current action with the host dependence. Otherwise, we
5268 // generate the host dependences and override the action with the device
5269 // dependence. The dependences can't therefore be a top-level action.
5270 OA
->doOnEachDependence(
5271 /*IsHostDependence=*/BuildingForOffloadDevice
,
5272 [&](Action
*DepA
, const ToolChain
*DepTC
, const char *DepBoundArch
) {
5273 OffloadDependencesInputInfo
.append(BuildJobsForAction(
5274 C
, DepA
, DepTC
, DepBoundArch
, /*AtTopLevel=*/false,
5275 /*MultipleArchs*/ !!DepBoundArch
, LinkingOutput
, CachedResults
,
5276 DepA
->getOffloadingDeviceKind()));
5279 A
= BuildingForOffloadDevice
5280 ? OA
->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
5281 : OA
->getHostDependence();
5283 // We may have already built this action as a part of the offloading
5284 // toolchain, return the cached input if so.
5285 std::pair
<const Action
*, std::string
> ActionTC
= {
5286 OA
->getHostDependence(),
5287 GetTriplePlusArchString(TC
, BoundArch
, TargetDeviceOffloadKind
)};
5288 if (CachedResults
.find(ActionTC
) != CachedResults
.end()) {
5289 InputInfoList Inputs
= CachedResults
[ActionTC
];
5290 Inputs
.append(OffloadDependencesInputInfo
);
5295 if (const InputAction
*IA
= dyn_cast
<InputAction
>(A
)) {
5296 // FIXME: It would be nice to not claim this here; maybe the old scheme of
5297 // just using Args was better?
5298 const Arg
&Input
= IA
->getInputArg();
5300 if (Input
.getOption().matches(options::OPT_INPUT
)) {
5301 const char *Name
= Input
.getValue();
5302 return {InputInfo(A
, Name
, /* _BaseInput = */ Name
)};
5304 return {InputInfo(A
, &Input
, /* _BaseInput = */ "")};
5307 if (const BindArchAction
*BAA
= dyn_cast
<BindArchAction
>(A
)) {
5308 const ToolChain
*TC
;
5309 StringRef ArchName
= BAA
->getArchName();
5311 if (!ArchName
.empty())
5312 TC
= &getToolChain(C
.getArgs(),
5313 computeTargetTriple(*this, TargetTriple
,
5314 C
.getArgs(), ArchName
));
5316 TC
= &C
.getDefaultToolChain();
5318 return BuildJobsForAction(C
, *BAA
->input_begin(), TC
, ArchName
, AtTopLevel
,
5319 MultipleArchs
, LinkingOutput
, CachedResults
,
5320 TargetDeviceOffloadKind
);
5324 ActionList Inputs
= A
->getInputs();
5326 const JobAction
*JA
= cast
<JobAction
>(A
);
5327 ActionList CollapsedOffloadActions
;
5329 ToolSelector
TS(JA
, *TC
, C
, isSaveTempsEnabled(),
5330 embedBitcodeInObject() && !isUsingLTO());
5331 const Tool
*T
= TS
.getTool(Inputs
, CollapsedOffloadActions
);
5334 return {InputInfo()};
5336 // If we've collapsed action list that contained OffloadAction we
5337 // need to build jobs for host/device-side inputs it may have held.
5338 for (const auto *OA
: CollapsedOffloadActions
)
5339 cast
<OffloadAction
>(OA
)->doOnEachDependence(
5340 /*IsHostDependence=*/BuildingForOffloadDevice
,
5341 [&](Action
*DepA
, const ToolChain
*DepTC
, const char *DepBoundArch
) {
5342 OffloadDependencesInputInfo
.append(BuildJobsForAction(
5343 C
, DepA
, DepTC
, DepBoundArch
, /* AtTopLevel */ false,
5344 /*MultipleArchs=*/!!DepBoundArch
, LinkingOutput
, CachedResults
,
5345 DepA
->getOffloadingDeviceKind()));
5348 // Only use pipes when there is exactly one input.
5349 InputInfoList InputInfos
;
5350 for (const Action
*Input
: Inputs
) {
5351 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
5352 // shouldn't get temporary output names.
5353 // FIXME: Clean this up.
5354 bool SubJobAtTopLevel
=
5355 AtTopLevel
&& (isa
<DsymutilJobAction
>(A
) || isa
<VerifyJobAction
>(A
));
5356 InputInfos
.append(BuildJobsForAction(
5357 C
, Input
, TC
, BoundArch
, SubJobAtTopLevel
, MultipleArchs
, LinkingOutput
,
5358 CachedResults
, A
->getOffloadingDeviceKind()));
5361 // Always use the first file input as the base input.
5362 const char *BaseInput
= InputInfos
[0].getBaseInput();
5363 for (auto &Info
: InputInfos
) {
5364 if (Info
.isFilename()) {
5365 BaseInput
= Info
.getBaseInput();
5370 // ... except dsymutil actions, which use their actual input as the base
5372 if (JA
->getType() == types::TY_dSYM
)
5373 BaseInput
= InputInfos
[0].getFilename();
5375 // Append outputs of offload device jobs to the input list
5376 if (!OffloadDependencesInputInfo
.empty())
5377 InputInfos
.append(OffloadDependencesInputInfo
.begin(),
5378 OffloadDependencesInputInfo
.end());
5380 // Set the effective triple of the toolchain for the duration of this job.
5381 llvm::Triple EffectiveTriple
;
5382 const ToolChain
&ToolTC
= T
->getToolChain();
5383 const ArgList
&Args
=
5384 C
.getArgsForToolChain(TC
, BoundArch
, A
->getOffloadingDeviceKind());
5385 if (InputInfos
.size() != 1) {
5386 EffectiveTriple
= llvm::Triple(ToolTC
.ComputeEffectiveClangTriple(Args
));
5388 // Pass along the input type if it can be unambiguously determined.
5389 EffectiveTriple
= llvm::Triple(
5390 ToolTC
.ComputeEffectiveClangTriple(Args
, InputInfos
[0].getType()));
5392 RegisterEffectiveTriple
TripleRAII(ToolTC
, EffectiveTriple
);
5394 // Determine the place to write output to, if any.
5396 InputInfoList UnbundlingResults
;
5397 if (auto *UA
= dyn_cast
<OffloadUnbundlingJobAction
>(JA
)) {
5398 // If we have an unbundling job, we need to create results for all the
5399 // outputs. We also update the results cache so that other actions using
5400 // this unbundling action can get the right results.
5401 for (auto &UI
: UA
->getDependentActionsInfo()) {
5402 assert(UI
.DependentOffloadKind
!= Action::OFK_None
&&
5403 "Unbundling with no offloading??");
5405 // Unbundling actions are never at the top level. When we generate the
5406 // offloading prefix, we also do that for the host file because the
5407 // unbundling action does not change the type of the output which can
5408 // cause a overwrite.
5409 std::string OffloadingPrefix
= Action::GetOffloadingFileNamePrefix(
5410 UI
.DependentOffloadKind
,
5411 UI
.DependentToolChain
->getTriple().normalize(),
5412 /*CreatePrefixForHost=*/true);
5413 auto CurI
= InputInfo(
5415 GetNamedOutputPath(C
, *UA
, BaseInput
, UI
.DependentBoundArch
,
5416 /*AtTopLevel=*/false,
5418 UI
.DependentOffloadKind
== Action::OFK_HIP
,
5421 // Save the unbundling result.
5422 UnbundlingResults
.push_back(CurI
);
5424 // Get the unique string identifier for this dependence and cache the
5427 if (TargetDeviceOffloadKind
== Action::OFK_HIP
) {
5428 if (UI
.DependentOffloadKind
== Action::OFK_Host
)
5431 Arch
= UI
.DependentBoundArch
;
5435 CachedResults
[{A
, GetTriplePlusArchString(UI
.DependentToolChain
, Arch
,
5436 UI
.DependentOffloadKind
)}] = {
5440 // Now that we have all the results generated, select the one that should be
5441 // returned for the current depending action.
5442 std::pair
<const Action
*, std::string
> ActionTC
= {
5443 A
, GetTriplePlusArchString(TC
, BoundArch
, TargetDeviceOffloadKind
)};
5444 assert(CachedResults
.find(ActionTC
) != CachedResults
.end() &&
5445 "Result does not exist??");
5446 Result
= CachedResults
[ActionTC
].front();
5447 } else if (JA
->getType() == types::TY_Nothing
)
5448 Result
= {InputInfo(A
, BaseInput
)};
5450 // We only have to generate a prefix for the host if this is not a top-level
5452 std::string OffloadingPrefix
= Action::GetOffloadingFileNamePrefix(
5453 A
->getOffloadingDeviceKind(), TC
->getTriple().normalize(),
5454 /*CreatePrefixForHost=*/isa
<OffloadPackagerJobAction
>(A
) ||
5455 !(A
->getOffloadingHostActiveKinds() == Action::OFK_None
||
5457 Result
= InputInfo(A
, GetNamedOutputPath(C
, *JA
, BaseInput
, BoundArch
,
5458 AtTopLevel
, MultipleArchs
,
5463 if (CCCPrintBindings
&& !CCGenDiagnostics
) {
5464 llvm::errs() << "# \"" << T
->getToolChain().getTripleString() << '"'
5465 << " - \"" << T
->getName() << "\", inputs: [";
5466 for (unsigned i
= 0, e
= InputInfos
.size(); i
!= e
; ++i
) {
5467 llvm::errs() << InputInfos
[i
].getAsString();
5469 llvm::errs() << ", ";
5471 if (UnbundlingResults
.empty())
5472 llvm::errs() << "], output: " << Result
.getAsString() << "\n";
5474 llvm::errs() << "], outputs: [";
5475 for (unsigned i
= 0, e
= UnbundlingResults
.size(); i
!= e
; ++i
) {
5476 llvm::errs() << UnbundlingResults
[i
].getAsString();
5478 llvm::errs() << ", ";
5480 llvm::errs() << "] \n";
5483 if (UnbundlingResults
.empty())
5485 C
, *JA
, Result
, InputInfos
,
5486 C
.getArgsForToolChain(TC
, BoundArch
, JA
->getOffloadingDeviceKind()),
5489 T
->ConstructJobMultipleOutputs(
5490 C
, *JA
, UnbundlingResults
, InputInfos
,
5491 C
.getArgsForToolChain(TC
, BoundArch
, JA
->getOffloadingDeviceKind()),
5497 const char *Driver::getDefaultImageName() const {
5498 llvm::Triple
Target(llvm::Triple::normalize(TargetTriple
));
5499 return Target
.isOSWindows() ? "a.exe" : "a.out";
5502 /// Create output filename based on ArgValue, which could either be a
5503 /// full filename, filename without extension, or a directory. If ArgValue
5504 /// does not provide a filename, then use BaseName, and use the extension
5505 /// suitable for FileType.
5506 static const char *MakeCLOutputFilename(const ArgList
&Args
, StringRef ArgValue
,
5508 types::ID FileType
) {
5509 SmallString
<128> Filename
= ArgValue
;
5511 if (ArgValue
.empty()) {
5512 // If the argument is empty, output to BaseName in the current dir.
5513 Filename
= BaseName
;
5514 } else if (llvm::sys::path::is_separator(Filename
.back())) {
5515 // If the argument is a directory, output to BaseName in that dir.
5516 llvm::sys::path::append(Filename
, BaseName
);
5519 if (!llvm::sys::path::has_extension(ArgValue
)) {
5520 // If the argument didn't provide an extension, then set it.
5521 const char *Extension
= types::getTypeTempSuffix(FileType
, true);
5523 if (FileType
== types::TY_Image
&&
5524 Args
.hasArg(options::OPT__SLASH_LD
, options::OPT__SLASH_LDd
)) {
5525 // The output file is a dll.
5529 llvm::sys::path::replace_extension(Filename
, Extension
);
5532 return Args
.MakeArgString(Filename
.c_str());
5535 static bool HasPreprocessOutput(const Action
&JA
) {
5536 if (isa
<PreprocessJobAction
>(JA
))
5538 if (isa
<OffloadAction
>(JA
) && isa
<PreprocessJobAction
>(JA
.getInputs()[0]))
5540 if (isa
<OffloadBundlingJobAction
>(JA
) &&
5541 HasPreprocessOutput(*(JA
.getInputs()[0])))
5546 const char *Driver::CreateTempFile(Compilation
&C
, StringRef Prefix
,
5547 StringRef Suffix
, bool MultipleArchs
,
5548 StringRef BoundArch
) const {
5549 SmallString
<128> TmpName
;
5550 Arg
*A
= C
.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir
);
5551 std::optional
<std::string
> CrashDirectory
=
5552 CCGenDiagnostics
&& A
5553 ? std::string(A
->getValue())
5554 : llvm::sys::Process::GetEnv("CLANG_CRASH_DIAGNOSTICS_DIR");
5555 if (CrashDirectory
) {
5556 if (!getVFS().exists(*CrashDirectory
))
5557 llvm::sys::fs::create_directories(*CrashDirectory
);
5558 SmallString
<128> Path(*CrashDirectory
);
5559 llvm::sys::path::append(Path
, Prefix
);
5560 const char *Middle
= !Suffix
.empty() ? "-%%%%%%." : "-%%%%%%";
5561 if (std::error_code EC
=
5562 llvm::sys::fs::createUniqueFile(Path
+ Middle
+ Suffix
, TmpName
)) {
5563 Diag(clang::diag::err_unable_to_make_temp
) << EC
.message();
5567 if (MultipleArchs
&& !BoundArch
.empty()) {
5568 TmpName
= GetTemporaryDirectory(Prefix
);
5569 llvm::sys::path::append(TmpName
,
5570 Twine(Prefix
) + "-" + BoundArch
+ "." + Suffix
);
5572 TmpName
= GetTemporaryPath(Prefix
, Suffix
);
5575 return C
.addTempFile(C
.getArgs().MakeArgString(TmpName
));
5578 // Calculate the output path of the module file when compiling a module unit
5579 // with the `-fmodule-output` option or `-fmodule-output=` option specified.
5581 // - If `-fmodule-output=` is specfied, then the module file is
5582 // writing to the value.
5583 // - Otherwise if the output object file of the module unit is specified, the
5585 // of the module file should be the same with the output object file except
5586 // the corresponding suffix. This requires both `-o` and `-c` are specified.
5587 // - Otherwise, the output path of the module file will be the same with the
5588 // input with the corresponding suffix.
5589 static const char *GetModuleOutputPath(Compilation
&C
, const JobAction
&JA
,
5590 const char *BaseInput
) {
5591 assert(isa
<PrecompileJobAction
>(JA
) && JA
.getType() == types::TY_ModuleFile
&&
5592 (C
.getArgs().hasArg(options::OPT_fmodule_output
) ||
5593 C
.getArgs().hasArg(options::OPT_fmodule_output_EQ
)));
5595 if (Arg
*ModuleOutputEQ
=
5596 C
.getArgs().getLastArg(options::OPT_fmodule_output_EQ
))
5597 return C
.addResultFile(ModuleOutputEQ
->getValue(), &JA
);
5599 SmallString
<64> OutputPath
;
5600 Arg
*FinalOutput
= C
.getArgs().getLastArg(options::OPT_o
);
5601 if (FinalOutput
&& C
.getArgs().hasArg(options::OPT_c
))
5602 OutputPath
= FinalOutput
->getValue();
5604 OutputPath
= BaseInput
;
5606 const char *Extension
= types::getTypeTempSuffix(JA
.getType());
5607 llvm::sys::path::replace_extension(OutputPath
, Extension
);
5608 return C
.addResultFile(C
.getArgs().MakeArgString(OutputPath
.c_str()), &JA
);
5611 const char *Driver::GetNamedOutputPath(Compilation
&C
, const JobAction
&JA
,
5612 const char *BaseInput
,
5613 StringRef OrigBoundArch
, bool AtTopLevel
,
5615 StringRef OffloadingPrefix
) const {
5616 std::string BoundArch
= OrigBoundArch
.str();
5617 if (is_style_windows(llvm::sys::path::Style::native
)) {
5618 // BoundArch may contains ':', which is invalid in file names on Windows,
5619 // therefore replace it with '%'.
5620 std::replace(BoundArch
.begin(), BoundArch
.end(), ':', '@');
5623 llvm::PrettyStackTraceString
CrashInfo("Computing output path");
5624 // Output to a user requested destination?
5625 if (AtTopLevel
&& !isa
<DsymutilJobAction
>(JA
) && !isa
<VerifyJobAction
>(JA
)) {
5626 if (Arg
*FinalOutput
= C
.getArgs().getLastArg(options::OPT_o
))
5627 return C
.addResultFile(FinalOutput
->getValue(), &JA
);
5630 // For /P, preprocess to file named after BaseInput.
5631 if (C
.getArgs().hasArg(options::OPT__SLASH_P
)) {
5632 assert(AtTopLevel
&& isa
<PreprocessJobAction
>(JA
));
5633 StringRef BaseName
= llvm::sys::path::filename(BaseInput
);
5635 if (Arg
*A
= C
.getArgs().getLastArg(options::OPT__SLASH_Fi
))
5636 NameArg
= A
->getValue();
5637 return C
.addResultFile(
5638 MakeCLOutputFilename(C
.getArgs(), NameArg
, BaseName
, types::TY_PP_C
),
5642 // Default to writing to stdout?
5643 if (AtTopLevel
&& !CCGenDiagnostics
&& HasPreprocessOutput(JA
)) {
5647 if (JA
.getType() == types::TY_ModuleFile
&&
5648 C
.getArgs().getLastArg(options::OPT_module_file_info
)) {
5652 if (IsDXCMode() && !C
.getArgs().hasArg(options::OPT_o
))
5655 // Is this the assembly listing for /FA?
5656 if (JA
.getType() == types::TY_PP_Asm
&&
5657 (C
.getArgs().hasArg(options::OPT__SLASH_FA
) ||
5658 C
.getArgs().hasArg(options::OPT__SLASH_Fa
))) {
5659 // Use /Fa and the input filename to determine the asm file name.
5660 StringRef BaseName
= llvm::sys::path::filename(BaseInput
);
5661 StringRef FaValue
= C
.getArgs().getLastArgValue(options::OPT__SLASH_Fa
);
5662 return C
.addResultFile(
5663 MakeCLOutputFilename(C
.getArgs(), FaValue
, BaseName
, JA
.getType()),
5667 bool SpecifiedModuleOutput
=
5668 C
.getArgs().hasArg(options::OPT_fmodule_output
) ||
5669 C
.getArgs().hasArg(options::OPT_fmodule_output_EQ
);
5670 if (MultipleArchs
&& SpecifiedModuleOutput
)
5671 Diag(clang::diag::err_drv_module_output_with_multiple_arch
);
5673 // If we're emitting a module output with the specified option
5674 // `-fmodule-output`.
5675 if (!AtTopLevel
&& isa
<PrecompileJobAction
>(JA
) &&
5676 JA
.getType() == types::TY_ModuleFile
&& SpecifiedModuleOutput
)
5677 return GetModuleOutputPath(C
, JA
, BaseInput
);
5679 // Output to a temporary file?
5680 if ((!AtTopLevel
&& !isSaveTempsEnabled() &&
5681 !C
.getArgs().hasArg(options::OPT__SLASH_Fo
)) ||
5683 StringRef Name
= llvm::sys::path::filename(BaseInput
);
5684 std::pair
<StringRef
, StringRef
> Split
= Name
.split('.');
5685 const char *Suffix
= types::getTypeTempSuffix(JA
.getType(), IsCLMode());
5686 return CreateTempFile(C
, Split
.first
, Suffix
, MultipleArchs
, BoundArch
);
5689 SmallString
<128> BasePath(BaseInput
);
5690 SmallString
<128> ExternalPath("");
5693 // Dsymutil actions should use the full path.
5694 if (isa
<DsymutilJobAction
>(JA
) && C
.getArgs().hasArg(options::OPT_dsym_dir
)) {
5695 ExternalPath
+= C
.getArgs().getLastArg(options::OPT_dsym_dir
)->getValue();
5696 // We use posix style here because the tests (specifically
5697 // darwin-dsymutil.c) demonstrate that posix style paths are acceptable
5698 // even on Windows and if we don't then the similar test covering this
5700 llvm::sys::path::append(ExternalPath
, llvm::sys::path::Style::posix
,
5701 llvm::sys::path::filename(BasePath
));
5702 BaseName
= ExternalPath
;
5703 } else if (isa
<DsymutilJobAction
>(JA
) || isa
<VerifyJobAction
>(JA
))
5704 BaseName
= BasePath
;
5706 BaseName
= llvm::sys::path::filename(BasePath
);
5708 // Determine what the derived output name should be.
5709 const char *NamedOutput
;
5711 if ((JA
.getType() == types::TY_Object
|| JA
.getType() == types::TY_LTO_BC
) &&
5712 C
.getArgs().hasArg(options::OPT__SLASH_Fo
, options::OPT__SLASH_o
)) {
5713 // The /Fo or /o flag decides the object filename.
5716 .getLastArg(options::OPT__SLASH_Fo
, options::OPT__SLASH_o
)
5719 MakeCLOutputFilename(C
.getArgs(), Val
, BaseName
, types::TY_Object
);
5720 } else if (JA
.getType() == types::TY_Image
&&
5721 C
.getArgs().hasArg(options::OPT__SLASH_Fe
,
5722 options::OPT__SLASH_o
)) {
5723 // The /Fe or /o flag names the linked file.
5726 .getLastArg(options::OPT__SLASH_Fe
, options::OPT__SLASH_o
)
5729 MakeCLOutputFilename(C
.getArgs(), Val
, BaseName
, types::TY_Image
);
5730 } else if (JA
.getType() == types::TY_Image
) {
5732 // clang-cl uses BaseName for the executable name.
5734 MakeCLOutputFilename(C
.getArgs(), "", BaseName
, types::TY_Image
);
5736 SmallString
<128> Output(getDefaultImageName());
5737 // HIP image for device compilation with -fno-gpu-rdc is per compilation
5739 bool IsHIPNoRDC
= JA
.getOffloadingDeviceKind() == Action::OFK_HIP
&&
5740 !C
.getArgs().hasFlag(options::OPT_fgpu_rdc
,
5741 options::OPT_fno_gpu_rdc
, false);
5742 bool UseOutExtension
= IsHIPNoRDC
|| isa
<OffloadPackagerJobAction
>(JA
);
5743 if (UseOutExtension
) {
5745 llvm::sys::path::replace_extension(Output
, "");
5747 Output
+= OffloadingPrefix
;
5748 if (MultipleArchs
&& !BoundArch
.empty()) {
5750 Output
.append(BoundArch
);
5752 if (UseOutExtension
)
5754 NamedOutput
= C
.getArgs().MakeArgString(Output
.c_str());
5756 } else if (JA
.getType() == types::TY_PCH
&& IsCLMode()) {
5757 NamedOutput
= C
.getArgs().MakeArgString(GetClPchPath(C
, BaseName
));
5758 } else if ((JA
.getType() == types::TY_Plist
|| JA
.getType() == types::TY_AST
) &&
5759 C
.getArgs().hasArg(options::OPT__SLASH_o
)) {
5762 .getLastArg(options::OPT__SLASH_o
)
5765 MakeCLOutputFilename(C
.getArgs(), Val
, BaseName
, types::TY_Object
);
5767 const char *Suffix
= types::getTypeTempSuffix(JA
.getType(), IsCLMode());
5768 assert(Suffix
&& "All types used for output should have a suffix.");
5770 std::string::size_type End
= std::string::npos
;
5771 if (!types::appendSuffixForType(JA
.getType()))
5772 End
= BaseName
.rfind('.');
5773 SmallString
<128> Suffixed(BaseName
.substr(0, End
));
5774 Suffixed
+= OffloadingPrefix
;
5775 if (MultipleArchs
&& !BoundArch
.empty()) {
5777 Suffixed
.append(BoundArch
);
5779 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
5780 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
5781 // optimized bitcode output.
5782 auto IsAMDRDCInCompilePhase
= [](const JobAction
&JA
,
5783 const llvm::opt::DerivedArgList
&Args
) {
5784 // The relocatable compilation in HIP and OpenMP implies -emit-llvm.
5785 // Similarly, use a ".tmp.bc" suffix for the unoptimized bitcode
5786 // (generated in the compile phase.)
5787 const ToolChain
*TC
= JA
.getOffloadingToolChain();
5788 return isa
<CompileJobAction
>(JA
) &&
5789 ((JA
.getOffloadingDeviceKind() == Action::OFK_HIP
&&
5790 Args
.hasFlag(options::OPT_fgpu_rdc
, options::OPT_fno_gpu_rdc
,
5792 (JA
.getOffloadingDeviceKind() == Action::OFK_OpenMP
&& TC
&&
5793 TC
->getTriple().isAMDGPU()));
5795 if (!AtTopLevel
&& JA
.getType() == types::TY_LLVM_BC
&&
5796 (C
.getArgs().hasArg(options::OPT_emit_llvm
) ||
5797 IsAMDRDCInCompilePhase(JA
, C
.getArgs())))
5801 NamedOutput
= C
.getArgs().MakeArgString(Suffixed
.c_str());
5804 // Prepend object file path if -save-temps=obj
5805 if (!AtTopLevel
&& isSaveTempsObj() && C
.getArgs().hasArg(options::OPT_o
) &&
5806 JA
.getType() != types::TY_PCH
) {
5807 Arg
*FinalOutput
= C
.getArgs().getLastArg(options::OPT_o
);
5808 SmallString
<128> TempPath(FinalOutput
->getValue());
5809 llvm::sys::path::remove_filename(TempPath
);
5810 StringRef OutputFileName
= llvm::sys::path::filename(NamedOutput
);
5811 llvm::sys::path::append(TempPath
, OutputFileName
);
5812 NamedOutput
= C
.getArgs().MakeArgString(TempPath
.c_str());
5815 // If we're saving temps and the temp file conflicts with the input file,
5816 // then avoid overwriting input file.
5817 if (!AtTopLevel
&& isSaveTempsEnabled() && NamedOutput
== BaseName
) {
5818 bool SameFile
= false;
5819 SmallString
<256> Result
;
5820 llvm::sys::fs::current_path(Result
);
5821 llvm::sys::path::append(Result
, BaseName
);
5822 llvm::sys::fs::equivalent(BaseInput
, Result
.c_str(), SameFile
);
5823 // Must share the same path to conflict.
5825 StringRef Name
= llvm::sys::path::filename(BaseInput
);
5826 std::pair
<StringRef
, StringRef
> Split
= Name
.split('.');
5827 std::string TmpName
= GetTemporaryPath(
5828 Split
.first
, types::getTypeTempSuffix(JA
.getType(), IsCLMode()));
5829 return C
.addTempFile(C
.getArgs().MakeArgString(TmpName
));
5833 // As an annoying special case, PCH generation doesn't strip the pathname.
5834 if (JA
.getType() == types::TY_PCH
&& !IsCLMode()) {
5835 llvm::sys::path::remove_filename(BasePath
);
5836 if (BasePath
.empty())
5837 BasePath
= NamedOutput
;
5839 llvm::sys::path::append(BasePath
, NamedOutput
);
5840 return C
.addResultFile(C
.getArgs().MakeArgString(BasePath
.c_str()), &JA
);
5843 return C
.addResultFile(NamedOutput
, &JA
);
5846 std::string
Driver::GetFilePath(StringRef Name
, const ToolChain
&TC
) const {
5847 // Search for Name in a list of paths.
5848 auto SearchPaths
= [&](const llvm::SmallVectorImpl
<std::string
> &P
)
5849 -> std::optional
<std::string
> {
5850 // Respect a limited subset of the '-Bprefix' functionality in GCC by
5851 // attempting to use this prefix when looking for file paths.
5852 for (const auto &Dir
: P
) {
5855 SmallString
<128> P(Dir
[0] == '=' ? SysRoot
+ Dir
.substr(1) : Dir
);
5856 llvm::sys::path::append(P
, Name
);
5857 if (llvm::sys::fs::exists(Twine(P
)))
5858 return std::string(P
);
5860 return std::nullopt
;
5863 if (auto P
= SearchPaths(PrefixDirs
))
5866 SmallString
<128> R(ResourceDir
);
5867 llvm::sys::path::append(R
, Name
);
5868 if (llvm::sys::fs::exists(Twine(R
)))
5869 return std::string(R
.str());
5871 SmallString
<128> P(TC
.getCompilerRTPath());
5872 llvm::sys::path::append(P
, Name
);
5873 if (llvm::sys::fs::exists(Twine(P
)))
5874 return std::string(P
.str());
5876 SmallString
<128> D(Dir
);
5877 llvm::sys::path::append(D
, "..", Name
);
5878 if (llvm::sys::fs::exists(Twine(D
)))
5879 return std::string(D
.str());
5881 if (auto P
= SearchPaths(TC
.getLibraryPaths()))
5884 if (auto P
= SearchPaths(TC
.getFilePaths()))
5887 return std::string(Name
);
5890 void Driver::generatePrefixedToolNames(
5891 StringRef Tool
, const ToolChain
&TC
,
5892 SmallVectorImpl
<std::string
> &Names
) const {
5893 // FIXME: Needs a better variable than TargetTriple
5894 Names
.emplace_back((TargetTriple
+ "-" + Tool
).str());
5895 Names
.emplace_back(Tool
);
5898 static bool ScanDirForExecutable(SmallString
<128> &Dir
, StringRef Name
) {
5899 llvm::sys::path::append(Dir
, Name
);
5900 if (llvm::sys::fs::can_execute(Twine(Dir
)))
5902 llvm::sys::path::remove_filename(Dir
);
5906 std::string
Driver::GetProgramPath(StringRef Name
, const ToolChain
&TC
) const {
5907 SmallVector
<std::string
, 2> TargetSpecificExecutables
;
5908 generatePrefixedToolNames(Name
, TC
, TargetSpecificExecutables
);
5910 // Respect a limited subset of the '-Bprefix' functionality in GCC by
5911 // attempting to use this prefix when looking for program paths.
5912 for (const auto &PrefixDir
: PrefixDirs
) {
5913 if (llvm::sys::fs::is_directory(PrefixDir
)) {
5914 SmallString
<128> P(PrefixDir
);
5915 if (ScanDirForExecutable(P
, Name
))
5916 return std::string(P
.str());
5918 SmallString
<128> P((PrefixDir
+ Name
).str());
5919 if (llvm::sys::fs::can_execute(Twine(P
)))
5920 return std::string(P
.str());
5924 const ToolChain::path_list
&List
= TC
.getProgramPaths();
5925 for (const auto &TargetSpecificExecutable
: TargetSpecificExecutables
) {
5926 // For each possible name of the tool look for it in
5927 // program paths first, then the path.
5928 // Higher priority names will be first, meaning that
5929 // a higher priority name in the path will be found
5930 // instead of a lower priority name in the program path.
5931 // E.g. <triple>-gcc on the path will be found instead
5932 // of gcc in the program path
5933 for (const auto &Path
: List
) {
5934 SmallString
<128> P(Path
);
5935 if (ScanDirForExecutable(P
, TargetSpecificExecutable
))
5936 return std::string(P
.str());
5939 // Fall back to the path
5940 if (llvm::ErrorOr
<std::string
> P
=
5941 llvm::sys::findProgramByName(TargetSpecificExecutable
))
5945 return std::string(Name
);
5948 std::string
Driver::GetTemporaryPath(StringRef Prefix
, StringRef Suffix
) const {
5949 SmallString
<128> Path
;
5950 std::error_code EC
= llvm::sys::fs::createTemporaryFile(Prefix
, Suffix
, Path
);
5952 Diag(clang::diag::err_unable_to_make_temp
) << EC
.message();
5956 return std::string(Path
.str());
5959 std::string
Driver::GetTemporaryDirectory(StringRef Prefix
) const {
5960 SmallString
<128> Path
;
5961 std::error_code EC
= llvm::sys::fs::createUniqueDirectory(Prefix
, Path
);
5963 Diag(clang::diag::err_unable_to_make_temp
) << EC
.message();
5967 return std::string(Path
.str());
5970 std::string
Driver::GetClPchPath(Compilation
&C
, StringRef BaseName
) const {
5971 SmallString
<128> Output
;
5972 if (Arg
*FpArg
= C
.getArgs().getLastArg(options::OPT__SLASH_Fp
)) {
5973 // FIXME: If anybody needs it, implement this obscure rule:
5974 // "If you specify a directory without a file name, the default file name
5975 // is VCx0.pch., where x is the major version of Visual C++ in use."
5976 Output
= FpArg
->getValue();
5978 // "If you do not specify an extension as part of the path name, an
5979 // extension of .pch is assumed. "
5980 if (!llvm::sys::path::has_extension(Output
))
5983 if (Arg
*YcArg
= C
.getArgs().getLastArg(options::OPT__SLASH_Yc
))
5984 Output
= YcArg
->getValue();
5987 llvm::sys::path::replace_extension(Output
, ".pch");
5989 return std::string(Output
.str());
5992 const ToolChain
&Driver::getToolChain(const ArgList
&Args
,
5993 const llvm::Triple
&Target
) const {
5995 auto &TC
= ToolChains
[Target
.str()];
5997 switch (Target
.getOS()) {
5998 case llvm::Triple::AIX
:
5999 TC
= std::make_unique
<toolchains::AIX
>(*this, Target
, Args
);
6001 case llvm::Triple::Haiku
:
6002 TC
= std::make_unique
<toolchains::Haiku
>(*this, Target
, Args
);
6004 case llvm::Triple::Ananas
:
6005 TC
= std::make_unique
<toolchains::Ananas
>(*this, Target
, Args
);
6007 case llvm::Triple::CloudABI
:
6008 TC
= std::make_unique
<toolchains::CloudABI
>(*this, Target
, Args
);
6010 case llvm::Triple::Darwin
:
6011 case llvm::Triple::MacOSX
:
6012 case llvm::Triple::IOS
:
6013 case llvm::Triple::TvOS
:
6014 case llvm::Triple::WatchOS
:
6015 case llvm::Triple::DriverKit
:
6016 TC
= std::make_unique
<toolchains::DarwinClang
>(*this, Target
, Args
);
6018 case llvm::Triple::DragonFly
:
6019 TC
= std::make_unique
<toolchains::DragonFly
>(*this, Target
, Args
);
6021 case llvm::Triple::OpenBSD
:
6022 TC
= std::make_unique
<toolchains::OpenBSD
>(*this, Target
, Args
);
6024 case llvm::Triple::NetBSD
:
6025 TC
= std::make_unique
<toolchains::NetBSD
>(*this, Target
, Args
);
6027 case llvm::Triple::FreeBSD
:
6029 TC
= std::make_unique
<toolchains::PPCFreeBSDToolChain
>(*this, Target
,
6032 TC
= std::make_unique
<toolchains::FreeBSD
>(*this, Target
, Args
);
6034 case llvm::Triple::Minix
:
6035 TC
= std::make_unique
<toolchains::Minix
>(*this, Target
, Args
);
6037 case llvm::Triple::Linux
:
6038 case llvm::Triple::ELFIAMCU
:
6039 if (Target
.getArch() == llvm::Triple::hexagon
)
6040 TC
= std::make_unique
<toolchains::HexagonToolChain
>(*this, Target
,
6042 else if ((Target
.getVendor() == llvm::Triple::MipsTechnologies
) &&
6043 !Target
.hasEnvironment())
6044 TC
= std::make_unique
<toolchains::MipsLLVMToolChain
>(*this, Target
,
6046 else if (Target
.isPPC())
6047 TC
= std::make_unique
<toolchains::PPCLinuxToolChain
>(*this, Target
,
6049 else if (Target
.getArch() == llvm::Triple::ve
)
6050 TC
= std::make_unique
<toolchains::VEToolChain
>(*this, Target
, Args
);
6053 TC
= std::make_unique
<toolchains::Linux
>(*this, Target
, Args
);
6055 case llvm::Triple::NaCl
:
6056 TC
= std::make_unique
<toolchains::NaClToolChain
>(*this, Target
, Args
);
6058 case llvm::Triple::Fuchsia
:
6059 TC
= std::make_unique
<toolchains::Fuchsia
>(*this, Target
, Args
);
6061 case llvm::Triple::Solaris
:
6062 TC
= std::make_unique
<toolchains::Solaris
>(*this, Target
, Args
);
6064 case llvm::Triple::CUDA
:
6065 TC
= std::make_unique
<toolchains::NVPTXToolChain
>(*this, Target
, Args
);
6067 case llvm::Triple::AMDHSA
:
6068 TC
= std::make_unique
<toolchains::ROCMToolChain
>(*this, Target
, Args
);
6070 case llvm::Triple::AMDPAL
:
6071 case llvm::Triple::Mesa3D
:
6072 TC
= std::make_unique
<toolchains::AMDGPUToolChain
>(*this, Target
, Args
);
6074 case llvm::Triple::Win32
:
6075 switch (Target
.getEnvironment()) {
6077 if (Target
.isOSBinFormatELF())
6078 TC
= std::make_unique
<toolchains::Generic_ELF
>(*this, Target
, Args
);
6079 else if (Target
.isOSBinFormatMachO())
6080 TC
= std::make_unique
<toolchains::MachO
>(*this, Target
, Args
);
6082 TC
= std::make_unique
<toolchains::Generic_GCC
>(*this, Target
, Args
);
6084 case llvm::Triple::GNU
:
6085 TC
= std::make_unique
<toolchains::MinGW
>(*this, Target
, Args
);
6087 case llvm::Triple::Itanium
:
6088 TC
= std::make_unique
<toolchains::CrossWindowsToolChain
>(*this, Target
,
6091 case llvm::Triple::MSVC
:
6092 case llvm::Triple::UnknownEnvironment
:
6093 if (Args
.getLastArgValue(options::OPT_fuse_ld_EQ
)
6094 .startswith_insensitive("bfd"))
6095 TC
= std::make_unique
<toolchains::CrossWindowsToolChain
>(
6096 *this, Target
, Args
);
6099 std::make_unique
<toolchains::MSVCToolChain
>(*this, Target
, Args
);
6103 case llvm::Triple::PS4
:
6104 TC
= std::make_unique
<toolchains::PS4CPU
>(*this, Target
, Args
);
6106 case llvm::Triple::PS5
:
6107 TC
= std::make_unique
<toolchains::PS5CPU
>(*this, Target
, Args
);
6109 case llvm::Triple::Contiki
:
6110 TC
= std::make_unique
<toolchains::Contiki
>(*this, Target
, Args
);
6112 case llvm::Triple::Hurd
:
6113 TC
= std::make_unique
<toolchains::Hurd
>(*this, Target
, Args
);
6115 case llvm::Triple::ZOS
:
6116 TC
= std::make_unique
<toolchains::ZOS
>(*this, Target
, Args
);
6118 case llvm::Triple::ShaderModel
:
6119 TC
= std::make_unique
<toolchains::HLSLToolChain
>(*this, Target
, Args
);
6122 // Of these targets, Hexagon is the only one that might have
6123 // an OS of Linux, in which case it got handled above already.
6124 switch (Target
.getArch()) {
6125 case llvm::Triple::tce
:
6126 TC
= std::make_unique
<toolchains::TCEToolChain
>(*this, Target
, Args
);
6128 case llvm::Triple::tcele
:
6129 TC
= std::make_unique
<toolchains::TCELEToolChain
>(*this, Target
, Args
);
6131 case llvm::Triple::hexagon
:
6132 TC
= std::make_unique
<toolchains::HexagonToolChain
>(*this, Target
,
6135 case llvm::Triple::lanai
:
6136 TC
= std::make_unique
<toolchains::LanaiToolChain
>(*this, Target
, Args
);
6138 case llvm::Triple::xcore
:
6139 TC
= std::make_unique
<toolchains::XCoreToolChain
>(*this, Target
, Args
);
6141 case llvm::Triple::wasm32
:
6142 case llvm::Triple::wasm64
:
6143 TC
= std::make_unique
<toolchains::WebAssembly
>(*this, Target
, Args
);
6145 case llvm::Triple::avr
:
6146 TC
= std::make_unique
<toolchains::AVRToolChain
>(*this, Target
, Args
);
6148 case llvm::Triple::msp430
:
6150 std::make_unique
<toolchains::MSP430ToolChain
>(*this, Target
, Args
);
6152 case llvm::Triple::riscv32
:
6153 case llvm::Triple::riscv64
:
6154 if (toolchains::RISCVToolChain::hasGCCToolchain(*this, Args
))
6156 std::make_unique
<toolchains::RISCVToolChain
>(*this, Target
, Args
);
6158 TC
= std::make_unique
<toolchains::BareMetal
>(*this, Target
, Args
);
6160 case llvm::Triple::ve
:
6161 TC
= std::make_unique
<toolchains::VEToolChain
>(*this, Target
, Args
);
6163 case llvm::Triple::spirv32
:
6164 case llvm::Triple::spirv64
:
6165 TC
= std::make_unique
<toolchains::SPIRVToolChain
>(*this, Target
, Args
);
6167 case llvm::Triple::csky
:
6168 TC
= std::make_unique
<toolchains::CSKYToolChain
>(*this, Target
, Args
);
6171 if (Target
.getVendor() == llvm::Triple::Myriad
)
6172 TC
= std::make_unique
<toolchains::MyriadToolChain
>(*this, Target
,
6174 else if (toolchains::BareMetal::handlesTarget(Target
))
6175 TC
= std::make_unique
<toolchains::BareMetal
>(*this, Target
, Args
);
6176 else if (Target
.isOSBinFormatELF())
6177 TC
= std::make_unique
<toolchains::Generic_ELF
>(*this, Target
, Args
);
6178 else if (Target
.isOSBinFormatMachO())
6179 TC
= std::make_unique
<toolchains::MachO
>(*this, Target
, Args
);
6181 TC
= std::make_unique
<toolchains::Generic_GCC
>(*this, Target
, Args
);
6189 const ToolChain
&Driver::getOffloadingDeviceToolChain(
6190 const ArgList
&Args
, const llvm::Triple
&Target
, const ToolChain
&HostTC
,
6191 const Action::OffloadKind
&TargetDeviceOffloadKind
) const {
6192 // Use device / host triples as the key into the ToolChains map because the
6193 // device ToolChain we create depends on both.
6194 auto &TC
= ToolChains
[Target
.str() + "/" + HostTC
.getTriple().str()];
6196 // Categorized by offload kind > arch rather than OS > arch like
6197 // the normal getToolChain call, as it seems a reasonable way to categorize
6199 switch (TargetDeviceOffloadKind
) {
6200 case Action::OFK_HIP
: {
6201 if (Target
.getArch() == llvm::Triple::amdgcn
&&
6202 Target
.getVendor() == llvm::Triple::AMD
&&
6203 Target
.getOS() == llvm::Triple::AMDHSA
)
6204 TC
= std::make_unique
<toolchains::HIPAMDToolChain
>(*this, Target
,
6206 else if (Target
.getArch() == llvm::Triple::spirv64
&&
6207 Target
.getVendor() == llvm::Triple::UnknownVendor
&&
6208 Target
.getOS() == llvm::Triple::UnknownOS
)
6209 TC
= std::make_unique
<toolchains::HIPSPVToolChain
>(*this, Target
,
6221 bool Driver::ShouldUseClangCompiler(const JobAction
&JA
) const {
6222 // Say "no" if there is not exactly one input of a type clang understands.
6223 if (JA
.size() != 1 ||
6224 !types::isAcceptedByClang((*JA
.input_begin())->getType()))
6227 // And say "no" if this is not a kind of action clang understands.
6228 if (!isa
<PreprocessJobAction
>(JA
) && !isa
<PrecompileJobAction
>(JA
) &&
6229 !isa
<CompileJobAction
>(JA
) && !isa
<BackendJobAction
>(JA
) &&
6230 !isa
<ExtractAPIJobAction
>(JA
))
6236 bool Driver::ShouldUseFlangCompiler(const JobAction
&JA
) const {
6237 // Say "no" if there is not exactly one input of a type flang understands.
6238 if (JA
.size() != 1 ||
6239 !types::isAcceptedByFlang((*JA
.input_begin())->getType()))
6242 // And say "no" if this is not a kind of action flang understands.
6243 if (!isa
<PreprocessJobAction
>(JA
) && !isa
<CompileJobAction
>(JA
) &&
6244 !isa
<BackendJobAction
>(JA
))
6250 bool Driver::ShouldEmitStaticLibrary(const ArgList
&Args
) const {
6251 // Only emit static library if the flag is set explicitly.
6252 if (Args
.hasArg(options::OPT_emit_static_lib
))
6257 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
6258 /// grouped values as integers. Numbers which are not provided are set to 0.
6260 /// \return True if the entire string was parsed (9.2), or all groups were
6261 /// parsed (10.3.5extrastuff).
6262 bool Driver::GetReleaseVersion(StringRef Str
, unsigned &Major
, unsigned &Minor
,
6263 unsigned &Micro
, bool &HadExtra
) {
6266 Major
= Minor
= Micro
= 0;
6270 if (Str
.consumeInteger(10, Major
))
6277 Str
= Str
.drop_front(1);
6279 if (Str
.consumeInteger(10, Minor
))
6285 Str
= Str
.drop_front(1);
6287 if (Str
.consumeInteger(10, Micro
))
6294 /// Parse digits from a string \p Str and fulfill \p Digits with
6295 /// the parsed numbers. This method assumes that the max number of
6296 /// digits to look for is equal to Digits.size().
6298 /// \return True if the entire string was parsed and there are
6299 /// no extra characters remaining at the end.
6300 bool Driver::GetReleaseVersion(StringRef Str
,
6301 MutableArrayRef
<unsigned> Digits
) {
6305 unsigned CurDigit
= 0;
6306 while (CurDigit
< Digits
.size()) {
6308 if (Str
.consumeInteger(10, Digit
))
6310 Digits
[CurDigit
] = Digit
;
6315 Str
= Str
.drop_front(1);
6319 // More digits than requested, bail out...
6323 std::pair
<unsigned, unsigned>
6324 Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode
) const {
6325 unsigned IncludedFlagsBitmask
= 0;
6326 unsigned ExcludedFlagsBitmask
= options::NoDriverOption
;
6328 if (IsClCompatMode
) {
6329 // Include CL and Core options.
6330 IncludedFlagsBitmask
|= options::CLOption
;
6331 IncludedFlagsBitmask
|= options::CLDXCOption
;
6332 IncludedFlagsBitmask
|= options::CoreOption
;
6334 ExcludedFlagsBitmask
|= options::CLOption
;
6337 // Include DXC and Core options.
6338 IncludedFlagsBitmask
|= options::DXCOption
;
6339 IncludedFlagsBitmask
|= options::CLDXCOption
;
6340 IncludedFlagsBitmask
|= options::CoreOption
;
6342 ExcludedFlagsBitmask
|= options::DXCOption
;
6344 if (!IsClCompatMode
&& !IsDXCMode())
6345 ExcludedFlagsBitmask
|= options::CLDXCOption
;
6347 return std::make_pair(IncludedFlagsBitmask
, ExcludedFlagsBitmask
);
6350 const char *Driver::getExecutableForDriverMode(DriverMode Mode
) {
6366 llvm_unreachable("Unhandled Mode");
6369 bool clang::driver::isOptimizationLevelFast(const ArgList
&Args
) {
6370 return Args
.hasFlag(options::OPT_Ofast
, options::OPT_O_Group
, false);
6373 bool clang::driver::willEmitRemarks(const ArgList
&Args
) {
6374 // -fsave-optimization-record enables it.
6375 if (Args
.hasFlag(options::OPT_fsave_optimization_record
,
6376 options::OPT_fno_save_optimization_record
, false))
6379 // -fsave-optimization-record=<format> enables it as well.
6380 if (Args
.hasFlag(options::OPT_fsave_optimization_record_EQ
,
6381 options::OPT_fno_save_optimization_record
, false))
6384 // -foptimization-record-file alone enables it too.
6385 if (Args
.hasFlag(options::OPT_foptimization_record_file_EQ
,
6386 options::OPT_fno_save_optimization_record
, false))
6389 // -foptimization-record-passes alone enables it too.
6390 if (Args
.hasFlag(options::OPT_foptimization_record_passes_EQ
,
6391 options::OPT_fno_save_optimization_record
, false))
6396 llvm::StringRef
clang::driver::getDriverMode(StringRef ProgName
,
6397 ArrayRef
<const char *> Args
) {
6398 static const std::string OptName
=
6399 getDriverOptTable().getOption(options::OPT_driver_mode
).getPrefixedName();
6400 llvm::StringRef Opt
;
6401 for (StringRef Arg
: Args
) {
6402 if (!Arg
.startswith(OptName
))
6407 Opt
= ToolChain::getTargetAndModeFromProgramName(ProgName
).DriverMode
;
6408 return Opt
.consume_front(OptName
) ? Opt
: "";
6411 bool driver::IsClangCL(StringRef DriverMode
) { return DriverMode
.equals("cl"); }