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/Config/config.h"
15 #include "clang/Driver/Action.h"
16 #include "clang/Driver/Compilation.h"
17 #include "clang/Driver/DriverDiagnostic.h"
18 #include "clang/Driver/Job.h"
19 #include "clang/Driver/Options.h"
20 #include "clang/Driver/SanitizerArgs.h"
21 #include "clang/Driver/Tool.h"
22 #include "clang/Driver/ToolChain.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSet.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/Option/Arg.h"
29 #include "llvm/Option/ArgList.h"
30 #include "llvm/Option/OptSpecifier.h"
31 #include "llvm/Option/OptTable.h"
32 #include "llvm/Option/Option.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/PrettyStackTrace.h"
38 #include "llvm/Support/Process.h"
39 #include "llvm/Support/Program.h"
40 #include "llvm/Support/raw_ostream.h"
44 using namespace clang::driver;
45 using namespace clang;
46 using namespace llvm::opt;
48 Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
49 DiagnosticsEngine &Diags)
50 : Opts(createDriverOptTable()), Diags(Diags), Mode(GCCMode),
51 SaveTemps(SaveTempsNone), ClangExecutable(ClangExecutable),
52 SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
53 DefaultTargetTriple(DefaultTargetTriple),
54 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
55 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
56 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
57 CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
58 CCCUsePCH(true), SuppressMissingInputWarning(false) {
60 Name = llvm::sys::path::filename(ClangExecutable);
61 Dir = llvm::sys::path::parent_path(ClangExecutable);
63 // Compute the path to the resource directory.
64 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
65 SmallString<128> P(Dir);
66 if (ClangResourceDir != "") {
67 llvm::sys::path::append(P, ClangResourceDir);
69 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
70 llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang",
71 CLANG_VERSION_STRING);
73 ResourceDir = P.str();
79 llvm::DeleteContainerSeconds(ToolChains);
82 void Driver::ParseDriverMode(ArrayRef<const char *> Args) {
83 const std::string OptName =
84 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
86 for (const char *ArgPtr : Args) {
87 // Ingore nullptrs, they are response file's EOL markers
88 if (ArgPtr == nullptr)
90 const StringRef Arg = ArgPtr;
91 if (!Arg.startswith(OptName))
94 const StringRef Value = Arg.drop_front(OptName.size());
95 const unsigned M = llvm::StringSwitch<unsigned>(Value)
103 Mode = static_cast<DriverMode>(M);
105 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
109 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
110 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
112 unsigned IncludedFlagsBitmask;
113 unsigned ExcludedFlagsBitmask;
114 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
115 getIncludeExcludeOptionFlagMasks();
117 unsigned MissingArgIndex, MissingArgCount;
119 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
120 IncludedFlagsBitmask, ExcludedFlagsBitmask);
122 // Check for missing argument error.
124 Diag(clang::diag::err_drv_missing_argument)
125 << Args.getArgString(MissingArgIndex) << MissingArgCount;
127 // Check for unsupported options.
128 for (const Arg *A : Args) {
129 if (A->getOption().hasFlag(options::Unsupported)) {
130 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
134 // Warn about -mcpu= without an argument.
135 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
136 Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
140 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
141 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
146 // Determine which compilation mode we are in. We look for options which
147 // affect the phase, starting with the earliest phases, and record which
148 // option we used to determine the final phase.
149 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
150 Arg **FinalPhaseArg) const {
151 Arg *PhaseArg = nullptr;
152 phases::ID FinalPhase;
154 // -{E,EP,P,M,MM} only run the preprocessor.
155 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
156 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
157 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
158 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
159 FinalPhase = phases::Preprocess;
161 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
162 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
163 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
164 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
165 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
166 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
167 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
168 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
169 options::OPT__analyze_auto)) ||
170 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
171 FinalPhase = phases::Compile;
173 // -S only runs up to the backend.
174 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
175 FinalPhase = phases::Backend;
177 // -c and partial CUDA compilations only run up to the assembler.
178 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c)) ||
179 (PhaseArg = DAL.getLastArg(options::OPT_cuda_device_only)) ||
180 (PhaseArg = DAL.getLastArg(options::OPT_cuda_host_only))) {
181 FinalPhase = phases::Assemble;
183 // Otherwise do everything.
185 FinalPhase = phases::Link;
188 *FinalPhaseArg = PhaseArg;
193 static Arg *MakeInputArg(DerivedArgList &Args, OptTable *Opts,
195 Arg *A = new Arg(Opts->getOption(options::OPT_INPUT), Value,
196 Args.getBaseArgs().MakeIndex(Value), Value.data());
197 Args.AddSynthesizedArg(A);
202 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
203 DerivedArgList *DAL = new DerivedArgList(Args);
205 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
206 for (Arg *A : Args) {
207 // Unfortunately, we have to parse some forwarding options (-Xassembler,
208 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
209 // (assembler and preprocessor), or bypass a previous driver ('collect2').
211 // Rewrite linker options, to replace --no-demangle with a custom internal
213 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
214 A->getOption().matches(options::OPT_Xlinker)) &&
215 A->containsValue("--no-demangle")) {
216 // Add the rewritten no-demangle argument.
217 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
219 // Add the remaining values as Xlinker arguments.
220 for (const StringRef Val : A->getValues())
221 if (Val != "--no-demangle")
222 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
227 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
228 // some build systems. We don't try to be complete here because we don't
229 // care to encourage this usage model.
230 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
231 (A->getValue(0) == StringRef("-MD") ||
232 A->getValue(0) == StringRef("-MMD"))) {
233 // Rewrite to -MD/-MMD along with -MF.
234 if (A->getValue(0) == StringRef("-MD"))
235 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
237 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
238 if (A->getNumValues() == 2)
239 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
244 // Rewrite reserved library names.
245 if (A->getOption().matches(options::OPT_l)) {
246 StringRef Value = A->getValue();
248 // Rewrite unless -nostdlib is present.
249 if (!HasNostdlib && Value == "stdc++") {
250 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
254 // Rewrite unconditionally.
255 if (Value == "cc_kext") {
256 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
261 // Pick up inputs via the -- option.
262 if (A->getOption().matches(options::OPT__DASH_DASH)) {
264 for (const StringRef Val : A->getValues())
265 DAL->append(MakeInputArg(*DAL, Opts, Val));
272 // Add a default value of -mlinker-version=, if one was given and the user
273 // didn't specify one.
274 #if defined(HOST_LINK_VERSION)
275 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
276 strlen(HOST_LINK_VERSION) > 0) {
277 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
279 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
286 /// \brief Compute target triple from args.
288 /// This routine provides the logic to compute a target triple from various
289 /// args passed to the driver and the default triple string.
290 static llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple,
292 StringRef DarwinArchName = "") {
293 // FIXME: Already done in Compilation *Driver::BuildCompilation
294 if (const Arg *A = Args.getLastArg(options::OPT_target))
295 DefaultTargetTriple = A->getValue();
297 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
299 // Handle Apple-specific options available here.
300 if (Target.isOSBinFormatMachO()) {
301 // If an explict Darwin arch name is given, that trumps all.
302 if (!DarwinArchName.empty()) {
303 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
307 // Handle the Darwin '-arch' flag.
308 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
309 StringRef ArchName = A->getValue();
310 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
314 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
315 // '-mbig-endian'/'-EB'.
316 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
317 options::OPT_mbig_endian)) {
318 if (A->getOption().matches(options::OPT_mlittle_endian)) {
319 llvm::Triple LE = Target.getLittleEndianArchVariant();
320 if (LE.getArch() != llvm::Triple::UnknownArch)
321 Target = std::move(LE);
323 llvm::Triple BE = Target.getBigEndianArchVariant();
324 if (BE.getArch() != llvm::Triple::UnknownArch)
325 Target = std::move(BE);
329 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
330 if (Target.getArchName() == "tce" || Target.getOS() == llvm::Triple::Minix)
333 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
334 if (Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
335 options::OPT_m32, options::OPT_m16)) {
336 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
338 if (A->getOption().matches(options::OPT_m64)) {
339 AT = Target.get64BitArchVariant().getArch();
340 if (Target.getEnvironment() == llvm::Triple::GNUX32)
341 Target.setEnvironment(llvm::Triple::GNU);
342 } else if (A->getOption().matches(options::OPT_mx32) &&
343 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
344 AT = llvm::Triple::x86_64;
345 Target.setEnvironment(llvm::Triple::GNUX32);
346 } else if (A->getOption().matches(options::OPT_m32)) {
347 AT = Target.get32BitArchVariant().getArch();
348 if (Target.getEnvironment() == llvm::Triple::GNUX32)
349 Target.setEnvironment(llvm::Triple::GNU);
350 } else if (A->getOption().matches(options::OPT_m16) &&
351 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
352 AT = llvm::Triple::x86;
353 Target.setEnvironment(llvm::Triple::CODE16);
356 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
363 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
364 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
366 // FIXME: Handle environment options which affect driver behavior, somewhere
367 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
369 if (char *env = ::getenv("COMPILER_PATH")) {
370 StringRef CompilerPath = env;
371 while (!CompilerPath.empty()) {
372 std::pair<StringRef, StringRef> Split =
373 CompilerPath.split(llvm::sys::EnvPathSeparator);
374 PrefixDirs.push_back(Split.first);
375 CompilerPath = Split.second;
379 // We look for the driver mode option early, because the mode can affect
380 // how other options are parsed.
381 ParseDriverMode(ArgList.slice(1));
383 // FIXME: What are we going to do with -V and -b?
385 // FIXME: This stuff needs to go into the Compilation, not the driver.
388 InputArgList Args = ParseArgStrings(ArgList.slice(1));
390 // -no-canonical-prefixes is used very early in main.
391 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
394 Args.ClaimAllArgs(options::OPT_pipe);
396 // Extract -ccc args.
398 // FIXME: We need to figure out where this behavior should live. Most of it
399 // should be outside in the client; the parts that aren't should have proper
400 // options, either by introducing new ones or by overloading gcc ones like -V
402 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
403 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
404 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
405 CCCGenericGCCName = A->getValue();
407 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
408 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
409 // and getToolChain is const.
411 // clang-cl targets MSVC-style Win32.
412 llvm::Triple T(DefaultTargetTriple);
413 T.setOS(llvm::Triple::Win32);
414 T.setEnvironment(llvm::Triple::MSVC);
415 DefaultTargetTriple = T.str();
417 if (const Arg *A = Args.getLastArg(options::OPT_target))
418 DefaultTargetTriple = A->getValue();
419 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
420 Dir = InstalledDir = A->getValue();
421 for (const Arg *A : Args.filtered(options::OPT_B)) {
423 PrefixDirs.push_back(A->getValue(0));
425 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
426 SysRoot = A->getValue();
427 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
428 DyldPrefix = A->getValue();
429 if (Args.hasArg(options::OPT_nostdlib))
432 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
433 ResourceDir = A->getValue();
435 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
436 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
437 .Case("cwd", SaveTempsCwd)
438 .Case("obj", SaveTempsObj)
439 .Default(SaveTempsCwd);
442 std::unique_ptr<llvm::opt::InputArgList> UArgs =
443 llvm::make_unique<InputArgList>(std::move(Args));
445 // Perform the default argument translations.
446 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
448 // Owned by the host.
449 const ToolChain &TC =
450 getToolChain(*UArgs, computeTargetTriple(DefaultTargetTriple, *UArgs));
452 // The compilation takes ownership of Args.
453 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
455 if (!HandleImmediateArgs(*C))
458 // Construct the list of inputs.
460 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
462 // Construct the list of abstract actions to perform for this compilation. On
463 // MachO targets this uses the driver-driver and universal actions.
464 if (TC.getTriple().isOSBinFormatMachO())
465 BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(), Inputs,
468 BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs,
471 if (CCCPrintPhases) {
481 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
482 llvm::opt::ArgStringList ASL;
483 for (const auto *A : Args)
484 A->render(Args, ASL);
486 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
487 if (I != ASL.begin())
489 Command::printArg(OS, *I, true);
494 // When clang crashes, produce diagnostic information including the fully
495 // preprocessed source file(s). Request that the developer attach the
496 // diagnostic information to a bug report.
497 void Driver::generateCompilationDiagnostics(Compilation &C,
498 const Command &FailingCommand) {
499 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
502 // Don't try to generate diagnostics for link or dsymutil jobs.
503 if (FailingCommand.getCreator().isLinkJob() ||
504 FailingCommand.getCreator().isDsymutilJob())
507 // Print the version of the compiler.
508 PrintVersion(C, llvm::errs());
510 Diag(clang::diag::note_drv_command_failed_diag_msg)
511 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
512 "crash backtrace, preprocessed source, and associated run script.";
514 // Suppress driver output and emit preprocessor output to temp file.
516 CCGenDiagnostics = true;
518 // Save the original job command(s).
519 Command Cmd = FailingCommand;
521 // Keep track of whether we produce any errors while trying to produce
522 // preprocessed sources.
523 DiagnosticErrorTrap Trap(Diags);
525 // Suppress tool output.
526 C.initCompilationForDiagnostics();
528 // Construct the list of inputs.
530 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
532 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
533 bool IgnoreInput = false;
535 // Ignore input from stdin or any inputs that cannot be preprocessed.
536 // Check type first as not all linker inputs have a value.
537 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
539 } else if (!strcmp(it->second->getValue(), "-")) {
540 Diag(clang::diag::note_drv_command_failed_diag_msg)
541 << "Error generating preprocessed source(s) - "
542 "ignoring input from stdin.";
547 it = Inputs.erase(it);
554 if (Inputs.empty()) {
555 Diag(clang::diag::note_drv_command_failed_diag_msg)
556 << "Error generating preprocessed source(s) - "
557 "no preprocessable inputs.";
561 // Don't attempt to generate preprocessed files if multiple -arch options are
562 // used, unless they're all duplicates.
563 llvm::StringSet<> ArchNames;
564 for (const Arg *A : C.getArgs()) {
565 if (A->getOption().matches(options::OPT_arch)) {
566 StringRef ArchName = A->getValue();
567 ArchNames.insert(ArchName);
570 if (ArchNames.size() > 1) {
571 Diag(clang::diag::note_drv_command_failed_diag_msg)
572 << "Error generating preprocessed source(s) - cannot generate "
573 "preprocessed source with multiple -arch options.";
577 // Construct the list of abstract actions to perform for this compilation. On
578 // Darwin OSes this uses the driver-driver and builds universal actions.
579 const ToolChain &TC = C.getDefaultToolChain();
580 if (TC.getTriple().isOSBinFormatMachO())
581 BuildUniversalActions(TC, C.getArgs(), Inputs, C.getActions());
583 BuildActions(TC, C.getArgs(), Inputs, C.getActions());
587 // If there were errors building the compilation, quit now.
588 if (Trap.hasErrorOccurred()) {
589 Diag(clang::diag::note_drv_command_failed_diag_msg)
590 << "Error generating preprocessed source(s).";
594 // Generate preprocessed output.
595 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
596 C.ExecuteJobs(C.getJobs(), FailingCommands);
598 // If any of the preprocessing commands failed, clean up and exit.
599 if (!FailingCommands.empty()) {
600 if (!isSaveTempsEnabled())
601 C.CleanupFileList(C.getTempFiles(), true);
603 Diag(clang::diag::note_drv_command_failed_diag_msg)
604 << "Error generating preprocessed source(s).";
608 const ArgStringList &TempFiles = C.getTempFiles();
609 if (TempFiles.empty()) {
610 Diag(clang::diag::note_drv_command_failed_diag_msg)
611 << "Error generating preprocessed source(s).";
615 Diag(clang::diag::note_drv_command_failed_diag_msg)
616 << "\n********************\n\n"
617 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
618 "Preprocessed source(s) and associated run script(s) are located at:";
620 SmallString<128> VFS;
621 for (const char *TempFile : TempFiles) {
622 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
623 if (StringRef(TempFile).endswith(".cache")) {
624 // In some cases (modules) we'll dump extra data to help with reproducing
625 // the crash into a directory next to the output.
626 VFS = llvm::sys::path::filename(TempFile);
627 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
631 // Assume associated files are based off of the first temporary file.
632 CrashReportInfo CrashInfo(TempFiles[0], VFS);
634 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
636 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
638 Diag(clang::diag::note_drv_command_failed_diag_msg)
639 << "Error generating run script: " + Script + " " + EC.message();
641 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
642 << "# Driver args: ";
643 printArgList(ScriptOS, C.getInputArgs());
644 ScriptOS << "# Original command: ";
645 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
646 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
647 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
650 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
651 options::OPT_frewrite_map_file_EQ))
652 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
654 Diag(clang::diag::note_drv_command_failed_diag_msg)
655 << "\n\n********************";
658 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
659 // Since argumentsFitWithinSystemLimits() may underestimate system's capacity
660 // if the tool does not support response files, there is a chance/ that things
661 // will just work without a response file, so we silently just skip it.
662 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
663 llvm::sys::argumentsFitWithinSystemLimits(Cmd.getArguments()))
666 std::string TmpName = GetTemporaryPath("response", "txt");
668 C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())));
671 int Driver::ExecuteCompilation(
673 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
674 // Just print if -### was present.
675 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
676 C.getJobs().Print(llvm::errs(), "\n", true);
680 // If there were errors building the compilation, quit now.
681 if (Diags.hasErrorOccurred())
684 // Set up response file names for each command, if necessary
685 for (auto &Job : C.getJobs())
686 setUpResponseFiles(C, Job);
688 C.ExecuteJobs(C.getJobs(), FailingCommands);
690 // Remove temp files.
691 C.CleanupFileList(C.getTempFiles());
693 // If the command succeeded, we are done.
694 if (FailingCommands.empty())
697 // Otherwise, remove result files and print extra information about abnormal
699 for (const auto &CmdPair : FailingCommands) {
700 int Res = CmdPair.first;
701 const Command *FailingCommand = CmdPair.second;
703 // Remove result files if we're not saving temps.
704 if (!isSaveTempsEnabled()) {
705 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
706 C.CleanupFileMap(C.getResultFiles(), JA, true);
708 // Failure result files are valid unless we crashed.
710 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
713 // Print extra information about abnormal failures, if possible.
715 // This is ad-hoc, but we don't want to be excessively noisy. If the result
716 // status was 1, assume the command failed normally. In particular, if it
717 // was the compiler then assume it gave a reasonable error code. Failures
718 // in other tools are less common, and they generally have worse
719 // diagnostics, so always print the diagnostic there.
720 const Tool &FailingTool = FailingCommand->getCreator();
722 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
723 // FIXME: See FIXME above regarding result code interpretation.
725 Diag(clang::diag::err_drv_command_signalled)
726 << FailingTool.getShortName();
728 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
735 void Driver::PrintHelp(bool ShowHidden) const {
736 unsigned IncludedFlagsBitmask;
737 unsigned ExcludedFlagsBitmask;
738 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
739 getIncludeExcludeOptionFlagMasks();
741 ExcludedFlagsBitmask |= options::NoDriverOption;
743 ExcludedFlagsBitmask |= HelpHidden;
745 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
746 IncludedFlagsBitmask, ExcludedFlagsBitmask);
749 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
750 // FIXME: The following handlers should use a callback mechanism, we don't
751 // know what the client would like to do.
752 OS << getClangFullVersion() << '\n';
753 const ToolChain &TC = C.getDefaultToolChain();
754 OS << "Target: " << TC.getTripleString() << '\n';
756 // Print the threading model.
757 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
758 // Don't print if the ToolChain would have barfed on it already
759 if (TC.isThreadModelSupported(A->getValue()))
760 OS << "Thread model: " << A->getValue();
762 OS << "Thread model: " << TC.getThreadModel();
766 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
768 static void PrintDiagnosticCategories(raw_ostream &OS) {
769 // Skip the empty category.
770 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
772 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
775 bool Driver::HandleImmediateArgs(const Compilation &C) {
776 // The order these options are handled in gcc is all over the place, but we
777 // don't expect inconsistencies w.r.t. that to matter in practice.
779 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
780 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
784 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
785 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
786 // return an answer which matches our definition of __VERSION__.
788 // If we want to return a more correct answer some day, then we should
789 // introduce a non-pedantically GCC compatible mode to Clang in which we
790 // provide sensible definitions for -dumpversion, __VERSION__, etc.
791 llvm::outs() << "4.2.1\n";
795 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
796 PrintDiagnosticCategories(llvm::outs());
800 if (C.getArgs().hasArg(options::OPT_help) ||
801 C.getArgs().hasArg(options::OPT__help_hidden)) {
802 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
806 if (C.getArgs().hasArg(options::OPT__version)) {
807 // Follow gcc behavior and use stdout for --version and stderr for -v.
808 PrintVersion(C, llvm::outs());
812 if (C.getArgs().hasArg(options::OPT_v) ||
813 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
814 PrintVersion(C, llvm::errs());
815 SuppressMissingInputWarning = true;
818 const ToolChain &TC = C.getDefaultToolChain();
820 if (C.getArgs().hasArg(options::OPT_v))
821 TC.printVerboseInfo(llvm::errs());
823 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
824 llvm::outs() << "programs: =";
825 bool separator = false;
826 for (const std::string &Path : TC.getProgramPaths()) {
829 llvm::outs() << Path;
832 llvm::outs() << "\n";
833 llvm::outs() << "libraries: =" << ResourceDir;
835 StringRef sysroot = C.getSysRoot();
837 for (const std::string &Path : TC.getFilePaths()) {
838 // Always print a separator. ResourceDir was the first item shown.
840 // Interpretation of leading '=' is needed only for NetBSD.
842 llvm::outs() << sysroot << Path.substr(1);
844 llvm::outs() << Path;
846 llvm::outs() << "\n";
850 // FIXME: The following handlers should use a callback mechanism, we don't
851 // know what the client would like to do.
852 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
853 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
857 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
858 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
862 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
863 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
867 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
868 for (const Multilib &Multilib : TC.getMultilibs())
869 llvm::outs() << Multilib << "\n";
873 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
874 for (const Multilib &Multilib : TC.getMultilibs()) {
875 if (Multilib.gccSuffix().empty())
876 llvm::outs() << ".\n";
878 StringRef Suffix(Multilib.gccSuffix());
879 assert(Suffix.front() == '/');
880 llvm::outs() << Suffix.substr(1) << "\n";
888 // Display an action graph human-readably. Action A is the "sink" node
889 // and latest-occuring action. Traversal is in pre-order, visiting the
890 // inputs to each action before printing the action itself.
891 static unsigned PrintActions1(const Compilation &C, Action *A,
892 std::map<Action *, unsigned> &Ids) {
893 if (Ids.count(A)) // A was already visited.
897 llvm::raw_string_ostream os(str);
899 os << Action::getClassName(A->getKind()) << ", ";
900 if (InputAction *IA = dyn_cast<InputAction>(A)) {
901 os << "\"" << IA->getInputArg().getValue() << "\"";
902 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
903 os << '"' << BIA->getArchName() << '"' << ", {"
904 << PrintActions1(C, *BIA->begin(), Ids) << "}";
905 } else if (CudaDeviceAction *CDA = dyn_cast<CudaDeviceAction>(A)) {
906 os << '"' << CDA->getGpuArchName() << '"' << ", {"
907 << PrintActions1(C, *CDA->begin(), Ids) << "}";
910 if (CudaHostAction *CHA = dyn_cast<CudaHostAction>(A)) {
911 os << "{" << PrintActions1(C, *CHA->begin(), Ids) << "}"
912 << ", gpu binaries ";
913 AL = &CHA->getDeviceActions();
915 AL = &A->getInputs();
917 const char *Prefix = "{";
918 for (Action *PreRequisite : *AL) {
919 os << Prefix << PrintActions1(C, PreRequisite, Ids);
925 unsigned Id = Ids.size();
927 llvm::errs() << Id << ": " << os.str() << ", "
928 << types::getTypeName(A->getType()) << "\n";
933 // Print the action graphs in a compilation C.
934 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
935 void Driver::PrintActions(const Compilation &C) const {
936 std::map<Action *, unsigned> Ids;
937 for (Action *A : C.getActions())
938 PrintActions1(C, A, Ids);
941 /// \brief Check whether the given input tree contains any compilation or
942 /// assembly actions.
943 static bool ContainsCompileOrAssembleAction(const Action *A) {
944 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
945 isa<AssembleJobAction>(A))
948 for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
949 if (ContainsCompileOrAssembleAction(*it))
955 void Driver::BuildUniversalActions(const ToolChain &TC, DerivedArgList &Args,
956 const InputList &BAInputs,
957 ActionList &Actions) const {
958 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
959 // Collect the list of architectures. Duplicates are allowed, but should only
960 // be handled once (in the order seen).
961 llvm::StringSet<> ArchNames;
962 SmallVector<const char *, 4> Archs;
963 for (Arg *A : Args) {
964 if (A->getOption().matches(options::OPT_arch)) {
965 // Validate the option here; we don't save the type here because its
966 // particular spelling may participate in other driver choices.
967 llvm::Triple::ArchType Arch =
968 tools::darwin::getArchTypeForMachOArchName(A->getValue());
969 if (Arch == llvm::Triple::UnknownArch) {
970 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
975 if (ArchNames.insert(A->getValue()).second)
976 Archs.push_back(A->getValue());
980 // When there is no explicit arch for this platform, make sure we still bind
981 // the architecture (to the default) so that -Xarch_ is handled correctly.
983 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
985 ActionList SingleActions;
986 BuildActions(TC, Args, BAInputs, SingleActions);
988 // Add in arch bindings for every top level action, as well as lipo and
989 // dsymutil steps if needed.
990 for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
991 Action *Act = SingleActions[i];
993 // Make sure we can lipo this kind of output. If not (and it is an actual
994 // output) then we disallow, since we can't create an output file with the
995 // right name without overwriting it. We could remove this oddity by just
996 // changing the output names to include the arch, which would also fix
997 // -save-temps. Compatibility wins for now.
999 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1000 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1001 << types::getTypeName(Act->getType());
1004 for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
1006 new BindArchAction(std::unique_ptr<Action>(Act), Archs[i]));
1008 Inputs.back()->setOwnsInputs(false);
1011 // Lipo if necessary, we do it this way because we need to set the arch flag
1012 // so that -Xarch_ gets overwritten.
1013 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1014 Actions.append(Inputs.begin(), Inputs.end());
1016 Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
1018 // Handle debug info queries.
1019 Arg *A = Args.getLastArg(options::OPT_g_Group);
1020 if (A && !A->getOption().matches(options::OPT_g0) &&
1021 !A->getOption().matches(options::OPT_gstabs) &&
1022 ContainsCompileOrAssembleAction(Actions.back())) {
1024 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1025 // have a compile input. We need to run 'dsymutil' ourselves in such cases
1026 // because the debug info will refer to a temporary object file which
1027 // will be removed at the end of the compilation process.
1028 if (Act->getType() == types::TY_Image) {
1030 Inputs.push_back(Actions.back());
1032 Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
1035 // Verify the debug info output.
1036 if (Args.hasArg(options::OPT_verify_debug_info)) {
1037 std::unique_ptr<Action> VerifyInput(Actions.back());
1039 Actions.push_back(new VerifyDebugInfoJobAction(std::move(VerifyInput),
1040 types::TY_Nothing));
1046 /// \brief Check that the file referenced by Value exists. If it doesn't,
1047 /// issue a diagnostic and return false.
1048 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
1050 if (!D.getCheckInputsExist())
1053 // stdin always exists.
1057 SmallString<64> Path(Value);
1058 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1059 if (!llvm::sys::path::is_absolute(Path)) {
1060 SmallString<64> Directory(WorkDir->getValue());
1061 llvm::sys::path::append(Directory, Value);
1062 Path.assign(Directory);
1066 if (llvm::sys::fs::exists(Twine(Path)))
1069 if (D.IsCLMode() && !llvm::sys::path::is_absolute(Twine(Path)) &&
1070 llvm::sys::Process::FindInEnvPath("LIB", Value))
1073 D.Diag(clang::diag::err_drv_no_such_file) << Path;
1077 // Construct a the list of inputs and their types.
1078 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
1079 InputList &Inputs) const {
1080 // Track the current user specified (-x) input. We also explicitly track the
1081 // argument used to set the type; we only want to claim the type when we
1082 // actually use it, so we warn about unused -x arguments.
1083 types::ID InputType = types::TY_Nothing;
1084 Arg *InputTypeArg = nullptr;
1086 // The last /TC or /TP option sets the input type to C or C++ globally.
1087 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1088 options::OPT__SLASH_TP)) {
1089 InputTypeArg = TCTP;
1090 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
1095 Args.filtered_begin(options::OPT__SLASH_TC, options::OPT__SLASH_TP);
1096 const arg_iterator ie = Args.filtered_end();
1097 Arg *Previous = *it++;
1098 bool ShowNote = false;
1100 Diag(clang::diag::warn_drv_overriding_flag_option)
1101 << Previous->getSpelling() << (*it)->getSpelling();
1106 Diag(clang::diag::note_drv_t_option_is_global);
1108 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1109 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1112 for (Arg *A : Args) {
1113 if (A->getOption().getKind() == Option::InputClass) {
1114 const char *Value = A->getValue();
1115 types::ID Ty = types::TY_INVALID;
1117 // Infer the input type if necessary.
1118 if (InputType == types::TY_Nothing) {
1119 // If there was an explicit arg for this, claim it.
1121 InputTypeArg->claim();
1123 // stdin must be handled specially.
1124 if (memcmp(Value, "-", 2) == 0) {
1125 // If running with -E, treat as a C input (this changes the builtin
1126 // macros, for example). This may be overridden by -ObjC below.
1128 // Otherwise emit an error but still use a valid type to avoid
1129 // spurious errors (e.g., no inputs).
1130 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
1131 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1132 : clang::diag::err_drv_unknown_stdin_type);
1135 // Otherwise lookup by extension.
1136 // Fallback is C if invoked as C preprocessor or Object otherwise.
1137 // We use a host hook here because Darwin at least has its own
1138 // idea of what .s is.
1139 if (const char *Ext = strrchr(Value, '.'))
1140 Ty = TC.LookupTypeForExtension(Ext + 1);
1142 if (Ty == types::TY_INVALID) {
1146 Ty = types::TY_Object;
1149 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1150 // should autodetect some input files as C++ for g++ compatibility.
1152 types::ID OldTy = Ty;
1153 Ty = types::lookupCXXTypeForCType(Ty);
1156 Diag(clang::diag::warn_drv_treating_input_as_cxx)
1157 << getTypeName(OldTy) << getTypeName(Ty);
1161 // -ObjC and -ObjC++ override the default language, but only for "source
1162 // files". We just treat everything that isn't a linker input as a
1165 // FIXME: Clean this up if we move the phase sequence into the type.
1166 if (Ty != types::TY_Object) {
1167 if (Args.hasArg(options::OPT_ObjC))
1168 Ty = types::TY_ObjC;
1169 else if (Args.hasArg(options::OPT_ObjCXX))
1170 Ty = types::TY_ObjCXX;
1173 assert(InputTypeArg && "InputType set w/o InputTypeArg");
1174 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1175 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1177 const char *Ext = strrchr(Value, '.');
1178 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1179 Ty = types::TY_Object;
1181 if (Ty == types::TY_INVALID) {
1183 InputTypeArg->claim();
1187 if (DiagnoseInputExistence(*this, Args, Value))
1188 Inputs.push_back(std::make_pair(Ty, A));
1190 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1191 StringRef Value = A->getValue();
1192 if (DiagnoseInputExistence(*this, Args, Value)) {
1193 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1194 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1197 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1198 StringRef Value = A->getValue();
1199 if (DiagnoseInputExistence(*this, Args, Value)) {
1200 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1201 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1204 } else if (A->getOption().hasFlag(options::LinkerInput)) {
1205 // Just treat as object type, we could make a special type for this if
1207 Inputs.push_back(std::make_pair(types::TY_Object, A));
1209 } else if (A->getOption().matches(options::OPT_x)) {
1211 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
1214 // Follow gcc behavior and treat as linker input for invalid -x
1215 // options. Its not clear why we shouldn't just revert to unknown; but
1216 // this isn't very important, we might as well be bug compatible.
1218 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
1219 InputType = types::TY_Object;
1223 if (CCCIsCPP() && Inputs.empty()) {
1224 // If called as standalone preprocessor, stdin is processed
1225 // if no other input is present.
1226 Arg *A = MakeInputArg(Args, Opts, "-");
1227 Inputs.push_back(std::make_pair(types::TY_C, A));
1231 // For each unique --cuda-gpu-arch= argument creates a TY_CUDA_DEVICE input
1232 // action and then wraps each in CudaDeviceAction paired with appropriate GPU
1233 // arch name. If we're only building device-side code, each action remains
1234 // independent. Otherwise we pass device-side actions as inputs to a new
1235 // CudaHostAction which combines both host and device side actions.
1236 static std::unique_ptr<Action>
1237 buildCudaActions(const Driver &D, const ToolChain &TC, DerivedArgList &Args,
1238 const Arg *InputArg, const types::ID InputType,
1239 std::unique_ptr<Action> Current, ActionList &Actions) {
1241 assert(InputType == types::TY_CUDA &&
1242 "CUDA Actions only apply to CUDA inputs.");
1244 // Collect all cuda_gpu_arch parameters, removing duplicates.
1245 SmallVector<const char *, 4> GpuArchList;
1246 llvm::StringSet<> GpuArchNames;
1247 for (Arg *A : Args) {
1248 if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ)) {
1250 if (GpuArchNames.insert(A->getValue()).second)
1251 GpuArchList.push_back(A->getValue());
1255 // Default to sm_20 which is the lowest common denominator for supported GPUs.
1256 // sm_20 code should work correctly, if suboptimally, on all newer GPUs.
1257 if (GpuArchList.empty())
1258 GpuArchList.push_back("sm_20");
1260 // Replicate inputs for each GPU architecture.
1261 Driver::InputList CudaDeviceInputs;
1262 for (unsigned i = 0, e = GpuArchList.size(); i != e; ++i)
1263 CudaDeviceInputs.push_back(std::make_pair(types::TY_CUDA_DEVICE, InputArg));
1265 // Build actions for all device inputs.
1266 ActionList CudaDeviceActions;
1267 D.BuildActions(TC, Args, CudaDeviceInputs, CudaDeviceActions);
1268 assert(GpuArchList.size() == CudaDeviceActions.size() &&
1269 "Failed to create actions for all devices");
1271 // Check whether any of device actions stopped before they could generate PTX.
1272 bool PartialCompilation = false;
1273 bool DeviceOnlyCompilation = Args.hasArg(options::OPT_cuda_device_only);
1274 for (unsigned i = 0, e = GpuArchList.size(); i != e; ++i) {
1275 if (CudaDeviceActions[i]->getKind() != Action::BackendJobClass) {
1276 PartialCompilation = true;
1281 // Figure out what to do with device actions -- pass them as inputs to the
1282 // host action or run each of them independently.
1283 if (PartialCompilation || DeviceOnlyCompilation) {
1284 // In case of partial or device-only compilation results of device actions
1285 // are not consumed by the host action device actions have to be added to
1286 // top-level actions list with AtTopLevel=true and run independently.
1288 // -o is ambiguous if we have more than one top-level action.
1289 if (Args.hasArg(options::OPT_o) &&
1290 (!DeviceOnlyCompilation || GpuArchList.size() > 1)) {
1291 D.Diag(clang::diag::err_drv_output_argument_with_multiple_files);
1295 for (unsigned i = 0, e = GpuArchList.size(); i != e; ++i)
1297 new CudaDeviceAction(std::unique_ptr<Action>(CudaDeviceActions[i]),
1298 GpuArchList[i], /* AtTopLevel */ true));
1299 // Kill host action in case of device-only compilation.
1300 if (DeviceOnlyCompilation)
1301 Current.reset(nullptr);
1304 // Outputs of device actions during complete CUDA compilation get created
1305 // with AtTopLevel=false and become inputs for the host action.
1306 ActionList DeviceActions;
1307 for (unsigned i = 0, e = GpuArchList.size(); i != e; ++i)
1308 DeviceActions.push_back(
1309 new CudaDeviceAction(std::unique_ptr<Action>(CudaDeviceActions[i]),
1310 GpuArchList[i], /* AtTopLevel */ false));
1311 // Return a new host action that incorporates original host action and all
1313 return std::unique_ptr<Action>(
1314 new CudaHostAction(std::move(Current), DeviceActions));
1318 void Driver::BuildActions(const ToolChain &TC, DerivedArgList &Args,
1319 const InputList &Inputs, ActionList &Actions) const {
1320 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
1322 if (!SuppressMissingInputWarning && Inputs.empty()) {
1323 Diag(clang::diag::err_drv_no_input_files);
1328 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
1330 if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) {
1331 Diag(clang::diag::err_drv_emit_llvm_link);
1334 // Reject -Z* at the top level, these options should never have been exposed
1336 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
1337 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
1339 // Diagnose misuse of /Fo.
1340 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
1341 StringRef V = A->getValue();
1342 if (Inputs.size() > 1 && !V.empty() &&
1343 !llvm::sys::path::is_separator(V.back())) {
1344 // Check whether /Fo tries to name an output file for multiple inputs.
1345 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
1346 << A->getSpelling() << V;
1347 Args.eraseArg(options::OPT__SLASH_Fo);
1351 // Diagnose misuse of /Fa.
1352 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
1353 StringRef V = A->getValue();
1354 if (Inputs.size() > 1 && !V.empty() &&
1355 !llvm::sys::path::is_separator(V.back())) {
1356 // Check whether /Fa tries to name an asm file for multiple inputs.
1357 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
1358 << A->getSpelling() << V;
1359 Args.eraseArg(options::OPT__SLASH_Fa);
1363 // Diagnose misuse of /o.
1364 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
1365 if (A->getValue()[0] == '\0') {
1366 // It has to have a value.
1367 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
1368 Args.eraseArg(options::OPT__SLASH_o);
1372 // Construct the actions to perform.
1373 ActionList LinkerInputs;
1375 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
1376 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
1377 types::ID InputType = Inputs[i].first;
1378 const Arg *InputArg = Inputs[i].second;
1381 types::getCompilationPhases(InputType, PL);
1383 // If the first step comes after the final phase we are doing as part of
1384 // this compilation, warn the user about it.
1385 phases::ID InitialPhase = PL[0];
1386 if (InitialPhase > FinalPhase) {
1387 // Claim here to avoid the more general unused warning.
1390 // Suppress all unused style warnings with -Qunused-arguments
1391 if (Args.hasArg(options::OPT_Qunused_arguments))
1394 // Special case when final phase determined by binary name, rather than
1395 // by a command-line argument with a corresponding Arg.
1397 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
1398 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
1399 // Special case '-E' warning on a previously preprocessed file to make
1401 else if (InitialPhase == phases::Compile &&
1402 FinalPhase == phases::Preprocess &&
1403 getPreprocessedType(InputType) == types::TY_INVALID)
1404 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
1405 << InputArg->getAsString(Args) << !!FinalPhaseArg
1406 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
1408 Diag(clang::diag::warn_drv_input_file_unused)
1409 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
1411 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
1415 phases::ID CudaInjectionPhase;
1416 if (isSaveTempsEnabled()) {
1417 // All phases are done independently, inject GPU blobs during compilation
1418 // phase as that's where we generate glue code to init them.
1419 CudaInjectionPhase = phases::Compile;
1421 // Assumes that clang does everything up until linking phase, so we inject
1422 // cuda device actions at the last step before linking. Otherwise CUDA
1423 // host action forces preprocessor into a separate invocation.
1424 if (FinalPhase == phases::Link) {
1425 for (auto i = PL.begin(), e = PL.end(); i != e; ++i) {
1427 if (next != e && *next == phases::Link)
1428 CudaInjectionPhase = *i;
1431 CudaInjectionPhase = FinalPhase;
1434 // Build the pipeline for this file.
1435 std::unique_ptr<Action> Current(new InputAction(*InputArg, InputType));
1436 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
1438 phases::ID Phase = *i;
1440 // We are done if this step is past what the user requested.
1441 if (Phase > FinalPhase)
1444 // Queue linker inputs.
1445 if (Phase == phases::Link) {
1446 assert((i + 1) == e && "linking must be final compilation step.");
1447 LinkerInputs.push_back(Current.release());
1451 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
1452 // encode this in the steps because the intermediate type depends on
1453 // arguments. Just special case here.
1454 if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
1457 // Otherwise construct the appropriate action.
1458 Current = ConstructPhaseAction(TC, Args, Phase, std::move(Current));
1460 if (InputType == types::TY_CUDA && Phase == CudaInjectionPhase &&
1461 !Args.hasArg(options::OPT_cuda_host_only)) {
1462 Current = buildCudaActions(*this, TC, Args, InputArg, InputType,
1463 std::move(Current), Actions);
1468 if (Current->getType() == types::TY_Nothing)
1472 // If we ended with something, add to the output list.
1474 Actions.push_back(Current.release());
1477 // Add a link action if necessary.
1478 if (!LinkerInputs.empty())
1479 Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
1481 // If we are linking, claim any options which are obviously only used for
1483 if (FinalPhase == phases::Link && PL.size() == 1) {
1484 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
1485 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
1488 // Claim ignored clang-cl options.
1489 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
1492 std::unique_ptr<Action>
1493 Driver::ConstructPhaseAction(const ToolChain &TC, const ArgList &Args,
1495 std::unique_ptr<Action> Input) const {
1496 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
1497 // Build the appropriate action.
1500 llvm_unreachable("link action invalid here.");
1501 case phases::Preprocess: {
1503 // -{M, MM} alter the output type.
1504 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
1505 OutputTy = types::TY_Dependencies;
1507 OutputTy = Input->getType();
1508 if (!Args.hasFlag(options::OPT_frewrite_includes,
1509 options::OPT_fno_rewrite_includes, false) &&
1511 OutputTy = types::getPreprocessedType(OutputTy);
1512 assert(OutputTy != types::TY_INVALID &&
1513 "Cannot preprocess this input type!");
1515 return llvm::make_unique<PreprocessJobAction>(std::move(Input), OutputTy);
1517 case phases::Precompile: {
1518 types::ID OutputTy = types::TY_PCH;
1519 if (Args.hasArg(options::OPT_fsyntax_only)) {
1520 // Syntax checks should not emit a PCH file
1521 OutputTy = types::TY_Nothing;
1523 return llvm::make_unique<PrecompileJobAction>(std::move(Input), OutputTy);
1525 case phases::Compile: {
1526 if (Args.hasArg(options::OPT_fsyntax_only))
1527 return llvm::make_unique<CompileJobAction>(std::move(Input),
1529 if (Args.hasArg(options::OPT_rewrite_objc))
1530 return llvm::make_unique<CompileJobAction>(std::move(Input),
1531 types::TY_RewrittenObjC);
1532 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
1533 return llvm::make_unique<CompileJobAction>(std::move(Input),
1534 types::TY_RewrittenLegacyObjC);
1535 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
1536 return llvm::make_unique<AnalyzeJobAction>(std::move(Input),
1538 if (Args.hasArg(options::OPT__migrate))
1539 return llvm::make_unique<MigrateJobAction>(std::move(Input),
1541 if (Args.hasArg(options::OPT_emit_ast))
1542 return llvm::make_unique<CompileJobAction>(std::move(Input),
1544 if (Args.hasArg(options::OPT_module_file_info))
1545 return llvm::make_unique<CompileJobAction>(std::move(Input),
1546 types::TY_ModuleFile);
1547 if (Args.hasArg(options::OPT_verify_pch))
1548 return llvm::make_unique<VerifyPCHJobAction>(std::move(Input),
1550 return llvm::make_unique<CompileJobAction>(std::move(Input),
1553 case phases::Backend: {
1554 if (IsUsingLTO(Args)) {
1556 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
1557 return llvm::make_unique<BackendJobAction>(std::move(Input), Output);
1559 if (Args.hasArg(options::OPT_emit_llvm)) {
1561 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
1562 return llvm::make_unique<BackendJobAction>(std::move(Input), Output);
1564 return llvm::make_unique<BackendJobAction>(std::move(Input),
1567 case phases::Assemble:
1568 return llvm::make_unique<AssembleJobAction>(std::move(Input),
1572 llvm_unreachable("invalid phase in ConstructPhaseAction");
1575 bool Driver::IsUsingLTO(const ArgList &Args) const {
1576 return Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false);
1579 void Driver::BuildJobs(Compilation &C) const {
1580 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1582 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
1584 // It is an error to provide a -o option if we are making multiple output
1587 unsigned NumOutputs = 0;
1588 for (const Action *A : C.getActions())
1589 if (A->getType() != types::TY_Nothing)
1592 if (NumOutputs > 1) {
1593 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
1594 FinalOutput = nullptr;
1598 // Collect the list of architectures.
1599 llvm::StringSet<> ArchNames;
1600 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
1601 for (const Arg *A : C.getArgs())
1602 if (A->getOption().matches(options::OPT_arch))
1603 ArchNames.insert(A->getValue());
1605 for (Action *A : C.getActions()) {
1606 // If we are linking an image for multiple archs then the linker wants
1607 // -arch_multiple and -final_output <final image name>. Unfortunately, this
1608 // doesn't fit in cleanly because we have to pass this information down.
1610 // FIXME: This is a hack; find a cleaner way to integrate this into the
1612 const char *LinkingOutput = nullptr;
1613 if (isa<LipoJobAction>(A)) {
1615 LinkingOutput = FinalOutput->getValue();
1617 LinkingOutput = getDefaultImageName();
1621 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
1622 /*BoundArch*/ nullptr,
1623 /*AtTopLevel*/ true,
1624 /*MultipleArchs*/ ArchNames.size() > 1,
1625 /*LinkingOutput*/ LinkingOutput, II);
1628 // If the user passed -Qunused-arguments or there were errors, don't warn
1629 // about any unused arguments.
1630 if (Diags.hasErrorOccurred() ||
1631 C.getArgs().hasArg(options::OPT_Qunused_arguments))
1635 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1637 // Claim --driver-mode, it was handled earlier.
1638 (void)C.getArgs().hasArg(options::OPT_driver_mode);
1640 for (Arg *A : C.getArgs()) {
1641 // FIXME: It would be nice to be able to send the argument to the
1642 // DiagnosticsEngine, so that extra values, position, and so on could be
1644 if (!A->isClaimed()) {
1645 if (A->getOption().hasFlag(options::NoArgumentUnused))
1648 // Suppress the warning automatically if this is just a flag, and it is an
1649 // instance of an argument we already claimed.
1650 const Option &Opt = A->getOption();
1651 if (Opt.getKind() == Option::FlagClass) {
1652 bool DuplicateClaimed = false;
1654 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
1655 if (AA->isClaimed()) {
1656 DuplicateClaimed = true;
1661 if (DuplicateClaimed)
1665 Diag(clang::diag::warn_drv_unused_argument)
1666 << A->getAsString(C.getArgs());
1671 static const Tool *SelectToolForJob(Compilation &C, bool SaveTemps,
1672 const ToolChain *TC, const JobAction *JA,
1673 const ActionList *&Inputs) {
1674 const Tool *ToolForJob = nullptr;
1676 // See if we should look for a compiler with an integrated assembler. We match
1677 // bottom up, so what we are actually looking for is an assembler job with a
1680 if (TC->useIntegratedAs() && !SaveTemps &&
1681 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
1682 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
1683 !C.getArgs().hasArg(options::OPT__SLASH_Fa) &&
1684 isa<AssembleJobAction>(JA) && Inputs->size() == 1 &&
1685 isa<BackendJobAction>(*Inputs->begin())) {
1686 // A BackendJob is always preceded by a CompileJob, and without
1687 // -save-temps they will always get combined together, so instead of
1688 // checking the backend tool, check if the tool for the CompileJob
1689 // has an integrated assembler.
1690 const ActionList *BackendInputs = &(*Inputs)[0]->getInputs();
1691 JobAction *CompileJA = cast<CompileJobAction>(*BackendInputs->begin());
1692 const Tool *Compiler = TC->SelectTool(*CompileJA);
1695 if (Compiler->hasIntegratedAssembler()) {
1696 Inputs = &(*BackendInputs)[0]->getInputs();
1697 ToolForJob = Compiler;
1701 // A backend job should always be combined with the preceding compile job
1702 // unless OPT_save_temps is enabled and the compiler is capable of emitting
1703 // LLVM IR as an intermediate output.
1704 if (isa<BackendJobAction>(JA)) {
1705 // Check if the compiler supports emitting LLVM IR.
1706 assert(Inputs->size() == 1);
1707 JobAction *CompileJA;
1708 // Extract real host action, if it's a CudaHostAction.
1709 if (CudaHostAction *CudaHA = dyn_cast<CudaHostAction>(*Inputs->begin()))
1710 CompileJA = cast<CompileJobAction>(*CudaHA->begin());
1712 CompileJA = cast<CompileJobAction>(*Inputs->begin());
1714 const Tool *Compiler = TC->SelectTool(*CompileJA);
1717 if (!Compiler->canEmitIR() || !SaveTemps) {
1718 Inputs = &(*Inputs)[0]->getInputs();
1719 ToolForJob = Compiler;
1723 // Otherwise use the tool for the current job.
1725 ToolForJob = TC->SelectTool(*JA);
1727 // See if we should use an integrated preprocessor. We do so when we have
1728 // exactly one input, since this is the only use case we care about
1729 // (irrelevant since we don't support combine yet).
1730 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
1731 !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
1732 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
1733 !C.getArgs().hasArg(options::OPT_rewrite_objc) &&
1734 ToolForJob->hasIntegratedCPP())
1735 Inputs = &(*Inputs)[0]->getInputs();
1740 void Driver::BuildJobsForAction(Compilation &C, const Action *A,
1741 const ToolChain *TC, const char *BoundArch,
1742 bool AtTopLevel, bool MultipleArchs,
1743 const char *LinkingOutput,
1744 InputInfo &Result) const {
1745 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1747 InputInfoList CudaDeviceInputInfos;
1748 if (const CudaHostAction *CHA = dyn_cast<CudaHostAction>(A)) {
1750 // Append outputs of device jobs to the input list.
1751 for (const Action *DA : CHA->getDeviceActions()) {
1752 BuildJobsForAction(C, DA, TC, "", AtTopLevel,
1753 /*MultipleArchs*/ false, LinkingOutput, II);
1754 CudaDeviceInputInfos.push_back(II);
1756 // Override current action with a real host compile action and continue
1761 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
1762 // FIXME: It would be nice to not claim this here; maybe the old scheme of
1763 // just using Args was better?
1764 const Arg &Input = IA->getInputArg();
1766 if (Input.getOption().matches(options::OPT_INPUT)) {
1767 const char *Name = Input.getValue();
1768 Result = InputInfo(Name, A->getType(), Name);
1770 Result = InputInfo(&Input, A->getType(), "");
1775 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1776 const ToolChain *TC;
1777 const char *ArchName = BAA->getArchName();
1782 computeTargetTriple(DefaultTargetTriple, C.getArgs(), ArchName));
1784 TC = &C.getDefaultToolChain();
1786 BuildJobsForAction(C, *BAA->begin(), TC, ArchName, AtTopLevel,
1787 MultipleArchs, LinkingOutput, Result);
1791 if (const CudaDeviceAction *CDA = dyn_cast<CudaDeviceAction>(A)) {
1792 // Figure out which NVPTX triple to use for device-side compilation based on
1793 // whether host is 64-bit.
1794 llvm::Triple DeviceTriple(C.getDefaultToolChain().getTriple().isArch64Bit()
1795 ? "nvptx64-nvidia-cuda"
1796 : "nvptx-nvidia-cuda");
1797 BuildJobsForAction(C, *CDA->begin(),
1798 &getToolChain(C.getArgs(), DeviceTriple),
1799 CDA->getGpuArchName(), CDA->isAtTopLevel(),
1800 /*MultipleArchs*/ true, LinkingOutput, Result);
1804 const ActionList *Inputs = &A->getInputs();
1806 const JobAction *JA = cast<JobAction>(A);
1807 const Tool *T = SelectToolForJob(C, isSaveTempsEnabled(), TC, JA, Inputs);
1811 // Only use pipes when there is exactly one input.
1812 InputInfoList InputInfos;
1813 for (const Action *Input : *Inputs) {
1814 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
1815 // shouldn't get temporary output names.
1816 // FIXME: Clean this up.
1817 bool SubJobAtTopLevel = false;
1818 if (AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A)))
1819 SubJobAtTopLevel = true;
1822 BuildJobsForAction(C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs,
1824 InputInfos.push_back(II);
1827 // Always use the first input as the base input.
1828 const char *BaseInput = InputInfos[0].getBaseInput();
1830 // ... except dsymutil actions, which use their actual input as the base
1832 if (JA->getType() == types::TY_dSYM)
1833 BaseInput = InputInfos[0].getFilename();
1835 // Append outputs of cuda device jobs to the input list
1836 if (CudaDeviceInputInfos.size())
1837 InputInfos.append(CudaDeviceInputInfos.begin(), CudaDeviceInputInfos.end());
1839 // Determine the place to write output to, if any.
1840 if (JA->getType() == types::TY_Nothing)
1841 Result = InputInfo(A->getType(), BaseInput);
1843 Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
1844 AtTopLevel, MultipleArchs),
1845 A->getType(), BaseInput);
1847 if (CCCPrintBindings && !CCGenDiagnostics) {
1848 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
1849 << " - \"" << T->getName() << "\", inputs: [";
1850 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1851 llvm::errs() << InputInfos[i].getAsString();
1853 llvm::errs() << ", ";
1855 llvm::errs() << "], output: " << Result.getAsString() << "\n";
1857 T->ConstructJob(C, *JA, Result, InputInfos,
1858 C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
1862 const char *Driver::getDefaultImageName() const {
1863 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
1864 return Target.isOSWindows() ? "a.exe" : "a.out";
1867 /// \brief Create output filename based on ArgValue, which could either be a
1868 /// full filename, filename without extension, or a directory. If ArgValue
1869 /// does not provide a filename, then use BaseName, and use the extension
1870 /// suitable for FileType.
1871 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
1873 types::ID FileType) {
1874 SmallString<128> Filename = ArgValue;
1876 if (ArgValue.empty()) {
1877 // If the argument is empty, output to BaseName in the current dir.
1878 Filename = BaseName;
1879 } else if (llvm::sys::path::is_separator(Filename.back())) {
1880 // If the argument is a directory, output to BaseName in that dir.
1881 llvm::sys::path::append(Filename, BaseName);
1884 if (!llvm::sys::path::has_extension(ArgValue)) {
1885 // If the argument didn't provide an extension, then set it.
1886 const char *Extension = types::getTypeTempSuffix(FileType, true);
1888 if (FileType == types::TY_Image &&
1889 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
1890 // The output file is a dll.
1894 llvm::sys::path::replace_extension(Filename, Extension);
1897 return Args.MakeArgString(Filename.c_str());
1900 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
1901 const char *BaseInput,
1902 const char *BoundArch, bool AtTopLevel,
1903 bool MultipleArchs) const {
1904 llvm::PrettyStackTraceString CrashInfo("Computing output path");
1905 // Output to a user requested destination?
1906 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
1907 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1908 return C.addResultFile(FinalOutput->getValue(), &JA);
1911 // For /P, preprocess to file named after BaseInput.
1912 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
1913 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
1914 StringRef BaseName = llvm::sys::path::filename(BaseInput);
1916 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
1917 NameArg = A->getValue();
1918 return C.addResultFile(
1919 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
1923 // Default to writing to stdout?
1924 if (AtTopLevel && !CCGenDiagnostics &&
1925 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
1928 // Is this the assembly listing for /FA?
1929 if (JA.getType() == types::TY_PP_Asm &&
1930 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
1931 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
1932 // Use /Fa and the input filename to determine the asm file name.
1933 StringRef BaseName = llvm::sys::path::filename(BaseInput);
1934 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
1935 return C.addResultFile(
1936 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
1940 // Output to a temporary file?
1941 if ((!AtTopLevel && !isSaveTempsEnabled() &&
1942 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
1944 StringRef Name = llvm::sys::path::filename(BaseInput);
1945 std::pair<StringRef, StringRef> Split = Name.split('.');
1946 std::string TmpName = GetTemporaryPath(
1947 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
1948 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1951 SmallString<128> BasePath(BaseInput);
1954 // Dsymutil actions should use the full path.
1955 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
1956 BaseName = BasePath;
1958 BaseName = llvm::sys::path::filename(BasePath);
1960 // Determine what the derived output name should be.
1961 const char *NamedOutput;
1963 if (JA.getType() == types::TY_Object &&
1964 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
1965 // The /Fo or /o flag decides the object filename.
1968 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
1971 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
1972 } else if (JA.getType() == types::TY_Image &&
1973 C.getArgs().hasArg(options::OPT__SLASH_Fe,
1974 options::OPT__SLASH_o)) {
1975 // The /Fe or /o flag names the linked file.
1978 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
1981 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
1982 } else if (JA.getType() == types::TY_Image) {
1984 // clang-cl uses BaseName for the executable name.
1986 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
1987 } else if (MultipleArchs && BoundArch) {
1988 SmallString<128> Output(getDefaultImageName());
1990 Output.append(BoundArch);
1991 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
1993 NamedOutput = getDefaultImageName();
1995 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
1996 assert(Suffix && "All types used for output should have a suffix.");
1998 std::string::size_type End = std::string::npos;
1999 if (!types::appendSuffixForType(JA.getType()))
2000 End = BaseName.rfind('.');
2001 SmallString<128> Suffixed(BaseName.substr(0, End));
2002 if (MultipleArchs && BoundArch) {
2004 Suffixed.append(BoundArch);
2006 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
2007 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
2008 // optimized bitcode output.
2009 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
2010 JA.getType() == types::TY_LLVM_BC)
2014 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
2017 // Prepend object file path if -save-temps=obj
2018 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
2019 JA.getType() != types::TY_PCH) {
2020 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2021 SmallString<128> TempPath(FinalOutput->getValue());
2022 llvm::sys::path::remove_filename(TempPath);
2023 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
2024 llvm::sys::path::append(TempPath, OutputFileName);
2025 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
2028 // If we're saving temps and the temp file conflicts with the input file,
2029 // then avoid overwriting input file.
2030 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
2031 bool SameFile = false;
2032 SmallString<256> Result;
2033 llvm::sys::fs::current_path(Result);
2034 llvm::sys::path::append(Result, BaseName);
2035 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
2036 // Must share the same path to conflict.
2038 StringRef Name = llvm::sys::path::filename(BaseInput);
2039 std::pair<StringRef, StringRef> Split = Name.split('.');
2040 std::string TmpName = GetTemporaryPath(
2041 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
2042 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
2046 // As an annoying special case, PCH generation doesn't strip the pathname.
2047 if (JA.getType() == types::TY_PCH) {
2048 llvm::sys::path::remove_filename(BasePath);
2049 if (BasePath.empty())
2050 BasePath = NamedOutput;
2052 llvm::sys::path::append(BasePath, NamedOutput);
2053 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
2055 return C.addResultFile(NamedOutput, &JA);
2059 std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
2060 // Respect a limited subset of the '-Bprefix' functionality in GCC by
2061 // attempting to use this prefix when looking for file paths.
2062 for (const std::string &Dir : PrefixDirs) {
2065 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
2066 llvm::sys::path::append(P, Name);
2067 if (llvm::sys::fs::exists(Twine(P)))
2071 SmallString<128> P(ResourceDir);
2072 llvm::sys::path::append(P, Name);
2073 if (llvm::sys::fs::exists(Twine(P)))
2076 for (const std::string &Dir : TC.getFilePaths()) {
2079 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
2080 llvm::sys::path::append(P, Name);
2081 if (llvm::sys::fs::exists(Twine(P)))
2088 void Driver::generatePrefixedToolNames(
2089 const char *Tool, const ToolChain &TC,
2090 SmallVectorImpl<std::string> &Names) const {
2091 // FIXME: Needs a better variable than DefaultTargetTriple
2092 Names.emplace_back(DefaultTargetTriple + "-" + Tool);
2093 Names.emplace_back(Tool);
2096 static bool ScanDirForExecutable(SmallString<128> &Dir,
2097 ArrayRef<std::string> Names) {
2098 for (const auto &Name : Names) {
2099 llvm::sys::path::append(Dir, Name);
2100 if (llvm::sys::fs::can_execute(Twine(Dir)))
2102 llvm::sys::path::remove_filename(Dir);
2107 std::string Driver::GetProgramPath(const char *Name,
2108 const ToolChain &TC) const {
2109 SmallVector<std::string, 2> TargetSpecificExecutables;
2110 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
2112 // Respect a limited subset of the '-Bprefix' functionality in GCC by
2113 // attempting to use this prefix when looking for program paths.
2114 for (const auto &PrefixDir : PrefixDirs) {
2115 if (llvm::sys::fs::is_directory(PrefixDir)) {
2116 SmallString<128> P(PrefixDir);
2117 if (ScanDirForExecutable(P, TargetSpecificExecutables))
2120 SmallString<128> P(PrefixDir + Name);
2121 if (llvm::sys::fs::can_execute(Twine(P)))
2126 const ToolChain::path_list &List = TC.getProgramPaths();
2127 for (const auto &Path : List) {
2128 SmallString<128> P(Path);
2129 if (ScanDirForExecutable(P, TargetSpecificExecutables))
2133 // If all else failed, search the path.
2134 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
2135 if (llvm::ErrorOr<std::string> P =
2136 llvm::sys::findProgramByName(TargetSpecificExecutable))
2142 std::string Driver::GetTemporaryPath(StringRef Prefix,
2143 const char *Suffix) const {
2144 SmallString<128> Path;
2145 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
2147 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
2154 const ToolChain &Driver::getToolChain(const ArgList &Args,
2155 const llvm::Triple &Target) const {
2157 ToolChain *&TC = ToolChains[Target.str()];
2159 switch (Target.getOS()) {
2160 case llvm::Triple::CloudABI:
2161 TC = new toolchains::CloudABI(*this, Target, Args);
2163 case llvm::Triple::Darwin:
2164 case llvm::Triple::MacOSX:
2165 case llvm::Triple::IOS:
2166 TC = new toolchains::DarwinClang(*this, Target, Args);
2168 case llvm::Triple::DragonFly:
2169 TC = new toolchains::DragonFly(*this, Target, Args);
2171 case llvm::Triple::OpenBSD:
2172 TC = new toolchains::OpenBSD(*this, Target, Args);
2174 case llvm::Triple::Bitrig:
2175 TC = new toolchains::Bitrig(*this, Target, Args);
2177 case llvm::Triple::NetBSD:
2178 TC = new toolchains::NetBSD(*this, Target, Args);
2180 case llvm::Triple::FreeBSD:
2181 TC = new toolchains::FreeBSD(*this, Target, Args);
2183 case llvm::Triple::Minix:
2184 TC = new toolchains::Minix(*this, Target, Args);
2186 case llvm::Triple::Linux:
2187 if (Target.getArch() == llvm::Triple::hexagon)
2188 TC = new toolchains::Hexagon_TC(*this, Target, Args);
2190 TC = new toolchains::Linux(*this, Target, Args);
2192 case llvm::Triple::NaCl:
2193 TC = new toolchains::NaCl_TC(*this, Target, Args);
2195 case llvm::Triple::Solaris:
2196 TC = new toolchains::Solaris(*this, Target, Args);
2198 case llvm::Triple::Win32:
2199 switch (Target.getEnvironment()) {
2201 if (Target.isOSBinFormatELF())
2202 TC = new toolchains::Generic_ELF(*this, Target, Args);
2203 else if (Target.isOSBinFormatMachO())
2204 TC = new toolchains::MachO(*this, Target, Args);
2206 TC = new toolchains::Generic_GCC(*this, Target, Args);
2208 case llvm::Triple::GNU:
2209 TC = new toolchains::MinGW(*this, Target, Args);
2211 case llvm::Triple::Itanium:
2212 TC = new toolchains::CrossWindowsToolChain(*this, Target, Args);
2214 case llvm::Triple::MSVC:
2215 case llvm::Triple::UnknownEnvironment:
2216 TC = new toolchains::MSVCToolChain(*this, Target, Args);
2220 case llvm::Triple::CUDA:
2221 TC = new toolchains::CudaToolChain(*this, Target, Args);
2224 // Of these targets, Hexagon is the only one that might have
2225 // an OS of Linux, in which case it got handled above already.
2226 if (Target.getArchName() == "tce")
2227 TC = new toolchains::TCEToolChain(*this, Target, Args);
2228 else if (Target.getArch() == llvm::Triple::hexagon)
2229 TC = new toolchains::Hexagon_TC(*this, Target, Args);
2230 else if (Target.getArch() == llvm::Triple::xcore)
2231 TC = new toolchains::XCore(*this, Target, Args);
2232 else if (Target.getArch() == llvm::Triple::shave)
2233 TC = new toolchains::SHAVEToolChain(*this, Target, Args);
2234 else if (Target.isOSBinFormatELF())
2235 TC = new toolchains::Generic_ELF(*this, Target, Args);
2236 else if (Target.isOSBinFormatMachO())
2237 TC = new toolchains::MachO(*this, Target, Args);
2239 TC = new toolchains::Generic_GCC(*this, Target, Args);
2246 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
2247 // Say "no" if there is not exactly one input of a type clang understands.
2248 if (JA.size() != 1 || !types::isAcceptedByClang((*JA.begin())->getType()))
2251 // And say "no" if this is not a kind of action clang understands.
2252 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
2253 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
2259 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
2260 /// grouped values as integers. Numbers which are not provided are set to 0.
2262 /// \return True if the entire string was parsed (9.2), or all groups were
2263 /// parsed (10.3.5extrastuff).
2264 bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
2265 unsigned &Minor, unsigned &Micro,
2269 Major = Minor = Micro = 0;
2274 Major = (unsigned)strtol(Str, &End, 10);
2275 if (*Str != '\0' && *End == '\0')
2281 Minor = (unsigned)strtol(Str, &End, 10);
2282 if (*Str != '\0' && *End == '\0')
2288 Micro = (unsigned)strtol(Str, &End, 10);
2289 if (*Str != '\0' && *End == '\0')
2297 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
2298 unsigned IncludedFlagsBitmask = 0;
2299 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
2301 if (Mode == CLMode) {
2302 // Include CL and Core options.
2303 IncludedFlagsBitmask |= options::CLOption;
2304 IncludedFlagsBitmask |= options::CoreOption;
2306 ExcludedFlagsBitmask |= options::CLOption;
2309 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
2312 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
2313 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);