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 "InputInfo.h"
11 #include "ToolChains/AIX.h"
12 #include "ToolChains/AMDGPU.h"
13 #include "ToolChains/AVR.h"
14 #include "ToolChains/Ananas.h"
15 #include "ToolChains/BareMetal.h"
16 #include "ToolChains/Clang.h"
17 #include "ToolChains/CloudABI.h"
18 #include "ToolChains/Contiki.h"
19 #include "ToolChains/CrossWindows.h"
20 #include "ToolChains/Cuda.h"
21 #include "ToolChains/Darwin.h"
22 #include "ToolChains/DragonFly.h"
23 #include "ToolChains/FreeBSD.h"
24 #include "ToolChains/Fuchsia.h"
25 #include "ToolChains/Gnu.h"
26 #include "ToolChains/HIP.h"
27 #include "ToolChains/Haiku.h"
28 #include "ToolChains/Hexagon.h"
29 #include "ToolChains/Hurd.h"
30 #include "ToolChains/Lanai.h"
31 #include "ToolChains/Linux.h"
32 #include "ToolChains/MSP430.h"
33 #include "ToolChains/MSVC.h"
34 #include "ToolChains/MinGW.h"
35 #include "ToolChains/Minix.h"
36 #include "ToolChains/MipsLinux.h"
37 #include "ToolChains/Myriad.h"
38 #include "ToolChains/NaCl.h"
39 #include "ToolChains/NetBSD.h"
40 #include "ToolChains/OpenBSD.h"
41 #include "ToolChains/PS4CPU.h"
42 #include "ToolChains/PPCLinux.h"
43 #include "ToolChains/RISCVToolchain.h"
44 #include "ToolChains/Solaris.h"
45 #include "ToolChains/TCE.h"
46 #include "ToolChains/WebAssembly.h"
47 #include "ToolChains/XCore.h"
48 #include "clang/Basic/Version.h"
49 #include "clang/Config/config.h"
50 #include "clang/Driver/Action.h"
51 #include "clang/Driver/Compilation.h"
52 #include "clang/Driver/DriverDiagnostic.h"
53 #include "clang/Driver/Job.h"
54 #include "clang/Driver/Options.h"
55 #include "clang/Driver/SanitizerArgs.h"
56 #include "clang/Driver/Tool.h"
57 #include "clang/Driver/ToolChain.h"
58 #include "llvm/ADT/ArrayRef.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include "llvm/ADT/SmallSet.h"
61 #include "llvm/ADT/StringExtras.h"
62 #include "llvm/ADT/StringSet.h"
63 #include "llvm/ADT/StringSwitch.h"
64 #include "llvm/Config/llvm-config.h"
65 #include "llvm/Option/Arg.h"
66 #include "llvm/Option/ArgList.h"
67 #include "llvm/Option/OptSpecifier.h"
68 #include "llvm/Option/OptTable.h"
69 #include "llvm/Option/Option.h"
70 #include "llvm/Support/CommandLine.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/FileSystem.h"
73 #include "llvm/Support/FormatVariadic.h"
74 #include "llvm/Support/Path.h"
75 #include "llvm/Support/PrettyStackTrace.h"
76 #include "llvm/Support/Process.h"
77 #include "llvm/Support/Program.h"
78 #include "llvm/Support/StringSaver.h"
79 #include "llvm/Support/TargetRegistry.h"
80 #include "llvm/Support/VirtualFileSystem.h"
81 #include "llvm/Support/raw_ostream.h"
86 #include <unistd.h> // getpid
87 #include <sysexits.h> // EX_IOERR
90 using namespace clang::driver;
91 using namespace clang;
92 using namespace llvm::opt;
95 std::string Driver::GetResourcesPath(StringRef BinaryPath,
96 StringRef CustomResourceDir) {
97 // Since the resource directory is embedded in the module hash, it's important
98 // that all places that need it call this function, so that they get the
99 // exact same string ("a/../b/" and "b/" get different hashes, for example).
101 // Dir is bin/ or lib/, depending on where BinaryPath is.
102 std::string Dir = llvm::sys::path::parent_path(BinaryPath);
104 SmallString<128> P(Dir);
105 if (CustomResourceDir != "") {
106 llvm::sys::path::append(P, CustomResourceDir);
108 // On Windows, libclang.dll is in bin/.
109 // On non-Windows, libclang.so/.dylib is in lib/.
110 // With a static-library build of libclang, LibClangPath will contain the
111 // path of the embedding binary, which for LLVM binaries will be in bin/.
112 // ../lib gets us to lib/ in both cases.
113 P = llvm::sys::path::parent_path(Dir);
114 llvm::sys::path::append(P, Twine("lib") + CLANG_LIBDIR_SUFFIX, "clang",
115 CLANG_VERSION_STRING);
121 Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
122 DiagnosticsEngine &Diags,
123 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
124 : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
125 SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None),
126 ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
127 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
128 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
129 CCCPrintBindings(false), CCPrintOptions(false), CCPrintHeaders(false),
130 CCLogDiagnostics(false), CCGenDiagnostics(false),
131 TargetTriple(TargetTriple), CCCGenericGCCName(""), Saver(Alloc),
132 CheckInputsExist(true), GenReproducer(false),
133 SuppressMissingInputWarning(false) {
135 // Provide a sane fallback if no VFS is specified.
137 this->VFS = llvm::vfs::getRealFileSystem();
139 Name = llvm::sys::path::filename(ClangExecutable);
140 Dir = llvm::sys::path::parent_path(ClangExecutable);
141 InstalledDir = Dir; // Provide a sensible default installed dir.
143 #if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
144 SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
146 #if defined(CLANG_CONFIG_FILE_USER_DIR)
147 UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
150 // Compute the path to the resource directory.
151 ResourceDir = GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
154 void Driver::ParseDriverMode(StringRef ProgramName,
155 ArrayRef<const char *> Args) {
156 if (ClangNameParts.isEmpty())
157 ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
158 setDriverModeFromOption(ClangNameParts.DriverMode);
160 for (const char *ArgPtr : Args) {
161 // Ignore nullptrs, they are the response file's EOL markers.
162 if (ArgPtr == nullptr)
164 const StringRef Arg = ArgPtr;
165 setDriverModeFromOption(Arg);
169 void Driver::setDriverModeFromOption(StringRef Opt) {
170 const std::string OptName =
171 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
172 if (!Opt.startswith(OptName))
174 StringRef Value = Opt.drop_front(OptName.size());
176 if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
177 .Case("gcc", GCCMode)
178 .Case("g++", GXXMode)
179 .Case("cpp", CPPMode)
181 .Case("flang", FlangMode)
185 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
188 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
190 bool &ContainsError) {
191 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
192 ContainsError = false;
194 unsigned IncludedFlagsBitmask;
195 unsigned ExcludedFlagsBitmask;
196 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
197 getIncludeExcludeOptionFlagMasks(IsClCompatMode);
199 unsigned MissingArgIndex, MissingArgCount;
201 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
202 IncludedFlagsBitmask, ExcludedFlagsBitmask);
204 // Check for missing argument error.
205 if (MissingArgCount) {
206 Diag(diag::err_drv_missing_argument)
207 << Args.getArgString(MissingArgIndex) << MissingArgCount;
209 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
210 SourceLocation()) > DiagnosticsEngine::Warning;
213 // Check for unsupported options.
214 for (const Arg *A : Args) {
215 if (A->getOption().hasFlag(options::Unsupported)) {
217 auto ArgString = A->getAsString(Args);
219 if (getOpts().findNearest(
220 ArgString, Nearest, IncludedFlagsBitmask,
221 ExcludedFlagsBitmask | options::Unsupported) > 1) {
222 DiagID = diag::err_drv_unsupported_opt;
223 Diag(DiagID) << ArgString;
225 DiagID = diag::err_drv_unsupported_opt_with_suggestion;
226 Diag(DiagID) << ArgString << Nearest;
228 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
229 DiagnosticsEngine::Warning;
233 // Warn about -mcpu= without an argument.
234 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
235 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
236 ContainsError |= Diags.getDiagnosticLevel(
237 diag::warn_drv_empty_joined_argument,
238 SourceLocation()) > DiagnosticsEngine::Warning;
242 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
244 auto ArgString = A->getAsString(Args);
246 if (getOpts().findNearest(
247 ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
248 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
249 : diag::err_drv_unknown_argument;
250 Diags.Report(DiagID) << ArgString;
253 ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
254 : diag::err_drv_unknown_argument_with_suggestion;
255 Diags.Report(DiagID) << ArgString << Nearest;
257 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
258 DiagnosticsEngine::Warning;
264 // Determine which compilation mode we are in. We look for options which
265 // affect the phase, starting with the earliest phases, and record which
266 // option we used to determine the final phase.
267 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
268 Arg **FinalPhaseArg) const {
269 Arg *PhaseArg = nullptr;
270 phases::ID FinalPhase;
272 // -{E,EP,P,M,MM} only run the preprocessor.
273 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
274 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
275 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
276 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
277 FinalPhase = phases::Preprocess;
279 // --precompile only runs up to precompilation.
280 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
281 FinalPhase = phases::Precompile;
283 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
284 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
285 (PhaseArg = DAL.getLastArg(options::OPT_print_supported_cpus)) ||
286 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
287 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
288 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
289 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
290 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
291 (PhaseArg = DAL.getLastArg(options::OPT__analyze)) ||
292 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
293 FinalPhase = phases::Compile;
295 // -S only runs up to the backend.
296 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
297 FinalPhase = phases::Backend;
299 // -c compilation only runs up to the assembler.
300 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
301 FinalPhase = phases::Assemble;
303 // Otherwise do everything.
305 FinalPhase = phases::Link;
308 *FinalPhaseArg = PhaseArg;
313 static Arg *MakeInputArg(DerivedArgList &Args, const OptTable &Opts,
314 StringRef Value, bool Claim = true) {
315 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
316 Args.getBaseArgs().MakeIndex(Value), Value.data());
317 Args.AddSynthesizedArg(A);
323 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
324 const llvm::opt::OptTable &Opts = getOpts();
325 DerivedArgList *DAL = new DerivedArgList(Args);
327 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
328 bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
329 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
330 for (Arg *A : Args) {
331 // Unfortunately, we have to parse some forwarding options (-Xassembler,
332 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
333 // (assembler and preprocessor), or bypass a previous driver ('collect2').
335 // Rewrite linker options, to replace --no-demangle with a custom internal
337 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
338 A->getOption().matches(options::OPT_Xlinker)) &&
339 A->containsValue("--no-demangle")) {
340 // Add the rewritten no-demangle argument.
341 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_Xlinker__no_demangle));
343 // Add the remaining values as Xlinker arguments.
344 for (StringRef Val : A->getValues())
345 if (Val != "--no-demangle")
346 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_Xlinker), Val);
351 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
352 // some build systems. We don't try to be complete here because we don't
353 // care to encourage this usage model.
354 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
355 (A->getValue(0) == StringRef("-MD") ||
356 A->getValue(0) == StringRef("-MMD"))) {
357 // Rewrite to -MD/-MMD along with -MF.
358 if (A->getValue(0) == StringRef("-MD"))
359 DAL->AddFlagArg(A, Opts.getOption(options::OPT_MD));
361 DAL->AddFlagArg(A, Opts.getOption(options::OPT_MMD));
362 if (A->getNumValues() == 2)
363 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue(1));
367 // Rewrite reserved library names.
368 if (A->getOption().matches(options::OPT_l)) {
369 StringRef Value = A->getValue();
371 // Rewrite unless -nostdlib is present.
372 if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx &&
374 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_stdcxx));
378 // Rewrite unconditionally.
379 if (Value == "cc_kext") {
380 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_cckext));
385 // Pick up inputs via the -- option.
386 if (A->getOption().matches(options::OPT__DASH_DASH)) {
388 for (StringRef Val : A->getValues())
389 DAL->append(MakeInputArg(*DAL, Opts, Val, false));
396 // Enforce -static if -miamcu is present.
397 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
398 DAL->AddFlagArg(0, Opts.getOption(options::OPT_static));
400 // Add a default value of -mlinker-version=, if one was given and the user
401 // didn't specify one.
402 #if defined(HOST_LINK_VERSION)
403 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
404 strlen(HOST_LINK_VERSION) > 0) {
405 DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ),
407 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
414 /// Compute target triple from args.
416 /// This routine provides the logic to compute a target triple from various
417 /// args passed to the driver and the default triple string.
418 static llvm::Triple computeTargetTriple(const Driver &D,
419 StringRef TargetTriple,
421 StringRef DarwinArchName = "") {
422 // FIXME: Already done in Compilation *Driver::BuildCompilation
423 if (const Arg *A = Args.getLastArg(options::OPT_target))
424 TargetTriple = A->getValue();
426 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
428 // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
429 // -gnu* only, and we can not change this, so we have to detect that case as
430 // being the Hurd OS.
431 if (TargetTriple.find("-unknown-gnu") != StringRef::npos ||
432 TargetTriple.find("-pc-gnu") != StringRef::npos)
433 Target.setOSName("hurd");
435 // Handle Apple-specific options available here.
436 if (Target.isOSBinFormatMachO()) {
437 // If an explicit Darwin arch name is given, that trumps all.
438 if (!DarwinArchName.empty()) {
439 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
443 // Handle the Darwin '-arch' flag.
444 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
445 StringRef ArchName = A->getValue();
446 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
450 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
451 // '-mbig-endian'/'-EB'.
452 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
453 options::OPT_mbig_endian)) {
454 if (A->getOption().matches(options::OPT_mlittle_endian)) {
455 llvm::Triple LE = Target.getLittleEndianArchVariant();
456 if (LE.getArch() != llvm::Triple::UnknownArch)
457 Target = std::move(LE);
459 llvm::Triple BE = Target.getBigEndianArchVariant();
460 if (BE.getArch() != llvm::Triple::UnknownArch)
461 Target = std::move(BE);
465 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
466 if (Target.getArch() == llvm::Triple::tce ||
467 Target.getOS() == llvm::Triple::Minix)
470 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
471 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
472 options::OPT_m32, options::OPT_m16);
474 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
476 if (A->getOption().matches(options::OPT_m64)) {
477 AT = Target.get64BitArchVariant().getArch();
478 if (Target.getEnvironment() == llvm::Triple::GNUX32)
479 Target.setEnvironment(llvm::Triple::GNU);
480 } else if (A->getOption().matches(options::OPT_mx32) &&
481 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
482 AT = llvm::Triple::x86_64;
483 Target.setEnvironment(llvm::Triple::GNUX32);
484 } else if (A->getOption().matches(options::OPT_m32)) {
485 AT = Target.get32BitArchVariant().getArch();
486 if (Target.getEnvironment() == llvm::Triple::GNUX32)
487 Target.setEnvironment(llvm::Triple::GNU);
488 } else if (A->getOption().matches(options::OPT_m16) &&
489 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
490 AT = llvm::Triple::x86;
491 Target.setEnvironment(llvm::Triple::CODE16);
494 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
498 // Handle -miamcu flag.
499 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
500 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
501 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
504 if (A && !A->getOption().matches(options::OPT_m32))
505 D.Diag(diag::err_drv_argument_not_allowed_with)
506 << "-miamcu" << A->getBaseArg().getAsString(Args);
508 Target.setArch(llvm::Triple::x86);
509 Target.setArchName("i586");
510 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
511 Target.setEnvironmentName("");
512 Target.setOS(llvm::Triple::ELFIAMCU);
513 Target.setVendor(llvm::Triple::UnknownVendor);
514 Target.setVendorName("intel");
517 // If target is MIPS adjust the target triple
518 // accordingly to provided ABI name.
519 A = Args.getLastArg(options::OPT_mabi_EQ);
520 if (A && Target.isMIPS()) {
521 StringRef ABIName = A->getValue();
522 if (ABIName == "32") {
523 Target = Target.get32BitArchVariant();
524 if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
525 Target.getEnvironment() == llvm::Triple::GNUABIN32)
526 Target.setEnvironment(llvm::Triple::GNU);
527 } else if (ABIName == "n32") {
528 Target = Target.get64BitArchVariant();
529 if (Target.getEnvironment() == llvm::Triple::GNU ||
530 Target.getEnvironment() == llvm::Triple::GNUABI64)
531 Target.setEnvironment(llvm::Triple::GNUABIN32);
532 } else if (ABIName == "64") {
533 Target = Target.get64BitArchVariant();
534 if (Target.getEnvironment() == llvm::Triple::GNU ||
535 Target.getEnvironment() == llvm::Triple::GNUABIN32)
536 Target.setEnvironment(llvm::Triple::GNUABI64);
540 // If target is RISC-V adjust the target triple according to
541 // provided architecture name
542 A = Args.getLastArg(options::OPT_march_EQ);
543 if (A && Target.isRISCV()) {
544 StringRef ArchName = A->getValue();
545 if (ArchName.startswith_lower("rv32"))
546 Target.setArch(llvm::Triple::riscv32);
547 else if (ArchName.startswith_lower("rv64"))
548 Target.setArch(llvm::Triple::riscv64);
554 // Parse the LTO options and record the type of LTO compilation
555 // based on which -f(no-)?lto(=.*)? option occurs last.
556 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
558 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
559 options::OPT_fno_lto, false))
562 StringRef LTOName("full");
564 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
566 LTOName = A->getValue();
568 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
569 .Case("full", LTOK_Full)
570 .Case("thin", LTOK_Thin)
571 .Default(LTOK_Unknown);
573 if (LTOMode == LTOK_Unknown) {
575 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
580 /// Compute the desired OpenMP runtime from the flags provided.
581 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
582 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
584 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
586 RuntimeName = A->getValue();
588 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
589 .Case("libomp", OMPRT_OMP)
590 .Case("libgomp", OMPRT_GOMP)
591 .Case("libiomp5", OMPRT_IOMP5)
592 .Default(OMPRT_Unknown);
594 if (RT == OMPRT_Unknown) {
596 Diag(diag::err_drv_unsupported_option_argument)
597 << A->getOption().getName() << A->getValue();
599 // FIXME: We could use a nicer diagnostic here.
600 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
606 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
612 // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
613 // or HIP type. However, mixed CUDA/HIP compilation is not supported.
615 llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
616 return types::isCuda(I.first);
620 [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
621 return types::isHIP(I.first);
623 C.getInputArgs().hasArg(options::OPT_hip_link);
624 if (IsCuda && IsHIP) {
625 Diag(clang::diag::err_drv_mix_cuda_hip);
629 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
630 const llvm::Triple &HostTriple = HostTC->getTriple();
631 StringRef DeviceTripleStr;
632 auto OFK = Action::OFK_Cuda;
634 HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" : "nvptx-nvidia-cuda";
635 llvm::Triple CudaTriple(DeviceTripleStr);
636 // Use the CUDA and host triples as the key into the ToolChains map,
637 // because the device toolchain we create depends on both.
638 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
640 CudaTC = std::make_unique<toolchains::CudaToolChain>(
641 *this, CudaTriple, *HostTC, C.getInputArgs(), OFK);
643 C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
645 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
646 const llvm::Triple &HostTriple = HostTC->getTriple();
647 StringRef DeviceTripleStr;
648 auto OFK = Action::OFK_HIP;
649 DeviceTripleStr = "amdgcn-amd-amdhsa";
650 llvm::Triple HIPTriple(DeviceTripleStr);
651 // Use the HIP and host triples as the key into the ToolChains map,
652 // because the device toolchain we create depends on both.
653 auto &HIPTC = ToolChains[HIPTriple.str() + "/" + HostTriple.str()];
655 HIPTC = std::make_unique<toolchains::HIPToolChain>(
656 *this, HIPTriple, *HostTC, C.getInputArgs());
658 C.addOffloadDeviceToolChain(HIPTC.get(), OFK);
664 // We need to generate an OpenMP toolchain if the user specified targets with
665 // the -fopenmp-targets option.
666 if (Arg *OpenMPTargets =
667 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
668 if (OpenMPTargets->getNumValues()) {
669 // We expect that -fopenmp-targets is always used in conjunction with the
670 // option -fopenmp specifying a valid runtime with offloading support,
671 // i.e. libomp or libiomp.
672 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
673 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
674 options::OPT_fno_openmp, false);
675 if (HasValidOpenMPRuntime) {
676 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
677 HasValidOpenMPRuntime =
678 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
681 if (HasValidOpenMPRuntime) {
682 llvm::StringMap<const char *> FoundNormalizedTriples;
683 for (const char *Val : OpenMPTargets->getValues()) {
684 llvm::Triple TT(Val);
685 std::string NormalizedName = TT.normalize();
687 // Make sure we don't have a duplicate triple.
688 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
689 if (Duplicate != FoundNormalizedTriples.end()) {
690 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
691 << Val << Duplicate->second;
695 // Store the current triple so that we can check for duplicates in the
696 // following iterations.
697 FoundNormalizedTriples[NormalizedName] = Val;
699 // If the specified target is invalid, emit a diagnostic.
700 if (TT.getArch() == llvm::Triple::UnknownArch)
701 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
704 // CUDA toolchains have to be selected differently. They pair host
705 // and device in their implementation.
707 const ToolChain *HostTC =
708 C.getSingleOffloadToolChain<Action::OFK_Host>();
709 assert(HostTC && "Host toolchain should be always defined.");
711 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
713 CudaTC = std::make_unique<toolchains::CudaToolChain>(
714 *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
717 TC = &getToolChain(C.getInputArgs(), TT);
718 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
722 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
724 Diag(clang::diag::warn_drv_empty_joined_argument)
725 << OpenMPTargets->getAsString(C.getInputArgs());
729 // TODO: Add support for other offloading programming models here.
733 /// Looks the given directories for the specified file.
735 /// \param[out] FilePath File path, if the file was found.
736 /// \param[in] Dirs Directories used for the search.
737 /// \param[in] FileName Name of the file to search for.
738 /// \return True if file was found.
740 /// Looks for file specified by FileName sequentially in directories specified
743 static bool searchForFile(SmallVectorImpl<char> &FilePath,
744 ArrayRef<std::string> Dirs,
745 StringRef FileName) {
746 SmallString<128> WPath;
747 for (const std::string &Dir : Dirs) {
751 llvm::sys::path::append(WPath, Dir, FileName);
752 llvm::sys::path::native(WPath);
753 if (llvm::sys::fs::is_regular_file(WPath)) {
754 FilePath = std::move(WPath);
761 bool Driver::readConfigFile(StringRef FileName) {
762 // Try reading the given file.
763 SmallVector<const char *, 32> NewCfgArgs;
764 if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
765 Diag(diag::err_drv_cannot_read_config_file) << FileName;
769 // Read options from config file.
770 llvm::SmallString<128> CfgFileName(FileName);
771 llvm::sys::path::native(CfgFileName);
772 ConfigFile = CfgFileName.str();
774 CfgOptions = std::make_unique<InputArgList>(
775 ParseArgStrings(NewCfgArgs, IsCLMode(), ContainErrors));
781 if (CfgOptions->hasArg(options::OPT_config)) {
783 Diag(diag::err_drv_nested_config_file);
787 // Claim all arguments that come from a configuration file so that the driver
788 // does not warn on any that is unused.
789 for (Arg *A : *CfgOptions)
794 bool Driver::loadConfigFile() {
795 std::string CfgFileName;
796 bool FileSpecifiedExplicitly = false;
798 // Process options that change search path for config files.
800 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
801 SmallString<128> CfgDir;
803 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
804 if (!CfgDir.empty()) {
805 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
806 SystemConfigDir.clear();
808 SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
811 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
812 SmallString<128> CfgDir;
814 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
815 if (!CfgDir.empty()) {
816 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
817 UserConfigDir.clear();
819 UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
824 // First try to find config file specified in command line.
826 std::vector<std::string> ConfigFiles =
827 CLOptions->getAllArgValues(options::OPT_config);
828 if (ConfigFiles.size() > 1) {
829 Diag(diag::err_drv_duplicate_config);
833 if (!ConfigFiles.empty()) {
834 CfgFileName = ConfigFiles.front();
835 assert(!CfgFileName.empty());
837 // If argument contains directory separator, treat it as a path to
838 // configuration file.
839 if (llvm::sys::path::has_parent_path(CfgFileName)) {
840 SmallString<128> CfgFilePath;
841 if (llvm::sys::path::is_relative(CfgFileName))
842 llvm::sys::fs::current_path(CfgFilePath);
843 llvm::sys::path::append(CfgFilePath, CfgFileName);
844 if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
845 Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
848 return readConfigFile(CfgFilePath);
851 FileSpecifiedExplicitly = true;
855 // If config file is not specified explicitly, try to deduce configuration
856 // from executable name. For instance, an executable 'armv7l-clang' will
857 // search for config file 'armv7l-clang.cfg'.
858 if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
859 CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
861 if (CfgFileName.empty())
864 // Determine architecture part of the file name, if it is present.
865 StringRef CfgFileArch = CfgFileName;
866 size_t ArchPrefixLen = CfgFileArch.find('-');
867 if (ArchPrefixLen == StringRef::npos)
868 ArchPrefixLen = CfgFileArch.size();
869 llvm::Triple CfgTriple;
870 CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
871 CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
872 if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
875 if (!StringRef(CfgFileName).endswith(".cfg"))
876 CfgFileName += ".cfg";
878 // If config file starts with architecture name and command line options
879 // redefine architecture (with options like -m32 -LE etc), try finding new
880 // config file with that architecture.
881 SmallString<128> FixedConfigFile;
882 size_t FixedArchPrefixLen = 0;
884 // Get architecture name from config file name like 'i386.cfg' or
885 // 'armv7l-clang.cfg'.
886 // Check if command line options changes effective triple.
887 llvm::Triple EffectiveTriple = computeTargetTriple(*this,
888 CfgTriple.getTriple(), *CLOptions);
889 if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
890 FixedConfigFile = EffectiveTriple.getArchName();
891 FixedArchPrefixLen = FixedConfigFile.size();
892 // Append the rest of original file name so that file name transforms
893 // like: i386-clang.cfg -> x86_64-clang.cfg.
894 if (ArchPrefixLen < CfgFileName.size())
895 FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
899 // Prepare list of directories where config file is searched for.
900 SmallVector<std::string, 3> CfgFileSearchDirs;
901 CfgFileSearchDirs.push_back(UserConfigDir);
902 CfgFileSearchDirs.push_back(SystemConfigDir);
903 CfgFileSearchDirs.push_back(Dir);
905 // Try to find config file. First try file with corrected architecture.
906 llvm::SmallString<128> CfgFilePath;
907 if (!FixedConfigFile.empty()) {
908 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
909 return readConfigFile(CfgFilePath);
910 // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
911 FixedConfigFile.resize(FixedArchPrefixLen);
912 FixedConfigFile.append(".cfg");
913 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
914 return readConfigFile(CfgFilePath);
917 // Then try original file name.
918 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
919 return readConfigFile(CfgFilePath);
921 // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
922 if (!ClangNameParts.ModeSuffix.empty() &&
923 !ClangNameParts.TargetPrefix.empty()) {
924 CfgFileName.assign(ClangNameParts.TargetPrefix);
925 CfgFileName.append(".cfg");
926 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
927 return readConfigFile(CfgFilePath);
930 // Report error but only if config file was specified explicitly, by option
931 // --config. If it was deduced from executable name, it is not an error.
932 if (FileSpecifiedExplicitly) {
933 Diag(diag::err_drv_config_file_not_found) << CfgFileName;
934 for (const std::string &SearchDir : CfgFileSearchDirs)
935 if (!SearchDir.empty())
936 Diag(diag::note_drv_config_file_searched_in) << SearchDir;
943 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
944 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
946 // FIXME: Handle environment options which affect driver behavior, somewhere
947 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
949 if (Optional<std::string> CompilerPathValue =
950 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
951 StringRef CompilerPath = *CompilerPathValue;
952 while (!CompilerPath.empty()) {
953 std::pair<StringRef, StringRef> Split =
954 CompilerPath.split(llvm::sys::EnvPathSeparator);
955 PrefixDirs.push_back(Split.first);
956 CompilerPath = Split.second;
960 // We look for the driver mode option early, because the mode can affect
961 // how other options are parsed.
962 ParseDriverMode(ClangExecutable, ArgList.slice(1));
964 // FIXME: What are we going to do with -V and -b?
966 // Arguments specified in command line.
968 CLOptions = std::make_unique<InputArgList>(
969 ParseArgStrings(ArgList.slice(1), IsCLMode(), ContainsError));
971 // Try parsing configuration file.
973 ContainsError = loadConfigFile();
974 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
976 // All arguments, from both config file and command line.
977 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
978 : std::move(*CLOptions));
980 // The args for config files or /clang: flags belong to different InputArgList
981 // objects than Args. This copies an Arg from one of those other InputArgLists
982 // to the ownership of Args.
983 auto appendOneArg = [&Args](const Arg *Opt, const Arg *BaseArg) {
984 unsigned Index = Args.MakeIndex(Opt->getSpelling());
985 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
987 Copy->getValues() = Opt->getValues();
988 if (Opt->isClaimed())
994 for (auto *Opt : *CLOptions) {
995 if (Opt->getOption().matches(options::OPT_config))
997 const Arg *BaseArg = &Opt->getBaseArg();
1000 appendOneArg(Opt, BaseArg);
1003 // In CL mode, look for any pass-through arguments
1004 if (IsCLMode() && !ContainsError) {
1005 SmallVector<const char *, 16> CLModePassThroughArgList;
1006 for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
1008 CLModePassThroughArgList.push_back(A->getValue());
1011 if (!CLModePassThroughArgList.empty()) {
1012 // Parse any pass through args using default clang processing rather
1013 // than clang-cl processing.
1014 auto CLModePassThroughOptions = std::make_unique<InputArgList>(
1015 ParseArgStrings(CLModePassThroughArgList, false, ContainsError));
1018 for (auto *Opt : *CLModePassThroughOptions) {
1019 appendOneArg(Opt, nullptr);
1024 // Check for working directory option before accessing any files
1025 if (Arg *WD = Args.getLastArg(options::OPT_working_directory))
1026 if (VFS->setCurrentWorkingDirectory(WD->getValue()))
1027 Diag(diag::err_drv_unable_to_set_working_directory) << WD->getValue();
1029 // FIXME: This stuff needs to go into the Compilation, not the driver.
1030 bool CCCPrintPhases;
1032 // Silence driver warnings if requested
1033 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
1035 // -no-canonical-prefixes is used very early in main.
1036 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
1038 // f(no-)integated-cc1 is also used very early in main.
1039 Args.ClaimAllArgs(options::OPT_fintegrated_cc1);
1040 Args.ClaimAllArgs(options::OPT_fno_integrated_cc1);
1043 Args.ClaimAllArgs(options::OPT_pipe);
1045 // Extract -ccc args.
1047 // FIXME: We need to figure out where this behavior should live. Most of it
1048 // should be outside in the client; the parts that aren't should have proper
1049 // options, either by introducing new ones or by overloading gcc ones like -V
1051 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
1052 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
1053 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
1054 CCCGenericGCCName = A->getValue();
1055 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
1056 options::OPT_fno_crash_diagnostics,
1057 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
1058 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
1059 // and getToolChain is const.
1061 // clang-cl targets MSVC-style Win32.
1062 llvm::Triple T(TargetTriple);
1063 T.setOS(llvm::Triple::Win32);
1064 T.setVendor(llvm::Triple::PC);
1065 T.setEnvironment(llvm::Triple::MSVC);
1066 T.setObjectFormat(llvm::Triple::COFF);
1067 TargetTriple = T.str();
1069 if (const Arg *A = Args.getLastArg(options::OPT_target))
1070 TargetTriple = A->getValue();
1071 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
1072 Dir = InstalledDir = A->getValue();
1073 for (const Arg *A : Args.filtered(options::OPT_B)) {
1075 PrefixDirs.push_back(A->getValue(0));
1077 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
1078 SysRoot = A->getValue();
1079 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
1080 DyldPrefix = A->getValue();
1082 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
1083 ResourceDir = A->getValue();
1085 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
1086 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1087 .Case("cwd", SaveTempsCwd)
1088 .Case("obj", SaveTempsObj)
1089 .Default(SaveTempsCwd);
1094 // Process -fembed-bitcode= flags.
1095 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1096 StringRef Name = A->getValue();
1097 unsigned Model = llvm::StringSwitch<unsigned>(Name)
1098 .Case("off", EmbedNone)
1099 .Case("all", EmbedBitcode)
1100 .Case("bitcode", EmbedBitcode)
1101 .Case("marker", EmbedMarker)
1104 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1107 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
1110 std::unique_ptr<llvm::opt::InputArgList> UArgs =
1111 std::make_unique<InputArgList>(std::move(Args));
1113 // Perform the default argument translations.
1114 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
1116 // Owned by the host.
1117 const ToolChain &TC = getToolChain(
1118 *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
1120 // The compilation takes ownership of Args.
1121 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1124 if (!HandleImmediateArgs(*C))
1127 // Construct the list of inputs.
1129 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
1131 // Populate the tool chains for the offloading devices, if any.
1132 CreateOffloadingDeviceToolChains(*C, Inputs);
1134 // Construct the list of abstract actions to perform for this compilation. On
1135 // MachO targets this uses the driver-driver and universal actions.
1136 if (TC.getTriple().isOSBinFormatMachO())
1137 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
1139 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
1141 if (CCCPrintPhases) {
1151 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1152 llvm::opt::ArgStringList ASL;
1153 for (const auto *A : Args)
1154 A->render(Args, ASL);
1156 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1157 if (I != ASL.begin())
1159 Command::printArg(OS, *I, true);
1164 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1165 SmallString<128> &CrashDiagDir) {
1166 using namespace llvm::sys;
1167 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1168 "Only knows about .crash files on Darwin");
1170 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1171 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1172 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1173 path::home_directory(CrashDiagDir);
1174 if (CrashDiagDir.startswith("/var/root"))
1176 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1184 fs::file_status FileStatus;
1185 TimePoint<> LastAccessTime;
1186 SmallString<128> CrashFilePath;
1187 // Lookup the .crash files and get the one generated by a subprocess spawned
1188 // by this driver invocation.
1189 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1190 File != FileEnd && !EC; File.increment(EC)) {
1191 StringRef FileName = path::filename(File->path());
1192 if (!FileName.startswith(Name))
1194 if (fs::status(File->path(), FileStatus))
1196 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1197 llvm::MemoryBuffer::getFile(File->path());
1200 // The first line should start with "Process:", otherwise this isn't a real
1202 StringRef Data = CrashFile.get()->getBuffer();
1203 if (!Data.startswith("Process:"))
1205 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1206 size_t ParentProcPos = Data.find("Parent Process:");
1207 if (ParentProcPos == StringRef::npos)
1209 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1210 if (LineEnd == StringRef::npos)
1212 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1213 int OpenBracket = -1, CloseBracket = -1;
1214 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1215 if (ParentProcess[i] == '[')
1217 if (ParentProcess[i] == ']')
1220 // Extract the parent process PID from the .crash file and check whether
1221 // it matches this driver invocation pid.
1223 if (OpenBracket < 0 || CloseBracket < 0 ||
1224 ParentProcess.slice(OpenBracket + 1, CloseBracket)
1225 .getAsInteger(10, CrashPID) || CrashPID != PID) {
1229 // Found a .crash file matching the driver pid. To avoid getting an older
1230 // and misleading crash file, continue looking for the most recent.
1231 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1232 // multiple crashes poiting to the same parent process. Since the driver
1233 // does not collect pid information for the dispatched invocation there's
1234 // currently no way to distinguish among them.
1235 const auto FileAccessTime = FileStatus.getLastModificationTime();
1236 if (FileAccessTime > LastAccessTime) {
1237 CrashFilePath.assign(File->path());
1238 LastAccessTime = FileAccessTime;
1242 // If found, copy it over to the location of other reproducer files.
1243 if (!CrashFilePath.empty()) {
1244 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1253 // When clang crashes, produce diagnostic information including the fully
1254 // preprocessed source file(s). Request that the developer attach the
1255 // diagnostic information to a bug report.
1256 void Driver::generateCompilationDiagnostics(
1257 Compilation &C, const Command &FailingCommand,
1258 StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
1259 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
1262 // Don't try to generate diagnostics for link or dsymutil jobs.
1263 if (FailingCommand.getCreator().isLinkJob() ||
1264 FailingCommand.getCreator().isDsymutilJob())
1267 // Print the version of the compiler.
1268 PrintVersion(C, llvm::errs());
1270 Diag(clang::diag::note_drv_command_failed_diag_msg)
1271 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
1272 "crash backtrace, preprocessed source, and associated run script.";
1274 // Suppress driver output and emit preprocessor output to temp file.
1276 CCGenDiagnostics = true;
1278 // Save the original job command(s).
1279 Command Cmd = FailingCommand;
1281 // Keep track of whether we produce any errors while trying to produce
1282 // preprocessed sources.
1283 DiagnosticErrorTrap Trap(Diags);
1285 // Suppress tool output.
1286 C.initCompilationForDiagnostics();
1288 // Construct the list of inputs.
1290 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
1292 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
1293 bool IgnoreInput = false;
1295 // Ignore input from stdin or any inputs that cannot be preprocessed.
1296 // Check type first as not all linker inputs have a value.
1297 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
1299 } else if (!strcmp(it->second->getValue(), "-")) {
1300 Diag(clang::diag::note_drv_command_failed_diag_msg)
1301 << "Error generating preprocessed source(s) - "
1302 "ignoring input from stdin.";
1307 it = Inputs.erase(it);
1314 if (Inputs.empty()) {
1315 Diag(clang::diag::note_drv_command_failed_diag_msg)
1316 << "Error generating preprocessed source(s) - "
1317 "no preprocessable inputs.";
1321 // Don't attempt to generate preprocessed files if multiple -arch options are
1322 // used, unless they're all duplicates.
1323 llvm::StringSet<> ArchNames;
1324 for (const Arg *A : C.getArgs()) {
1325 if (A->getOption().matches(options::OPT_arch)) {
1326 StringRef ArchName = A->getValue();
1327 ArchNames.insert(ArchName);
1330 if (ArchNames.size() > 1) {
1331 Diag(clang::diag::note_drv_command_failed_diag_msg)
1332 << "Error generating preprocessed source(s) - cannot generate "
1333 "preprocessed source with multiple -arch options.";
1337 // Construct the list of abstract actions to perform for this compilation. On
1338 // Darwin OSes this uses the driver-driver and builds universal actions.
1339 const ToolChain &TC = C.getDefaultToolChain();
1340 if (TC.getTriple().isOSBinFormatMachO())
1341 BuildUniversalActions(C, TC, Inputs);
1343 BuildActions(C, C.getArgs(), Inputs, C.getActions());
1347 // If there were errors building the compilation, quit now.
1348 if (Trap.hasErrorOccurred()) {
1349 Diag(clang::diag::note_drv_command_failed_diag_msg)
1350 << "Error generating preprocessed source(s).";
1354 // Generate preprocessed output.
1355 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
1356 C.ExecuteJobs(C.getJobs(), FailingCommands);
1358 // If any of the preprocessing commands failed, clean up and exit.
1359 if (!FailingCommands.empty()) {
1360 Diag(clang::diag::note_drv_command_failed_diag_msg)
1361 << "Error generating preprocessed source(s).";
1365 const ArgStringList &TempFiles = C.getTempFiles();
1366 if (TempFiles.empty()) {
1367 Diag(clang::diag::note_drv_command_failed_diag_msg)
1368 << "Error generating preprocessed source(s).";
1372 Diag(clang::diag::note_drv_command_failed_diag_msg)
1373 << "\n********************\n\n"
1374 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1375 "Preprocessed source(s) and associated run script(s) are located at:";
1377 SmallString<128> VFS;
1378 SmallString<128> ReproCrashFilename;
1379 for (const char *TempFile : TempFiles) {
1380 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
1382 Report->TemporaryFiles.push_back(TempFile);
1383 if (ReproCrashFilename.empty()) {
1384 ReproCrashFilename = TempFile;
1385 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1387 if (StringRef(TempFile).endswith(".cache")) {
1388 // In some cases (modules) we'll dump extra data to help with reproducing
1389 // the crash into a directory next to the output.
1390 VFS = llvm::sys::path::filename(TempFile);
1391 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1395 // Assume associated files are based off of the first temporary file.
1396 CrashReportInfo CrashInfo(TempFiles[0], VFS);
1398 llvm::SmallString<128> Script(CrashInfo.Filename);
1399 llvm::sys::path::replace_extension(Script, "sh");
1401 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew);
1403 Diag(clang::diag::note_drv_command_failed_diag_msg)
1404 << "Error generating run script: " << Script << " " << EC.message();
1406 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
1407 << "# Driver args: ";
1408 printArgList(ScriptOS, C.getInputArgs());
1409 ScriptOS << "# Original command: ";
1410 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
1411 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
1412 if (!AdditionalInformation.empty())
1413 ScriptOS << "\n# Additional information: " << AdditionalInformation
1416 Report->TemporaryFiles.push_back(Script.str());
1417 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
1420 // On darwin, provide information about the .crash diagnostic report.
1421 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1422 SmallString<128> CrashDiagDir;
1423 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1424 Diag(clang::diag::note_drv_command_failed_diag_msg)
1425 << ReproCrashFilename.str();
1426 } else { // Suggest a directory for the user to look for .crash files.
1427 llvm::sys::path::append(CrashDiagDir, Name);
1428 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1429 Diag(clang::diag::note_drv_command_failed_diag_msg)
1430 << "Crash backtrace is located in";
1431 Diag(clang::diag::note_drv_command_failed_diag_msg)
1432 << CrashDiagDir.str();
1433 Diag(clang::diag::note_drv_command_failed_diag_msg)
1434 << "(choose the .crash file that corresponds to your crash)";
1438 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1439 options::OPT_frewrite_map_file_EQ))
1440 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1442 Diag(clang::diag::note_drv_command_failed_diag_msg)
1443 << "\n\n********************";
1446 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1447 // Since commandLineFitsWithinSystemLimits() may underestimate system's
1448 // capacity if the tool does not support response files, there is a chance/
1449 // that things will just work without a response file, so we silently just
1451 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
1452 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(),
1453 Cmd.getArguments()))
1456 std::string TmpName = GetTemporaryPath("response", "txt");
1457 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1460 int Driver::ExecuteCompilation(
1462 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1463 // Just print if -### was present.
1464 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1465 C.getJobs().Print(llvm::errs(), "\n", true);
1469 // If there were errors building the compilation, quit now.
1470 if (Diags.hasErrorOccurred())
1473 // Set up response file names for each command, if necessary
1474 for (auto &Job : C.getJobs())
1475 setUpResponseFiles(C, Job);
1477 C.ExecuteJobs(C.getJobs(), FailingCommands);
1479 // If the command succeeded, we are done.
1480 if (FailingCommands.empty())
1483 // Otherwise, remove result files and print extra information about abnormal
1486 for (const auto &CmdPair : FailingCommands) {
1487 int CommandRes = CmdPair.first;
1488 const Command *FailingCommand = CmdPair.second;
1490 // Remove result files if we're not saving temps.
1491 if (!isSaveTempsEnabled()) {
1492 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1493 C.CleanupFileMap(C.getResultFiles(), JA, true);
1495 // Failure result files are valid unless we crashed.
1497 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1501 // llvm/lib/Support/Unix/Signals.inc will exit with a special return code
1502 // for SIGPIPE. Do not print diagnostics for this case.
1503 if (CommandRes == EX_IOERR) {
1509 // Print extra information about abnormal failures, if possible.
1511 // This is ad-hoc, but we don't want to be excessively noisy. If the result
1512 // status was 1, assume the command failed normally. In particular, if it
1513 // was the compiler then assume it gave a reasonable error code. Failures
1514 // in other tools are less common, and they generally have worse
1515 // diagnostics, so always print the diagnostic there.
1516 const Tool &FailingTool = FailingCommand->getCreator();
1518 if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
1519 // FIXME: See FIXME above regarding result code interpretation.
1521 Diag(clang::diag::err_drv_command_signalled)
1522 << FailingTool.getShortName();
1524 Diag(clang::diag::err_drv_command_failed)
1525 << FailingTool.getShortName() << CommandRes;
1531 void Driver::PrintHelp(bool ShowHidden) const {
1532 unsigned IncludedFlagsBitmask;
1533 unsigned ExcludedFlagsBitmask;
1534 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1535 getIncludeExcludeOptionFlagMasks(IsCLMode());
1537 ExcludedFlagsBitmask |= options::NoDriverOption;
1539 ExcludedFlagsBitmask |= HelpHidden;
1541 std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1542 getOpts().PrintHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
1543 IncludedFlagsBitmask, ExcludedFlagsBitmask,
1544 /*ShowAllAliases=*/false);
1547 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1548 // FIXME: The following handlers should use a callback mechanism, we don't
1549 // know what the client would like to do.
1550 OS << getClangFullVersion() << '\n';
1551 const ToolChain &TC = C.getDefaultToolChain();
1552 OS << "Target: " << TC.getTripleString() << '\n';
1554 // Print the threading model.
1555 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1556 // Don't print if the ToolChain would have barfed on it already
1557 if (TC.isThreadModelSupported(A->getValue()))
1558 OS << "Thread model: " << A->getValue();
1560 OS << "Thread model: " << TC.getThreadModel();
1563 // Print out the install directory.
1564 OS << "InstalledDir: " << InstalledDir << '\n';
1566 // If configuration file was used, print its path.
1567 if (!ConfigFile.empty())
1568 OS << "Configuration file: " << ConfigFile << '\n';
1571 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1573 static void PrintDiagnosticCategories(raw_ostream &OS) {
1574 // Skip the empty category.
1575 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1577 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1580 void Driver::HandleAutocompletions(StringRef PassedFlags) const {
1581 if (PassedFlags == "")
1583 // Print out all options that start with a given argument. This is used for
1584 // shell autocompletion.
1585 std::vector<std::string> SuggestedCompletions;
1586 std::vector<std::string> Flags;
1588 unsigned short DisableFlags =
1589 options::NoDriverOption | options::Unsupported | options::Ignored;
1591 // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
1592 // because the latter indicates that the user put space before pushing tab
1593 // which should end up in a file completion.
1594 const bool HasSpace = PassedFlags.endswith(",");
1596 // Parse PassedFlags by "," as all the command-line flags are passed to this
1597 // function separated by ","
1598 StringRef TargetFlags = PassedFlags;
1599 while (TargetFlags != "") {
1601 std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1602 Flags.push_back(std::string(CurFlag));
1605 // We want to show cc1-only options only when clang is invoked with -cc1 or
1607 if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1"))
1608 DisableFlags &= ~options::NoDriverOption;
1610 const llvm::opt::OptTable &Opts = getOpts();
1612 Cur = Flags.at(Flags.size() - 1);
1614 if (Flags.size() >= 2) {
1615 Prev = Flags.at(Flags.size() - 2);
1616 SuggestedCompletions = Opts.suggestValueCompletions(Prev, Cur);
1619 if (SuggestedCompletions.empty())
1620 SuggestedCompletions = Opts.suggestValueCompletions(Cur, "");
1622 // If Flags were empty, it means the user typed `clang [tab]` where we should
1623 // list all possible flags. If there was no value completion and the user
1624 // pressed tab after a space, we should fall back to a file completion.
1625 // We're printing a newline to be consistent with what we print at the end of
1627 if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
1628 llvm::outs() << '\n';
1632 // When flag ends with '=' and there was no value completion, return empty
1633 // string and fall back to the file autocompletion.
1634 if (SuggestedCompletions.empty() && !Cur.endswith("=")) {
1635 // If the flag is in the form of "--autocomplete=-foo",
1636 // we were requested to print out all option names that start with "-foo".
1637 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
1638 SuggestedCompletions = Opts.findByPrefix(Cur, DisableFlags);
1640 // We have to query the -W flags manually as they're not in the OptTable.
1641 // TODO: Find a good way to add them to OptTable instead and them remove
1643 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
1644 if (S.startswith(Cur))
1645 SuggestedCompletions.push_back(S);
1648 // Sort the autocomplete candidates so that shells print them out in a
1649 // deterministic order. We could sort in any way, but we chose
1650 // case-insensitive sorting for consistency with the -help option
1651 // which prints out options in the case-insensitive alphabetical order.
1652 llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
1653 if (int X = A.compare_lower(B))
1655 return A.compare(B) > 0;
1658 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1661 bool Driver::HandleImmediateArgs(const Compilation &C) {
1662 // The order these options are handled in gcc is all over the place, but we
1663 // don't expect inconsistencies w.r.t. that to matter in practice.
1665 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1666 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1670 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
1671 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1672 // return an answer which matches our definition of __VERSION__.
1673 llvm::outs() << CLANG_VERSION_STRING << "\n";
1677 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1678 PrintDiagnosticCategories(llvm::outs());
1682 if (C.getArgs().hasArg(options::OPT_help) ||
1683 C.getArgs().hasArg(options::OPT__help_hidden)) {
1684 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
1688 if (C.getArgs().hasArg(options::OPT__version)) {
1689 // Follow gcc behavior and use stdout for --version and stderr for -v.
1690 PrintVersion(C, llvm::outs());
1694 if (C.getArgs().hasArg(options::OPT_v) ||
1695 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH) ||
1696 C.getArgs().hasArg(options::OPT_print_supported_cpus)) {
1697 PrintVersion(C, llvm::errs());
1698 SuppressMissingInputWarning = true;
1701 if (C.getArgs().hasArg(options::OPT_v)) {
1702 if (!SystemConfigDir.empty())
1703 llvm::errs() << "System configuration file directory: "
1704 << SystemConfigDir << "\n";
1705 if (!UserConfigDir.empty())
1706 llvm::errs() << "User configuration file directory: "
1707 << UserConfigDir << "\n";
1710 const ToolChain &TC = C.getDefaultToolChain();
1712 if (C.getArgs().hasArg(options::OPT_v))
1713 TC.printVerboseInfo(llvm::errs());
1715 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
1716 llvm::outs() << ResourceDir << '\n';
1720 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1721 llvm::outs() << "programs: =";
1722 bool separator = false;
1723 for (const std::string &Path : TC.getProgramPaths()) {
1725 llvm::outs() << llvm::sys::EnvPathSeparator;
1726 llvm::outs() << Path;
1729 llvm::outs() << "\n";
1730 llvm::outs() << "libraries: =" << ResourceDir;
1732 StringRef sysroot = C.getSysRoot();
1734 for (const std::string &Path : TC.getFilePaths()) {
1735 // Always print a separator. ResourceDir was the first item shown.
1736 llvm::outs() << llvm::sys::EnvPathSeparator;
1737 // Interpretation of leading '=' is needed only for NetBSD.
1739 llvm::outs() << sysroot << Path.substr(1);
1741 llvm::outs() << Path;
1743 llvm::outs() << "\n";
1747 // FIXME: The following handlers should use a callback mechanism, we don't
1748 // know what the client would like to do.
1749 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
1750 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
1754 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
1755 StringRef ProgName = A->getValue();
1757 // Null program name cannot have a path.
1758 if (! ProgName.empty())
1759 llvm::outs() << GetProgramPath(ProgName, TC);
1761 llvm::outs() << "\n";
1765 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
1766 StringRef PassedFlags = A->getValue();
1767 HandleAutocompletions(PassedFlags);
1771 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
1772 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1773 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1774 RegisterEffectiveTriple TripleRAII(TC, Triple);
1776 case ToolChain::RLT_CompilerRT:
1777 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1779 case ToolChain::RLT_Libgcc:
1780 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1786 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
1787 for (const Multilib &Multilib : TC.getMultilibs())
1788 llvm::outs() << Multilib << "\n";
1792 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
1793 const Multilib &Multilib = TC.getMultilib();
1794 if (Multilib.gccSuffix().empty())
1795 llvm::outs() << ".\n";
1797 StringRef Suffix(Multilib.gccSuffix());
1798 assert(Suffix.front() == '/');
1799 llvm::outs() << Suffix.substr(1) << "\n";
1804 if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
1805 llvm::outs() << TC.getTripleString() << "\n";
1809 if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
1810 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1811 llvm::outs() << Triple.getTriple() << "\n";
1824 // Display an action graph human-readably. Action A is the "sink" node
1825 // and latest-occuring action. Traversal is in pre-order, visiting the
1826 // inputs to each action before printing the action itself.
1827 static unsigned PrintActions1(const Compilation &C, Action *A,
1828 std::map<Action *, unsigned> &Ids,
1829 Twine Indent = {}, int Kind = TopLevelAction) {
1830 if (Ids.count(A)) // A was already visited.
1834 llvm::raw_string_ostream os(str);
1836 auto getSibIndent = [](int K) -> Twine {
1837 return (K == HeadSibAction) ? " " : (K == OtherSibAction) ? "| " : "";
1840 Twine SibIndent = Indent + getSibIndent(Kind);
1841 int SibKind = HeadSibAction;
1842 os << Action::getClassName(A->getKind()) << ", ";
1843 if (InputAction *IA = dyn_cast<InputAction>(A)) {
1844 os << "\"" << IA->getInputArg().getValue() << "\"";
1845 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1846 os << '"' << BIA->getArchName() << '"' << ", {"
1847 << PrintActions1(C, *BIA->input_begin(), Ids, SibIndent, SibKind) << "}";
1848 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1849 bool IsFirst = true;
1850 OA->doOnEachDependence(
1851 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1852 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1853 // sm_35 this will generate:
1854 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1855 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1860 os << A->getOffloadingKindPrefix();
1864 os << TC->getTriple().normalize();
1867 os << ":" << BoundArch;
1870 os << " {" << PrintActions1(C, A, Ids, SibIndent, SibKind) << "}";
1872 SibKind = OtherSibAction;
1875 const ActionList *AL = &A->getInputs();
1878 const char *Prefix = "{";
1879 for (Action *PreRequisite : *AL) {
1880 os << Prefix << PrintActions1(C, PreRequisite, Ids, SibIndent, SibKind);
1882 SibKind = OtherSibAction;
1889 // Append offload info for all options other than the offloading action
1890 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1891 std::string offload_str;
1892 llvm::raw_string_ostream offload_os(offload_str);
1893 if (!isa<OffloadAction>(A)) {
1894 auto S = A->getOffloadingKindPrefix();
1896 offload_os << ", (" << S;
1897 if (A->getOffloadingArch())
1898 offload_os << ", " << A->getOffloadingArch();
1903 auto getSelfIndent = [](int K) -> Twine {
1904 return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : "";
1907 unsigned Id = Ids.size();
1909 llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", "
1910 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1915 // Print the action graphs in a compilation C.
1916 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
1917 void Driver::PrintActions(const Compilation &C) const {
1918 std::map<Action *, unsigned> Ids;
1919 for (Action *A : C.getActions())
1920 PrintActions1(C, A, Ids);
1923 /// Check whether the given input tree contains any compilation or
1924 /// assembly actions.
1925 static bool ContainsCompileOrAssembleAction(const Action *A) {
1926 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1927 isa<AssembleJobAction>(A))
1930 for (const Action *Input : A->inputs())
1931 if (ContainsCompileOrAssembleAction(Input))
1937 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1938 const InputList &BAInputs) const {
1939 DerivedArgList &Args = C.getArgs();
1940 ActionList &Actions = C.getActions();
1941 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1942 // Collect the list of architectures. Duplicates are allowed, but should only
1943 // be handled once (in the order seen).
1944 llvm::StringSet<> ArchNames;
1945 SmallVector<const char *, 4> Archs;
1946 for (Arg *A : Args) {
1947 if (A->getOption().matches(options::OPT_arch)) {
1948 // Validate the option here; we don't save the type here because its
1949 // particular spelling may participate in other driver choices.
1950 llvm::Triple::ArchType Arch =
1951 tools::darwin::getArchTypeForMachOArchName(A->getValue());
1952 if (Arch == llvm::Triple::UnknownArch) {
1953 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1958 if (ArchNames.insert(A->getValue()).second)
1959 Archs.push_back(A->getValue());
1963 // When there is no explicit arch for this platform, make sure we still bind
1964 // the architecture (to the default) so that -Xarch_ is handled correctly.
1966 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1968 ActionList SingleActions;
1969 BuildActions(C, Args, BAInputs, SingleActions);
1971 // Add in arch bindings for every top level action, as well as lipo and
1972 // dsymutil steps if needed.
1973 for (Action* Act : SingleActions) {
1974 // Make sure we can lipo this kind of output. If not (and it is an actual
1975 // output) then we disallow, since we can't create an output file with the
1976 // right name without overwriting it. We could remove this oddity by just
1977 // changing the output names to include the arch, which would also fix
1978 // -save-temps. Compatibility wins for now.
1980 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1981 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1982 << types::getTypeName(Act->getType());
1985 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1986 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
1988 // Lipo if necessary, we do it this way because we need to set the arch flag
1989 // so that -Xarch_ gets overwritten.
1990 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1991 Actions.append(Inputs.begin(), Inputs.end());
1993 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
1995 // Handle debug info queries.
1996 Arg *A = Args.getLastArg(options::OPT_g_Group);
1997 bool enablesDebugInfo = A && !A->getOption().matches(options::OPT_g0) &&
1998 !A->getOption().matches(options::OPT_gstabs);
1999 if ((enablesDebugInfo || willEmitRemarks(Args)) &&
2000 ContainsCompileOrAssembleAction(Actions.back())) {
2002 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
2003 // have a compile input. We need to run 'dsymutil' ourselves in such cases
2004 // because the debug info will refer to a temporary object file which
2005 // will be removed at the end of the compilation process.
2006 if (Act->getType() == types::TY_Image) {
2008 Inputs.push_back(Actions.back());
2011 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
2014 // Verify the debug info output.
2015 if (Args.hasArg(options::OPT_verify_debug_info)) {
2016 Action* LastAction = Actions.back();
2018 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
2019 LastAction, types::TY_Nothing));
2025 bool Driver::DiagnoseInputExistence(const DerivedArgList &Args, StringRef Value,
2026 types::ID Ty, bool TypoCorrect) const {
2027 if (!getCheckInputsExist())
2030 // stdin always exists.
2034 if (getVFS().exists(Value))
2038 if (!llvm::sys::path::is_absolute(Twine(Value)) &&
2039 llvm::sys::Process::FindInEnvPath("LIB", Value))
2042 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
2043 // Arguments to the /link flag might cause the linker to search for object
2044 // and library files in paths we don't know about. Don't error in such
2051 // Check if the filename is a typo for an option flag. OptTable thinks
2052 // that all args that are not known options and that start with / are
2053 // filenames, but e.g. `/diagnostic:caret` is more likely a typo for
2054 // the option `/diagnostics:caret` than a reference to a file in the root
2056 unsigned IncludedFlagsBitmask;
2057 unsigned ExcludedFlagsBitmask;
2058 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
2059 getIncludeExcludeOptionFlagMasks(IsCLMode());
2060 std::string Nearest;
2061 if (getOpts().findNearest(Value, Nearest, IncludedFlagsBitmask,
2062 ExcludedFlagsBitmask) <= 1) {
2063 Diag(clang::diag::err_drv_no_such_file_with_suggestion)
2064 << Value << Nearest;
2069 Diag(clang::diag::err_drv_no_such_file) << Value;
2073 // Construct a the list of inputs and their types.
2074 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
2075 InputList &Inputs) const {
2076 const llvm::opt::OptTable &Opts = getOpts();
2077 // Track the current user specified (-x) input. We also explicitly track the
2078 // argument used to set the type; we only want to claim the type when we
2079 // actually use it, so we warn about unused -x arguments.
2080 types::ID InputType = types::TY_Nothing;
2081 Arg *InputTypeArg = nullptr;
2083 // The last /TC or /TP option sets the input type to C or C++ globally.
2084 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
2085 options::OPT__SLASH_TP)) {
2086 InputTypeArg = TCTP;
2087 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
2091 Arg *Previous = nullptr;
2092 bool ShowNote = false;
2094 Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
2096 Diag(clang::diag::warn_drv_overriding_flag_option)
2097 << Previous->getSpelling() << A->getSpelling();
2103 Diag(clang::diag::note_drv_t_option_is_global);
2105 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
2106 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
2109 for (Arg *A : Args) {
2110 if (A->getOption().getKind() == Option::InputClass) {
2111 const char *Value = A->getValue();
2112 types::ID Ty = types::TY_INVALID;
2114 // Infer the input type if necessary.
2115 if (InputType == types::TY_Nothing) {
2116 // If there was an explicit arg for this, claim it.
2118 InputTypeArg->claim();
2120 // stdin must be handled specially.
2121 if (memcmp(Value, "-", 2) == 0) {
2122 // If running with -E, treat as a C input (this changes the builtin
2123 // macros, for example). This may be overridden by -ObjC below.
2125 // Otherwise emit an error but still use a valid type to avoid
2126 // spurious errors (e.g., no inputs).
2127 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
2128 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2129 : clang::diag::err_drv_unknown_stdin_type);
2132 // Otherwise lookup by extension.
2133 // Fallback is C if invoked as C preprocessor, C++ if invoked with
2134 // clang-cl /E, or Object otherwise.
2135 // We use a host hook here because Darwin at least has its own
2136 // idea of what .s is.
2137 if (const char *Ext = strrchr(Value, '.'))
2138 Ty = TC.LookupTypeForExtension(Ext + 1);
2140 if (Ty == types::TY_INVALID) {
2143 else if (IsCLMode() && Args.hasArgNoClaim(options::OPT_E))
2146 Ty = types::TY_Object;
2149 // If the driver is invoked as C++ compiler (like clang++ or c++) it
2150 // should autodetect some input files as C++ for g++ compatibility.
2152 types::ID OldTy = Ty;
2153 Ty = types::lookupCXXTypeForCType(Ty);
2156 Diag(clang::diag::warn_drv_treating_input_as_cxx)
2157 << getTypeName(OldTy) << getTypeName(Ty);
2160 // If running with -fthinlto-index=, extensions that normally identify
2161 // native object files actually identify LLVM bitcode files.
2162 if (Args.hasArgNoClaim(options::OPT_fthinlto_index_EQ) &&
2163 Ty == types::TY_Object)
2164 Ty = types::TY_LLVM_BC;
2167 // -ObjC and -ObjC++ override the default language, but only for "source
2168 // files". We just treat everything that isn't a linker input as a
2171 // FIXME: Clean this up if we move the phase sequence into the type.
2172 if (Ty != types::TY_Object) {
2173 if (Args.hasArg(options::OPT_ObjC))
2174 Ty = types::TY_ObjC;
2175 else if (Args.hasArg(options::OPT_ObjCXX))
2176 Ty = types::TY_ObjCXX;
2179 assert(InputTypeArg && "InputType set w/o InputTypeArg");
2180 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2181 // If emulating cl.exe, make sure that /TC and /TP don't affect input
2183 const char *Ext = strrchr(Value, '.');
2184 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2185 Ty = types::TY_Object;
2187 if (Ty == types::TY_INVALID) {
2189 InputTypeArg->claim();
2193 if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true))
2194 Inputs.push_back(std::make_pair(Ty, A));
2196 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2197 StringRef Value = A->getValue();
2198 if (DiagnoseInputExistence(Args, Value, types::TY_C,
2199 /*TypoCorrect=*/false)) {
2200 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2201 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2204 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2205 StringRef Value = A->getValue();
2206 if (DiagnoseInputExistence(Args, Value, types::TY_CXX,
2207 /*TypoCorrect=*/false)) {
2208 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2209 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2212 } else if (A->getOption().hasFlag(options::LinkerInput)) {
2213 // Just treat as object type, we could make a special type for this if
2215 Inputs.push_back(std::make_pair(types::TY_Object, A));
2217 } else if (A->getOption().matches(options::OPT_x)) {
2219 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
2222 // Follow gcc behavior and treat as linker input for invalid -x
2223 // options. Its not clear why we shouldn't just revert to unknown; but
2224 // this isn't very important, we might as well be bug compatible.
2226 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
2227 InputType = types::TY_Object;
2229 } else if (A->getOption().getID() == options::OPT_U) {
2230 assert(A->getNumValues() == 1 && "The /U option has one value.");
2231 StringRef Val = A->getValue(0);
2232 if (Val.find_first_of("/\\") != StringRef::npos) {
2233 // Warn about e.g. "/Users/me/myfile.c".
2234 Diag(diag::warn_slash_u_filename) << Val;
2235 Diag(diag::note_use_dashdash);
2239 if (CCCIsCPP() && Inputs.empty()) {
2240 // If called as standalone preprocessor, stdin is processed
2241 // if no other input is present.
2242 Arg *A = MakeInputArg(Args, Opts, "-");
2243 Inputs.push_back(std::make_pair(types::TY_C, A));
2248 /// Provides a convenient interface for different programming models to generate
2249 /// the required device actions.
2250 class OffloadingActionBuilder final {
2251 /// Flag used to trace errors in the builder.
2252 bool IsValid = false;
2254 /// The compilation that is using this builder.
2257 /// Map between an input argument and the offload kinds used to process it.
2258 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2260 /// Builder interface. It doesn't build anything or keep any state.
2261 class DeviceActionBuilder {
2263 typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy;
2265 enum ActionBuilderReturnCode {
2266 // The builder acted successfully on the current action.
2268 // The builder didn't have to act on the current action.
2270 // The builder was successful and requested the host action to not be
2276 /// Compilation associated with this builder.
2279 /// Tool chains associated with this builder. The same programming
2280 /// model may have associated one or more tool chains.
2281 SmallVector<const ToolChain *, 2> ToolChains;
2283 /// The derived arguments associated with this builder.
2284 DerivedArgList &Args;
2286 /// The inputs associated with this builder.
2287 const Driver::InputList &Inputs;
2289 /// The associated offload kind.
2290 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2293 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2294 const Driver::InputList &Inputs,
2295 Action::OffloadKind AssociatedOffloadKind)
2296 : C(C), Args(Args), Inputs(Inputs),
2297 AssociatedOffloadKind(AssociatedOffloadKind) {}
2298 virtual ~DeviceActionBuilder() {}
2300 /// Fill up the array \a DA with all the device dependences that should be
2301 /// added to the provided host action \a HostAction. By default it is
2303 virtual ActionBuilderReturnCode
2304 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2305 phases::ID CurPhase, phases::ID FinalPhase,
2307 return ABRT_Inactive;
2310 /// Update the state to include the provided host action \a HostAction as a
2311 /// dependency of the current device action. By default it is inactive.
2312 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2313 return ABRT_Inactive;
2316 /// Append top level actions generated by the builder.
2317 virtual void appendTopLevelActions(ActionList &AL) {}
2319 /// Append linker actions generated by the builder.
2320 virtual void appendLinkActions(ActionList &AL) {}
2322 /// Append linker actions generated by the builder.
2323 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2325 /// Initialize the builder. Return true if any initialization errors are
2327 virtual bool initialize() { return false; }
2329 /// Return true if the builder can use bundling/unbundling.
2330 virtual bool canUseBundlerUnbundler() const { return false; }
2332 /// Return true if this builder is valid. We have a valid builder if we have
2333 /// associated device tool chains.
2334 bool isValid() { return !ToolChains.empty(); }
2336 /// Return the associated offload kind.
2337 Action::OffloadKind getAssociatedOffloadKind() {
2338 return AssociatedOffloadKind;
2342 /// Base class for CUDA/HIP action builder. It injects device code in
2343 /// the host backend action.
2344 class CudaActionBuilderBase : public DeviceActionBuilder {
2346 /// Flags to signal if the user requested host-only or device-only
2348 bool CompileHostOnly = false;
2349 bool CompileDeviceOnly = false;
2350 bool EmitLLVM = false;
2351 bool EmitAsm = false;
2353 /// List of GPU architectures to use in this compilation.
2354 SmallVector<CudaArch, 4> GpuArchList;
2356 /// The CUDA actions for the current input.
2357 ActionList CudaDeviceActions;
2359 /// The CUDA fat binary if it was generated for the current input.
2360 Action *CudaFatBinary = nullptr;
2362 /// Flag that is set to true if this builder acted on the current input.
2363 bool IsActive = false;
2365 /// Flag for -fgpu-rdc.
2366 bool Relocatable = false;
2368 /// Default GPU architecture if there's no one specified.
2369 CudaArch DefaultCudaArch = CudaArch::UNKNOWN;
2372 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2373 const Driver::InputList &Inputs,
2374 Action::OffloadKind OFKind)
2375 : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
2377 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2378 // While generating code for CUDA, we only depend on the host input action
2379 // to trigger the creation of all the CUDA device actions.
2381 // If we are dealing with an input action, replicate it for each GPU
2382 // architecture. If we are in host-only mode we return 'success' so that
2383 // the host uses the CUDA offload kind.
2384 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2385 assert(!GpuArchList.empty() &&
2386 "We should have at least one GPU architecture.");
2388 // If the host input is not CUDA or HIP, we don't need to bother about
2390 if (IA->getType() != types::TY_CUDA &&
2391 IA->getType() != types::TY_HIP) {
2392 // The builder will ignore this input.
2394 return ABRT_Inactive;
2397 // Set the flag to true, so that the builder acts on the current input.
2400 if (CompileHostOnly)
2401 return ABRT_Success;
2403 // Replicate inputs for each GPU architecture.
2404 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2405 : types::TY_CUDA_DEVICE;
2406 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2407 CudaDeviceActions.push_back(
2408 C.MakeAction<InputAction>(IA->getInputArg(), Ty));
2411 return ABRT_Success;
2414 // If this is an unbundling action use it as is for each CUDA toolchain.
2415 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2417 // If -fgpu-rdc is disabled, should not unbundle since there is no
2418 // device code to link.
2420 return ABRT_Inactive;
2422 CudaDeviceActions.clear();
2423 auto *IA = cast<InputAction>(UA->getInputs().back());
2424 std::string FileName = IA->getInputArg().getAsString(Args);
2425 // Check if the type of the file is the same as the action. Do not
2426 // unbundle it if it is not. Do not unbundle .so files, for example,
2427 // which are not object files.
2428 if (IA->getType() == types::TY_Object &&
2429 (!llvm::sys::path::has_extension(FileName) ||
2430 types::lookupTypeForExtension(
2431 llvm::sys::path::extension(FileName).drop_front()) !=
2433 return ABRT_Inactive;
2435 for (auto Arch : GpuArchList) {
2436 CudaDeviceActions.push_back(UA);
2437 UA->registerDependentActionInfo(ToolChains[0], CudaArchToString(Arch),
2438 AssociatedOffloadKind);
2440 return ABRT_Success;
2443 return IsActive ? ABRT_Success : ABRT_Inactive;
2446 void appendTopLevelActions(ActionList &AL) override {
2447 // Utility to append actions to the top level list.
2448 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
2449 OffloadAction::DeviceDependences Dep;
2450 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
2451 AssociatedOffloadKind);
2452 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2455 // If we have a fat binary, add it to the list.
2456 if (CudaFatBinary) {
2457 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
2458 CudaDeviceActions.clear();
2459 CudaFatBinary = nullptr;
2463 if (CudaDeviceActions.empty())
2466 // If we have CUDA actions at this point, that's because we have a have
2467 // partial compilation, so we should have an action for each GPU
2469 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2470 "Expecting one action per GPU architecture.");
2471 assert(ToolChains.size() == 1 &&
2472 "Expecting to have a sing CUDA toolchain.");
2473 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2474 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2476 CudaDeviceActions.clear();
2479 bool initialize() override {
2480 assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2481 AssociatedOffloadKind == Action::OFK_HIP);
2483 // We don't need to support CUDA.
2484 if (AssociatedOffloadKind == Action::OFK_Cuda &&
2485 !C.hasOffloadToolChain<Action::OFK_Cuda>())
2488 // We don't need to support HIP.
2489 if (AssociatedOffloadKind == Action::OFK_HIP &&
2490 !C.hasOffloadToolChain<Action::OFK_HIP>())
2493 Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2494 options::OPT_fno_gpu_rdc, /*Default=*/false);
2496 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2497 assert(HostTC && "No toolchain for host compilation.");
2498 if (HostTC->getTriple().isNVPTX() ||
2499 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2500 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
2501 // an error and abort pipeline construction early so we don't trip
2502 // asserts that assume device-side compilation.
2503 C.getDriver().Diag(diag::err_drv_cuda_host_arch)
2504 << HostTC->getTriple().getArchName();
2508 ToolChains.push_back(
2509 AssociatedOffloadKind == Action::OFK_Cuda
2510 ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2511 : C.getSingleOffloadToolChain<Action::OFK_HIP>());
2513 Arg *PartialCompilationArg = Args.getLastArg(
2514 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2515 options::OPT_cuda_compile_host_device);
2516 CompileHostOnly = PartialCompilationArg &&
2517 PartialCompilationArg->getOption().matches(
2518 options::OPT_cuda_host_only);
2519 CompileDeviceOnly = PartialCompilationArg &&
2520 PartialCompilationArg->getOption().matches(
2521 options::OPT_cuda_device_only);
2522 EmitLLVM = Args.getLastArg(options::OPT_emit_llvm);
2523 EmitAsm = Args.getLastArg(options::OPT_S);
2525 // Collect all cuda_gpu_arch parameters, removing duplicates.
2526 std::set<CudaArch> GpuArchs;
2528 for (Arg *A : Args) {
2529 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2530 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
2534 const StringRef ArchStr = A->getValue();
2535 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2540 CudaArch Arch = StringToCudaArch(ArchStr);
2541 if (Arch == CudaArch::UNKNOWN) {
2542 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2544 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2545 GpuArchs.insert(Arch);
2546 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2547 GpuArchs.erase(Arch);
2549 llvm_unreachable("Unexpected option.");
2552 // Collect list of GPUs remaining in the set.
2553 for (CudaArch Arch : GpuArchs)
2554 GpuArchList.push_back(Arch);
2556 // Default to sm_20 which is the lowest common denominator for
2557 // supported GPUs. sm_20 code should work correctly, if
2558 // suboptimally, on all newer GPUs.
2559 if (GpuArchList.empty())
2560 GpuArchList.push_back(DefaultCudaArch);
2566 /// \brief CUDA action builder. It injects device code in the host backend
2568 class CudaActionBuilder final : public CudaActionBuilderBase {
2570 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2571 const Driver::InputList &Inputs)
2572 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {
2573 DefaultCudaArch = CudaArch::SM_20;
2576 ActionBuilderReturnCode
2577 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2578 phases::ID CurPhase, phases::ID FinalPhase,
2579 PhasesTy &Phases) override {
2581 return ABRT_Inactive;
2583 // If we don't have more CUDA actions, we don't have any dependences to
2584 // create for the host.
2585 if (CudaDeviceActions.empty())
2586 return ABRT_Success;
2588 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2589 "Expecting one action per GPU architecture.");
2590 assert(!CompileHostOnly &&
2591 "Not expecting CUDA actions in host-only compilation.");
2593 // If we are generating code for the device or we are in a backend phase,
2594 // we attempt to generate the fat binary. We compile each arch to ptx and
2595 // assemble to cubin, then feed the cubin *and* the ptx into a device
2596 // "link" action, which uses fatbinary to combine these cubins into one
2597 // fatbin. The fatbin is then an input to the host action if not in
2598 // device-only mode.
2599 if (CompileDeviceOnly || CurPhase == phases::Backend) {
2600 ActionList DeviceActions;
2601 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2602 // Produce the device action from the current phase up to the assemble
2604 for (auto Ph : Phases) {
2605 // Skip the phases that were already dealt with.
2608 // We have to be consistent with the host final phase.
2609 if (Ph > FinalPhase)
2612 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
2613 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
2615 if (Ph == phases::Assemble)
2619 // If we didn't reach the assemble phase, we can't generate the fat
2620 // binary. We don't need to generate the fat binary if we are not in
2621 // device-only mode.
2622 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2626 Action *AssembleAction = CudaDeviceActions[I];
2627 assert(AssembleAction->getType() == types::TY_Object);
2628 assert(AssembleAction->getInputs().size() == 1);
2630 Action *BackendAction = AssembleAction->getInputs()[0];
2631 assert(BackendAction->getType() == types::TY_PP_Asm);
2633 for (auto &A : {AssembleAction, BackendAction}) {
2634 OffloadAction::DeviceDependences DDep;
2635 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
2637 DeviceActions.push_back(
2638 C.MakeAction<OffloadAction>(DDep, A->getType()));
2642 // We generate the fat binary if we have device input actions.
2643 if (!DeviceActions.empty()) {
2645 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2647 if (!CompileDeviceOnly) {
2648 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2650 // Clear the fat binary, it is already a dependence to an host
2652 CudaFatBinary = nullptr;
2655 // Remove the CUDA actions as they are already connected to an host
2656 // action or fat binary.
2657 CudaDeviceActions.clear();
2660 // We avoid creating host action in device-only mode.
2661 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
2662 } else if (CurPhase > phases::Backend) {
2663 // If we are past the backend phase and still have a device action, we
2664 // don't have to do anything as this action is already a device
2665 // top-level action.
2666 return ABRT_Success;
2669 assert(CurPhase < phases::Backend && "Generating single CUDA "
2670 "instructions should only occur "
2671 "before the backend phase!");
2673 // By default, we produce an action for each device arch.
2674 for (Action *&A : CudaDeviceActions)
2675 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2677 return ABRT_Success;
2680 /// \brief HIP action builder. It injects device code in the host backend
2682 class HIPActionBuilder final : public CudaActionBuilderBase {
2683 /// The linker inputs obtained for each device arch.
2684 SmallVector<ActionList, 8> DeviceLinkerInputs;
2687 HIPActionBuilder(Compilation &C, DerivedArgList &Args,
2688 const Driver::InputList &Inputs)
2689 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {
2690 DefaultCudaArch = CudaArch::GFX803;
2693 bool canUseBundlerUnbundler() const override { return true; }
2695 ActionBuilderReturnCode
2696 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2697 phases::ID CurPhase, phases::ID FinalPhase,
2698 PhasesTy &Phases) override {
2699 // amdgcn does not support linking of object files, therefore we skip
2700 // backend and assemble phases to output LLVM IR. Except for generating
2701 // non-relocatable device coee, where we generate fat binary for device
2702 // code and pass to host in Backend phase.
2703 if (CudaDeviceActions.empty() ||
2704 (CurPhase == phases::Backend && Relocatable) ||
2705 CurPhase == phases::Assemble)
2706 return ABRT_Success;
2708 assert(((CurPhase == phases::Link && Relocatable) ||
2709 CudaDeviceActions.size() == GpuArchList.size()) &&
2710 "Expecting one action per GPU architecture.");
2711 assert(!CompileHostOnly &&
2712 "Not expecting CUDA actions in host-only compilation.");
2714 if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM &&
2716 // If we are in backend phase, we attempt to generate the fat binary.
2717 // We compile each arch to IR and use a link action to generate code
2718 // object containing ISA. Then we use a special "link" action to create
2719 // a fat binary containing all the code objects for different GPU's.
2720 // The fat binary is then an input to the host action.
2721 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2722 // Create a link action to link device IR with device library
2723 // and generate ISA.
2725 AL.push_back(CudaDeviceActions[I]);
2726 CudaDeviceActions[I] =
2727 C.MakeAction<LinkJobAction>(AL, types::TY_Image);
2729 // OffloadingActionBuilder propagates device arch until an offload
2730 // action. Since the next action for creating fatbin does
2731 // not have device arch, whereas the above link action and its input
2732 // have device arch, an offload action is needed to stop the null
2733 // device arch of the next action being propagated to the above link
2735 OffloadAction::DeviceDependences DDep;
2736 DDep.add(*CudaDeviceActions[I], *ToolChains.front(),
2737 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2738 CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
2739 DDep, CudaDeviceActions[I]->getType());
2741 // Create HIP fat binary with a special "link" action.
2743 C.MakeAction<LinkJobAction>(CudaDeviceActions,
2744 types::TY_HIP_FATBIN);
2746 if (!CompileDeviceOnly) {
2747 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2748 AssociatedOffloadKind);
2749 // Clear the fat binary, it is already a dependence to an host
2751 CudaFatBinary = nullptr;
2754 // Remove the CUDA actions as they are already connected to an host
2755 // action or fat binary.
2756 CudaDeviceActions.clear();
2758 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
2759 } else if (CurPhase == phases::Link) {
2760 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
2761 // This happens to each device action originated from each input file.
2762 // Later on, device actions in DeviceLinkerInputs are used to create
2763 // device link actions in appendLinkDependences and the created device
2764 // link actions are passed to the offload action as device dependence.
2765 DeviceLinkerInputs.resize(CudaDeviceActions.size());
2766 auto LI = DeviceLinkerInputs.begin();
2767 for (auto *A : CudaDeviceActions) {
2772 // We will pass the device action as a host dependence, so we don't
2773 // need to do anything else with them.
2774 CudaDeviceActions.clear();
2775 return ABRT_Success;
2778 // By default, we produce an action for each device arch.
2779 for (Action *&A : CudaDeviceActions)
2780 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
2781 AssociatedOffloadKind);
2783 return (CompileDeviceOnly && CurPhase == FinalPhase) ? ABRT_Ignore_Host
2787 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2788 // Append a new link action for each device.
2790 for (auto &LI : DeviceLinkerInputs) {
2791 auto *DeviceLinkAction =
2792 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2793 DA.add(*DeviceLinkAction, *ToolChains[0],
2794 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2800 /// OpenMP action builder. The host bitcode is passed to the device frontend
2801 /// and all the device linked images are passed to the host link phase.
2802 class OpenMPActionBuilder final : public DeviceActionBuilder {
2803 /// The OpenMP actions for the current input.
2804 ActionList OpenMPDeviceActions;
2806 /// The linker inputs obtained for each toolchain.
2807 SmallVector<ActionList, 8> DeviceLinkerInputs;
2810 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2811 const Driver::InputList &Inputs)
2812 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2814 ActionBuilderReturnCode
2815 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2816 phases::ID CurPhase, phases::ID FinalPhase,
2817 PhasesTy &Phases) override {
2818 if (OpenMPDeviceActions.empty())
2819 return ABRT_Inactive;
2821 // We should always have an action for each input.
2822 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2823 "Number of OpenMP actions and toolchains do not match.");
2825 // The host only depends on device action in the linking phase, when all
2826 // the device images have to be embedded in the host image.
2827 if (CurPhase == phases::Link) {
2828 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2829 "Toolchains and linker inputs sizes do not match.");
2830 auto LI = DeviceLinkerInputs.begin();
2831 for (auto *A : OpenMPDeviceActions) {
2836 // We passed the device action as a host dependence, so we don't need to
2837 // do anything else with them.
2838 OpenMPDeviceActions.clear();
2839 return ABRT_Success;
2842 // By default, we produce an action for each device arch.
2843 for (Action *&A : OpenMPDeviceActions)
2844 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2846 return ABRT_Success;
2849 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2851 // If this is an input action replicate it for each OpenMP toolchain.
2852 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2853 OpenMPDeviceActions.clear();
2854 for (unsigned I = 0; I < ToolChains.size(); ++I)
2855 OpenMPDeviceActions.push_back(
2856 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2857 return ABRT_Success;
2860 // If this is an unbundling action use it as is for each OpenMP toolchain.
2861 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2862 OpenMPDeviceActions.clear();
2863 auto *IA = cast<InputAction>(UA->getInputs().back());
2864 std::string FileName = IA->getInputArg().getAsString(Args);
2865 // Check if the type of the file is the same as the action. Do not
2866 // unbundle it if it is not. Do not unbundle .so files, for example,
2867 // which are not object files.
2868 if (IA->getType() == types::TY_Object &&
2869 (!llvm::sys::path::has_extension(FileName) ||
2870 types::lookupTypeForExtension(
2871 llvm::sys::path::extension(FileName).drop_front()) !=
2873 return ABRT_Inactive;
2874 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2875 OpenMPDeviceActions.push_back(UA);
2876 UA->registerDependentActionInfo(
2877 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2879 return ABRT_Success;
2882 // When generating code for OpenMP we use the host compile phase result as
2883 // a dependence to the device compile phase so that it can learn what
2884 // declarations should be emitted. However, this is not the only use for
2885 // the host action, so we prevent it from being collapsed.
2886 if (isa<CompileJobAction>(HostAction)) {
2887 HostAction->setCannotBeCollapsedWithNextDependentAction();
2888 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2889 "Toolchains and device action sizes do not match.");
2890 OffloadAction::HostDependence HDep(
2891 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2892 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2893 auto TC = ToolChains.begin();
2894 for (Action *&A : OpenMPDeviceActions) {
2895 assert(isa<CompileJobAction>(A));
2896 OffloadAction::DeviceDependences DDep;
2897 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2898 A = C.MakeAction<OffloadAction>(HDep, DDep);
2902 return ABRT_Success;
2905 void appendTopLevelActions(ActionList &AL) override {
2906 if (OpenMPDeviceActions.empty())
2909 // We should always have an action for each input.
2910 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2911 "Number of OpenMP actions and toolchains do not match.");
2913 // Append all device actions followed by the proper offload action.
2914 auto TI = ToolChains.begin();
2915 for (auto *A : OpenMPDeviceActions) {
2916 OffloadAction::DeviceDependences Dep;
2917 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2918 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2921 // We no longer need the action stored in this builder.
2922 OpenMPDeviceActions.clear();
2925 void appendLinkActions(ActionList &AL) override {
2926 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2927 "Toolchains and linker inputs sizes do not match.");
2929 // Append a new link action for each device.
2930 auto TC = ToolChains.begin();
2931 for (auto &LI : DeviceLinkerInputs) {
2932 auto *DeviceLinkAction =
2933 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2934 OffloadAction::DeviceDependences DeviceLinkDeps;
2935 DeviceLinkDeps.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2936 Action::OFK_OpenMP);
2937 AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps,
2938 DeviceLinkAction->getType()));
2941 DeviceLinkerInputs.clear();
2944 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
2946 bool initialize() override {
2947 // Get the OpenMP toolchains. If we don't get any, the action builder will
2948 // know there is nothing to do related to OpenMP offloading.
2949 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2950 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2952 ToolChains.push_back(TI->second);
2954 DeviceLinkerInputs.resize(ToolChains.size());
2958 bool canUseBundlerUnbundler() const override {
2959 // OpenMP should use bundled files whenever possible.
2965 /// TODO: Add the implementation for other specialized builders here.
2968 /// Specialized builders being used by this offloading action builder.
2969 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2971 /// Flag set to true if all valid builders allow file bundling/unbundling.
2975 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2976 const Driver::InputList &Inputs)
2978 // Create a specialized builder for each device toolchain.
2982 // Create a specialized builder for CUDA.
2983 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2985 // Create a specialized builder for HIP.
2986 SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
2988 // Create a specialized builder for OpenMP.
2989 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2992 // TODO: Build other specialized builders here.
2995 // Initialize all the builders, keeping track of errors. If all valid
2996 // builders agree that we can use bundling, set the flag to true.
2997 unsigned ValidBuilders = 0u;
2998 unsigned ValidBuildersSupportingBundling = 0u;
2999 for (auto *SB : SpecializedBuilders) {
3000 IsValid = IsValid && !SB->initialize();
3002 // Update the counters if the builder is valid.
3003 if (SB->isValid()) {
3005 if (SB->canUseBundlerUnbundler())
3006 ++ValidBuildersSupportingBundling;
3010 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
3013 ~OffloadingActionBuilder() {
3014 for (auto *SB : SpecializedBuilders)
3018 /// Generate an action that adds device dependences (if any) to a host action.
3019 /// If no device dependence actions exist, just return the host action \a
3020 /// HostAction. If an error is found or if no builder requires the host action
3021 /// to be generated, return nullptr.
3023 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
3024 phases::ID CurPhase, phases::ID FinalPhase,
3025 DeviceActionBuilder::PhasesTy &Phases) {
3029 if (SpecializedBuilders.empty())
3032 assert(HostAction && "Invalid host action!");
3034 OffloadAction::DeviceDependences DDeps;
3035 // Check if all the programming models agree we should not emit the host
3036 // action. Also, keep track of the offloading kinds employed.
3037 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3038 unsigned InactiveBuilders = 0u;
3039 unsigned IgnoringBuilders = 0u;
3040 for (auto *SB : SpecializedBuilders) {
3041 if (!SB->isValid()) {
3047 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
3049 // If the builder explicitly says the host action should be ignored,
3050 // we need to increment the variable that tracks the builders that request
3051 // the host object to be ignored.
3052 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
3055 // Unless the builder was inactive for this action, we have to record the
3056 // offload kind because the host will have to use it.
3057 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3058 OffloadKind |= SB->getAssociatedOffloadKind();
3061 // If all builders agree that the host object should be ignored, just return
3063 if (IgnoringBuilders &&
3064 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
3067 if (DDeps.getActions().empty())
3070 // We have dependences we need to bundle together. We use an offload action
3072 OffloadAction::HostDependence HDep(
3073 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3074 /*BoundArch=*/nullptr, DDeps);
3075 return C.MakeAction<OffloadAction>(HDep, DDeps);
3078 /// Generate an action that adds a host dependence to a device action. The
3079 /// results will be kept in this action builder. Return true if an error was
3081 bool addHostDependenceToDeviceActions(Action *&HostAction,
3082 const Arg *InputArg) {
3086 // If we are supporting bundling/unbundling and the current action is an
3087 // input action of non-source file, we replace the host action by the
3088 // unbundling action. The bundler tool has the logic to detect if an input
3089 // is a bundle or not and if the input is not a bundle it assumes it is a
3090 // host file. Therefore it is safe to create an unbundling action even if
3091 // the input is not a bundle.
3092 if (CanUseBundler && isa<InputAction>(HostAction) &&
3093 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
3094 !types::isSrcFile(HostAction->getType())) {
3095 auto UnbundlingHostAction =
3096 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
3097 UnbundlingHostAction->registerDependentActionInfo(
3098 C.getSingleOffloadToolChain<Action::OFK_Host>(),
3099 /*BoundArch=*/StringRef(), Action::OFK_Host);
3100 HostAction = UnbundlingHostAction;
3103 assert(HostAction && "Invalid host action!");
3105 // Register the offload kinds that are used.
3106 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3107 for (auto *SB : SpecializedBuilders) {
3111 auto RetCode = SB->addDeviceDepences(HostAction);
3113 // Host dependences for device actions are not compatible with that same
3114 // action being ignored.
3115 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
3116 "Host dependence not expected to be ignored.!");
3118 // Unless the builder was inactive for this action, we have to record the
3119 // offload kind because the host will have to use it.
3120 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3121 OffloadKind |= SB->getAssociatedOffloadKind();
3124 // Do not use unbundler if the Host does not depend on device action.
3125 if (OffloadKind == Action::OFK_None && CanUseBundler)
3126 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3127 HostAction = UA->getInputs().back();
3132 /// Add the offloading top level actions to the provided action list. This
3133 /// function can replace the host action by a bundling action if the
3134 /// programming models allow it.
3135 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3136 const Arg *InputArg) {
3137 // Get the device actions to be appended.
3138 ActionList OffloadAL;
3139 for (auto *SB : SpecializedBuilders) {
3142 SB->appendTopLevelActions(OffloadAL);
3145 // If we can use the bundler, replace the host action by the bundling one in
3146 // the resulting list. Otherwise, just append the device actions. For
3147 // device only compilation, HostAction is a null pointer, therefore only do
3148 // this when HostAction is not a null pointer.
3149 if (CanUseBundler && HostAction &&
3150 HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) {
3151 // Add the host action to the list in order to create the bundling action.
3152 OffloadAL.push_back(HostAction);
3154 // We expect that the host action was just appended to the action list
3155 // before this method was called.
3156 assert(HostAction == AL.back() && "Host action not in the list??");
3157 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3158 AL.back() = HostAction;
3160 AL.append(OffloadAL.begin(), OffloadAL.end());
3162 // Propagate to the current host action (if any) the offload information
3163 // associated with the current input.
3165 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3166 /*BoundArch=*/nullptr);
3170 Action* makeHostLinkAction() {
3171 // Build a list of device linking actions.
3172 ActionList DeviceAL;
3173 for (DeviceActionBuilder *SB : SpecializedBuilders) {
3176 SB->appendLinkActions(DeviceAL);
3179 if (DeviceAL.empty())
3182 // Create wrapper bitcode from the result of device link actions and compile
3183 // it to an object which will be added to the host link command.
3184 auto *BC = C.MakeAction<OffloadWrapperJobAction>(DeviceAL, types::TY_LLVM_BC);
3185 auto *ASM = C.MakeAction<BackendJobAction>(BC, types::TY_PP_Asm);
3186 return C.MakeAction<AssembleJobAction>(ASM, types::TY_Object);
3189 /// Processes the host linker action. This currently consists of replacing it
3190 /// with an offload action if there are device link objects and propagate to
3191 /// the host action all the offload kinds used in the current compilation. The
3192 /// resulting action is returned.
3193 Action *processHostLinkAction(Action *HostAction) {
3194 // Add all the dependences from the device linking actions.
3195 OffloadAction::DeviceDependences DDeps;
3196 for (auto *SB : SpecializedBuilders) {
3200 SB->appendLinkDependences(DDeps);
3203 // Calculate all the offload kinds used in the current compilation.
3204 unsigned ActiveOffloadKinds = 0u;
3205 for (auto &I : InputArgToOffloadKindMap)
3206 ActiveOffloadKinds |= I.second;
3208 // If we don't have device dependencies, we don't have to create an offload
3210 if (DDeps.getActions().empty()) {
3211 // Propagate all the active kinds to host action. Given that it is a link
3212 // action it is assumed to depend on all actions generated so far.
3213 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
3214 /*BoundArch=*/nullptr);
3218 // Create the offload action with all dependences. When an offload action
3219 // is created the kinds are propagated to the host action, so we don't have
3220 // to do that explicitly here.
3221 OffloadAction::HostDependence HDep(
3222 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3223 /*BoundArch*/ nullptr, ActiveOffloadKinds);
3224 return C.MakeAction<OffloadAction>(HDep, DDeps);
3227 } // anonymous namespace.
3229 void Driver::handleArguments(Compilation &C, DerivedArgList &Args,
3230 const InputList &Inputs,
3231 ActionList &Actions) const {
3233 // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
3234 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3235 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
3236 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3237 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3238 Args.eraseArg(options::OPT__SLASH_Yc);
3239 Args.eraseArg(options::OPT__SLASH_Yu);
3240 YcArg = YuArg = nullptr;
3242 if (YcArg && Inputs.size() > 1) {
3243 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3244 Args.eraseArg(options::OPT__SLASH_Yc);
3249 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
3251 if (FinalPhase == phases::Link) {
3252 if (Args.hasArg(options::OPT_emit_llvm))
3253 Diag(clang::diag::err_drv_emit_llvm_link);
3254 if (IsCLMode() && LTOMode != LTOK_None &&
3255 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
3256 Diag(clang::diag::err_drv_lto_without_lld);
3259 if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3260 // If only preprocessing or /Y- is used, all pch handling is disabled.
3261 // Rather than check for it everywhere, just remove clang-cl pch-related
3263 Args.eraseArg(options::OPT__SLASH_Fp);
3264 Args.eraseArg(options::OPT__SLASH_Yc);
3265 Args.eraseArg(options::OPT__SLASH_Yu);
3266 YcArg = YuArg = nullptr;
3269 unsigned LastPLSize = 0;
3270 for (auto &I : Inputs) {
3271 types::ID InputType = I.first;
3272 const Arg *InputArg = I.second;
3274 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
3275 types::getCompilationPhases(InputType, PL);
3276 LastPLSize = PL.size();
3278 // If the first step comes after the final phase we are doing as part of
3279 // this compilation, warn the user about it.
3280 phases::ID InitialPhase = PL[0];
3281 if (InitialPhase > FinalPhase) {
3282 if (InputArg->isClaimed())
3285 // Claim here to avoid the more general unused warning.
3288 // Suppress all unused style warnings with -Qunused-arguments
3289 if (Args.hasArg(options::OPT_Qunused_arguments))
3292 // Special case when final phase determined by binary name, rather than
3293 // by a command-line argument with a corresponding Arg.
3295 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
3296 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
3297 // Special case '-E' warning on a previously preprocessed file to make
3299 else if (InitialPhase == phases::Compile &&
3300 (Args.getLastArg(options::OPT__SLASH_EP,
3301 options::OPT__SLASH_P) ||
3302 Args.getLastArg(options::OPT_E) ||
3303 Args.getLastArg(options::OPT_M, options::OPT_MM)) &&
3304 getPreprocessedType(InputType) == types::TY_INVALID)
3305 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
3306 << InputArg->getAsString(Args) << !!FinalPhaseArg
3307 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3309 Diag(clang::diag::warn_drv_input_file_unused)
3310 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3312 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3317 // Add a separate precompile phase for the compile phase.
3318 if (FinalPhase >= phases::Compile) {
3319 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
3320 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
3321 types::getCompilationPhases(HeaderType, PCHPL);
3322 // Build the pipeline for the pch file.
3323 Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType);
3324 for (phases::ID Phase : PCHPL)
3325 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3327 Actions.push_back(ClangClPch);
3328 // The driver currently exits after the first failed command. This
3329 // relies on that behavior, to make sure if the pch generation fails,
3330 // the main compilation won't run.
3331 // FIXME: If the main compilation fails, the PCH generation should
3332 // probably not be considered successful either.
3337 // If we are linking, claim any options which are obviously only used for
3339 // FIXME: Understand why the last Phase List length is used here.
3340 if (FinalPhase == phases::Link && LastPLSize == 1) {
3341 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
3342 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3346 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
3347 const InputList &Inputs, ActionList &Actions) const {
3348 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
3350 if (!SuppressMissingInputWarning && Inputs.empty()) {
3351 Diag(clang::diag::err_drv_no_input_files);
3355 // Reject -Z* at the top level, these options should never have been exposed
3357 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
3358 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
3360 // Diagnose misuse of /Fo.
3361 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
3362 StringRef V = A->getValue();
3363 if (Inputs.size() > 1 && !V.empty() &&
3364 !llvm::sys::path::is_separator(V.back())) {
3365 // Check whether /Fo tries to name an output file for multiple inputs.
3366 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3367 << A->getSpelling() << V;
3368 Args.eraseArg(options::OPT__SLASH_Fo);
3372 // Diagnose misuse of /Fa.
3373 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
3374 StringRef V = A->getValue();
3375 if (Inputs.size() > 1 && !V.empty() &&
3376 !llvm::sys::path::is_separator(V.back())) {
3377 // Check whether /Fa tries to name an asm file for multiple inputs.
3378 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3379 << A->getSpelling() << V;
3380 Args.eraseArg(options::OPT__SLASH_Fa);
3384 // Diagnose misuse of /o.
3385 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
3386 if (A->getValue()[0] == '\0') {
3387 // It has to have a value.
3388 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
3389 Args.eraseArg(options::OPT__SLASH_o);
3393 handleArguments(C, Args, Inputs, Actions);
3395 // Builder to be used to build offloading actions.
3396 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
3398 // Construct the actions to perform.
3399 HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
3400 ActionList LinkerInputs;
3401 ActionList MergerInputs;
3403 for (auto &I : Inputs) {
3404 types::ID InputType = I.first;
3405 const Arg *InputArg = I.second;
3407 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
3408 types::getCompilationPhases(*this, Args, InputType, PL);
3412 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> FullPL;
3413 types::getCompilationPhases(InputType, FullPL);
3415 // Build the pipeline for this file.
3416 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3418 // Use the current host action in any of the offloading actions, if
3420 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3423 for (phases::ID Phase : PL) {
3425 // Add any offload action the host action depends on.
3426 Current = OffloadBuilder.addDeviceDependencesToHostAction(
3427 Current, InputArg, Phase, PL.back(), FullPL);
3431 // Queue linker inputs.
3432 if (Phase == phases::Link) {
3433 assert(Phase == PL.back() && "linking must be final compilation step.");
3434 LinkerInputs.push_back(Current);
3439 // TODO: Consider removing this because the merged may not end up being
3440 // the final Phase in the pipeline. Perhaps the merged could just merge
3441 // and then pass an artifact of some sort to the Link Phase.
3442 // Queue merger inputs.
3443 if (Phase == phases::IfsMerge) {
3444 assert(Phase == PL.back() && "merging must be final compilation step.");
3445 MergerInputs.push_back(Current);
3450 // Each precompiled header file after a module file action is a module
3451 // header of that same module file, rather than being compiled to a
3453 if (Phase == phases::Precompile && HeaderModuleAction &&
3454 getPrecompiledType(InputType) == types::TY_PCH) {
3455 HeaderModuleAction->addModuleHeaderInput(Current);
3460 // FIXME: Should we include any prior module file outputs as inputs of
3461 // later actions in the same command line?
3463 // Otherwise construct the appropriate action.
3464 Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
3466 // We didn't create a new action, so we will just move to the next phase.
3467 if (NewCurrent == Current)
3470 if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
3471 HeaderModuleAction = HMA;
3473 Current = NewCurrent;
3475 // Use the current host action in any of the offloading actions, if
3477 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3480 if (Current->getType() == types::TY_Nothing)
3484 // If we ended with something, add to the output list.
3486 Actions.push_back(Current);
3488 // Add any top level actions generated for offloading.
3489 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
3492 // Add a link action if necessary.
3493 if (!LinkerInputs.empty()) {
3494 if (Action *Wrapper = OffloadBuilder.makeHostLinkAction())
3495 LinkerInputs.push_back(Wrapper);
3496 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3497 LA = OffloadBuilder.processHostLinkAction(LA);
3498 Actions.push_back(LA);
3501 // Add an interface stubs merge action if necessary.
3502 if (!MergerInputs.empty())
3504 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
3506 if (Args.hasArg(options::OPT_emit_interface_stubs)) {
3507 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhaseList;
3508 if (Args.hasArg(options::OPT_c)) {
3509 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> CompilePhaseList;
3510 types::getCompilationPhases(types::TY_IFS_CPP, CompilePhaseList);
3511 llvm::copy_if(CompilePhaseList, std::back_inserter(PhaseList),
3512 [&](phases::ID Phase) { return Phase <= phases::Compile; });
3514 types::getCompilationPhases(types::TY_IFS_CPP, PhaseList);
3517 ActionList MergerInputs;
3519 for (auto &I : Inputs) {
3520 types::ID InputType = I.first;
3521 const Arg *InputArg = I.second;
3523 // Currently clang and the llvm assembler do not support generating symbol
3524 // stubs from assembly, so we skip the input on asm files. For ifs files
3525 // we rely on the normal pipeline setup in the pipeline setup code above.
3526 if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm ||
3527 InputType == types::TY_Asm)
3530 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3532 for (auto Phase : PhaseList) {
3536 "IFS Pipeline can only consist of Compile followed by IfsMerge.");
3537 case phases::Compile: {
3538 // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs
3539 // files where the .o file is located. The compile action can not
3541 if (InputType == types::TY_Object)
3544 Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP);
3547 case phases::IfsMerge: {
3548 assert(Phase == PhaseList.back() &&
3549 "merging must be final compilation step.");
3550 MergerInputs.push_back(Current);
3557 // If we ended with something, add to the output list.
3559 Actions.push_back(Current);
3562 // Add an interface stubs merge action if necessary.
3563 if (!MergerInputs.empty())
3565 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
3568 // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a custom
3569 // Compile phase that prints out supported cpu models and quits.
3570 if (Arg *A = Args.getLastArg(options::OPT_print_supported_cpus)) {
3571 // Use the -mcpu=? flag as the dummy input to cc1.
3573 Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C);
3575 C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing));
3576 for (auto &I : Inputs)
3580 // Claim ignored clang-cl options.
3581 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
3583 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3584 // to non-CUDA compilations and should not trigger warnings there.
3585 Args.ClaimAllArgs(options::OPT_cuda_host_only);
3586 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
3589 Action *Driver::ConstructPhaseAction(
3590 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3591 Action::OffloadKind TargetDeviceOffloadKind) const {
3592 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
3594 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3595 // encode this in the steps because the intermediate type depends on
3596 // arguments. Just special case here.
3597 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3600 // Build the appropriate action.
3603 llvm_unreachable("link action invalid here.");
3604 case phases::IfsMerge:
3605 llvm_unreachable("ifsmerge action invalid here.");
3606 case phases::Preprocess: {
3608 // -M and -MM specify the dependency file name by altering the output type,
3609 // -if -MD and -MMD are not specified.
3610 if (Args.hasArg(options::OPT_M, options::OPT_MM) &&
3611 !Args.hasArg(options::OPT_MD, options::OPT_MMD)) {
3612 OutputTy = types::TY_Dependencies;
3614 OutputTy = Input->getType();
3615 if (!Args.hasFlag(options::OPT_frewrite_includes,
3616 options::OPT_fno_rewrite_includes, false) &&
3617 !Args.hasFlag(options::OPT_frewrite_imports,
3618 options::OPT_fno_rewrite_imports, false) &&
3620 OutputTy = types::getPreprocessedType(OutputTy);
3621 assert(OutputTy != types::TY_INVALID &&
3622 "Cannot preprocess this input type!");
3624 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
3626 case phases::Precompile: {
3627 types::ID OutputTy = getPrecompiledType(Input->getType());
3628 assert(OutputTy != types::TY_INVALID &&
3629 "Cannot precompile this input type!");
3631 // If we're given a module name, precompile header file inputs as a
3632 // module, not as a precompiled header.
3633 const char *ModName = nullptr;
3634 if (OutputTy == types::TY_PCH) {
3635 if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
3636 ModName = A->getValue();
3638 OutputTy = types::TY_ModuleFile;
3641 if (Args.hasArg(options::OPT_fsyntax_only)) {
3642 // Syntax checks should not emit a PCH file
3643 OutputTy = types::TY_Nothing;
3647 return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
3649 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
3651 case phases::Compile: {
3652 if (Args.hasArg(options::OPT_fsyntax_only))
3653 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
3654 if (Args.hasArg(options::OPT_rewrite_objc))
3655 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
3656 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
3657 return C.MakeAction<CompileJobAction>(Input,
3658 types::TY_RewrittenLegacyObjC);
3659 if (Args.hasArg(options::OPT__analyze))
3660 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
3661 if (Args.hasArg(options::OPT__migrate))
3662 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
3663 if (Args.hasArg(options::OPT_emit_ast))
3664 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
3665 if (Args.hasArg(options::OPT_module_file_info))
3666 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
3667 if (Args.hasArg(options::OPT_verify_pch))
3668 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3669 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
3671 case phases::Backend: {
3672 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
3674 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
3675 return C.MakeAction<BackendJobAction>(Input, Output);
3677 if (Args.hasArg(options::OPT_emit_llvm)) {
3679 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
3680 return C.MakeAction<BackendJobAction>(Input, Output);
3682 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
3684 case phases::Assemble:
3685 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
3688 llvm_unreachable("invalid phase in ConstructPhaseAction");
3691 void Driver::BuildJobs(Compilation &C) const {
3692 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3694 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3696 // It is an error to provide a -o option if we are making multiple output
3697 // files. There are exceptions:
3699 // IfsMergeJob: when generating interface stubs enabled we want to be able to
3700 // generate the stub file at the same time that we generate the real
3701 // library/a.out. So when a .o, .so, etc are the output, with clang interface
3702 // stubs there will also be a .ifs and .ifso at the same location.
3704 // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled
3705 // and -c is passed, we still want to be able to generate a .ifs file while
3706 // we are also generating .o files. So we allow more than one output file in
3707 // this case as well.
3710 unsigned NumOutputs = 0;
3711 unsigned NumIfsOutputs = 0;
3712 for (const Action *A : C.getActions())
3713 if (A->getType() != types::TY_Nothing &&
3714 !(A->getKind() == Action::IfsMergeJobClass ||
3715 (A->getType() == clang::driver::types::TY_IFS_CPP &&
3716 A->getKind() == clang::driver::Action::CompileJobClass &&
3717 0 == NumIfsOutputs++) ||
3718 (A->getKind() == Action::BindArchClass && A->getInputs().size() &&
3719 A->getInputs().front()->getKind() == Action::IfsMergeJobClass)))
3722 if (NumOutputs > 1) {
3723 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
3724 FinalOutput = nullptr;
3728 // Collect the list of architectures.
3729 llvm::StringSet<> ArchNames;
3730 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
3731 for (const Arg *A : C.getArgs())
3732 if (A->getOption().matches(options::OPT_arch))
3733 ArchNames.insert(A->getValue());
3735 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3736 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
3737 for (Action *A : C.getActions()) {
3738 // If we are linking an image for multiple archs then the linker wants
3739 // -arch_multiple and -final_output <final image name>. Unfortunately, this
3740 // doesn't fit in cleanly because we have to pass this information down.
3742 // FIXME: This is a hack; find a cleaner way to integrate this into the
3744 const char *LinkingOutput = nullptr;
3745 if (isa<LipoJobAction>(A)) {
3747 LinkingOutput = FinalOutput->getValue();
3749 LinkingOutput = getDefaultImageName();
3752 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
3753 /*BoundArch*/ StringRef(),
3754 /*AtTopLevel*/ true,
3755 /*MultipleArchs*/ ArchNames.size() > 1,
3756 /*LinkingOutput*/ LinkingOutput, CachedResults,
3757 /*TargetDeviceOffloadKind*/ Action::OFK_None);
3760 // If we have more than one job, then disable integrated-cc1 for now.
3761 if (C.getJobs().size() > 1)
3762 for (auto &J : C.getJobs())
3763 J.InProcess = false;
3765 // If the user passed -Qunused-arguments or there were errors, don't warn
3766 // about any unused arguments.
3767 if (Diags.hasErrorOccurred() ||
3768 C.getArgs().hasArg(options::OPT_Qunused_arguments))
3772 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
3774 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
3775 (void)C.getArgs().hasArg(options::OPT_driver_mode);
3776 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
3778 for (Arg *A : C.getArgs()) {
3779 // FIXME: It would be nice to be able to send the argument to the
3780 // DiagnosticsEngine, so that extra values, position, and so on could be
3782 if (!A->isClaimed()) {
3783 if (A->getOption().hasFlag(options::NoArgumentUnused))
3786 // Suppress the warning automatically if this is just a flag, and it is an
3787 // instance of an argument we already claimed.
3788 const Option &Opt = A->getOption();
3789 if (Opt.getKind() == Option::FlagClass) {
3790 bool DuplicateClaimed = false;
3792 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
3793 if (AA->isClaimed()) {
3794 DuplicateClaimed = true;
3799 if (DuplicateClaimed)
3803 // In clang-cl, don't mention unknown arguments here since they have
3804 // already been warned about.
3805 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
3806 Diag(clang::diag::warn_drv_unused_argument)
3807 << A->getAsString(C.getArgs());
3813 /// Utility class to control the collapse of dependent actions and select the
3814 /// tools accordingly.
3815 class ToolSelector final {
3816 /// The tool chain this selector refers to.
3817 const ToolChain &TC;
3819 /// The compilation this selector refers to.
3820 const Compilation &C;
3822 /// The base action this selector refers to.
3823 const JobAction *BaseAction;
3825 /// Set to true if the current toolchain refers to host actions.
3826 bool IsHostSelector;
3828 /// Set to true if save-temps and embed-bitcode functionalities are active.
3832 /// Get previous dependent action or null if that does not exist. If
3833 /// \a CanBeCollapsed is false, that action must be legal to collapse or
3834 /// null will be returned.
3835 const JobAction *getPrevDependentAction(const ActionList &Inputs,
3836 ActionList &SavedOffloadAction,
3837 bool CanBeCollapsed = true) {
3838 // An option can be collapsed only if it has a single input.
3839 if (Inputs.size() != 1)
3842 Action *CurAction = *Inputs.begin();
3843 if (CanBeCollapsed &&
3844 !CurAction->isCollapsingWithNextDependentActionLegal())
3847 // If the input action is an offload action. Look through it and save any
3848 // offload action that can be dropped in the event of a collapse.
3849 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
3850 // If the dependent action is a device action, we will attempt to collapse
3851 // only with other device actions. Otherwise, we would do the same but
3852 // with host actions only.
3853 if (!IsHostSelector) {
3854 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
3856 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
3857 if (CanBeCollapsed &&
3858 !CurAction->isCollapsingWithNextDependentActionLegal())
3860 SavedOffloadAction.push_back(OA);
3861 return dyn_cast<JobAction>(CurAction);
3863 } else if (OA->hasHostDependence()) {
3864 CurAction = OA->getHostDependence();
3865 if (CanBeCollapsed &&
3866 !CurAction->isCollapsingWithNextDependentActionLegal())
3868 SavedOffloadAction.push_back(OA);
3869 return dyn_cast<JobAction>(CurAction);
3874 return dyn_cast<JobAction>(CurAction);
3877 /// Return true if an assemble action can be collapsed.
3878 bool canCollapseAssembleAction() const {
3879 return TC.useIntegratedAs() && !SaveTemps &&
3880 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
3881 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
3882 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
3885 /// Return true if a preprocessor action can be collapsed.
3886 bool canCollapsePreprocessorAction() const {
3887 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
3888 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
3889 !C.getArgs().hasArg(options::OPT_rewrite_objc);
3892 /// Struct that relates an action with the offload actions that would be
3893 /// collapsed with it.
3894 struct JobActionInfo final {
3895 /// The action this info refers to.
3896 const JobAction *JA = nullptr;
3897 /// The offload actions we need to take care off if this action is
3899 ActionList SavedOffloadAction;
3902 /// Append collapsed offload actions from the give nnumber of elements in the
3903 /// action info array.
3904 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
3905 ArrayRef<JobActionInfo> &ActionInfo,
3906 unsigned ElementNum) {
3907 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3908 for (unsigned I = 0; I < ElementNum; ++I)
3909 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3910 ActionInfo[I].SavedOffloadAction.end());
3913 /// Functions that attempt to perform the combining. They detect if that is
3914 /// legal, and if so they update the inputs \a Inputs and the offload action
3915 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3916 /// the combined action is returned. If the combining is not legal or if the
3917 /// tool does not exist, null is returned.
3918 /// Currently three kinds of collapsing are supported:
3919 /// - Assemble + Backend + Compile;
3920 /// - Assemble + Backend ;
3921 /// - Backend + Compile.
3923 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3925 ActionList &CollapsedOffloadAction) {
3926 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3928 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3929 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3930 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3931 if (!AJ || !BJ || !CJ)
3934 // Get compiler tool.
3935 const Tool *T = TC.SelectTool(*CJ);
3939 // When using -fembed-bitcode, it is required to have the same tool (clang)
3940 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3942 const Tool *BT = TC.SelectTool(*BJ);
3947 if (!T->hasIntegratedAssembler())
3950 Inputs = CJ->getInputs();
3951 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3955 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
3957 ActionList &CollapsedOffloadAction) {
3958 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3960 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3961 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3965 // Get backend tool.
3966 const Tool *T = TC.SelectTool(*BJ);
3970 if (!T->hasIntegratedAssembler())
3973 Inputs = BJ->getInputs();
3974 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3978 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3980 ActionList &CollapsedOffloadAction) {
3981 if (ActionInfo.size() < 2)
3983 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3984 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3988 // Check if the initial input (to the compile job or its predessor if one
3989 // exists) is LLVM bitcode. In that case, no preprocessor step is required
3990 // and we can still collapse the compile and backend jobs when we have
3991 // -save-temps. I.e. there is no need for a separate compile job just to
3992 // emit unoptimized bitcode.
3993 bool InputIsBitcode = true;
3994 for (size_t i = 1; i < ActionInfo.size(); i++)
3995 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
3996 ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
3997 InputIsBitcode = false;
4000 if (!InputIsBitcode && !canCollapsePreprocessorAction())
4003 // Get compiler tool.
4004 const Tool *T = TC.SelectTool(*CJ);
4008 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
4011 Inputs = CJ->getInputs();
4012 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4017 /// Updates the inputs if the obtained tool supports combining with
4018 /// preprocessor action, and the current input is indeed a preprocessor
4019 /// action. If combining results in the collapse of offloading actions, those
4020 /// are appended to \a CollapsedOffloadAction.
4021 void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
4022 ActionList &CollapsedOffloadAction) {
4023 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
4026 // Attempt to get a preprocessor action dependence.
4027 ActionList PreprocessJobOffloadActions;
4028 ActionList NewInputs;
4029 for (Action *A : Inputs) {
4030 auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
4031 if (!PJ || !isa<PreprocessJobAction>(PJ)) {
4032 NewInputs.push_back(A);
4036 // This is legal to combine. Append any offload action we found and add the
4037 // current input to preprocessor inputs.
4038 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
4039 PreprocessJobOffloadActions.end());
4040 NewInputs.append(PJ->input_begin(), PJ->input_end());
4046 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
4047 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
4048 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
4049 EmbedBitcode(EmbedBitcode) {
4050 assert(BaseAction && "Invalid base action.");
4051 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
4054 /// Check if a chain of actions can be combined and return the tool that can
4055 /// handle the combination of actions. The pointer to the current inputs \a
4056 /// Inputs and the list of offload actions \a CollapsedOffloadActions
4057 /// connected to collapsed actions are updated accordingly. The latter enables
4058 /// the caller of the selector to process them afterwards instead of just
4059 /// dropping them. If no suitable tool is found, null will be returned.
4060 const Tool *getTool(ActionList &Inputs,
4061 ActionList &CollapsedOffloadAction) {
4063 // Get the largest chain of actions that we could combine.
4066 SmallVector<JobActionInfo, 5> ActionChain(1);
4067 ActionChain.back().JA = BaseAction;
4068 while (ActionChain.back().JA) {
4069 const Action *CurAction = ActionChain.back().JA;
4071 // Grow the chain by one element.
4072 ActionChain.resize(ActionChain.size() + 1);
4073 JobActionInfo &AI = ActionChain.back();
4075 // Attempt to fill it with the
4077 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
4080 // Pop the last action info as it could not be filled.
4081 ActionChain.pop_back();
4084 // Attempt to combine actions. If all combining attempts failed, just return
4085 // the tool of the provided action. At the end we attempt to combine the
4086 // action with any preprocessor action it may depend on.
4089 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
4090 CollapsedOffloadAction);
4092 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
4094 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
4096 Inputs = BaseAction->getInputs();
4097 T = TC.SelectTool(*BaseAction);
4100 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
4106 /// Return a string that uniquely identifies the result of a job. The bound arch
4107 /// is not necessarily represented in the toolchain's triple -- for example,
4108 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
4109 /// Also, we need to add the offloading device kind, as the same tool chain can
4110 /// be used for host and device for some programming models, e.g. OpenMP.
4111 static std::string GetTriplePlusArchString(const ToolChain *TC,
4112 StringRef BoundArch,
4113 Action::OffloadKind OffloadKind) {
4114 std::string TriplePlusArch = TC->getTriple().normalize();
4115 if (!BoundArch.empty()) {
4116 TriplePlusArch += "-";
4117 TriplePlusArch += BoundArch;
4119 TriplePlusArch += "-";
4120 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
4121 return TriplePlusArch;
4124 InputInfo Driver::BuildJobsForAction(
4125 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
4126 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
4127 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
4128 Action::OffloadKind TargetDeviceOffloadKind) const {
4129 std::pair<const Action *, std::string> ActionTC = {
4130 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4131 auto CachedResult = CachedResults.find(ActionTC);
4132 if (CachedResult != CachedResults.end()) {
4133 return CachedResult->second;
4135 InputInfo Result = BuildJobsForActionNoCache(
4136 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
4137 CachedResults, TargetDeviceOffloadKind);
4138 CachedResults[ActionTC] = Result;
4142 InputInfo Driver::BuildJobsForActionNoCache(
4143 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
4144 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
4145 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
4146 Action::OffloadKind TargetDeviceOffloadKind) const {
4147 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
4149 InputInfoList OffloadDependencesInputInfo;
4150 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
4151 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
4152 // The 'Darwin' toolchain is initialized only when its arguments are
4153 // computed. Get the default arguments for OFK_None to ensure that
4154 // initialization is performed before processing the offload action.
4155 // FIXME: Remove when darwin's toolchain is initialized during construction.
4156 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
4158 // The offload action is expected to be used in four different situations.
4160 // a) Set a toolchain/architecture/kind for a host action:
4161 // Host Action 1 -> OffloadAction -> Host Action 2
4163 // b) Set a toolchain/architecture/kind for a device action;
4164 // Device Action 1 -> OffloadAction -> Device Action 2
4166 // c) Specify a device dependence to a host action;
4167 // Device Action 1 _
4169 // Host Action 1 ---> OffloadAction -> Host Action 2
4171 // d) Specify a host dependence to a device action.
4174 // Device Action 1 ---> OffloadAction -> Device Action 2
4176 // For a) and b), we just return the job generated for the dependence. For
4177 // c) and d) we override the current action with the host/device dependence
4178 // if the current toolchain is host/device and set the offload dependences
4179 // info with the jobs obtained from the device/host dependence(s).
4181 // If there is a single device option, just generate the job for it.
4182 if (OA->hasSingleDeviceDependence()) {
4184 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
4185 const char *DepBoundArch) {
4187 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
4188 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
4189 CachedResults, DepA->getOffloadingDeviceKind());
4194 // If 'Action 2' is host, we generate jobs for the device dependences and
4195 // override the current action with the host dependence. Otherwise, we
4196 // generate the host dependences and override the action with the device
4197 // dependence. The dependences can't therefore be a top-level action.
4198 OA->doOnEachDependence(
4199 /*IsHostDependence=*/BuildingForOffloadDevice,
4200 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4201 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
4202 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
4203 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
4204 DepA->getOffloadingDeviceKind()));
4207 A = BuildingForOffloadDevice
4208 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
4209 : OA->getHostDependence();
4212 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
4213 // FIXME: It would be nice to not claim this here; maybe the old scheme of
4214 // just using Args was better?
4215 const Arg &Input = IA->getInputArg();
4217 if (Input.getOption().matches(options::OPT_INPUT)) {
4218 const char *Name = Input.getValue();
4219 return InputInfo(A, Name, /* _BaseInput = */ Name);
4221 return InputInfo(A, &Input, /* _BaseInput = */ "");
4224 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
4225 const ToolChain *TC;
4226 StringRef ArchName = BAA->getArchName();
4228 if (!ArchName.empty())
4229 TC = &getToolChain(C.getArgs(),
4230 computeTargetTriple(*this, TargetTriple,
4231 C.getArgs(), ArchName));
4233 TC = &C.getDefaultToolChain();
4235 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
4236 MultipleArchs, LinkingOutput, CachedResults,
4237 TargetDeviceOffloadKind);
4241 ActionList Inputs = A->getInputs();
4243 const JobAction *JA = cast<JobAction>(A);
4244 ActionList CollapsedOffloadActions;
4246 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
4247 embedBitcodeInObject() && !isUsingLTO());
4248 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
4253 // If we've collapsed action list that contained OffloadAction we
4254 // need to build jobs for host/device-side inputs it may have held.
4255 for (const auto *OA : CollapsedOffloadActions)
4256 cast<OffloadAction>(OA)->doOnEachDependence(
4257 /*IsHostDependence=*/BuildingForOffloadDevice,
4258 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4259 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
4260 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
4261 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
4262 DepA->getOffloadingDeviceKind()));
4265 // Only use pipes when there is exactly one input.
4266 InputInfoList InputInfos;
4267 for (const Action *Input : Inputs) {
4268 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
4269 // shouldn't get temporary output names.
4270 // FIXME: Clean this up.
4271 bool SubJobAtTopLevel =
4272 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
4273 InputInfos.push_back(BuildJobsForAction(
4274 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
4275 CachedResults, A->getOffloadingDeviceKind()));
4278 // Always use the first input as the base input.
4279 const char *BaseInput = InputInfos[0].getBaseInput();
4281 // ... except dsymutil actions, which use their actual input as the base
4283 if (JA->getType() == types::TY_dSYM)
4284 BaseInput = InputInfos[0].getFilename();
4286 // ... and in header module compilations, which use the module name.
4287 if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
4288 BaseInput = ModuleJA->getModuleName();
4290 // Append outputs of offload device jobs to the input list
4291 if (!OffloadDependencesInputInfo.empty())
4292 InputInfos.append(OffloadDependencesInputInfo.begin(),
4293 OffloadDependencesInputInfo.end());
4295 // Set the effective triple of the toolchain for the duration of this job.
4296 llvm::Triple EffectiveTriple;
4297 const ToolChain &ToolTC = T->getToolChain();
4298 const ArgList &Args =
4299 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
4300 if (InputInfos.size() != 1) {
4301 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
4303 // Pass along the input type if it can be unambiguously determined.
4304 EffectiveTriple = llvm::Triple(
4305 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
4307 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
4309 // Determine the place to write output to, if any.
4311 InputInfoList UnbundlingResults;
4312 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
4313 // If we have an unbundling job, we need to create results for all the
4314 // outputs. We also update the results cache so that other actions using
4315 // this unbundling action can get the right results.
4316 for (auto &UI : UA->getDependentActionsInfo()) {
4317 assert(UI.DependentOffloadKind != Action::OFK_None &&
4318 "Unbundling with no offloading??");
4320 // Unbundling actions are never at the top level. When we generate the
4321 // offloading prefix, we also do that for the host file because the
4322 // unbundling action does not change the type of the output which can
4323 // cause a overwrite.
4324 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4325 UI.DependentOffloadKind,
4326 UI.DependentToolChain->getTriple().normalize(),
4327 /*CreatePrefixForHost=*/true);
4328 auto CurI = InputInfo(
4330 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
4331 /*AtTopLevel=*/false,
4333 UI.DependentOffloadKind == Action::OFK_HIP,
4336 // Save the unbundling result.
4337 UnbundlingResults.push_back(CurI);
4339 // Get the unique string identifier for this dependence and cache the
4342 if (TargetDeviceOffloadKind == Action::OFK_HIP) {
4343 if (UI.DependentOffloadKind == Action::OFK_Host)
4346 Arch = UI.DependentBoundArch;
4350 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
4351 UI.DependentOffloadKind)}] =
4355 // Now that we have all the results generated, select the one that should be
4356 // returned for the current depending action.
4357 std::pair<const Action *, std::string> ActionTC = {
4358 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4359 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
4360 "Result does not exist??");
4361 Result = CachedResults[ActionTC];
4362 } else if (JA->getType() == types::TY_Nothing)
4363 Result = InputInfo(A, BaseInput);
4365 // We only have to generate a prefix for the host if this is not a top-level
4367 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4368 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
4369 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
4371 if (isa<OffloadWrapperJobAction>(JA)) {
4372 OffloadingPrefix += "-wrapper";
4373 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
4374 BaseInput = FinalOutput->getValue();
4376 BaseInput = getDefaultImageName();
4378 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
4379 AtTopLevel, MultipleArchs,
4384 if (CCCPrintBindings && !CCGenDiagnostics) {
4385 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
4386 << " - \"" << T->getName() << "\", inputs: [";
4387 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
4388 llvm::errs() << InputInfos[i].getAsString();
4390 llvm::errs() << ", ";
4392 if (UnbundlingResults.empty())
4393 llvm::errs() << "], output: " << Result.getAsString() << "\n";
4395 llvm::errs() << "], outputs: [";
4396 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
4397 llvm::errs() << UnbundlingResults[i].getAsString();
4399 llvm::errs() << ", ";
4401 llvm::errs() << "] \n";
4404 if (UnbundlingResults.empty())
4406 C, *JA, Result, InputInfos,
4407 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4410 T->ConstructJobMultipleOutputs(
4411 C, *JA, UnbundlingResults, InputInfos,
4412 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4418 const char *Driver::getDefaultImageName() const {
4419 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
4420 return Target.isOSWindows() ? "a.exe" : "a.out";
4423 /// Create output filename based on ArgValue, which could either be a
4424 /// full filename, filename without extension, or a directory. If ArgValue
4425 /// does not provide a filename, then use BaseName, and use the extension
4426 /// suitable for FileType.
4427 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
4429 types::ID FileType) {
4430 SmallString<128> Filename = ArgValue;
4432 if (ArgValue.empty()) {
4433 // If the argument is empty, output to BaseName in the current dir.
4434 Filename = BaseName;
4435 } else if (llvm::sys::path::is_separator(Filename.back())) {
4436 // If the argument is a directory, output to BaseName in that dir.
4437 llvm::sys::path::append(Filename, BaseName);
4440 if (!llvm::sys::path::has_extension(ArgValue)) {
4441 // If the argument didn't provide an extension, then set it.
4442 const char *Extension = types::getTypeTempSuffix(FileType, true);
4444 if (FileType == types::TY_Image &&
4445 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
4446 // The output file is a dll.
4450 llvm::sys::path::replace_extension(Filename, Extension);
4453 return Args.MakeArgString(Filename.c_str());
4456 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
4457 const char *BaseInput,
4458 StringRef BoundArch, bool AtTopLevel,
4460 StringRef OffloadingPrefix) const {
4461 llvm::PrettyStackTraceString CrashInfo("Computing output path");
4462 // Output to a user requested destination?
4463 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
4464 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
4465 return C.addResultFile(FinalOutput->getValue(), &JA);
4468 // For /P, preprocess to file named after BaseInput.
4469 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
4470 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
4471 StringRef BaseName = llvm::sys::path::filename(BaseInput);
4473 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
4474 NameArg = A->getValue();
4475 return C.addResultFile(
4476 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
4480 // Default to writing to stdout?
4481 if (AtTopLevel && !CCGenDiagnostics && isa<PreprocessJobAction>(JA))
4484 // Is this the assembly listing for /FA?
4485 if (JA.getType() == types::TY_PP_Asm &&
4486 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
4487 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
4488 // Use /Fa and the input filename to determine the asm file name.
4489 StringRef BaseName = llvm::sys::path::filename(BaseInput);
4490 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
4491 return C.addResultFile(
4492 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
4496 // Output to a temporary file?
4497 if ((!AtTopLevel && !isSaveTempsEnabled() &&
4498 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
4500 StringRef Name = llvm::sys::path::filename(BaseInput);
4501 std::pair<StringRef, StringRef> Split = Name.split('.');
4502 SmallString<128> TmpName;
4503 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4504 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
4505 if (CCGenDiagnostics && A) {
4506 SmallString<128> CrashDirectory(A->getValue());
4507 if (!getVFS().exists(CrashDirectory))
4508 llvm::sys::fs::create_directories(CrashDirectory);
4509 llvm::sys::path::append(CrashDirectory, Split.first);
4510 const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%";
4511 std::error_code EC = llvm::sys::fs::createUniqueFile(
4512 CrashDirectory + Middle + Suffix, TmpName);
4514 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4518 TmpName = GetTemporaryPath(Split.first, Suffix);
4520 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4523 SmallString<128> BasePath(BaseInput);
4526 // Dsymutil actions should use the full path.
4527 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
4528 BaseName = BasePath;
4530 BaseName = llvm::sys::path::filename(BasePath);
4532 // Determine what the derived output name should be.
4533 const char *NamedOutput;
4535 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
4536 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
4537 // The /Fo or /o flag decides the object filename.
4540 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
4543 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
4544 } else if (JA.getType() == types::TY_Image &&
4545 C.getArgs().hasArg(options::OPT__SLASH_Fe,
4546 options::OPT__SLASH_o)) {
4547 // The /Fe or /o flag names the linked file.
4550 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
4553 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
4554 } else if (JA.getType() == types::TY_Image) {
4556 // clang-cl uses BaseName for the executable name.
4558 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
4560 SmallString<128> Output(getDefaultImageName());
4561 // HIP image for device compilation with -fno-gpu-rdc is per compilation
4563 bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
4564 !C.getArgs().hasFlag(options::OPT_fgpu_rdc,
4565 options::OPT_fno_gpu_rdc, false);
4568 llvm::sys::path::replace_extension(Output, "");
4570 Output += OffloadingPrefix;
4571 if (MultipleArchs && !BoundArch.empty()) {
4573 Output.append(BoundArch);
4577 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
4579 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
4580 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
4582 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4583 assert(Suffix && "All types used for output should have a suffix.");
4585 std::string::size_type End = std::string::npos;
4586 if (!types::appendSuffixForType(JA.getType()))
4587 End = BaseName.rfind('.');
4588 SmallString<128> Suffixed(BaseName.substr(0, End));
4589 Suffixed += OffloadingPrefix;
4590 if (MultipleArchs && !BoundArch.empty()) {
4592 Suffixed.append(BoundArch);
4594 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
4595 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
4596 // optimized bitcode output.
4597 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
4598 JA.getType() == types::TY_LLVM_BC)
4602 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
4605 // Prepend object file path if -save-temps=obj
4606 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
4607 JA.getType() != types::TY_PCH) {
4608 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4609 SmallString<128> TempPath(FinalOutput->getValue());
4610 llvm::sys::path::remove_filename(TempPath);
4611 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
4612 llvm::sys::path::append(TempPath, OutputFileName);
4613 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
4616 // If we're saving temps and the temp file conflicts with the input file,
4617 // then avoid overwriting input file.
4618 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
4619 bool SameFile = false;
4620 SmallString<256> Result;
4621 llvm::sys::fs::current_path(Result);
4622 llvm::sys::path::append(Result, BaseName);
4623 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
4624 // Must share the same path to conflict.
4626 StringRef Name = llvm::sys::path::filename(BaseInput);
4627 std::pair<StringRef, StringRef> Split = Name.split('.');
4628 std::string TmpName = GetTemporaryPath(
4629 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
4630 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4634 // As an annoying special case, PCH generation doesn't strip the pathname.
4635 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
4636 llvm::sys::path::remove_filename(BasePath);
4637 if (BasePath.empty())
4638 BasePath = NamedOutput;
4640 llvm::sys::path::append(BasePath, NamedOutput);
4641 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
4643 return C.addResultFile(NamedOutput, &JA);
4647 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
4648 // Search for Name in a list of paths.
4649 auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
4650 -> llvm::Optional<std::string> {
4651 // Respect a limited subset of the '-Bprefix' functionality in GCC by
4652 // attempting to use this prefix when looking for file paths.
4653 for (const auto &Dir : P) {
4656 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
4657 llvm::sys::path::append(P, Name);
4658 if (llvm::sys::fs::exists(Twine(P)))
4659 return P.str().str();
4664 if (auto P = SearchPaths(PrefixDirs))
4667 SmallString<128> R(ResourceDir);
4668 llvm::sys::path::append(R, Name);
4669 if (llvm::sys::fs::exists(Twine(R)))
4672 SmallString<128> P(TC.getCompilerRTPath());
4673 llvm::sys::path::append(P, Name);
4674 if (llvm::sys::fs::exists(Twine(P)))
4677 SmallString<128> D(Dir);
4678 llvm::sys::path::append(D, "..", Name);
4679 if (llvm::sys::fs::exists(Twine(D)))
4682 if (auto P = SearchPaths(TC.getLibraryPaths()))
4685 if (auto P = SearchPaths(TC.getFilePaths()))
4691 void Driver::generatePrefixedToolNames(
4692 StringRef Tool, const ToolChain &TC,
4693 SmallVectorImpl<std::string> &Names) const {
4694 // FIXME: Needs a better variable than TargetTriple
4695 Names.emplace_back((TargetTriple + "-" + Tool).str());
4696 Names.emplace_back(Tool);
4698 // Allow the discovery of tools prefixed with LLVM's default target triple.
4699 std::string DefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4700 if (DefaultTargetTriple != TargetTriple)
4701 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
4704 static bool ScanDirForExecutable(SmallString<128> &Dir,
4705 ArrayRef<std::string> Names) {
4706 for (const auto &Name : Names) {
4707 llvm::sys::path::append(Dir, Name);
4708 if (llvm::sys::fs::can_execute(Twine(Dir)))
4710 llvm::sys::path::remove_filename(Dir);
4715 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
4716 SmallVector<std::string, 2> TargetSpecificExecutables;
4717 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4719 // Respect a limited subset of the '-Bprefix' functionality in GCC by
4720 // attempting to use this prefix when looking for program paths.
4721 for (const auto &PrefixDir : PrefixDirs) {
4722 if (llvm::sys::fs::is_directory(PrefixDir)) {
4723 SmallString<128> P(PrefixDir);
4724 if (ScanDirForExecutable(P, TargetSpecificExecutables))
4727 SmallString<128> P((PrefixDir + Name).str());
4728 if (llvm::sys::fs::can_execute(Twine(P)))
4733 const ToolChain::path_list &List = TC.getProgramPaths();
4734 for (const auto &Path : List) {
4735 SmallString<128> P(Path);
4736 if (ScanDirForExecutable(P, TargetSpecificExecutables))
4740 // If all else failed, search the path.
4741 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
4742 if (llvm::ErrorOr<std::string> P =
4743 llvm::sys::findProgramByName(TargetSpecificExecutable))
4749 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
4750 SmallString<128> Path;
4751 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
4753 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4760 std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
4761 SmallString<128> Path;
4762 std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
4764 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4771 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
4772 SmallString<128> Output;
4773 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
4774 // FIXME: If anybody needs it, implement this obscure rule:
4775 // "If you specify a directory without a file name, the default file name
4776 // is VCx0.pch., where x is the major version of Visual C++ in use."
4777 Output = FpArg->getValue();
4779 // "If you do not specify an extension as part of the path name, an
4780 // extension of .pch is assumed. "
4781 if (!llvm::sys::path::has_extension(Output))
4784 if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
4785 Output = YcArg->getValue();
4788 llvm::sys::path::replace_extension(Output, ".pch");
4790 return Output.str();
4793 const ToolChain &Driver::getToolChain(const ArgList &Args,
4794 const llvm::Triple &Target) const {
4796 auto &TC = ToolChains[Target.str()];
4798 switch (Target.getOS()) {
4799 case llvm::Triple::AIX:
4800 TC = std::make_unique<toolchains::AIX>(*this, Target, Args);
4802 case llvm::Triple::Haiku:
4803 TC = std::make_unique<toolchains::Haiku>(*this, Target, Args);
4805 case llvm::Triple::Ananas:
4806 TC = std::make_unique<toolchains::Ananas>(*this, Target, Args);
4808 case llvm::Triple::CloudABI:
4809 TC = std::make_unique<toolchains::CloudABI>(*this, Target, Args);
4811 case llvm::Triple::Darwin:
4812 case llvm::Triple::MacOSX:
4813 case llvm::Triple::IOS:
4814 case llvm::Triple::TvOS:
4815 case llvm::Triple::WatchOS:
4816 TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args);
4818 case llvm::Triple::DragonFly:
4819 TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args);
4821 case llvm::Triple::OpenBSD:
4822 TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args);
4824 case llvm::Triple::NetBSD:
4825 TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args);
4827 case llvm::Triple::FreeBSD:
4828 TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args);
4830 case llvm::Triple::Minix:
4831 TC = std::make_unique<toolchains::Minix>(*this, Target, Args);
4833 case llvm::Triple::Linux:
4834 case llvm::Triple::ELFIAMCU:
4835 if (Target.getArch() == llvm::Triple::hexagon)
4836 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
4838 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
4839 !Target.hasEnvironment())
4840 TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
4842 else if (Target.getArch() == llvm::Triple::ppc ||
4843 Target.getArch() == llvm::Triple::ppc64 ||
4844 Target.getArch() == llvm::Triple::ppc64le)
4845 TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
4848 TC = std::make_unique<toolchains::Linux>(*this, Target, Args);
4850 case llvm::Triple::NaCl:
4851 TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
4853 case llvm::Triple::Fuchsia:
4854 TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args);
4856 case llvm::Triple::Solaris:
4857 TC = std::make_unique<toolchains::Solaris>(*this, Target, Args);
4859 case llvm::Triple::AMDHSA:
4860 case llvm::Triple::AMDPAL:
4861 case llvm::Triple::Mesa3D:
4862 TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
4864 case llvm::Triple::Win32:
4865 switch (Target.getEnvironment()) {
4867 if (Target.isOSBinFormatELF())
4868 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
4869 else if (Target.isOSBinFormatMachO())
4870 TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
4872 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
4874 case llvm::Triple::GNU:
4875 TC = std::make_unique<toolchains::MinGW>(*this, Target, Args);
4877 case llvm::Triple::Itanium:
4878 TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
4881 case llvm::Triple::MSVC:
4882 case llvm::Triple::UnknownEnvironment:
4883 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
4884 .startswith_lower("bfd"))
4885 TC = std::make_unique<toolchains::CrossWindowsToolChain>(
4886 *this, Target, Args);
4889 std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
4893 case llvm::Triple::PS4:
4894 TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args);
4896 case llvm::Triple::Contiki:
4897 TC = std::make_unique<toolchains::Contiki>(*this, Target, Args);
4899 case llvm::Triple::Hurd:
4900 TC = std::make_unique<toolchains::Hurd>(*this, Target, Args);
4903 // Of these targets, Hexagon is the only one that might have
4904 // an OS of Linux, in which case it got handled above already.
4905 switch (Target.getArch()) {
4906 case llvm::Triple::tce:
4907 TC = std::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
4909 case llvm::Triple::tcele:
4910 TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
4912 case llvm::Triple::hexagon:
4913 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
4916 case llvm::Triple::lanai:
4917 TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
4919 case llvm::Triple::xcore:
4920 TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
4922 case llvm::Triple::wasm32:
4923 case llvm::Triple::wasm64:
4924 TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args);
4926 case llvm::Triple::avr:
4927 TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
4929 case llvm::Triple::msp430:
4931 std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
4933 case llvm::Triple::riscv32:
4934 case llvm::Triple::riscv64:
4935 TC = std::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
4938 if (Target.getVendor() == llvm::Triple::Myriad)
4939 TC = std::make_unique<toolchains::MyriadToolChain>(*this, Target,
4941 else if (toolchains::BareMetal::handlesTarget(Target))
4942 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
4943 else if (Target.isOSBinFormatELF())
4944 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
4945 else if (Target.isOSBinFormatMachO())
4946 TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
4948 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
4953 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
4954 // compiles always need two toolchains, the CUDA toolchain and the host
4955 // toolchain. So the only valid way to create a CUDA toolchain is via
4956 // CreateOffloadingDeviceToolChains.
4961 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
4962 // Say "no" if there is not exactly one input of a type clang understands.
4963 if (JA.size() != 1 ||
4964 !types::isAcceptedByClang((*JA.input_begin())->getType()))
4967 // And say "no" if this is not a kind of action clang understands.
4968 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
4969 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
4975 bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const {
4976 // Say "no" if there is not exactly one input of a type flang understands.
4977 if (JA.size() != 1 ||
4978 !types::isFortran((*JA.input_begin())->getType()))
4981 // And say "no" if this is not a kind of action flang understands.
4982 if (!isa<PreprocessJobAction>(JA) && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
4988 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
4989 /// grouped values as integers. Numbers which are not provided are set to 0.
4991 /// \return True if the entire string was parsed (9.2), or all groups were
4992 /// parsed (10.3.5extrastuff).
4993 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
4994 unsigned &Micro, bool &HadExtra) {
4997 Major = Minor = Micro = 0;
5001 if (Str.consumeInteger(10, Major))
5008 Str = Str.drop_front(1);
5010 if (Str.consumeInteger(10, Minor))
5016 Str = Str.drop_front(1);
5018 if (Str.consumeInteger(10, Micro))
5025 /// Parse digits from a string \p Str and fulfill \p Digits with
5026 /// the parsed numbers. This method assumes that the max number of
5027 /// digits to look for is equal to Digits.size().
5029 /// \return True if the entire string was parsed and there are
5030 /// no extra characters remaining at the end.
5031 bool Driver::GetReleaseVersion(StringRef Str,
5032 MutableArrayRef<unsigned> Digits) {
5036 unsigned CurDigit = 0;
5037 while (CurDigit < Digits.size()) {
5039 if (Str.consumeInteger(10, Digit))
5041 Digits[CurDigit] = Digit;
5046 Str = Str.drop_front(1);
5050 // More digits than requested, bail out...
5054 std::pair<unsigned, unsigned>
5055 Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const {
5056 unsigned IncludedFlagsBitmask = 0;
5057 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
5059 if (IsClCompatMode) {
5060 // Include CL and Core options.
5061 IncludedFlagsBitmask |= options::CLOption;
5062 IncludedFlagsBitmask |= options::CoreOption;
5064 ExcludedFlagsBitmask |= options::CLOption;
5067 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
5070 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
5071 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
5074 bool clang::driver::willEmitRemarks(const ArgList &Args) {
5075 // -fsave-optimization-record enables it.
5076 if (Args.hasFlag(options::OPT_fsave_optimization_record,
5077 options::OPT_fno_save_optimization_record, false))
5080 // -fsave-optimization-record=<format> enables it as well.
5081 if (Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
5082 options::OPT_fno_save_optimization_record, false))
5085 // -foptimization-record-file alone enables it too.
5086 if (Args.hasFlag(options::OPT_foptimization_record_file_EQ,
5087 options::OPT_fno_save_optimization_record, false))
5090 // -foptimization-record-passes alone enables it too.
5091 if (Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
5092 options::OPT_fno_save_optimization_record, false))