]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/Driver.cpp
Merge OpenSSL 1.0.2e.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Driver / Driver.cpp
1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
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"
41 #include <map>
42 #include <memory>
43
44 using namespace clang::driver;
45 using namespace clang;
46 using namespace llvm::opt;
47
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) {
59
60   Name = llvm::sys::path::filename(ClangExecutable);
61   Dir = llvm::sys::path::parent_path(ClangExecutable);
62
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);
68   } else {
69     StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
70     llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang",
71                             CLANG_VERSION_STRING);
72   }
73   ResourceDir = P.str();
74 }
75
76 Driver::~Driver() {
77   delete Opts;
78
79   llvm::DeleteContainerSeconds(ToolChains);
80 }
81
82 void Driver::ParseDriverMode(ArrayRef<const char *> Args) {
83   const std::string OptName =
84       getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
85
86   for (const char *ArgPtr : Args) {
87     // Ingore nullptrs, they are response file's EOL markers
88     if (ArgPtr == nullptr)
89       continue;
90     const StringRef Arg = ArgPtr;
91     if (!Arg.startswith(OptName))
92       continue;
93
94     const StringRef Value = Arg.drop_front(OptName.size());
95     const unsigned M = llvm::StringSwitch<unsigned>(Value)
96                            .Case("gcc", GCCMode)
97                            .Case("g++", GXXMode)
98                            .Case("cpp", CPPMode)
99                            .Case("cl", CLMode)
100                            .Default(~0U);
101
102     if (M != ~0U)
103       Mode = static_cast<DriverMode>(M);
104     else
105       Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
106   }
107 }
108
109 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
110   llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
111
112   unsigned IncludedFlagsBitmask;
113   unsigned ExcludedFlagsBitmask;
114   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
115       getIncludeExcludeOptionFlagMasks();
116
117   unsigned MissingArgIndex, MissingArgCount;
118   InputArgList Args =
119       getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
120                           IncludedFlagsBitmask, ExcludedFlagsBitmask);
121
122   // Check for missing argument error.
123   if (MissingArgCount)
124     Diag(clang::diag::err_drv_missing_argument)
125         << Args.getArgString(MissingArgIndex) << MissingArgCount;
126
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);
131       continue;
132     }
133
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);
137     }
138   }
139
140   for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
141     Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
142
143   return Args;
144 }
145
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;
153
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;
160
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;
172
173     // -S only runs up to the backend.
174   } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
175     FinalPhase = phases::Backend;
176
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;
182
183     // Otherwise do everything.
184   } else
185     FinalPhase = phases::Link;
186
187   if (FinalPhaseArg)
188     *FinalPhaseArg = PhaseArg;
189
190   return FinalPhase;
191 }
192
193 static Arg *MakeInputArg(DerivedArgList &Args, OptTable *Opts,
194                          StringRef Value) {
195   Arg *A = new Arg(Opts->getOption(options::OPT_INPUT), Value,
196                    Args.getBaseArgs().MakeIndex(Value), Value.data());
197   Args.AddSynthesizedArg(A);
198   A->claim();
199   return A;
200 }
201
202 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
203   DerivedArgList *DAL = new DerivedArgList(Args);
204
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').
210
211     // Rewrite linker options, to replace --no-demangle with a custom internal
212     // option.
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));
218
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);
223
224       continue;
225     }
226
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));
236       else
237         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
238       if (A->getNumValues() == 2)
239         DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
240                             A->getValue(1));
241       continue;
242     }
243
244     // Rewrite reserved library names.
245     if (A->getOption().matches(options::OPT_l)) {
246       StringRef Value = A->getValue();
247
248       // Rewrite unless -nostdlib is present.
249       if (!HasNostdlib && Value == "stdc++") {
250         DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
251         continue;
252       }
253
254       // Rewrite unconditionally.
255       if (Value == "cc_kext") {
256         DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
257         continue;
258       }
259     }
260
261     // Pick up inputs via the -- option.
262     if (A->getOption().matches(options::OPT__DASH_DASH)) {
263       A->claim();
264       for (const StringRef Val : A->getValues())
265         DAL->append(MakeInputArg(*DAL, Opts, Val));
266       continue;
267     }
268
269     DAL->append(A);
270   }
271
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),
278                       HOST_LINK_VERSION);
279     DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
280   }
281 #endif
282
283   return DAL;
284 }
285
286 /// \brief Compute target triple from args.
287 ///
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,
291                                         const ArgList &Args,
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();
296
297   llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
298
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);
304       return Target;
305     }
306
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);
311     }
312   }
313
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);
322     } else {
323       llvm::Triple BE = Target.getBigEndianArchVariant();
324       if (BE.getArch() != llvm::Triple::UnknownArch)
325         Target = std::move(BE);
326     }
327   }
328
329   // Skip further flag support on OSes which don't support '-m32' or '-m64'.
330   if (Target.getArchName() == "tce" || Target.getOS() == llvm::Triple::Minix)
331     return Target;
332
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;
337
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);
354     }
355
356     if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
357       Target.setArch(AT);
358   }
359
360   return Target;
361 }
362
363 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
364   llvm::PrettyStackTraceString CrashInfo("Compilation construction");
365
366   // FIXME: Handle environment options which affect driver behavior, somewhere
367   // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
368
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;
376     }
377   }
378
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));
382
383   // FIXME: What are we going to do with -V and -b?
384
385   // FIXME: This stuff needs to go into the Compilation, not the driver.
386   bool CCCPrintPhases;
387
388   InputArgList Args = ParseArgStrings(ArgList.slice(1));
389
390   // -no-canonical-prefixes is used very early in main.
391   Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
392
393   // Ignore -pipe.
394   Args.ClaimAllArgs(options::OPT_pipe);
395
396   // Extract -ccc args.
397   //
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
401   // or -b.
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();
406   CCCUsePCH =
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.
410   if (IsCLMode()) {
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();
416   }
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)) {
422     A->claim();
423     PrefixDirs.push_back(A->getValue(0));
424   }
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))
430     UseStdLib = false;
431
432   if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
433     ResourceDir = A->getValue();
434
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);
440   }
441
442   std::unique_ptr<llvm::opt::InputArgList> UArgs =
443       llvm::make_unique<InputArgList>(std::move(Args));
444
445   // Perform the default argument translations.
446   DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
447
448   // Owned by the host.
449   const ToolChain &TC =
450       getToolChain(*UArgs, computeTargetTriple(DefaultTargetTriple, *UArgs));
451
452   // The compilation takes ownership of Args.
453   Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
454
455   if (!HandleImmediateArgs(*C))
456     return C;
457
458   // Construct the list of inputs.
459   InputList Inputs;
460   BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
461
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,
466                           C->getActions());
467   else
468     BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs,
469                  C->getActions());
470
471   if (CCCPrintPhases) {
472     PrintActions(*C);
473     return C;
474   }
475
476   BuildJobs(*C);
477
478   return C;
479 }
480
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);
485
486   for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
487     if (I != ASL.begin())
488       OS << ' ';
489     Command::printArg(OS, *I, true);
490   }
491   OS << '\n';
492 }
493
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))
500     return;
501
502   // Don't try to generate diagnostics for link or dsymutil jobs.
503   if (FailingCommand.getCreator().isLinkJob() ||
504       FailingCommand.getCreator().isDsymutilJob())
505     return;
506
507   // Print the version of the compiler.
508   PrintVersion(C, llvm::errs());
509
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.";
513
514   // Suppress driver output and emit preprocessor output to temp file.
515   Mode = CPPMode;
516   CCGenDiagnostics = true;
517
518   // Save the original job command(s).
519   Command Cmd = FailingCommand;
520
521   // Keep track of whether we produce any errors while trying to produce
522   // preprocessed sources.
523   DiagnosticErrorTrap Trap(Diags);
524
525   // Suppress tool output.
526   C.initCompilationForDiagnostics();
527
528   // Construct the list of inputs.
529   InputList Inputs;
530   BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
531
532   for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
533     bool IgnoreInput = false;
534
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) {
538       IgnoreInput = true;
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.";
543       IgnoreInput = true;
544     }
545
546     if (IgnoreInput) {
547       it = Inputs.erase(it);
548       ie = Inputs.end();
549     } else {
550       ++it;
551     }
552   }
553
554   if (Inputs.empty()) {
555     Diag(clang::diag::note_drv_command_failed_diag_msg)
556         << "Error generating preprocessed source(s) - "
557            "no preprocessable inputs.";
558     return;
559   }
560
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);
568     }
569   }
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.";
574     return;
575   }
576
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());
582   else
583     BuildActions(TC, C.getArgs(), Inputs, C.getActions());
584
585   BuildJobs(C);
586
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).";
591     return;
592   }
593
594   // Generate preprocessed output.
595   SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
596   C.ExecuteJobs(C.getJobs(), FailingCommands);
597
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);
602
603     Diag(clang::diag::note_drv_command_failed_diag_msg)
604         << "Error generating preprocessed source(s).";
605     return;
606   }
607
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).";
612     return;
613   }
614
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:";
619
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");
628     }
629   }
630
631   // Assume associated files are based off of the first temporary file.
632   CrashReportInfo CrashInfo(TempFiles[0], VFS);
633
634   std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
635   std::error_code EC;
636   llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
637   if (EC) {
638     Diag(clang::diag::note_drv_command_failed_diag_msg)
639         << "Error generating run script: " + Script + " " + EC.message();
640   } else {
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;
648   }
649
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();
653
654   Diag(clang::diag::note_drv_command_failed_diag_msg)
655       << "\n\n********************";
656 }
657
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()))
664     return;
665
666   std::string TmpName = GetTemporaryPath("response", "txt");
667   Cmd.setResponseFile(
668       C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())));
669 }
670
671 int Driver::ExecuteCompilation(
672     Compilation &C,
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);
677     return 0;
678   }
679
680   // If there were errors building the compilation, quit now.
681   if (Diags.hasErrorOccurred())
682     return 1;
683
684   // Set up response file names for each command, if necessary
685   for (auto &Job : C.getJobs())
686     setUpResponseFiles(C, Job);
687
688   C.ExecuteJobs(C.getJobs(), FailingCommands);
689
690   // Remove temp files.
691   C.CleanupFileList(C.getTempFiles());
692
693   // If the command succeeded, we are done.
694   if (FailingCommands.empty())
695     return 0;
696
697   // Otherwise, remove result files and print extra information about abnormal
698   // failures.
699   for (const auto &CmdPair : FailingCommands) {
700     int Res = CmdPair.first;
701     const Command *FailingCommand = CmdPair.second;
702
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);
707
708       // Failure result files are valid unless we crashed.
709       if (Res < 0)
710         C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
711     }
712
713     // Print extra information about abnormal failures, if possible.
714     //
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();
721
722     if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
723       // FIXME: See FIXME above regarding result code interpretation.
724       if (Res < 0)
725         Diag(clang::diag::err_drv_command_signalled)
726             << FailingTool.getShortName();
727       else
728         Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
729                                                   << Res;
730     }
731   }
732   return 0;
733 }
734
735 void Driver::PrintHelp(bool ShowHidden) const {
736   unsigned IncludedFlagsBitmask;
737   unsigned ExcludedFlagsBitmask;
738   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
739       getIncludeExcludeOptionFlagMasks();
740
741   ExcludedFlagsBitmask |= options::NoDriverOption;
742   if (!ShowHidden)
743     ExcludedFlagsBitmask |= HelpHidden;
744
745   getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
746                       IncludedFlagsBitmask, ExcludedFlagsBitmask);
747 }
748
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';
755
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();
761   } else
762     OS << "Thread model: " << TC.getThreadModel();
763   OS << '\n';
764 }
765
766 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
767 /// option.
768 static void PrintDiagnosticCategories(raw_ostream &OS) {
769   // Skip the empty category.
770   for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
771        ++i)
772     OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
773 }
774
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.
778
779   if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
780     llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
781     return false;
782   }
783
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__.
787     //
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";
792     return false;
793   }
794
795   if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
796     PrintDiagnosticCategories(llvm::outs());
797     return false;
798   }
799
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));
803     return false;
804   }
805
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());
809     return false;
810   }
811
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;
816   }
817
818   const ToolChain &TC = C.getDefaultToolChain();
819
820   if (C.getArgs().hasArg(options::OPT_v))
821     TC.printVerboseInfo(llvm::errs());
822
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()) {
827       if (separator)
828         llvm::outs() << ':';
829       llvm::outs() << Path;
830       separator = true;
831     }
832     llvm::outs() << "\n";
833     llvm::outs() << "libraries: =" << ResourceDir;
834
835     StringRef sysroot = C.getSysRoot();
836
837     for (const std::string &Path : TC.getFilePaths()) {
838       // Always print a separator. ResourceDir was the first item shown.
839       llvm::outs() << ':';
840       // Interpretation of leading '=' is needed only for NetBSD.
841       if (Path[0] == '=')
842         llvm::outs() << sysroot << Path.substr(1);
843       else
844         llvm::outs() << Path;
845     }
846     llvm::outs() << "\n";
847     return false;
848   }
849
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";
854     return false;
855   }
856
857   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
858     llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
859     return false;
860   }
861
862   if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
863     llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
864     return false;
865   }
866
867   if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
868     for (const Multilib &Multilib : TC.getMultilibs())
869       llvm::outs() << Multilib << "\n";
870     return false;
871   }
872
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";
877       else {
878         StringRef Suffix(Multilib.gccSuffix());
879         assert(Suffix.front() == '/');
880         llvm::outs() << Suffix.substr(1) << "\n";
881       }
882     }
883     return false;
884   }
885   return true;
886 }
887
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.
894     return Ids[A];
895
896   std::string str;
897   llvm::raw_string_ostream os(str);
898
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) << "}";
908   } else {
909     ActionList *AL;
910     if (CudaHostAction *CHA = dyn_cast<CudaHostAction>(A)) {
911       os << "{" << PrintActions1(C, *CHA->begin(), Ids) << "}"
912          << ", gpu binaries ";
913       AL = &CHA->getDeviceActions();
914     } else
915       AL = &A->getInputs();
916
917     const char *Prefix = "{";
918     for (Action *PreRequisite : *AL) {
919       os << Prefix << PrintActions1(C, PreRequisite, Ids);
920       Prefix = ", ";
921     }
922     os << "}";
923   }
924
925   unsigned Id = Ids.size();
926   Ids[A] = Id;
927   llvm::errs() << Id << ": " << os.str() << ", "
928                << types::getTypeName(A->getType()) << "\n";
929
930   return Id;
931 }
932
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);
939 }
940
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))
946     return true;
947
948   for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
949     if (ContainsCompileOrAssembleAction(*it))
950       return true;
951
952   return false;
953 }
954
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);
971         continue;
972       }
973
974       A->claim();
975       if (ArchNames.insert(A->getValue()).second)
976         Archs.push_back(A->getValue());
977     }
978   }
979
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.
982   if (!Archs.size())
983     Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
984
985   ActionList SingleActions;
986   BuildActions(TC, Args, BAInputs, SingleActions);
987
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];
992
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.
998
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());
1002
1003     ActionList Inputs;
1004     for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
1005       Inputs.push_back(
1006           new BindArchAction(std::unique_ptr<Action>(Act), Archs[i]));
1007       if (i != 0)
1008         Inputs.back()->setOwnsInputs(false);
1009     }
1010
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());
1015     else
1016       Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
1017
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())) {
1023
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) {
1029         ActionList Inputs;
1030         Inputs.push_back(Actions.back());
1031         Actions.pop_back();
1032         Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
1033       }
1034
1035       // Verify the debug info output.
1036       if (Args.hasArg(options::OPT_verify_debug_info)) {
1037         std::unique_ptr<Action> VerifyInput(Actions.back());
1038         Actions.pop_back();
1039         Actions.push_back(new VerifyDebugInfoJobAction(std::move(VerifyInput),
1040                                                        types::TY_Nothing));
1041       }
1042     }
1043   }
1044 }
1045
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,
1049                                    StringRef Value) {
1050   if (!D.getCheckInputsExist())
1051     return true;
1052
1053   // stdin always exists.
1054   if (Value == "-")
1055     return true;
1056
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);
1063     }
1064   }
1065
1066   if (llvm::sys::fs::exists(Twine(Path)))
1067     return true;
1068
1069   if (D.IsCLMode() && !llvm::sys::path::is_absolute(Twine(Path)) &&
1070       llvm::sys::Process::FindInEnvPath("LIB", Value))
1071     return true;
1072
1073   D.Diag(clang::diag::err_drv_no_such_file) << Path;
1074   return false;
1075 }
1076
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;
1085
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)
1091                     ? types::TY_C
1092                     : types::TY_CXX;
1093
1094     arg_iterator it =
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;
1099     while (it != ie) {
1100       Diag(clang::diag::warn_drv_overriding_flag_option)
1101           << Previous->getSpelling() << (*it)->getSpelling();
1102       Previous = *it++;
1103       ShowNote = true;
1104     }
1105     if (ShowNote)
1106       Diag(clang::diag::note_drv_t_option_is_global);
1107
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");
1110   }
1111
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;
1116
1117       // Infer the input type if necessary.
1118       if (InputType == types::TY_Nothing) {
1119         // If there was an explicit arg for this, claim it.
1120         if (InputTypeArg)
1121           InputTypeArg->claim();
1122
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.
1127           //
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);
1133           Ty = types::TY_C;
1134         } else {
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);
1141
1142           if (Ty == types::TY_INVALID) {
1143             if (CCCIsCPP())
1144               Ty = types::TY_C;
1145             else
1146               Ty = types::TY_Object;
1147           }
1148
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.
1151           if (CCCIsCXX()) {
1152             types::ID OldTy = Ty;
1153             Ty = types::lookupCXXTypeForCType(Ty);
1154
1155             if (Ty != OldTy)
1156               Diag(clang::diag::warn_drv_treating_input_as_cxx)
1157                   << getTypeName(OldTy) << getTypeName(Ty);
1158           }
1159         }
1160
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
1163         // source file.
1164         //
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;
1171         }
1172       } else {
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
1176           // object files.
1177           const char *Ext = strrchr(Value, '.');
1178           if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1179             Ty = types::TY_Object;
1180         }
1181         if (Ty == types::TY_INVALID) {
1182           Ty = InputType;
1183           InputTypeArg->claim();
1184         }
1185       }
1186
1187       if (DiagnoseInputExistence(*this, Args, Value))
1188         Inputs.push_back(std::make_pair(Ty, A));
1189
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));
1195       }
1196       A->claim();
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));
1202       }
1203       A->claim();
1204     } else if (A->getOption().hasFlag(options::LinkerInput)) {
1205       // Just treat as object type, we could make a special type for this if
1206       // necessary.
1207       Inputs.push_back(std::make_pair(types::TY_Object, A));
1208
1209     } else if (A->getOption().matches(options::OPT_x)) {
1210       InputTypeArg = A;
1211       InputType = types::lookupTypeForTypeSpecifier(A->getValue());
1212       A->claim();
1213
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.
1217       if (!InputType) {
1218         Diag(clang::diag::err_drv_unknown_language) << A->getValue();
1219         InputType = types::TY_Object;
1220       }
1221     }
1222   }
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));
1228   }
1229 }
1230
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) {
1240
1241   assert(InputType == types::TY_CUDA &&
1242          "CUDA Actions only apply to CUDA inputs.");
1243
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)) {
1249       A->claim();
1250       if (GpuArchNames.insert(A->getValue()).second)
1251         GpuArchList.push_back(A->getValue());
1252     }
1253   }
1254
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");
1259
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));
1264
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");
1270
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;
1277       break;
1278     }
1279   }
1280
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.
1287
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);
1292       return nullptr;
1293     }
1294
1295     for (unsigned i = 0, e = GpuArchList.size(); i != e; ++i)
1296       Actions.push_back(
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);
1302     return Current;
1303   } else {
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
1312     // device actions.
1313     return std::unique_ptr<Action>(
1314         new CudaHostAction(std::move(Current), DeviceActions));
1315   }
1316 }
1317
1318 void Driver::BuildActions(const ToolChain &TC, DerivedArgList &Args,
1319                           const InputList &Inputs, ActionList &Actions) const {
1320   llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
1321
1322   if (!SuppressMissingInputWarning && Inputs.empty()) {
1323     Diag(clang::diag::err_drv_no_input_files);
1324     return;
1325   }
1326
1327   Arg *FinalPhaseArg;
1328   phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
1329
1330   if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) {
1331     Diag(clang::diag::err_drv_emit_llvm_link);
1332   }
1333
1334   // Reject -Z* at the top level, these options should never have been exposed
1335   // by gcc.
1336   if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
1337     Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
1338
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);
1348     }
1349   }
1350
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);
1360     }
1361   }
1362
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);
1369     }
1370   }
1371
1372   // Construct the actions to perform.
1373   ActionList LinkerInputs;
1374
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;
1379
1380     PL.clear();
1381     types::getCompilationPhases(InputType, PL);
1382
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.
1388       InputArg->claim();
1389
1390       // Suppress all unused style warnings with -Qunused-arguments
1391       if (Args.hasArg(options::OPT_Qunused_arguments))
1392         continue;
1393
1394       // Special case when final phase determined by binary name, rather than
1395       // by a command-line argument with a corresponding Arg.
1396       if (CCCIsCPP())
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
1400       // more sense.
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() : "");
1407       else
1408         Diag(clang::diag::warn_drv_input_file_unused)
1409             << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
1410             << !!FinalPhaseArg
1411             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
1412       continue;
1413     }
1414
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;
1420     } else {
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) {
1426           auto next = i + 1;
1427           if (next != e && *next == phases::Link)
1428             CudaInjectionPhase = *i;
1429         }
1430       } else
1431         CudaInjectionPhase = FinalPhase;
1432     }
1433
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();
1437          i != e; ++i) {
1438       phases::ID Phase = *i;
1439
1440       // We are done if this step is past what the user requested.
1441       if (Phase > FinalPhase)
1442         break;
1443
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());
1448         break;
1449       }
1450
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)
1455         continue;
1456
1457       // Otherwise construct the appropriate action.
1458       Current = ConstructPhaseAction(TC, Args, Phase, std::move(Current));
1459
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);
1464         if (!Current)
1465           break;
1466       }
1467
1468       if (Current->getType() == types::TY_Nothing)
1469         break;
1470     }
1471
1472     // If we ended with something, add to the output list.
1473     if (Current)
1474       Actions.push_back(Current.release());
1475   }
1476
1477   // Add a link action if necessary.
1478   if (!LinkerInputs.empty())
1479     Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
1480
1481   // If we are linking, claim any options which are obviously only used for
1482   // compilation.
1483   if (FinalPhase == phases::Link && PL.size() == 1) {
1484     Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
1485     Args.ClaimAllArgs(options::OPT_cl_compile_Group);
1486   }
1487
1488   // Claim ignored clang-cl options.
1489   Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
1490 }
1491
1492 std::unique_ptr<Action>
1493 Driver::ConstructPhaseAction(const ToolChain &TC, const ArgList &Args,
1494                              phases::ID Phase,
1495                              std::unique_ptr<Action> Input) const {
1496   llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
1497   // Build the appropriate action.
1498   switch (Phase) {
1499   case phases::Link:
1500     llvm_unreachable("link action invalid here.");
1501   case phases::Preprocess: {
1502     types::ID OutputTy;
1503     // -{M, MM} alter the output type.
1504     if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
1505       OutputTy = types::TY_Dependencies;
1506     } else {
1507       OutputTy = Input->getType();
1508       if (!Args.hasFlag(options::OPT_frewrite_includes,
1509                         options::OPT_fno_rewrite_includes, false) &&
1510           !CCGenDiagnostics)
1511         OutputTy = types::getPreprocessedType(OutputTy);
1512       assert(OutputTy != types::TY_INVALID &&
1513              "Cannot preprocess this input type!");
1514     }
1515     return llvm::make_unique<PreprocessJobAction>(std::move(Input), OutputTy);
1516   }
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;
1522     }
1523     return llvm::make_unique<PrecompileJobAction>(std::move(Input), OutputTy);
1524   }
1525   case phases::Compile: {
1526     if (Args.hasArg(options::OPT_fsyntax_only))
1527       return llvm::make_unique<CompileJobAction>(std::move(Input),
1528                                                  types::TY_Nothing);
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),
1537                                                  types::TY_Plist);
1538     if (Args.hasArg(options::OPT__migrate))
1539       return llvm::make_unique<MigrateJobAction>(std::move(Input),
1540                                                  types::TY_Remap);
1541     if (Args.hasArg(options::OPT_emit_ast))
1542       return llvm::make_unique<CompileJobAction>(std::move(Input),
1543                                                  types::TY_AST);
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),
1549                                                    types::TY_Nothing);
1550     return llvm::make_unique<CompileJobAction>(std::move(Input),
1551                                                types::TY_LLVM_BC);
1552   }
1553   case phases::Backend: {
1554     if (IsUsingLTO(Args)) {
1555       types::ID Output =
1556           Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
1557       return llvm::make_unique<BackendJobAction>(std::move(Input), Output);
1558     }
1559     if (Args.hasArg(options::OPT_emit_llvm)) {
1560       types::ID Output =
1561           Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
1562       return llvm::make_unique<BackendJobAction>(std::move(Input), Output);
1563     }
1564     return llvm::make_unique<BackendJobAction>(std::move(Input),
1565                                                types::TY_PP_Asm);
1566   }
1567   case phases::Assemble:
1568     return llvm::make_unique<AssembleJobAction>(std::move(Input),
1569                                                 types::TY_Object);
1570   }
1571
1572   llvm_unreachable("invalid phase in ConstructPhaseAction");
1573 }
1574
1575 bool Driver::IsUsingLTO(const ArgList &Args) const {
1576   return Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false);
1577 }
1578
1579 void Driver::BuildJobs(Compilation &C) const {
1580   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1581
1582   Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
1583
1584   // It is an error to provide a -o option if we are making multiple output
1585   // files.
1586   if (FinalOutput) {
1587     unsigned NumOutputs = 0;
1588     for (const Action *A : C.getActions())
1589       if (A->getType() != types::TY_Nothing)
1590         ++NumOutputs;
1591
1592     if (NumOutputs > 1) {
1593       Diag(clang::diag::err_drv_output_argument_with_multiple_files);
1594       FinalOutput = nullptr;
1595     }
1596   }
1597
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());
1604
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.
1609     //
1610     // FIXME: This is a hack; find a cleaner way to integrate this into the
1611     // process.
1612     const char *LinkingOutput = nullptr;
1613     if (isa<LipoJobAction>(A)) {
1614       if (FinalOutput)
1615         LinkingOutput = FinalOutput->getValue();
1616       else
1617         LinkingOutput = getDefaultImageName();
1618     }
1619
1620     InputInfo II;
1621     BuildJobsForAction(C, A, &C.getDefaultToolChain(),
1622                        /*BoundArch*/ nullptr,
1623                        /*AtTopLevel*/ true,
1624                        /*MultipleArchs*/ ArchNames.size() > 1,
1625                        /*LinkingOutput*/ LinkingOutput, II);
1626   }
1627
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))
1632     return;
1633
1634   // Claim -### here.
1635   (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1636
1637   // Claim --driver-mode, it was handled earlier.
1638   (void)C.getArgs().hasArg(options::OPT_driver_mode);
1639
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
1643     // printed.
1644     if (!A->isClaimed()) {
1645       if (A->getOption().hasFlag(options::NoArgumentUnused))
1646         continue;
1647
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;
1653
1654         for (const Arg *AA : C.getArgs().filtered(&Opt)) {
1655           if (AA->isClaimed()) {
1656             DuplicateClaimed = true;
1657             break;
1658           }
1659         }
1660
1661         if (DuplicateClaimed)
1662           continue;
1663       }
1664
1665       Diag(clang::diag::warn_drv_unused_argument)
1666           << A->getAsString(C.getArgs());
1667     }
1668   }
1669 }
1670
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;
1675
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
1678   // compiler input.
1679
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);
1693     if (!Compiler)
1694       return nullptr;
1695     if (Compiler->hasIntegratedAssembler()) {
1696       Inputs = &(*BackendInputs)[0]->getInputs();
1697       ToolForJob = Compiler;
1698     }
1699   }
1700
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());
1711     else
1712       CompileJA = cast<CompileJobAction>(*Inputs->begin());
1713
1714     const Tool *Compiler = TC->SelectTool(*CompileJA);
1715     if (!Compiler)
1716       return nullptr;
1717     if (!Compiler->canEmitIR() || !SaveTemps) {
1718       Inputs = &(*Inputs)[0]->getInputs();
1719       ToolForJob = Compiler;
1720     }
1721   }
1722
1723   // Otherwise use the tool for the current job.
1724   if (!ToolForJob)
1725     ToolForJob = TC->SelectTool(*JA);
1726
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();
1736
1737   return ToolForJob;
1738 }
1739
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");
1746
1747   InputInfoList CudaDeviceInputInfos;
1748   if (const CudaHostAction *CHA = dyn_cast<CudaHostAction>(A)) {
1749     InputInfo II;
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);
1755     }
1756     // Override current action with a real host compile action and continue
1757     // processing it.
1758     A = *CHA->begin();
1759   }
1760
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();
1765     Input.claim();
1766     if (Input.getOption().matches(options::OPT_INPUT)) {
1767       const char *Name = Input.getValue();
1768       Result = InputInfo(Name, A->getType(), Name);
1769     } else {
1770       Result = InputInfo(&Input, A->getType(), "");
1771     }
1772     return;
1773   }
1774
1775   if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1776     const ToolChain *TC;
1777     const char *ArchName = BAA->getArchName();
1778
1779     if (ArchName)
1780       TC = &getToolChain(
1781           C.getArgs(),
1782           computeTargetTriple(DefaultTargetTriple, C.getArgs(), ArchName));
1783     else
1784       TC = &C.getDefaultToolChain();
1785
1786     BuildJobsForAction(C, *BAA->begin(), TC, ArchName, AtTopLevel,
1787                        MultipleArchs, LinkingOutput, Result);
1788     return;
1789   }
1790
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);
1801     return;
1802   }
1803
1804   const ActionList *Inputs = &A->getInputs();
1805
1806   const JobAction *JA = cast<JobAction>(A);
1807   const Tool *T = SelectToolForJob(C, isSaveTempsEnabled(), TC, JA, Inputs);
1808   if (!T)
1809     return;
1810
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;
1820
1821     InputInfo II;
1822     BuildJobsForAction(C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs,
1823                        LinkingOutput, II);
1824     InputInfos.push_back(II);
1825   }
1826
1827   // Always use the first input as the base input.
1828   const char *BaseInput = InputInfos[0].getBaseInput();
1829
1830   // ... except dsymutil actions, which use their actual input as the base
1831   // input.
1832   if (JA->getType() == types::TY_dSYM)
1833     BaseInput = InputInfos[0].getFilename();
1834
1835   // Append outputs of cuda device jobs to the input list
1836   if (CudaDeviceInputInfos.size())
1837     InputInfos.append(CudaDeviceInputInfos.begin(), CudaDeviceInputInfos.end());
1838
1839   // Determine the place to write output to, if any.
1840   if (JA->getType() == types::TY_Nothing)
1841     Result = InputInfo(A->getType(), BaseInput);
1842   else
1843     Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
1844                                           AtTopLevel, MultipleArchs),
1845                        A->getType(), BaseInput);
1846
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();
1852       if (i + 1 != e)
1853         llvm::errs() << ", ";
1854     }
1855     llvm::errs() << "], output: " << Result.getAsString() << "\n";
1856   } else {
1857     T->ConstructJob(C, *JA, Result, InputInfos,
1858                     C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
1859   }
1860 }
1861
1862 const char *Driver::getDefaultImageName() const {
1863   llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
1864   return Target.isOSWindows() ? "a.exe" : "a.out";
1865 }
1866
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,
1872                                         StringRef BaseName,
1873                                         types::ID FileType) {
1874   SmallString<128> Filename = ArgValue;
1875
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);
1882   }
1883
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);
1887
1888     if (FileType == types::TY_Image &&
1889         Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
1890       // The output file is a dll.
1891       Extension = "dll";
1892     }
1893
1894     llvm::sys::path::replace_extension(Filename, Extension);
1895   }
1896
1897   return Args.MakeArgString(Filename.c_str());
1898 }
1899
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);
1909   }
1910
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);
1915     StringRef NameArg;
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),
1920         &JA);
1921   }
1922
1923   // Default to writing to stdout?
1924   if (AtTopLevel && !CCGenDiagnostics &&
1925       (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
1926     return "-";
1927
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()),
1937         &JA);
1938   }
1939
1940   // Output to a temporary file?
1941   if ((!AtTopLevel && !isSaveTempsEnabled() &&
1942        !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
1943       CCGenDiagnostics) {
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()));
1949   }
1950
1951   SmallString<128> BasePath(BaseInput);
1952   StringRef BaseName;
1953
1954   // Dsymutil actions should use the full path.
1955   if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
1956     BaseName = BasePath;
1957   else
1958     BaseName = llvm::sys::path::filename(BasePath);
1959
1960   // Determine what the derived output name should be.
1961   const char *NamedOutput;
1962
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.
1966     StringRef Val =
1967         C.getArgs()
1968             .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
1969             ->getValue();
1970     NamedOutput =
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.
1976     StringRef Val =
1977         C.getArgs()
1978             .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
1979             ->getValue();
1980     NamedOutput =
1981         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
1982   } else if (JA.getType() == types::TY_Image) {
1983     if (IsCLMode()) {
1984       // clang-cl uses BaseName for the executable name.
1985       NamedOutput =
1986           MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
1987     } else if (MultipleArchs && BoundArch) {
1988       SmallString<128> Output(getDefaultImageName());
1989       Output += "-";
1990       Output.append(BoundArch);
1991       NamedOutput = C.getArgs().MakeArgString(Output.c_str());
1992     } else
1993       NamedOutput = getDefaultImageName();
1994   } else {
1995     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
1996     assert(Suffix && "All types used for output should have a suffix.");
1997
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) {
2003       Suffixed += "-";
2004       Suffixed.append(BoundArch);
2005     }
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)
2011       Suffixed += ".tmp";
2012     Suffixed += '.';
2013     Suffixed += Suffix;
2014     NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
2015   }
2016
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());
2026   }
2027
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.
2037     if (SameFile) {
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()));
2043     }
2044   }
2045
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;
2051     else
2052       llvm::sys::path::append(BasePath, NamedOutput);
2053     return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
2054   } else {
2055     return C.addResultFile(NamedOutput, &JA);
2056   }
2057 }
2058
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) {
2063     if (Dir.empty())
2064       continue;
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)))
2068       return P.str();
2069   }
2070
2071   SmallString<128> P(ResourceDir);
2072   llvm::sys::path::append(P, Name);
2073   if (llvm::sys::fs::exists(Twine(P)))
2074     return P.str();
2075
2076   for (const std::string &Dir : TC.getFilePaths()) {
2077     if (Dir.empty())
2078       continue;
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)))
2082       return P.str();
2083   }
2084
2085   return Name;
2086 }
2087
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);
2094 }
2095
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)))
2101       return true;
2102     llvm::sys::path::remove_filename(Dir);
2103   }
2104   return false;
2105 }
2106
2107 std::string Driver::GetProgramPath(const char *Name,
2108                                    const ToolChain &TC) const {
2109   SmallVector<std::string, 2> TargetSpecificExecutables;
2110   generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
2111
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))
2118         return P.str();
2119     } else {
2120       SmallString<128> P(PrefixDir + Name);
2121       if (llvm::sys::fs::can_execute(Twine(P)))
2122         return P.str();
2123     }
2124   }
2125
2126   const ToolChain::path_list &List = TC.getProgramPaths();
2127   for (const auto &Path : List) {
2128     SmallString<128> P(Path);
2129     if (ScanDirForExecutable(P, TargetSpecificExecutables))
2130       return P.str();
2131   }
2132
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))
2137       return *P;
2138
2139   return Name;
2140 }
2141
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);
2146   if (EC) {
2147     Diag(clang::diag::err_unable_to_make_temp) << EC.message();
2148     return "";
2149   }
2150
2151   return Path.str();
2152 }
2153
2154 const ToolChain &Driver::getToolChain(const ArgList &Args,
2155                                       const llvm::Triple &Target) const {
2156
2157   ToolChain *&TC = ToolChains[Target.str()];
2158   if (!TC) {
2159     switch (Target.getOS()) {
2160     case llvm::Triple::CloudABI:
2161       TC = new toolchains::CloudABI(*this, Target, Args);
2162       break;
2163     case llvm::Triple::Darwin:
2164     case llvm::Triple::MacOSX:
2165     case llvm::Triple::IOS:
2166       TC = new toolchains::DarwinClang(*this, Target, Args);
2167       break;
2168     case llvm::Triple::DragonFly:
2169       TC = new toolchains::DragonFly(*this, Target, Args);
2170       break;
2171     case llvm::Triple::OpenBSD:
2172       TC = new toolchains::OpenBSD(*this, Target, Args);
2173       break;
2174     case llvm::Triple::Bitrig:
2175       TC = new toolchains::Bitrig(*this, Target, Args);
2176       break;
2177     case llvm::Triple::NetBSD:
2178       TC = new toolchains::NetBSD(*this, Target, Args);
2179       break;
2180     case llvm::Triple::FreeBSD:
2181       TC = new toolchains::FreeBSD(*this, Target, Args);
2182       break;
2183     case llvm::Triple::Minix:
2184       TC = new toolchains::Minix(*this, Target, Args);
2185       break;
2186     case llvm::Triple::Linux:
2187       if (Target.getArch() == llvm::Triple::hexagon)
2188         TC = new toolchains::Hexagon_TC(*this, Target, Args);
2189       else
2190         TC = new toolchains::Linux(*this, Target, Args);
2191       break;
2192     case llvm::Triple::NaCl:
2193       TC = new toolchains::NaCl_TC(*this, Target, Args);
2194       break;
2195     case llvm::Triple::Solaris:
2196       TC = new toolchains::Solaris(*this, Target, Args);
2197       break;
2198     case llvm::Triple::Win32:
2199       switch (Target.getEnvironment()) {
2200       default:
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);
2205         else
2206           TC = new toolchains::Generic_GCC(*this, Target, Args);
2207         break;
2208       case llvm::Triple::GNU:
2209         TC = new toolchains::MinGW(*this, Target, Args);
2210         break;
2211       case llvm::Triple::Itanium:
2212         TC = new toolchains::CrossWindowsToolChain(*this, Target, Args);
2213         break;
2214       case llvm::Triple::MSVC:
2215       case llvm::Triple::UnknownEnvironment:
2216         TC = new toolchains::MSVCToolChain(*this, Target, Args);
2217         break;
2218       }
2219       break;
2220     case llvm::Triple::CUDA:
2221       TC = new toolchains::CudaToolChain(*this, Target, Args);
2222       break;
2223     default:
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);
2238       else
2239         TC = new toolchains::Generic_GCC(*this, Target, Args);
2240       break;
2241     }
2242   }
2243   return *TC;
2244 }
2245
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()))
2249     return false;
2250
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))
2254     return false;
2255
2256   return true;
2257 }
2258
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.
2261 ///
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,
2266                                bool &HadExtra) {
2267   HadExtra = false;
2268
2269   Major = Minor = Micro = 0;
2270   if (*Str == '\0')
2271     return false;
2272
2273   char *End;
2274   Major = (unsigned)strtol(Str, &End, 10);
2275   if (*Str != '\0' && *End == '\0')
2276     return true;
2277   if (*End != '.')
2278     return false;
2279
2280   Str = End + 1;
2281   Minor = (unsigned)strtol(Str, &End, 10);
2282   if (*Str != '\0' && *End == '\0')
2283     return true;
2284   if (*End != '.')
2285     return false;
2286
2287   Str = End + 1;
2288   Micro = (unsigned)strtol(Str, &End, 10);
2289   if (*Str != '\0' && *End == '\0')
2290     return true;
2291   if (Str == End)
2292     return false;
2293   HadExtra = true;
2294   return true;
2295 }
2296
2297 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
2298   unsigned IncludedFlagsBitmask = 0;
2299   unsigned ExcludedFlagsBitmask = options::NoDriverOption;
2300
2301   if (Mode == CLMode) {
2302     // Include CL and Core options.
2303     IncludedFlagsBitmask |= options::CLOption;
2304     IncludedFlagsBitmask |= options::CoreOption;
2305   } else {
2306     ExcludedFlagsBitmask |= options::CLOption;
2307   }
2308
2309   return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
2310 }
2311
2312 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
2313   return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
2314 }