1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/Driver/Driver.h"
11 #include "InputInfo.h"
12 #include "ToolChains.h"
13 #include "clang/Basic/Version.h"
14 #include "clang/Basic/VirtualFileSystem.h"
15 #include "clang/Config/config.h"
16 #include "clang/Driver/Action.h"
17 #include "clang/Driver/Compilation.h"
18 #include "clang/Driver/DriverDiagnostic.h"
19 #include "clang/Driver/Job.h"
20 #include "clang/Driver/Options.h"
21 #include "clang/Driver/SanitizerArgs.h"
22 #include "clang/Driver/Tool.h"
23 #include "clang/Driver/ToolChain.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSet.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/Option/Arg.h"
31 #include "llvm/Option/ArgList.h"
32 #include "llvm/Option/OptSpecifier.h"
33 #include "llvm/Option/OptTable.h"
34 #include "llvm/Option/Option.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/PrettyStackTrace.h"
40 #include "llvm/Support/Process.h"
41 #include "llvm/Support/Program.h"
42 #include "llvm/Support/raw_ostream.h"
47 using namespace clang::driver;
48 using namespace clang;
49 using namespace llvm::opt;
51 Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
52 DiagnosticsEngine &Diags,
53 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
54 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
55 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
56 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
57 SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
58 DefaultTargetTriple(DefaultTargetTriple),
59 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
60 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
61 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
62 CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
63 CCCUsePCH(true), SuppressMissingInputWarning(false) {
65 // Provide a sane fallback if no VFS is specified.
67 this->VFS = vfs::getRealFileSystem();
69 Name = llvm::sys::path::filename(ClangExecutable);
70 Dir = llvm::sys::path::parent_path(ClangExecutable);
71 InstalledDir = Dir; // Provide a sensible default installed dir.
73 // Compute the path to the resource directory.
74 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
75 SmallString<128> P(Dir);
76 if (ClangResourceDir != "") {
77 llvm::sys::path::append(P, ClangResourceDir);
79 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
80 llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang",
81 CLANG_VERSION_STRING);
83 ResourceDir = P.str();
89 llvm::DeleteContainerSeconds(ToolChains);
92 void Driver::ParseDriverMode(ArrayRef<const char *> Args) {
93 const std::string OptName =
94 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
96 for (const char *ArgPtr : Args) {
97 // Ingore nullptrs, they are response file's EOL markers
98 if (ArgPtr == nullptr)
100 const StringRef Arg = ArgPtr;
101 if (!Arg.startswith(OptName))
104 const StringRef Value = Arg.drop_front(OptName.size());
105 const unsigned M = llvm::StringSwitch<unsigned>(Value)
106 .Case("gcc", GCCMode)
107 .Case("g++", GXXMode)
108 .Case("cpp", CPPMode)
113 Mode = static_cast<DriverMode>(M);
115 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
119 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
120 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
122 unsigned IncludedFlagsBitmask;
123 unsigned ExcludedFlagsBitmask;
124 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
125 getIncludeExcludeOptionFlagMasks();
127 unsigned MissingArgIndex, MissingArgCount;
129 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
130 IncludedFlagsBitmask, ExcludedFlagsBitmask);
132 // Check for missing argument error.
134 Diag(clang::diag::err_drv_missing_argument)
135 << Args.getArgString(MissingArgIndex) << MissingArgCount;
137 // Check for unsupported options.
138 for (const Arg *A : Args) {
139 if (A->getOption().hasFlag(options::Unsupported)) {
140 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
144 // Warn about -mcpu= without an argument.
145 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
146 Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
150 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
151 Diags.Report(IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl :
152 diag::err_drv_unknown_argument)
153 << A->getAsString(Args);
158 // Determine which compilation mode we are in. We look for options which
159 // affect the phase, starting with the earliest phases, and record which
160 // option we used to determine the final phase.
161 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
162 Arg **FinalPhaseArg) const {
163 Arg *PhaseArg = nullptr;
164 phases::ID FinalPhase;
166 // -{E,EP,P,M,MM} only run the preprocessor.
167 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
168 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
169 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
170 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
171 FinalPhase = phases::Preprocess;
173 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
174 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
175 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
176 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
177 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
178 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
179 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
180 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
181 options::OPT__analyze_auto)) ||
182 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
183 FinalPhase = phases::Compile;
185 // -S only runs up to the backend.
186 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
187 FinalPhase = phases::Backend;
189 // -c compilation only runs up to the assembler.
190 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
191 FinalPhase = phases::Assemble;
193 // Otherwise do everything.
195 FinalPhase = phases::Link;
198 *FinalPhaseArg = PhaseArg;
203 static Arg *MakeInputArg(DerivedArgList &Args, OptTable *Opts,
205 Arg *A = new Arg(Opts->getOption(options::OPT_INPUT), Value,
206 Args.getBaseArgs().MakeIndex(Value), Value.data());
207 Args.AddSynthesizedArg(A);
212 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
213 DerivedArgList *DAL = new DerivedArgList(Args);
215 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
216 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
217 for (Arg *A : Args) {
218 // Unfortunately, we have to parse some forwarding options (-Xassembler,
219 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
220 // (assembler and preprocessor), or bypass a previous driver ('collect2').
222 // Rewrite linker options, to replace --no-demangle with a custom internal
224 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
225 A->getOption().matches(options::OPT_Xlinker)) &&
226 A->containsValue("--no-demangle")) {
227 // Add the rewritten no-demangle argument.
228 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
230 // Add the remaining values as Xlinker arguments.
231 for (StringRef Val : A->getValues())
232 if (Val != "--no-demangle")
233 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
238 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
239 // some build systems. We don't try to be complete here because we don't
240 // care to encourage this usage model.
241 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
242 (A->getValue(0) == StringRef("-MD") ||
243 A->getValue(0) == StringRef("-MMD"))) {
244 // Rewrite to -MD/-MMD along with -MF.
245 if (A->getValue(0) == StringRef("-MD"))
246 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
248 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
249 if (A->getNumValues() == 2)
250 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
255 // Rewrite reserved library names.
256 if (A->getOption().matches(options::OPT_l)) {
257 StringRef Value = A->getValue();
259 // Rewrite unless -nostdlib is present.
260 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
261 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
265 // Rewrite unconditionally.
266 if (Value == "cc_kext") {
267 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
272 // Pick up inputs via the -- option.
273 if (A->getOption().matches(options::OPT__DASH_DASH)) {
275 for (StringRef Val : A->getValues())
276 DAL->append(MakeInputArg(*DAL, Opts, Val));
283 // Enforce -static if -miamcu is present.
284 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
285 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
287 // Add a default value of -mlinker-version=, if one was given and the user
288 // didn't specify one.
289 #if defined(HOST_LINK_VERSION)
290 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
291 strlen(HOST_LINK_VERSION) > 0) {
292 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
294 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
301 /// \brief Compute target triple from args.
303 /// This routine provides the logic to compute a target triple from various
304 /// args passed to the driver and the default triple string.
305 static llvm::Triple computeTargetTriple(const Driver &D,
306 StringRef DefaultTargetTriple,
308 StringRef DarwinArchName = "") {
309 // FIXME: Already done in Compilation *Driver::BuildCompilation
310 if (const Arg *A = Args.getLastArg(options::OPT_target))
311 DefaultTargetTriple = A->getValue();
313 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
315 // Handle Apple-specific options available here.
316 if (Target.isOSBinFormatMachO()) {
317 // If an explict Darwin arch name is given, that trumps all.
318 if (!DarwinArchName.empty()) {
319 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
323 // Handle the Darwin '-arch' flag.
324 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
325 StringRef ArchName = A->getValue();
326 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
330 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
331 // '-mbig-endian'/'-EB'.
332 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
333 options::OPT_mbig_endian)) {
334 if (A->getOption().matches(options::OPT_mlittle_endian)) {
335 llvm::Triple LE = Target.getLittleEndianArchVariant();
336 if (LE.getArch() != llvm::Triple::UnknownArch)
337 Target = std::move(LE);
339 llvm::Triple BE = Target.getBigEndianArchVariant();
340 if (BE.getArch() != llvm::Triple::UnknownArch)
341 Target = std::move(BE);
345 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
346 if (Target.getArch() == llvm::Triple::tce ||
347 Target.getOS() == llvm::Triple::Minix)
350 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
351 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
352 options::OPT_m32, options::OPT_m16);
354 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
356 if (A->getOption().matches(options::OPT_m64)) {
357 AT = Target.get64BitArchVariant().getArch();
358 if (Target.getEnvironment() == llvm::Triple::GNUX32)
359 Target.setEnvironment(llvm::Triple::GNU);
360 } else if (A->getOption().matches(options::OPT_mx32) &&
361 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
362 AT = llvm::Triple::x86_64;
363 Target.setEnvironment(llvm::Triple::GNUX32);
364 } else if (A->getOption().matches(options::OPT_m32)) {
365 AT = Target.get32BitArchVariant().getArch();
366 if (Target.getEnvironment() == llvm::Triple::GNUX32)
367 Target.setEnvironment(llvm::Triple::GNU);
368 } else if (A->getOption().matches(options::OPT_m16) &&
369 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
370 AT = llvm::Triple::x86;
371 Target.setEnvironment(llvm::Triple::CODE16);
374 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
378 // Handle -miamcu flag.
379 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
380 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
381 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
384 if (A && !A->getOption().matches(options::OPT_m32))
385 D.Diag(diag::err_drv_argument_not_allowed_with)
386 << "-miamcu" << A->getBaseArg().getAsString(Args);
388 Target.setArch(llvm::Triple::x86);
389 Target.setArchName("i586");
390 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
391 Target.setEnvironmentName("");
392 Target.setOS(llvm::Triple::ELFIAMCU);
393 Target.setVendor(llvm::Triple::UnknownVendor);
394 Target.setVendorName("intel");
400 // \brief Parse the LTO options and record the type of LTO compilation
401 // based on which -f(no-)?lto(=.*)? option occurs last.
402 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
404 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
405 options::OPT_fno_lto, false))
408 StringRef LTOName("full");
410 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
412 LTOName = A->getValue();
414 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
415 .Case("full", LTOK_Full)
416 .Case("thin", LTOK_Thin)
417 .Default(LTOK_Unknown);
419 if (LTOMode == LTOK_Unknown) {
421 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
426 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
432 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
433 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
434 return types::isCuda(I.first);
436 const ToolChain &TC = getToolChain(
438 llvm::Triple(C.getSingleOffloadToolChain<Action::OFK_Host>()
441 ? "nvptx64-nvidia-cuda"
442 : "nvptx-nvidia-cuda"));
443 C.addOffloadDeviceToolChain(&TC, Action::OFK_Cuda);
447 // TODO: Add support for other offloading programming models here.
453 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
454 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
456 // FIXME: Handle environment options which affect driver behavior, somewhere
457 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
459 if (char *env = ::getenv("COMPILER_PATH")) {
460 StringRef CompilerPath = env;
461 while (!CompilerPath.empty()) {
462 std::pair<StringRef, StringRef> Split =
463 CompilerPath.split(llvm::sys::EnvPathSeparator);
464 PrefixDirs.push_back(Split.first);
465 CompilerPath = Split.second;
469 // We look for the driver mode option early, because the mode can affect
470 // how other options are parsed.
471 ParseDriverMode(ArgList.slice(1));
473 // FIXME: What are we going to do with -V and -b?
475 // FIXME: This stuff needs to go into the Compilation, not the driver.
478 InputArgList Args = ParseArgStrings(ArgList.slice(1));
480 // Silence driver warnings if requested
481 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
483 // -no-canonical-prefixes is used very early in main.
484 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
487 Args.ClaimAllArgs(options::OPT_pipe);
489 // Extract -ccc args.
491 // FIXME: We need to figure out where this behavior should live. Most of it
492 // should be outside in the client; the parts that aren't should have proper
493 // options, either by introducing new ones or by overloading gcc ones like -V
495 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
496 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
497 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
498 CCCGenericGCCName = A->getValue();
500 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
501 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
502 // and getToolChain is const.
504 // clang-cl targets MSVC-style Win32.
505 llvm::Triple T(DefaultTargetTriple);
506 T.setOS(llvm::Triple::Win32);
507 T.setVendor(llvm::Triple::PC);
508 T.setEnvironment(llvm::Triple::MSVC);
509 DefaultTargetTriple = T.str();
511 if (const Arg *A = Args.getLastArg(options::OPT_target))
512 DefaultTargetTriple = A->getValue();
513 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
514 Dir = InstalledDir = A->getValue();
515 for (const Arg *A : Args.filtered(options::OPT_B)) {
517 PrefixDirs.push_back(A->getValue(0));
519 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
520 SysRoot = A->getValue();
521 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
522 DyldPrefix = A->getValue();
523 if (Args.hasArg(options::OPT_nostdlib))
526 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
527 ResourceDir = A->getValue();
529 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
530 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
531 .Case("cwd", SaveTempsCwd)
532 .Case("obj", SaveTempsObj)
533 .Default(SaveTempsCwd);
538 // Ignore -fembed-bitcode options with LTO
539 // since the output will be bitcode anyway.
540 if (getLTOMode() == LTOK_None) {
541 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
542 StringRef Name = A->getValue();
543 unsigned Model = llvm::StringSwitch<unsigned>(Name)
544 .Case("off", EmbedNone)
545 .Case("all", EmbedBitcode)
546 .Case("bitcode", EmbedBitcode)
547 .Case("marker", EmbedMarker)
550 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
553 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
556 // claim the bitcode option under LTO so no warning is issued.
557 Args.ClaimAllArgs(options::OPT_fembed_bitcode_EQ);
560 std::unique_ptr<llvm::opt::InputArgList> UArgs =
561 llvm::make_unique<InputArgList>(std::move(Args));
563 // Perform the default argument translations.
564 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
566 // Owned by the host.
567 const ToolChain &TC = getToolChain(
568 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
570 // The compilation takes ownership of Args.
571 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
573 if (!HandleImmediateArgs(*C))
576 // Construct the list of inputs.
578 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
580 // Populate the tool chains for the offloading devices, if any.
581 CreateOffloadingDeviceToolChains(*C, Inputs);
583 // Construct the list of abstract actions to perform for this compilation. On
584 // MachO targets this uses the driver-driver and universal actions.
585 if (TC.getTriple().isOSBinFormatMachO())
586 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
588 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
590 if (CCCPrintPhases) {
600 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
601 llvm::opt::ArgStringList ASL;
602 for (const auto *A : Args)
603 A->render(Args, ASL);
605 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
606 if (I != ASL.begin())
608 Command::printArg(OS, *I, true);
613 // When clang crashes, produce diagnostic information including the fully
614 // preprocessed source file(s). Request that the developer attach the
615 // diagnostic information to a bug report.
616 void Driver::generateCompilationDiagnostics(Compilation &C,
617 const Command &FailingCommand) {
618 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
621 // Don't try to generate diagnostics for link or dsymutil jobs.
622 if (FailingCommand.getCreator().isLinkJob() ||
623 FailingCommand.getCreator().isDsymutilJob())
626 // Print the version of the compiler.
627 PrintVersion(C, llvm::errs());
629 Diag(clang::diag::note_drv_command_failed_diag_msg)
630 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
631 "crash backtrace, preprocessed source, and associated run script.";
633 // Suppress driver output and emit preprocessor output to temp file.
635 CCGenDiagnostics = true;
637 // Save the original job command(s).
638 Command Cmd = FailingCommand;
640 // Keep track of whether we produce any errors while trying to produce
641 // preprocessed sources.
642 DiagnosticErrorTrap Trap(Diags);
644 // Suppress tool output.
645 C.initCompilationForDiagnostics();
647 // Construct the list of inputs.
649 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
651 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
652 bool IgnoreInput = false;
654 // Ignore input from stdin or any inputs that cannot be preprocessed.
655 // Check type first as not all linker inputs have a value.
656 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
658 } else if (!strcmp(it->second->getValue(), "-")) {
659 Diag(clang::diag::note_drv_command_failed_diag_msg)
660 << "Error generating preprocessed source(s) - "
661 "ignoring input from stdin.";
666 it = Inputs.erase(it);
673 if (Inputs.empty()) {
674 Diag(clang::diag::note_drv_command_failed_diag_msg)
675 << "Error generating preprocessed source(s) - "
676 "no preprocessable inputs.";
680 // Don't attempt to generate preprocessed files if multiple -arch options are
681 // used, unless they're all duplicates.
682 llvm::StringSet<> ArchNames;
683 for (const Arg *A : C.getArgs()) {
684 if (A->getOption().matches(options::OPT_arch)) {
685 StringRef ArchName = A->getValue();
686 ArchNames.insert(ArchName);
689 if (ArchNames.size() > 1) {
690 Diag(clang::diag::note_drv_command_failed_diag_msg)
691 << "Error generating preprocessed source(s) - cannot generate "
692 "preprocessed source with multiple -arch options.";
696 // Construct the list of abstract actions to perform for this compilation. On
697 // Darwin OSes this uses the driver-driver and builds universal actions.
698 const ToolChain &TC = C.getDefaultToolChain();
699 if (TC.getTriple().isOSBinFormatMachO())
700 BuildUniversalActions(C, TC, Inputs);
702 BuildActions(C, C.getArgs(), Inputs, C.getActions());
706 // If there were errors building the compilation, quit now.
707 if (Trap.hasErrorOccurred()) {
708 Diag(clang::diag::note_drv_command_failed_diag_msg)
709 << "Error generating preprocessed source(s).";
713 // Generate preprocessed output.
714 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
715 C.ExecuteJobs(C.getJobs(), FailingCommands);
717 // If any of the preprocessing commands failed, clean up and exit.
718 if (!FailingCommands.empty()) {
719 if (!isSaveTempsEnabled())
720 C.CleanupFileList(C.getTempFiles(), true);
722 Diag(clang::diag::note_drv_command_failed_diag_msg)
723 << "Error generating preprocessed source(s).";
727 const ArgStringList &TempFiles = C.getTempFiles();
728 if (TempFiles.empty()) {
729 Diag(clang::diag::note_drv_command_failed_diag_msg)
730 << "Error generating preprocessed source(s).";
734 Diag(clang::diag::note_drv_command_failed_diag_msg)
735 << "\n********************\n\n"
736 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
737 "Preprocessed source(s) and associated run script(s) are located at:";
739 SmallString<128> VFS;
740 for (const char *TempFile : TempFiles) {
741 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
742 if (StringRef(TempFile).endswith(".cache")) {
743 // In some cases (modules) we'll dump extra data to help with reproducing
744 // the crash into a directory next to the output.
745 VFS = llvm::sys::path::filename(TempFile);
746 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
750 // Assume associated files are based off of the first temporary file.
751 CrashReportInfo CrashInfo(TempFiles[0], VFS);
753 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
755 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
757 Diag(clang::diag::note_drv_command_failed_diag_msg)
758 << "Error generating run script: " + Script + " " + EC.message();
760 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
761 << "# Driver args: ";
762 printArgList(ScriptOS, C.getInputArgs());
763 ScriptOS << "# Original command: ";
764 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
765 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
766 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
769 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
770 options::OPT_frewrite_map_file_EQ))
771 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
773 Diag(clang::diag::note_drv_command_failed_diag_msg)
774 << "\n\n********************";
777 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
778 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
779 // if the tool does not support response files, there is a chance/ that things
780 // will just work without a response file, so we silently just skip it.
781 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
782 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
785 std::string TmpName = GetTemporaryPath("response", "txt");
787 C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())));
790 int Driver::ExecuteCompilation(
792 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
793 // Just print if -### was present.
794 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
795 C.getJobs().Print(llvm::errs(), "\n", true);
799 // If there were errors building the compilation, quit now.
800 if (Diags.hasErrorOccurred())
803 // Set up response file names for each command, if necessary
804 for (auto &Job : C.getJobs())
805 setUpResponseFiles(C, Job);
807 C.ExecuteJobs(C.getJobs(), FailingCommands);
809 // Remove temp files.
810 C.CleanupFileList(C.getTempFiles());
812 // If the command succeeded, we are done.
813 if (FailingCommands.empty())
816 // Otherwise, remove result files and print extra information about abnormal
818 for (const auto &CmdPair : FailingCommands) {
819 int Res = CmdPair.first;
820 const Command *FailingCommand = CmdPair.second;
822 // Remove result files if we're not saving temps.
823 if (!isSaveTempsEnabled()) {
824 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
825 C.CleanupFileMap(C.getResultFiles(), JA, true);
827 // Failure result files are valid unless we crashed.
829 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
832 // Print extra information about abnormal failures, if possible.
834 // This is ad-hoc, but we don't want to be excessively noisy. If the result
835 // status was 1, assume the command failed normally. In particular, if it
836 // was the compiler then assume it gave a reasonable error code. Failures
837 // in other tools are less common, and they generally have worse
838 // diagnostics, so always print the diagnostic there.
839 const Tool &FailingTool = FailingCommand->getCreator();
841 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
842 // FIXME: See FIXME above regarding result code interpretation.
844 Diag(clang::diag::err_drv_command_signalled)
845 << FailingTool.getShortName();
847 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
854 void Driver::PrintHelp(bool ShowHidden) const {
855 unsigned IncludedFlagsBitmask;
856 unsigned ExcludedFlagsBitmask;
857 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
858 getIncludeExcludeOptionFlagMasks();
860 ExcludedFlagsBitmask |= options::NoDriverOption;
862 ExcludedFlagsBitmask |= HelpHidden;
864 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
865 IncludedFlagsBitmask, ExcludedFlagsBitmask);
868 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
869 // FIXME: The following handlers should use a callback mechanism, we don't
870 // know what the client would like to do.
871 OS << getClangFullVersion() << '\n';
872 const ToolChain &TC = C.getDefaultToolChain();
873 OS << "Target: " << TC.getTripleString() << '\n';
875 // Print the threading model.
876 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
877 // Don't print if the ToolChain would have barfed on it already
878 if (TC.isThreadModelSupported(A->getValue()))
879 OS << "Thread model: " << A->getValue();
881 OS << "Thread model: " << TC.getThreadModel();
884 // Print out the install directory.
885 OS << "InstalledDir: " << InstalledDir << '\n';
888 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
890 static void PrintDiagnosticCategories(raw_ostream &OS) {
891 // Skip the empty category.
892 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
894 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
897 bool Driver::HandleImmediateArgs(const Compilation &C) {
898 // The order these options are handled in gcc is all over the place, but we
899 // don't expect inconsistencies w.r.t. that to matter in practice.
901 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
902 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
906 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
907 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
908 // return an answer which matches our definition of __VERSION__.
910 // If we want to return a more correct answer some day, then we should
911 // introduce a non-pedantically GCC compatible mode to Clang in which we
912 // provide sensible definitions for -dumpversion, __VERSION__, etc.
913 llvm::outs() << "4.2.1\n";
917 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
918 PrintDiagnosticCategories(llvm::outs());
922 if (C.getArgs().hasArg(options::OPT_help) ||
923 C.getArgs().hasArg(options::OPT__help_hidden)) {
924 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
928 if (C.getArgs().hasArg(options::OPT__version)) {
929 // Follow gcc behavior and use stdout for --version and stderr for -v.
930 PrintVersion(C, llvm::outs());
934 if (C.getArgs().hasArg(options::OPT_v) ||
935 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
936 PrintVersion(C, llvm::errs());
937 SuppressMissingInputWarning = true;
940 const ToolChain &TC = C.getDefaultToolChain();
942 if (C.getArgs().hasArg(options::OPT_v))
943 TC.printVerboseInfo(llvm::errs());
945 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
946 llvm::outs() << "programs: =";
947 bool separator = false;
948 for (const std::string &Path : TC.getProgramPaths()) {
951 llvm::outs() << Path;
954 llvm::outs() << "\n";
955 llvm::outs() << "libraries: =" << ResourceDir;
957 StringRef sysroot = C.getSysRoot();
959 for (const std::string &Path : TC.getFilePaths()) {
960 // Always print a separator. ResourceDir was the first item shown.
962 // Interpretation of leading '=' is needed only for NetBSD.
964 llvm::outs() << sysroot << Path.substr(1);
966 llvm::outs() << Path;
968 llvm::outs() << "\n";
972 // FIXME: The following handlers should use a callback mechanism, we don't
973 // know what the client would like to do.
974 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
975 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
979 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
980 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
984 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
985 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
989 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
990 for (const Multilib &Multilib : TC.getMultilibs())
991 llvm::outs() << Multilib << "\n";
995 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
996 for (const Multilib &Multilib : TC.getMultilibs()) {
997 if (Multilib.gccSuffix().empty())
998 llvm::outs() << ".\n";
1000 StringRef Suffix(Multilib.gccSuffix());
1001 assert(Suffix.front() == '/');
1002 llvm::outs() << Suffix.substr(1) << "\n";
1010 // Display an action graph human-readably. Action A is the "sink" node
1011 // and latest-occuring action. Traversal is in pre-order, visiting the
1012 // inputs to each action before printing the action itself.
1013 static unsigned PrintActions1(const Compilation &C, Action *A,
1014 std::map<Action *, unsigned> &Ids) {
1015 if (Ids.count(A)) // A was already visited.
1019 llvm::raw_string_ostream os(str);
1021 os << Action::getClassName(A->getKind()) << ", ";
1022 if (InputAction *IA = dyn_cast<InputAction>(A)) {
1023 os << "\"" << IA->getInputArg().getValue() << "\"";
1024 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1025 os << '"' << BIA->getArchName() << '"' << ", {"
1026 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
1027 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1028 bool IsFirst = true;
1029 OA->doOnEachDependence(
1030 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1031 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1032 // sm_35 this will generate:
1033 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1034 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1039 os << A->getOffloadingKindPrefix();
1043 os << TC->getTriple().normalize();
1046 os << ":" << BoundArch;
1049 os << " {" << PrintActions1(C, A, Ids) << "}";
1053 const ActionList *AL = &A->getInputs();
1056 const char *Prefix = "{";
1057 for (Action *PreRequisite : *AL) {
1058 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1066 // Append offload info for all options other than the offloading action
1067 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1068 std::string offload_str;
1069 llvm::raw_string_ostream offload_os(offload_str);
1070 if (!isa<OffloadAction>(A)) {
1071 auto S = A->getOffloadingKindPrefix();
1073 offload_os << ", (" << S;
1074 if (A->getOffloadingArch())
1075 offload_os << ", " << A->getOffloadingArch();
1080 unsigned Id = Ids.size();
1082 llvm::errs() << Id << ": " << os.str() << ", "
1083 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1088 // Print the action graphs in a compilation C.
1089 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
1090 void Driver::PrintActions(const Compilation &C) const {
1091 std::map<Action *, unsigned> Ids;
1092 for (Action *A : C.getActions())
1093 PrintActions1(C, A, Ids);
1096 /// \brief Check whether the given input tree contains any compilation or
1097 /// assembly actions.
1098 static bool ContainsCompileOrAssembleAction(const Action *A) {
1099 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1100 isa<AssembleJobAction>(A))
1103 for (const Action *Input : A->inputs())
1104 if (ContainsCompileOrAssembleAction(Input))
1110 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1111 const InputList &BAInputs) const {
1112 DerivedArgList &Args = C.getArgs();
1113 ActionList &Actions = C.getActions();
1114 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1115 // Collect the list of architectures. Duplicates are allowed, but should only
1116 // be handled once (in the order seen).
1117 llvm::StringSet<> ArchNames;
1118 SmallVector<const char *, 4> Archs;
1119 for (Arg *A : Args) {
1120 if (A->getOption().matches(options::OPT_arch)) {
1121 // Validate the option here; we don't save the type here because its
1122 // particular spelling may participate in other driver choices.
1123 llvm::Triple::ArchType Arch =
1124 tools::darwin::getArchTypeForMachOArchName(A->getValue());
1125 if (Arch == llvm::Triple::UnknownArch) {
1126 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1131 if (ArchNames.insert(A->getValue()).second)
1132 Archs.push_back(A->getValue());
1136 // When there is no explicit arch for this platform, make sure we still bind
1137 // the architecture (to the default) so that -Xarch_ is handled correctly.
1139 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1141 ActionList SingleActions;
1142 BuildActions(C, Args, BAInputs, SingleActions);
1144 // Add in arch bindings for every top level action, as well as lipo and
1145 // dsymutil steps if needed.
1146 for (Action* Act : SingleActions) {
1147 // Make sure we can lipo this kind of output. If not (and it is an actual
1148 // output) then we disallow, since we can't create an output file with the
1149 // right name without overwriting it. We could remove this oddity by just
1150 // changing the output names to include the arch, which would also fix
1151 // -save-temps. Compatibility wins for now.
1153 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1154 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1155 << types::getTypeName(Act->getType());
1158 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1159 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
1161 // Lipo if necessary, we do it this way because we need to set the arch flag
1162 // so that -Xarch_ gets overwritten.
1163 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1164 Actions.append(Inputs.begin(), Inputs.end());
1166 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
1168 // Handle debug info queries.
1169 Arg *A = Args.getLastArg(options::OPT_g_Group);
1170 if (A && !A->getOption().matches(options::OPT_g0) &&
1171 !A->getOption().matches(options::OPT_gstabs) &&
1172 ContainsCompileOrAssembleAction(Actions.back())) {
1174 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1175 // have a compile input. We need to run 'dsymutil' ourselves in such cases
1176 // because the debug info will refer to a temporary object file which
1177 // will be removed at the end of the compilation process.
1178 if (Act->getType() == types::TY_Image) {
1180 Inputs.push_back(Actions.back());
1183 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
1186 // Verify the debug info output.
1187 if (Args.hasArg(options::OPT_verify_debug_info)) {
1188 Action* LastAction = Actions.back();
1190 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1191 LastAction, types::TY_Nothing));
1197 /// \brief Check that the file referenced by Value exists. If it doesn't,
1198 /// issue a diagnostic and return false.
1199 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
1200 StringRef Value, types::ID Ty) {
1201 if (!D.getCheckInputsExist())
1204 // stdin always exists.
1208 SmallString<64> Path(Value);
1209 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1210 if (!llvm::sys::path::is_absolute(Path)) {
1211 SmallString<64> Directory(WorkDir->getValue());
1212 llvm::sys::path::append(Directory, Value);
1213 Path.assign(Directory);
1217 if (llvm::sys::fs::exists(Twine(Path)))
1221 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1222 llvm::sys::Process::FindInEnvPath("LIB", Value))
1225 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1226 // Arguments to the /link flag might cause the linker to search for object
1227 // and library files in paths we don't know about. Don't error in such
1233 D.Diag(clang::diag::err_drv_no_such_file) << Path;
1237 // Construct a the list of inputs and their types.
1238 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
1239 InputList &Inputs) const {
1240 // Track the current user specified (-x) input. We also explicitly track the
1241 // argument used to set the type; we only want to claim the type when we
1242 // actually use it, so we warn about unused -x arguments.
1243 types::ID InputType = types::TY_Nothing;
1244 Arg *InputTypeArg = nullptr;
1246 // The last /TC or /TP option sets the input type to C or C++ globally.
1247 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1248 options::OPT__SLASH_TP)) {
1249 InputTypeArg = TCTP;
1250 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
1255 Args.filtered_begin(options::OPT__SLASH_TC, options::OPT__SLASH_TP);
1256 const arg_iterator ie = Args.filtered_end();
1257 Arg *Previous = *it++;
1258 bool ShowNote = false;
1260 Diag(clang::diag::warn_drv_overriding_flag_option)
1261 << Previous->getSpelling() << (*it)->getSpelling();
1266 Diag(clang::diag::note_drv_t_option_is_global);
1268 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1269 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1272 for (Arg *A : Args) {
1273 if (A->getOption().getKind() == Option::InputClass) {
1274 const char *Value = A->getValue();
1275 types::ID Ty = types::TY_INVALID;
1277 // Infer the input type if necessary.
1278 if (InputType == types::TY_Nothing) {
1279 // If there was an explicit arg for this, claim it.
1281 InputTypeArg->claim();
1283 // stdin must be handled specially.
1284 if (memcmp(Value, "-", 2) == 0) {
1285 // If running with -E, treat as a C input (this changes the builtin
1286 // macros, for example). This may be overridden by -ObjC below.
1288 // Otherwise emit an error but still use a valid type to avoid
1289 // spurious errors (e.g., no inputs).
1290 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
1291 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1292 : clang::diag::err_drv_unknown_stdin_type);
1295 // Otherwise lookup by extension.
1296 // Fallback is C if invoked as C preprocessor or Object otherwise.
1297 // We use a host hook here because Darwin at least has its own
1298 // idea of what .s is.
1299 if (const char *Ext = strrchr(Value, '.'))
1300 Ty = TC.LookupTypeForExtension(Ext + 1);
1302 if (Ty == types::TY_INVALID) {
1306 Ty = types::TY_Object;
1309 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1310 // should autodetect some input files as C++ for g++ compatibility.
1312 types::ID OldTy = Ty;
1313 Ty = types::lookupCXXTypeForCType(Ty);
1316 Diag(clang::diag::warn_drv_treating_input_as_cxx)
1317 << getTypeName(OldTy) << getTypeName(Ty);
1321 // -ObjC and -ObjC++ override the default language, but only for "source
1322 // files". We just treat everything that isn't a linker input as a
1325 // FIXME: Clean this up if we move the phase sequence into the type.
1326 if (Ty != types::TY_Object) {
1327 if (Args.hasArg(options::OPT_ObjC))
1328 Ty = types::TY_ObjC;
1329 else if (Args.hasArg(options::OPT_ObjCXX))
1330 Ty = types::TY_ObjCXX;
1333 assert(InputTypeArg && "InputType set w/o InputTypeArg");
1334 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1335 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1337 const char *Ext = strrchr(Value, '.');
1338 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1339 Ty = types::TY_Object;
1341 if (Ty == types::TY_INVALID) {
1343 InputTypeArg->claim();
1347 if (DiagnoseInputExistence(*this, Args, Value, Ty))
1348 Inputs.push_back(std::make_pair(Ty, A));
1350 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1351 StringRef Value = A->getValue();
1352 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
1353 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1354 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1357 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1358 StringRef Value = A->getValue();
1359 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
1360 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1361 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1364 } else if (A->getOption().hasFlag(options::LinkerInput)) {
1365 // Just treat as object type, we could make a special type for this if
1367 Inputs.push_back(std::make_pair(types::TY_Object, A));
1369 } else if (A->getOption().matches(options::OPT_x)) {
1371 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
1374 // Follow gcc behavior and treat as linker input for invalid -x
1375 // options. Its not clear why we shouldn't just revert to unknown; but
1376 // this isn't very important, we might as well be bug compatible.
1378 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
1379 InputType = types::TY_Object;
1383 if (CCCIsCPP() && Inputs.empty()) {
1384 // If called as standalone preprocessor, stdin is processed
1385 // if no other input is present.
1386 Arg *A = MakeInputArg(Args, Opts, "-");
1387 Inputs.push_back(std::make_pair(types::TY_C, A));
1391 // For each unique --cuda-gpu-arch= argument creates a TY_CUDA_DEVICE
1392 // input action and then wraps each in CudaDeviceAction paired with
1393 // appropriate GPU arch name. In case of partial (i.e preprocessing
1394 // only) or device-only compilation, each device action is added to /p
1395 // Actions and /p Current is released. Otherwise the function creates
1396 // and returns a new CudaHostAction which wraps /p Current and device
1398 static Action *buildCudaActions(Compilation &C, DerivedArgList &Args,
1399 const Arg *InputArg, Action *HostAction,
1400 ActionList &Actions) {
1401 Arg *PartialCompilationArg = Args.getLastArg(
1402 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
1403 options::OPT_cuda_compile_host_device);
1404 bool CompileHostOnly =
1405 PartialCompilationArg &&
1406 PartialCompilationArg->getOption().matches(options::OPT_cuda_host_only);
1407 bool CompileDeviceOnly =
1408 PartialCompilationArg &&
1409 PartialCompilationArg->getOption().matches(options::OPT_cuda_device_only);
1411 if (CompileHostOnly) {
1412 OffloadAction::HostDependence HDep(
1413 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
1414 /*BoundArch=*/nullptr, Action::OFK_Cuda);
1415 return C.MakeAction<OffloadAction>(HDep);
1418 // Collect all cuda_gpu_arch parameters, removing duplicates.
1419 SmallVector<CudaArch, 4> GpuArchList;
1420 llvm::SmallSet<CudaArch, 4> GpuArchs;
1421 for (Arg *A : Args) {
1422 if (!A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
1426 const auto &ArchStr = A->getValue();
1427 CudaArch Arch = StringToCudaArch(ArchStr);
1428 if (Arch == CudaArch::UNKNOWN)
1429 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
1430 else if (GpuArchs.insert(Arch).second)
1431 GpuArchList.push_back(Arch);
1434 // Default to sm_20 which is the lowest common denominator for supported GPUs.
1435 // sm_20 code should work correctly, if suboptimally, on all newer GPUs.
1436 if (GpuArchList.empty())
1437 GpuArchList.push_back(CudaArch::SM_20);
1439 // Replicate inputs for each GPU architecture.
1440 Driver::InputList CudaDeviceInputs;
1441 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1442 CudaDeviceInputs.push_back(std::make_pair(types::TY_CUDA_DEVICE, InputArg));
1444 // Build actions for all device inputs.
1445 ActionList CudaDeviceActions;
1446 C.getDriver().BuildActions(C, Args, CudaDeviceInputs, CudaDeviceActions);
1447 assert(GpuArchList.size() == CudaDeviceActions.size() &&
1448 "Failed to create actions for all devices");
1450 // Check whether any of device actions stopped before they could generate PTX.
1451 bool PartialCompilation =
1452 llvm::any_of(CudaDeviceActions, [](const Action *a) {
1453 return a->getKind() != Action::AssembleJobClass;
1456 const ToolChain *CudaTC = C.getSingleOffloadToolChain<Action::OFK_Cuda>();
1458 // Figure out what to do with device actions -- pass them as inputs to the
1459 // host action or run each of them independently.
1460 if (PartialCompilation || CompileDeviceOnly) {
1461 // In case of partial or device-only compilation results of device actions
1462 // are not consumed by the host action device actions have to be added to
1463 // top-level actions list with AtTopLevel=true and run independently.
1465 // -o is ambiguous if we have more than one top-level action.
1466 if (Args.hasArg(options::OPT_o) &&
1467 (!CompileDeviceOnly || GpuArchList.size() > 1)) {
1469 clang::diag::err_drv_output_argument_with_multiple_files);
1473 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1474 OffloadAction::DeviceDependences DDep;
1475 DDep.add(*CudaDeviceActions[I], *CudaTC, CudaArchToString(GpuArchList[I]),
1478 C.MakeAction<OffloadAction>(DDep, CudaDeviceActions[I]->getType()));
1480 // Kill host action in case of device-only compilation.
1481 if (CompileDeviceOnly)
1486 // If we're not a partial or device-only compilation, we compile each arch to
1487 // ptx and assemble to cubin, then feed the cubin *and* the ptx into a device
1488 // "link" action, which uses fatbinary to combine these cubins into one
1489 // fatbin. The fatbin is then an input to the host compilation.
1490 ActionList DeviceActions;
1491 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1492 Action* AssembleAction = CudaDeviceActions[I];
1493 assert(AssembleAction->getType() == types::TY_Object);
1494 assert(AssembleAction->getInputs().size() == 1);
1496 Action* BackendAction = AssembleAction->getInputs()[0];
1497 assert(BackendAction->getType() == types::TY_PP_Asm);
1499 for (auto &A : {AssembleAction, BackendAction}) {
1500 OffloadAction::DeviceDependences DDep;
1501 DDep.add(*A, *CudaTC, CudaArchToString(GpuArchList[I]), Action::OFK_Cuda);
1502 DeviceActions.push_back(C.MakeAction<OffloadAction>(DDep, A->getType()));
1506 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
1508 // Return a new host action that incorporates original host action and all
1510 OffloadAction::HostDependence HDep(
1511 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
1512 /*BoundArch=*/nullptr, Action::OFK_Cuda);
1513 OffloadAction::DeviceDependences DDep;
1514 DDep.add(*FatbinAction, *CudaTC, /*BoundArch=*/nullptr, Action::OFK_Cuda);
1515 return C.MakeAction<OffloadAction>(HDep, DDep);
1518 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
1519 const InputList &Inputs, ActionList &Actions) const {
1520 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
1522 if (!SuppressMissingInputWarning && Inputs.empty()) {
1523 Diag(clang::diag::err_drv_no_input_files);
1528 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
1530 if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) {
1531 Diag(clang::diag::err_drv_emit_llvm_link);
1534 // Reject -Z* at the top level, these options should never have been exposed
1536 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
1537 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
1539 // Diagnose misuse of /Fo.
1540 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
1541 StringRef V = A->getValue();
1542 if (Inputs.size() > 1 && !V.empty() &&
1543 !llvm::sys::path::is_separator(V.back())) {
1544 // Check whether /Fo tries to name an output file for multiple inputs.
1545 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
1546 << A->getSpelling() << V;
1547 Args.eraseArg(options::OPT__SLASH_Fo);
1551 // Diagnose misuse of /Fa.
1552 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
1553 StringRef V = A->getValue();
1554 if (Inputs.size() > 1 && !V.empty() &&
1555 !llvm::sys::path::is_separator(V.back())) {
1556 // Check whether /Fa tries to name an asm file for multiple inputs.
1557 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
1558 << A->getSpelling() << V;
1559 Args.eraseArg(options::OPT__SLASH_Fa);
1563 // Diagnose misuse of /o.
1564 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
1565 if (A->getValue()[0] == '\0') {
1566 // It has to have a value.
1567 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
1568 Args.eraseArg(options::OPT__SLASH_o);
1572 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
1573 // * no filename after it
1574 // * both /Yc and /Yu passed but with different filenames
1575 // * corresponding file not also passed as /FI
1576 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1577 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1578 if (YcArg && YcArg->getValue()[0] == '\0') {
1579 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
1580 Args.eraseArg(options::OPT__SLASH_Yc);
1583 if (YuArg && YuArg->getValue()[0] == '\0') {
1584 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
1585 Args.eraseArg(options::OPT__SLASH_Yu);
1588 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
1589 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
1590 Args.eraseArg(options::OPT__SLASH_Yc);
1591 Args.eraseArg(options::OPT__SLASH_Yu);
1592 YcArg = YuArg = nullptr;
1594 if (YcArg || YuArg) {
1595 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
1596 bool FoundMatchingInclude = false;
1597 for (const Arg *Inc : Args.filtered(options::OPT_include)) {
1598 // FIXME: Do case-insensitive matching and consider / and \ as equal.
1599 if (Inc->getValue() == Val)
1600 FoundMatchingInclude = true;
1602 if (!FoundMatchingInclude) {
1603 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
1604 << (YcArg ? YcArg : YuArg)->getSpelling();
1605 Args.eraseArg(options::OPT__SLASH_Yc);
1606 Args.eraseArg(options::OPT__SLASH_Yu);
1607 YcArg = YuArg = nullptr;
1610 if (YcArg && Inputs.size() > 1) {
1611 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
1612 Args.eraseArg(options::OPT__SLASH_Yc);
1615 if (Args.hasArg(options::OPT__SLASH_Y_)) {
1616 // /Y- disables all pch handling. Rather than check for it everywhere,
1617 // just remove clang-cl pch-related flags here.
1618 Args.eraseArg(options::OPT__SLASH_Fp);
1619 Args.eraseArg(options::OPT__SLASH_Yc);
1620 Args.eraseArg(options::OPT__SLASH_Yu);
1621 YcArg = YuArg = nullptr;
1624 // Track the host offload kinds used on this compilation.
1625 unsigned CompilationActiveOffloadHostKinds = 0u;
1627 // Construct the actions to perform.
1628 ActionList LinkerInputs;
1630 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
1631 for (auto &I : Inputs) {
1632 types::ID InputType = I.first;
1633 const Arg *InputArg = I.second;
1636 types::getCompilationPhases(InputType, PL);
1638 // If the first step comes after the final phase we are doing as part of
1639 // this compilation, warn the user about it.
1640 phases::ID InitialPhase = PL[0];
1641 if (InitialPhase > FinalPhase) {
1642 // Claim here to avoid the more general unused warning.
1645 // Suppress all unused style warnings with -Qunused-arguments
1646 if (Args.hasArg(options::OPT_Qunused_arguments))
1649 // Special case when final phase determined by binary name, rather than
1650 // by a command-line argument with a corresponding Arg.
1652 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
1653 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
1654 // Special case '-E' warning on a previously preprocessed file to make
1656 else if (InitialPhase == phases::Compile &&
1657 FinalPhase == phases::Preprocess &&
1658 getPreprocessedType(InputType) == types::TY_INVALID)
1659 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
1660 << InputArg->getAsString(Args) << !!FinalPhaseArg
1661 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
1663 Diag(clang::diag::warn_drv_input_file_unused)
1664 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
1666 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
1671 // Add a separate precompile phase for the compile phase.
1672 if (FinalPhase >= phases::Compile) {
1673 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
1674 types::getCompilationPhases(types::TY_CXXHeader, PCHPL);
1675 Arg *PchInputArg = MakeInputArg(Args, Opts, YcArg->getValue());
1677 // Build the pipeline for the pch file.
1678 Action *ClangClPch = C.MakeAction<InputAction>(*PchInputArg, InputType);
1679 for (phases::ID Phase : PCHPL)
1680 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
1682 Actions.push_back(ClangClPch);
1683 // The driver currently exits after the first failed command. This
1684 // relies on that behavior, to make sure if the pch generation fails,
1685 // the main compilation won't run.
1689 phases::ID CudaInjectionPhase =
1690 (phases::Compile < FinalPhase &&
1691 llvm::find(PL, phases::Compile) != PL.end())
1695 // Track the host offload kinds used on this input.
1696 unsigned InputActiveOffloadHostKinds = 0u;
1698 // Build the pipeline for this file.
1699 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
1700 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
1702 phases::ID Phase = *i;
1704 // We are done if this step is past what the user requested.
1705 if (Phase > FinalPhase)
1708 // Queue linker inputs.
1709 if (Phase == phases::Link) {
1710 assert((i + 1) == e && "linking must be final compilation step.");
1711 LinkerInputs.push_back(Current);
1716 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
1717 // encode this in the steps because the intermediate type depends on
1718 // arguments. Just special case here.
1719 if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
1722 // Otherwise construct the appropriate action.
1723 Current = ConstructPhaseAction(C, Args, Phase, Current);
1725 if (InputType == types::TY_CUDA && Phase == CudaInjectionPhase) {
1726 Current = buildCudaActions(C, Args, InputArg, Current, Actions);
1730 // We produced a CUDA action for this input, so the host has to support
1732 InputActiveOffloadHostKinds |= Action::OFK_Cuda;
1733 CompilationActiveOffloadHostKinds |= Action::OFK_Cuda;
1736 if (Current->getType() == types::TY_Nothing)
1740 // If we ended with something, add to the output list. Also, propagate the
1741 // offload information to the top-level host action related with the current
1744 if (InputActiveOffloadHostKinds)
1745 Current->propagateHostOffloadInfo(InputActiveOffloadHostKinds,
1746 /*BoundArch=*/nullptr);
1747 Actions.push_back(Current);
1751 // Add a link action if necessary and propagate the offload information for
1752 // the current compilation.
1753 if (!LinkerInputs.empty()) {
1755 C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image));
1756 Actions.back()->propagateHostOffloadInfo(CompilationActiveOffloadHostKinds,
1757 /*BoundArch=*/nullptr);
1760 // If we are linking, claim any options which are obviously only used for
1762 if (FinalPhase == phases::Link && PL.size() == 1) {
1763 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
1764 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
1767 // Claim ignored clang-cl options.
1768 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
1770 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
1771 // to non-CUDA compilations and should not trigger warnings there.
1772 Args.ClaimAllArgs(options::OPT_cuda_host_only);
1773 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
1776 Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
1777 phases::ID Phase, Action *Input) const {
1778 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
1779 // Build the appropriate action.
1782 llvm_unreachable("link action invalid here.");
1783 case phases::Preprocess: {
1785 // -{M, MM} alter the output type.
1786 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
1787 OutputTy = types::TY_Dependencies;
1789 OutputTy = Input->getType();
1790 if (!Args.hasFlag(options::OPT_frewrite_includes,
1791 options::OPT_fno_rewrite_includes, false) &&
1793 OutputTy = types::getPreprocessedType(OutputTy);
1794 assert(OutputTy != types::TY_INVALID &&
1795 "Cannot preprocess this input type!");
1797 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
1799 case phases::Precompile: {
1800 types::ID OutputTy = types::TY_PCH;
1801 if (Args.hasArg(options::OPT_fsyntax_only)) {
1802 // Syntax checks should not emit a PCH file
1803 OutputTy = types::TY_Nothing;
1805 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
1807 case phases::Compile: {
1808 if (Args.hasArg(options::OPT_fsyntax_only))
1809 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
1810 if (Args.hasArg(options::OPT_rewrite_objc))
1811 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
1812 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
1813 return C.MakeAction<CompileJobAction>(Input,
1814 types::TY_RewrittenLegacyObjC);
1815 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
1816 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
1817 if (Args.hasArg(options::OPT__migrate))
1818 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
1819 if (Args.hasArg(options::OPT_emit_ast))
1820 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
1821 if (Args.hasArg(options::OPT_module_file_info))
1822 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
1823 if (Args.hasArg(options::OPT_verify_pch))
1824 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
1825 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
1827 case phases::Backend: {
1830 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
1831 return C.MakeAction<BackendJobAction>(Input, Output);
1833 if (Args.hasArg(options::OPT_emit_llvm)) {
1835 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
1836 return C.MakeAction<BackendJobAction>(Input, Output);
1838 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
1840 case phases::Assemble:
1841 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
1844 llvm_unreachable("invalid phase in ConstructPhaseAction");
1847 void Driver::BuildJobs(Compilation &C) const {
1848 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1850 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
1852 // It is an error to provide a -o option if we are making multiple output
1855 unsigned NumOutputs = 0;
1856 for (const Action *A : C.getActions())
1857 if (A->getType() != types::TY_Nothing)
1860 if (NumOutputs > 1) {
1861 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
1862 FinalOutput = nullptr;
1866 // Collect the list of architectures.
1867 llvm::StringSet<> ArchNames;
1868 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
1869 for (const Arg *A : C.getArgs())
1870 if (A->getOption().matches(options::OPT_arch))
1871 ArchNames.insert(A->getValue());
1873 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
1874 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
1875 for (Action *A : C.getActions()) {
1876 // If we are linking an image for multiple archs then the linker wants
1877 // -arch_multiple and -final_output <final image name>. Unfortunately, this
1878 // doesn't fit in cleanly because we have to pass this information down.
1880 // FIXME: This is a hack; find a cleaner way to integrate this into the
1882 const char *LinkingOutput = nullptr;
1883 if (isa<LipoJobAction>(A)) {
1885 LinkingOutput = FinalOutput->getValue();
1887 LinkingOutput = getDefaultImageName();
1890 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
1891 /*BoundArch*/ nullptr,
1892 /*AtTopLevel*/ true,
1893 /*MultipleArchs*/ ArchNames.size() > 1,
1894 /*LinkingOutput*/ LinkingOutput, CachedResults,
1895 /*BuildForOffloadDevice*/ false);
1898 // If the user passed -Qunused-arguments or there were errors, don't warn
1899 // about any unused arguments.
1900 if (Diags.hasErrorOccurred() ||
1901 C.getArgs().hasArg(options::OPT_Qunused_arguments))
1905 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1907 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
1908 (void)C.getArgs().hasArg(options::OPT_driver_mode);
1909 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
1911 for (Arg *A : C.getArgs()) {
1912 // FIXME: It would be nice to be able to send the argument to the
1913 // DiagnosticsEngine, so that extra values, position, and so on could be
1915 if (!A->isClaimed()) {
1916 if (A->getOption().hasFlag(options::NoArgumentUnused))
1919 // Suppress the warning automatically if this is just a flag, and it is an
1920 // instance of an argument we already claimed.
1921 const Option &Opt = A->getOption();
1922 if (Opt.getKind() == Option::FlagClass) {
1923 bool DuplicateClaimed = false;
1925 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
1926 if (AA->isClaimed()) {
1927 DuplicateClaimed = true;
1932 if (DuplicateClaimed)
1936 // In clang-cl, don't mention unknown arguments here since they have
1937 // already been warned about.
1938 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
1939 Diag(clang::diag::warn_drv_unused_argument)
1940 << A->getAsString(C.getArgs());
1944 /// Collapse an offloading action looking for a job of the given type. The input
1945 /// action is changed to the input of the collapsed sequence. If we effectively
1946 /// had a collapse return the corresponding offloading action, otherwise return
1948 template <typename T>
1949 static OffloadAction *collapseOffloadingAction(Action *&CurAction) {
1952 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
1953 if (OA->hasHostDependence())
1954 if (auto *HDep = dyn_cast<T>(OA->getHostDependence())) {
1958 if (OA->hasSingleDeviceDependence())
1959 if (auto *DDep = dyn_cast<T>(OA->getSingleDeviceDependence())) {
1966 // Returns a Tool for a given JobAction. In case the action and its
1967 // predecessors can be combined, updates Inputs with the inputs of the
1968 // first combined action. If one of the collapsed actions is a
1969 // CudaHostAction, updates CollapsedCHA with the pointer to it so the
1970 // caller can deal with extra handling such action requires.
1971 static const Tool *selectToolForJob(Compilation &C, bool SaveTemps,
1972 bool EmbedBitcode, const ToolChain *TC,
1973 const JobAction *JA,
1974 const ActionList *&Inputs,
1975 ActionList &CollapsedOffloadAction) {
1976 const Tool *ToolForJob = nullptr;
1977 CollapsedOffloadAction.clear();
1979 // See if we should look for a compiler with an integrated assembler. We match
1980 // bottom up, so what we are actually looking for is an assembler job with a
1983 // Look through offload actions between assembler and backend actions.
1984 Action *BackendJA = (isa<AssembleJobAction>(JA) && Inputs->size() == 1)
1987 auto *BackendOA = collapseOffloadingAction<BackendJobAction>(BackendJA);
1989 if (TC->useIntegratedAs() && !SaveTemps &&
1990 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
1991 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
1992 !C.getArgs().hasArg(options::OPT__SLASH_Fa) && BackendJA &&
1993 isa<BackendJobAction>(BackendJA)) {
1994 // A BackendJob is always preceded by a CompileJob, and without -save-temps
1995 // or -fembed-bitcode, they will always get combined together, so instead of
1996 // checking the backend tool, check if the tool for the CompileJob has an
1997 // integrated assembler. For -fembed-bitcode, CompileJob is still used to
1998 // look up tools for BackendJob, but they need to match before we can split
2001 // Look through offload actions between backend and compile actions.
2002 Action *CompileJA = *BackendJA->getInputs().begin();
2003 auto *CompileOA = collapseOffloadingAction<CompileJobAction>(CompileJA);
2005 assert(CompileJA && isa<CompileJobAction>(CompileJA) &&
2006 "Backend job is not preceeded by compile job.");
2007 const Tool *Compiler = TC->SelectTool(*cast<CompileJobAction>(CompileJA));
2010 // When using -fembed-bitcode, it is required to have the same tool (clang)
2011 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
2013 JobAction *InputJA = cast<JobAction>(*Inputs->begin());
2014 const Tool *BackendTool = TC->SelectTool(*InputJA);
2015 if (BackendTool == Compiler)
2016 CompileJA = InputJA;
2018 if (Compiler->hasIntegratedAssembler()) {
2019 Inputs = &CompileJA->getInputs();
2020 ToolForJob = Compiler;
2021 // Save the collapsed offload actions because they may still contain
2024 CollapsedOffloadAction.push_back(CompileOA);
2026 CollapsedOffloadAction.push_back(BackendOA);
2030 // A backend job should always be combined with the preceding compile job
2031 // unless OPT_save_temps or OPT_fembed_bitcode is enabled and the compiler is
2032 // capable of emitting LLVM IR as an intermediate output.
2033 if (isa<BackendJobAction>(JA)) {
2034 // Check if the compiler supports emitting LLVM IR.
2035 assert(Inputs->size() == 1);
2037 // Look through offload actions between backend and compile actions.
2038 Action *CompileJA = *JA->getInputs().begin();
2039 auto *CompileOA = collapseOffloadingAction<CompileJobAction>(CompileJA);
2041 assert(CompileJA && isa<CompileJobAction>(CompileJA) &&
2042 "Backend job is not preceeded by compile job.");
2043 const Tool *Compiler = TC->SelectTool(*cast<CompileJobAction>(CompileJA));
2046 if (!Compiler->canEmitIR() ||
2047 (!SaveTemps && !EmbedBitcode)) {
2048 Inputs = &CompileJA->getInputs();
2049 ToolForJob = Compiler;
2052 CollapsedOffloadAction.push_back(CompileOA);
2056 // Otherwise use the tool for the current job.
2058 ToolForJob = TC->SelectTool(*JA);
2060 // See if we should use an integrated preprocessor. We do so when we have
2061 // exactly one input, since this is the only use case we care about
2062 // (irrelevant since we don't support combine yet).
2064 // Look through offload actions after preprocessing.
2065 Action *PreprocessJA = (Inputs->size() == 1) ? *Inputs->begin() : nullptr;
2066 auto *PreprocessOA =
2067 collapseOffloadingAction<PreprocessJobAction>(PreprocessJA);
2069 if (PreprocessJA && isa<PreprocessJobAction>(PreprocessJA) &&
2070 !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
2071 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
2072 !C.getArgs().hasArg(options::OPT_rewrite_objc) &&
2073 ToolForJob->hasIntegratedCPP()) {
2074 Inputs = &PreprocessJA->getInputs();
2076 CollapsedOffloadAction.push_back(PreprocessOA);
2082 InputInfo Driver::BuildJobsForAction(
2083 Compilation &C, const Action *A, const ToolChain *TC, const char *BoundArch,
2084 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
2085 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
2086 bool BuildForOffloadDevice) const {
2087 // The bound arch is not necessarily represented in the toolchain's triple --
2088 // for example, armv7 and armv7s both map to the same triple -- so we need
2090 std::string TriplePlusArch = TC->getTriple().normalize();
2092 TriplePlusArch += "-";
2093 TriplePlusArch += BoundArch;
2095 std::pair<const Action *, std::string> ActionTC = {A, TriplePlusArch};
2096 auto CachedResult = CachedResults.find(ActionTC);
2097 if (CachedResult != CachedResults.end()) {
2098 return CachedResult->second;
2100 InputInfo Result = BuildJobsForActionNoCache(
2101 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
2102 CachedResults, BuildForOffloadDevice);
2103 CachedResults[ActionTC] = Result;
2107 InputInfo Driver::BuildJobsForActionNoCache(
2108 Compilation &C, const Action *A, const ToolChain *TC, const char *BoundArch,
2109 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
2110 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
2111 bool BuildForOffloadDevice) const {
2112 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
2114 InputInfoList OffloadDependencesInputInfo;
2115 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
2116 // The offload action is expected to be used in four different situations.
2118 // a) Set a toolchain/architecture/kind for a host action:
2119 // Host Action 1 -> OffloadAction -> Host Action 2
2121 // b) Set a toolchain/architecture/kind for a device action;
2122 // Device Action 1 -> OffloadAction -> Device Action 2
2124 // c) Specify a device dependences to a host action;
2125 // Device Action 1 _
2127 // Host Action 1 ---> OffloadAction -> Host Action 2
2129 // d) Specify a host dependence to a device action.
2132 // Device Action 1 ---> OffloadAction -> Device Action 2
2134 // For a) and b), we just return the job generated for the dependence. For
2135 // c) and d) we override the current action with the host/device dependence
2136 // if the current toolchain is host/device and set the offload dependences
2137 // info with the jobs obtained from the device/host dependence(s).
2139 // If there is a single device option, just generate the job for it.
2140 if (OA->hasSingleDeviceDependence()) {
2142 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
2143 const char *DepBoundArch) {
2145 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
2146 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
2147 CachedResults, /*BuildForOffloadDevice=*/true);
2152 // If 'Action 2' is host, we generate jobs for the device dependences and
2153 // override the current action with the host dependence. Otherwise, we
2154 // generate the host dependences and override the action with the device
2155 // dependence. The dependences can't therefore be a top-level action.
2156 OA->doOnEachDependence(
2157 /*IsHostDependence=*/BuildForOffloadDevice,
2158 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
2159 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
2160 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
2161 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
2162 /*BuildForOffloadDevice=*/DepA->getOffloadingDeviceKind() !=
2166 A = BuildForOffloadDevice
2167 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
2168 : OA->getHostDependence();
2171 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
2172 // FIXME: It would be nice to not claim this here; maybe the old scheme of
2173 // just using Args was better?
2174 const Arg &Input = IA->getInputArg();
2176 if (Input.getOption().matches(options::OPT_INPUT)) {
2177 const char *Name = Input.getValue();
2178 return InputInfo(A, Name, /* BaseInput = */ Name);
2180 return InputInfo(A, &Input, /* BaseInput = */ "");
2183 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
2184 const ToolChain *TC;
2185 const char *ArchName = BAA->getArchName();
2188 TC = &getToolChain(C.getArgs(),
2189 computeTargetTriple(*this, DefaultTargetTriple,
2190 C.getArgs(), ArchName));
2192 TC = &C.getDefaultToolChain();
2194 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
2195 MultipleArchs, LinkingOutput, CachedResults,
2196 BuildForOffloadDevice);
2200 const ActionList *Inputs = &A->getInputs();
2202 const JobAction *JA = cast<JobAction>(A);
2203 ActionList CollapsedOffloadActions;
2206 selectToolForJob(C, isSaveTempsEnabled(), embedBitcodeEnabled(), TC, JA,
2207 Inputs, CollapsedOffloadActions);
2211 // If we've collapsed action list that contained OffloadAction we
2212 // need to build jobs for host/device-side inputs it may have held.
2213 for (const auto *OA : CollapsedOffloadActions)
2214 cast<OffloadAction>(OA)->doOnEachDependence(
2215 /*IsHostDependence=*/BuildForOffloadDevice,
2216 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
2217 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
2218 C, DepA, DepTC, DepBoundArch, AtTopLevel,
2219 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
2220 /*BuildForOffloadDevice=*/DepA->getOffloadingDeviceKind() !=
2224 // Only use pipes when there is exactly one input.
2225 InputInfoList InputInfos;
2226 for (const Action *Input : *Inputs) {
2227 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
2228 // shouldn't get temporary output names.
2229 // FIXME: Clean this up.
2230 bool SubJobAtTopLevel =
2231 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
2232 InputInfos.push_back(BuildJobsForAction(
2233 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
2234 CachedResults, BuildForOffloadDevice));
2237 // Always use the first input as the base input.
2238 const char *BaseInput = InputInfos[0].getBaseInput();
2240 // ... except dsymutil actions, which use their actual input as the base
2242 if (JA->getType() == types::TY_dSYM)
2243 BaseInput = InputInfos[0].getFilename();
2245 // Append outputs of offload device jobs to the input list
2246 if (!OffloadDependencesInputInfo.empty())
2247 InputInfos.append(OffloadDependencesInputInfo.begin(),
2248 OffloadDependencesInputInfo.end());
2250 // Determine the place to write output to, if any.
2252 if (JA->getType() == types::TY_Nothing)
2253 Result = InputInfo(A, BaseInput);
2255 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
2256 AtTopLevel, MultipleArchs,
2257 TC->getTriple().normalize()),
2260 if (CCCPrintBindings && !CCGenDiagnostics) {
2261 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
2262 << " - \"" << T->getName() << "\", inputs: [";
2263 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
2264 llvm::errs() << InputInfos[i].getAsString();
2266 llvm::errs() << ", ";
2268 llvm::errs() << "], output: " << Result.getAsString() << "\n";
2270 T->ConstructJob(C, *JA, Result, InputInfos,
2271 C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
2276 const char *Driver::getDefaultImageName() const {
2277 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
2278 return Target.isOSWindows() ? "a.exe" : "a.out";
2281 /// \brief Create output filename based on ArgValue, which could either be a
2282 /// full filename, filename without extension, or a directory. If ArgValue
2283 /// does not provide a filename, then use BaseName, and use the extension
2284 /// suitable for FileType.
2285 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
2287 types::ID FileType) {
2288 SmallString<128> Filename = ArgValue;
2290 if (ArgValue.empty()) {
2291 // If the argument is empty, output to BaseName in the current dir.
2292 Filename = BaseName;
2293 } else if (llvm::sys::path::is_separator(Filename.back())) {
2294 // If the argument is a directory, output to BaseName in that dir.
2295 llvm::sys::path::append(Filename, BaseName);
2298 if (!llvm::sys::path::has_extension(ArgValue)) {
2299 // If the argument didn't provide an extension, then set it.
2300 const char *Extension = types::getTypeTempSuffix(FileType, true);
2302 if (FileType == types::TY_Image &&
2303 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
2304 // The output file is a dll.
2308 llvm::sys::path::replace_extension(Filename, Extension);
2311 return Args.MakeArgString(Filename.c_str());
2314 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
2315 const char *BaseInput,
2316 const char *BoundArch, bool AtTopLevel,
2318 StringRef NormalizedTriple) const {
2319 llvm::PrettyStackTraceString CrashInfo("Computing output path");
2320 // Output to a user requested destination?
2321 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
2322 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
2323 return C.addResultFile(FinalOutput->getValue(), &JA);
2326 // For /P, preprocess to file named after BaseInput.
2327 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
2328 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
2329 StringRef BaseName = llvm::sys::path::filename(BaseInput);
2331 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
2332 NameArg = A->getValue();
2333 return C.addResultFile(
2334 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
2338 // Default to writing to stdout?
2339 if (AtTopLevel && !CCGenDiagnostics &&
2340 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
2343 // Is this the assembly listing for /FA?
2344 if (JA.getType() == types::TY_PP_Asm &&
2345 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
2346 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
2347 // Use /Fa and the input filename to determine the asm file name.
2348 StringRef BaseName = llvm::sys::path::filename(BaseInput);
2349 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
2350 return C.addResultFile(
2351 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
2355 // Output to a temporary file?
2356 if ((!AtTopLevel && !isSaveTempsEnabled() &&
2357 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
2359 StringRef Name = llvm::sys::path::filename(BaseInput);
2360 std::pair<StringRef, StringRef> Split = Name.split('.');
2361 std::string TmpName = GetTemporaryPath(
2362 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
2363 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
2366 SmallString<128> BasePath(BaseInput);
2369 // Dsymutil actions should use the full path.
2370 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
2371 BaseName = BasePath;
2373 BaseName = llvm::sys::path::filename(BasePath);
2375 // Determine what the derived output name should be.
2376 const char *NamedOutput;
2378 if (JA.getType() == types::TY_Object &&
2379 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
2380 // The /Fo or /o flag decides the object filename.
2383 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
2386 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
2387 } else if (JA.getType() == types::TY_Image &&
2388 C.getArgs().hasArg(options::OPT__SLASH_Fe,
2389 options::OPT__SLASH_o)) {
2390 // The /Fe or /o flag names the linked file.
2393 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
2396 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
2397 } else if (JA.getType() == types::TY_Image) {
2399 // clang-cl uses BaseName for the executable name.
2401 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
2402 } else if (MultipleArchs && BoundArch) {
2403 SmallString<128> Output(getDefaultImageName());
2404 Output += JA.getOffloadingFileNamePrefix(NormalizedTriple);
2406 Output.append(BoundArch);
2407 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
2409 NamedOutput = getDefaultImageName();
2411 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
2412 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName).c_str());
2414 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
2415 assert(Suffix && "All types used for output should have a suffix.");
2417 std::string::size_type End = std::string::npos;
2418 if (!types::appendSuffixForType(JA.getType()))
2419 End = BaseName.rfind('.');
2420 SmallString<128> Suffixed(BaseName.substr(0, End));
2421 Suffixed += JA.getOffloadingFileNamePrefix(NormalizedTriple);
2422 if (MultipleArchs && BoundArch) {
2424 Suffixed.append(BoundArch);
2426 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
2427 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
2428 // optimized bitcode output.
2429 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
2430 JA.getType() == types::TY_LLVM_BC)
2434 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
2437 // Prepend object file path if -save-temps=obj
2438 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
2439 JA.getType() != types::TY_PCH) {
2440 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2441 SmallString<128> TempPath(FinalOutput->getValue());
2442 llvm::sys::path::remove_filename(TempPath);
2443 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
2444 llvm::sys::path::append(TempPath, OutputFileName);
2445 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
2448 // If we're saving temps and the temp file conflicts with the input file,
2449 // then avoid overwriting input file.
2450 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
2451 bool SameFile = false;
2452 SmallString<256> Result;
2453 llvm::sys::fs::current_path(Result);
2454 llvm::sys::path::append(Result, BaseName);
2455 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
2456 // Must share the same path to conflict.
2458 StringRef Name = llvm::sys::path::filename(BaseInput);
2459 std::pair<StringRef, StringRef> Split = Name.split('.');
2460 std::string TmpName = GetTemporaryPath(
2461 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
2462 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
2466 // As an annoying special case, PCH generation doesn't strip the pathname.
2467 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
2468 llvm::sys::path::remove_filename(BasePath);
2469 if (BasePath.empty())
2470 BasePath = NamedOutput;
2472 llvm::sys::path::append(BasePath, NamedOutput);
2473 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
2475 return C.addResultFile(NamedOutput, &JA);
2479 std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
2480 // Respect a limited subset of the '-Bprefix' functionality in GCC by
2481 // attempting to use this prefix when looking for file paths.
2482 for (const std::string &Dir : PrefixDirs) {
2485 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
2486 llvm::sys::path::append(P, Name);
2487 if (llvm::sys::fs::exists(Twine(P)))
2491 SmallString<128> P(ResourceDir);
2492 llvm::sys::path::append(P, Name);
2493 if (llvm::sys::fs::exists(Twine(P)))
2496 for (const std::string &Dir : TC.getFilePaths()) {
2499 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
2500 llvm::sys::path::append(P, Name);
2501 if (llvm::sys::fs::exists(Twine(P)))
2508 void Driver::generatePrefixedToolNames(
2509 const char *Tool, const ToolChain &TC,
2510 SmallVectorImpl<std::string> &Names) const {
2511 // FIXME: Needs a better variable than DefaultTargetTriple
2512 Names.emplace_back(DefaultTargetTriple + "-" + Tool);
2513 Names.emplace_back(Tool);
2515 // Allow the discovery of tools prefixed with LLVM's default target triple.
2516 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
2517 if (LLVMDefaultTargetTriple != DefaultTargetTriple)
2518 Names.emplace_back(LLVMDefaultTargetTriple + "-" + Tool);
2521 static bool ScanDirForExecutable(SmallString<128> &Dir,
2522 ArrayRef<std::string> Names) {
2523 for (const auto &Name : Names) {
2524 llvm::sys::path::append(Dir, Name);
2525 if (llvm::sys::fs::can_execute(Twine(Dir)))
2527 llvm::sys::path::remove_filename(Dir);
2532 std::string Driver::GetProgramPath(const char *Name,
2533 const ToolChain &TC) const {
2534 SmallVector<std::string, 2> TargetSpecificExecutables;
2535 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
2537 // Respect a limited subset of the '-Bprefix' functionality in GCC by
2538 // attempting to use this prefix when looking for program paths.
2539 for (const auto &PrefixDir : PrefixDirs) {
2540 if (llvm::sys::fs::is_directory(PrefixDir)) {
2541 SmallString<128> P(PrefixDir);
2542 if (ScanDirForExecutable(P, TargetSpecificExecutables))
2545 SmallString<128> P(PrefixDir + Name);
2546 if (llvm::sys::fs::can_execute(Twine(P)))
2551 const ToolChain::path_list &List = TC.getProgramPaths();
2552 for (const auto &Path : List) {
2553 SmallString<128> P(Path);
2554 if (ScanDirForExecutable(P, TargetSpecificExecutables))
2558 // If all else failed, search the path.
2559 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
2560 if (llvm::ErrorOr<std::string> P =
2561 llvm::sys::findProgramByName(TargetSpecificExecutable))
2567 std::string Driver::GetTemporaryPath(StringRef Prefix,
2568 const char *Suffix) const {
2569 SmallString<128> Path;
2570 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
2572 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
2579 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
2580 SmallString<128> Output;
2581 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
2582 // FIXME: If anybody needs it, implement this obscure rule:
2583 // "If you specify a directory without a file name, the default file name
2584 // is VCx0.pch., where x is the major version of Visual C++ in use."
2585 Output = FpArg->getValue();
2587 // "If you do not specify an extension as part of the path name, an
2588 // extension of .pch is assumed. "
2589 if (!llvm::sys::path::has_extension(Output))
2593 llvm::sys::path::replace_extension(Output, ".pch");
2595 return Output.str();
2598 const ToolChain &Driver::getToolChain(const ArgList &Args,
2599 const llvm::Triple &Target) const {
2601 ToolChain *&TC = ToolChains[Target.str()];
2603 switch (Target.getOS()) {
2604 case llvm::Triple::Haiku:
2605 TC = new toolchains::Haiku(*this, Target, Args);
2607 case llvm::Triple::CloudABI:
2608 TC = new toolchains::CloudABI(*this, Target, Args);
2610 case llvm::Triple::Darwin:
2611 case llvm::Triple::MacOSX:
2612 case llvm::Triple::IOS:
2613 case llvm::Triple::TvOS:
2614 case llvm::Triple::WatchOS:
2615 TC = new toolchains::DarwinClang(*this, Target, Args);
2617 case llvm::Triple::DragonFly:
2618 TC = new toolchains::DragonFly(*this, Target, Args);
2620 case llvm::Triple::OpenBSD:
2621 TC = new toolchains::OpenBSD(*this, Target, Args);
2623 case llvm::Triple::Bitrig:
2624 TC = new toolchains::Bitrig(*this, Target, Args);
2626 case llvm::Triple::NetBSD:
2627 TC = new toolchains::NetBSD(*this, Target, Args);
2629 case llvm::Triple::FreeBSD:
2630 TC = new toolchains::FreeBSD(*this, Target, Args);
2632 case llvm::Triple::Minix:
2633 TC = new toolchains::Minix(*this, Target, Args);
2635 case llvm::Triple::Linux:
2636 case llvm::Triple::ELFIAMCU:
2637 if (Target.getArch() == llvm::Triple::hexagon)
2638 TC = new toolchains::HexagonToolChain(*this, Target, Args);
2639 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
2640 !Target.hasEnvironment())
2641 TC = new toolchains::MipsLLVMToolChain(*this, Target, Args);
2643 TC = new toolchains::Linux(*this, Target, Args);
2645 case llvm::Triple::NaCl:
2646 TC = new toolchains::NaClToolChain(*this, Target, Args);
2648 case llvm::Triple::Solaris:
2649 TC = new toolchains::Solaris(*this, Target, Args);
2651 case llvm::Triple::AMDHSA:
2652 TC = new toolchains::AMDGPUToolChain(*this, Target, Args);
2654 case llvm::Triple::Win32:
2655 switch (Target.getEnvironment()) {
2657 if (Target.isOSBinFormatELF())
2658 TC = new toolchains::Generic_ELF(*this, Target, Args);
2659 else if (Target.isOSBinFormatMachO())
2660 TC = new toolchains::MachO(*this, Target, Args);
2662 TC = new toolchains::Generic_GCC(*this, Target, Args);
2664 case llvm::Triple::GNU:
2665 TC = new toolchains::MinGW(*this, Target, Args);
2667 case llvm::Triple::Itanium:
2668 TC = new toolchains::CrossWindowsToolChain(*this, Target, Args);
2670 case llvm::Triple::MSVC:
2671 case llvm::Triple::UnknownEnvironment:
2672 TC = new toolchains::MSVCToolChain(*this, Target, Args);
2676 case llvm::Triple::CUDA:
2677 TC = new toolchains::CudaToolChain(*this, Target, Args);
2679 case llvm::Triple::PS4:
2680 TC = new toolchains::PS4CPU(*this, Target, Args);
2683 // Of these targets, Hexagon is the only one that might have
2684 // an OS of Linux, in which case it got handled above already.
2685 switch (Target.getArch()) {
2686 case llvm::Triple::tce:
2687 TC = new toolchains::TCEToolChain(*this, Target, Args);
2689 case llvm::Triple::hexagon:
2690 TC = new toolchains::HexagonToolChain(*this, Target, Args);
2692 case llvm::Triple::lanai:
2693 TC = new toolchains::LanaiToolChain(*this, Target, Args);
2695 case llvm::Triple::xcore:
2696 TC = new toolchains::XCoreToolChain(*this, Target, Args);
2698 case llvm::Triple::wasm32:
2699 case llvm::Triple::wasm64:
2700 TC = new toolchains::WebAssembly(*this, Target, Args);
2703 if (Target.getVendor() == llvm::Triple::Myriad)
2704 TC = new toolchains::MyriadToolChain(*this, Target, Args);
2705 else if (Target.isOSBinFormatELF())
2706 TC = new toolchains::Generic_ELF(*this, Target, Args);
2707 else if (Target.isOSBinFormatMachO())
2708 TC = new toolchains::MachO(*this, Target, Args);
2710 TC = new toolchains::Generic_GCC(*this, Target, Args);
2717 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
2718 // Say "no" if there is not exactly one input of a type clang understands.
2719 if (JA.size() != 1 ||
2720 !types::isAcceptedByClang((*JA.input_begin())->getType()))
2723 // And say "no" if this is not a kind of action clang understands.
2724 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
2725 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
2731 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
2732 /// grouped values as integers. Numbers which are not provided are set to 0.
2734 /// \return True if the entire string was parsed (9.2), or all groups were
2735 /// parsed (10.3.5extrastuff).
2736 bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
2737 unsigned &Minor, unsigned &Micro,
2741 Major = Minor = Micro = 0;
2746 Major = (unsigned)strtol(Str, &End, 10);
2747 if (*Str != '\0' && *End == '\0')
2753 Minor = (unsigned)strtol(Str, &End, 10);
2754 if (*Str != '\0' && *End == '\0')
2760 Micro = (unsigned)strtol(Str, &End, 10);
2761 if (*Str != '\0' && *End == '\0')
2769 /// Parse digits from a string \p Str and fulfill \p Digits with
2770 /// the parsed numbers. This method assumes that the max number of
2771 /// digits to look for is equal to Digits.size().
2773 /// \return True if the entire string was parsed and there are
2774 /// no extra characters remaining at the end.
2775 bool Driver::GetReleaseVersion(const char *Str,
2776 MutableArrayRef<unsigned> Digits) {
2781 unsigned CurDigit = 0;
2782 while (CurDigit < Digits.size()) {
2783 unsigned Digit = (unsigned)strtol(Str, &End, 10);
2784 Digits[CurDigit] = Digit;
2785 if (*Str != '\0' && *End == '\0')
2787 if (*End != '.' || Str == End)
2793 // More digits than requested, bail out...
2797 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
2798 unsigned IncludedFlagsBitmask = 0;
2799 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
2801 if (Mode == CLMode) {
2802 // Include CL and Core options.
2803 IncludedFlagsBitmask |= options::CLOption;
2804 IncludedFlagsBitmask |= options::CoreOption;
2806 ExcludedFlagsBitmask |= options::CLOption;
2809 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
2812 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
2813 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);