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/StringExtras.h"
27 #include "llvm/ADT/StringSet.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/Option/Arg.h"
30 #include "llvm/Option/ArgList.h"
31 #include "llvm/Option/OptSpecifier.h"
32 #include "llvm/Option/OptTable.h"
33 #include "llvm/Option/Option.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/PrettyStackTrace.h"
39 #include "llvm/Support/Process.h"
40 #include "llvm/Support/Program.h"
41 #include "llvm/Support/raw_ostream.h"
45 using namespace clang::driver;
46 using namespace clang;
47 using namespace llvm::opt;
49 Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
50 DiagnosticsEngine &Diags,
51 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
52 : Opts(createDriverOptTable()), Diags(Diags), VFS(VFS), Mode(GCCMode),
53 SaveTemps(SaveTempsNone), LTOMode(LTOK_None),
54 ClangExecutable(ClangExecutable),
55 SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
56 DefaultTargetTriple(DefaultTargetTriple),
57 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
58 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
59 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
60 CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
61 CCCUsePCH(true), SuppressMissingInputWarning(false) {
63 // Provide a sane fallback if no VFS is specified.
65 this->VFS = vfs::getRealFileSystem();
67 Name = llvm::sys::path::filename(ClangExecutable);
68 Dir = llvm::sys::path::parent_path(ClangExecutable);
69 InstalledDir = Dir; // Provide a sensible default installed dir.
71 // Compute the path to the resource directory.
72 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
73 SmallString<128> P(Dir);
74 if (ClangResourceDir != "") {
75 llvm::sys::path::append(P, ClangResourceDir);
77 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
78 llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang",
79 CLANG_VERSION_STRING);
81 ResourceDir = P.str();
87 llvm::DeleteContainerSeconds(ToolChains);
90 void Driver::ParseDriverMode(ArrayRef<const char *> Args) {
91 const std::string OptName =
92 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
94 for (const char *ArgPtr : Args) {
95 // Ingore nullptrs, they are response file's EOL markers
96 if (ArgPtr == nullptr)
98 const StringRef Arg = ArgPtr;
99 if (!Arg.startswith(OptName))
102 const StringRef Value = Arg.drop_front(OptName.size());
103 const unsigned M = llvm::StringSwitch<unsigned>(Value)
104 .Case("gcc", GCCMode)
105 .Case("g++", GXXMode)
106 .Case("cpp", CPPMode)
111 Mode = static_cast<DriverMode>(M);
113 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
117 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
118 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
120 unsigned IncludedFlagsBitmask;
121 unsigned ExcludedFlagsBitmask;
122 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
123 getIncludeExcludeOptionFlagMasks();
125 unsigned MissingArgIndex, MissingArgCount;
127 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
128 IncludedFlagsBitmask, ExcludedFlagsBitmask);
130 // Check for missing argument error.
132 Diag(clang::diag::err_drv_missing_argument)
133 << Args.getArgString(MissingArgIndex) << MissingArgCount;
135 // Check for unsupported options.
136 for (const Arg *A : Args) {
137 if (A->getOption().hasFlag(options::Unsupported)) {
138 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
142 // Warn about -mcpu= without an argument.
143 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
144 Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
148 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
149 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
154 // Determine which compilation mode we are in. We look for options which
155 // affect the phase, starting with the earliest phases, and record which
156 // option we used to determine the final phase.
157 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
158 Arg **FinalPhaseArg) const {
159 Arg *PhaseArg = nullptr;
160 phases::ID FinalPhase;
162 // -{E,EP,P,M,MM} only run the preprocessor.
163 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
164 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
165 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
166 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
167 FinalPhase = phases::Preprocess;
169 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
170 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
171 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
172 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
173 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
174 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
175 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
176 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
177 options::OPT__analyze_auto)) ||
178 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
179 FinalPhase = phases::Compile;
181 // -S only runs up to the backend.
182 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
183 FinalPhase = phases::Backend;
185 // -c compilation only runs up to the assembler.
186 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
187 FinalPhase = phases::Assemble;
189 // Otherwise do everything.
191 FinalPhase = phases::Link;
194 *FinalPhaseArg = PhaseArg;
199 static Arg *MakeInputArg(DerivedArgList &Args, OptTable *Opts,
201 Arg *A = new Arg(Opts->getOption(options::OPT_INPUT), Value,
202 Args.getBaseArgs().MakeIndex(Value), Value.data());
203 Args.AddSynthesizedArg(A);
208 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
209 DerivedArgList *DAL = new DerivedArgList(Args);
211 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
212 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
213 for (Arg *A : Args) {
214 // Unfortunately, we have to parse some forwarding options (-Xassembler,
215 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
216 // (assembler and preprocessor), or bypass a previous driver ('collect2').
218 // Rewrite linker options, to replace --no-demangle with a custom internal
220 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
221 A->getOption().matches(options::OPT_Xlinker)) &&
222 A->containsValue("--no-demangle")) {
223 // Add the rewritten no-demangle argument.
224 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
226 // Add the remaining values as Xlinker arguments.
227 for (StringRef Val : A->getValues())
228 if (Val != "--no-demangle")
229 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
234 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
235 // some build systems. We don't try to be complete here because we don't
236 // care to encourage this usage model.
237 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
238 (A->getValue(0) == StringRef("-MD") ||
239 A->getValue(0) == StringRef("-MMD"))) {
240 // Rewrite to -MD/-MMD along with -MF.
241 if (A->getValue(0) == StringRef("-MD"))
242 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
244 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
245 if (A->getNumValues() == 2)
246 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
251 // Rewrite reserved library names.
252 if (A->getOption().matches(options::OPT_l)) {
253 StringRef Value = A->getValue();
255 // Rewrite unless -nostdlib is present.
256 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
257 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
261 // Rewrite unconditionally.
262 if (Value == "cc_kext") {
263 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
268 // Pick up inputs via the -- option.
269 if (A->getOption().matches(options::OPT__DASH_DASH)) {
271 for (StringRef Val : A->getValues())
272 DAL->append(MakeInputArg(*DAL, Opts, Val));
279 // Add a default value of -mlinker-version=, if one was given and the user
280 // didn't specify one.
281 #if defined(HOST_LINK_VERSION)
282 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
283 strlen(HOST_LINK_VERSION) > 0) {
284 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
286 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
293 /// \brief Compute target triple from args.
295 /// This routine provides the logic to compute a target triple from various
296 /// args passed to the driver and the default triple string.
297 static llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple,
299 StringRef DarwinArchName = "") {
300 // FIXME: Already done in Compilation *Driver::BuildCompilation
301 if (const Arg *A = Args.getLastArg(options::OPT_target))
302 DefaultTargetTriple = A->getValue();
304 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
306 // Handle Apple-specific options available here.
307 if (Target.isOSBinFormatMachO()) {
308 // If an explict Darwin arch name is given, that trumps all.
309 if (!DarwinArchName.empty()) {
310 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
314 // Handle the Darwin '-arch' flag.
315 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
316 StringRef ArchName = A->getValue();
317 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
321 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
322 // '-mbig-endian'/'-EB'.
323 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
324 options::OPT_mbig_endian)) {
325 if (A->getOption().matches(options::OPT_mlittle_endian)) {
326 llvm::Triple LE = Target.getLittleEndianArchVariant();
327 if (LE.getArch() != llvm::Triple::UnknownArch)
328 Target = std::move(LE);
330 llvm::Triple BE = Target.getBigEndianArchVariant();
331 if (BE.getArch() != llvm::Triple::UnknownArch)
332 Target = std::move(BE);
336 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
337 if (Target.getArch() == llvm::Triple::tce ||
338 Target.getOS() == llvm::Triple::Minix)
341 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
342 if (Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
343 options::OPT_m32, options::OPT_m16)) {
344 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
346 if (A->getOption().matches(options::OPT_m64)) {
347 AT = Target.get64BitArchVariant().getArch();
348 if (Target.getEnvironment() == llvm::Triple::GNUX32)
349 Target.setEnvironment(llvm::Triple::GNU);
350 } else if (A->getOption().matches(options::OPT_mx32) &&
351 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
352 AT = llvm::Triple::x86_64;
353 Target.setEnvironment(llvm::Triple::GNUX32);
354 } else if (A->getOption().matches(options::OPT_m32)) {
355 AT = Target.get32BitArchVariant().getArch();
356 if (Target.getEnvironment() == llvm::Triple::GNUX32)
357 Target.setEnvironment(llvm::Triple::GNU);
358 } else if (A->getOption().matches(options::OPT_m16) &&
359 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
360 AT = llvm::Triple::x86;
361 Target.setEnvironment(llvm::Triple::CODE16);
364 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
371 // \brief Parse the LTO options and record the type of LTO compilation
372 // based on which -f(no-)?lto(=.*)? option occurs last.
373 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
375 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
376 options::OPT_fno_lto, false))
379 StringRef LTOName("full");
381 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
383 LTOName = A->getValue();
385 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
386 .Case("full", LTOK_Full)
387 .Case("thin", LTOK_Thin)
388 .Default(LTOK_Unknown);
390 if (LTOMode == LTOK_Unknown) {
392 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
397 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
398 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
400 // FIXME: Handle environment options which affect driver behavior, somewhere
401 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
403 if (char *env = ::getenv("COMPILER_PATH")) {
404 StringRef CompilerPath = env;
405 while (!CompilerPath.empty()) {
406 std::pair<StringRef, StringRef> Split =
407 CompilerPath.split(llvm::sys::EnvPathSeparator);
408 PrefixDirs.push_back(Split.first);
409 CompilerPath = Split.second;
413 // We look for the driver mode option early, because the mode can affect
414 // how other options are parsed.
415 ParseDriverMode(ArgList.slice(1));
417 // FIXME: What are we going to do with -V and -b?
419 // FIXME: This stuff needs to go into the Compilation, not the driver.
422 InputArgList Args = ParseArgStrings(ArgList.slice(1));
424 // Silence driver warnings if requested
425 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
427 // -no-canonical-prefixes is used very early in main.
428 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
431 Args.ClaimAllArgs(options::OPT_pipe);
433 // Extract -ccc args.
435 // FIXME: We need to figure out where this behavior should live. Most of it
436 // should be outside in the client; the parts that aren't should have proper
437 // options, either by introducing new ones or by overloading gcc ones like -V
439 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
440 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
441 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
442 CCCGenericGCCName = A->getValue();
444 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
445 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
446 // and getToolChain is const.
448 // clang-cl targets MSVC-style Win32.
449 llvm::Triple T(DefaultTargetTriple);
450 T.setOS(llvm::Triple::Win32);
451 T.setVendor(llvm::Triple::PC);
452 T.setEnvironment(llvm::Triple::MSVC);
453 DefaultTargetTriple = T.str();
455 if (const Arg *A = Args.getLastArg(options::OPT_target))
456 DefaultTargetTriple = A->getValue();
457 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
458 Dir = InstalledDir = A->getValue();
459 for (const Arg *A : Args.filtered(options::OPT_B)) {
461 PrefixDirs.push_back(A->getValue(0));
463 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
464 SysRoot = A->getValue();
465 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
466 DyldPrefix = A->getValue();
467 if (Args.hasArg(options::OPT_nostdlib))
470 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
471 ResourceDir = A->getValue();
473 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
474 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
475 .Case("cwd", SaveTempsCwd)
476 .Case("obj", SaveTempsObj)
477 .Default(SaveTempsCwd);
482 std::unique_ptr<llvm::opt::InputArgList> UArgs =
483 llvm::make_unique<InputArgList>(std::move(Args));
485 // Perform the default argument translations.
486 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
488 // Owned by the host.
489 const ToolChain &TC =
490 getToolChain(*UArgs, computeTargetTriple(DefaultTargetTriple, *UArgs));
492 // The compilation takes ownership of Args.
493 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
495 C->setCudaDeviceToolChain(
496 &getToolChain(C->getArgs(), llvm::Triple(TC.getTriple().isArch64Bit()
497 ? "nvptx64-nvidia-cuda"
498 : "nvptx-nvidia-cuda")));
499 if (!HandleImmediateArgs(*C))
502 // Construct the list of inputs.
504 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
506 // Construct the list of abstract actions to perform for this compilation. On
507 // MachO targets this uses the driver-driver and universal actions.
508 if (TC.getTriple().isOSBinFormatMachO())
509 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
511 BuildActions(*C, C->getDefaultToolChain(), C->getArgs(), Inputs,
514 if (CCCPrintPhases) {
524 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
525 llvm::opt::ArgStringList ASL;
526 for (const auto *A : Args)
527 A->render(Args, ASL);
529 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
530 if (I != ASL.begin())
532 Command::printArg(OS, *I, true);
537 // When clang crashes, produce diagnostic information including the fully
538 // preprocessed source file(s). Request that the developer attach the
539 // diagnostic information to a bug report.
540 void Driver::generateCompilationDiagnostics(Compilation &C,
541 const Command &FailingCommand) {
542 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
545 // Don't try to generate diagnostics for link or dsymutil jobs.
546 if (FailingCommand.getCreator().isLinkJob() ||
547 FailingCommand.getCreator().isDsymutilJob())
550 // Print the version of the compiler.
551 PrintVersion(C, llvm::errs());
553 Diag(clang::diag::note_drv_command_failed_diag_msg)
554 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
555 "crash backtrace, preprocessed source, and associated run script.";
557 // Suppress driver output and emit preprocessor output to temp file.
559 CCGenDiagnostics = true;
561 // Save the original job command(s).
562 Command Cmd = FailingCommand;
564 // Keep track of whether we produce any errors while trying to produce
565 // preprocessed sources.
566 DiagnosticErrorTrap Trap(Diags);
568 // Suppress tool output.
569 C.initCompilationForDiagnostics();
571 // Construct the list of inputs.
573 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
575 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
576 bool IgnoreInput = false;
578 // Ignore input from stdin or any inputs that cannot be preprocessed.
579 // Check type first as not all linker inputs have a value.
580 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
582 } else if (!strcmp(it->second->getValue(), "-")) {
583 Diag(clang::diag::note_drv_command_failed_diag_msg)
584 << "Error generating preprocessed source(s) - "
585 "ignoring input from stdin.";
590 it = Inputs.erase(it);
597 if (Inputs.empty()) {
598 Diag(clang::diag::note_drv_command_failed_diag_msg)
599 << "Error generating preprocessed source(s) - "
600 "no preprocessable inputs.";
604 // Don't attempt to generate preprocessed files if multiple -arch options are
605 // used, unless they're all duplicates.
606 llvm::StringSet<> ArchNames;
607 for (const Arg *A : C.getArgs()) {
608 if (A->getOption().matches(options::OPT_arch)) {
609 StringRef ArchName = A->getValue();
610 ArchNames.insert(ArchName);
613 if (ArchNames.size() > 1) {
614 Diag(clang::diag::note_drv_command_failed_diag_msg)
615 << "Error generating preprocessed source(s) - cannot generate "
616 "preprocessed source with multiple -arch options.";
620 // Construct the list of abstract actions to perform for this compilation. On
621 // Darwin OSes this uses the driver-driver and builds universal actions.
622 const ToolChain &TC = C.getDefaultToolChain();
623 if (TC.getTriple().isOSBinFormatMachO())
624 BuildUniversalActions(C, TC, Inputs);
626 BuildActions(C, TC, C.getArgs(), Inputs, C.getActions());
630 // If there were errors building the compilation, quit now.
631 if (Trap.hasErrorOccurred()) {
632 Diag(clang::diag::note_drv_command_failed_diag_msg)
633 << "Error generating preprocessed source(s).";
637 // Generate preprocessed output.
638 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
639 C.ExecuteJobs(C.getJobs(), FailingCommands);
641 // If any of the preprocessing commands failed, clean up and exit.
642 if (!FailingCommands.empty()) {
643 if (!isSaveTempsEnabled())
644 C.CleanupFileList(C.getTempFiles(), true);
646 Diag(clang::diag::note_drv_command_failed_diag_msg)
647 << "Error generating preprocessed source(s).";
651 const ArgStringList &TempFiles = C.getTempFiles();
652 if (TempFiles.empty()) {
653 Diag(clang::diag::note_drv_command_failed_diag_msg)
654 << "Error generating preprocessed source(s).";
658 Diag(clang::diag::note_drv_command_failed_diag_msg)
659 << "\n********************\n\n"
660 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
661 "Preprocessed source(s) and associated run script(s) are located at:";
663 SmallString<128> VFS;
664 for (const char *TempFile : TempFiles) {
665 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
666 if (StringRef(TempFile).endswith(".cache")) {
667 // In some cases (modules) we'll dump extra data to help with reproducing
668 // the crash into a directory next to the output.
669 VFS = llvm::sys::path::filename(TempFile);
670 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
674 // Assume associated files are based off of the first temporary file.
675 CrashReportInfo CrashInfo(TempFiles[0], VFS);
677 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
679 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
681 Diag(clang::diag::note_drv_command_failed_diag_msg)
682 << "Error generating run script: " + Script + " " + EC.message();
684 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
685 << "# Driver args: ";
686 printArgList(ScriptOS, C.getInputArgs());
687 ScriptOS << "# Original command: ";
688 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
689 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
690 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
693 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
694 options::OPT_frewrite_map_file_EQ))
695 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
697 Diag(clang::diag::note_drv_command_failed_diag_msg)
698 << "\n\n********************";
701 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
702 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
703 // if the tool does not support response files, there is a chance/ that things
704 // will just work without a response file, so we silently just skip it.
705 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
706 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
709 std::string TmpName = GetTemporaryPath("response", "txt");
711 C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())));
714 int Driver::ExecuteCompilation(
716 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
717 // Just print if -### was present.
718 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
719 C.getJobs().Print(llvm::errs(), "\n", true);
723 // If there were errors building the compilation, quit now.
724 if (Diags.hasErrorOccurred())
727 // Set up response file names for each command, if necessary
728 for (auto &Job : C.getJobs())
729 setUpResponseFiles(C, Job);
731 C.ExecuteJobs(C.getJobs(), FailingCommands);
733 // Remove temp files.
734 C.CleanupFileList(C.getTempFiles());
736 // If the command succeeded, we are done.
737 if (FailingCommands.empty())
740 // Otherwise, remove result files and print extra information about abnormal
742 for (const auto &CmdPair : FailingCommands) {
743 int Res = CmdPair.first;
744 const Command *FailingCommand = CmdPair.second;
746 // Remove result files if we're not saving temps.
747 if (!isSaveTempsEnabled()) {
748 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
749 C.CleanupFileMap(C.getResultFiles(), JA, true);
751 // Failure result files are valid unless we crashed.
753 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
756 // Print extra information about abnormal failures, if possible.
758 // This is ad-hoc, but we don't want to be excessively noisy. If the result
759 // status was 1, assume the command failed normally. In particular, if it
760 // was the compiler then assume it gave a reasonable error code. Failures
761 // in other tools are less common, and they generally have worse
762 // diagnostics, so always print the diagnostic there.
763 const Tool &FailingTool = FailingCommand->getCreator();
765 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
766 // FIXME: See FIXME above regarding result code interpretation.
768 Diag(clang::diag::err_drv_command_signalled)
769 << FailingTool.getShortName();
771 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
778 void Driver::PrintHelp(bool ShowHidden) const {
779 unsigned IncludedFlagsBitmask;
780 unsigned ExcludedFlagsBitmask;
781 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
782 getIncludeExcludeOptionFlagMasks();
784 ExcludedFlagsBitmask |= options::NoDriverOption;
786 ExcludedFlagsBitmask |= HelpHidden;
788 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
789 IncludedFlagsBitmask, ExcludedFlagsBitmask);
792 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
793 // FIXME: The following handlers should use a callback mechanism, we don't
794 // know what the client would like to do.
795 OS << getClangFullVersion() << '\n';
796 const ToolChain &TC = C.getDefaultToolChain();
797 OS << "Target: " << TC.getTripleString() << '\n';
799 // Print the threading model.
800 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
801 // Don't print if the ToolChain would have barfed on it already
802 if (TC.isThreadModelSupported(A->getValue()))
803 OS << "Thread model: " << A->getValue();
805 OS << "Thread model: " << TC.getThreadModel();
808 // Print out the install directory.
809 OS << "InstalledDir: " << InstalledDir << '\n';
812 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
814 static void PrintDiagnosticCategories(raw_ostream &OS) {
815 // Skip the empty category.
816 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
818 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
821 bool Driver::HandleImmediateArgs(const Compilation &C) {
822 // The order these options are handled in gcc is all over the place, but we
823 // don't expect inconsistencies w.r.t. that to matter in practice.
825 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
826 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
830 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
831 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
832 // return an answer which matches our definition of __VERSION__.
834 // If we want to return a more correct answer some day, then we should
835 // introduce a non-pedantically GCC compatible mode to Clang in which we
836 // provide sensible definitions for -dumpversion, __VERSION__, etc.
837 llvm::outs() << "4.2.1\n";
841 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
842 PrintDiagnosticCategories(llvm::outs());
846 if (C.getArgs().hasArg(options::OPT_help) ||
847 C.getArgs().hasArg(options::OPT__help_hidden)) {
848 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
852 if (C.getArgs().hasArg(options::OPT__version)) {
853 // Follow gcc behavior and use stdout for --version and stderr for -v.
854 PrintVersion(C, llvm::outs());
858 if (C.getArgs().hasArg(options::OPT_v) ||
859 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
860 PrintVersion(C, llvm::errs());
861 SuppressMissingInputWarning = true;
864 const ToolChain &TC = C.getDefaultToolChain();
866 if (C.getArgs().hasArg(options::OPT_v))
867 TC.printVerboseInfo(llvm::errs());
869 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
870 llvm::outs() << "programs: =";
871 bool separator = false;
872 for (const std::string &Path : TC.getProgramPaths()) {
875 llvm::outs() << Path;
878 llvm::outs() << "\n";
879 llvm::outs() << "libraries: =" << ResourceDir;
881 StringRef sysroot = C.getSysRoot();
883 for (const std::string &Path : TC.getFilePaths()) {
884 // Always print a separator. ResourceDir was the first item shown.
886 // Interpretation of leading '=' is needed only for NetBSD.
888 llvm::outs() << sysroot << Path.substr(1);
890 llvm::outs() << Path;
892 llvm::outs() << "\n";
896 // FIXME: The following handlers should use a callback mechanism, we don't
897 // know what the client would like to do.
898 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
899 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
903 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
904 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
908 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
909 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
913 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
914 for (const Multilib &Multilib : TC.getMultilibs())
915 llvm::outs() << Multilib << "\n";
919 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
920 for (const Multilib &Multilib : TC.getMultilibs()) {
921 if (Multilib.gccSuffix().empty())
922 llvm::outs() << ".\n";
924 StringRef Suffix(Multilib.gccSuffix());
925 assert(Suffix.front() == '/');
926 llvm::outs() << Suffix.substr(1) << "\n";
934 // Display an action graph human-readably. Action A is the "sink" node
935 // and latest-occuring action. Traversal is in pre-order, visiting the
936 // inputs to each action before printing the action itself.
937 static unsigned PrintActions1(const Compilation &C, Action *A,
938 std::map<Action *, unsigned> &Ids) {
939 if (Ids.count(A)) // A was already visited.
943 llvm::raw_string_ostream os(str);
945 os << Action::getClassName(A->getKind()) << ", ";
946 if (InputAction *IA = dyn_cast<InputAction>(A)) {
947 os << "\"" << IA->getInputArg().getValue() << "\"";
948 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
949 os << '"' << BIA->getArchName() << '"' << ", {"
950 << PrintActions1(C, *BIA->begin(), Ids) << "}";
951 } else if (CudaDeviceAction *CDA = dyn_cast<CudaDeviceAction>(A)) {
952 os << '"' << CDA->getGpuArchName() << '"' << ", {"
953 << PrintActions1(C, *CDA->begin(), Ids) << "}";
955 const ActionList *AL;
956 if (CudaHostAction *CHA = dyn_cast<CudaHostAction>(A)) {
957 os << "{" << PrintActions1(C, *CHA->begin(), Ids) << "}"
958 << ", gpu binaries ";
959 AL = &CHA->getDeviceActions();
961 AL = &A->getInputs();
964 const char *Prefix = "{";
965 for (Action *PreRequisite : *AL) {
966 os << Prefix << PrintActions1(C, PreRequisite, Ids);
974 unsigned Id = Ids.size();
976 llvm::errs() << Id << ": " << os.str() << ", "
977 << types::getTypeName(A->getType()) << "\n";
982 // Print the action graphs in a compilation C.
983 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
984 void Driver::PrintActions(const Compilation &C) const {
985 std::map<Action *, unsigned> Ids;
986 for (Action *A : C.getActions())
987 PrintActions1(C, A, Ids);
990 /// \brief Check whether the given input tree contains any compilation or
991 /// assembly actions.
992 static bool ContainsCompileOrAssembleAction(const Action *A) {
993 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
994 isa<AssembleJobAction>(A))
997 for (const Action *Input : *A)
998 if (ContainsCompileOrAssembleAction(Input))
1004 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1005 const InputList &BAInputs) const {
1006 DerivedArgList &Args = C.getArgs();
1007 ActionList &Actions = C.getActions();
1008 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1009 // Collect the list of architectures. Duplicates are allowed, but should only
1010 // be handled once (in the order seen).
1011 llvm::StringSet<> ArchNames;
1012 SmallVector<const char *, 4> Archs;
1013 for (Arg *A : Args) {
1014 if (A->getOption().matches(options::OPT_arch)) {
1015 // Validate the option here; we don't save the type here because its
1016 // particular spelling may participate in other driver choices.
1017 llvm::Triple::ArchType Arch =
1018 tools::darwin::getArchTypeForMachOArchName(A->getValue());
1019 if (Arch == llvm::Triple::UnknownArch) {
1020 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1025 if (ArchNames.insert(A->getValue()).second)
1026 Archs.push_back(A->getValue());
1030 // When there is no explicit arch for this platform, make sure we still bind
1031 // the architecture (to the default) so that -Xarch_ is handled correctly.
1033 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1035 ActionList SingleActions;
1036 BuildActions(C, TC, Args, BAInputs, SingleActions);
1038 // Add in arch bindings for every top level action, as well as lipo and
1039 // dsymutil steps if needed.
1040 for (Action* Act : SingleActions) {
1041 // Make sure we can lipo this kind of output. If not (and it is an actual
1042 // output) then we disallow, since we can't create an output file with the
1043 // right name without overwriting it. We could remove this oddity by just
1044 // changing the output names to include the arch, which would also fix
1045 // -save-temps. Compatibility wins for now.
1047 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1048 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1049 << types::getTypeName(Act->getType());
1052 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1053 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
1055 // Lipo if necessary, we do it this way because we need to set the arch flag
1056 // so that -Xarch_ gets overwritten.
1057 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1058 Actions.append(Inputs.begin(), Inputs.end());
1060 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
1062 // Handle debug info queries.
1063 Arg *A = Args.getLastArg(options::OPT_g_Group);
1064 if (A && !A->getOption().matches(options::OPT_g0) &&
1065 !A->getOption().matches(options::OPT_gstabs) &&
1066 ContainsCompileOrAssembleAction(Actions.back())) {
1068 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1069 // have a compile input. We need to run 'dsymutil' ourselves in such cases
1070 // because the debug info will refer to a temporary object file which
1071 // will be removed at the end of the compilation process.
1072 if (Act->getType() == types::TY_Image) {
1074 Inputs.push_back(Actions.back());
1077 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
1080 // Verify the debug info output.
1081 if (Args.hasArg(options::OPT_verify_debug_info)) {
1082 Action* LastAction = Actions.back();
1084 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1085 LastAction, types::TY_Nothing));
1091 /// \brief Check that the file referenced by Value exists. If it doesn't,
1092 /// issue a diagnostic and return false.
1093 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
1095 if (!D.getCheckInputsExist())
1098 // stdin always exists.
1102 SmallString<64> Path(Value);
1103 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1104 if (!llvm::sys::path::is_absolute(Path)) {
1105 SmallString<64> Directory(WorkDir->getValue());
1106 llvm::sys::path::append(Directory, Value);
1107 Path.assign(Directory);
1111 if (llvm::sys::fs::exists(Twine(Path)))
1114 if (D.IsCLMode() && !llvm::sys::path::is_absolute(Twine(Path)) &&
1115 llvm::sys::Process::FindInEnvPath("LIB", Value))
1118 D.Diag(clang::diag::err_drv_no_such_file) << Path;
1122 // Construct a the list of inputs and their types.
1123 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
1124 InputList &Inputs) const {
1125 // Track the current user specified (-x) input. We also explicitly track the
1126 // argument used to set the type; we only want to claim the type when we
1127 // actually use it, so we warn about unused -x arguments.
1128 types::ID InputType = types::TY_Nothing;
1129 Arg *InputTypeArg = nullptr;
1131 // The last /TC or /TP option sets the input type to C or C++ globally.
1132 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1133 options::OPT__SLASH_TP)) {
1134 InputTypeArg = TCTP;
1135 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
1140 Args.filtered_begin(options::OPT__SLASH_TC, options::OPT__SLASH_TP);
1141 const arg_iterator ie = Args.filtered_end();
1142 Arg *Previous = *it++;
1143 bool ShowNote = false;
1145 Diag(clang::diag::warn_drv_overriding_flag_option)
1146 << Previous->getSpelling() << (*it)->getSpelling();
1151 Diag(clang::diag::note_drv_t_option_is_global);
1153 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1154 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1157 for (Arg *A : Args) {
1158 if (A->getOption().getKind() == Option::InputClass) {
1159 const char *Value = A->getValue();
1160 types::ID Ty = types::TY_INVALID;
1162 // Infer the input type if necessary.
1163 if (InputType == types::TY_Nothing) {
1164 // If there was an explicit arg for this, claim it.
1166 InputTypeArg->claim();
1168 // stdin must be handled specially.
1169 if (memcmp(Value, "-", 2) == 0) {
1170 // If running with -E, treat as a C input (this changes the builtin
1171 // macros, for example). This may be overridden by -ObjC below.
1173 // Otherwise emit an error but still use a valid type to avoid
1174 // spurious errors (e.g., no inputs).
1175 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
1176 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1177 : clang::diag::err_drv_unknown_stdin_type);
1180 // Otherwise lookup by extension.
1181 // Fallback is C if invoked as C preprocessor or Object otherwise.
1182 // We use a host hook here because Darwin at least has its own
1183 // idea of what .s is.
1184 if (const char *Ext = strrchr(Value, '.'))
1185 Ty = TC.LookupTypeForExtension(Ext + 1);
1187 if (Ty == types::TY_INVALID) {
1191 Ty = types::TY_Object;
1194 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1195 // should autodetect some input files as C++ for g++ compatibility.
1197 types::ID OldTy = Ty;
1198 Ty = types::lookupCXXTypeForCType(Ty);
1201 Diag(clang::diag::warn_drv_treating_input_as_cxx)
1202 << getTypeName(OldTy) << getTypeName(Ty);
1206 // -ObjC and -ObjC++ override the default language, but only for "source
1207 // files". We just treat everything that isn't a linker input as a
1210 // FIXME: Clean this up if we move the phase sequence into the type.
1211 if (Ty != types::TY_Object) {
1212 if (Args.hasArg(options::OPT_ObjC))
1213 Ty = types::TY_ObjC;
1214 else if (Args.hasArg(options::OPT_ObjCXX))
1215 Ty = types::TY_ObjCXX;
1218 assert(InputTypeArg && "InputType set w/o InputTypeArg");
1219 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1220 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1222 const char *Ext = strrchr(Value, '.');
1223 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1224 Ty = types::TY_Object;
1226 if (Ty == types::TY_INVALID) {
1228 InputTypeArg->claim();
1232 if (DiagnoseInputExistence(*this, Args, Value))
1233 Inputs.push_back(std::make_pair(Ty, A));
1235 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1236 StringRef Value = A->getValue();
1237 if (DiagnoseInputExistence(*this, Args, Value)) {
1238 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1239 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1242 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1243 StringRef Value = A->getValue();
1244 if (DiagnoseInputExistence(*this, Args, Value)) {
1245 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1246 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1249 } else if (A->getOption().hasFlag(options::LinkerInput)) {
1250 // Just treat as object type, we could make a special type for this if
1252 Inputs.push_back(std::make_pair(types::TY_Object, A));
1254 } else if (A->getOption().matches(options::OPT_x)) {
1256 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
1259 // Follow gcc behavior and treat as linker input for invalid -x
1260 // options. Its not clear why we shouldn't just revert to unknown; but
1261 // this isn't very important, we might as well be bug compatible.
1263 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
1264 InputType = types::TY_Object;
1268 if (CCCIsCPP() && Inputs.empty()) {
1269 // If called as standalone preprocessor, stdin is processed
1270 // if no other input is present.
1271 Arg *A = MakeInputArg(Args, Opts, "-");
1272 Inputs.push_back(std::make_pair(types::TY_C, A));
1276 // For each unique --cuda-gpu-arch= argument creates a TY_CUDA_DEVICE
1277 // input action and then wraps each in CudaDeviceAction paired with
1278 // appropriate GPU arch name. In case of partial (i.e preprocessing
1279 // only) or device-only compilation, each device action is added to /p
1280 // Actions and /p Current is released. Otherwise the function creates
1281 // and returns a new CudaHostAction which wraps /p Current and device
1283 static Action *buildCudaActions(Compilation &C, DerivedArgList &Args,
1284 const Arg *InputArg, Action *HostAction,
1285 ActionList &Actions) {
1286 Arg *PartialCompilationArg = Args.getLastArg(options::OPT_cuda_host_only,
1287 options::OPT_cuda_device_only);
1288 // Host-only compilation case.
1289 if (PartialCompilationArg &&
1290 PartialCompilationArg->getOption().matches(options::OPT_cuda_host_only))
1291 return C.MakeAction<CudaHostAction>(HostAction, ActionList());
1293 // Collect all cuda_gpu_arch parameters, removing duplicates.
1294 SmallVector<const char *, 4> GpuArchList;
1295 llvm::StringSet<> GpuArchNames;
1296 for (Arg *A : Args) {
1297 if (!A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
1301 const auto& Arch = A->getValue();
1302 if (!CudaDeviceAction::IsValidGpuArchName(Arch))
1303 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << Arch;
1304 else if (GpuArchNames.insert(Arch).second)
1305 GpuArchList.push_back(Arch);
1308 // Default to sm_20 which is the lowest common denominator for supported GPUs.
1309 // sm_20 code should work correctly, if suboptimally, on all newer GPUs.
1310 if (GpuArchList.empty())
1311 GpuArchList.push_back("sm_20");
1313 // Replicate inputs for each GPU architecture.
1314 Driver::InputList CudaDeviceInputs;
1315 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1316 CudaDeviceInputs.push_back(std::make_pair(types::TY_CUDA_DEVICE, InputArg));
1318 // Build actions for all device inputs.
1319 assert(C.getCudaDeviceToolChain() &&
1320 "Missing toolchain for device-side compilation.");
1321 ActionList CudaDeviceActions;
1322 C.getDriver().BuildActions(C, *C.getCudaDeviceToolChain(), Args,
1323 CudaDeviceInputs, CudaDeviceActions);
1324 assert(GpuArchList.size() == CudaDeviceActions.size() &&
1325 "Failed to create actions for all devices");
1327 // Check whether any of device actions stopped before they could generate PTX.
1328 bool PartialCompilation =
1329 llvm::any_of(CudaDeviceActions, [](const Action *a) {
1330 return a->getKind() != Action::BackendJobClass;
1333 // Figure out what to do with device actions -- pass them as inputs to the
1334 // host action or run each of them independently.
1335 bool DeviceOnlyCompilation = PartialCompilationArg != nullptr;
1336 if (PartialCompilation || DeviceOnlyCompilation) {
1337 // In case of partial or device-only compilation results of device actions
1338 // are not consumed by the host action device actions have to be added to
1339 // top-level actions list with AtTopLevel=true and run independently.
1341 // -o is ambiguous if we have more than one top-level action.
1342 if (Args.hasArg(options::OPT_o) &&
1343 (!DeviceOnlyCompilation || GpuArchList.size() > 1)) {
1345 clang::diag::err_drv_output_argument_with_multiple_files);
1349 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1350 Actions.push_back(C.MakeAction<CudaDeviceAction>(CudaDeviceActions[I],
1352 /* AtTopLevel */ true));
1353 // Kill host action in case of device-only compilation.
1354 if (DeviceOnlyCompilation)
1359 // Outputs of device actions during complete CUDA compilation get created
1360 // with AtTopLevel=false and become inputs for the host action.
1361 ActionList DeviceActions;
1362 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1363 DeviceActions.push_back(
1364 C.MakeAction<CudaDeviceAction>(CudaDeviceActions[I], GpuArchList[I],
1365 /* AtTopLevel */ false));
1366 // Return a new host action that incorporates original host action and all
1368 return C.MakeAction<CudaHostAction>(HostAction, DeviceActions);
1371 void Driver::BuildActions(Compilation &C, const ToolChain &TC,
1372 DerivedArgList &Args, const InputList &Inputs,
1373 ActionList &Actions) const {
1374 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
1376 if (!SuppressMissingInputWarning && Inputs.empty()) {
1377 Diag(clang::diag::err_drv_no_input_files);
1382 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
1384 if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) {
1385 Diag(clang::diag::err_drv_emit_llvm_link);
1388 // Reject -Z* at the top level, these options should never have been exposed
1390 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
1391 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
1393 // Diagnose misuse of /Fo.
1394 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
1395 StringRef V = A->getValue();
1396 if (Inputs.size() > 1 && !V.empty() &&
1397 !llvm::sys::path::is_separator(V.back())) {
1398 // Check whether /Fo tries to name an output file for multiple inputs.
1399 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
1400 << A->getSpelling() << V;
1401 Args.eraseArg(options::OPT__SLASH_Fo);
1405 // Diagnose misuse of /Fa.
1406 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
1407 StringRef V = A->getValue();
1408 if (Inputs.size() > 1 && !V.empty() &&
1409 !llvm::sys::path::is_separator(V.back())) {
1410 // Check whether /Fa tries to name an asm file for multiple inputs.
1411 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
1412 << A->getSpelling() << V;
1413 Args.eraseArg(options::OPT__SLASH_Fa);
1417 // Diagnose misuse of /o.
1418 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
1419 if (A->getValue()[0] == '\0') {
1420 // It has to have a value.
1421 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
1422 Args.eraseArg(options::OPT__SLASH_o);
1426 // Construct the actions to perform.
1427 ActionList LinkerInputs;
1429 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
1430 for (auto &I : Inputs) {
1431 types::ID InputType = I.first;
1432 const Arg *InputArg = I.second;
1435 types::getCompilationPhases(InputType, PL);
1437 // If the first step comes after the final phase we are doing as part of
1438 // this compilation, warn the user about it.
1439 phases::ID InitialPhase = PL[0];
1440 if (InitialPhase > FinalPhase) {
1441 // Claim here to avoid the more general unused warning.
1444 // Suppress all unused style warnings with -Qunused-arguments
1445 if (Args.hasArg(options::OPT_Qunused_arguments))
1448 // Special case when final phase determined by binary name, rather than
1449 // by a command-line argument with a corresponding Arg.
1451 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
1452 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
1453 // Special case '-E' warning on a previously preprocessed file to make
1455 else if (InitialPhase == phases::Compile &&
1456 FinalPhase == phases::Preprocess &&
1457 getPreprocessedType(InputType) == types::TY_INVALID)
1458 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
1459 << InputArg->getAsString(Args) << !!FinalPhaseArg
1460 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
1462 Diag(clang::diag::warn_drv_input_file_unused)
1463 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
1465 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
1469 phases::ID CudaInjectionPhase =
1470 (phases::Compile < FinalPhase &&
1471 llvm::find(PL, phases::Compile) != PL.end())
1475 // Build the pipeline for this file.
1476 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
1477 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
1479 phases::ID Phase = *i;
1481 // We are done if this step is past what the user requested.
1482 if (Phase > FinalPhase)
1485 // Queue linker inputs.
1486 if (Phase == phases::Link) {
1487 assert((i + 1) == e && "linking must be final compilation step.");
1488 LinkerInputs.push_back(Current);
1493 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
1494 // encode this in the steps because the intermediate type depends on
1495 // arguments. Just special case here.
1496 if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
1499 // Otherwise construct the appropriate action.
1500 Current = ConstructPhaseAction(C, TC, Args, Phase, Current);
1502 if (InputType == types::TY_CUDA && Phase == CudaInjectionPhase) {
1503 Current = buildCudaActions(C, Args, InputArg, Current, Actions);
1508 if (Current->getType() == types::TY_Nothing)
1512 // If we ended with something, add to the output list.
1514 Actions.push_back(Current);
1517 // Add a link action if necessary.
1518 if (!LinkerInputs.empty())
1520 C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image));
1522 // If we are linking, claim any options which are obviously only used for
1524 if (FinalPhase == phases::Link && PL.size() == 1) {
1525 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
1526 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
1529 // Claim ignored clang-cl options.
1530 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
1532 // Claim --cuda-host-only arg which may be passed to non-CUDA
1533 // compilations and should not trigger warnings there.
1534 Args.ClaimAllArgs(options::OPT_cuda_host_only);
1537 Action *Driver::ConstructPhaseAction(Compilation &C, const ToolChain &TC,
1538 const ArgList &Args, phases::ID Phase,
1539 Action *Input) const {
1540 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
1541 // Build the appropriate action.
1544 llvm_unreachable("link action invalid here.");
1545 case phases::Preprocess: {
1547 // -{M, MM} alter the output type.
1548 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
1549 OutputTy = types::TY_Dependencies;
1551 OutputTy = Input->getType();
1552 if (!Args.hasFlag(options::OPT_frewrite_includes,
1553 options::OPT_fno_rewrite_includes, false) &&
1555 OutputTy = types::getPreprocessedType(OutputTy);
1556 assert(OutputTy != types::TY_INVALID &&
1557 "Cannot preprocess this input type!");
1559 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
1561 case phases::Precompile: {
1562 types::ID OutputTy = types::TY_PCH;
1563 if (Args.hasArg(options::OPT_fsyntax_only)) {
1564 // Syntax checks should not emit a PCH file
1565 OutputTy = types::TY_Nothing;
1567 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
1569 case phases::Compile: {
1570 if (Args.hasArg(options::OPT_fsyntax_only))
1571 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
1572 if (Args.hasArg(options::OPT_rewrite_objc))
1573 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
1574 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
1575 return C.MakeAction<CompileJobAction>(Input,
1576 types::TY_RewrittenLegacyObjC);
1577 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
1578 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
1579 if (Args.hasArg(options::OPT__migrate))
1580 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
1581 if (Args.hasArg(options::OPT_emit_ast))
1582 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
1583 if (Args.hasArg(options::OPT_module_file_info))
1584 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
1585 if (Args.hasArg(options::OPT_verify_pch))
1586 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
1587 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
1589 case phases::Backend: {
1592 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
1593 return C.MakeAction<BackendJobAction>(Input, Output);
1595 if (Args.hasArg(options::OPT_emit_llvm)) {
1597 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
1598 return C.MakeAction<BackendJobAction>(Input, Output);
1600 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
1602 case phases::Assemble:
1603 return C.MakeAction<AssembleJobAction>(Input, types::TY_Object);
1606 llvm_unreachable("invalid phase in ConstructPhaseAction");
1609 void Driver::BuildJobs(Compilation &C) const {
1610 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1612 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
1614 // It is an error to provide a -o option if we are making multiple output
1617 unsigned NumOutputs = 0;
1618 for (const Action *A : C.getActions())
1619 if (A->getType() != types::TY_Nothing)
1622 if (NumOutputs > 1) {
1623 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
1624 FinalOutput = nullptr;
1628 // Collect the list of architectures.
1629 llvm::StringSet<> ArchNames;
1630 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
1631 for (const Arg *A : C.getArgs())
1632 if (A->getOption().matches(options::OPT_arch))
1633 ArchNames.insert(A->getValue());
1635 for (Action *A : C.getActions()) {
1636 // If we are linking an image for multiple archs then the linker wants
1637 // -arch_multiple and -final_output <final image name>. Unfortunately, this
1638 // doesn't fit in cleanly because we have to pass this information down.
1640 // FIXME: This is a hack; find a cleaner way to integrate this into the
1642 const char *LinkingOutput = nullptr;
1643 if (isa<LipoJobAction>(A)) {
1645 LinkingOutput = FinalOutput->getValue();
1647 LinkingOutput = getDefaultImageName();
1650 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
1651 /*BoundArch*/ nullptr,
1652 /*AtTopLevel*/ true,
1653 /*MultipleArchs*/ ArchNames.size() > 1,
1654 /*LinkingOutput*/ LinkingOutput);
1657 // If the user passed -Qunused-arguments or there were errors, don't warn
1658 // about any unused arguments.
1659 if (Diags.hasErrorOccurred() ||
1660 C.getArgs().hasArg(options::OPT_Qunused_arguments))
1664 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1666 // Claim --driver-mode, it was handled earlier.
1667 (void)C.getArgs().hasArg(options::OPT_driver_mode);
1669 for (Arg *A : C.getArgs()) {
1670 // FIXME: It would be nice to be able to send the argument to the
1671 // DiagnosticsEngine, so that extra values, position, and so on could be
1673 if (!A->isClaimed()) {
1674 if (A->getOption().hasFlag(options::NoArgumentUnused))
1677 // Suppress the warning automatically if this is just a flag, and it is an
1678 // instance of an argument we already claimed.
1679 const Option &Opt = A->getOption();
1680 if (Opt.getKind() == Option::FlagClass) {
1681 bool DuplicateClaimed = false;
1683 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
1684 if (AA->isClaimed()) {
1685 DuplicateClaimed = true;
1690 if (DuplicateClaimed)
1694 Diag(clang::diag::warn_drv_unused_argument)
1695 << A->getAsString(C.getArgs());
1700 // Returns a Tool for a given JobAction. In case the action and its
1701 // predecessors can be combined, updates Inputs with the inputs of the
1702 // first combined action. If one of the collapsed actions is a
1703 // CudaHostAction, updates CollapsedCHA with the pointer to it so the
1704 // caller can deal with extra handling such action requires.
1705 static const Tool *selectToolForJob(Compilation &C, bool SaveTemps,
1706 const ToolChain *TC, const JobAction *JA,
1707 const ActionList *&Inputs,
1708 const CudaHostAction *&CollapsedCHA) {
1709 const Tool *ToolForJob = nullptr;
1710 CollapsedCHA = nullptr;
1712 // See if we should look for a compiler with an integrated assembler. We match
1713 // bottom up, so what we are actually looking for is an assembler job with a
1716 if (TC->useIntegratedAs() && !SaveTemps &&
1717 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
1718 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
1719 !C.getArgs().hasArg(options::OPT__SLASH_Fa) &&
1720 isa<AssembleJobAction>(JA) && Inputs->size() == 1 &&
1721 isa<BackendJobAction>(*Inputs->begin())) {
1722 // A BackendJob is always preceded by a CompileJob, and without
1723 // -save-temps they will always get combined together, so instead of
1724 // checking the backend tool, check if the tool for the CompileJob
1725 // has an integrated assembler.
1726 const ActionList *BackendInputs = &(*Inputs)[0]->getInputs();
1727 // Compile job may be wrapped in CudaHostAction, extract it if
1728 // that's the case and update CollapsedCHA if we combine phases.
1729 CudaHostAction *CHA = dyn_cast<CudaHostAction>(*BackendInputs->begin());
1730 JobAction *CompileJA =
1731 cast<CompileJobAction>(CHA ? *CHA->begin() : *BackendInputs->begin());
1732 assert(CompileJA && "Backend job is not preceeded by compile job.");
1733 const Tool *Compiler = TC->SelectTool(*CompileJA);
1736 if (Compiler->hasIntegratedAssembler()) {
1737 Inputs = &CompileJA->getInputs();
1738 ToolForJob = Compiler;
1743 // A backend job should always be combined with the preceding compile job
1744 // unless OPT_save_temps is enabled and the compiler is capable of emitting
1745 // LLVM IR as an intermediate output.
1746 if (isa<BackendJobAction>(JA)) {
1747 // Check if the compiler supports emitting LLVM IR.
1748 assert(Inputs->size() == 1);
1749 // Compile job may be wrapped in CudaHostAction, extract it if
1750 // that's the case and update CollapsedCHA if we combine phases.
1751 CudaHostAction *CHA = dyn_cast<CudaHostAction>(*Inputs->begin());
1752 JobAction *CompileJA =
1753 cast<CompileJobAction>(CHA ? *CHA->begin() : *Inputs->begin());
1754 assert(CompileJA && "Backend job is not preceeded by compile job.");
1755 const Tool *Compiler = TC->SelectTool(*CompileJA);
1758 if (!Compiler->canEmitIR() || !SaveTemps) {
1759 Inputs = &CompileJA->getInputs();
1760 ToolForJob = Compiler;
1765 // Otherwise use the tool for the current job.
1767 ToolForJob = TC->SelectTool(*JA);
1769 // See if we should use an integrated preprocessor. We do so when we have
1770 // exactly one input, since this is the only use case we care about
1771 // (irrelevant since we don't support combine yet).
1772 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
1773 !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
1774 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
1775 !C.getArgs().hasArg(options::OPT_rewrite_objc) &&
1776 ToolForJob->hasIntegratedCPP())
1777 Inputs = &(*Inputs)[0]->getInputs();
1782 InputInfo Driver::BuildJobsForAction(Compilation &C, const Action *A,
1783 const ToolChain *TC, const char *BoundArch,
1784 bool AtTopLevel, bool MultipleArchs,
1785 const char *LinkingOutput) const {
1786 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1788 InputInfoList CudaDeviceInputInfos;
1789 if (const CudaHostAction *CHA = dyn_cast<CudaHostAction>(A)) {
1790 // Append outputs of device jobs to the input list.
1791 for (const Action *DA : CHA->getDeviceActions()) {
1792 CudaDeviceInputInfos.push_back(
1793 BuildJobsForAction(C, DA, TC, nullptr, AtTopLevel,
1794 /*MultipleArchs*/ false, LinkingOutput));
1796 // Override current action with a real host compile action and continue
1801 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
1802 // FIXME: It would be nice to not claim this here; maybe the old scheme of
1803 // just using Args was better?
1804 const Arg &Input = IA->getInputArg();
1806 if (Input.getOption().matches(options::OPT_INPUT)) {
1807 const char *Name = Input.getValue();
1808 return InputInfo(A, Name, /* BaseInput = */ Name);
1810 return InputInfo(A, &Input, /* BaseInput = */ "");
1813 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1814 const ToolChain *TC;
1815 const char *ArchName = BAA->getArchName();
1820 computeTargetTriple(DefaultTargetTriple, C.getArgs(), ArchName));
1822 TC = &C.getDefaultToolChain();
1824 return BuildJobsForAction(C, *BAA->begin(), TC, ArchName, AtTopLevel,
1825 MultipleArchs, LinkingOutput);
1828 if (const CudaDeviceAction *CDA = dyn_cast<CudaDeviceAction>(A)) {
1829 // Initial processing of CudaDeviceAction carries host params.
1830 // Call BuildJobsForAction() again, now with correct device parameters.
1831 assert(CDA->getGpuArchName() && "No GPU name in device action.");
1832 return BuildJobsForAction(C, *CDA->begin(), C.getCudaDeviceToolChain(),
1833 CDA->getGpuArchName(), CDA->isAtTopLevel(),
1834 /*MultipleArchs*/ true, LinkingOutput);
1837 const ActionList *Inputs = &A->getInputs();
1839 const JobAction *JA = cast<JobAction>(A);
1840 const CudaHostAction *CollapsedCHA = nullptr;
1842 selectToolForJob(C, isSaveTempsEnabled(), TC, JA, Inputs, CollapsedCHA);
1846 // If we've collapsed action list that contained CudaHostAction we
1847 // need to build jobs for device-side inputs it may have held.
1849 for (const Action *DA : CollapsedCHA->getDeviceActions()) {
1850 CudaDeviceInputInfos.push_back(
1851 BuildJobsForAction(C, DA, TC, "", AtTopLevel,
1852 /*MultipleArchs*/ false, LinkingOutput));
1856 // Only use pipes when there is exactly one input.
1857 InputInfoList InputInfos;
1858 for (const Action *Input : *Inputs) {
1859 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
1860 // shouldn't get temporary output names.
1861 // FIXME: Clean this up.
1862 bool SubJobAtTopLevel =
1863 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
1864 InputInfos.push_back(BuildJobsForAction(C, Input, TC, BoundArch,
1865 SubJobAtTopLevel, MultipleArchs,
1869 // Always use the first input as the base input.
1870 const char *BaseInput = InputInfos[0].getBaseInput();
1872 // ... except dsymutil actions, which use their actual input as the base
1874 if (JA->getType() == types::TY_dSYM)
1875 BaseInput = InputInfos[0].getFilename();
1877 // Append outputs of cuda device jobs to the input list
1878 if (CudaDeviceInputInfos.size())
1879 InputInfos.append(CudaDeviceInputInfos.begin(), CudaDeviceInputInfos.end());
1881 // Determine the place to write output to, if any.
1883 if (JA->getType() == types::TY_Nothing)
1884 Result = InputInfo(A, BaseInput);
1886 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
1887 AtTopLevel, MultipleArchs),
1890 if (CCCPrintBindings && !CCGenDiagnostics) {
1891 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
1892 << " - \"" << T->getName() << "\", inputs: [";
1893 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1894 llvm::errs() << InputInfos[i].getAsString();
1896 llvm::errs() << ", ";
1898 llvm::errs() << "], output: " << Result.getAsString() << "\n";
1900 T->ConstructJob(C, *JA, Result, InputInfos,
1901 C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
1906 const char *Driver::getDefaultImageName() const {
1907 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
1908 return Target.isOSWindows() ? "a.exe" : "a.out";
1911 /// \brief Create output filename based on ArgValue, which could either be a
1912 /// full filename, filename without extension, or a directory. If ArgValue
1913 /// does not provide a filename, then use BaseName, and use the extension
1914 /// suitable for FileType.
1915 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
1917 types::ID FileType) {
1918 SmallString<128> Filename = ArgValue;
1920 if (ArgValue.empty()) {
1921 // If the argument is empty, output to BaseName in the current dir.
1922 Filename = BaseName;
1923 } else if (llvm::sys::path::is_separator(Filename.back())) {
1924 // If the argument is a directory, output to BaseName in that dir.
1925 llvm::sys::path::append(Filename, BaseName);
1928 if (!llvm::sys::path::has_extension(ArgValue)) {
1929 // If the argument didn't provide an extension, then set it.
1930 const char *Extension = types::getTypeTempSuffix(FileType, true);
1932 if (FileType == types::TY_Image &&
1933 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
1934 // The output file is a dll.
1938 llvm::sys::path::replace_extension(Filename, Extension);
1941 return Args.MakeArgString(Filename.c_str());
1944 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
1945 const char *BaseInput,
1946 const char *BoundArch, bool AtTopLevel,
1947 bool MultipleArchs) const {
1948 llvm::PrettyStackTraceString CrashInfo("Computing output path");
1949 // Output to a user requested destination?
1950 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
1951 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1952 return C.addResultFile(FinalOutput->getValue(), &JA);
1955 // For /P, preprocess to file named after BaseInput.
1956 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
1957 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
1958 StringRef BaseName = llvm::sys::path::filename(BaseInput);
1960 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
1961 NameArg = A->getValue();
1962 return C.addResultFile(
1963 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
1967 // Default to writing to stdout?
1968 if (AtTopLevel && !CCGenDiagnostics &&
1969 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
1972 // Is this the assembly listing for /FA?
1973 if (JA.getType() == types::TY_PP_Asm &&
1974 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
1975 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
1976 // Use /Fa and the input filename to determine the asm file name.
1977 StringRef BaseName = llvm::sys::path::filename(BaseInput);
1978 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
1979 return C.addResultFile(
1980 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
1984 // Output to a temporary file?
1985 if ((!AtTopLevel && !isSaveTempsEnabled() &&
1986 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
1988 StringRef Name = llvm::sys::path::filename(BaseInput);
1989 std::pair<StringRef, StringRef> Split = Name.split('.');
1990 std::string TmpName = GetTemporaryPath(
1991 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
1992 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1995 SmallString<128> BasePath(BaseInput);
1998 // Dsymutil actions should use the full path.
1999 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
2000 BaseName = BasePath;
2002 BaseName = llvm::sys::path::filename(BasePath);
2004 // Determine what the derived output name should be.
2005 const char *NamedOutput;
2007 if (JA.getType() == types::TY_Object &&
2008 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
2009 // The /Fo or /o flag decides the object filename.
2012 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
2015 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
2016 } else if (JA.getType() == types::TY_Image &&
2017 C.getArgs().hasArg(options::OPT__SLASH_Fe,
2018 options::OPT__SLASH_o)) {
2019 // The /Fe or /o flag names the linked file.
2022 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
2025 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
2026 } else if (JA.getType() == types::TY_Image) {
2028 // clang-cl uses BaseName for the executable name.
2030 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
2031 } else if (MultipleArchs && BoundArch) {
2032 SmallString<128> Output(getDefaultImageName());
2034 Output.append(BoundArch);
2035 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
2037 NamedOutput = getDefaultImageName();
2039 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
2040 assert(Suffix && "All types used for output should have a suffix.");
2042 std::string::size_type End = std::string::npos;
2043 if (!types::appendSuffixForType(JA.getType()))
2044 End = BaseName.rfind('.');
2045 SmallString<128> Suffixed(BaseName.substr(0, End));
2046 if (MultipleArchs && BoundArch) {
2048 Suffixed.append(BoundArch);
2050 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
2051 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
2052 // optimized bitcode output.
2053 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
2054 JA.getType() == types::TY_LLVM_BC)
2058 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
2061 // Prepend object file path if -save-temps=obj
2062 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
2063 JA.getType() != types::TY_PCH) {
2064 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2065 SmallString<128> TempPath(FinalOutput->getValue());
2066 llvm::sys::path::remove_filename(TempPath);
2067 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
2068 llvm::sys::path::append(TempPath, OutputFileName);
2069 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
2072 // If we're saving temps and the temp file conflicts with the input file,
2073 // then avoid overwriting input file.
2074 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
2075 bool SameFile = false;
2076 SmallString<256> Result;
2077 llvm::sys::fs::current_path(Result);
2078 llvm::sys::path::append(Result, BaseName);
2079 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
2080 // Must share the same path to conflict.
2082 StringRef Name = llvm::sys::path::filename(BaseInput);
2083 std::pair<StringRef, StringRef> Split = Name.split('.');
2084 std::string TmpName = GetTemporaryPath(
2085 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
2086 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
2090 // As an annoying special case, PCH generation doesn't strip the pathname.
2091 if (JA.getType() == types::TY_PCH) {
2092 llvm::sys::path::remove_filename(BasePath);
2093 if (BasePath.empty())
2094 BasePath = NamedOutput;
2096 llvm::sys::path::append(BasePath, NamedOutput);
2097 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
2099 return C.addResultFile(NamedOutput, &JA);
2103 std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
2104 // Respect a limited subset of the '-Bprefix' functionality in GCC by
2105 // attempting to use this prefix when looking for file paths.
2106 for (const std::string &Dir : PrefixDirs) {
2109 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
2110 llvm::sys::path::append(P, Name);
2111 if (llvm::sys::fs::exists(Twine(P)))
2115 SmallString<128> P(ResourceDir);
2116 llvm::sys::path::append(P, Name);
2117 if (llvm::sys::fs::exists(Twine(P)))
2120 for (const std::string &Dir : TC.getFilePaths()) {
2123 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
2124 llvm::sys::path::append(P, Name);
2125 if (llvm::sys::fs::exists(Twine(P)))
2132 void Driver::generatePrefixedToolNames(
2133 const char *Tool, const ToolChain &TC,
2134 SmallVectorImpl<std::string> &Names) const {
2135 // FIXME: Needs a better variable than DefaultTargetTriple
2136 Names.emplace_back(DefaultTargetTriple + "-" + Tool);
2137 Names.emplace_back(Tool);
2139 // Allow the discovery of tools prefixed with LLVM's default target triple.
2140 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
2141 if (LLVMDefaultTargetTriple != DefaultTargetTriple)
2142 Names.emplace_back(LLVMDefaultTargetTriple + "-" + Tool);
2145 static bool ScanDirForExecutable(SmallString<128> &Dir,
2146 ArrayRef<std::string> Names) {
2147 for (const auto &Name : Names) {
2148 llvm::sys::path::append(Dir, Name);
2149 if (llvm::sys::fs::can_execute(Twine(Dir)))
2151 llvm::sys::path::remove_filename(Dir);
2156 std::string Driver::GetProgramPath(const char *Name,
2157 const ToolChain &TC) const {
2158 SmallVector<std::string, 2> TargetSpecificExecutables;
2159 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
2161 // Respect a limited subset of the '-Bprefix' functionality in GCC by
2162 // attempting to use this prefix when looking for program paths.
2163 for (const auto &PrefixDir : PrefixDirs) {
2164 if (llvm::sys::fs::is_directory(PrefixDir)) {
2165 SmallString<128> P(PrefixDir);
2166 if (ScanDirForExecutable(P, TargetSpecificExecutables))
2169 SmallString<128> P(PrefixDir + Name);
2170 if (llvm::sys::fs::can_execute(Twine(P)))
2175 const ToolChain::path_list &List = TC.getProgramPaths();
2176 for (const auto &Path : List) {
2177 SmallString<128> P(Path);
2178 if (ScanDirForExecutable(P, TargetSpecificExecutables))
2182 // If all else failed, search the path.
2183 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
2184 if (llvm::ErrorOr<std::string> P =
2185 llvm::sys::findProgramByName(TargetSpecificExecutable))
2191 std::string Driver::GetTemporaryPath(StringRef Prefix,
2192 const char *Suffix) const {
2193 SmallString<128> Path;
2194 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
2196 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
2203 const ToolChain &Driver::getToolChain(const ArgList &Args,
2204 const llvm::Triple &Target) const {
2206 ToolChain *&TC = ToolChains[Target.str()];
2208 switch (Target.getOS()) {
2209 case llvm::Triple::CloudABI:
2210 TC = new toolchains::CloudABI(*this, Target, Args);
2212 case llvm::Triple::Darwin:
2213 case llvm::Triple::MacOSX:
2214 case llvm::Triple::IOS:
2215 case llvm::Triple::TvOS:
2216 case llvm::Triple::WatchOS:
2217 TC = new toolchains::DarwinClang(*this, Target, Args);
2219 case llvm::Triple::DragonFly:
2220 TC = new toolchains::DragonFly(*this, Target, Args);
2222 case llvm::Triple::OpenBSD:
2223 TC = new toolchains::OpenBSD(*this, Target, Args);
2225 case llvm::Triple::Bitrig:
2226 TC = new toolchains::Bitrig(*this, Target, Args);
2228 case llvm::Triple::NetBSD:
2229 TC = new toolchains::NetBSD(*this, Target, Args);
2231 case llvm::Triple::FreeBSD:
2232 TC = new toolchains::FreeBSD(*this, Target, Args);
2234 case llvm::Triple::Minix:
2235 TC = new toolchains::Minix(*this, Target, Args);
2237 case llvm::Triple::Linux:
2238 if (Target.getArch() == llvm::Triple::hexagon)
2239 TC = new toolchains::HexagonToolChain(*this, Target, Args);
2240 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
2241 !Target.hasEnvironment())
2242 TC = new toolchains::MipsLLVMToolChain(*this, Target, Args);
2244 TC = new toolchains::Linux(*this, Target, Args);
2246 case llvm::Triple::NaCl:
2247 TC = new toolchains::NaClToolChain(*this, Target, Args);
2249 case llvm::Triple::Solaris:
2250 TC = new toolchains::Solaris(*this, Target, Args);
2252 case llvm::Triple::AMDHSA:
2253 TC = new toolchains::AMDGPUToolChain(*this, Target, Args);
2255 case llvm::Triple::Win32:
2256 switch (Target.getEnvironment()) {
2258 if (Target.isOSBinFormatELF())
2259 TC = new toolchains::Generic_ELF(*this, Target, Args);
2260 else if (Target.isOSBinFormatMachO())
2261 TC = new toolchains::MachO(*this, Target, Args);
2263 TC = new toolchains::Generic_GCC(*this, Target, Args);
2265 case llvm::Triple::GNU:
2266 TC = new toolchains::MinGW(*this, Target, Args);
2268 case llvm::Triple::Itanium:
2269 TC = new toolchains::CrossWindowsToolChain(*this, Target, Args);
2271 case llvm::Triple::MSVC:
2272 case llvm::Triple::UnknownEnvironment:
2273 TC = new toolchains::MSVCToolChain(*this, Target, Args);
2277 case llvm::Triple::CUDA:
2278 TC = new toolchains::CudaToolChain(*this, Target, Args);
2280 case llvm::Triple::PS4:
2281 TC = new toolchains::PS4CPU(*this, Target, Args);
2284 // Of these targets, Hexagon is the only one that might have
2285 // an OS of Linux, in which case it got handled above already.
2286 switch (Target.getArch()) {
2287 case llvm::Triple::tce:
2288 TC = new toolchains::TCEToolChain(*this, Target, Args);
2290 case llvm::Triple::hexagon:
2291 TC = new toolchains::HexagonToolChain(*this, Target, Args);
2293 case llvm::Triple::xcore:
2294 TC = new toolchains::XCoreToolChain(*this, Target, Args);
2296 case llvm::Triple::wasm32:
2297 case llvm::Triple::wasm64:
2298 TC = new toolchains::WebAssembly(*this, Target, Args);
2301 if (Target.getVendor() == llvm::Triple::Myriad)
2302 TC = new toolchains::MyriadToolChain(*this, Target, Args);
2303 else if (Target.isOSBinFormatELF())
2304 TC = new toolchains::Generic_ELF(*this, Target, Args);
2305 else if (Target.isOSBinFormatMachO())
2306 TC = new toolchains::MachO(*this, Target, Args);
2308 TC = new toolchains::Generic_GCC(*this, Target, Args);
2315 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
2316 // Say "no" if there is not exactly one input of a type clang understands.
2317 if (JA.size() != 1 || !types::isAcceptedByClang((*JA.begin())->getType()))
2320 // And say "no" if this is not a kind of action clang understands.
2321 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
2322 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
2328 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
2329 /// grouped values as integers. Numbers which are not provided are set to 0.
2331 /// \return True if the entire string was parsed (9.2), or all groups were
2332 /// parsed (10.3.5extrastuff).
2333 bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
2334 unsigned &Minor, unsigned &Micro,
2338 Major = Minor = Micro = 0;
2343 Major = (unsigned)strtol(Str, &End, 10);
2344 if (*Str != '\0' && *End == '\0')
2350 Minor = (unsigned)strtol(Str, &End, 10);
2351 if (*Str != '\0' && *End == '\0')
2357 Micro = (unsigned)strtol(Str, &End, 10);
2358 if (*Str != '\0' && *End == '\0')
2366 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
2367 unsigned IncludedFlagsBitmask = 0;
2368 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
2370 if (Mode == CLMode) {
2371 // Include CL and Core options.
2372 IncludedFlagsBitmask |= options::CLOption;
2373 IncludedFlagsBitmask |= options::CoreOption;
2375 ExcludedFlagsBitmask |= options::CLOption;
2378 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
2381 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
2382 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);