[clang] Handle __declspec() attributes in using
[llvm-project.git] / clang / lib / Driver / Driver.cpp
blob0567441225d0c378c1be554662eec2316e859542
1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
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
98 #include <map>
99 #include <memory>
100 #include <optional>
101 #include <utility>
102 #if LLVM_ON_UNIX
103 #include <unistd.h> // getpid
104 #endif
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()) {
117 default:
118 D.Diag(diag::err_drv_only_one_offload_target_supported);
119 return std::nullopt;
120 case 0:
121 D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << "";
122 return std::nullopt;
123 case 1:
124 break;
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))
140 return TT;
141 D.Diag(diag::err_drv_cuda_offload_only_emit_bc);
142 return std::nullopt;
144 D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str();
145 return std::nullopt;
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);
153 if (!TT)
154 return std::nullopt;
155 if (TT->getArch() == llvm::Triple::amdgcn &&
156 TT->getVendor() == llvm::Triple::AMD &&
157 TT->getOS() == llvm::Triple::AMDHSA)
158 return TT;
159 if (TT->getArch() == llvm::Triple::spirv64)
160 return TT;
161 D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str();
162 return std::nullopt;
165 // static
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);
178 } else {
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.
206 if (!this->VFS)
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;
222 #endif
223 #if defined(CLANG_CONFIG_FILE_USER_DIR)
225 SmallString<128> P;
226 llvm::sys::fs::expand_tilde(CLANG_CONFIG_FILE_USER_DIR, P);
227 UserConfigDir = static_cast<std::string>(P);
229 #endif
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)
242 .Case("cl", CLMode)
243 .Case("flang", FlangMode)
244 .Case("dxc", DXCMode)
245 .Default(std::nullopt))
246 Mode = *M;
247 else
248 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
251 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
252 bool IsClCompatMode,
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
264 if (!IsFlangMode())
265 ExcludedFlagsBitmask |= options::FlangOnlyOption;
267 unsigned MissingArgIndex, MissingArgCount;
268 InputArgList Args =
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;
276 ContainsError |=
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)) {
284 unsigned DiagID;
285 auto ArgString = A->getAsString(Args);
286 std::string Nearest;
287 if (getOpts().findNearest(
288 ArgString, Nearest, IncludedFlagsBitmask,
289 ExcludedFlagsBitmask | options::Unsupported) > 1) {
290 DiagID = diag::err_drv_unsupported_opt;
291 Diag(DiagID) << ArgString;
292 } else {
293 DiagID = diag::err_drv_unsupported_opt_with_suggestion;
294 Diag(DiagID) << ArgString << Nearest;
296 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
297 DiagnosticsEngine::Warning;
298 continue;
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)) {
311 unsigned DiagID;
312 auto ArgString = A->getAsString(Args);
313 std::string Nearest;
314 if (getOpts().findNearest(ArgString, Nearest, IncludedFlagsBitmask,
315 ExcludedFlagsBitmask) > 1) {
316 if (!IsCLMode() &&
317 getOpts().findExact(ArgString, Nearest, options::CC1Option)) {
318 DiagID = diag::err_drv_unknown_argument_with_suggestion;
319 Diags.Report(DiagID) << ArgString << "-Xclang " + Nearest;
320 } else {
321 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
322 : diag::err_drv_unknown_argument;
323 Diags.Report(DiagID) << ArgString;
325 } else {
326 DiagID = IsCLMode()
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())
337 continue;
339 // Warn on joined arguments that are similar to a long argument.
340 std::string ArgString = ArgStrings[A->getIndex()];
341 std::string Nearest;
342 if (getOpts().findExact("-" + ArgString, Nearest, IncludedFlagsBitmask,
343 ExcludedFlagsBitmask))
344 Diags.Report(diag::warn_drv_potentially_misspelled_joined_argument)
345 << A->getAsString(Args) << Nearest;
348 return Args;
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)) ||
364 CCGenDiagnostics) {
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.
399 } else
400 FinalPhase = phases::Link;
402 if (FinalPhaseArg)
403 *FinalPhaseArg = PhaseArg;
405 return FinalPhase;
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);
413 if (Claim)
414 A->claim();
415 return 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) {
427 if (IgnoreUnused)
428 A->claim();
430 if (A->getOption().matches(options::OPT_start_no_unused_arguments)) {
431 IgnoreUnused = true;
432 continue;
434 if (A->getOption().matches(options::OPT_end_no_unused_arguments)) {
435 IgnoreUnused = false;
436 continue;
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
444 // option.
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);
456 continue;
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));
468 else
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));
472 continue;
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 &&
481 Value == "stdc++") {
482 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_stdcxx));
483 continue;
486 // Rewrite unconditionally.
487 if (Value == "cc_kext") {
488 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_cckext));
489 continue;
493 // Pick up inputs via the -- option.
494 if (A->getOption().matches(options::OPT__DASH_DASH)) {
495 A->claim();
496 for (StringRef Val : A->getValues())
497 DAL->append(MakeInputArg(*DAL, Opts, Val, false));
498 continue;
501 DAL->append(A);
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),
514 HOST_LINK_VERSION);
515 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
517 #endif
519 return DAL;
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,
528 const ArgList &Args,
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);
547 return Target;
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);
565 } else {
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)
575 return Target;
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();
588 } else {
589 D.Diag(diag::err_drv_invalid_object_mode) << ObjectMode;
592 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
593 Target.setArch(AT);
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);
600 if (A) {
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);
614 else
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()) {
629 Target.setArch(AT);
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"
639 << Target.str();
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);
690 return Target;
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))
699 return LTOK_None;
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();
712 return LTOK_None;
714 return LTOMode;
717 // Parse the LTO options.
718 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
719 LTOMode =
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);
742 if (A)
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) {
752 if (A)
753 Diag(diag::err_drv_unsupported_option_argument)
754 << A->getSpelling() << A->getValue();
755 else
756 // FIXME: We could use a nicer diagnostic here.
757 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
760 return RT;
763 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
764 InputList &Inputs) {
767 // CUDA/HIP
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.
771 bool IsCuda =
772 llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
773 return types::isCuda(I.first);
775 bool IsHIP =
776 llvm::any_of(Inputs,
777 [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
778 return types::isHIP(I.first);
779 }) ||
780 C.getInputArgs().hasArg(options::OPT_hip_link);
781 if (IsCuda && IsHIP) {
782 Diag(clang::diag::err_drv_mix_cuda_hip);
783 return;
785 if (IsCuda) {
786 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
787 const llvm::Triple &HostTriple = HostTC->getTriple();
788 auto OFK = Action::OFK_Cuda;
789 auto CudaTriple =
790 getNVIDIAOffloadTargetTriple(*this, C.getInputArgs(), HostTriple);
791 if (!CudaTriple)
792 return;
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()];
796 if (!CudaTC) {
797 CudaTC = std::make_unique<toolchains::CudaToolChain>(
798 *this, *CudaTriple, *HostTC, C.getInputArgs());
800 C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
801 } else if (IsHIP) {
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";
806 return;
808 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
809 auto OFK = Action::OFK_HIP;
810 auto HIPTriple = getHIPOffloadTargetTriple(*this, C.getInputArgs());
811 if (!HIPTriple)
812 return;
813 auto *HIPTC = &getOffloadingDeviceToolChain(C.getInputArgs(), *HIPTriple,
814 *HostTC, OFK);
815 assert(HIPTC && "Could not create offloading device tool chain.");
816 C.addOffloadDeviceToolChain(HIPTC, OFK);
820 // OpenMP
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);
836 return;
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());
851 return;
853 llvm::copy(OpenMPTargets->getValues(), std::back_inserter(OpenMPTriples));
854 } else if (C.getInputArgs().hasArg(options::OPT_offload_arch_EQ) &&
855 !IsHIP && !IsCuda) {
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;
866 if (NVPTXTriple) {
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))
871 Archs.insert(Arch);
873 if (AMDTriple) {
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))
878 Archs.insert(Arch);
880 if (!AMDTriple && !NVPTXTriple) {
881 for (StringRef Arch :
882 getOffloadArchs(C, C.getArgs(), Action::OFK_OpenMP, nullptr, true))
883 Archs.insert(Arch);
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);
894 } else {
895 Diag(clang::diag::err_drv_failed_to_deduce_target_from_arch) << Arch;
896 return;
900 // If the set is empty then we failed to find a native architecture.
901 if (Archs.empty()) {
902 Diag(clang::diag::err_drv_failed_to_deduce_target_from_arch)
903 << "native";
904 return;
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;
920 continue;
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;
930 else {
931 const ToolChain *TC;
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.");
938 auto &DeviceTC =
939 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
940 if (!DeviceTC) {
941 if (TT.isNVPTX())
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());
947 else
948 assert(DeviceTC && "Device toolchain not defined.");
951 TC = DeviceTC.get();
952 } else
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);
961 return;
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),
976 Index, BaseArg);
977 Copy->getValues() = Opt->getValues();
978 if (Opt->isClaimed())
979 Copy->claim();
980 Copy->setOwnsValues(Opt->getOwnsValues());
981 Opt->setOwnsValues(false);
982 Args.append(Copy);
985 bool Driver::readConfigFile(StringRef FileName,
986 llvm::cl::ExpansionContext &ExpCtx) {
987 // Try opening the given file.
988 auto Status = getVFS().status(FileName);
989 if (!Status) {
990 Diag(diag::err_drv_cannot_open_config_file)
991 << FileName << Status.getError().message();
992 return true;
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";
997 return true;
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));
1005 return true;
1008 // Read options from config file.
1009 llvm::SmallString<128> CfgFileName(FileName);
1010 llvm::sys::path::native(CfgFileName);
1011 bool ContainErrors;
1012 std::unique_ptr<InputArgList> NewOptions = std::make_unique<InputArgList>(
1013 ParseArgStrings(NewCfgArgs, IsCLMode(), ContainErrors));
1014 if (ContainErrors)
1015 return true;
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)
1020 A->claim();
1022 if (!CfgOptions)
1023 CfgOptions = std::move(NewOptions);
1024 else {
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();
1028 if (BaseArg == Opt)
1029 BaseArg = nullptr;
1030 appendOneArg(*CfgOptions, Opt, BaseArg);
1033 ConfigFiles.push_back(std::string(CfgFileName));
1034 return false;
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.
1043 if (CLOptions) {
1044 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
1045 SmallString<128> CfgDir;
1046 CfgDir.append(
1047 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
1048 if (CfgDir.empty() || getVFS().makeAbsolute(CfgDir))
1049 SystemConfigDir.clear();
1050 else
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();
1059 else
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))
1070 return true;
1072 // Then load configuration files specified explicitly.
1073 SmallString<128> CfgFilePath;
1074 if (CLOptions) {
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";
1084 return true;
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;
1093 return true;
1096 // Try to read the config file, return on error.
1097 if (readConfigFile(CfgFilePath, ExpCtx))
1098 return true;
1102 // No error occurred.
1103 return false;
1106 bool Driver::loadDefaultConfigFiles(llvm::cl::ExpansionContext &ExpCtx) {
1107 // Disable default config if CLANG_NO_DEFAULT_CONFIG is set to a non-empty
1108 // value.
1109 if (const char *NoConfigEnv = ::getenv("CLANG_NO_DEFAULT_CONFIG")) {
1110 if (*NoConfigEnv)
1111 return false;
1113 if (CLOptions && CLOptions->hasArg(options::OPT_no_default_config))
1114 return false;
1116 std::string RealMode = getExecutableForDriverMode(Mode);
1117 std::string Triple;
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
1121 // compatibility.
1122 if (!ClangNameParts.TargetPrefix.empty() &&
1123 computeTargetTriple(*this, "/invalid/", *CLOptions).str() ==
1124 "/invalid/") {
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))
1168 return true;
1169 } else if (TryModeSuffix) {
1170 CfgFileName = ClangNameParts.ModeSuffix + ".cfg";
1171 if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath) &&
1172 readConfigFile(CfgFilePath, ExpCtx))
1173 return true;
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.
1183 return false;
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.
1202 bool ContainsError;
1203 CLOptions = std::make_unique<InputArgList>(
1204 ParseArgStrings(ArgList.slice(1), IsCLMode(), ContainsError));
1206 // Try parsing configuration file.
1207 if (!ContainsError)
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));
1215 if (HasConfigFile)
1216 for (auto *Opt : *CLOptions) {
1217 if (Opt->getOption().matches(options::OPT_config))
1218 continue;
1219 const Arg *BaseArg = &Opt->getBaseArg();
1220 if (BaseArg == Opt)
1221 BaseArg = nullptr;
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)) {
1229 A->claim();
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));
1239 if (!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);
1262 // Ignore -pipe.
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
1270 // or -b.
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.
1286 if (IsCLMode()) {
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();
1300 if (auto Triple =
1301 toolchains::HLSLToolChain::parseTargetProfile(TargetProfile))
1302 TargetTriple = *Triple;
1303 else
1304 Diag(diag::err_drv_invalid_directx_shader_module) << TargetProfile;
1306 A->claim();
1307 } else {
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)) {
1317 A->claim();
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;
1352 else
1353 Offload = OffloadHostDevice;
1356 setLTOMode(Args);
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)
1366 .Default(~0U);
1367 if (Model == ~0U) {
1368 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1369 << Name;
1370 } else
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);
1383 ModulesModeCXX20 =
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;
1395 else {
1396 StringRef ArgName = A->getValue();
1397 unsigned Kind = llvm::StringSwitch<unsigned>(ArgName)
1398 .Case("user", HeaderMode_User)
1399 .Case("system", HeaderMode_System)
1400 .Default(~0U);
1401 if (Kind == ~0U) {
1402 Diags.Report(diag::err_drv_invalid_value)
1403 << A->getAsString(Args) << ArgName;
1404 } else
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,
1429 ContainsError);
1431 if (!HandleImmediateArgs(*C))
1432 return C;
1434 // Construct the list of inputs.
1435 InputList 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);
1445 else
1446 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
1448 if (CCCPrintPhases) {
1449 PrintActions(*C);
1450 return C;
1453 BuildJobs(*C);
1455 return C;
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())
1465 A = A->getAlias();
1466 A->render(Args, ASL);
1469 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1470 if (I != ASL.begin())
1471 OS << ' ';
1472 llvm::sys::printArg(OS, *I, true);
1474 OS << '\n';
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"))
1488 CrashDiagDir = "/";
1489 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1490 int PID =
1491 #if LLVM_ON_UNIX
1492 getpid();
1493 #else
1495 #endif
1496 std::error_code EC;
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))
1506 continue;
1507 if (fs::status(File->path(), FileStatus))
1508 continue;
1509 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1510 llvm::MemoryBuffer::getFile(File->path());
1511 if (!CrashFile)
1512 continue;
1513 // The first line should start with "Process:", otherwise this isn't a real
1514 // .crash file.
1515 StringRef Data = CrashFile.get()->getBuffer();
1516 if (!Data.startswith("Process:"))
1517 continue;
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)
1521 continue;
1522 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1523 if (LineEnd == StringRef::npos)
1524 continue;
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] == '[')
1529 OpenBracket = i;
1530 if (ParentProcess[i] == ']')
1531 CloseBracket = i;
1533 // Extract the parent process PID from the .crash file and check whether
1534 // it matches this driver invocation pid.
1535 int CrashPID;
1536 if (OpenBracket < 0 || CloseBracket < 0 ||
1537 ParentProcess.slice(OpenBracket + 1, CloseBracket)
1538 .getAsInteger(10, CrashPID) || CrashPID != PID) {
1539 continue;
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);
1558 if (EC)
1559 return false;
1560 return true;
1563 return false;
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))
1578 return;
1580 unsigned Level = 1;
1581 if (Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_EQ)) {
1582 Level = llvm::StringSwitch<unsigned>(A->getValue())
1583 .Case("off", 0)
1584 .Case("compiler", 1)
1585 .Case("all", 2)
1586 .Default(1);
1588 if (!Level)
1589 return;
1591 // Don't try to generate diagnostics for dsymutil jobs.
1592 if (FailingCommand.getCreator().isDsymutilJob())
1593 return;
1595 bool IsLLD = false;
1596 ArgStringList SavedTemps;
1597 if (FailingCommand.getCreator().isLinkJob()) {
1598 C.getDefaultToolChain().GetLinkerPath(&IsLLD);
1599 if (!IsLLD || Level < 2)
1600 return;
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
1605 // later.
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.
1627 if (IsLLD) {
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()
1633 ? "/reproduce:"
1634 : "--reproduce=";
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********************";
1644 if (Report)
1645 Report->TemporaryFiles.push_back(TmpName);
1646 return;
1649 // Construct the list of inputs.
1650 InputList 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) {
1659 IgnoreInput = true;
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.";
1664 IgnoreInput = true;
1667 if (IgnoreInput) {
1668 it = Inputs.erase(it);
1669 ie = Inputs.end();
1670 } else {
1671 ++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.";
1679 return;
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.";
1695 return;
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);
1703 else
1704 BuildActions(C, C.getArgs(), Inputs, C.getActions());
1706 BuildJobs(C);
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).";
1712 return;
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).";
1723 return;
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).";
1730 return;
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;
1739 if (Report)
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");
1761 std::error_code EC;
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);
1765 if (EC) {
1766 Diag(clang::diag::note_drv_command_failed_diag_msg)
1767 << "Error generating run script: " << Script << " " << EC.message();
1768 } else {
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
1777 << "\n";
1778 if (Report)
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
1812 // skip it.
1813 if (Cmd.getResponseFileSupport().ResponseKind ==
1814 ResponseFileSupport::RF_None ||
1815 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(),
1816 Cmd.getArguments()))
1817 return;
1819 std::string TmpName = GetTemporaryPath("response", "txt");
1820 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1823 int Driver::ExecuteCompilation(
1824 Compilation &C,
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())
1834 return 1;
1836 return 0;
1839 // Just print if -### was present.
1840 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1841 C.getJobs().Print(llvm::errs(), "\n", true);
1842 return 0;
1845 // If there were errors building the compilation, quit now.
1846 if (Diags.hasErrorOccurred())
1847 return 1;
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())
1857 return 0;
1859 // Otherwise, remove result files and print extra information about abnormal
1860 // failures.
1861 int Res = 0;
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.
1872 if (CommandRes < 0)
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) {
1879 Res = CommandRes;
1880 continue;
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.
1894 if (CommandRes < 0)
1895 Diag(clang::diag::err_drv_command_signalled)
1896 << FailingTool.getShortName();
1897 else
1898 Diag(clang::diag::err_drv_command_failed)
1899 << FailingTool.getShortName() << CommandRes;
1902 return Res;
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;
1912 if (!ShowHidden)
1913 ExcludedFlagsBitmask |= HelpHidden;
1915 if (IsFlangMode())
1916 IncludedFlagsBitmask |= options::FlangOption;
1917 else
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';
1929 } else {
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();
1942 } else
1943 OS << "Thread model: " << TC.getThreadModel();
1944 OS << '\n';
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
1955 /// option.
1956 static void PrintDiagnosticCategories(raw_ostream &OS) {
1957 // Skip the empty category.
1958 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1959 ++i)
1960 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1963 void Driver::HandleAutocompletions(StringRef PassedFlags) const {
1964 if (PassedFlags == "")
1965 return;
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
1976 if (!IsFlangMode())
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 != "") {
1988 StringRef CurFlag;
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
1994 // -Xclang.
1995 if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1"))
1996 DisableFlags &= ~options::NoDriverOption;
1998 const llvm::opt::OptTable &Opts = getOpts();
1999 StringRef Cur;
2000 Cur = Flags.at(Flags.size() - 1);
2001 StringRef Prev;
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
2014 // this function.
2015 if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
2016 llvm::outs() << '\n';
2017 return;
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
2030 // this code.
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))
2042 return X < 0;
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';
2055 return false;
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";
2062 return false;
2065 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
2066 PrintDiagnosticCategories(llvm::outs());
2067 return false;
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));
2073 return false;
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());
2079 return false;
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';
2105 return false;
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) {
2113 if (separator)
2114 llvm::outs() << llvm::sys::EnvPathSeparator;
2115 llvm::outs() << Path;
2116 separator = true;
2118 for (const std::string &Path : TC.getProgramPaths()) {
2119 if (separator)
2120 llvm::outs() << llvm::sys::EnvPathSeparator;
2121 llvm::outs() << Path;
2122 separator = true;
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.
2133 if (Path[0] == '=')
2134 llvm::outs() << sysroot << Path.substr(1);
2135 else
2136 llvm::outs() << Path;
2138 llvm::outs() << "\n";
2139 return false;
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)) {
2147 RuntimePath = Path;
2148 break;
2151 if (!RuntimePath.empty())
2152 llvm::outs() << RuntimePath << '\n';
2153 else
2154 llvm::outs() << TC.getCompilerRTPath() << '\n';
2155 return false;
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";
2162 return false;
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";
2169 return false;
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";
2180 return false;
2183 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
2184 StringRef PassedFlags = A->getValue();
2185 HandleAutocompletions(PassedFlags);
2186 return false;
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);
2193 switch (RLT) {
2194 case ToolChain::RLT_CompilerRT:
2195 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
2196 break;
2197 case ToolChain::RLT_Libgcc:
2198 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
2199 break;
2201 return false;
2204 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
2205 for (const Multilib &Multilib : TC.getMultilibs())
2206 llvm::outs() << Multilib << "\n";
2207 return false;
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";
2214 else {
2215 StringRef Suffix(Multilib.gccSuffix());
2216 assert(Suffix.front() == '/');
2217 llvm::outs() << Suffix.substr(1) << "\n";
2219 return false;
2222 if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
2223 llvm::outs() << TC.getTripleString() << "\n";
2224 return false;
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";
2230 return false;
2233 if (C.getArgs().hasArg(options::OPT_print_targets)) {
2234 llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
2235 return false;
2238 return true;
2241 enum {
2242 TopLevelAction = 0,
2243 HeadSibAction = 1,
2244 OtherSibAction = 2,
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.
2254 return Ids[A];
2256 std::string str;
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}
2280 if (!IsFirst)
2281 os << ", ";
2282 os << '"';
2283 os << A->getOffloadingKindPrefix();
2284 os << " (";
2285 os << TC->getTriple().normalize();
2286 if (BoundArch)
2287 os << ":" << BoundArch;
2288 os << ")";
2289 os << '"';
2290 os << " {" << PrintActions1(C, A, Ids, SibIndent, SibKind) << "}";
2291 IsFirst = false;
2292 SibKind = OtherSibAction;
2294 } else {
2295 const ActionList *AL = &A->getInputs();
2297 if (AL->size()) {
2298 const char *Prefix = "{";
2299 for (Action *PreRequisite : *AL) {
2300 os << Prefix << PrintActions1(C, PreRequisite, Ids, SibIndent, SibKind);
2301 Prefix = ", ";
2302 SibKind = OtherSibAction;
2304 os << "}";
2305 } else
2306 os << "{}";
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();
2315 if (!S.empty()) {
2316 offload_os << ", (" << S;
2317 if (A->getOffloadingArch())
2318 offload_os << ", " << A->getOffloadingArch();
2319 offload_os << ")";
2323 auto getSelfIndent = [](int K) -> Twine {
2324 return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : "";
2327 unsigned Id = Ids.size();
2328 Ids[A] = Id;
2329 llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", "
2330 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
2332 return Id;
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))
2348 return true;
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);
2370 continue;
2373 A->claim();
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.
2381 if (!Archs.size())
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());
2400 ActionList Inputs;
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());
2408 else
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) {
2423 ActionList Inputs;
2424 Inputs.push_back(Actions.back());
2425 Actions.pop_back();
2426 Actions.push_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();
2433 Actions.pop_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())
2444 return true;
2446 // stdin always exists.
2447 if (Value == "-")
2448 return true;
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))
2456 return true;
2458 if (getVFS().exists(Value))
2459 return true;
2461 if (TypoCorrect) {
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
2466 // directory.
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;
2476 return false;
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
2482 // understand.
2483 // Examples:
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
2494 // of an error.)
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
2513 // unknown flags.)
2514 if (IsCLMode() && Ty == types::TY_Object && !Value.startswith("/"))
2515 return true;
2517 Diag(clang::diag::err_drv_no_such_file) << Value;
2518 return false;
2521 // Get the C++20 Header Unit type corresponding to the input type.
2522 static types::ID CXXHeaderUnitType(ModuleHeaderMode HM) {
2523 switch (HM) {
2524 case HeaderMode_User:
2525 return types::TY_CXXUHeader;
2526 case HeaderMode_System:
2527 return types::TY_CXXSHeader;
2528 case HeaderMode_Default:
2529 break;
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)
2551 ? types::TY_C
2552 : types::TY_CXX;
2554 Arg *Previous = nullptr;
2555 bool ShowNote = false;
2556 for (Arg *A :
2557 Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
2558 if (Previous) {
2559 Diag(clang::diag::warn_drv_overriding_flag_option)
2560 << Previous->getSpelling() << A->getSpelling();
2561 ShowNote = true;
2563 Previous = A;
2565 if (ShowNote)
2566 Diag(clang::diag::note_drv_t_option_is_global);
2569 // Warn -x after last input file has no effect
2570 if (!IsCLMode()) {
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();
2576 } else {
2577 // In CL mode suggest /TC or /TP since -x doesn't make sense if passed via
2578 // /clang:.
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.
2592 if (InputTypeArg)
2593 InputTypeArg->claim();
2595 // stdin must be handled specially.
2596 if (memcmp(Value, "-", 2) == 0) {
2597 if (IsFlangMode()) {
2598 Ty = types::TY_Fortran;
2599 } else {
2600 // If running with -E, treat as a C input (this changes the
2601 // builtin macros, for example). This may be overridden by -ObjC
2602 // below.
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);
2610 Ty = types::TY_C;
2612 } else {
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))
2623 Ty = types::TY_CXX;
2624 else if (CCCIsCPP() || CCGenDiagnostics)
2625 Ty = types::TY_C;
2626 else
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.
2632 if (CCCIsCXX()) {
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
2652 // source file.
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) &&
2667 hasHeaderMode())
2668 Ty = CXXHeaderUnitType(CXX20HeaderType);
2669 } else {
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
2673 // object files.
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) {
2679 Ty = InputType;
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));
2694 A->claim();
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));
2702 A->claim();
2703 } else if (A->getOption().hasFlag(options::LinkerInput)) {
2704 // Just treat as object type, we could make a special type for this if
2705 // necessary.
2706 Inputs.push_back(std::make_pair(types::TY_Object, A));
2708 } else if (A->getOption().matches(options::OPT_x)) {
2709 InputTypeArg = A;
2710 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
2711 A->claim();
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.
2716 if (!InputType) {
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));
2743 namespace {
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.
2751 Compilation &C;
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 {
2761 public:
2762 typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy;
2764 enum ActionBuilderReturnCode {
2765 // The builder acted successfully on the current action.
2766 ABRT_Success,
2767 // The builder didn't have to act on the current action.
2768 ABRT_Inactive,
2769 // The builder was successful and requested the host action to not be
2770 // generated.
2771 ABRT_Ignore_Host,
2774 protected:
2775 /// Compilation associated with this builder.
2776 Compilation &C;
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;
2791 public:
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
2801 /// inactive.
2802 virtual ActionBuilderReturnCode
2803 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2804 phases::ID CurPhase, phases::ID FinalPhase,
2805 PhasesTy &Phases) {
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
2828 /// found.
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 {
2847 protected:
2848 /// Flags to signal if the user requested host-only or device-only
2849 /// compilation.
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.
2858 /// gfx906+xnack.
2859 struct TargetID {
2860 /// Target ID string which is persistent throughout the compilation.
2861 const char *ID;
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
2886 /// '-fuse-cuid='.
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;
2893 public:
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
2911 // this input.
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.
2916 IsActive = false;
2917 return ABRT_Inactive;
2920 // Set the flag to true, so that the builder acts on the current input.
2921 IsActive = true;
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();
2930 if (CUID.empty()) {
2931 if (UseCUID == CUID_Random)
2932 CUID = llvm::utohexstr(llvm::sys::Process::GetRandomNumber(),
2933 /*LowerCase=*/true);
2934 else if (UseCUID == CUID_Hash) {
2935 llvm::MD5 Hasher;
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))
2943 continue;
2944 Hasher.update(A->getAsString(Args));
2946 Hasher.final(Hash);
2947 CUID = llvm::utohexstr(Hash.low(), /*LowerCase=*/true);
2950 IA->setId(CUID);
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()) !=
2981 types::TY_Object ||
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);
2990 IsActive = true;
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;
3010 return;
3013 if (CudaDeviceActions.empty())
3014 return;
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
3018 // architecture.
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>())
3043 return false;
3045 // We don't need to support HIP.
3046 if (AssociatedOffloadKind == Action::OFK_HIP &&
3047 !C.hasOffloadToolChain<Action::OFK_HIP>())
3048 return false;
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();
3062 return true;
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();
3086 return true;
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"
3095 << "--offload";
3098 // Collect all offload arch parameters, removing duplicates.
3099 std::set<StringRef> GpuArchs;
3100 bool Error = false;
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)))
3104 continue;
3105 A->claim();
3107 for (StringRef ArchStr : llvm::split(A->getValue(), ",")) {
3108 if (A->getOption().matches(options::OPT_no_offload_arch_EQ) &&
3109 ArchStr == "all") {
3110 GpuArchs.clear();
3111 } else if (ArchStr == "native") {
3112 const ToolChain &TC = *ToolChains.front();
3113 auto GPUsOrErr = ToolChains.front()->getSystemGPUArchs(Args);
3114 if (!GPUsOrErr) {
3115 TC.getDriver().Diag(diag::err_drv_undetermined_gpu_arch)
3116 << llvm::Triple::getArchTypeName(TC.getArch())
3117 << llvm::toString(GPUsOrErr.takeError()) << "--offload-arch";
3118 continue;
3121 for (auto GPU : *GPUsOrErr) {
3122 GpuArchs.insert(Args.MakeArgString(GPU));
3124 } else {
3125 ArchStr = getCanonicalOffloadArch(ArchStr);
3126 if (ArchStr.empty()) {
3127 Error = true;
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);
3132 else
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();
3143 return true;
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);
3156 else
3157 GpuArchList.push_back(DefaultCudaArch);
3160 return Error;
3164 /// \brief CUDA action builder. It injects device code in the host backend
3165 /// action.
3166 class CudaActionBuilder final : public CudaActionBuilderBase {
3167 public:
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;
3178 return StringRef();
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 {
3193 if (!IsActive)
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
3216 // phase.
3217 for (auto Ph : Phases) {
3218 // Skip the phases that were already dealt with.
3219 if (Ph < CurPhase)
3220 continue;
3221 // We have to be consistent with the host final phase.
3222 if (Ph > FinalPhase)
3223 break;
3225 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
3226 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
3228 if (Ph == phases::Assemble)
3229 break;
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]) ||
3236 CompileDeviceOnly)
3237 continue;
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()) {
3256 CudaFatBinary =
3257 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
3259 if (!CompileDeviceOnly) {
3260 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
3261 Action::OFK_Cuda);
3262 // Clear the fat binary, it is already a dependence to an host
3263 // action.
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
3293 /// action.
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;
3304 public:
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,
3323 &Features);
3324 if (!ArchStr) {
3325 C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << IdStr;
3326 C.setContainsError();
3327 return StringRef();
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 {
3343 if (!IsActive)
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 &&
3360 !EmitAsm) {
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.
3370 ActionList AL;
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);
3376 } else {
3377 // When LTO is not enabled, we follow the conventional
3378 // compiler phases, including backend and assemble phases.
3379 ActionList AL;
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)
3385 ? types::TY_LLVM_IR
3386 : types::TY_LLVM_BC;
3387 BackendAction =
3388 C.MakeAction<BackendJobAction>(CudaDeviceActions[I], Output);
3389 } else
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
3408 // action.
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
3425 // action.
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) {
3444 LI->push_back(A);
3445 ++LI;
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 &&
3460 *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());
3468 CudaFatBinary =
3469 C.MakeAction<OffloadBundlingJobAction>(CudaDeviceActions);
3470 CudaDeviceActions.clear();
3473 return (CompileDeviceOnly && CurPhase == FinalPhase) ? ABRT_Ignore_Host
3474 : ABRT_Success;
3477 void appendLinkDeviceActions(ActionList &AL) override {
3478 if (DeviceLinkerInputs.size() == 0)
3479 return;
3481 assert(DeviceLinkerInputs.size() == GpuArchList.size() &&
3482 "Linker inputs and GPU arch list sizes do not match.");
3484 ActionList Actions;
3485 unsigned I = 0;
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)
3491 ? types::TY_LLVM_BC
3492 : types::TY_Image;
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()));
3502 ++I;
3504 DeviceLinkerInputs.clear();
3506 // If emitting LLVM, do not generate final host/device compilation action
3507 if (Args.hasArg(options::OPT_emit_llvm)) {
3508 AL.append(Actions);
3509 return;
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>(
3518 Actions,
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.
3523 AL.push_back(
3524 C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType()));
3525 } else {
3526 AL.append(Actions);
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.
3543 bool CanUseBundler;
3545 public:
3546 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
3547 const Driver::InputList &Inputs)
3548 : C(C) {
3549 // Create a specialized builder for each device toolchain.
3551 IsValid = true;
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()) {
3572 ++ValidBuilders;
3573 if (SB->canUseBundlerUnbundler())
3574 ++ValidBuildersSupportingBundling;
3577 CanUseBundler =
3578 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
3581 ~OffloadingActionBuilder() {
3582 for (auto *SB : SpecializedBuilders)
3583 delete SB;
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.
3601 Action *
3602 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
3603 phases::ID CurPhase, phases::ID FinalPhase,
3604 DeviceActionBuilder::PhasesTy &Phases) {
3605 if (!IsValid)
3606 return nullptr;
3608 if (SpecializedBuilders.empty())
3609 return HostAction;
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()) {
3622 ++InactiveBuilders;
3623 continue;
3626 auto RetCode =
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)
3633 ++IgnoringBuilders;
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
3642 // nullptr.
3643 if (IgnoringBuilders &&
3644 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
3645 return nullptr;
3647 if (DDeps.getActions().empty())
3648 return HostAction;
3650 // We have dependences we need to bundle together. We use an offload action
3651 // for that.
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
3660 /// found.
3661 bool addHostDependenceToDeviceActions(Action *&HostAction,
3662 const Arg *InputArg) {
3663 if (!IsValid)
3664 return true;
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) {
3692 if (!SB->isValid())
3693 continue;
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();
3713 return false;
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) {
3721 if (HostAction)
3722 recordHostAction(HostAction, InputArg);
3724 // Get the device actions to be appended.
3725 ActionList OffloadAL;
3726 for (auto *SB : SpecializedBuilders) {
3727 if (!SB->isValid())
3728 continue;
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;
3747 } else
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.
3752 if (HostAction)
3753 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3754 /*BoundArch=*/nullptr);
3755 return false;
3758 void appendDeviceLinkActions(ActionList &AL) {
3759 for (DeviceActionBuilder *SB : SpecializedBuilders) {
3760 if (!SB->isValid())
3761 continue;
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())
3771 return nullptr;
3773 // Let builders add host linking actions.
3774 Action* HA = nullptr;
3775 for (DeviceActionBuilder *SB : SpecializedBuilders) {
3776 if (!SB->isValid())
3777 continue;
3778 HA = SB->appendLinkHostActions(DeviceAL);
3779 // This created host action has no originating input argument, therefore
3780 // needs to set its offloading kind directly.
3781 if (HA)
3782 HA->propagateHostOffloadInfo(SB->getAssociatedOffloadKind(),
3783 /*BoundArch=*/nullptr);
3785 return HA;
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) {
3796 if (!SB->isValid())
3797 continue;
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
3808 // action.
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
3812 // far.
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())
3820 continue;
3821 auto OFKLoc = InputArgToOffloadKindMap.find(ArgLoc->second);
3822 if (OFKLoc == InputArgToOffloadKindMap.end())
3823 continue;
3824 A->propagateHostOffloadInfo(OFKLoc->second, /*BoundArch=*/nullptr);
3826 return HostAction;
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);
3856 YcArg = nullptr;
3859 Arg *FinalPhaseArg;
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
3875 // flags here.
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())
3895 continue;
3897 // Claim here to avoid the more general unused warning.
3898 InputArg->claim();
3900 // Suppress all unused style warnings with -Qunused-arguments
3901 if (Args.hasArg(options::OPT_Qunused_arguments))
3902 continue;
3904 // Special case when final phase determined by binary name, rather than
3905 // by a command-line argument with a corresponding Arg.
3906 if (CCCIsCPP())
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
3910 // more sense.
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() : "");
3920 else
3921 Diag(clang::diag::warn_drv_input_file_unused)
3922 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3923 << !!FinalPhaseArg
3924 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3925 continue;
3928 if (YcArg) {
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);
3936 assert(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
3948 // compilation.
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);
3962 return;
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)
4009 : nullptr;
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);
4021 if (PL.empty())
4022 continue;
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
4030 // required.
4031 if (!UseNewOffloadingDriver)
4032 if (OffloadBuilder->addHostDependenceToDeviceActions(Current, InputArg))
4033 break;
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);
4041 if (!Current)
4042 break;
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);
4051 Current = nullptr;
4052 break;
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);
4062 Current = nullptr;
4063 break;
4066 if (Phase == phases::Precompile && ExtractAPIAction) {
4067 ExtractAPIAction->addHeaderInput(Current);
4068 Current = nullptr;
4069 break;
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)
4080 continue;
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
4088 // required.
4089 if (!UseNewOffloadingDriver)
4090 if (OffloadBuilder->addHostDependenceToDeviceActions(Current, InputArg))
4091 break;
4093 // Try to build the offloading actions and add the result as a dependency
4094 // to the host.
4095 if (UseNewOffloadingDriver)
4096 Current = BuildOffloadingActions(C, Args, I, Current);
4098 if (Current->getType() == types::TY_Nothing)
4099 break;
4102 // If we ended with something, add to the output list.
4103 if (Current)
4104 Actions.push_back(Current);
4106 // Add any top level actions generated for offloading.
4107 if (!UseNewOffloadingDriver)
4108 OffloadBuilder->appendTopLevelActions(Actions, Current, InputArg);
4109 else if (Current)
4110 Current->propagateHostOffloadInfo(C.getActiveOffloadKinds(),
4111 /*BoundArch=*/nullptr);
4114 // Add a link action if necessary.
4116 if (LinkerInputs.empty()) {
4117 Arg *FinalPhaseArg;
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);
4127 Action *LA;
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);
4136 } else {
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())
4146 Actions.push_back(
4147 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
4149 if (Args.hasArg(options::OPT_emit_interface_stubs)) {
4150 auto PhaseList = types::getCompilationPhases(
4151 types::TY_IFS_CPP,
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)
4165 continue;
4167 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
4169 for (auto Phase : PhaseList) {
4170 switch (Phase) {
4171 default:
4172 llvm_unreachable(
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
4177 // handle this.
4178 if (InputType == types::TY_Object)
4179 break;
4181 Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP);
4182 break;
4184 case phases::IfsMerge: {
4185 assert(Phase == PhaseList.back() &&
4186 "merging must be final compilation step.");
4187 MergerInputs.push_back(Current);
4188 Current = nullptr;
4189 break;
4194 // If we ended with something, add to the output list.
4195 if (Current)
4196 Actions.push_back(Current);
4199 // Add an interface stubs merge action if necessary.
4200 if (!MergerInputs.empty())
4201 Actions.push_back(
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.
4209 Actions.clear();
4210 Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C);
4211 Actions.push_back(
4212 C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing));
4213 for (auto &I : Inputs)
4214 I.second->claim();
4217 // Call validator for dxil when -Vd not in Args.
4218 if (C.getDefaultToolChain().getTriple().isDXIL()) {
4219 // Only add action when needValidation.
4220 const auto &TC =
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,
4237 StringRef ArchStr,
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;
4247 return StringRef();
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;
4252 return StringRef();
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());
4261 if (!HIPTriple)
4262 return StringRef();
4263 auto Arch = parseTargetID(*HIPTriple, ArchStr, &Features);
4264 if (!Arch) {
4265 C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << ArchStr;
4266 C.setContainsError();
4267 return StringRef();
4269 return Args.MakeArgStringRef(getCanonicalTargetID(*Arch, Features));
4272 // If the input isn't CUDA or HIP just return the architecture.
4273 return ArchStr;
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 {
4293 if (!TC)
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)
4301 << "--offload"
4302 << (Args.hasArgNoClaim(options::OPT_offload_arch_EQ)
4303 ? "--offload-arch"
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()) {
4316 Arg->claim();
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);
4328 if (!GPUsOrErr) {
4329 if (SuppressError)
4330 llvm::consumeError(GPUsOrErr.takeError());
4331 else
4332 TC->getDriver().Diag(diag::err_drv_undetermined_gpu_arch)
4333 << llvm::Triple::getArchTypeName(TC->getArch())
4334 << llvm::toString(GPUsOrErr.takeError()) << "--offload-arch";
4335 continue;
4338 for (auto ArchStr : *GPUsOrErr) {
4339 Archs.insert(
4340 getCanonicalArchString(C, Args, Args.MakeArgString(ArchStr),
4341 TC->getTriple(), SuppressError));
4343 } else {
4344 StringRef ArchStr = getCanonicalArchString(
4345 C, Args, Arch, TC->getTriple(), SuppressError);
4346 if (ArchStr.empty())
4347 return Archs;
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") {
4354 Archs.clear();
4355 } else {
4356 StringRef ArchStr = getCanonicalArchString(
4357 C, Args, Arch, TC->getTriple(), SuppressError);
4358 if (ArchStr.empty())
4359 return Archs;
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.
4373 if (SuppressError)
4374 return Archs;
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());
4383 } else {
4384 Args.ClaimAllArgs(options::OPT_offload_arch_EQ);
4385 Args.ClaimAllArgs(options::OPT_no_offload_arch_EQ);
4388 return Archs;
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))
4401 return HostAction;
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())
4418 continue;
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)))
4426 continue;
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())
4438 return HostAction;
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.");
4445 break;
4448 auto TCAndArch = TCAndArchs.begin();
4449 for (Action *&A : DeviceActions) {
4450 if (A->getType() == types::TY_Nothing)
4451 continue;
4453 // Propagate the ToolChain so we can use it in ConstructPhaseAction.
4454 A->propagateDeviceOffloadInfo(Kind, TCAndArch->second.data(),
4455 TCAndArch->first);
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);
4473 ++TCAndArch;
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))
4483 continue;
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()));
4494 ++TCAndArch;
4498 if (offloadDeviceOnly())
4499 return C.MakeAction<OffloadAction>(DDeps, types::TY_Nothing);
4501 if (OffloadActions.empty())
4502 return HostAction;
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,
4515 false)) {
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);
4522 } else {
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)
4551 return Input;
4553 // Build the appropriate action.
4554 switch (Phase) {
4555 case phases::Link:
4556 llvm_unreachable("link action invalid here.");
4557 case phases::IfsMerge:
4558 llvm_unreachable("ifsmerge action invalid here.");
4559 case phases::Preprocess: {
4560 types::ID OutputTy;
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;
4566 } else {
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) &&
4576 !CCGenDiagnostics)
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();
4598 if (ModName)
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) {
4633 types::ID Output =
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) {
4639 types::ID Output =
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,
4648 false) ||
4649 TargetDeviceOffloadKind == Action::OFK_OpenMP))) {
4650 types::ID Output =
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)))
4657 ? types::TY_LLVM_IR
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
4691 // -fsyntax-only.
4692 if (FinalOutput) {
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)))
4704 ++NumOutputs;
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
4741 // process.
4742 const char *LinkingOutput = nullptr;
4743 if (isa<LipoJobAction>(A)) {
4744 if (FinalOutput)
4745 LinkingOutput = FinalOutput->getValue();
4746 else
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();
4768 if (!ProcStat)
4769 return;
4771 const char *LinkingOutput = nullptr;
4772 if (FinalOutput)
4773 LinkingOutput = FinalOutput->getValue();
4774 else if (!Cmd.getOutputFilenames().empty())
4775 LinkingOutput = Cmd.getOutputFilenames().front().c_str();
4776 else
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"
4786 << ", user="
4787 << format("%.3f", ProcStat->UserTime.count() / 1000.) << " ms"
4788 << ", mem=" << ProcStat->PeakMemory << " Kb\n";
4789 } else {
4790 // CSV format.
4791 std::string Buffer;
4792 llvm::raw_string_ostream Out(Buffer);
4793 llvm::sys::printArg(Out, llvm::sys::path::filename(Cmd.getExecutable()),
4794 /*Quote*/ true);
4795 Out << ',';
4796 llvm::sys::printArg(Out, LinkingOutput, true);
4797 Out << ',' << ProcStat->TotalTime.count() << ','
4798 << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory
4799 << '\n';
4800 Out.flush();
4801 std::error_code EC;
4802 llvm::raw_fd_ostream OS(CCPrintStatReportFilename, EC,
4803 llvm::sys::fs::OF_Append |
4804 llvm::sys::fs::OF_Text);
4805 if (EC)
4806 return;
4807 auto L = OS.lock();
4808 if (!L) {
4809 llvm::errs() << "ERROR: Cannot lock file "
4810 << CCPrintStatReportFilename << ": "
4811 << toString(L.takeError()) << "\n";
4812 return;
4814 OS << Buffer;
4815 OS.flush();
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))
4824 return;
4826 // Claim -fdriver-only here.
4827 (void)C.getArgs().hasArg(options::OPT_fdriver_only);
4828 // Claim -### here.
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
4838 // printed.
4839 if (!A->isClaimed()) {
4840 if (A->getOption().hasFlag(options::NoArgumentUnused))
4841 continue;
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;
4852 break;
4856 if (DuplicateClaimed)
4857 continue;
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());
4869 namespace {
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.
4886 bool SaveTemps;
4887 bool EmbedBitcode;
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)
4897 return nullptr;
4899 Action *CurAction = *Inputs.begin();
4900 if (CanBeCollapsed &&
4901 !CurAction->isCollapsingWithNextDependentActionLegal())
4902 return nullptr;
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)) {
4912 CurAction =
4913 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
4914 if (CanBeCollapsed &&
4915 !CurAction->isCollapsingWithNextDependentActionLegal())
4916 return nullptr;
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())
4924 return nullptr;
4925 SavedOffloadAction.push_back(OA);
4926 return dyn_cast<JobAction>(CurAction);
4928 return nullptr;
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
4955 /// collapsed.
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.
4979 const Tool *
4980 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
4981 ActionList &Inputs,
4982 ActionList &CollapsedOffloadAction) {
4983 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
4984 return nullptr;
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)
4989 return nullptr;
4991 // Get compiler tool.
4992 const Tool *T = TC.SelectTool(*CJ);
4993 if (!T)
4994 return nullptr;
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()))
5000 return nullptr;
5002 // When using -fembed-bitcode, it is required to have the same tool (clang)
5003 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
5004 if (EmbedBitcode) {
5005 const Tool *BT = TC.SelectTool(*BJ);
5006 if (BT == T)
5007 return nullptr;
5010 if (!T->hasIntegratedAssembler())
5011 return nullptr;
5013 Inputs = CJ->getInputs();
5014 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
5015 /*NumElements=*/3);
5016 return T;
5018 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
5019 ActionList &Inputs,
5020 ActionList &CollapsedOffloadAction) {
5021 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
5022 return nullptr;
5023 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
5024 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
5025 if (!AJ || !BJ)
5026 return nullptr;
5028 // Get backend tool.
5029 const Tool *T = TC.SelectTool(*BJ);
5030 if (!T)
5031 return nullptr;
5033 if (!T->hasIntegratedAssembler())
5034 return nullptr;
5036 Inputs = BJ->getInputs();
5037 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
5038 /*NumElements=*/2);
5039 return T;
5041 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
5042 ActionList &Inputs,
5043 ActionList &CollapsedOffloadAction) {
5044 if (ActionInfo.size() < 2)
5045 return nullptr;
5046 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
5047 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
5048 if (!BJ || !CJ)
5049 return nullptr;
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;
5061 break;
5063 if (!InputIsBitcode && !canCollapsePreprocessorAction())
5064 return nullptr;
5066 // Get compiler tool.
5067 const Tool *T = TC.SelectTool(*CJ);
5068 if (!T)
5069 return nullptr;
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()))
5075 return nullptr;
5077 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
5078 return nullptr;
5080 Inputs = CJ->getInputs();
5081 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
5082 /*NumElements=*/2);
5083 return T;
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())
5093 return;
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);
5102 continue;
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());
5111 Inputs = NewInputs;
5114 public:
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
5145 AI.JA =
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);
5160 if (!T)
5161 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
5162 if (!T)
5163 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
5164 if (!T) {
5165 Inputs = BaseAction->getInputs();
5166 T = TC.SelectTool(*BaseAction);
5169 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
5170 return T;
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>
5197 &CachedResults,
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;
5209 return 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>
5216 &CachedResults,
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 _
5239 // \
5240 // Host Action 1 ---> OffloadAction -> Host Action 2
5242 // d) Specify a host dependence to a device action.
5243 // Host Action 1 _
5244 // \
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
5253 // the job for it.
5254 if (OA->hasSingleDeviceDependence() || !OA->hasHostDependence()) {
5255 InputInfoList DevA;
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()));
5263 return DevA;
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);
5291 return Inputs;
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();
5299 Input.claim();
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));
5315 else
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);
5333 if (!T)
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();
5366 break;
5370 // ... except dsymutil actions, which use their actual input as the base
5371 // input.
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));
5387 } else {
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.
5395 InputInfo Result;
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,
5417 MultipleArchs ||
5418 UI.DependentOffloadKind == Action::OFK_HIP,
5419 OffloadingPrefix),
5420 BaseInput);
5421 // Save the unbundling result.
5422 UnbundlingResults.push_back(CurI);
5424 // Get the unique string identifier for this dependence and cache the
5425 // result.
5426 StringRef Arch;
5427 if (TargetDeviceOffloadKind == Action::OFK_HIP) {
5428 if (UI.DependentOffloadKind == Action::OFK_Host)
5429 Arch = StringRef();
5430 else
5431 Arch = UI.DependentBoundArch;
5432 } else
5433 Arch = BoundArch;
5435 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
5436 UI.DependentOffloadKind)}] = {
5437 CurI};
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)};
5449 else {
5450 // We only have to generate a prefix for the host if this is not a top-level
5451 // action.
5452 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
5453 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
5454 /*CreatePrefixForHost=*/isa<OffloadPackagerJobAction>(A) ||
5455 !(A->getOffloadingHostActiveKinds() == Action::OFK_None ||
5456 AtTopLevel));
5457 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
5458 AtTopLevel, MultipleArchs,
5459 OffloadingPrefix),
5460 BaseInput);
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();
5468 if (i + 1 != e)
5469 llvm::errs() << ", ";
5471 if (UnbundlingResults.empty())
5472 llvm::errs() << "], output: " << Result.getAsString() << "\n";
5473 else {
5474 llvm::errs() << "], outputs: [";
5475 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
5476 llvm::errs() << UnbundlingResults[i].getAsString();
5477 if (i + 1 != e)
5478 llvm::errs() << ", ";
5480 llvm::errs() << "] \n";
5482 } else {
5483 if (UnbundlingResults.empty())
5484 T->ConstructJob(
5485 C, *JA, Result, InputInfos,
5486 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
5487 LinkingOutput);
5488 else
5489 T->ConstructJobMultipleOutputs(
5490 C, *JA, UnbundlingResults, InputInfos,
5491 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
5492 LinkingOutput);
5494 return {Result};
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,
5507 StringRef BaseName,
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.
5526 Extension = "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))
5537 return true;
5538 if (isa<OffloadAction>(JA) && isa<PreprocessJobAction>(JA.getInputs()[0]))
5539 return true;
5540 if (isa<OffloadBundlingJobAction>(JA) &&
5541 HasPreprocessOutput(*(JA.getInputs()[0])))
5542 return true;
5543 return false;
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();
5564 return "";
5566 } else {
5567 if (MultipleArchs && !BoundArch.empty()) {
5568 TmpName = GetTemporaryDirectory(Prefix);
5569 llvm::sys::path::append(TmpName,
5570 Twine(Prefix) + "-" + BoundArch + "." + Suffix);
5571 } else {
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.
5580 // The behavior is:
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
5584 // output path
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();
5603 else
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,
5614 bool MultipleArchs,
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);
5634 StringRef NameArg;
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),
5639 &JA);
5642 // Default to writing to stdout?
5643 if (AtTopLevel && !CCGenDiagnostics && HasPreprocessOutput(JA)) {
5644 return "-";
5647 if (JA.getType() == types::TY_ModuleFile &&
5648 C.getArgs().getLastArg(options::OPT_module_file_info)) {
5649 return "-";
5652 if (IsDXCMode() && !C.getArgs().hasArg(options::OPT_o))
5653 return "-";
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()),
5664 &JA);
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)) ||
5682 CCGenDiagnostics) {
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("");
5691 StringRef BaseName;
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
5699 // fails.
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;
5705 else
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.
5714 StringRef Val =
5715 C.getArgs()
5716 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
5717 ->getValue();
5718 NamedOutput =
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.
5724 StringRef Val =
5725 C.getArgs()
5726 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
5727 ->getValue();
5728 NamedOutput =
5729 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
5730 } else if (JA.getType() == types::TY_Image) {
5731 if (IsCLMode()) {
5732 // clang-cl uses BaseName for the executable name.
5733 NamedOutput =
5734 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
5735 } else {
5736 SmallString<128> Output(getDefaultImageName());
5737 // HIP image for device compilation with -fno-gpu-rdc is per compilation
5738 // unit.
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) {
5744 Output = BaseName;
5745 llvm::sys::path::replace_extension(Output, "");
5747 Output += OffloadingPrefix;
5748 if (MultipleArchs && !BoundArch.empty()) {
5749 Output += "-";
5750 Output.append(BoundArch);
5752 if (UseOutExtension)
5753 Output += ".out";
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)) {
5760 StringRef Val =
5761 C.getArgs()
5762 .getLastArg(options::OPT__SLASH_o)
5763 ->getValue();
5764 NamedOutput =
5765 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
5766 } else {
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()) {
5776 Suffixed += "-";
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,
5791 false)) ||
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())))
5798 Suffixed += ".tmp";
5799 Suffixed += '.';
5800 Suffixed += Suffix;
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.
5824 if (SameFile) {
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;
5838 else
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) {
5853 if (Dir.empty())
5854 continue;
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))
5864 return *P;
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()))
5882 return *P;
5884 if (auto P = SearchPaths(TC.getFilePaths()))
5885 return *P;
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)))
5901 return true;
5902 llvm::sys::path::remove_filename(Dir);
5903 return false;
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());
5917 } else {
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))
5942 return *P;
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);
5951 if (EC) {
5952 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5953 return "";
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);
5962 if (EC) {
5963 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5964 return "";
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))
5981 Output += ".pch";
5982 } else {
5983 if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
5984 Output = YcArg->getValue();
5985 if (Output.empty())
5986 Output = BaseName;
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()];
5996 if (!TC) {
5997 switch (Target.getOS()) {
5998 case llvm::Triple::AIX:
5999 TC = std::make_unique<toolchains::AIX>(*this, Target, Args);
6000 break;
6001 case llvm::Triple::Haiku:
6002 TC = std::make_unique<toolchains::Haiku>(*this, Target, Args);
6003 break;
6004 case llvm::Triple::Ananas:
6005 TC = std::make_unique<toolchains::Ananas>(*this, Target, Args);
6006 break;
6007 case llvm::Triple::CloudABI:
6008 TC = std::make_unique<toolchains::CloudABI>(*this, Target, Args);
6009 break;
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);
6017 break;
6018 case llvm::Triple::DragonFly:
6019 TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args);
6020 break;
6021 case llvm::Triple::OpenBSD:
6022 TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args);
6023 break;
6024 case llvm::Triple::NetBSD:
6025 TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args);
6026 break;
6027 case llvm::Triple::FreeBSD:
6028 if (Target.isPPC())
6029 TC = std::make_unique<toolchains::PPCFreeBSDToolChain>(*this, Target,
6030 Args);
6031 else
6032 TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args);
6033 break;
6034 case llvm::Triple::Minix:
6035 TC = std::make_unique<toolchains::Minix>(*this, Target, Args);
6036 break;
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,
6041 Args);
6042 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
6043 !Target.hasEnvironment())
6044 TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
6045 Args);
6046 else if (Target.isPPC())
6047 TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
6048 Args);
6049 else if (Target.getArch() == llvm::Triple::ve)
6050 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
6052 else
6053 TC = std::make_unique<toolchains::Linux>(*this, Target, Args);
6054 break;
6055 case llvm::Triple::NaCl:
6056 TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
6057 break;
6058 case llvm::Triple::Fuchsia:
6059 TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args);
6060 break;
6061 case llvm::Triple::Solaris:
6062 TC = std::make_unique<toolchains::Solaris>(*this, Target, Args);
6063 break;
6064 case llvm::Triple::CUDA:
6065 TC = std::make_unique<toolchains::NVPTXToolChain>(*this, Target, Args);
6066 break;
6067 case llvm::Triple::AMDHSA:
6068 TC = std::make_unique<toolchains::ROCMToolChain>(*this, Target, Args);
6069 break;
6070 case llvm::Triple::AMDPAL:
6071 case llvm::Triple::Mesa3D:
6072 TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
6073 break;
6074 case llvm::Triple::Win32:
6075 switch (Target.getEnvironment()) {
6076 default:
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);
6081 else
6082 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
6083 break;
6084 case llvm::Triple::GNU:
6085 TC = std::make_unique<toolchains::MinGW>(*this, Target, Args);
6086 break;
6087 case llvm::Triple::Itanium:
6088 TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
6089 Args);
6090 break;
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);
6097 else
6098 TC =
6099 std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
6100 break;
6102 break;
6103 case llvm::Triple::PS4:
6104 TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args);
6105 break;
6106 case llvm::Triple::PS5:
6107 TC = std::make_unique<toolchains::PS5CPU>(*this, Target, Args);
6108 break;
6109 case llvm::Triple::Contiki:
6110 TC = std::make_unique<toolchains::Contiki>(*this, Target, Args);
6111 break;
6112 case llvm::Triple::Hurd:
6113 TC = std::make_unique<toolchains::Hurd>(*this, Target, Args);
6114 break;
6115 case llvm::Triple::ZOS:
6116 TC = std::make_unique<toolchains::ZOS>(*this, Target, Args);
6117 break;
6118 case llvm::Triple::ShaderModel:
6119 TC = std::make_unique<toolchains::HLSLToolChain>(*this, Target, Args);
6120 break;
6121 default:
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);
6127 break;
6128 case llvm::Triple::tcele:
6129 TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
6130 break;
6131 case llvm::Triple::hexagon:
6132 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
6133 Args);
6134 break;
6135 case llvm::Triple::lanai:
6136 TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
6137 break;
6138 case llvm::Triple::xcore:
6139 TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
6140 break;
6141 case llvm::Triple::wasm32:
6142 case llvm::Triple::wasm64:
6143 TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args);
6144 break;
6145 case llvm::Triple::avr:
6146 TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
6147 break;
6148 case llvm::Triple::msp430:
6149 TC =
6150 std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
6151 break;
6152 case llvm::Triple::riscv32:
6153 case llvm::Triple::riscv64:
6154 if (toolchains::RISCVToolChain::hasGCCToolchain(*this, Args))
6155 TC =
6156 std::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
6157 else
6158 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
6159 break;
6160 case llvm::Triple::ve:
6161 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
6162 break;
6163 case llvm::Triple::spirv32:
6164 case llvm::Triple::spirv64:
6165 TC = std::make_unique<toolchains::SPIRVToolChain>(*this, Target, Args);
6166 break;
6167 case llvm::Triple::csky:
6168 TC = std::make_unique<toolchains::CSKYToolChain>(*this, Target, Args);
6169 break;
6170 default:
6171 if (Target.getVendor() == llvm::Triple::Myriad)
6172 TC = std::make_unique<toolchains::MyriadToolChain>(*this, Target,
6173 Args);
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);
6180 else
6181 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
6186 return *TC;
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()];
6195 if (!TC) {
6196 // Categorized by offload kind > arch rather than OS > arch like
6197 // the normal getToolChain call, as it seems a reasonable way to categorize
6198 // things.
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,
6205 HostTC, Args);
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,
6210 HostTC, Args);
6211 break;
6213 default:
6214 break;
6218 return *TC;
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()))
6225 return false;
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))
6231 return false;
6233 return true;
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()))
6240 return false;
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))
6245 return false;
6247 return true;
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))
6253 return true;
6254 return false;
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) {
6264 HadExtra = false;
6266 Major = Minor = Micro = 0;
6267 if (Str.empty())
6268 return false;
6270 if (Str.consumeInteger(10, Major))
6271 return false;
6272 if (Str.empty())
6273 return true;
6274 if (Str[0] != '.')
6275 return false;
6277 Str = Str.drop_front(1);
6279 if (Str.consumeInteger(10, Minor))
6280 return false;
6281 if (Str.empty())
6282 return true;
6283 if (Str[0] != '.')
6284 return false;
6285 Str = Str.drop_front(1);
6287 if (Str.consumeInteger(10, Micro))
6288 return false;
6289 if (!Str.empty())
6290 HadExtra = true;
6291 return true;
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) {
6302 if (Str.empty())
6303 return false;
6305 unsigned CurDigit = 0;
6306 while (CurDigit < Digits.size()) {
6307 unsigned Digit;
6308 if (Str.consumeInteger(10, Digit))
6309 return false;
6310 Digits[CurDigit] = Digit;
6311 if (Str.empty())
6312 return true;
6313 if (Str[0] != '.')
6314 return false;
6315 Str = Str.drop_front(1);
6316 CurDigit++;
6319 // More digits than requested, bail out...
6320 return false;
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;
6333 } else {
6334 ExcludedFlagsBitmask |= options::CLOption;
6336 if (IsDXCMode()) {
6337 // Include DXC and Core options.
6338 IncludedFlagsBitmask |= options::DXCOption;
6339 IncludedFlagsBitmask |= options::CLDXCOption;
6340 IncludedFlagsBitmask |= options::CoreOption;
6341 } else {
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) {
6351 switch (Mode) {
6352 case GCCMode:
6353 return "clang";
6354 case GXXMode:
6355 return "clang++";
6356 case CPPMode:
6357 return "clang-cpp";
6358 case CLMode:
6359 return "clang-cl";
6360 case FlangMode:
6361 return "flang";
6362 case DXCMode:
6363 return "clang-dxc";
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))
6377 return true;
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))
6382 return true;
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))
6387 return true;
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))
6392 return true;
6393 return 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))
6403 continue;
6404 Opt = Arg;
6406 if (Opt.empty())
6407 Opt = ToolChain::getTargetAndModeFromProgramName(ProgName).DriverMode;
6408 return Opt.consume_front(OptName) ? Opt : "";
6411 bool driver::IsClangCL(StringRef DriverMode) { return DriverMode.equals("cl"); }