1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "clang/Driver/Driver.h"
10 #include "ToolChains/AIX.h"
11 #include "ToolChains/AMDGPU.h"
12 #include "ToolChains/AMDGPUOpenMP.h"
13 #include "ToolChains/AVR.h"
14 #include "ToolChains/Ananas.h"
15 #include "ToolChains/BareMetal.h"
16 #include "ToolChains/CSKYToolChain.h"
17 #include "ToolChains/Clang.h"
18 #include "ToolChains/CloudABI.h"
19 #include "ToolChains/Contiki.h"
20 #include "ToolChains/CrossWindows.h"
21 #include "ToolChains/Cuda.h"
22 #include "ToolChains/Darwin.h"
23 #include "ToolChains/DragonFly.h"
24 #include "ToolChains/FreeBSD.h"
25 #include "ToolChains/Fuchsia.h"
26 #include "ToolChains/Gnu.h"
27 #include "ToolChains/HIPAMD.h"
28 #include "ToolChains/HIPSPV.h"
29 #include "ToolChains/HLSL.h"
30 #include "ToolChains/Haiku.h"
31 #include "ToolChains/Hexagon.h"
32 #include "ToolChains/Hurd.h"
33 #include "ToolChains/Lanai.h"
34 #include "ToolChains/Linux.h"
35 #include "ToolChains/MSP430.h"
36 #include "ToolChains/MSVC.h"
37 #include "ToolChains/MinGW.h"
38 #include "ToolChains/Minix.h"
39 #include "ToolChains/MipsLinux.h"
40 #include "ToolChains/Myriad.h"
41 #include "ToolChains/NaCl.h"
42 #include "ToolChains/NetBSD.h"
43 #include "ToolChains/OpenBSD.h"
44 #include "ToolChains/PPCFreeBSD.h"
45 #include "ToolChains/PPCLinux.h"
46 #include "ToolChains/PS4CPU.h"
47 #include "ToolChains/RISCVToolchain.h"
48 #include "ToolChains/SPIRV.h"
49 #include "ToolChains/Solaris.h"
50 #include "ToolChains/TCE.h"
51 #include "ToolChains/VEToolchain.h"
52 #include "ToolChains/WebAssembly.h"
53 #include "ToolChains/XCore.h"
54 #include "ToolChains/ZOS.h"
55 #include "clang/Basic/TargetID.h"
56 #include "clang/Basic/Version.h"
57 #include "clang/Config/config.h"
58 #include "clang/Driver/Action.h"
59 #include "clang/Driver/Compilation.h"
60 #include "clang/Driver/DriverDiagnostic.h"
61 #include "clang/Driver/InputInfo.h"
62 #include "clang/Driver/Job.h"
63 #include "clang/Driver/Options.h"
64 #include "clang/Driver/Phases.h"
65 #include "clang/Driver/SanitizerArgs.h"
66 #include "clang/Driver/Tool.h"
67 #include "clang/Driver/ToolChain.h"
68 #include "clang/Driver/Types.h"
69 #include "llvm/ADT/ArrayRef.h"
70 #include "llvm/ADT/STLExtras.h"
71 #include "llvm/ADT/SmallSet.h"
72 #include "llvm/ADT/StringExtras.h"
73 #include "llvm/ADT/StringRef.h"
74 #include "llvm/ADT/StringSet.h"
75 #include "llvm/ADT/StringSwitch.h"
76 #include "llvm/Config/llvm-config.h"
77 #include "llvm/MC/TargetRegistry.h"
78 #include "llvm/Option/Arg.h"
79 #include "llvm/Option/ArgList.h"
80 #include "llvm/Option/OptSpecifier.h"
81 #include "llvm/Option/OptTable.h"
82 #include "llvm/Option/Option.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/ErrorHandling.h"
85 #include "llvm/Support/ExitCodes.h"
86 #include "llvm/Support/FileSystem.h"
87 #include "llvm/Support/FormatVariadic.h"
88 #include "llvm/Support/Host.h"
89 #include "llvm/Support/MD5.h"
90 #include "llvm/Support/Path.h"
91 #include "llvm/Support/PrettyStackTrace.h"
92 #include "llvm/Support/Process.h"
93 #include "llvm/Support/Program.h"
94 #include "llvm/Support/StringSaver.h"
95 #include "llvm/Support/VirtualFileSystem.h"
96 #include "llvm/Support/raw_ostream.h"
97 #include <cstdlib> // ::getenv
102 #include <unistd.h> // getpid
105 using namespace clang::driver;
106 using namespace clang;
107 using namespace llvm::opt;
109 static llvm::Optional<llvm::Triple>
110 getOffloadTargetTriple(const Driver &D, const ArgList &Args) {
111 auto OffloadTargets = Args.getAllArgValues(options::OPT_offload_EQ);
112 // Offload compilation flow does not support multiple targets for now. We
113 // need the HIPActionBuilder (and possibly the CudaActionBuilder{,Base}too)
114 // to support multiple tool chains first.
115 switch (OffloadTargets.size()) {
117 D.Diag(diag::err_drv_only_one_offload_target_supported);
120 D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << "";
125 return llvm::Triple(OffloadTargets[0]);
128 static llvm::Optional<llvm::Triple>
129 getNVIDIAOffloadTargetTriple(const Driver &D, const ArgList &Args,
130 const llvm::Triple &HostTriple) {
131 if (!Args.hasArg(options::OPT_offload_EQ)) {
132 return llvm::Triple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
133 : "nvptx-nvidia-cuda");
135 auto TT = getOffloadTargetTriple(D, Args);
136 if (TT && (TT->getArch() == llvm::Triple::spirv32 ||
137 TT->getArch() == llvm::Triple::spirv64)) {
138 if (Args.hasArg(options::OPT_emit_llvm))
140 D.Diag(diag::err_drv_cuda_offload_only_emit_bc);
143 D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str();
146 static llvm::Optional<llvm::Triple>
147 getHIPOffloadTargetTriple(const Driver &D, const ArgList &Args) {
148 if (!Args.hasArg(options::OPT_offload_EQ)) {
149 return llvm::Triple("amdgcn-amd-amdhsa"); // Default HIP triple.
151 auto TT = getOffloadTargetTriple(D, Args);
154 if (TT->getArch() == llvm::Triple::amdgcn &&
155 TT->getVendor() == llvm::Triple::AMD &&
156 TT->getOS() == llvm::Triple::AMDHSA)
158 if (TT->getArch() == llvm::Triple::spirv64)
160 D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str();
165 std::string Driver::GetResourcesPath(StringRef BinaryPath,
166 StringRef CustomResourceDir) {
167 // Since the resource directory is embedded in the module hash, it's important
168 // that all places that need it call this function, so that they get the
169 // exact same string ("a/../b/" and "b/" get different hashes, for example).
171 // Dir is bin/ or lib/, depending on where BinaryPath is.
172 std::string Dir = std::string(llvm::sys::path::parent_path(BinaryPath));
174 SmallString<128> P(Dir);
175 if (CustomResourceDir != "") {
176 llvm::sys::path::append(P, CustomResourceDir);
178 // On Windows, libclang.dll is in bin/.
179 // On non-Windows, libclang.so/.dylib is in lib/.
180 // With a static-library build of libclang, LibClangPath will contain the
181 // path of the embedding binary, which for LLVM binaries will be in bin/.
182 // ../lib gets us to lib/ in both cases.
183 P = llvm::sys::path::parent_path(Dir);
184 llvm::sys::path::append(P, CLANG_INSTALL_LIBDIR_BASENAME, "clang",
185 CLANG_VERSION_STRING);
188 return std::string(P.str());
191 Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
192 DiagnosticsEngine &Diags, std::string Title,
193 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
194 : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
195 SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
196 Offload(OffloadHostDevice), CXX20HeaderType(HeaderMode_None),
197 ModulesModeCXX20(false), LTOMode(LTOK_None),
198 ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
199 DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false),
200 CCPrintHeaders(false), CCLogDiagnostics(false), CCGenDiagnostics(false),
201 CCPrintProcessStats(false), TargetTriple(TargetTriple), Saver(Alloc),
202 CheckInputsExist(true), ProbePrecompiled(true),
203 SuppressMissingInputWarning(false) {
204 // Provide a sane fallback if no VFS is specified.
206 this->VFS = llvm::vfs::getRealFileSystem();
208 Name = std::string(llvm::sys::path::filename(ClangExecutable));
209 Dir = std::string(llvm::sys::path::parent_path(ClangExecutable));
210 InstalledDir = Dir; // Provide a sensible default installed dir.
212 if ((!SysRoot.empty()) && llvm::sys::path::is_relative(SysRoot)) {
213 // Prepend InstalledDir if SysRoot is relative
214 SmallString<128> P(InstalledDir);
215 llvm::sys::path::append(P, SysRoot);
216 SysRoot = std::string(P);
219 #if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
220 SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
222 #if defined(CLANG_CONFIG_FILE_USER_DIR)
223 UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
226 // Compute the path to the resource directory.
227 ResourceDir = GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
230 void Driver::setDriverMode(StringRef Value) {
231 static const std::string OptName =
232 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
233 if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
234 .Case("gcc", GCCMode)
235 .Case("g++", GXXMode)
236 .Case("cpp", CPPMode)
238 .Case("flang", FlangMode)
239 .Case("dxc", DXCMode)
243 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
246 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
248 bool &ContainsError) {
249 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
250 ContainsError = false;
252 unsigned IncludedFlagsBitmask;
253 unsigned ExcludedFlagsBitmask;
254 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
255 getIncludeExcludeOptionFlagMasks(IsClCompatMode);
257 // Make sure that Flang-only options don't pollute the Clang output
258 // TODO: Make sure that Clang-only options don't pollute Flang output
260 ExcludedFlagsBitmask |= options::FlangOnlyOption;
262 unsigned MissingArgIndex, MissingArgCount;
264 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
265 IncludedFlagsBitmask, ExcludedFlagsBitmask);
267 // Check for missing argument error.
268 if (MissingArgCount) {
269 Diag(diag::err_drv_missing_argument)
270 << Args.getArgString(MissingArgIndex) << MissingArgCount;
272 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
273 SourceLocation()) > DiagnosticsEngine::Warning;
276 // Check for unsupported options.
277 for (const Arg *A : Args) {
278 if (A->getOption().hasFlag(options::Unsupported)) {
280 auto ArgString = A->getAsString(Args);
282 if (getOpts().findNearest(
283 ArgString, Nearest, IncludedFlagsBitmask,
284 ExcludedFlagsBitmask | options::Unsupported) > 1) {
285 DiagID = diag::err_drv_unsupported_opt;
286 Diag(DiagID) << ArgString;
288 DiagID = diag::err_drv_unsupported_opt_with_suggestion;
289 Diag(DiagID) << ArgString << Nearest;
291 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
292 DiagnosticsEngine::Warning;
296 // Warn about -mcpu= without an argument.
297 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
298 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
299 ContainsError |= Diags.getDiagnosticLevel(
300 diag::warn_drv_empty_joined_argument,
301 SourceLocation()) > DiagnosticsEngine::Warning;
305 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
307 auto ArgString = A->getAsString(Args);
309 if (getOpts().findNearest(ArgString, Nearest, IncludedFlagsBitmask,
310 ExcludedFlagsBitmask) > 1) {
311 if (getOpts().findNearest(ArgString, Nearest, options::CC1Option) == 0 &&
313 DiagID = diag::err_drv_unknown_argument_with_suggestion;
314 Diags.Report(DiagID) << ArgString << "-Xclang " + Nearest;
316 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
317 : diag::err_drv_unknown_argument;
318 Diags.Report(DiagID) << ArgString;
322 ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
323 : diag::err_drv_unknown_argument_with_suggestion;
324 Diags.Report(DiagID) << ArgString << Nearest;
326 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
327 DiagnosticsEngine::Warning;
330 for (const Arg *A : Args.filtered(options::OPT_o)) {
331 if (ArgStrings[A->getIndex()] == A->getSpelling())
334 // Warn on joined arguments that are similar to a long argument.
335 std::string ArgString = ArgStrings[A->getIndex()];
337 if (getOpts().findNearest("-" + ArgString, Nearest, IncludedFlagsBitmask,
338 ExcludedFlagsBitmask) == 0)
339 Diags.Report(diag::warn_drv_potentially_misspelled_joined_argument)
340 << A->getAsString(Args) << Nearest;
346 // Determine which compilation mode we are in. We look for options which
347 // affect the phase, starting with the earliest phases, and record which
348 // option we used to determine the final phase.
349 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
350 Arg **FinalPhaseArg) const {
351 Arg *PhaseArg = nullptr;
352 phases::ID FinalPhase;
354 // -{E,EP,P,M,MM} only run the preprocessor.
355 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
356 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
357 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
358 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P)) ||
360 FinalPhase = phases::Preprocess;
362 // --precompile only runs up to precompilation.
363 // Options that cause the output of C++20 compiled module interfaces or
364 // header units have the same effect.
365 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile)) ||
366 (PhaseArg = DAL.getLastArg(options::OPT_extract_api)) ||
367 (PhaseArg = DAL.getLastArg(options::OPT_fmodule_header,
368 options::OPT_fmodule_header_EQ))) {
369 FinalPhase = phases::Precompile;
370 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
371 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
372 (PhaseArg = DAL.getLastArg(options::OPT_print_supported_cpus)) ||
373 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
374 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
375 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
376 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
377 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
378 (PhaseArg = DAL.getLastArg(options::OPT__analyze)) ||
379 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
380 FinalPhase = phases::Compile;
382 // -S only runs up to the backend.
383 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
384 FinalPhase = phases::Backend;
386 // -c compilation only runs up to the assembler.
387 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
388 FinalPhase = phases::Assemble;
390 } else if ((PhaseArg = DAL.getLastArg(options::OPT_emit_interface_stubs))) {
391 FinalPhase = phases::IfsMerge;
393 // Otherwise do everything.
395 FinalPhase = phases::Link;
398 *FinalPhaseArg = PhaseArg;
403 static Arg *MakeInputArg(DerivedArgList &Args, const OptTable &Opts,
404 StringRef Value, bool Claim = true) {
405 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
406 Args.getBaseArgs().MakeIndex(Value), Value.data());
407 Args.AddSynthesizedArg(A);
413 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
414 const llvm::opt::OptTable &Opts = getOpts();
415 DerivedArgList *DAL = new DerivedArgList(Args);
417 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
418 bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
419 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
420 bool IgnoreUnused = false;
421 for (Arg *A : Args) {
425 if (A->getOption().matches(options::OPT_start_no_unused_arguments)) {
429 if (A->getOption().matches(options::OPT_end_no_unused_arguments)) {
430 IgnoreUnused = false;
434 // Unfortunately, we have to parse some forwarding options (-Xassembler,
435 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
436 // (assembler and preprocessor), or bypass a previous driver ('collect2').
438 // Rewrite linker options, to replace --no-demangle with a custom internal
440 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
441 A->getOption().matches(options::OPT_Xlinker)) &&
442 A->containsValue("--no-demangle")) {
443 // Add the rewritten no-demangle argument.
444 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_Xlinker__no_demangle));
446 // Add the remaining values as Xlinker arguments.
447 for (StringRef Val : A->getValues())
448 if (Val != "--no-demangle")
449 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_Xlinker), Val);
454 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
455 // some build systems. We don't try to be complete here because we don't
456 // care to encourage this usage model.
457 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
458 (A->getValue(0) == StringRef("-MD") ||
459 A->getValue(0) == StringRef("-MMD"))) {
460 // Rewrite to -MD/-MMD along with -MF.
461 if (A->getValue(0) == StringRef("-MD"))
462 DAL->AddFlagArg(A, Opts.getOption(options::OPT_MD));
464 DAL->AddFlagArg(A, Opts.getOption(options::OPT_MMD));
465 if (A->getNumValues() == 2)
466 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue(1));
470 // Rewrite reserved library names.
471 if (A->getOption().matches(options::OPT_l)) {
472 StringRef Value = A->getValue();
474 // Rewrite unless -nostdlib is present.
475 if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx &&
477 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_stdcxx));
481 // Rewrite unconditionally.
482 if (Value == "cc_kext") {
483 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_cckext));
488 // Pick up inputs via the -- option.
489 if (A->getOption().matches(options::OPT__DASH_DASH)) {
491 for (StringRef Val : A->getValues())
492 DAL->append(MakeInputArg(*DAL, Opts, Val, false));
499 // Enforce -static if -miamcu is present.
500 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
501 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_static));
503 // Add a default value of -mlinker-version=, if one was given and the user
504 // didn't specify one.
505 #if defined(HOST_LINK_VERSION)
506 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
507 strlen(HOST_LINK_VERSION) > 0) {
508 DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ),
510 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
517 /// Compute target triple from args.
519 /// This routine provides the logic to compute a target triple from various
520 /// args passed to the driver and the default triple string.
521 static llvm::Triple computeTargetTriple(const Driver &D,
522 StringRef TargetTriple,
524 StringRef DarwinArchName = "") {
525 // FIXME: Already done in Compilation *Driver::BuildCompilation
526 if (const Arg *A = Args.getLastArg(options::OPT_target))
527 TargetTriple = A->getValue();
529 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
531 // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
532 // -gnu* only, and we can not change this, so we have to detect that case as
533 // being the Hurd OS.
534 if (TargetTriple.contains("-unknown-gnu") || TargetTriple.contains("-pc-gnu"))
535 Target.setOSName("hurd");
537 // Handle Apple-specific options available here.
538 if (Target.isOSBinFormatMachO()) {
539 // If an explicit Darwin arch name is given, that trumps all.
540 if (!DarwinArchName.empty()) {
541 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
545 // Handle the Darwin '-arch' flag.
546 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
547 StringRef ArchName = A->getValue();
548 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
552 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
553 // '-mbig-endian'/'-EB'.
554 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
555 options::OPT_mbig_endian)) {
556 if (A->getOption().matches(options::OPT_mlittle_endian)) {
557 llvm::Triple LE = Target.getLittleEndianArchVariant();
558 if (LE.getArch() != llvm::Triple::UnknownArch)
559 Target = std::move(LE);
561 llvm::Triple BE = Target.getBigEndianArchVariant();
562 if (BE.getArch() != llvm::Triple::UnknownArch)
563 Target = std::move(BE);
567 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
568 if (Target.getArch() == llvm::Triple::tce ||
569 Target.getOS() == llvm::Triple::Minix)
572 // On AIX, the env OBJECT_MODE may affect the resulting arch variant.
573 if (Target.isOSAIX()) {
574 if (Optional<std::string> ObjectModeValue =
575 llvm::sys::Process::GetEnv("OBJECT_MODE")) {
576 StringRef ObjectMode = *ObjectModeValue;
577 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
579 if (ObjectMode.equals("64")) {
580 AT = Target.get64BitArchVariant().getArch();
581 } else if (ObjectMode.equals("32")) {
582 AT = Target.get32BitArchVariant().getArch();
584 D.Diag(diag::err_drv_invalid_object_mode) << ObjectMode;
587 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
592 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
593 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
594 options::OPT_m32, options::OPT_m16);
596 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
598 if (A->getOption().matches(options::OPT_m64)) {
599 AT = Target.get64BitArchVariant().getArch();
600 if (Target.getEnvironment() == llvm::Triple::GNUX32)
601 Target.setEnvironment(llvm::Triple::GNU);
602 else if (Target.getEnvironment() == llvm::Triple::MuslX32)
603 Target.setEnvironment(llvm::Triple::Musl);
604 } else if (A->getOption().matches(options::OPT_mx32) &&
605 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
606 AT = llvm::Triple::x86_64;
607 if (Target.getEnvironment() == llvm::Triple::Musl)
608 Target.setEnvironment(llvm::Triple::MuslX32);
610 Target.setEnvironment(llvm::Triple::GNUX32);
611 } else if (A->getOption().matches(options::OPT_m32)) {
612 AT = Target.get32BitArchVariant().getArch();
613 if (Target.getEnvironment() == llvm::Triple::GNUX32)
614 Target.setEnvironment(llvm::Triple::GNU);
615 else if (Target.getEnvironment() == llvm::Triple::MuslX32)
616 Target.setEnvironment(llvm::Triple::Musl);
617 } else if (A->getOption().matches(options::OPT_m16) &&
618 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
619 AT = llvm::Triple::x86;
620 Target.setEnvironment(llvm::Triple::CODE16);
623 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) {
625 if (Target.isWindowsGNUEnvironment())
626 toolchains::MinGW::fixTripleArch(D, Target, Args);
630 // Handle -miamcu flag.
631 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
632 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
633 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
636 if (A && !A->getOption().matches(options::OPT_m32))
637 D.Diag(diag::err_drv_argument_not_allowed_with)
638 << "-miamcu" << A->getBaseArg().getAsString(Args);
640 Target.setArch(llvm::Triple::x86);
641 Target.setArchName("i586");
642 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
643 Target.setEnvironmentName("");
644 Target.setOS(llvm::Triple::ELFIAMCU);
645 Target.setVendor(llvm::Triple::UnknownVendor);
646 Target.setVendorName("intel");
649 // If target is MIPS adjust the target triple
650 // accordingly to provided ABI name.
651 if (Target.isMIPS()) {
652 if ((A = Args.getLastArg(options::OPT_mabi_EQ))) {
653 StringRef ABIName = A->getValue();
654 if (ABIName == "32") {
655 Target = Target.get32BitArchVariant();
656 if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
657 Target.getEnvironment() == llvm::Triple::GNUABIN32)
658 Target.setEnvironment(llvm::Triple::GNU);
659 } else if (ABIName == "n32") {
660 Target = Target.get64BitArchVariant();
661 if (Target.getEnvironment() == llvm::Triple::GNU ||
662 Target.getEnvironment() == llvm::Triple::GNUABI64)
663 Target.setEnvironment(llvm::Triple::GNUABIN32);
664 } else if (ABIName == "64") {
665 Target = Target.get64BitArchVariant();
666 if (Target.getEnvironment() == llvm::Triple::GNU ||
667 Target.getEnvironment() == llvm::Triple::GNUABIN32)
668 Target.setEnvironment(llvm::Triple::GNUABI64);
673 // If target is RISC-V adjust the target triple according to
674 // provided architecture name
675 if (Target.isRISCV()) {
676 if ((A = Args.getLastArg(options::OPT_march_EQ))) {
677 StringRef ArchName = A->getValue();
678 if (ArchName.startswith_insensitive("rv32"))
679 Target.setArch(llvm::Triple::riscv32);
680 else if (ArchName.startswith_insensitive("rv64"))
681 Target.setArch(llvm::Triple::riscv64);
688 // Parse the LTO options and record the type of LTO compilation
689 // based on which -f(no-)?lto(=.*)? or -f(no-)?offload-lto(=.*)?
690 // option occurs last.
691 static driver::LTOKind parseLTOMode(Driver &D, const llvm::opt::ArgList &Args,
692 OptSpecifier OptEq, OptSpecifier OptNeg) {
693 if (!Args.hasFlag(OptEq, OptNeg, false))
696 const Arg *A = Args.getLastArg(OptEq);
697 StringRef LTOName = A->getValue();
699 driver::LTOKind LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
700 .Case("full", LTOK_Full)
701 .Case("thin", LTOK_Thin)
702 .Default(LTOK_Unknown);
704 if (LTOMode == LTOK_Unknown) {
705 D.Diag(diag::err_drv_unsupported_option_argument)
706 << A->getOption().getName() << A->getValue();
712 // Parse the LTO options.
713 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
715 parseLTOMode(*this, Args, options::OPT_flto_EQ, options::OPT_fno_lto);
717 OffloadLTOMode = parseLTOMode(*this, Args, options::OPT_foffload_lto_EQ,
718 options::OPT_fno_offload_lto);
721 /// Compute the desired OpenMP runtime from the flags provided.
722 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
723 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
725 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
727 RuntimeName = A->getValue();
729 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
730 .Case("libomp", OMPRT_OMP)
731 .Case("libgomp", OMPRT_GOMP)
732 .Case("libiomp5", OMPRT_IOMP5)
733 .Default(OMPRT_Unknown);
735 if (RT == OMPRT_Unknown) {
737 Diag(diag::err_drv_unsupported_option_argument)
738 << A->getOption().getName() << A->getValue();
740 // FIXME: We could use a nicer diagnostic here.
741 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
747 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
753 // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
754 // or HIP type. However, mixed CUDA/HIP compilation is not supported.
756 llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
757 return types::isCuda(I.first);
761 [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
762 return types::isHIP(I.first);
764 C.getInputArgs().hasArg(options::OPT_hip_link);
765 if (IsCuda && IsHIP) {
766 Diag(clang::diag::err_drv_mix_cuda_hip);
770 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
771 const llvm::Triple &HostTriple = HostTC->getTriple();
772 auto OFK = Action::OFK_Cuda;
774 getNVIDIAOffloadTargetTriple(*this, C.getInputArgs(), HostTriple);
777 // Use the CUDA and host triples as the key into the ToolChains map,
778 // because the device toolchain we create depends on both.
779 auto &CudaTC = ToolChains[CudaTriple->str() + "/" + HostTriple.str()];
781 CudaTC = std::make_unique<toolchains::CudaToolChain>(
782 *this, *CudaTriple, *HostTC, C.getInputArgs());
784 C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
786 if (auto *OMPTargetArg =
787 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
788 Diag(clang::diag::err_drv_unsupported_opt_for_language_mode)
789 << OMPTargetArg->getSpelling() << "HIP";
792 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
793 auto OFK = Action::OFK_HIP;
794 auto HIPTriple = getHIPOffloadTargetTriple(*this, C.getInputArgs());
797 auto *HIPTC = &getOffloadingDeviceToolChain(C.getInputArgs(), *HIPTriple,
799 assert(HIPTC && "Could not create offloading device tool chain.");
800 C.addOffloadDeviceToolChain(HIPTC, OFK);
806 // We need to generate an OpenMP toolchain if the user specified targets with
807 // the -fopenmp-targets option or used --offload-arch with OpenMP enabled.
808 bool IsOpenMPOffloading =
809 C.getInputArgs().hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
810 options::OPT_fno_openmp, false) &&
811 (C.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ) ||
812 C.getInputArgs().hasArg(options::OPT_offload_arch_EQ));
813 if (IsOpenMPOffloading) {
814 // We expect that -fopenmp-targets is always used in conjunction with the
815 // option -fopenmp specifying a valid runtime with offloading support, i.e.
816 // libomp or libiomp.
817 OpenMPRuntimeKind RuntimeKind = getOpenMPRuntime(C.getInputArgs());
818 if (RuntimeKind != OMPRT_OMP && RuntimeKind != OMPRT_IOMP5) {
819 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
823 llvm::StringMap<llvm::DenseSet<StringRef>> DerivedArchs;
824 llvm::StringMap<StringRef> FoundNormalizedTriples;
825 llvm::SmallVector<StringRef, 4> OpenMPTriples;
827 // If the user specified -fopenmp-targets= we create a toolchain for each
828 // valid triple. Otherwise, if only --offload-arch= was specified we instead
829 // attempt to derive the appropriate toolchains from the arguments.
830 if (Arg *OpenMPTargets =
831 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
832 if (OpenMPTargets && !OpenMPTargets->getNumValues()) {
833 Diag(clang::diag::warn_drv_empty_joined_argument)
834 << OpenMPTargets->getAsString(C.getInputArgs());
837 llvm::copy(OpenMPTargets->getValues(), std::back_inserter(OpenMPTriples));
838 } else if (C.getInputArgs().hasArg(options::OPT_offload_arch_EQ) &&
840 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
841 auto AMDTriple = getHIPOffloadTargetTriple(*this, C.getInputArgs());
842 auto NVPTXTriple = getNVIDIAOffloadTargetTriple(*this, C.getInputArgs(),
843 HostTC->getTriple());
845 // Attempt to deduce the offloading triple from the set of architectures.
846 // We can only correctly deduce NVPTX / AMDGPU triples currently.
847 llvm::DenseSet<StringRef> Archs =
848 getOffloadArchs(C, C.getArgs(), Action::OFK_OpenMP, nullptr);
849 for (StringRef Arch : Archs) {
850 if (NVPTXTriple && IsNVIDIAGpuArch(StringToCudaArch(
851 getProcessorFromTargetID(*NVPTXTriple, Arch)))) {
852 DerivedArchs[NVPTXTriple->getTriple()].insert(Arch);
853 } else if (AMDTriple &&
854 IsAMDGpuArch(StringToCudaArch(
855 getProcessorFromTargetID(*AMDTriple, Arch)))) {
856 DerivedArchs[AMDTriple->getTriple()].insert(Arch);
858 Diag(clang::diag::err_drv_failed_to_deduce_target_from_arch) << Arch;
863 for (const auto &TripleAndArchs : DerivedArchs)
864 OpenMPTriples.push_back(TripleAndArchs.first());
867 for (StringRef Val : OpenMPTriples) {
868 llvm::Triple TT(ToolChain::getOpenMPTriple(Val));
869 std::string NormalizedName = TT.normalize();
871 // Make sure we don't have a duplicate triple.
872 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
873 if (Duplicate != FoundNormalizedTriples.end()) {
874 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
875 << Val << Duplicate->second;
879 // Store the current triple so that we can check for duplicates in the
880 // following iterations.
881 FoundNormalizedTriples[NormalizedName] = Val;
883 // If the specified target is invalid, emit a diagnostic.
884 if (TT.getArch() == llvm::Triple::UnknownArch)
885 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
888 // Device toolchains have to be selected differently. They pair host
889 // and device in their implementation.
890 if (TT.isNVPTX() || TT.isAMDGCN()) {
891 const ToolChain *HostTC =
892 C.getSingleOffloadToolChain<Action::OFK_Host>();
893 assert(HostTC && "Host toolchain should be always defined.");
895 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
898 DeviceTC = std::make_unique<toolchains::CudaToolChain>(
899 *this, TT, *HostTC, C.getInputArgs());
900 else if (TT.isAMDGCN())
901 DeviceTC = std::make_unique<toolchains::AMDGPUOpenMPToolChain>(
902 *this, TT, *HostTC, C.getInputArgs());
904 assert(DeviceTC && "Device toolchain not defined.");
909 TC = &getToolChain(C.getInputArgs(), TT);
910 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
911 if (DerivedArchs.find(TT.getTriple()) != DerivedArchs.end())
912 KnownArchs[TC] = DerivedArchs[TT.getTriple()];
915 } else if (C.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ)) {
916 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
921 // TODO: Add support for other offloading programming models here.
925 static void appendOneArg(InputArgList &Args, const Arg *Opt,
926 const Arg *BaseArg) {
927 // The args for config files or /clang: flags belong to different InputArgList
928 // objects than Args. This copies an Arg from one of those other InputArgLists
929 // to the ownership of Args.
930 unsigned Index = Args.MakeIndex(Opt->getSpelling());
931 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Args.getArgString(Index),
933 Copy->getValues() = Opt->getValues();
934 if (Opt->isClaimed())
936 Copy->setOwnsValues(Opt->getOwnsValues());
937 Opt->setOwnsValues(false);
941 bool Driver::readConfigFile(StringRef FileName,
942 llvm::cl::ExpansionContext &ExpCtx) {
943 // Try reading the given file.
944 SmallVector<const char *, 32> NewCfgArgs;
945 if (!ExpCtx.readConfigFile(FileName, NewCfgArgs)) {
946 Diag(diag::err_drv_cannot_read_config_file) << FileName;
950 // Read options from config file.
951 llvm::SmallString<128> CfgFileName(FileName);
952 llvm::sys::path::native(CfgFileName);
954 std::unique_ptr<InputArgList> NewOptions = std::make_unique<InputArgList>(
955 ParseArgStrings(NewCfgArgs, IsCLMode(), ContainErrors));
959 if (NewOptions->hasArg(options::OPT_config)) {
960 Diag(diag::err_drv_nested_config_file);
964 // Claim all arguments that come from a configuration file so that the driver
965 // does not warn on any that is unused.
966 for (Arg *A : *NewOptions)
970 CfgOptions = std::move(NewOptions);
972 // If this is a subsequent config file, append options to the previous one.
973 for (auto *Opt : *NewOptions) {
974 const Arg *BaseArg = &Opt->getBaseArg();
977 appendOneArg(*CfgOptions, Opt, BaseArg);
980 ConfigFiles.push_back(std::string(CfgFileName));
984 bool Driver::loadConfigFiles() {
985 llvm::cl::ExpansionContext ExpCtx(Saver.getAllocator(),
986 llvm::cl::tokenizeConfigFile);
987 ExpCtx.setVFS(&getVFS());
989 // Process options that change search path for config files.
991 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
992 SmallString<128> CfgDir;
994 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
995 if (CfgDir.empty() || getVFS().makeAbsolute(CfgDir))
996 SystemConfigDir.clear();
998 SystemConfigDir = static_cast<std::string>(CfgDir);
1000 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
1001 SmallString<128> CfgDir;
1003 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
1004 if (CfgDir.empty() || getVFS().makeAbsolute(CfgDir))
1005 UserConfigDir.clear();
1007 UserConfigDir = static_cast<std::string>(CfgDir);
1011 // Prepare list of directories where config file is searched for.
1012 StringRef CfgFileSearchDirs[] = {UserConfigDir, SystemConfigDir, Dir};
1013 ExpCtx.setSearchDirs(CfgFileSearchDirs);
1015 // First try to load configuration from the default files, return on error.
1016 if (loadDefaultConfigFiles(ExpCtx))
1019 // Then load configuration files specified explicitly.
1020 SmallString<128> CfgFilePath;
1022 for (auto CfgFileName : CLOptions->getAllArgValues(options::OPT_config)) {
1023 // If argument contains directory separator, treat it as a path to
1024 // configuration file.
1025 if (llvm::sys::path::has_parent_path(CfgFileName)) {
1026 CfgFilePath.assign(CfgFileName);
1027 if (llvm::sys::path::is_relative(CfgFilePath)) {
1028 if (getVFS().makeAbsolute(CfgFilePath))
1030 auto Status = getVFS().status(CfgFilePath);
1032 Status->getType() != llvm::sys::fs::file_type::regular_file) {
1033 Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
1037 } else if (!ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) {
1038 // Report an error that the config file could not be found.
1039 Diag(diag::err_drv_config_file_not_found) << CfgFileName;
1040 for (const StringRef &SearchDir : CfgFileSearchDirs)
1041 if (!SearchDir.empty())
1042 Diag(diag::note_drv_config_file_searched_in) << SearchDir;
1046 // Try to read the config file, return on error.
1047 if (readConfigFile(CfgFilePath, ExpCtx))
1052 // No error occurred.
1056 bool Driver::loadDefaultConfigFiles(llvm::cl::ExpansionContext &ExpCtx) {
1057 // Disable default config if CLANG_NO_DEFAULT_CONFIG is set to a non-empty
1059 if (const char *NoConfigEnv = ::getenv("CLANG_NO_DEFAULT_CONFIG")) {
1063 if (CLOptions && CLOptions->hasArg(options::OPT_no_default_config))
1066 std::string RealMode = getExecutableForDriverMode(Mode);
1069 // If name prefix is present, no --target= override was passed via CLOptions
1070 // and the name prefix is not a valid triple, force it for backwards
1072 if (!ClangNameParts.TargetPrefix.empty() &&
1073 computeTargetTriple(*this, "/invalid/", *CLOptions).str() ==
1075 llvm::Triple PrefixTriple{ClangNameParts.TargetPrefix};
1076 if (PrefixTriple.getArch() == llvm::Triple::UnknownArch ||
1077 PrefixTriple.isOSUnknown())
1078 Triple = PrefixTriple.str();
1081 // Otherwise, use the real triple as used by the driver.
1082 if (Triple.empty()) {
1083 llvm::Triple RealTriple =
1084 computeTargetTriple(*this, TargetTriple, *CLOptions);
1085 Triple = RealTriple.str();
1086 assert(!Triple.empty());
1089 // Search for config files in the following order:
1090 // 1. <triple>-<mode>.cfg using real driver mode
1091 // (e.g. i386-pc-linux-gnu-clang++.cfg).
1092 // 2. <triple>-<mode>.cfg using executable suffix
1093 // (e.g. i386-pc-linux-gnu-clang-g++.cfg for *clang-g++).
1094 // 3. <triple>.cfg + <mode>.cfg using real driver mode
1095 // (e.g. i386-pc-linux-gnu.cfg + clang++.cfg).
1096 // 4. <triple>.cfg + <mode>.cfg using executable suffix
1097 // (e.g. i386-pc-linux-gnu.cfg + clang-g++.cfg for *clang-g++).
1099 // Try loading <triple>-<mode>.cfg, and return if we find a match.
1100 SmallString<128> CfgFilePath;
1101 std::string CfgFileName = Triple + '-' + RealMode + ".cfg";
1102 if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath))
1103 return readConfigFile(CfgFilePath, ExpCtx);
1105 bool TryModeSuffix = !ClangNameParts.ModeSuffix.empty() &&
1106 ClangNameParts.ModeSuffix != RealMode;
1107 if (TryModeSuffix) {
1108 CfgFileName = Triple + '-' + ClangNameParts.ModeSuffix + ".cfg";
1109 if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath))
1110 return readConfigFile(CfgFilePath, ExpCtx);
1113 // Try loading <mode>.cfg, and return if loading failed. If a matching file
1114 // was not found, still proceed on to try <triple>.cfg.
1115 CfgFileName = RealMode + ".cfg";
1116 if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) {
1117 if (readConfigFile(CfgFilePath, ExpCtx))
1119 } else if (TryModeSuffix) {
1120 CfgFileName = ClangNameParts.ModeSuffix + ".cfg";
1121 if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath) &&
1122 readConfigFile(CfgFilePath, ExpCtx))
1126 // Try loading <triple>.cfg and return if we find a match.
1127 CfgFileName = Triple + ".cfg";
1128 if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath))
1129 return readConfigFile(CfgFilePath, ExpCtx);
1131 // If we were unable to find a config file deduced from executable name,
1132 // that is not an error.
1136 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
1137 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
1139 // FIXME: Handle environment options which affect driver behavior, somewhere
1140 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
1142 // We look for the driver mode option early, because the mode can affect
1143 // how other options are parsed.
1145 auto DriverMode = getDriverMode(ClangExecutable, ArgList.slice(1));
1146 if (!DriverMode.empty())
1147 setDriverMode(DriverMode);
1149 // FIXME: What are we going to do with -V and -b?
1151 // Arguments specified in command line.
1153 CLOptions = std::make_unique<InputArgList>(
1154 ParseArgStrings(ArgList.slice(1), IsCLMode(), ContainsError));
1156 // Try parsing configuration file.
1158 ContainsError = loadConfigFiles();
1159 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
1161 // All arguments, from both config file and command line.
1162 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
1163 : std::move(*CLOptions));
1166 for (auto *Opt : *CLOptions) {
1167 if (Opt->getOption().matches(options::OPT_config))
1169 const Arg *BaseArg = &Opt->getBaseArg();
1172 appendOneArg(Args, Opt, BaseArg);
1175 // In CL mode, look for any pass-through arguments
1176 if (IsCLMode() && !ContainsError) {
1177 SmallVector<const char *, 16> CLModePassThroughArgList;
1178 for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
1180 CLModePassThroughArgList.push_back(A->getValue());
1183 if (!CLModePassThroughArgList.empty()) {
1184 // Parse any pass through args using default clang processing rather
1185 // than clang-cl processing.
1186 auto CLModePassThroughOptions = std::make_unique<InputArgList>(
1187 ParseArgStrings(CLModePassThroughArgList, false, ContainsError));
1190 for (auto *Opt : *CLModePassThroughOptions) {
1191 appendOneArg(Args, Opt, nullptr);
1196 // Check for working directory option before accessing any files
1197 if (Arg *WD = Args.getLastArg(options::OPT_working_directory))
1198 if (VFS->setCurrentWorkingDirectory(WD->getValue()))
1199 Diag(diag::err_drv_unable_to_set_working_directory) << WD->getValue();
1201 // FIXME: This stuff needs to go into the Compilation, not the driver.
1202 bool CCCPrintPhases;
1204 // Silence driver warnings if requested
1205 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
1207 // -canonical-prefixes, -no-canonical-prefixes are used very early in main.
1208 Args.ClaimAllArgs(options::OPT_canonical_prefixes);
1209 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
1211 // f(no-)integated-cc1 is also used very early in main.
1212 Args.ClaimAllArgs(options::OPT_fintegrated_cc1);
1213 Args.ClaimAllArgs(options::OPT_fno_integrated_cc1);
1216 Args.ClaimAllArgs(options::OPT_pipe);
1218 // Extract -ccc args.
1220 // FIXME: We need to figure out where this behavior should live. Most of it
1221 // should be outside in the client; the parts that aren't should have proper
1222 // options, either by introducing new ones or by overloading gcc ones like -V
1224 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
1225 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
1226 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
1227 CCCGenericGCCName = A->getValue();
1229 // Process -fproc-stat-report options.
1230 if (const Arg *A = Args.getLastArg(options::OPT_fproc_stat_report_EQ)) {
1231 CCPrintProcessStats = true;
1232 CCPrintStatReportFilename = A->getValue();
1234 if (Args.hasArg(options::OPT_fproc_stat_report))
1235 CCPrintProcessStats = true;
1237 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
1238 // and getToolChain is const.
1240 // clang-cl targets MSVC-style Win32.
1241 llvm::Triple T(TargetTriple);
1242 T.setOS(llvm::Triple::Win32);
1243 T.setVendor(llvm::Triple::PC);
1244 T.setEnvironment(llvm::Triple::MSVC);
1245 T.setObjectFormat(llvm::Triple::COFF);
1246 if (Args.hasArg(options::OPT__SLASH_arm64EC))
1247 T.setArch(llvm::Triple::aarch64, llvm::Triple::AArch64SubArch_arm64ec);
1248 TargetTriple = T.str();
1249 } else if (IsDXCMode()) {
1250 // Build TargetTriple from target_profile option for clang-dxc.
1251 if (const Arg *A = Args.getLastArg(options::OPT_target_profile)) {
1252 StringRef TargetProfile = A->getValue();
1254 toolchains::HLSLToolChain::parseTargetProfile(TargetProfile))
1255 TargetTriple = *Triple;
1257 Diag(diag::err_drv_invalid_directx_shader_module) << TargetProfile;
1261 Diag(diag::err_drv_dxc_missing_target_profile);
1265 if (const Arg *A = Args.getLastArg(options::OPT_target))
1266 TargetTriple = A->getValue();
1267 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
1268 Dir = InstalledDir = A->getValue();
1269 for (const Arg *A : Args.filtered(options::OPT_B)) {
1271 PrefixDirs.push_back(A->getValue(0));
1273 if (Optional<std::string> CompilerPathValue =
1274 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
1275 StringRef CompilerPath = *CompilerPathValue;
1276 while (!CompilerPath.empty()) {
1277 std::pair<StringRef, StringRef> Split =
1278 CompilerPath.split(llvm::sys::EnvPathSeparator);
1279 PrefixDirs.push_back(std::string(Split.first));
1280 CompilerPath = Split.second;
1283 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
1284 SysRoot = A->getValue();
1285 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
1286 DyldPrefix = A->getValue();
1288 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
1289 ResourceDir = A->getValue();
1291 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
1292 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1293 .Case("cwd", SaveTempsCwd)
1294 .Case("obj", SaveTempsObj)
1295 .Default(SaveTempsCwd);
1298 if (const Arg *A = Args.getLastArg(options::OPT_offload_host_only,
1299 options::OPT_offload_device_only,
1300 options::OPT_offload_host_device)) {
1301 if (A->getOption().matches(options::OPT_offload_host_only))
1302 Offload = OffloadHost;
1303 else if (A->getOption().matches(options::OPT_offload_device_only))
1304 Offload = OffloadDevice;
1306 Offload = OffloadHostDevice;
1311 // Process -fembed-bitcode= flags.
1312 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1313 StringRef Name = A->getValue();
1314 unsigned Model = llvm::StringSwitch<unsigned>(Name)
1315 .Case("off", EmbedNone)
1316 .Case("all", EmbedBitcode)
1317 .Case("bitcode", EmbedBitcode)
1318 .Case("marker", EmbedMarker)
1321 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1324 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
1327 // Remove existing compilation database so that each job can append to it.
1328 if (Arg *A = Args.getLastArg(options::OPT_MJ))
1329 llvm::sys::fs::remove(A->getValue());
1331 // Setting up the jobs for some precompile cases depends on whether we are
1332 // treating them as PCH, implicit modules or C++20 ones.
1333 // TODO: inferring the mode like this seems fragile (it meets the objective
1334 // of not requiring anything new for operation, however).
1335 const Arg *Std = Args.getLastArg(options::OPT_std_EQ);
1337 !Args.hasArg(options::OPT_fmodules) && Std &&
1338 (Std->containsValue("c++20") || Std->containsValue("c++2b") ||
1339 Std->containsValue("c++2a") || Std->containsValue("c++latest"));
1341 // Process -fmodule-header{=} flags.
1342 if (Arg *A = Args.getLastArg(options::OPT_fmodule_header_EQ,
1343 options::OPT_fmodule_header)) {
1344 // These flags force C++20 handling of headers.
1345 ModulesModeCXX20 = true;
1346 if (A->getOption().matches(options::OPT_fmodule_header))
1347 CXX20HeaderType = HeaderMode_Default;
1349 StringRef ArgName = A->getValue();
1350 unsigned Kind = llvm::StringSwitch<unsigned>(ArgName)
1351 .Case("user", HeaderMode_User)
1352 .Case("system", HeaderMode_System)
1355 Diags.Report(diag::err_drv_invalid_value)
1356 << A->getAsString(Args) << ArgName;
1358 CXX20HeaderType = static_cast<ModuleHeaderMode>(Kind);
1362 std::unique_ptr<llvm::opt::InputArgList> UArgs =
1363 std::make_unique<InputArgList>(std::move(Args));
1365 // Perform the default argument translations.
1366 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
1368 // Owned by the host.
1369 const ToolChain &TC = getToolChain(
1370 *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
1372 // Report warning when arm64EC option is overridden by specified target
1373 if ((TC.getTriple().getArch() != llvm::Triple::aarch64 ||
1374 TC.getTriple().getSubArch() != llvm::Triple::AArch64SubArch_arm64ec) &&
1375 UArgs->hasArg(options::OPT__SLASH_arm64EC)) {
1376 getDiags().Report(clang::diag::warn_target_override_arm64ec)
1377 << TC.getTriple().str();
1380 // The compilation takes ownership of Args.
1381 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1384 if (!HandleImmediateArgs(*C))
1387 // Construct the list of inputs.
1389 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
1391 // Populate the tool chains for the offloading devices, if any.
1392 CreateOffloadingDeviceToolChains(*C, Inputs);
1394 // Construct the list of abstract actions to perform for this compilation. On
1395 // MachO targets this uses the driver-driver and universal actions.
1396 if (TC.getTriple().isOSBinFormatMachO())
1397 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
1399 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
1401 if (CCCPrintPhases) {
1411 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1412 llvm::opt::ArgStringList ASL;
1413 for (const auto *A : Args) {
1414 // Use user's original spelling of flags. For example, use
1415 // `/source-charset:utf-8` instead of `-finput-charset=utf-8` if the user
1416 // wrote the former.
1417 while (A->getAlias())
1419 A->render(Args, ASL);
1422 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1423 if (I != ASL.begin())
1425 llvm::sys::printArg(OS, *I, true);
1430 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1431 SmallString<128> &CrashDiagDir) {
1432 using namespace llvm::sys;
1433 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1434 "Only knows about .crash files on Darwin");
1436 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1437 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1438 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1439 path::home_directory(CrashDiagDir);
1440 if (CrashDiagDir.startswith("/var/root"))
1442 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1450 fs::file_status FileStatus;
1451 TimePoint<> LastAccessTime;
1452 SmallString<128> CrashFilePath;
1453 // Lookup the .crash files and get the one generated by a subprocess spawned
1454 // by this driver invocation.
1455 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1456 File != FileEnd && !EC; File.increment(EC)) {
1457 StringRef FileName = path::filename(File->path());
1458 if (!FileName.startswith(Name))
1460 if (fs::status(File->path(), FileStatus))
1462 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1463 llvm::MemoryBuffer::getFile(File->path());
1466 // The first line should start with "Process:", otherwise this isn't a real
1468 StringRef Data = CrashFile.get()->getBuffer();
1469 if (!Data.startswith("Process:"))
1471 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1472 size_t ParentProcPos = Data.find("Parent Process:");
1473 if (ParentProcPos == StringRef::npos)
1475 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1476 if (LineEnd == StringRef::npos)
1478 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1479 int OpenBracket = -1, CloseBracket = -1;
1480 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1481 if (ParentProcess[i] == '[')
1483 if (ParentProcess[i] == ']')
1486 // Extract the parent process PID from the .crash file and check whether
1487 // it matches this driver invocation pid.
1489 if (OpenBracket < 0 || CloseBracket < 0 ||
1490 ParentProcess.slice(OpenBracket + 1, CloseBracket)
1491 .getAsInteger(10, CrashPID) || CrashPID != PID) {
1495 // Found a .crash file matching the driver pid. To avoid getting an older
1496 // and misleading crash file, continue looking for the most recent.
1497 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1498 // multiple crashes poiting to the same parent process. Since the driver
1499 // does not collect pid information for the dispatched invocation there's
1500 // currently no way to distinguish among them.
1501 const auto FileAccessTime = FileStatus.getLastModificationTime();
1502 if (FileAccessTime > LastAccessTime) {
1503 CrashFilePath.assign(File->path());
1504 LastAccessTime = FileAccessTime;
1508 // If found, copy it over to the location of other reproducer files.
1509 if (!CrashFilePath.empty()) {
1510 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1519 // When clang crashes, produce diagnostic information including the fully
1520 // preprocessed source file(s). Request that the developer attach the
1521 // diagnostic information to a bug report.
1522 void Driver::generateCompilationDiagnostics(
1523 Compilation &C, const Command &FailingCommand,
1524 StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
1525 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
1529 if (Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_EQ)) {
1530 Level = llvm::StringSwitch<unsigned>(A->getValue())
1532 .Case("compiler", 1)
1539 // Don't try to generate diagnostics for dsymutil jobs.
1540 if (FailingCommand.getCreator().isDsymutilJob())
1544 ArgStringList SavedTemps;
1545 if (FailingCommand.getCreator().isLinkJob()) {
1546 C.getDefaultToolChain().GetLinkerPath(&IsLLD);
1547 if (!IsLLD || Level < 2)
1550 // If lld crashed, we will re-run the same command with the input it used
1551 // to have. In that case we should not remove temp files in
1552 // initCompilationForDiagnostics yet. They will be added back and removed
1554 SavedTemps = std::move(C.getTempFiles());
1555 assert(!C.getTempFiles().size());
1558 // Print the version of the compiler.
1559 PrintVersion(C, llvm::errs());
1561 // Suppress driver output and emit preprocessor output to temp file.
1562 CCGenDiagnostics = true;
1564 // Save the original job command(s).
1565 Command Cmd = FailingCommand;
1567 // Keep track of whether we produce any errors while trying to produce
1568 // preprocessed sources.
1569 DiagnosticErrorTrap Trap(Diags);
1571 // Suppress tool output.
1572 C.initCompilationForDiagnostics();
1574 // Construct the list of inputs.
1576 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
1578 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
1579 bool IgnoreInput = false;
1581 // Ignore input from stdin or any inputs that cannot be preprocessed.
1582 // Check type first as not all linker inputs have a value.
1583 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
1585 } else if (!strcmp(it->second->getValue(), "-")) {
1586 Diag(clang::diag::note_drv_command_failed_diag_msg)
1587 << "Error generating preprocessed source(s) - "
1588 "ignoring input from stdin.";
1593 it = Inputs.erase(it);
1600 if (Inputs.empty()) {
1601 Diag(clang::diag::note_drv_command_failed_diag_msg)
1602 << "Error generating preprocessed source(s) - "
1603 "no preprocessable inputs.";
1607 // Don't attempt to generate preprocessed files if multiple -arch options are
1608 // used, unless they're all duplicates.
1609 llvm::StringSet<> ArchNames;
1610 for (const Arg *A : C.getArgs()) {
1611 if (A->getOption().matches(options::OPT_arch)) {
1612 StringRef ArchName = A->getValue();
1613 ArchNames.insert(ArchName);
1616 if (ArchNames.size() > 1) {
1617 Diag(clang::diag::note_drv_command_failed_diag_msg)
1618 << "Error generating preprocessed source(s) - cannot generate "
1619 "preprocessed source with multiple -arch options.";
1623 // Construct the list of abstract actions to perform for this compilation. On
1624 // Darwin OSes this uses the driver-driver and builds universal actions.
1625 const ToolChain &TC = C.getDefaultToolChain();
1626 if (TC.getTriple().isOSBinFormatMachO())
1627 BuildUniversalActions(C, TC, Inputs);
1629 BuildActions(C, C.getArgs(), Inputs, C.getActions());
1633 // If there were errors building the compilation, quit now.
1634 if (Trap.hasErrorOccurred()) {
1635 Diag(clang::diag::note_drv_command_failed_diag_msg)
1636 << "Error generating preprocessed source(s).";
1640 // Generate preprocessed output.
1641 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
1642 C.ExecuteJobs(C.getJobs(), FailingCommands);
1644 // If any of the preprocessing commands failed, clean up and exit.
1645 if (!FailingCommands.empty()) {
1646 Diag(clang::diag::note_drv_command_failed_diag_msg)
1647 << "Error generating preprocessed source(s).";
1651 // If lld failed, rerun it again with --reproduce.
1653 const char *TmpName = CreateTempFile(C, "linker-crash", "tar");
1654 Command NewLLDInvocation = Cmd;
1655 llvm::opt::ArgStringList ArgList = NewLLDInvocation.getArguments();
1656 StringRef ReproduceOption =
1657 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment()
1660 ArgList.push_back(Saver.save(Twine(ReproduceOption) + TmpName).data());
1661 NewLLDInvocation.replaceArguments(std::move(ArgList));
1663 // Redirect stdout/stderr to /dev/null.
1664 NewLLDInvocation.Execute({None, {""}, {""}}, nullptr, nullptr);
1667 const ArgStringList &TempFiles = C.getTempFiles();
1668 if (TempFiles.empty()) {
1669 Diag(clang::diag::note_drv_command_failed_diag_msg)
1670 << "Error generating preprocessed source(s).";
1674 Diag(clang::diag::note_drv_command_failed_diag_msg)
1675 << "\n********************\n\n"
1676 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1677 "Preprocessed source(s) and associated run script(s) are located at:";
1679 SmallString<128> VFS;
1680 SmallString<128> ReproCrashFilename;
1681 for (const char *TempFile : TempFiles) {
1682 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
1684 Report->TemporaryFiles.push_back(TempFile);
1685 if (ReproCrashFilename.empty()) {
1686 ReproCrashFilename = TempFile;
1687 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1689 if (StringRef(TempFile).endswith(".cache")) {
1690 // In some cases (modules) we'll dump extra data to help with reproducing
1691 // the crash into a directory next to the output.
1692 VFS = llvm::sys::path::filename(TempFile);
1693 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1697 for (const char *TempFile : SavedTemps)
1698 C.addTempFile(TempFile);
1700 // Assume associated files are based off of the first temporary file.
1701 CrashReportInfo CrashInfo(TempFiles[0], VFS);
1703 llvm::SmallString<128> Script(CrashInfo.Filename);
1704 llvm::sys::path::replace_extension(Script, "sh");
1706 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew,
1707 llvm::sys::fs::FA_Write,
1708 llvm::sys::fs::OF_Text);
1710 Diag(clang::diag::note_drv_command_failed_diag_msg)
1711 << "Error generating run script: " << Script << " " << EC.message();
1713 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
1714 << "# Driver args: ";
1715 printArgList(ScriptOS, C.getInputArgs());
1716 ScriptOS << "# Original command: ";
1717 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
1718 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
1719 if (!AdditionalInformation.empty())
1720 ScriptOS << "\n# Additional information: " << AdditionalInformation
1723 Report->TemporaryFiles.push_back(std::string(Script.str()));
1724 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
1727 // On darwin, provide information about the .crash diagnostic report.
1728 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1729 SmallString<128> CrashDiagDir;
1730 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1731 Diag(clang::diag::note_drv_command_failed_diag_msg)
1732 << ReproCrashFilename.str();
1733 } else { // Suggest a directory for the user to look for .crash files.
1734 llvm::sys::path::append(CrashDiagDir, Name);
1735 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1736 Diag(clang::diag::note_drv_command_failed_diag_msg)
1737 << "Crash backtrace is located in";
1738 Diag(clang::diag::note_drv_command_failed_diag_msg)
1739 << CrashDiagDir.str();
1740 Diag(clang::diag::note_drv_command_failed_diag_msg)
1741 << "(choose the .crash file that corresponds to your crash)";
1745 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file_EQ))
1746 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1748 Diag(clang::diag::note_drv_command_failed_diag_msg)
1749 << "\n\n********************";
1752 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1753 // Since commandLineFitsWithinSystemLimits() may underestimate system's
1754 // capacity if the tool does not support response files, there is a chance/
1755 // that things will just work without a response file, so we silently just
1757 if (Cmd.getResponseFileSupport().ResponseKind ==
1758 ResponseFileSupport::RF_None ||
1759 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(),
1760 Cmd.getArguments()))
1763 std::string TmpName = GetTemporaryPath("response", "txt");
1764 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1767 int Driver::ExecuteCompilation(
1769 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1770 if (C.getArgs().hasArg(options::OPT_fdriver_only)) {
1771 if (C.getArgs().hasArg(options::OPT_v))
1772 C.getJobs().Print(llvm::errs(), "\n", true);
1774 C.ExecuteJobs(C.getJobs(), FailingCommands, /*LogOnly=*/true);
1776 // If there were errors building the compilation, quit now.
1777 if (!FailingCommands.empty() || Diags.hasErrorOccurred())
1783 // Just print if -### was present.
1784 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1785 C.getJobs().Print(llvm::errs(), "\n", true);
1789 // If there were errors building the compilation, quit now.
1790 if (Diags.hasErrorOccurred())
1793 // Set up response file names for each command, if necessary.
1794 for (auto &Job : C.getJobs())
1795 setUpResponseFiles(C, Job);
1797 C.ExecuteJobs(C.getJobs(), FailingCommands);
1799 // If the command succeeded, we are done.
1800 if (FailingCommands.empty())
1803 // Otherwise, remove result files and print extra information about abnormal
1806 for (const auto &CmdPair : FailingCommands) {
1807 int CommandRes = CmdPair.first;
1808 const Command *FailingCommand = CmdPair.second;
1810 // Remove result files if we're not saving temps.
1811 if (!isSaveTempsEnabled()) {
1812 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1813 C.CleanupFileMap(C.getResultFiles(), JA, true);
1815 // Failure result files are valid unless we crashed.
1817 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1821 // llvm/lib/Support/Unix/Signals.inc will exit with a special return code
1822 // for SIGPIPE. Do not print diagnostics for this case.
1823 if (CommandRes == EX_IOERR) {
1829 // Print extra information about abnormal failures, if possible.
1831 // This is ad-hoc, but we don't want to be excessively noisy. If the result
1832 // status was 1, assume the command failed normally. In particular, if it
1833 // was the compiler then assume it gave a reasonable error code. Failures
1834 // in other tools are less common, and they generally have worse
1835 // diagnostics, so always print the diagnostic there.
1836 const Tool &FailingTool = FailingCommand->getCreator();
1838 if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
1839 // FIXME: See FIXME above regarding result code interpretation.
1841 Diag(clang::diag::err_drv_command_signalled)
1842 << FailingTool.getShortName();
1844 Diag(clang::diag::err_drv_command_failed)
1845 << FailingTool.getShortName() << CommandRes;
1851 void Driver::PrintHelp(bool ShowHidden) const {
1852 unsigned IncludedFlagsBitmask;
1853 unsigned ExcludedFlagsBitmask;
1854 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1855 getIncludeExcludeOptionFlagMasks(IsCLMode());
1857 ExcludedFlagsBitmask |= options::NoDriverOption;
1859 ExcludedFlagsBitmask |= HelpHidden;
1862 IncludedFlagsBitmask |= options::FlangOption;
1864 ExcludedFlagsBitmask |= options::FlangOnlyOption;
1866 std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1867 getOpts().printHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
1868 IncludedFlagsBitmask, ExcludedFlagsBitmask,
1869 /*ShowAllAliases=*/false);
1872 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1873 if (IsFlangMode()) {
1874 OS << getClangToolFullVersion("flang-new") << '\n';
1876 // FIXME: The following handlers should use a callback mechanism, we don't
1877 // know what the client would like to do.
1878 OS << getClangFullVersion() << '\n';
1880 const ToolChain &TC = C.getDefaultToolChain();
1881 OS << "Target: " << TC.getTripleString() << '\n';
1883 // Print the threading model.
1884 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1885 // Don't print if the ToolChain would have barfed on it already
1886 if (TC.isThreadModelSupported(A->getValue()))
1887 OS << "Thread model: " << A->getValue();
1889 OS << "Thread model: " << TC.getThreadModel();
1892 // Print out the install directory.
1893 OS << "InstalledDir: " << InstalledDir << '\n';
1895 // If configuration files were used, print their paths.
1896 for (auto ConfigFile : ConfigFiles)
1897 OS << "Configuration file: " << ConfigFile << '\n';
1900 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1902 static void PrintDiagnosticCategories(raw_ostream &OS) {
1903 // Skip the empty category.
1904 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1906 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1909 void Driver::HandleAutocompletions(StringRef PassedFlags) const {
1910 if (PassedFlags == "")
1912 // Print out all options that start with a given argument. This is used for
1913 // shell autocompletion.
1914 std::vector<std::string> SuggestedCompletions;
1915 std::vector<std::string> Flags;
1917 unsigned int DisableFlags =
1918 options::NoDriverOption | options::Unsupported | options::Ignored;
1920 // Make sure that Flang-only options don't pollute the Clang output
1921 // TODO: Make sure that Clang-only options don't pollute Flang output
1923 DisableFlags |= options::FlangOnlyOption;
1925 // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
1926 // because the latter indicates that the user put space before pushing tab
1927 // which should end up in a file completion.
1928 const bool HasSpace = PassedFlags.endswith(",");
1930 // Parse PassedFlags by "," as all the command-line flags are passed to this
1931 // function separated by ","
1932 StringRef TargetFlags = PassedFlags;
1933 while (TargetFlags != "") {
1935 std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1936 Flags.push_back(std::string(CurFlag));
1939 // We want to show cc1-only options only when clang is invoked with -cc1 or
1941 if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1"))
1942 DisableFlags &= ~options::NoDriverOption;
1944 const llvm::opt::OptTable &Opts = getOpts();
1946 Cur = Flags.at(Flags.size() - 1);
1948 if (Flags.size() >= 2) {
1949 Prev = Flags.at(Flags.size() - 2);
1950 SuggestedCompletions = Opts.suggestValueCompletions(Prev, Cur);
1953 if (SuggestedCompletions.empty())
1954 SuggestedCompletions = Opts.suggestValueCompletions(Cur, "");
1956 // If Flags were empty, it means the user typed `clang [tab]` where we should
1957 // list all possible flags. If there was no value completion and the user
1958 // pressed tab after a space, we should fall back to a file completion.
1959 // We're printing a newline to be consistent with what we print at the end of
1961 if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
1962 llvm::outs() << '\n';
1966 // When flag ends with '=' and there was no value completion, return empty
1967 // string and fall back to the file autocompletion.
1968 if (SuggestedCompletions.empty() && !Cur.endswith("=")) {
1969 // If the flag is in the form of "--autocomplete=-foo",
1970 // we were requested to print out all option names that start with "-foo".
1971 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
1972 SuggestedCompletions = Opts.findByPrefix(Cur, DisableFlags);
1974 // We have to query the -W flags manually as they're not in the OptTable.
1975 // TODO: Find a good way to add them to OptTable instead and them remove
1977 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
1978 if (S.startswith(Cur))
1979 SuggestedCompletions.push_back(std::string(S));
1982 // Sort the autocomplete candidates so that shells print them out in a
1983 // deterministic order. We could sort in any way, but we chose
1984 // case-insensitive sorting for consistency with the -help option
1985 // which prints out options in the case-insensitive alphabetical order.
1986 llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
1987 if (int X = A.compare_insensitive(B))
1989 return A.compare(B) > 0;
1992 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1995 bool Driver::HandleImmediateArgs(const Compilation &C) {
1996 // The order these options are handled in gcc is all over the place, but we
1997 // don't expect inconsistencies w.r.t. that to matter in practice.
1999 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
2000 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
2004 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
2005 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
2006 // return an answer which matches our definition of __VERSION__.
2007 llvm::outs() << CLANG_VERSION_STRING << "\n";
2011 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
2012 PrintDiagnosticCategories(llvm::outs());
2016 if (C.getArgs().hasArg(options::OPT_help) ||
2017 C.getArgs().hasArg(options::OPT__help_hidden)) {
2018 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
2022 if (C.getArgs().hasArg(options::OPT__version)) {
2023 // Follow gcc behavior and use stdout for --version and stderr for -v.
2024 PrintVersion(C, llvm::outs());
2028 if (C.getArgs().hasArg(options::OPT_v) ||
2029 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH) ||
2030 C.getArgs().hasArg(options::OPT_print_supported_cpus)) {
2031 PrintVersion(C, llvm::errs());
2032 SuppressMissingInputWarning = true;
2035 if (C.getArgs().hasArg(options::OPT_v)) {
2036 if (!SystemConfigDir.empty())
2037 llvm::errs() << "System configuration file directory: "
2038 << SystemConfigDir << "\n";
2039 if (!UserConfigDir.empty())
2040 llvm::errs() << "User configuration file directory: "
2041 << UserConfigDir << "\n";
2044 const ToolChain &TC = C.getDefaultToolChain();
2046 if (C.getArgs().hasArg(options::OPT_v))
2047 TC.printVerboseInfo(llvm::errs());
2049 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
2050 llvm::outs() << ResourceDir << '\n';
2054 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
2055 llvm::outs() << "programs: =";
2056 bool separator = false;
2057 // Print -B and COMPILER_PATH.
2058 for (const std::string &Path : PrefixDirs) {
2060 llvm::outs() << llvm::sys::EnvPathSeparator;
2061 llvm::outs() << Path;
2064 for (const std::string &Path : TC.getProgramPaths()) {
2066 llvm::outs() << llvm::sys::EnvPathSeparator;
2067 llvm::outs() << Path;
2070 llvm::outs() << "\n";
2071 llvm::outs() << "libraries: =" << ResourceDir;
2073 StringRef sysroot = C.getSysRoot();
2075 for (const std::string &Path : TC.getFilePaths()) {
2076 // Always print a separator. ResourceDir was the first item shown.
2077 llvm::outs() << llvm::sys::EnvPathSeparator;
2078 // Interpretation of leading '=' is needed only for NetBSD.
2080 llvm::outs() << sysroot << Path.substr(1);
2082 llvm::outs() << Path;
2084 llvm::outs() << "\n";
2088 if (C.getArgs().hasArg(options::OPT_print_runtime_dir)) {
2089 std::string RuntimePath;
2090 // Get the first existing path, if any.
2091 for (auto Path : TC.getRuntimePaths()) {
2092 if (getVFS().exists(Path)) {
2097 if (!RuntimePath.empty())
2098 llvm::outs() << RuntimePath << '\n';
2100 llvm::outs() << TC.getCompilerRTPath() << '\n';
2104 if (C.getArgs().hasArg(options::OPT_print_diagnostic_options)) {
2105 std::vector<std::string> Flags = DiagnosticIDs::getDiagnosticFlags();
2106 for (std::size_t I = 0; I != Flags.size(); I += 2)
2107 llvm::outs() << " " << Flags[I] << "\n " << Flags[I + 1] << "\n\n";
2111 // FIXME: The following handlers should use a callback mechanism, we don't
2112 // know what the client would like to do.
2113 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
2114 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
2118 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
2119 StringRef ProgName = A->getValue();
2121 // Null program name cannot have a path.
2122 if (! ProgName.empty())
2123 llvm::outs() << GetProgramPath(ProgName, TC);
2125 llvm::outs() << "\n";
2129 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
2130 StringRef PassedFlags = A->getValue();
2131 HandleAutocompletions(PassedFlags);
2135 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
2136 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
2137 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
2138 RegisterEffectiveTriple TripleRAII(TC, Triple);
2140 case ToolChain::RLT_CompilerRT:
2141 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
2143 case ToolChain::RLT_Libgcc:
2144 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
2150 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
2151 for (const Multilib &Multilib : TC.getMultilibs())
2152 llvm::outs() << Multilib << "\n";
2156 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
2157 const Multilib &Multilib = TC.getMultilib();
2158 if (Multilib.gccSuffix().empty())
2159 llvm::outs() << ".\n";
2161 StringRef Suffix(Multilib.gccSuffix());
2162 assert(Suffix.front() == '/');
2163 llvm::outs() << Suffix.substr(1) << "\n";
2168 if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
2169 llvm::outs() << TC.getTripleString() << "\n";
2173 if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
2174 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
2175 llvm::outs() << Triple.getTriple() << "\n";
2179 if (C.getArgs().hasArg(options::OPT_print_targets)) {
2180 llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
2193 // Display an action graph human-readably. Action A is the "sink" node
2194 // and latest-occuring action. Traversal is in pre-order, visiting the
2195 // inputs to each action before printing the action itself.
2196 static unsigned PrintActions1(const Compilation &C, Action *A,
2197 std::map<Action *, unsigned> &Ids,
2198 Twine Indent = {}, int Kind = TopLevelAction) {
2199 if (Ids.count(A)) // A was already visited.
2203 llvm::raw_string_ostream os(str);
2205 auto getSibIndent = [](int K) -> Twine {
2206 return (K == HeadSibAction) ? " " : (K == OtherSibAction) ? "| " : "";
2209 Twine SibIndent = Indent + getSibIndent(Kind);
2210 int SibKind = HeadSibAction;
2211 os << Action::getClassName(A->getKind()) << ", ";
2212 if (InputAction *IA = dyn_cast<InputAction>(A)) {
2213 os << "\"" << IA->getInputArg().getValue() << "\"";
2214 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
2215 os << '"' << BIA->getArchName() << '"' << ", {"
2216 << PrintActions1(C, *BIA->input_begin(), Ids, SibIndent, SibKind) << "}";
2217 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
2218 bool IsFirst = true;
2219 OA->doOnEachDependence(
2220 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
2221 assert(TC && "Unknown host toolchain");
2222 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
2223 // sm_35 this will generate:
2224 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
2225 // (nvptx64-nvidia-cuda:sm_35) {#ID}
2229 os << A->getOffloadingKindPrefix();
2231 os << TC->getTriple().normalize();
2233 os << ":" << BoundArch;
2236 os << " {" << PrintActions1(C, A, Ids, SibIndent, SibKind) << "}";
2238 SibKind = OtherSibAction;
2241 const ActionList *AL = &A->getInputs();
2244 const char *Prefix = "{";
2245 for (Action *PreRequisite : *AL) {
2246 os << Prefix << PrintActions1(C, PreRequisite, Ids, SibIndent, SibKind);
2248 SibKind = OtherSibAction;
2255 // Append offload info for all options other than the offloading action
2256 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
2257 std::string offload_str;
2258 llvm::raw_string_ostream offload_os(offload_str);
2259 if (!isa<OffloadAction>(A)) {
2260 auto S = A->getOffloadingKindPrefix();
2262 offload_os << ", (" << S;
2263 if (A->getOffloadingArch())
2264 offload_os << ", " << A->getOffloadingArch();
2269 auto getSelfIndent = [](int K) -> Twine {
2270 return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : "";
2273 unsigned Id = Ids.size();
2275 llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", "
2276 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
2281 // Print the action graphs in a compilation C.
2282 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
2283 void Driver::PrintActions(const Compilation &C) const {
2284 std::map<Action *, unsigned> Ids;
2285 for (Action *A : C.getActions())
2286 PrintActions1(C, A, Ids);
2289 /// Check whether the given input tree contains any compilation or
2290 /// assembly actions.
2291 static bool ContainsCompileOrAssembleAction(const Action *A) {
2292 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
2293 isa<AssembleJobAction>(A))
2296 return llvm::any_of(A->inputs(), ContainsCompileOrAssembleAction);
2299 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
2300 const InputList &BAInputs) const {
2301 DerivedArgList &Args = C.getArgs();
2302 ActionList &Actions = C.getActions();
2303 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
2304 // Collect the list of architectures. Duplicates are allowed, but should only
2305 // be handled once (in the order seen).
2306 llvm::StringSet<> ArchNames;
2307 SmallVector<const char *, 4> Archs;
2308 for (Arg *A : Args) {
2309 if (A->getOption().matches(options::OPT_arch)) {
2310 // Validate the option here; we don't save the type here because its
2311 // particular spelling may participate in other driver choices.
2312 llvm::Triple::ArchType Arch =
2313 tools::darwin::getArchTypeForMachOArchName(A->getValue());
2314 if (Arch == llvm::Triple::UnknownArch) {
2315 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
2320 if (ArchNames.insert(A->getValue()).second)
2321 Archs.push_back(A->getValue());
2325 // When there is no explicit arch for this platform, make sure we still bind
2326 // the architecture (to the default) so that -Xarch_ is handled correctly.
2328 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
2330 ActionList SingleActions;
2331 BuildActions(C, Args, BAInputs, SingleActions);
2333 // Add in arch bindings for every top level action, as well as lipo and
2334 // dsymutil steps if needed.
2335 for (Action* Act : SingleActions) {
2336 // Make sure we can lipo this kind of output. If not (and it is an actual
2337 // output) then we disallow, since we can't create an output file with the
2338 // right name without overwriting it. We could remove this oddity by just
2339 // changing the output names to include the arch, which would also fix
2340 // -save-temps. Compatibility wins for now.
2342 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
2343 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
2344 << types::getTypeName(Act->getType());
2347 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
2348 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
2350 // Lipo if necessary, we do it this way because we need to set the arch flag
2351 // so that -Xarch_ gets overwritten.
2352 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
2353 Actions.append(Inputs.begin(), Inputs.end());
2355 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
2357 // Handle debug info queries.
2358 Arg *A = Args.getLastArg(options::OPT_g_Group);
2359 bool enablesDebugInfo = A && !A->getOption().matches(options::OPT_g0) &&
2360 !A->getOption().matches(options::OPT_gstabs);
2361 if ((enablesDebugInfo || willEmitRemarks(Args)) &&
2362 ContainsCompileOrAssembleAction(Actions.back())) {
2364 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
2365 // have a compile input. We need to run 'dsymutil' ourselves in such cases
2366 // because the debug info will refer to a temporary object file which
2367 // will be removed at the end of the compilation process.
2368 if (Act->getType() == types::TY_Image) {
2370 Inputs.push_back(Actions.back());
2373 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
2376 // Verify the debug info output.
2377 if (Args.hasArg(options::OPT_verify_debug_info)) {
2378 Action* LastAction = Actions.back();
2380 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
2381 LastAction, types::TY_Nothing));
2387 bool Driver::DiagnoseInputExistence(const DerivedArgList &Args, StringRef Value,
2388 types::ID Ty, bool TypoCorrect) const {
2389 if (!getCheckInputsExist())
2392 // stdin always exists.
2396 // If it's a header to be found in the system or user search path, then defer
2397 // complaints about its absence until those searches can be done. When we
2398 // are definitely processing headers for C++20 header units, extend this to
2399 // allow the user to put "-fmodule-header -xc++-header vector" for example.
2400 if (Ty == types::TY_CXXSHeader || Ty == types::TY_CXXUHeader ||
2401 (ModulesModeCXX20 && Ty == types::TY_CXXHeader))
2404 if (getVFS().exists(Value))
2408 // Check if the filename is a typo for an option flag. OptTable thinks
2409 // that all args that are not known options and that start with / are
2410 // filenames, but e.g. `/diagnostic:caret` is more likely a typo for
2411 // the option `/diagnostics:caret` than a reference to a file in the root
2413 unsigned IncludedFlagsBitmask;
2414 unsigned ExcludedFlagsBitmask;
2415 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
2416 getIncludeExcludeOptionFlagMasks(IsCLMode());
2417 std::string Nearest;
2418 if (getOpts().findNearest(Value, Nearest, IncludedFlagsBitmask,
2419 ExcludedFlagsBitmask) <= 1) {
2420 Diag(clang::diag::err_drv_no_such_file_with_suggestion)
2421 << Value << Nearest;
2426 // In CL mode, don't error on apparently non-existent linker inputs, because
2427 // they can be influenced by linker flags the clang driver might not
2430 // - `clang-cl main.cc ole32.lib` in a a non-MSVC shell will make the driver
2431 // module look for an MSVC installation in the registry. (We could ask
2432 // the MSVCToolChain object if it can find `ole32.lib`, but the logic to
2433 // look in the registry might move into lld-link in the future so that
2434 // lld-link invocations in non-MSVC shells just work too.)
2435 // - `clang-cl ... /link ...` can pass arbitrary flags to the linker,
2436 // including /libpath:, which is used to find .lib and .obj files.
2437 // So do not diagnose this on the driver level. Rely on the linker diagnosing
2438 // it. (If we don't end up invoking the linker, this means we'll emit a
2439 // "'linker' input unused [-Wunused-command-line-argument]" warning instead
2442 // Only do this skip after the typo correction step above. `/Brepo` is treated
2443 // as TY_Object, but it's clearly a typo for `/Brepro`. It seems fine to emit
2444 // an error if we have a flag that's within an edit distance of 1 from a
2445 // flag. (Users can use `-Wl,` or `/linker` to launder the flag past the
2446 // driver in the unlikely case they run into this.)
2448 // Don't do this for inputs that start with a '/', else we'd pass options
2449 // like /libpath: through to the linker silently.
2451 // Emitting an error for linker inputs can also cause incorrect diagnostics
2452 // with the gcc driver. The command
2453 // clang -fuse-ld=lld -Wl,--chroot,some/dir /file.o
2454 // will make lld look for some/dir/file.o, while we will diagnose here that
2455 // `/file.o` does not exist. However, configure scripts check if
2456 // `clang /GR-` compiles without error to see if the compiler is cl.exe,
2457 // so we can't downgrade diagnostics for `/GR-` from an error to a warning
2458 // in cc mode. (We can in cl mode because cl.exe itself only warns on
2460 if (IsCLMode() && Ty == types::TY_Object && !Value.startswith("/"))
2463 Diag(clang::diag::err_drv_no_such_file) << Value;
2467 // Get the C++20 Header Unit type corresponding to the input type.
2468 static types::ID CXXHeaderUnitType(ModuleHeaderMode HM) {
2470 case HeaderMode_User:
2471 return types::TY_CXXUHeader;
2472 case HeaderMode_System:
2473 return types::TY_CXXSHeader;
2474 case HeaderMode_Default:
2476 case HeaderMode_None:
2477 llvm_unreachable("should not be called in this case");
2479 return types::TY_CXXHUHeader;
2482 // Construct a the list of inputs and their types.
2483 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
2484 InputList &Inputs) const {
2485 const llvm::opt::OptTable &Opts = getOpts();
2486 // Track the current user specified (-x) input. We also explicitly track the
2487 // argument used to set the type; we only want to claim the type when we
2488 // actually use it, so we warn about unused -x arguments.
2489 types::ID InputType = types::TY_Nothing;
2490 Arg *InputTypeArg = nullptr;
2492 // The last /TC or /TP option sets the input type to C or C++ globally.
2493 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
2494 options::OPT__SLASH_TP)) {
2495 InputTypeArg = TCTP;
2496 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
2500 Arg *Previous = nullptr;
2501 bool ShowNote = false;
2503 Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
2505 Diag(clang::diag::warn_drv_overriding_flag_option)
2506 << Previous->getSpelling() << A->getSpelling();
2512 Diag(clang::diag::note_drv_t_option_is_global);
2514 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
2515 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
2518 // Warn -x after last input file has no effect
2520 Arg *LastXArg = Args.getLastArgNoClaim(options::OPT_x);
2521 Arg *LastInputArg = Args.getLastArgNoClaim(options::OPT_INPUT);
2522 if (LastXArg && LastInputArg && LastInputArg->getIndex() < LastXArg->getIndex())
2523 Diag(clang::diag::warn_drv_unused_x) << LastXArg->getValue();
2526 for (Arg *A : Args) {
2527 if (A->getOption().getKind() == Option::InputClass) {
2528 const char *Value = A->getValue();
2529 types::ID Ty = types::TY_INVALID;
2531 // Infer the input type if necessary.
2532 if (InputType == types::TY_Nothing) {
2533 // If there was an explicit arg for this, claim it.
2535 InputTypeArg->claim();
2537 // stdin must be handled specially.
2538 if (memcmp(Value, "-", 2) == 0) {
2539 if (IsFlangMode()) {
2540 Ty = types::TY_Fortran;
2542 // If running with -E, treat as a C input (this changes the
2543 // builtin macros, for example). This may be overridden by -ObjC
2546 // Otherwise emit an error but still use a valid type to avoid
2547 // spurious errors (e.g., no inputs).
2548 assert(!CCGenDiagnostics && "stdin produces no crash reproducer");
2549 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
2550 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2551 : clang::diag::err_drv_unknown_stdin_type);
2555 // Otherwise lookup by extension.
2556 // Fallback is C if invoked as C preprocessor, C++ if invoked with
2557 // clang-cl /E, or Object otherwise.
2558 // We use a host hook here because Darwin at least has its own
2559 // idea of what .s is.
2560 if (const char *Ext = strrchr(Value, '.'))
2561 Ty = TC.LookupTypeForExtension(Ext + 1);
2563 if (Ty == types::TY_INVALID) {
2564 if (IsCLMode() && (Args.hasArgNoClaim(options::OPT_E) || CCGenDiagnostics))
2566 else if (CCCIsCPP() || CCGenDiagnostics)
2569 Ty = types::TY_Object;
2572 // If the driver is invoked as C++ compiler (like clang++ or c++) it
2573 // should autodetect some input files as C++ for g++ compatibility.
2575 types::ID OldTy = Ty;
2576 Ty = types::lookupCXXTypeForCType(Ty);
2578 // Do not complain about foo.h, when we are known to be processing
2579 // it as a C++20 header unit.
2580 if (Ty != OldTy && !(OldTy == types::TY_CHeader && hasHeaderMode()))
2581 Diag(clang::diag::warn_drv_treating_input_as_cxx)
2582 << getTypeName(OldTy) << getTypeName(Ty);
2585 // If running with -fthinlto-index=, extensions that normally identify
2586 // native object files actually identify LLVM bitcode files.
2587 if (Args.hasArgNoClaim(options::OPT_fthinlto_index_EQ) &&
2588 Ty == types::TY_Object)
2589 Ty = types::TY_LLVM_BC;
2592 // -ObjC and -ObjC++ override the default language, but only for "source
2593 // files". We just treat everything that isn't a linker input as a
2596 // FIXME: Clean this up if we move the phase sequence into the type.
2597 if (Ty != types::TY_Object) {
2598 if (Args.hasArg(options::OPT_ObjC))
2599 Ty = types::TY_ObjC;
2600 else if (Args.hasArg(options::OPT_ObjCXX))
2601 Ty = types::TY_ObjCXX;
2604 // Disambiguate headers that are meant to be header units from those
2605 // intended to be PCH. Avoid missing '.h' cases that are counted as
2606 // C headers by default - we know we are in C++ mode and we do not
2607 // want to issue a complaint about compiling things in the wrong mode.
2608 if ((Ty == types::TY_CXXHeader || Ty == types::TY_CHeader) &&
2610 Ty = CXXHeaderUnitType(CXX20HeaderType);
2612 assert(InputTypeArg && "InputType set w/o InputTypeArg");
2613 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2614 // If emulating cl.exe, make sure that /TC and /TP don't affect input
2616 const char *Ext = strrchr(Value, '.');
2617 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2618 Ty = types::TY_Object;
2620 if (Ty == types::TY_INVALID) {
2622 InputTypeArg->claim();
2626 if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true))
2627 Inputs.push_back(std::make_pair(Ty, A));
2629 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2630 StringRef Value = A->getValue();
2631 if (DiagnoseInputExistence(Args, Value, types::TY_C,
2632 /*TypoCorrect=*/false)) {
2633 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2634 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2637 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2638 StringRef Value = A->getValue();
2639 if (DiagnoseInputExistence(Args, Value, types::TY_CXX,
2640 /*TypoCorrect=*/false)) {
2641 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2642 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2645 } else if (A->getOption().hasFlag(options::LinkerInput)) {
2646 // Just treat as object type, we could make a special type for this if
2648 Inputs.push_back(std::make_pair(types::TY_Object, A));
2650 } else if (A->getOption().matches(options::OPT_x)) {
2652 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
2655 // Follow gcc behavior and treat as linker input for invalid -x
2656 // options. Its not clear why we shouldn't just revert to unknown; but
2657 // this isn't very important, we might as well be bug compatible.
2659 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
2660 InputType = types::TY_Object;
2663 // If the user has put -fmodule-header{,=} then we treat C++ headers as
2664 // header unit inputs. So we 'promote' -xc++-header appropriately.
2665 if (InputType == types::TY_CXXHeader && hasHeaderMode())
2666 InputType = CXXHeaderUnitType(CXX20HeaderType);
2667 } else if (A->getOption().getID() == options::OPT_U) {
2668 assert(A->getNumValues() == 1 && "The /U option has one value.");
2669 StringRef Val = A->getValue(0);
2670 if (Val.find_first_of("/\\") != StringRef::npos) {
2671 // Warn about e.g. "/Users/me/myfile.c".
2672 Diag(diag::warn_slash_u_filename) << Val;
2673 Diag(diag::note_use_dashdash);
2677 if (CCCIsCPP() && Inputs.empty()) {
2678 // If called as standalone preprocessor, stdin is processed
2679 // if no other input is present.
2680 Arg *A = MakeInputArg(Args, Opts, "-");
2681 Inputs.push_back(std::make_pair(types::TY_C, A));
2686 /// Provides a convenient interface for different programming models to generate
2687 /// the required device actions.
2688 class OffloadingActionBuilder final {
2689 /// Flag used to trace errors in the builder.
2690 bool IsValid = false;
2692 /// The compilation that is using this builder.
2695 /// Map between an input argument and the offload kinds used to process it.
2696 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2698 /// Map between a host action and its originating input argument.
2699 std::map<Action *, const Arg *> HostActionToInputArgMap;
2701 /// Builder interface. It doesn't build anything or keep any state.
2702 class DeviceActionBuilder {
2704 typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy;
2706 enum ActionBuilderReturnCode {
2707 // The builder acted successfully on the current action.
2709 // The builder didn't have to act on the current action.
2711 // The builder was successful and requested the host action to not be
2717 /// Compilation associated with this builder.
2720 /// Tool chains associated with this builder. The same programming
2721 /// model may have associated one or more tool chains.
2722 SmallVector<const ToolChain *, 2> ToolChains;
2724 /// The derived arguments associated with this builder.
2725 DerivedArgList &Args;
2727 /// The inputs associated with this builder.
2728 const Driver::InputList &Inputs;
2730 /// The associated offload kind.
2731 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2734 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2735 const Driver::InputList &Inputs,
2736 Action::OffloadKind AssociatedOffloadKind)
2737 : C(C), Args(Args), Inputs(Inputs),
2738 AssociatedOffloadKind(AssociatedOffloadKind) {}
2739 virtual ~DeviceActionBuilder() {}
2741 /// Fill up the array \a DA with all the device dependences that should be
2742 /// added to the provided host action \a HostAction. By default it is
2744 virtual ActionBuilderReturnCode
2745 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2746 phases::ID CurPhase, phases::ID FinalPhase,
2748 return ABRT_Inactive;
2751 /// Update the state to include the provided host action \a HostAction as a
2752 /// dependency of the current device action. By default it is inactive.
2753 virtual ActionBuilderReturnCode addDeviceDependences(Action *HostAction) {
2754 return ABRT_Inactive;
2757 /// Append top level actions generated by the builder.
2758 virtual void appendTopLevelActions(ActionList &AL) {}
2760 /// Append linker device actions generated by the builder.
2761 virtual void appendLinkDeviceActions(ActionList &AL) {}
2763 /// Append linker host action generated by the builder.
2764 virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; }
2766 /// Append linker actions generated by the builder.
2767 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2769 /// Initialize the builder. Return true if any initialization errors are
2771 virtual bool initialize() { return false; }
2773 /// Return true if the builder can use bundling/unbundling.
2774 virtual bool canUseBundlerUnbundler() const { return false; }
2776 /// Return true if this builder is valid. We have a valid builder if we have
2777 /// associated device tool chains.
2778 bool isValid() { return !ToolChains.empty(); }
2780 /// Return the associated offload kind.
2781 Action::OffloadKind getAssociatedOffloadKind() {
2782 return AssociatedOffloadKind;
2786 /// Base class for CUDA/HIP action builder. It injects device code in
2787 /// the host backend action.
2788 class CudaActionBuilderBase : public DeviceActionBuilder {
2790 /// Flags to signal if the user requested host-only or device-only
2792 bool CompileHostOnly = false;
2793 bool CompileDeviceOnly = false;
2794 bool EmitLLVM = false;
2795 bool EmitAsm = false;
2797 /// ID to identify each device compilation. For CUDA it is simply the
2798 /// GPU arch string. For HIP it is either the GPU arch string or GPU
2799 /// arch string plus feature strings delimited by a plus sign, e.g.
2802 /// Target ID string which is persistent throughout the compilation.
2804 TargetID(CudaArch Arch) { ID = CudaArchToString(Arch); }
2805 TargetID(const char *ID) : ID(ID) {}
2806 operator const char *() { return ID; }
2807 operator StringRef() { return StringRef(ID); }
2809 /// List of GPU architectures to use in this compilation.
2810 SmallVector<TargetID, 4> GpuArchList;
2812 /// The CUDA actions for the current input.
2813 ActionList CudaDeviceActions;
2815 /// The CUDA fat binary if it was generated for the current input.
2816 Action *CudaFatBinary = nullptr;
2818 /// Flag that is set to true if this builder acted on the current input.
2819 bool IsActive = false;
2821 /// Flag for -fgpu-rdc.
2822 bool Relocatable = false;
2824 /// Default GPU architecture if there's no one specified.
2825 CudaArch DefaultCudaArch = CudaArch::UNKNOWN;
2827 /// Method to generate compilation unit ID specified by option
2829 enum UseCUIDKind { CUID_Hash, CUID_Random, CUID_None, CUID_Invalid };
2830 UseCUIDKind UseCUID = CUID_Hash;
2832 /// Compilation unit ID specified by option '-cuid='.
2833 StringRef FixedCUID;
2836 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2837 const Driver::InputList &Inputs,
2838 Action::OffloadKind OFKind)
2839 : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
2841 ActionBuilderReturnCode addDeviceDependences(Action *HostAction) override {
2842 // While generating code for CUDA, we only depend on the host input action
2843 // to trigger the creation of all the CUDA device actions.
2845 // If we are dealing with an input action, replicate it for each GPU
2846 // architecture. If we are in host-only mode we return 'success' so that
2847 // the host uses the CUDA offload kind.
2848 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2849 assert(!GpuArchList.empty() &&
2850 "We should have at least one GPU architecture.");
2852 // If the host input is not CUDA or HIP, we don't need to bother about
2854 if (!(IA->getType() == types::TY_CUDA ||
2855 IA->getType() == types::TY_HIP ||
2856 IA->getType() == types::TY_PP_HIP)) {
2857 // The builder will ignore this input.
2859 return ABRT_Inactive;
2862 // Set the flag to true, so that the builder acts on the current input.
2865 if (CompileHostOnly)
2866 return ABRT_Success;
2868 // Replicate inputs for each GPU architecture.
2869 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2870 : types::TY_CUDA_DEVICE;
2871 std::string CUID = FixedCUID.str();
2873 if (UseCUID == CUID_Random)
2874 CUID = llvm::utohexstr(llvm::sys::Process::GetRandomNumber(),
2875 /*LowerCase=*/true);
2876 else if (UseCUID == CUID_Hash) {
2878 llvm::MD5::MD5Result Hash;
2879 SmallString<256> RealPath;
2880 llvm::sys::fs::real_path(IA->getInputArg().getValue(), RealPath,
2881 /*expand_tilde=*/true);
2882 Hasher.update(RealPath);
2883 for (auto *A : Args) {
2884 if (A->getOption().matches(options::OPT_INPUT))
2886 Hasher.update(A->getAsString(Args));
2889 CUID = llvm::utohexstr(Hash.low(), /*LowerCase=*/true);
2894 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2895 CudaDeviceActions.push_back(
2896 C.MakeAction<InputAction>(IA->getInputArg(), Ty, IA->getId()));
2899 return ABRT_Success;
2902 // If this is an unbundling action use it as is for each CUDA toolchain.
2903 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2905 // If -fgpu-rdc is disabled, should not unbundle since there is no
2906 // device code to link.
2907 if (UA->getType() == types::TY_Object && !Relocatable)
2908 return ABRT_Inactive;
2910 CudaDeviceActions.clear();
2911 auto *IA = cast<InputAction>(UA->getInputs().back());
2912 std::string FileName = IA->getInputArg().getAsString(Args);
2913 // Check if the type of the file is the same as the action. Do not
2914 // unbundle it if it is not. Do not unbundle .so files, for example,
2915 // which are not object files. Files with extension ".lib" is classified
2916 // as TY_Object but they are actually archives, therefore should not be
2917 // unbundled here as objects. They will be handled at other places.
2918 const StringRef LibFileExt = ".lib";
2919 if (IA->getType() == types::TY_Object &&
2920 (!llvm::sys::path::has_extension(FileName) ||
2921 types::lookupTypeForExtension(
2922 llvm::sys::path::extension(FileName).drop_front()) !=
2924 llvm::sys::path::extension(FileName) == LibFileExt))
2925 return ABRT_Inactive;
2927 for (auto Arch : GpuArchList) {
2928 CudaDeviceActions.push_back(UA);
2929 UA->registerDependentActionInfo(ToolChains[0], Arch,
2930 AssociatedOffloadKind);
2933 return ABRT_Success;
2936 return IsActive ? ABRT_Success : ABRT_Inactive;
2939 void appendTopLevelActions(ActionList &AL) override {
2940 // Utility to append actions to the top level list.
2941 auto AddTopLevel = [&](Action *A, TargetID TargetID) {
2942 OffloadAction::DeviceDependences Dep;
2943 Dep.add(*A, *ToolChains.front(), TargetID, AssociatedOffloadKind);
2944 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2947 // If we have a fat binary, add it to the list.
2948 if (CudaFatBinary) {
2949 AddTopLevel(CudaFatBinary, CudaArch::UNUSED);
2950 CudaDeviceActions.clear();
2951 CudaFatBinary = nullptr;
2955 if (CudaDeviceActions.empty())
2958 // If we have CUDA actions at this point, that's because we have a have
2959 // partial compilation, so we should have an action for each GPU
2961 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2962 "Expecting one action per GPU architecture.");
2963 assert(ToolChains.size() == 1 &&
2964 "Expecting to have a single CUDA toolchain.");
2965 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2966 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2968 CudaDeviceActions.clear();
2971 /// Get canonicalized offload arch option. \returns empty StringRef if the
2972 /// option is invalid.
2973 virtual StringRef getCanonicalOffloadArch(StringRef Arch) = 0;
2975 virtual llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>>
2976 getConflictOffloadArchCombination(const std::set<StringRef> &GpuArchs) = 0;
2978 bool initialize() override {
2979 assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2980 AssociatedOffloadKind == Action::OFK_HIP);
2982 // We don't need to support CUDA.
2983 if (AssociatedOffloadKind == Action::OFK_Cuda &&
2984 !C.hasOffloadToolChain<Action::OFK_Cuda>())
2987 // We don't need to support HIP.
2988 if (AssociatedOffloadKind == Action::OFK_HIP &&
2989 !C.hasOffloadToolChain<Action::OFK_HIP>())
2992 Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2993 options::OPT_fno_gpu_rdc, /*Default=*/false);
2995 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2996 assert(HostTC && "No toolchain for host compilation.");
2997 if (HostTC->getTriple().isNVPTX() ||
2998 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2999 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
3000 // an error and abort pipeline construction early so we don't trip
3001 // asserts that assume device-side compilation.
3002 C.getDriver().Diag(diag::err_drv_cuda_host_arch)
3003 << HostTC->getTriple().getArchName();
3007 ToolChains.push_back(
3008 AssociatedOffloadKind == Action::OFK_Cuda
3009 ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3010 : C.getSingleOffloadToolChain<Action::OFK_HIP>());
3012 CompileHostOnly = C.getDriver().offloadHostOnly();
3013 CompileDeviceOnly = C.getDriver().offloadDeviceOnly();
3014 EmitLLVM = Args.getLastArg(options::OPT_emit_llvm);
3015 EmitAsm = Args.getLastArg(options::OPT_S);
3016 FixedCUID = Args.getLastArgValue(options::OPT_cuid_EQ);
3017 if (Arg *A = Args.getLastArg(options::OPT_fuse_cuid_EQ)) {
3018 StringRef UseCUIDStr = A->getValue();
3019 UseCUID = llvm::StringSwitch<UseCUIDKind>(UseCUIDStr)
3020 .Case("hash", CUID_Hash)
3021 .Case("random", CUID_Random)
3022 .Case("none", CUID_None)
3023 .Default(CUID_Invalid);
3024 if (UseCUID == CUID_Invalid) {
3025 C.getDriver().Diag(diag::err_drv_invalid_value)
3026 << A->getAsString(Args) << UseCUIDStr;
3027 C.setContainsError();
3032 // --offload and --offload-arch options are mutually exclusive.
3033 if (Args.hasArgNoClaim(options::OPT_offload_EQ) &&
3034 Args.hasArgNoClaim(options::OPT_offload_arch_EQ,
3035 options::OPT_no_offload_arch_EQ)) {
3036 C.getDriver().Diag(diag::err_opt_not_valid_with_opt) << "--offload-arch"
3040 // Collect all offload arch parameters, removing duplicates.
3041 std::set<StringRef> GpuArchs;
3043 for (Arg *A : Args) {
3044 if (!(A->getOption().matches(options::OPT_offload_arch_EQ) ||
3045 A->getOption().matches(options::OPT_no_offload_arch_EQ)))
3049 for (StringRef ArchStr : llvm::split(A->getValue(), ",")) {
3050 if (A->getOption().matches(options::OPT_no_offload_arch_EQ) &&
3054 ArchStr = getCanonicalOffloadArch(ArchStr);
3055 if (ArchStr.empty()) {
3057 } else if (A->getOption().matches(options::OPT_offload_arch_EQ))
3058 GpuArchs.insert(ArchStr);
3059 else if (A->getOption().matches(options::OPT_no_offload_arch_EQ))
3060 GpuArchs.erase(ArchStr);
3062 llvm_unreachable("Unexpected option.");
3067 auto &&ConflictingArchs = getConflictOffloadArchCombination(GpuArchs);
3068 if (ConflictingArchs) {
3069 C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo)
3070 << ConflictingArchs->first << ConflictingArchs->second;
3071 C.setContainsError();
3075 // Collect list of GPUs remaining in the set.
3076 for (auto Arch : GpuArchs)
3077 GpuArchList.push_back(Arch.data());
3079 // Default to sm_20 which is the lowest common denominator for
3080 // supported GPUs. sm_20 code should work correctly, if
3081 // suboptimally, on all newer GPUs.
3082 if (GpuArchList.empty()) {
3083 if (ToolChains.front()->getTriple().isSPIRV())
3084 GpuArchList.push_back(CudaArch::Generic);
3086 GpuArchList.push_back(DefaultCudaArch);
3093 /// \brief CUDA action builder. It injects device code in the host backend
3095 class CudaActionBuilder final : public CudaActionBuilderBase {
3097 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
3098 const Driver::InputList &Inputs)
3099 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {
3100 DefaultCudaArch = CudaArch::SM_35;
3103 StringRef getCanonicalOffloadArch(StringRef ArchStr) override {
3104 CudaArch Arch = StringToCudaArch(ArchStr);
3105 if (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch)) {
3106 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
3109 return CudaArchToString(Arch);
3112 llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>>
3113 getConflictOffloadArchCombination(
3114 const std::set<StringRef> &GpuArchs) override {
3118 ActionBuilderReturnCode
3119 getDeviceDependences(OffloadAction::DeviceDependences &DA,
3120 phases::ID CurPhase, phases::ID FinalPhase,
3121 PhasesTy &Phases) override {
3123 return ABRT_Inactive;
3125 // If we don't have more CUDA actions, we don't have any dependences to
3126 // create for the host.
3127 if (CudaDeviceActions.empty())
3128 return ABRT_Success;
3130 assert(CudaDeviceActions.size() == GpuArchList.size() &&
3131 "Expecting one action per GPU architecture.");
3132 assert(!CompileHostOnly &&
3133 "Not expecting CUDA actions in host-only compilation.");
3135 // If we are generating code for the device or we are in a backend phase,
3136 // we attempt to generate the fat binary. We compile each arch to ptx and
3137 // assemble to cubin, then feed the cubin *and* the ptx into a device
3138 // "link" action, which uses fatbinary to combine these cubins into one
3139 // fatbin. The fatbin is then an input to the host action if not in
3140 // device-only mode.
3141 if (CompileDeviceOnly || CurPhase == phases::Backend) {
3142 ActionList DeviceActions;
3143 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3144 // Produce the device action from the current phase up to the assemble
3146 for (auto Ph : Phases) {
3147 // Skip the phases that were already dealt with.
3150 // We have to be consistent with the host final phase.
3151 if (Ph > FinalPhase)
3154 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
3155 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
3157 if (Ph == phases::Assemble)
3161 // If we didn't reach the assemble phase, we can't generate the fat
3162 // binary. We don't need to generate the fat binary if we are not in
3163 // device-only mode.
3164 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
3168 Action *AssembleAction = CudaDeviceActions[I];
3169 assert(AssembleAction->getType() == types::TY_Object);
3170 assert(AssembleAction->getInputs().size() == 1);
3172 Action *BackendAction = AssembleAction->getInputs()[0];
3173 assert(BackendAction->getType() == types::TY_PP_Asm);
3175 for (auto &A : {AssembleAction, BackendAction}) {
3176 OffloadAction::DeviceDependences DDep;
3177 DDep.add(*A, *ToolChains.front(), GpuArchList[I], Action::OFK_Cuda);
3178 DeviceActions.push_back(
3179 C.MakeAction<OffloadAction>(DDep, A->getType()));
3183 // We generate the fat binary if we have device input actions.
3184 if (!DeviceActions.empty()) {
3186 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
3188 if (!CompileDeviceOnly) {
3189 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
3191 // Clear the fat binary, it is already a dependence to an host
3193 CudaFatBinary = nullptr;
3196 // Remove the CUDA actions as they are already connected to an host
3197 // action or fat binary.
3198 CudaDeviceActions.clear();
3201 // We avoid creating host action in device-only mode.
3202 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
3203 } else if (CurPhase > phases::Backend) {
3204 // If we are past the backend phase and still have a device action, we
3205 // don't have to do anything as this action is already a device
3206 // top-level action.
3207 return ABRT_Success;
3210 assert(CurPhase < phases::Backend && "Generating single CUDA "
3211 "instructions should only occur "
3212 "before the backend phase!");
3214 // By default, we produce an action for each device arch.
3215 for (Action *&A : CudaDeviceActions)
3216 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
3218 return ABRT_Success;
3221 /// \brief HIP action builder. It injects device code in the host backend
3223 class HIPActionBuilder final : public CudaActionBuilderBase {
3224 /// The linker inputs obtained for each device arch.
3225 SmallVector<ActionList, 8> DeviceLinkerInputs;
3226 // The default bundling behavior depends on the type of output, therefore
3227 // BundleOutput needs to be tri-value: None, true, or false.
3228 // Bundle code objects except --no-gpu-output is specified for device
3229 // only compilation. Bundle other type of output files only if
3230 // --gpu-bundle-output is specified for device only compilation.
3231 Optional<bool> BundleOutput;
3234 HIPActionBuilder(Compilation &C, DerivedArgList &Args,
3235 const Driver::InputList &Inputs)
3236 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {
3237 DefaultCudaArch = CudaArch::GFX803;
3238 if (Args.hasArg(options::OPT_gpu_bundle_output,
3239 options::OPT_no_gpu_bundle_output))
3240 BundleOutput = Args.hasFlag(options::OPT_gpu_bundle_output,
3241 options::OPT_no_gpu_bundle_output, true);
3244 bool canUseBundlerUnbundler() const override { return true; }
3246 StringRef getCanonicalOffloadArch(StringRef IdStr) override {
3247 llvm::StringMap<bool> Features;
3248 // getHIPOffloadTargetTriple() is known to return valid value as it has
3249 // been called successfully in the CreateOffloadingDeviceToolChains().
3250 auto ArchStr = parseTargetID(
3251 *getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs()), IdStr,
3254 C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << IdStr;
3255 C.setContainsError();
3258 auto CanId = getCanonicalTargetID(*ArchStr, Features);
3259 return Args.MakeArgStringRef(CanId);
3262 llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>>
3263 getConflictOffloadArchCombination(
3264 const std::set<StringRef> &GpuArchs) override {
3265 return getConflictTargetIDCombination(GpuArchs);
3268 ActionBuilderReturnCode
3269 getDeviceDependences(OffloadAction::DeviceDependences &DA,
3270 phases::ID CurPhase, phases::ID FinalPhase,
3271 PhasesTy &Phases) override {
3273 return ABRT_Inactive;
3275 // amdgcn does not support linking of object files, therefore we skip
3276 // backend and assemble phases to output LLVM IR. Except for generating
3277 // non-relocatable device code, where we generate fat binary for device
3278 // code and pass to host in Backend phase.
3279 if (CudaDeviceActions.empty())
3280 return ABRT_Success;
3282 assert(((CurPhase == phases::Link && Relocatable) ||
3283 CudaDeviceActions.size() == GpuArchList.size()) &&
3284 "Expecting one action per GPU architecture.");
3285 assert(!CompileHostOnly &&
3286 "Not expecting HIP actions in host-only compilation.");
3288 if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM &&
3290 // If we are in backend phase, we attempt to generate the fat binary.
3291 // We compile each arch to IR and use a link action to generate code
3292 // object containing ISA. Then we use a special "link" action to create
3293 // a fat binary containing all the code objects for different GPU's.
3294 // The fat binary is then an input to the host action.
3295 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3296 if (C.getDriver().isUsingLTO(/*IsOffload=*/true)) {
3297 // When LTO is enabled, skip the backend and assemble phases and
3298 // use lld to link the bitcode.
3300 AL.push_back(CudaDeviceActions[I]);
3301 // Create a link action to link device IR with device library
3302 // and generate ISA.
3303 CudaDeviceActions[I] =
3304 C.MakeAction<LinkJobAction>(AL, types::TY_Image);
3306 // When LTO is not enabled, we follow the conventional
3307 // compiler phases, including backend and assemble phases.
3309 Action *BackendAction = nullptr;
3310 if (ToolChains.front()->getTriple().isSPIRV()) {
3311 // Emit LLVM bitcode for SPIR-V targets. SPIR-V device tool chain
3312 // (HIPSPVToolChain) runs post-link LLVM IR passes.
3313 types::ID Output = Args.hasArg(options::OPT_S)
3315 : types::TY_LLVM_BC;
3317 C.MakeAction<BackendJobAction>(CudaDeviceActions[I], Output);
3319 BackendAction = C.getDriver().ConstructPhaseAction(
3320 C, Args, phases::Backend, CudaDeviceActions[I],
3321 AssociatedOffloadKind);
3322 auto AssembleAction = C.getDriver().ConstructPhaseAction(
3323 C, Args, phases::Assemble, BackendAction,
3324 AssociatedOffloadKind);
3325 AL.push_back(AssembleAction);
3326 // Create a link action to link device IR with device library
3327 // and generate ISA.
3328 CudaDeviceActions[I] =
3329 C.MakeAction<LinkJobAction>(AL, types::TY_Image);
3332 // OffloadingActionBuilder propagates device arch until an offload
3333 // action. Since the next action for creating fatbin does
3334 // not have device arch, whereas the above link action and its input
3335 // have device arch, an offload action is needed to stop the null
3336 // device arch of the next action being propagated to the above link
3338 OffloadAction::DeviceDependences DDep;
3339 DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I],
3340 AssociatedOffloadKind);
3341 CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
3342 DDep, CudaDeviceActions[I]->getType());
3345 if (!CompileDeviceOnly || !BundleOutput || *BundleOutput) {
3346 // Create HIP fat binary with a special "link" action.
3347 CudaFatBinary = C.MakeAction<LinkJobAction>(CudaDeviceActions,
3348 types::TY_HIP_FATBIN);
3350 if (!CompileDeviceOnly) {
3351 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
3352 AssociatedOffloadKind);
3353 // Clear the fat binary, it is already a dependence to an host
3355 CudaFatBinary = nullptr;
3358 // Remove the CUDA actions as they are already connected to an host
3359 // action or fat binary.
3360 CudaDeviceActions.clear();
3363 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
3364 } else if (CurPhase == phases::Link) {
3365 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
3366 // This happens to each device action originated from each input file.
3367 // Later on, device actions in DeviceLinkerInputs are used to create
3368 // device link actions in appendLinkDependences and the created device
3369 // link actions are passed to the offload action as device dependence.
3370 DeviceLinkerInputs.resize(CudaDeviceActions.size());
3371 auto LI = DeviceLinkerInputs.begin();
3372 for (auto *A : CudaDeviceActions) {
3377 // We will pass the device action as a host dependence, so we don't
3378 // need to do anything else with them.
3379 CudaDeviceActions.clear();
3380 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
3383 // By default, we produce an action for each device arch.
3384 for (Action *&A : CudaDeviceActions)
3385 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
3386 AssociatedOffloadKind);
3388 if (CompileDeviceOnly && CurPhase == FinalPhase && BundleOutput &&
3389 BundleOutput.value()) {
3390 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3391 OffloadAction::DeviceDependences DDep;
3392 DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I],
3393 AssociatedOffloadKind);
3394 CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
3395 DDep, CudaDeviceActions[I]->getType());
3398 C.MakeAction<OffloadBundlingJobAction>(CudaDeviceActions);
3399 CudaDeviceActions.clear();
3402 return (CompileDeviceOnly && CurPhase == FinalPhase) ? ABRT_Ignore_Host
3406 void appendLinkDeviceActions(ActionList &AL) override {
3407 if (DeviceLinkerInputs.size() == 0)
3410 assert(DeviceLinkerInputs.size() == GpuArchList.size() &&
3411 "Linker inputs and GPU arch list sizes do not match.");
3415 // Append a new link action for each device.
3416 // Each entry in DeviceLinkerInputs corresponds to a GPU arch.
3417 for (auto &LI : DeviceLinkerInputs) {
3419 types::ID Output = Args.hasArg(options::OPT_emit_llvm)
3423 auto *DeviceLinkAction = C.MakeAction<LinkJobAction>(LI, Output);
3424 // Linking all inputs for the current GPU arch.
3425 // LI contains all the inputs for the linker.
3426 OffloadAction::DeviceDependences DeviceLinkDeps;
3427 DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0],
3428 GpuArchList[I], AssociatedOffloadKind);
3429 Actions.push_back(C.MakeAction<OffloadAction>(
3430 DeviceLinkDeps, DeviceLinkAction->getType()));
3433 DeviceLinkerInputs.clear();
3435 // If emitting LLVM, do not generate final host/device compilation action
3436 if (Args.hasArg(options::OPT_emit_llvm)) {
3441 // Create a host object from all the device images by embedding them
3442 // in a fat binary for mixed host-device compilation. For device-only
3443 // compilation, creates a fat binary.
3444 OffloadAction::DeviceDependences DDeps;
3445 if (!CompileDeviceOnly || !BundleOutput || *BundleOutput) {
3446 auto *TopDeviceLinkAction = C.MakeAction<LinkJobAction>(
3448 CompileDeviceOnly ? types::TY_HIP_FATBIN : types::TY_Object);
3449 DDeps.add(*TopDeviceLinkAction, *ToolChains[0], nullptr,
3450 AssociatedOffloadKind);
3451 // Offload the host object to the host linker.
3453 C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType()));
3459 Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); }
3461 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
3465 /// TODO: Add the implementation for other specialized builders here.
3468 /// Specialized builders being used by this offloading action builder.
3469 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
3471 /// Flag set to true if all valid builders allow file bundling/unbundling.
3475 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
3476 const Driver::InputList &Inputs)
3478 // Create a specialized builder for each device toolchain.
3482 // Create a specialized builder for CUDA.
3483 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
3485 // Create a specialized builder for HIP.
3486 SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
3489 // TODO: Build other specialized builders here.
3492 // Initialize all the builders, keeping track of errors. If all valid
3493 // builders agree that we can use bundling, set the flag to true.
3494 unsigned ValidBuilders = 0u;
3495 unsigned ValidBuildersSupportingBundling = 0u;
3496 for (auto *SB : SpecializedBuilders) {
3497 IsValid = IsValid && !SB->initialize();
3499 // Update the counters if the builder is valid.
3500 if (SB->isValid()) {
3502 if (SB->canUseBundlerUnbundler())
3503 ++ValidBuildersSupportingBundling;
3507 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
3510 ~OffloadingActionBuilder() {
3511 for (auto *SB : SpecializedBuilders)
3515 /// Record a host action and its originating input argument.
3516 void recordHostAction(Action *HostAction, const Arg *InputArg) {
3517 assert(HostAction && "Invalid host action");
3518 assert(InputArg && "Invalid input argument");
3519 auto Loc = HostActionToInputArgMap.find(HostAction);
3520 if (Loc == HostActionToInputArgMap.end())
3521 HostActionToInputArgMap[HostAction] = InputArg;
3522 assert(HostActionToInputArgMap[HostAction] == InputArg &&
3523 "host action mapped to multiple input arguments");
3526 /// Generate an action that adds device dependences (if any) to a host action.
3527 /// If no device dependence actions exist, just return the host action \a
3528 /// HostAction. If an error is found or if no builder requires the host action
3529 /// to be generated, return nullptr.
3531 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
3532 phases::ID CurPhase, phases::ID FinalPhase,
3533 DeviceActionBuilder::PhasesTy &Phases) {
3537 if (SpecializedBuilders.empty())
3540 assert(HostAction && "Invalid host action!");
3541 recordHostAction(HostAction, InputArg);
3543 OffloadAction::DeviceDependences DDeps;
3544 // Check if all the programming models agree we should not emit the host
3545 // action. Also, keep track of the offloading kinds employed.
3546 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3547 unsigned InactiveBuilders = 0u;
3548 unsigned IgnoringBuilders = 0u;
3549 for (auto *SB : SpecializedBuilders) {
3550 if (!SB->isValid()) {
3556 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
3558 // If the builder explicitly says the host action should be ignored,
3559 // we need to increment the variable that tracks the builders that request
3560 // the host object to be ignored.
3561 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
3564 // Unless the builder was inactive for this action, we have to record the
3565 // offload kind because the host will have to use it.
3566 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3567 OffloadKind |= SB->getAssociatedOffloadKind();
3570 // If all builders agree that the host object should be ignored, just return
3572 if (IgnoringBuilders &&
3573 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
3576 if (DDeps.getActions().empty())
3579 // We have dependences we need to bundle together. We use an offload action
3581 OffloadAction::HostDependence HDep(
3582 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3583 /*BoundArch=*/nullptr, DDeps);
3584 return C.MakeAction<OffloadAction>(HDep, DDeps);
3587 /// Generate an action that adds a host dependence to a device action. The
3588 /// results will be kept in this action builder. Return true if an error was
3590 bool addHostDependenceToDeviceActions(Action *&HostAction,
3591 const Arg *InputArg) {
3595 recordHostAction(HostAction, InputArg);
3597 // If we are supporting bundling/unbundling and the current action is an
3598 // input action of non-source file, we replace the host action by the
3599 // unbundling action. The bundler tool has the logic to detect if an input
3600 // is a bundle or not and if the input is not a bundle it assumes it is a
3601 // host file. Therefore it is safe to create an unbundling action even if
3602 // the input is not a bundle.
3603 if (CanUseBundler && isa<InputAction>(HostAction) &&
3604 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
3605 (!types::isSrcFile(HostAction->getType()) ||
3606 HostAction->getType() == types::TY_PP_HIP)) {
3607 auto UnbundlingHostAction =
3608 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
3609 UnbundlingHostAction->registerDependentActionInfo(
3610 C.getSingleOffloadToolChain<Action::OFK_Host>(),
3611 /*BoundArch=*/StringRef(), Action::OFK_Host);
3612 HostAction = UnbundlingHostAction;
3613 recordHostAction(HostAction, InputArg);
3616 assert(HostAction && "Invalid host action!");
3618 // Register the offload kinds that are used.
3619 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3620 for (auto *SB : SpecializedBuilders) {
3624 auto RetCode = SB->addDeviceDependences(HostAction);
3626 // Host dependences for device actions are not compatible with that same
3627 // action being ignored.
3628 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
3629 "Host dependence not expected to be ignored.!");
3631 // Unless the builder was inactive for this action, we have to record the
3632 // offload kind because the host will have to use it.
3633 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3634 OffloadKind |= SB->getAssociatedOffloadKind();
3637 // Do not use unbundler if the Host does not depend on device action.
3638 if (OffloadKind == Action::OFK_None && CanUseBundler)
3639 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3640 HostAction = UA->getInputs().back();
3645 /// Add the offloading top level actions to the provided action list. This
3646 /// function can replace the host action by a bundling action if the
3647 /// programming models allow it.
3648 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3649 const Arg *InputArg) {
3651 recordHostAction(HostAction, InputArg);
3653 // Get the device actions to be appended.
3654 ActionList OffloadAL;
3655 for (auto *SB : SpecializedBuilders) {
3658 SB->appendTopLevelActions(OffloadAL);
3661 // If we can use the bundler, replace the host action by the bundling one in
3662 // the resulting list. Otherwise, just append the device actions. For
3663 // device only compilation, HostAction is a null pointer, therefore only do
3664 // this when HostAction is not a null pointer.
3665 if (CanUseBundler && HostAction &&
3666 HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) {
3667 // Add the host action to the list in order to create the bundling action.
3668 OffloadAL.push_back(HostAction);
3670 // We expect that the host action was just appended to the action list
3671 // before this method was called.
3672 assert(HostAction == AL.back() && "Host action not in the list??");
3673 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3674 recordHostAction(HostAction, InputArg);
3675 AL.back() = HostAction;
3677 AL.append(OffloadAL.begin(), OffloadAL.end());
3679 // Propagate to the current host action (if any) the offload information
3680 // associated with the current input.
3682 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3683 /*BoundArch=*/nullptr);
3687 void appendDeviceLinkActions(ActionList &AL) {
3688 for (DeviceActionBuilder *SB : SpecializedBuilders) {
3691 SB->appendLinkDeviceActions(AL);
3695 Action *makeHostLinkAction() {
3696 // Build a list of device linking actions.
3697 ActionList DeviceAL;
3698 appendDeviceLinkActions(DeviceAL);
3699 if (DeviceAL.empty())
3702 // Let builders add host linking actions.
3703 Action* HA = nullptr;
3704 for (DeviceActionBuilder *SB : SpecializedBuilders) {
3707 HA = SB->appendLinkHostActions(DeviceAL);
3708 // This created host action has no originating input argument, therefore
3709 // needs to set its offloading kind directly.
3711 HA->propagateHostOffloadInfo(SB->getAssociatedOffloadKind(),
3712 /*BoundArch=*/nullptr);
3717 /// Processes the host linker action. This currently consists of replacing it
3718 /// with an offload action if there are device link objects and propagate to
3719 /// the host action all the offload kinds used in the current compilation. The
3720 /// resulting action is returned.
3721 Action *processHostLinkAction(Action *HostAction) {
3722 // Add all the dependences from the device linking actions.
3723 OffloadAction::DeviceDependences DDeps;
3724 for (auto *SB : SpecializedBuilders) {
3728 SB->appendLinkDependences(DDeps);
3731 // Calculate all the offload kinds used in the current compilation.
3732 unsigned ActiveOffloadKinds = 0u;
3733 for (auto &I : InputArgToOffloadKindMap)
3734 ActiveOffloadKinds |= I.second;
3736 // If we don't have device dependencies, we don't have to create an offload
3738 if (DDeps.getActions().empty()) {
3739 // Set all the active offloading kinds to the link action. Given that it
3740 // is a link action it is assumed to depend on all actions generated so
3742 HostAction->setHostOffloadInfo(ActiveOffloadKinds,
3743 /*BoundArch=*/nullptr);
3744 // Propagate active offloading kinds for each input to the link action.
3745 // Each input may have different active offloading kind.
3746 for (auto *A : HostAction->inputs()) {
3747 auto ArgLoc = HostActionToInputArgMap.find(A);
3748 if (ArgLoc == HostActionToInputArgMap.end())
3750 auto OFKLoc = InputArgToOffloadKindMap.find(ArgLoc->second);
3751 if (OFKLoc == InputArgToOffloadKindMap.end())
3753 A->propagateHostOffloadInfo(OFKLoc->second, /*BoundArch=*/nullptr);
3758 // Create the offload action with all dependences. When an offload action
3759 // is created the kinds are propagated to the host action, so we don't have
3760 // to do that explicitly here.
3761 OffloadAction::HostDependence HDep(
3762 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3763 /*BoundArch*/ nullptr, ActiveOffloadKinds);
3764 return C.MakeAction<OffloadAction>(HDep, DDeps);
3767 } // anonymous namespace.
3769 void Driver::handleArguments(Compilation &C, DerivedArgList &Args,
3770 const InputList &Inputs,
3771 ActionList &Actions) const {
3773 // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
3774 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3775 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
3776 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3777 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3778 Args.eraseArg(options::OPT__SLASH_Yc);
3779 Args.eraseArg(options::OPT__SLASH_Yu);
3780 YcArg = YuArg = nullptr;
3782 if (YcArg && Inputs.size() > 1) {
3783 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3784 Args.eraseArg(options::OPT__SLASH_Yc);
3789 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
3791 if (FinalPhase == phases::Link) {
3792 // Emitting LLVM while linking disabled except in HIPAMD Toolchain
3793 if (Args.hasArg(options::OPT_emit_llvm) && !Args.hasArg(options::OPT_hip_link))
3794 Diag(clang::diag::err_drv_emit_llvm_link);
3795 if (IsCLMode() && LTOMode != LTOK_None &&
3796 !Args.getLastArgValue(options::OPT_fuse_ld_EQ)
3797 .equals_insensitive("lld"))
3798 Diag(clang::diag::err_drv_lto_without_lld);
3801 if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3802 // If only preprocessing or /Y- is used, all pch handling is disabled.
3803 // Rather than check for it everywhere, just remove clang-cl pch-related
3805 Args.eraseArg(options::OPT__SLASH_Fp);
3806 Args.eraseArg(options::OPT__SLASH_Yc);
3807 Args.eraseArg(options::OPT__SLASH_Yu);
3808 YcArg = YuArg = nullptr;
3811 unsigned LastPLSize = 0;
3812 for (auto &I : Inputs) {
3813 types::ID InputType = I.first;
3814 const Arg *InputArg = I.second;
3816 auto PL = types::getCompilationPhases(InputType);
3817 LastPLSize = PL.size();
3819 // If the first step comes after the final phase we are doing as part of
3820 // this compilation, warn the user about it.
3821 phases::ID InitialPhase = PL[0];
3822 if (InitialPhase > FinalPhase) {
3823 if (InputArg->isClaimed())
3826 // Claim here to avoid the more general unused warning.
3829 // Suppress all unused style warnings with -Qunused-arguments
3830 if (Args.hasArg(options::OPT_Qunused_arguments))
3833 // Special case when final phase determined by binary name, rather than
3834 // by a command-line argument with a corresponding Arg.
3836 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
3837 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
3838 // Special case '-E' warning on a previously preprocessed file to make
3840 else if (InitialPhase == phases::Compile &&
3841 (Args.getLastArg(options::OPT__SLASH_EP,
3842 options::OPT__SLASH_P) ||
3843 Args.getLastArg(options::OPT_E) ||
3844 Args.getLastArg(options::OPT_M, options::OPT_MM)) &&
3845 getPreprocessedType(InputType) == types::TY_INVALID)
3846 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
3847 << InputArg->getAsString(Args) << !!FinalPhaseArg
3848 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3850 Diag(clang::diag::warn_drv_input_file_unused)
3851 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3853 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3858 // Add a separate precompile phase for the compile phase.
3859 if (FinalPhase >= phases::Compile) {
3860 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
3861 // Build the pipeline for the pch file.
3862 Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType);
3863 for (phases::ID Phase : types::getCompilationPhases(HeaderType))
3864 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3866 Actions.push_back(ClangClPch);
3867 // The driver currently exits after the first failed command. This
3868 // relies on that behavior, to make sure if the pch generation fails,
3869 // the main compilation won't run.
3870 // FIXME: If the main compilation fails, the PCH generation should
3871 // probably not be considered successful either.
3876 // If we are linking, claim any options which are obviously only used for
3878 // FIXME: Understand why the last Phase List length is used here.
3879 if (FinalPhase == phases::Link && LastPLSize == 1) {
3880 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
3881 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3885 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
3886 const InputList &Inputs, ActionList &Actions) const {
3887 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
3889 if (!SuppressMissingInputWarning && Inputs.empty()) {
3890 Diag(clang::diag::err_drv_no_input_files);
3894 // Diagnose misuse of /Fo.
3895 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
3896 StringRef V = A->getValue();
3897 if (Inputs.size() > 1 && !V.empty() &&
3898 !llvm::sys::path::is_separator(V.back())) {
3899 // Check whether /Fo tries to name an output file for multiple inputs.
3900 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3901 << A->getSpelling() << V;
3902 Args.eraseArg(options::OPT__SLASH_Fo);
3906 // Diagnose misuse of /Fa.
3907 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
3908 StringRef V = A->getValue();
3909 if (Inputs.size() > 1 && !V.empty() &&
3910 !llvm::sys::path::is_separator(V.back())) {
3911 // Check whether /Fa tries to name an asm file for multiple inputs.
3912 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3913 << A->getSpelling() << V;
3914 Args.eraseArg(options::OPT__SLASH_Fa);
3918 // Diagnose misuse of /o.
3919 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
3920 if (A->getValue()[0] == '\0') {
3921 // It has to have a value.
3922 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
3923 Args.eraseArg(options::OPT__SLASH_o);
3927 handleArguments(C, Args, Inputs, Actions);
3929 bool UseNewOffloadingDriver =
3930 C.isOffloadingHostKind(Action::OFK_OpenMP) ||
3931 Args.hasFlag(options::OPT_offload_new_driver,
3932 options::OPT_no_offload_new_driver, false);
3934 // Builder to be used to build offloading actions.
3935 std::unique_ptr<OffloadingActionBuilder> OffloadBuilder =
3936 !UseNewOffloadingDriver
3937 ? std::make_unique<OffloadingActionBuilder>(C, Args, Inputs)
3940 // Construct the actions to perform.
3941 HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
3942 ExtractAPIJobAction *ExtractAPIAction = nullptr;
3943 ActionList LinkerInputs;
3944 ActionList MergerInputs;
3946 for (auto &I : Inputs) {
3947 types::ID InputType = I.first;
3948 const Arg *InputArg = I.second;
3950 auto PL = types::getCompilationPhases(*this, Args, InputType);
3954 auto FullPL = types::getCompilationPhases(InputType);
3956 // Build the pipeline for this file.
3957 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3959 // Use the current host action in any of the offloading actions, if
3961 if (!UseNewOffloadingDriver)
3962 if (OffloadBuilder->addHostDependenceToDeviceActions(Current, InputArg))
3965 for (phases::ID Phase : PL) {
3967 // Add any offload action the host action depends on.
3968 if (!UseNewOffloadingDriver)
3969 Current = OffloadBuilder->addDeviceDependencesToHostAction(
3970 Current, InputArg, Phase, PL.back(), FullPL);
3974 // Queue linker inputs.
3975 if (Phase == phases::Link) {
3976 assert(Phase == PL.back() && "linking must be final compilation step.");
3977 // We don't need to generate additional link commands if emitting AMD bitcode
3978 if (!(C.getInputArgs().hasArg(options::OPT_hip_link) &&
3979 (C.getInputArgs().hasArg(options::OPT_emit_llvm))))
3980 LinkerInputs.push_back(Current);
3985 // TODO: Consider removing this because the merged may not end up being
3986 // the final Phase in the pipeline. Perhaps the merged could just merge
3987 // and then pass an artifact of some sort to the Link Phase.
3988 // Queue merger inputs.
3989 if (Phase == phases::IfsMerge) {
3990 assert(Phase == PL.back() && "merging must be final compilation step.");
3991 MergerInputs.push_back(Current);
3996 // Each precompiled header file after a module file action is a module
3997 // header of that same module file, rather than being compiled to a
3999 if (Phase == phases::Precompile && HeaderModuleAction &&
4000 getPrecompiledType(InputType) == types::TY_PCH) {
4001 HeaderModuleAction->addModuleHeaderInput(Current);
4006 if (Phase == phases::Precompile && ExtractAPIAction) {
4007 ExtractAPIAction->addHeaderInput(Current);
4012 // FIXME: Should we include any prior module file outputs as inputs of
4013 // later actions in the same command line?
4015 // Otherwise construct the appropriate action.
4016 Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
4018 // We didn't create a new action, so we will just move to the next phase.
4019 if (NewCurrent == Current)
4022 if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
4023 HeaderModuleAction = HMA;
4024 else if (auto *EAA = dyn_cast<ExtractAPIJobAction>(NewCurrent))
4025 ExtractAPIAction = EAA;
4027 Current = NewCurrent;
4029 // Use the current host action in any of the offloading actions, if
4031 if (!UseNewOffloadingDriver)
4032 if (OffloadBuilder->addHostDependenceToDeviceActions(Current, InputArg))
4035 // Try to build the offloading actions and add the result as a dependency
4037 if (UseNewOffloadingDriver)
4038 Current = BuildOffloadingActions(C, Args, I, Current);
4040 if (Current->getType() == types::TY_Nothing)
4044 // If we ended with something, add to the output list.
4046 Actions.push_back(Current);
4048 // Add any top level actions generated for offloading.
4049 if (!UseNewOffloadingDriver)
4050 OffloadBuilder->appendTopLevelActions(Actions, Current, InputArg);
4052 Current->propagateHostOffloadInfo(C.getActiveOffloadKinds(),
4053 /*BoundArch=*/nullptr);
4056 // Add a link action if necessary.
4058 if (LinkerInputs.empty()) {
4060 if (getFinalPhase(Args, &FinalPhaseArg) == phases::Link)
4061 if (!UseNewOffloadingDriver)
4062 OffloadBuilder->appendDeviceLinkActions(Actions);
4065 if (!LinkerInputs.empty()) {
4066 if (!UseNewOffloadingDriver)
4067 if (Action *Wrapper = OffloadBuilder->makeHostLinkAction())
4068 LinkerInputs.push_back(Wrapper);
4070 // Check if this Linker Job should emit a static library.
4071 if (ShouldEmitStaticLibrary(Args)) {
4072 LA = C.MakeAction<StaticLibJobAction>(LinkerInputs, types::TY_Image);
4073 } else if (UseNewOffloadingDriver ||
4074 Args.hasArg(options::OPT_offload_link)) {
4075 LA = C.MakeAction<LinkerWrapperJobAction>(LinkerInputs, types::TY_Image);
4076 LA->propagateHostOffloadInfo(C.getActiveOffloadKinds(),
4077 /*BoundArch=*/nullptr);
4079 LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
4081 if (!UseNewOffloadingDriver)
4082 LA = OffloadBuilder->processHostLinkAction(LA);
4083 Actions.push_back(LA);
4086 // Add an interface stubs merge action if necessary.
4087 if (!MergerInputs.empty())
4089 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
4091 if (Args.hasArg(options::OPT_emit_interface_stubs)) {
4092 auto PhaseList = types::getCompilationPhases(
4094 Args.hasArg(options::OPT_c) ? phases::Compile : phases::IfsMerge);
4096 ActionList MergerInputs;
4098 for (auto &I : Inputs) {
4099 types::ID InputType = I.first;
4100 const Arg *InputArg = I.second;
4102 // Currently clang and the llvm assembler do not support generating symbol
4103 // stubs from assembly, so we skip the input on asm files. For ifs files
4104 // we rely on the normal pipeline setup in the pipeline setup code above.
4105 if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm ||
4106 InputType == types::TY_Asm)
4109 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
4111 for (auto Phase : PhaseList) {
4115 "IFS Pipeline can only consist of Compile followed by IfsMerge.");
4116 case phases::Compile: {
4117 // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs
4118 // files where the .o file is located. The compile action can not
4120 if (InputType == types::TY_Object)
4123 Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP);
4126 case phases::IfsMerge: {
4127 assert(Phase == PhaseList.back() &&
4128 "merging must be final compilation step.");
4129 MergerInputs.push_back(Current);
4136 // If we ended with something, add to the output list.
4138 Actions.push_back(Current);
4141 // Add an interface stubs merge action if necessary.
4142 if (!MergerInputs.empty())
4144 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
4147 // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a custom
4148 // Compile phase that prints out supported cpu models and quits.
4149 if (Arg *A = Args.getLastArg(options::OPT_print_supported_cpus)) {
4150 // Use the -mcpu=? flag as the dummy input to cc1.
4152 Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C);
4154 C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing));
4155 for (auto &I : Inputs)
4159 // Claim ignored clang-cl options.
4160 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
4163 /// Returns the canonical name for the offloading architecture when using a HIP
4164 /// or CUDA architecture.
4165 static StringRef getCanonicalArchString(Compilation &C,
4166 const llvm::opt::DerivedArgList &Args,
4168 const llvm::Triple &Triple) {
4169 // Lookup the CUDA / HIP architecture string. Only report an error if we were
4170 // expecting the triple to be only NVPTX / AMDGPU.
4171 CudaArch Arch = StringToCudaArch(getProcessorFromTargetID(Triple, ArchStr));
4172 if (Triple.isNVPTX() &&
4173 (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch))) {
4174 C.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch)
4175 << "CUDA" << ArchStr;
4177 } else if (Triple.isAMDGPU() &&
4178 (Arch == CudaArch::UNKNOWN || !IsAMDGpuArch(Arch))) {
4179 C.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch)
4180 << "HIP" << ArchStr;
4184 if (IsNVIDIAGpuArch(Arch))
4185 return Args.MakeArgStringRef(CudaArchToString(Arch));
4187 if (IsAMDGpuArch(Arch)) {
4188 llvm::StringMap<bool> Features;
4189 auto HIPTriple = getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs());
4192 auto Arch = parseTargetID(*HIPTriple, ArchStr, &Features);
4194 C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << ArchStr;
4195 C.setContainsError();
4198 return Args.MakeArgStringRef(getCanonicalTargetID(*Arch, Features));
4201 // If the input isn't CUDA or HIP just return the architecture.
4205 /// Checks if the set offloading architectures does not conflict. Returns the
4206 /// incompatible pair if a conflict occurs.
4207 static llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>>
4208 getConflictOffloadArchCombination(const llvm::DenseSet<StringRef> &Archs,
4209 Action::OffloadKind Kind) {
4210 if (Kind != Action::OFK_HIP)
4213 std::set<StringRef> ArchSet;
4214 llvm::copy(Archs, std::inserter(ArchSet, ArchSet.begin()));
4215 return getConflictTargetIDCombination(ArchSet);
4218 llvm::DenseSet<StringRef>
4219 Driver::getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args,
4220 Action::OffloadKind Kind, const ToolChain *TC) const {
4222 TC = &C.getDefaultToolChain();
4224 // --offload and --offload-arch options are mutually exclusive.
4225 if (Args.hasArgNoClaim(options::OPT_offload_EQ) &&
4226 Args.hasArgNoClaim(options::OPT_offload_arch_EQ,
4227 options::OPT_no_offload_arch_EQ)) {
4228 C.getDriver().Diag(diag::err_opt_not_valid_with_opt)
4230 << (Args.hasArgNoClaim(options::OPT_offload_arch_EQ)
4232 : "--no-offload-arch");
4235 if (KnownArchs.find(TC) != KnownArchs.end())
4236 return KnownArchs.lookup(TC);
4238 llvm::DenseSet<StringRef> Archs;
4239 for (auto *Arg : Args) {
4240 // Extract any '--[no-]offload-arch' arguments intended for this toolchain.
4241 std::unique_ptr<llvm::opt::Arg> ExtractedArg = nullptr;
4242 if (Arg->getOption().matches(options::OPT_Xopenmp_target_EQ) &&
4243 ToolChain::getOpenMPTriple(Arg->getValue(0)) == TC->getTriple()) {
4245 unsigned Index = Args.getBaseArgs().MakeIndex(Arg->getValue(1));
4246 ExtractedArg = getOpts().ParseOneArg(Args, Index);
4247 Arg = ExtractedArg.get();
4250 // Add or remove the seen architectures in order of appearance. If an
4251 // invalid architecture is given we simply exit.
4252 if (Arg->getOption().matches(options::OPT_offload_arch_EQ)) {
4253 for (StringRef Arch : llvm::split(Arg->getValue(), ",")) {
4255 getCanonicalArchString(C, Args, Arch, TC->getTriple());
4256 if (ArchStr.empty())
4258 Archs.insert(ArchStr);
4260 } else if (Arg->getOption().matches(options::OPT_no_offload_arch_EQ)) {
4261 for (StringRef Arch : llvm::split(Arg->getValue(), ",")) {
4262 if (Arch == "all") {
4266 getCanonicalArchString(C, Args, Arch, TC->getTriple());
4267 if (ArchStr.empty())
4269 Archs.erase(ArchStr);
4275 if (auto ConflictingArchs = getConflictOffloadArchCombination(Archs, Kind)) {
4276 C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo)
4277 << ConflictingArchs->first << ConflictingArchs->second;
4278 C.setContainsError();
4281 if (Archs.empty()) {
4282 if (Kind == Action::OFK_Cuda)
4283 Archs.insert(CudaArchToString(CudaArch::CudaDefault));
4284 else if (Kind == Action::OFK_HIP)
4285 Archs.insert(CudaArchToString(CudaArch::HIPDefault));
4286 else if (Kind == Action::OFK_OpenMP)
4287 Archs.insert(StringRef());
4289 Args.ClaimAllArgs(options::OPT_offload_arch_EQ);
4290 Args.ClaimAllArgs(options::OPT_no_offload_arch_EQ);
4296 Action *Driver::BuildOffloadingActions(Compilation &C,
4297 llvm::opt::DerivedArgList &Args,
4298 const InputTy &Input,
4299 Action *HostAction) const {
4300 // Don't build offloading actions if explicitly disabled or we do not have a
4301 // valid source input and compile action to embed it in. If preprocessing only
4302 // ignore embedding.
4303 if (offloadHostOnly() || !types::isSrcFile(Input.first) ||
4304 !(isa<CompileJobAction>(HostAction) ||
4305 getFinalPhase(Args) == phases::Preprocess))
4308 ActionList OffloadActions;
4309 OffloadAction::DeviceDependences DDeps;
4311 const Action::OffloadKind OffloadKinds[] = {
4312 Action::OFK_OpenMP, Action::OFK_Cuda, Action::OFK_HIP};
4314 for (Action::OffloadKind Kind : OffloadKinds) {
4315 SmallVector<const ToolChain *, 2> ToolChains;
4316 ActionList DeviceActions;
4318 auto TCRange = C.getOffloadToolChains(Kind);
4319 for (auto TI = TCRange.first, TE = TCRange.second; TI != TE; ++TI)
4320 ToolChains.push_back(TI->second);
4322 if (ToolChains.empty())
4325 types::ID InputType = Input.first;
4326 const Arg *InputArg = Input.second;
4328 // The toolchain can be active for unsupported file types.
4329 if ((Kind == Action::OFK_Cuda && !types::isCuda(InputType)) ||
4330 (Kind == Action::OFK_HIP && !types::isHIP(InputType)))
4333 // Get the product of all bound architectures and toolchains.
4334 SmallVector<std::pair<const ToolChain *, StringRef>> TCAndArchs;
4335 for (const ToolChain *TC : ToolChains)
4336 for (StringRef Arch : getOffloadArchs(C, Args, Kind, TC))
4337 TCAndArchs.push_back(std::make_pair(TC, Arch));
4339 for (unsigned I = 0, E = TCAndArchs.size(); I != E; ++I)
4340 DeviceActions.push_back(C.MakeAction<InputAction>(*InputArg, InputType));
4342 if (DeviceActions.empty())
4345 auto PL = types::getCompilationPhases(*this, Args, InputType);
4347 for (phases::ID Phase : PL) {
4348 if (Phase == phases::Link) {
4349 assert(Phase == PL.back() && "linking must be final compilation step.");
4353 auto TCAndArch = TCAndArchs.begin();
4354 for (Action *&A : DeviceActions) {
4355 if (A->getType() == types::TY_Nothing)
4358 A = ConstructPhaseAction(C, Args, Phase, A, Kind);
4360 if (isa<CompileJobAction>(A) && isa<CompileJobAction>(HostAction) &&
4361 Kind == Action::OFK_OpenMP &&
4362 HostAction->getType() != types::TY_Nothing) {
4363 // OpenMP offloading has a dependency on the host compile action to
4364 // identify which declarations need to be emitted. This shouldn't be
4365 // collapsed with any other actions so we can use it in the device.
4366 HostAction->setCannotBeCollapsedWithNextDependentAction();
4367 OffloadAction::HostDependence HDep(
4368 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4369 TCAndArch->second.data(), Kind);
4370 OffloadAction::DeviceDependences DDep;
4371 DDep.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4372 A = C.MakeAction<OffloadAction>(HDep, DDep);
4378 // Compiling HIP in non-RDC mode requires linking each action individually.
4379 for (Action *&A : DeviceActions) {
4380 if ((A->getType() != types::TY_Object &&
4381 A->getType() != types::TY_LTO_BC) ||
4382 Kind != Action::OFK_HIP ||
4383 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
4385 ActionList LinkerInput = {A};
4386 A = C.MakeAction<LinkJobAction>(LinkerInput, types::TY_Image);
4389 auto TCAndArch = TCAndArchs.begin();
4390 for (Action *A : DeviceActions) {
4391 DDeps.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4392 OffloadAction::DeviceDependences DDep;
4393 DDep.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind);
4394 OffloadActions.push_back(C.MakeAction<OffloadAction>(DDep, A->getType()));
4399 if (offloadDeviceOnly())
4400 return C.MakeAction<OffloadAction>(DDeps, types::TY_Nothing);
4402 if (OffloadActions.empty())
4405 OffloadAction::DeviceDependences DDep;
4406 if (C.isOffloadingHostKind(Action::OFK_Cuda) &&
4407 !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) {
4408 // If we are not in RDC-mode we just emit the final CUDA fatbinary for
4409 // each translation unit without requiring any linking.
4410 Action *FatbinAction =
4411 C.MakeAction<LinkJobAction>(OffloadActions, types::TY_CUDA_FATBIN);
4412 DDep.add(*FatbinAction, *C.getSingleOffloadToolChain<Action::OFK_Cuda>(),
4413 nullptr, Action::OFK_Cuda);
4414 } else if (C.isOffloadingHostKind(Action::OFK_HIP) &&
4415 !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4417 // If we are not in RDC-mode we just emit the final HIP fatbinary for each
4418 // translation unit, linking each input individually.
4419 Action *FatbinAction =
4420 C.MakeAction<LinkJobAction>(OffloadActions, types::TY_HIP_FATBIN);
4421 DDep.add(*FatbinAction, *C.getSingleOffloadToolChain<Action::OFK_HIP>(),
4422 nullptr, Action::OFK_HIP);
4424 // Package all the offloading actions into a single output that can be
4425 // embedded in the host and linked.
4426 Action *PackagerAction =
4427 C.MakeAction<OffloadPackagerJobAction>(OffloadActions, types::TY_Image);
4428 DDep.add(*PackagerAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4429 nullptr, C.getActiveOffloadKinds());
4432 // If we are unable to embed a single device output into the host, we need to
4433 // add each device output as a host dependency to ensure they are still built.
4434 bool SingleDeviceOutput = !llvm::any_of(OffloadActions, [](Action *A) {
4435 return A->getType() == types::TY_Nothing;
4436 }) && isa<CompileJobAction>(HostAction);
4437 OffloadAction::HostDependence HDep(
4438 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4439 /*BoundArch=*/nullptr, SingleDeviceOutput ? DDep : DDeps);
4440 return C.MakeAction<OffloadAction>(HDep, SingleDeviceOutput ? DDep : DDeps);
4443 Action *Driver::ConstructPhaseAction(
4444 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
4445 Action::OffloadKind TargetDeviceOffloadKind) const {
4446 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
4448 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
4449 // encode this in the steps because the intermediate type depends on
4450 // arguments. Just special case here.
4451 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
4454 // Build the appropriate action.
4457 llvm_unreachable("link action invalid here.");
4458 case phases::IfsMerge:
4459 llvm_unreachable("ifsmerge action invalid here.");
4460 case phases::Preprocess: {
4462 // -M and -MM specify the dependency file name by altering the output type,
4463 // -if -MD and -MMD are not specified.
4464 if (Args.hasArg(options::OPT_M, options::OPT_MM) &&
4465 !Args.hasArg(options::OPT_MD, options::OPT_MMD)) {
4466 OutputTy = types::TY_Dependencies;
4468 OutputTy = Input->getType();
4469 // For these cases, the preprocessor is only translating forms, the Output
4470 // still needs preprocessing.
4471 if (!Args.hasFlag(options::OPT_frewrite_includes,
4472 options::OPT_fno_rewrite_includes, false) &&
4473 !Args.hasFlag(options::OPT_frewrite_imports,
4474 options::OPT_fno_rewrite_imports, false) &&
4475 !Args.hasFlag(options::OPT_fdirectives_only,
4476 options::OPT_fno_directives_only, false) &&
4478 OutputTy = types::getPreprocessedType(OutputTy);
4479 assert(OutputTy != types::TY_INVALID &&
4480 "Cannot preprocess this input type!");
4482 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
4484 case phases::Precompile: {
4485 // API extraction should not generate an actual precompilation action.
4486 if (Args.hasArg(options::OPT_extract_api))
4487 return C.MakeAction<ExtractAPIJobAction>(Input, types::TY_API_INFO);
4489 types::ID OutputTy = getPrecompiledType(Input->getType());
4490 assert(OutputTy != types::TY_INVALID &&
4491 "Cannot precompile this input type!");
4493 // If we're given a module name, precompile header file inputs as a
4494 // module, not as a precompiled header.
4495 const char *ModName = nullptr;
4496 if (OutputTy == types::TY_PCH) {
4497 if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
4498 ModName = A->getValue();
4500 OutputTy = types::TY_ModuleFile;
4503 if (Args.hasArg(options::OPT_fsyntax_only)) {
4504 // Syntax checks should not emit a PCH file
4505 OutputTy = types::TY_Nothing;
4509 return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
4511 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
4513 case phases::Compile: {
4514 if (Args.hasArg(options::OPT_fsyntax_only))
4515 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
4516 if (Args.hasArg(options::OPT_rewrite_objc))
4517 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
4518 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
4519 return C.MakeAction<CompileJobAction>(Input,
4520 types::TY_RewrittenLegacyObjC);
4521 if (Args.hasArg(options::OPT__analyze))
4522 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
4523 if (Args.hasArg(options::OPT__migrate))
4524 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
4525 if (Args.hasArg(options::OPT_emit_ast))
4526 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
4527 if (Args.hasArg(options::OPT_module_file_info))
4528 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
4529 if (Args.hasArg(options::OPT_verify_pch))
4530 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
4531 if (Args.hasArg(options::OPT_extract_api))
4532 return C.MakeAction<ExtractAPIJobAction>(Input, types::TY_API_INFO);
4533 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
4535 case phases::Backend: {
4536 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
4538 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
4539 return C.MakeAction<BackendJobAction>(Input, Output);
4541 if (isUsingLTO(/* IsOffload */ true) &&
4542 TargetDeviceOffloadKind != Action::OFK_None) {
4544 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
4545 return C.MakeAction<BackendJobAction>(Input, Output);
4547 if (Args.hasArg(options::OPT_emit_llvm) ||
4548 (TargetDeviceOffloadKind == Action::OFK_HIP &&
4549 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4552 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
4553 return C.MakeAction<BackendJobAction>(Input, Output);
4555 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
4557 case phases::Assemble:
4558 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
4561 llvm_unreachable("invalid phase in ConstructPhaseAction");
4564 void Driver::BuildJobs(Compilation &C) const {
4565 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
4567 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4569 // It is an error to provide a -o option if we are making multiple output
4570 // files. There are exceptions:
4572 // IfsMergeJob: when generating interface stubs enabled we want to be able to
4573 // generate the stub file at the same time that we generate the real
4574 // library/a.out. So when a .o, .so, etc are the output, with clang interface
4575 // stubs there will also be a .ifs and .ifso at the same location.
4577 // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled
4578 // and -c is passed, we still want to be able to generate a .ifs file while
4579 // we are also generating .o files. So we allow more than one output file in
4580 // this case as well.
4582 // OffloadClass of type TY_Nothing: device-only output will place many outputs
4583 // into a single offloading action. We should count all inputs to the action
4584 // as outputs. Also ignore device-only outputs if we're compiling with
4587 unsigned NumOutputs = 0;
4588 unsigned NumIfsOutputs = 0;
4589 for (const Action *A : C.getActions()) {
4590 if (A->getType() != types::TY_Nothing &&
4591 !(A->getKind() == Action::IfsMergeJobClass ||
4592 (A->getType() == clang::driver::types::TY_IFS_CPP &&
4593 A->getKind() == clang::driver::Action::CompileJobClass &&
4594 0 == NumIfsOutputs++) ||
4595 (A->getKind() == Action::BindArchClass && A->getInputs().size() &&
4596 A->getInputs().front()->getKind() == Action::IfsMergeJobClass)))
4598 else if (A->getKind() == Action::OffloadClass &&
4599 A->getType() == types::TY_Nothing &&
4600 !C.getArgs().hasArg(options::OPT_fsyntax_only))
4601 NumOutputs += A->size();
4604 if (NumOutputs > 1) {
4605 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
4606 FinalOutput = nullptr;
4610 const llvm::Triple &RawTriple = C.getDefaultToolChain().getTriple();
4611 if (RawTriple.isOSAIX()) {
4612 if (Arg *A = C.getArgs().getLastArg(options::OPT_G))
4613 Diag(diag::err_drv_unsupported_opt_for_target)
4614 << A->getSpelling() << RawTriple.str();
4615 if (LTOMode == LTOK_Thin)
4616 Diag(diag::err_drv_clang_unsupported) << "thinLTO on AIX";
4619 // Collect the list of architectures.
4620 llvm::StringSet<> ArchNames;
4621 if (RawTriple.isOSBinFormatMachO())
4622 for (const Arg *A : C.getArgs())
4623 if (A->getOption().matches(options::OPT_arch))
4624 ArchNames.insert(A->getValue());
4626 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
4627 std::map<std::pair<const Action *, std::string>, InputInfoList> CachedResults;
4628 for (Action *A : C.getActions()) {
4629 // If we are linking an image for multiple archs then the linker wants
4630 // -arch_multiple and -final_output <final image name>. Unfortunately, this
4631 // doesn't fit in cleanly because we have to pass this information down.
4633 // FIXME: This is a hack; find a cleaner way to integrate this into the
4635 const char *LinkingOutput = nullptr;
4636 if (isa<LipoJobAction>(A)) {
4638 LinkingOutput = FinalOutput->getValue();
4640 LinkingOutput = getDefaultImageName();
4643 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
4644 /*BoundArch*/ StringRef(),
4645 /*AtTopLevel*/ true,
4646 /*MultipleArchs*/ ArchNames.size() > 1,
4647 /*LinkingOutput*/ LinkingOutput, CachedResults,
4648 /*TargetDeviceOffloadKind*/ Action::OFK_None);
4651 // If we have more than one job, then disable integrated-cc1 for now. Do this
4652 // also when we need to report process execution statistics.
4653 if (C.getJobs().size() > 1 || CCPrintProcessStats)
4654 for (auto &J : C.getJobs())
4655 J.InProcess = false;
4657 if (CCPrintProcessStats) {
4658 C.setPostCallback([=](const Command &Cmd, int Res) {
4659 Optional<llvm::sys::ProcessStatistics> ProcStat =
4660 Cmd.getProcessStatistics();
4664 const char *LinkingOutput = nullptr;
4666 LinkingOutput = FinalOutput->getValue();
4667 else if (!Cmd.getOutputFilenames().empty())
4668 LinkingOutput = Cmd.getOutputFilenames().front().c_str();
4670 LinkingOutput = getDefaultImageName();
4672 if (CCPrintStatReportFilename.empty()) {
4673 using namespace llvm;
4674 // Human readable output.
4675 outs() << sys::path::filename(Cmd.getExecutable()) << ": "
4676 << "output=" << LinkingOutput;
4677 outs() << ", total="
4678 << format("%.3f", ProcStat->TotalTime.count() / 1000.) << " ms"
4680 << format("%.3f", ProcStat->UserTime.count() / 1000.) << " ms"
4681 << ", mem=" << ProcStat->PeakMemory << " Kb\n";
4685 llvm::raw_string_ostream Out(Buffer);
4686 llvm::sys::printArg(Out, llvm::sys::path::filename(Cmd.getExecutable()),
4689 llvm::sys::printArg(Out, LinkingOutput, true);
4690 Out << ',' << ProcStat->TotalTime.count() << ','
4691 << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory
4695 llvm::raw_fd_ostream OS(CCPrintStatReportFilename, EC,
4696 llvm::sys::fs::OF_Append |
4697 llvm::sys::fs::OF_Text);
4702 llvm::errs() << "ERROR: Cannot lock file "
4703 << CCPrintStatReportFilename << ": "
4704 << toString(L.takeError()) << "\n";
4713 // If the user passed -Qunused-arguments or there were errors, don't warn
4714 // about any unused arguments.
4715 if (Diags.hasErrorOccurred() ||
4716 C.getArgs().hasArg(options::OPT_Qunused_arguments))
4719 // Claim -fdriver-only here.
4720 (void)C.getArgs().hasArg(options::OPT_fdriver_only);
4722 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
4724 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
4725 (void)C.getArgs().hasArg(options::OPT_driver_mode);
4726 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
4728 for (Arg *A : C.getArgs()) {
4729 // FIXME: It would be nice to be able to send the argument to the
4730 // DiagnosticsEngine, so that extra values, position, and so on could be
4732 if (!A->isClaimed()) {
4733 if (A->getOption().hasFlag(options::NoArgumentUnused))
4736 // Suppress the warning automatically if this is just a flag, and it is an
4737 // instance of an argument we already claimed.
4738 const Option &Opt = A->getOption();
4739 if (Opt.getKind() == Option::FlagClass) {
4740 bool DuplicateClaimed = false;
4742 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
4743 if (AA->isClaimed()) {
4744 DuplicateClaimed = true;
4749 if (DuplicateClaimed)
4753 // In clang-cl, don't mention unknown arguments here since they have
4754 // already been warned about.
4755 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
4756 Diag(clang::diag::warn_drv_unused_argument)
4757 << A->getAsString(C.getArgs());
4763 /// Utility class to control the collapse of dependent actions and select the
4764 /// tools accordingly.
4765 class ToolSelector final {
4766 /// The tool chain this selector refers to.
4767 const ToolChain &TC;
4769 /// The compilation this selector refers to.
4770 const Compilation &C;
4772 /// The base action this selector refers to.
4773 const JobAction *BaseAction;
4775 /// Set to true if the current toolchain refers to host actions.
4776 bool IsHostSelector;
4778 /// Set to true if save-temps and embed-bitcode functionalities are active.
4782 /// Get previous dependent action or null if that does not exist. If
4783 /// \a CanBeCollapsed is false, that action must be legal to collapse or
4784 /// null will be returned.
4785 const JobAction *getPrevDependentAction(const ActionList &Inputs,
4786 ActionList &SavedOffloadAction,
4787 bool CanBeCollapsed = true) {
4788 // An option can be collapsed only if it has a single input.
4789 if (Inputs.size() != 1)
4792 Action *CurAction = *Inputs.begin();
4793 if (CanBeCollapsed &&
4794 !CurAction->isCollapsingWithNextDependentActionLegal())
4797 // If the input action is an offload action. Look through it and save any
4798 // offload action that can be dropped in the event of a collapse.
4799 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
4800 // If the dependent action is a device action, we will attempt to collapse
4801 // only with other device actions. Otherwise, we would do the same but
4802 // with host actions only.
4803 if (!IsHostSelector) {
4804 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
4806 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
4807 if (CanBeCollapsed &&
4808 !CurAction->isCollapsingWithNextDependentActionLegal())
4810 SavedOffloadAction.push_back(OA);
4811 return dyn_cast<JobAction>(CurAction);
4813 } else if (OA->hasHostDependence()) {
4814 CurAction = OA->getHostDependence();
4815 if (CanBeCollapsed &&
4816 !CurAction->isCollapsingWithNextDependentActionLegal())
4818 SavedOffloadAction.push_back(OA);
4819 return dyn_cast<JobAction>(CurAction);
4824 return dyn_cast<JobAction>(CurAction);
4827 /// Return true if an assemble action can be collapsed.
4828 bool canCollapseAssembleAction() const {
4829 return TC.useIntegratedAs() && !SaveTemps &&
4830 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
4831 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
4832 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
4835 /// Return true if a preprocessor action can be collapsed.
4836 bool canCollapsePreprocessorAction() const {
4837 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
4838 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
4839 !C.getArgs().hasArg(options::OPT_rewrite_objc);
4842 /// Struct that relates an action with the offload actions that would be
4843 /// collapsed with it.
4844 struct JobActionInfo final {
4845 /// The action this info refers to.
4846 const JobAction *JA = nullptr;
4847 /// The offload actions we need to take care off if this action is
4849 ActionList SavedOffloadAction;
4852 /// Append collapsed offload actions from the give nnumber of elements in the
4853 /// action info array.
4854 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
4855 ArrayRef<JobActionInfo> &ActionInfo,
4856 unsigned ElementNum) {
4857 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
4858 for (unsigned I = 0; I < ElementNum; ++I)
4859 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
4860 ActionInfo[I].SavedOffloadAction.end());
4863 /// Functions that attempt to perform the combining. They detect if that is
4864 /// legal, and if so they update the inputs \a Inputs and the offload action
4865 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
4866 /// the combined action is returned. If the combining is not legal or if the
4867 /// tool does not exist, null is returned.
4868 /// Currently three kinds of collapsing are supported:
4869 /// - Assemble + Backend + Compile;
4870 /// - Assemble + Backend ;
4871 /// - Backend + Compile.
4873 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
4875 ActionList &CollapsedOffloadAction) {
4876 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
4878 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
4879 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
4880 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
4881 if (!AJ || !BJ || !CJ)
4884 // Get compiler tool.
4885 const Tool *T = TC.SelectTool(*CJ);
4889 // Can't collapse if we don't have codegen support unless we are
4890 // emitting LLVM IR.
4891 bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType());
4892 if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR()))
4895 // When using -fembed-bitcode, it is required to have the same tool (clang)
4896 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
4898 const Tool *BT = TC.SelectTool(*BJ);
4903 if (!T->hasIntegratedAssembler())
4906 Inputs = CJ->getInputs();
4907 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4911 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
4913 ActionList &CollapsedOffloadAction) {
4914 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
4916 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
4917 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
4921 // Get backend tool.
4922 const Tool *T = TC.SelectTool(*BJ);
4926 if (!T->hasIntegratedAssembler())
4929 Inputs = BJ->getInputs();
4930 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4934 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
4936 ActionList &CollapsedOffloadAction) {
4937 if (ActionInfo.size() < 2)
4939 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
4940 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
4944 // Check if the initial input (to the compile job or its predessor if one
4945 // exists) is LLVM bitcode. In that case, no preprocessor step is required
4946 // and we can still collapse the compile and backend jobs when we have
4947 // -save-temps. I.e. there is no need for a separate compile job just to
4948 // emit unoptimized bitcode.
4949 bool InputIsBitcode = true;
4950 for (size_t i = 1; i < ActionInfo.size(); i++)
4951 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
4952 ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
4953 InputIsBitcode = false;
4956 if (!InputIsBitcode && !canCollapsePreprocessorAction())
4959 // Get compiler tool.
4960 const Tool *T = TC.SelectTool(*CJ);
4964 // Can't collapse if we don't have codegen support unless we are
4965 // emitting LLVM IR.
4966 bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType());
4967 if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR()))
4970 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
4973 Inputs = CJ->getInputs();
4974 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4979 /// Updates the inputs if the obtained tool supports combining with
4980 /// preprocessor action, and the current input is indeed a preprocessor
4981 /// action. If combining results in the collapse of offloading actions, those
4982 /// are appended to \a CollapsedOffloadAction.
4983 void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
4984 ActionList &CollapsedOffloadAction) {
4985 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
4988 // Attempt to get a preprocessor action dependence.
4989 ActionList PreprocessJobOffloadActions;
4990 ActionList NewInputs;
4991 for (Action *A : Inputs) {
4992 auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
4993 if (!PJ || !isa<PreprocessJobAction>(PJ)) {
4994 NewInputs.push_back(A);
4998 // This is legal to combine. Append any offload action we found and add the
4999 // current input to preprocessor inputs.
5000 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
5001 PreprocessJobOffloadActions.end());
5002 NewInputs.append(PJ->input_begin(), PJ->input_end());
5008 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
5009 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
5010 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
5011 EmbedBitcode(EmbedBitcode) {
5012 assert(BaseAction && "Invalid base action.");
5013 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
5016 /// Check if a chain of actions can be combined and return the tool that can
5017 /// handle the combination of actions. The pointer to the current inputs \a
5018 /// Inputs and the list of offload actions \a CollapsedOffloadActions
5019 /// connected to collapsed actions are updated accordingly. The latter enables
5020 /// the caller of the selector to process them afterwards instead of just
5021 /// dropping them. If no suitable tool is found, null will be returned.
5022 const Tool *getTool(ActionList &Inputs,
5023 ActionList &CollapsedOffloadAction) {
5025 // Get the largest chain of actions that we could combine.
5028 SmallVector<JobActionInfo, 5> ActionChain(1);
5029 ActionChain.back().JA = BaseAction;
5030 while (ActionChain.back().JA) {
5031 const Action *CurAction = ActionChain.back().JA;
5033 // Grow the chain by one element.
5034 ActionChain.resize(ActionChain.size() + 1);
5035 JobActionInfo &AI = ActionChain.back();
5037 // Attempt to fill it with the
5039 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
5042 // Pop the last action info as it could not be filled.
5043 ActionChain.pop_back();
5046 // Attempt to combine actions. If all combining attempts failed, just return
5047 // the tool of the provided action. At the end we attempt to combine the
5048 // action with any preprocessor action it may depend on.
5051 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
5052 CollapsedOffloadAction);
5054 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
5056 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
5058 Inputs = BaseAction->getInputs();
5059 T = TC.SelectTool(*BaseAction);
5062 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
5068 /// Return a string that uniquely identifies the result of a job. The bound arch
5069 /// is not necessarily represented in the toolchain's triple -- for example,
5070 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
5071 /// Also, we need to add the offloading device kind, as the same tool chain can
5072 /// be used for host and device for some programming models, e.g. OpenMP.
5073 static std::string GetTriplePlusArchString(const ToolChain *TC,
5074 StringRef BoundArch,
5075 Action::OffloadKind OffloadKind) {
5076 std::string TriplePlusArch = TC->getTriple().normalize();
5077 if (!BoundArch.empty()) {
5078 TriplePlusArch += "-";
5079 TriplePlusArch += BoundArch;
5081 TriplePlusArch += "-";
5082 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
5083 return TriplePlusArch;
5086 InputInfoList Driver::BuildJobsForAction(
5087 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
5088 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
5089 std::map<std::pair<const Action *, std::string>, InputInfoList>
5091 Action::OffloadKind TargetDeviceOffloadKind) const {
5092 std::pair<const Action *, std::string> ActionTC = {
5093 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
5094 auto CachedResult = CachedResults.find(ActionTC);
5095 if (CachedResult != CachedResults.end()) {
5096 return CachedResult->second;
5098 InputInfoList Result = BuildJobsForActionNoCache(
5099 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
5100 CachedResults, TargetDeviceOffloadKind);
5101 CachedResults[ActionTC] = Result;
5105 InputInfoList Driver::BuildJobsForActionNoCache(
5106 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
5107 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
5108 std::map<std::pair<const Action *, std::string>, InputInfoList>
5110 Action::OffloadKind TargetDeviceOffloadKind) const {
5111 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
5113 InputInfoList OffloadDependencesInputInfo;
5114 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
5115 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
5116 // The 'Darwin' toolchain is initialized only when its arguments are
5117 // computed. Get the default arguments for OFK_None to ensure that
5118 // initialization is performed before processing the offload action.
5119 // FIXME: Remove when darwin's toolchain is initialized during construction.
5120 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
5122 // The offload action is expected to be used in four different situations.
5124 // a) Set a toolchain/architecture/kind for a host action:
5125 // Host Action 1 -> OffloadAction -> Host Action 2
5127 // b) Set a toolchain/architecture/kind for a device action;
5128 // Device Action 1 -> OffloadAction -> Device Action 2
5130 // c) Specify a device dependence to a host action;
5131 // Device Action 1 _
5133 // Host Action 1 ---> OffloadAction -> Host Action 2
5135 // d) Specify a host dependence to a device action.
5138 // Device Action 1 ---> OffloadAction -> Device Action 2
5140 // For a) and b), we just return the job generated for the dependences. For
5141 // c) and d) we override the current action with the host/device dependence
5142 // if the current toolchain is host/device and set the offload dependences
5143 // info with the jobs obtained from the device/host dependence(s).
5145 // If there is a single device option or has no host action, just generate
5147 if (OA->hasSingleDeviceDependence() || !OA->hasHostDependence()) {
5149 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
5150 const char *DepBoundArch) {
5151 DevA.append(BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
5152 /*MultipleArchs*/ !!DepBoundArch,
5153 LinkingOutput, CachedResults,
5154 DepA->getOffloadingDeviceKind()));
5159 // If 'Action 2' is host, we generate jobs for the device dependences and
5160 // override the current action with the host dependence. Otherwise, we
5161 // generate the host dependences and override the action with the device
5162 // dependence. The dependences can't therefore be a top-level action.
5163 OA->doOnEachDependence(
5164 /*IsHostDependence=*/BuildingForOffloadDevice,
5165 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
5166 OffloadDependencesInputInfo.append(BuildJobsForAction(
5167 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
5168 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
5169 DepA->getOffloadingDeviceKind()));
5172 A = BuildingForOffloadDevice
5173 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
5174 : OA->getHostDependence();
5176 // We may have already built this action as a part of the offloading
5177 // toolchain, return the cached input if so.
5178 std::pair<const Action *, std::string> ActionTC = {
5179 OA->getHostDependence(),
5180 GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
5181 if (CachedResults.find(ActionTC) != CachedResults.end()) {
5182 InputInfoList Inputs = CachedResults[ActionTC];
5183 Inputs.append(OffloadDependencesInputInfo);
5188 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
5189 // FIXME: It would be nice to not claim this here; maybe the old scheme of
5190 // just using Args was better?
5191 const Arg &Input = IA->getInputArg();
5193 if (Input.getOption().matches(options::OPT_INPUT)) {
5194 const char *Name = Input.getValue();
5195 return {InputInfo(A, Name, /* _BaseInput = */ Name)};
5197 return {InputInfo(A, &Input, /* _BaseInput = */ "")};
5200 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
5201 const ToolChain *TC;
5202 StringRef ArchName = BAA->getArchName();
5204 if (!ArchName.empty())
5205 TC = &getToolChain(C.getArgs(),
5206 computeTargetTriple(*this, TargetTriple,
5207 C.getArgs(), ArchName));
5209 TC = &C.getDefaultToolChain();
5211 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
5212 MultipleArchs, LinkingOutput, CachedResults,
5213 TargetDeviceOffloadKind);
5217 ActionList Inputs = A->getInputs();
5219 const JobAction *JA = cast<JobAction>(A);
5220 ActionList CollapsedOffloadActions;
5222 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
5223 embedBitcodeInObject() && !isUsingLTO());
5224 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
5227 return {InputInfo()};
5229 if (BuildingForOffloadDevice &&
5230 A->getOffloadingDeviceKind() == Action::OFK_OpenMP) {
5231 if (TC->getTriple().isAMDGCN()) {
5232 // AMDGCN treats backend and assemble actions as no-op because
5233 // linker does not support object files.
5234 if (const BackendJobAction *BA = dyn_cast<BackendJobAction>(A)) {
5235 return BuildJobsForAction(C, *BA->input_begin(), TC, BoundArch,
5236 AtTopLevel, MultipleArchs, LinkingOutput,
5237 CachedResults, TargetDeviceOffloadKind);
5240 if (const AssembleJobAction *AA = dyn_cast<AssembleJobAction>(A)) {
5241 return BuildJobsForAction(C, *AA->input_begin(), TC, BoundArch,
5242 AtTopLevel, MultipleArchs, LinkingOutput,
5243 CachedResults, TargetDeviceOffloadKind);
5248 // If we've collapsed action list that contained OffloadAction we
5249 // need to build jobs for host/device-side inputs it may have held.
5250 for (const auto *OA : CollapsedOffloadActions)
5251 cast<OffloadAction>(OA)->doOnEachDependence(
5252 /*IsHostDependence=*/BuildingForOffloadDevice,
5253 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
5254 OffloadDependencesInputInfo.append(BuildJobsForAction(
5255 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
5256 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
5257 DepA->getOffloadingDeviceKind()));
5260 // Only use pipes when there is exactly one input.
5261 InputInfoList InputInfos;
5262 for (const Action *Input : Inputs) {
5263 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
5264 // shouldn't get temporary output names.
5265 // FIXME: Clean this up.
5266 bool SubJobAtTopLevel =
5267 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
5268 InputInfos.append(BuildJobsForAction(
5269 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
5270 CachedResults, A->getOffloadingDeviceKind()));
5273 // Always use the first file input as the base input.
5274 const char *BaseInput = InputInfos[0].getBaseInput();
5275 for (auto &Info : InputInfos) {
5276 if (Info.isFilename()) {
5277 BaseInput = Info.getBaseInput();
5282 // ... except dsymutil actions, which use their actual input as the base
5284 if (JA->getType() == types::TY_dSYM)
5285 BaseInput = InputInfos[0].getFilename();
5287 // ... and in header module compilations, which use the module name.
5288 if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
5289 BaseInput = ModuleJA->getModuleName();
5291 // Append outputs of offload device jobs to the input list
5292 if (!OffloadDependencesInputInfo.empty())
5293 InputInfos.append(OffloadDependencesInputInfo.begin(),
5294 OffloadDependencesInputInfo.end());
5296 // Set the effective triple of the toolchain for the duration of this job.
5297 llvm::Triple EffectiveTriple;
5298 const ToolChain &ToolTC = T->getToolChain();
5299 const ArgList &Args =
5300 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
5301 if (InputInfos.size() != 1) {
5302 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
5304 // Pass along the input type if it can be unambiguously determined.
5305 EffectiveTriple = llvm::Triple(
5306 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
5308 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
5310 // Determine the place to write output to, if any.
5312 InputInfoList UnbundlingResults;
5313 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
5314 // If we have an unbundling job, we need to create results for all the
5315 // outputs. We also update the results cache so that other actions using
5316 // this unbundling action can get the right results.
5317 for (auto &UI : UA->getDependentActionsInfo()) {
5318 assert(UI.DependentOffloadKind != Action::OFK_None &&
5319 "Unbundling with no offloading??");
5321 // Unbundling actions are never at the top level. When we generate the
5322 // offloading prefix, we also do that for the host file because the
5323 // unbundling action does not change the type of the output which can
5324 // cause a overwrite.
5325 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
5326 UI.DependentOffloadKind,
5327 UI.DependentToolChain->getTriple().normalize(),
5328 /*CreatePrefixForHost=*/true);
5329 auto CurI = InputInfo(
5331 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
5332 /*AtTopLevel=*/false,
5334 UI.DependentOffloadKind == Action::OFK_HIP,
5337 // Save the unbundling result.
5338 UnbundlingResults.push_back(CurI);
5340 // Get the unique string identifier for this dependence and cache the
5343 if (TargetDeviceOffloadKind == Action::OFK_HIP) {
5344 if (UI.DependentOffloadKind == Action::OFK_Host)
5347 Arch = UI.DependentBoundArch;
5351 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
5352 UI.DependentOffloadKind)}] = {
5356 // Now that we have all the results generated, select the one that should be
5357 // returned for the current depending action.
5358 std::pair<const Action *, std::string> ActionTC = {
5359 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
5360 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
5361 "Result does not exist??");
5362 Result = CachedResults[ActionTC].front();
5363 } else if (JA->getType() == types::TY_Nothing)
5364 Result = {InputInfo(A, BaseInput)};
5366 // We only have to generate a prefix for the host if this is not a top-level
5368 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
5369 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
5370 /*CreatePrefixForHost=*/isa<OffloadPackagerJobAction>(A) ||
5371 !(A->getOffloadingHostActiveKinds() == Action::OFK_None ||
5373 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
5374 AtTopLevel, MultipleArchs,
5379 if (CCCPrintBindings && !CCGenDiagnostics) {
5380 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
5381 << " - \"" << T->getName() << "\", inputs: [";
5382 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
5383 llvm::errs() << InputInfos[i].getAsString();
5385 llvm::errs() << ", ";
5387 if (UnbundlingResults.empty())
5388 llvm::errs() << "], output: " << Result.getAsString() << "\n";
5390 llvm::errs() << "], outputs: [";
5391 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
5392 llvm::errs() << UnbundlingResults[i].getAsString();
5394 llvm::errs() << ", ";
5396 llvm::errs() << "] \n";
5399 if (UnbundlingResults.empty())
5401 C, *JA, Result, InputInfos,
5402 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
5405 T->ConstructJobMultipleOutputs(
5406 C, *JA, UnbundlingResults, InputInfos,
5407 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
5413 const char *Driver::getDefaultImageName() const {
5414 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
5415 return Target.isOSWindows() ? "a.exe" : "a.out";
5418 /// Create output filename based on ArgValue, which could either be a
5419 /// full filename, filename without extension, or a directory. If ArgValue
5420 /// does not provide a filename, then use BaseName, and use the extension
5421 /// suitable for FileType.
5422 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
5424 types::ID FileType) {
5425 SmallString<128> Filename = ArgValue;
5427 if (ArgValue.empty()) {
5428 // If the argument is empty, output to BaseName in the current dir.
5429 Filename = BaseName;
5430 } else if (llvm::sys::path::is_separator(Filename.back())) {
5431 // If the argument is a directory, output to BaseName in that dir.
5432 llvm::sys::path::append(Filename, BaseName);
5435 if (!llvm::sys::path::has_extension(ArgValue)) {
5436 // If the argument didn't provide an extension, then set it.
5437 const char *Extension = types::getTypeTempSuffix(FileType, true);
5439 if (FileType == types::TY_Image &&
5440 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
5441 // The output file is a dll.
5445 llvm::sys::path::replace_extension(Filename, Extension);
5448 return Args.MakeArgString(Filename.c_str());
5451 static bool HasPreprocessOutput(const Action &JA) {
5452 if (isa<PreprocessJobAction>(JA))
5454 if (isa<OffloadAction>(JA) && isa<PreprocessJobAction>(JA.getInputs()[0]))
5456 if (isa<OffloadBundlingJobAction>(JA) &&
5457 HasPreprocessOutput(*(JA.getInputs()[0])))
5462 const char *Driver::CreateTempFile(Compilation &C, StringRef Prefix,
5463 StringRef Suffix, bool MultipleArchs,
5464 StringRef BoundArch) const {
5465 SmallString<128> TmpName;
5466 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
5467 Optional<std::string> CrashDirectory =
5468 CCGenDiagnostics && A
5469 ? std::string(A->getValue())
5470 : llvm::sys::Process::GetEnv("CLANG_CRASH_DIAGNOSTICS_DIR");
5471 if (CrashDirectory) {
5472 if (!getVFS().exists(*CrashDirectory))
5473 llvm::sys::fs::create_directories(*CrashDirectory);
5474 SmallString<128> Path(*CrashDirectory);
5475 llvm::sys::path::append(Path, Prefix);
5476 const char *Middle = !Suffix.empty() ? "-%%%%%%." : "-%%%%%%";
5477 if (std::error_code EC =
5478 llvm::sys::fs::createUniqueFile(Path + Middle + Suffix, TmpName)) {
5479 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5483 if (MultipleArchs && !BoundArch.empty()) {
5484 TmpName = GetTemporaryDirectory(Prefix);
5485 llvm::sys::path::append(TmpName,
5486 Twine(Prefix) + "-" + BoundArch + "." + Suffix);
5488 TmpName = GetTemporaryPath(Prefix, Suffix);
5491 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
5494 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
5495 const char *BaseInput,
5496 StringRef OrigBoundArch, bool AtTopLevel,
5498 StringRef OffloadingPrefix) const {
5499 std::string BoundArch = OrigBoundArch.str();
5500 if (is_style_windows(llvm::sys::path::Style::native)) {
5501 // BoundArch may contains ':', which is invalid in file names on Windows,
5502 // therefore replace it with '%'.
5503 std::replace(BoundArch.begin(), BoundArch.end(), ':', '@');
5506 llvm::PrettyStackTraceString CrashInfo("Computing output path");
5507 // Output to a user requested destination?
5508 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
5509 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
5510 return C.addResultFile(FinalOutput->getValue(), &JA);
5513 // For /P, preprocess to file named after BaseInput.
5514 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
5515 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
5516 StringRef BaseName = llvm::sys::path::filename(BaseInput);
5518 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
5519 NameArg = A->getValue();
5520 return C.addResultFile(
5521 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
5525 // Default to writing to stdout?
5526 if (AtTopLevel && !CCGenDiagnostics && HasPreprocessOutput(JA)) {
5530 if (JA.getType() == types::TY_ModuleFile &&
5531 C.getArgs().getLastArg(options::OPT_module_file_info)) {
5535 if (IsDXCMode() && !C.getArgs().hasArg(options::OPT_o))
5538 // Is this the assembly listing for /FA?
5539 if (JA.getType() == types::TY_PP_Asm &&
5540 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
5541 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
5542 // Use /Fa and the input filename to determine the asm file name.
5543 StringRef BaseName = llvm::sys::path::filename(BaseInput);
5544 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
5545 return C.addResultFile(
5546 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
5550 // Output to a temporary file?
5551 if ((!AtTopLevel && !isSaveTempsEnabled() &&
5552 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
5554 StringRef Name = llvm::sys::path::filename(BaseInput);
5555 std::pair<StringRef, StringRef> Split = Name.split('.');
5556 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
5557 return CreateTempFile(C, Split.first, Suffix, MultipleArchs, BoundArch);
5560 SmallString<128> BasePath(BaseInput);
5561 SmallString<128> ExternalPath("");
5564 // Dsymutil actions should use the full path.
5565 if (isa<DsymutilJobAction>(JA) && C.getArgs().hasArg(options::OPT_dsym_dir)) {
5566 ExternalPath += C.getArgs().getLastArg(options::OPT_dsym_dir)->getValue();
5567 // We use posix style here because the tests (specifically
5568 // darwin-dsymutil.c) demonstrate that posix style paths are acceptable
5569 // even on Windows and if we don't then the similar test covering this
5571 llvm::sys::path::append(ExternalPath, llvm::sys::path::Style::posix,
5572 llvm::sys::path::filename(BasePath));
5573 BaseName = ExternalPath;
5574 } else if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
5575 BaseName = BasePath;
5577 BaseName = llvm::sys::path::filename(BasePath);
5579 // Determine what the derived output name should be.
5580 const char *NamedOutput;
5582 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
5583 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
5584 // The /Fo or /o flag decides the object filename.
5587 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
5590 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
5591 } else if (JA.getType() == types::TY_Image &&
5592 C.getArgs().hasArg(options::OPT__SLASH_Fe,
5593 options::OPT__SLASH_o)) {
5594 // The /Fe or /o flag names the linked file.
5597 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
5600 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
5601 } else if (JA.getType() == types::TY_Image) {
5603 // clang-cl uses BaseName for the executable name.
5605 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
5607 SmallString<128> Output(getDefaultImageName());
5608 // HIP image for device compilation with -fno-gpu-rdc is per compilation
5610 bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
5611 !C.getArgs().hasFlag(options::OPT_fgpu_rdc,
5612 options::OPT_fno_gpu_rdc, false);
5613 bool UseOutExtension = IsHIPNoRDC || isa<OffloadPackagerJobAction>(JA);
5614 if (UseOutExtension) {
5616 llvm::sys::path::replace_extension(Output, "");
5618 Output += OffloadingPrefix;
5619 if (MultipleArchs && !BoundArch.empty()) {
5621 Output.append(BoundArch);
5623 if (UseOutExtension)
5625 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
5627 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
5628 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
5629 } else if ((JA.getType() == types::TY_Plist || JA.getType() == types::TY_AST) &&
5630 C.getArgs().hasArg(options::OPT__SLASH_o)) {
5633 .getLastArg(options::OPT__SLASH_o)
5636 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
5638 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
5639 assert(Suffix && "All types used for output should have a suffix.");
5641 std::string::size_type End = std::string::npos;
5642 if (!types::appendSuffixForType(JA.getType()))
5643 End = BaseName.rfind('.');
5644 SmallString<128> Suffixed(BaseName.substr(0, End));
5645 Suffixed += OffloadingPrefix;
5646 if (MultipleArchs && !BoundArch.empty()) {
5648 Suffixed.append(BoundArch);
5650 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
5651 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
5652 // optimized bitcode output.
5653 auto IsHIPRDCInCompilePhase = [](const JobAction &JA,
5654 const llvm::opt::DerivedArgList &Args) {
5655 // The relocatable compilation in HIP implies -emit-llvm. Similarly, use a
5656 // ".tmp.bc" suffix for the unoptimized bitcode (generated in the compile
5658 return isa<CompileJobAction>(JA) &&
5659 JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
5660 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
5663 if (!AtTopLevel && JA.getType() == types::TY_LLVM_BC &&
5664 (C.getArgs().hasArg(options::OPT_emit_llvm) ||
5665 IsHIPRDCInCompilePhase(JA, C.getArgs())))
5669 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
5672 // Prepend object file path if -save-temps=obj
5673 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
5674 JA.getType() != types::TY_PCH) {
5675 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
5676 SmallString<128> TempPath(FinalOutput->getValue());
5677 llvm::sys::path::remove_filename(TempPath);
5678 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
5679 llvm::sys::path::append(TempPath, OutputFileName);
5680 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
5683 // If we're saving temps and the temp file conflicts with the input file,
5684 // then avoid overwriting input file.
5685 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
5686 bool SameFile = false;
5687 SmallString<256> Result;
5688 llvm::sys::fs::current_path(Result);
5689 llvm::sys::path::append(Result, BaseName);
5690 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
5691 // Must share the same path to conflict.
5693 StringRef Name = llvm::sys::path::filename(BaseInput);
5694 std::pair<StringRef, StringRef> Split = Name.split('.');
5695 std::string TmpName = GetTemporaryPath(
5696 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
5697 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
5701 // As an annoying special case, PCH generation doesn't strip the pathname.
5702 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
5703 llvm::sys::path::remove_filename(BasePath);
5704 if (BasePath.empty())
5705 BasePath = NamedOutput;
5707 llvm::sys::path::append(BasePath, NamedOutput);
5708 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
5710 return C.addResultFile(NamedOutput, &JA);
5714 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
5715 // Search for Name in a list of paths.
5716 auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
5717 -> llvm::Optional<std::string> {
5718 // Respect a limited subset of the '-Bprefix' functionality in GCC by
5719 // attempting to use this prefix when looking for file paths.
5720 for (const auto &Dir : P) {
5723 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
5724 llvm::sys::path::append(P, Name);
5725 if (llvm::sys::fs::exists(Twine(P)))
5726 return std::string(P);
5731 if (auto P = SearchPaths(PrefixDirs))
5734 SmallString<128> R(ResourceDir);
5735 llvm::sys::path::append(R, Name);
5736 if (llvm::sys::fs::exists(Twine(R)))
5737 return std::string(R.str());
5739 SmallString<128> P(TC.getCompilerRTPath());
5740 llvm::sys::path::append(P, Name);
5741 if (llvm::sys::fs::exists(Twine(P)))
5742 return std::string(P.str());
5744 SmallString<128> D(Dir);
5745 llvm::sys::path::append(D, "..", Name);
5746 if (llvm::sys::fs::exists(Twine(D)))
5747 return std::string(D.str());
5749 if (auto P = SearchPaths(TC.getLibraryPaths()))
5752 if (auto P = SearchPaths(TC.getFilePaths()))
5755 return std::string(Name);
5758 void Driver::generatePrefixedToolNames(
5759 StringRef Tool, const ToolChain &TC,
5760 SmallVectorImpl<std::string> &Names) const {
5761 // FIXME: Needs a better variable than TargetTriple
5762 Names.emplace_back((TargetTriple + "-" + Tool).str());
5763 Names.emplace_back(Tool);
5766 static bool ScanDirForExecutable(SmallString<128> &Dir, StringRef Name) {
5767 llvm::sys::path::append(Dir, Name);
5768 if (llvm::sys::fs::can_execute(Twine(Dir)))
5770 llvm::sys::path::remove_filename(Dir);
5774 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
5775 SmallVector<std::string, 2> TargetSpecificExecutables;
5776 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
5778 // Respect a limited subset of the '-Bprefix' functionality in GCC by
5779 // attempting to use this prefix when looking for program paths.
5780 for (const auto &PrefixDir : PrefixDirs) {
5781 if (llvm::sys::fs::is_directory(PrefixDir)) {
5782 SmallString<128> P(PrefixDir);
5783 if (ScanDirForExecutable(P, Name))
5784 return std::string(P.str());
5786 SmallString<128> P((PrefixDir + Name).str());
5787 if (llvm::sys::fs::can_execute(Twine(P)))
5788 return std::string(P.str());
5792 const ToolChain::path_list &List = TC.getProgramPaths();
5793 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) {
5794 // For each possible name of the tool look for it in
5795 // program paths first, then the path.
5796 // Higher priority names will be first, meaning that
5797 // a higher priority name in the path will be found
5798 // instead of a lower priority name in the program path.
5799 // E.g. <triple>-gcc on the path will be found instead
5800 // of gcc in the program path
5801 for (const auto &Path : List) {
5802 SmallString<128> P(Path);
5803 if (ScanDirForExecutable(P, TargetSpecificExecutable))
5804 return std::string(P.str());
5807 // Fall back to the path
5808 if (llvm::ErrorOr<std::string> P =
5809 llvm::sys::findProgramByName(TargetSpecificExecutable))
5813 return std::string(Name);
5816 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
5817 SmallString<128> Path;
5818 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
5820 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5824 return std::string(Path.str());
5827 std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
5828 SmallString<128> Path;
5829 std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
5831 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5835 return std::string(Path.str());
5838 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
5839 SmallString<128> Output;
5840 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
5841 // FIXME: If anybody needs it, implement this obscure rule:
5842 // "If you specify a directory without a file name, the default file name
5843 // is VCx0.pch., where x is the major version of Visual C++ in use."
5844 Output = FpArg->getValue();
5846 // "If you do not specify an extension as part of the path name, an
5847 // extension of .pch is assumed. "
5848 if (!llvm::sys::path::has_extension(Output))
5851 if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
5852 Output = YcArg->getValue();
5855 llvm::sys::path::replace_extension(Output, ".pch");
5857 return std::string(Output.str());
5860 const ToolChain &Driver::getToolChain(const ArgList &Args,
5861 const llvm::Triple &Target) const {
5863 auto &TC = ToolChains[Target.str()];
5865 switch (Target.getOS()) {
5866 case llvm::Triple::AIX:
5867 TC = std::make_unique<toolchains::AIX>(*this, Target, Args);
5869 case llvm::Triple::Haiku:
5870 TC = std::make_unique<toolchains::Haiku>(*this, Target, Args);
5872 case llvm::Triple::Ananas:
5873 TC = std::make_unique<toolchains::Ananas>(*this, Target, Args);
5875 case llvm::Triple::CloudABI:
5876 TC = std::make_unique<toolchains::CloudABI>(*this, Target, Args);
5878 case llvm::Triple::Darwin:
5879 case llvm::Triple::MacOSX:
5880 case llvm::Triple::IOS:
5881 case llvm::Triple::TvOS:
5882 case llvm::Triple::WatchOS:
5883 case llvm::Triple::DriverKit:
5884 TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args);
5886 case llvm::Triple::DragonFly:
5887 TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args);
5889 case llvm::Triple::OpenBSD:
5890 TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args);
5892 case llvm::Triple::NetBSD:
5893 TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args);
5895 case llvm::Triple::FreeBSD:
5897 TC = std::make_unique<toolchains::PPCFreeBSDToolChain>(*this, Target,
5900 TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args);
5902 case llvm::Triple::Minix:
5903 TC = std::make_unique<toolchains::Minix>(*this, Target, Args);
5905 case llvm::Triple::Linux:
5906 case llvm::Triple::ELFIAMCU:
5907 if (Target.getArch() == llvm::Triple::hexagon)
5908 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
5910 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
5911 !Target.hasEnvironment())
5912 TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
5914 else if (Target.isPPC())
5915 TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
5917 else if (Target.getArch() == llvm::Triple::ve)
5918 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
5921 TC = std::make_unique<toolchains::Linux>(*this, Target, Args);
5923 case llvm::Triple::NaCl:
5924 TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
5926 case llvm::Triple::Fuchsia:
5927 TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args);
5929 case llvm::Triple::Solaris:
5930 TC = std::make_unique<toolchains::Solaris>(*this, Target, Args);
5932 case llvm::Triple::AMDHSA:
5933 TC = std::make_unique<toolchains::ROCMToolChain>(*this, Target, Args);
5935 case llvm::Triple::AMDPAL:
5936 case llvm::Triple::Mesa3D:
5937 TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
5939 case llvm::Triple::Win32:
5940 switch (Target.getEnvironment()) {
5942 if (Target.isOSBinFormatELF())
5943 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
5944 else if (Target.isOSBinFormatMachO())
5945 TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
5947 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
5949 case llvm::Triple::GNU:
5950 TC = std::make_unique<toolchains::MinGW>(*this, Target, Args);
5952 case llvm::Triple::Itanium:
5953 TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
5956 case llvm::Triple::MSVC:
5957 case llvm::Triple::UnknownEnvironment:
5958 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
5959 .startswith_insensitive("bfd"))
5960 TC = std::make_unique<toolchains::CrossWindowsToolChain>(
5961 *this, Target, Args);
5964 std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
5968 case llvm::Triple::PS4:
5969 TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args);
5971 case llvm::Triple::PS5:
5972 TC = std::make_unique<toolchains::PS5CPU>(*this, Target, Args);
5974 case llvm::Triple::Contiki:
5975 TC = std::make_unique<toolchains::Contiki>(*this, Target, Args);
5977 case llvm::Triple::Hurd:
5978 TC = std::make_unique<toolchains::Hurd>(*this, Target, Args);
5980 case llvm::Triple::ZOS:
5981 TC = std::make_unique<toolchains::ZOS>(*this, Target, Args);
5983 case llvm::Triple::ShaderModel:
5984 TC = std::make_unique<toolchains::HLSLToolChain>(*this, Target, Args);
5987 // Of these targets, Hexagon is the only one that might have
5988 // an OS of Linux, in which case it got handled above already.
5989 switch (Target.getArch()) {
5990 case llvm::Triple::tce:
5991 TC = std::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
5993 case llvm::Triple::tcele:
5994 TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
5996 case llvm::Triple::hexagon:
5997 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
6000 case llvm::Triple::lanai:
6001 TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
6003 case llvm::Triple::xcore:
6004 TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
6006 case llvm::Triple::wasm32:
6007 case llvm::Triple::wasm64:
6008 TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args);
6010 case llvm::Triple::avr:
6011 TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
6013 case llvm::Triple::msp430:
6015 std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
6017 case llvm::Triple::riscv32:
6018 case llvm::Triple::riscv64:
6019 if (toolchains::RISCVToolChain::hasGCCToolchain(*this, Args))
6021 std::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
6023 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
6025 case llvm::Triple::ve:
6026 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
6028 case llvm::Triple::spirv32:
6029 case llvm::Triple::spirv64:
6030 TC = std::make_unique<toolchains::SPIRVToolChain>(*this, Target, Args);
6032 case llvm::Triple::csky:
6033 TC = std::make_unique<toolchains::CSKYToolChain>(*this, Target, Args);
6036 if (Target.getVendor() == llvm::Triple::Myriad)
6037 TC = std::make_unique<toolchains::MyriadToolChain>(*this, Target,
6039 else if (toolchains::BareMetal::handlesTarget(Target))
6040 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
6041 else if (Target.isOSBinFormatELF())
6042 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
6043 else if (Target.isOSBinFormatMachO())
6044 TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
6046 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
6051 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
6052 // compiles always need two toolchains, the CUDA toolchain and the host
6053 // toolchain. So the only valid way to create a CUDA toolchain is via
6054 // CreateOffloadingDeviceToolChains.
6059 const ToolChain &Driver::getOffloadingDeviceToolChain(
6060 const ArgList &Args, const llvm::Triple &Target, const ToolChain &HostTC,
6061 const Action::OffloadKind &TargetDeviceOffloadKind) const {
6062 // Use device / host triples as the key into the ToolChains map because the
6063 // device ToolChain we create depends on both.
6064 auto &TC = ToolChains[Target.str() + "/" + HostTC.getTriple().str()];
6066 // Categorized by offload kind > arch rather than OS > arch like
6067 // the normal getToolChain call, as it seems a reasonable way to categorize
6069 switch (TargetDeviceOffloadKind) {
6070 case Action::OFK_HIP: {
6071 if (Target.getArch() == llvm::Triple::amdgcn &&
6072 Target.getVendor() == llvm::Triple::AMD &&
6073 Target.getOS() == llvm::Triple::AMDHSA)
6074 TC = std::make_unique<toolchains::HIPAMDToolChain>(*this, Target,
6076 else if (Target.getArch() == llvm::Triple::spirv64 &&
6077 Target.getVendor() == llvm::Triple::UnknownVendor &&
6078 Target.getOS() == llvm::Triple::UnknownOS)
6079 TC = std::make_unique<toolchains::HIPSPVToolChain>(*this, Target,
6091 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
6092 // Say "no" if there is not exactly one input of a type clang understands.
6093 if (JA.size() != 1 ||
6094 !types::isAcceptedByClang((*JA.input_begin())->getType()))
6097 // And say "no" if this is not a kind of action clang understands.
6098 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
6099 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA) &&
6100 !isa<ExtractAPIJobAction>(JA))
6106 bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const {
6107 // Say "no" if there is not exactly one input of a type flang understands.
6108 if (JA.size() != 1 ||
6109 !types::isAcceptedByFlang((*JA.input_begin())->getType()))
6112 // And say "no" if this is not a kind of action flang understands.
6113 if (!isa<PreprocessJobAction>(JA) && !isa<CompileJobAction>(JA) &&
6114 !isa<BackendJobAction>(JA))
6120 bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const {
6121 // Only emit static library if the flag is set explicitly.
6122 if (Args.hasArg(options::OPT_emit_static_lib))
6127 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
6128 /// grouped values as integers. Numbers which are not provided are set to 0.
6130 /// \return True if the entire string was parsed (9.2), or all groups were
6131 /// parsed (10.3.5extrastuff).
6132 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
6133 unsigned &Micro, bool &HadExtra) {
6136 Major = Minor = Micro = 0;
6140 if (Str.consumeInteger(10, Major))
6147 Str = Str.drop_front(1);
6149 if (Str.consumeInteger(10, Minor))
6155 Str = Str.drop_front(1);
6157 if (Str.consumeInteger(10, Micro))
6164 /// Parse digits from a string \p Str and fulfill \p Digits with
6165 /// the parsed numbers. This method assumes that the max number of
6166 /// digits to look for is equal to Digits.size().
6168 /// \return True if the entire string was parsed and there are
6169 /// no extra characters remaining at the end.
6170 bool Driver::GetReleaseVersion(StringRef Str,
6171 MutableArrayRef<unsigned> Digits) {
6175 unsigned CurDigit = 0;
6176 while (CurDigit < Digits.size()) {
6178 if (Str.consumeInteger(10, Digit))
6180 Digits[CurDigit] = Digit;
6185 Str = Str.drop_front(1);
6189 // More digits than requested, bail out...
6193 std::pair<unsigned, unsigned>
6194 Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const {
6195 unsigned IncludedFlagsBitmask = 0;
6196 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
6198 if (IsClCompatMode) {
6199 // Include CL and Core options.
6200 IncludedFlagsBitmask |= options::CLOption;
6201 IncludedFlagsBitmask |= options::CLDXCOption;
6202 IncludedFlagsBitmask |= options::CoreOption;
6204 ExcludedFlagsBitmask |= options::CLOption;
6207 // Include DXC and Core options.
6208 IncludedFlagsBitmask |= options::DXCOption;
6209 IncludedFlagsBitmask |= options::CLDXCOption;
6210 IncludedFlagsBitmask |= options::CoreOption;
6212 ExcludedFlagsBitmask |= options::DXCOption;
6214 if (!IsClCompatMode && !IsDXCMode())
6215 ExcludedFlagsBitmask |= options::CLDXCOption;
6217 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
6220 const char *Driver::getExecutableForDriverMode(DriverMode Mode) {
6236 llvm_unreachable("Unhandled Mode");
6239 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
6240 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
6243 bool clang::driver::willEmitRemarks(const ArgList &Args) {
6244 // -fsave-optimization-record enables it.
6245 if (Args.hasFlag(options::OPT_fsave_optimization_record,
6246 options::OPT_fno_save_optimization_record, false))
6249 // -fsave-optimization-record=<format> enables it as well.
6250 if (Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
6251 options::OPT_fno_save_optimization_record, false))
6254 // -foptimization-record-file alone enables it too.
6255 if (Args.hasFlag(options::OPT_foptimization_record_file_EQ,
6256 options::OPT_fno_save_optimization_record, false))
6259 // -foptimization-record-passes alone enables it too.
6260 if (Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
6261 options::OPT_fno_save_optimization_record, false))
6266 llvm::StringRef clang::driver::getDriverMode(StringRef ProgName,
6267 ArrayRef<const char *> Args) {
6268 static const std::string OptName =
6269 getDriverOptTable().getOption(options::OPT_driver_mode).getPrefixedName();
6270 llvm::StringRef Opt;
6271 for (StringRef Arg : Args) {
6272 if (!Arg.startswith(OptName))
6277 Opt = ToolChain::getTargetAndModeFromProgramName(ProgName).DriverMode;
6278 return Opt.consume_front(OptName) ? Opt : "";
6281 bool driver::IsClangCL(StringRef DriverMode) { return DriverMode.equals("cl"); }