]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/Driver.cpp
Update clang to trunk r256633.
[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/Basic/VirtualFileSystem.h"
15 #include "clang/Config/config.h"
16 #include "clang/Driver/Action.h"
17 #include "clang/Driver/Compilation.h"
18 #include "clang/Driver/DriverDiagnostic.h"
19 #include "clang/Driver/Job.h"
20 #include "clang/Driver/Options.h"
21 #include "clang/Driver/SanitizerArgs.h"
22 #include "clang/Driver/Tool.h"
23 #include "clang/Driver/ToolChain.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSet.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/Option/Arg.h"
30 #include "llvm/Option/ArgList.h"
31 #include "llvm/Option/OptSpecifier.h"
32 #include "llvm/Option/OptTable.h"
33 #include "llvm/Option/Option.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/PrettyStackTrace.h"
39 #include "llvm/Support/Process.h"
40 #include "llvm/Support/Program.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include <map>
43 #include <memory>
44
45 using namespace clang::driver;
46 using namespace clang;
47 using namespace llvm::opt;
48
49 Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
50                DiagnosticsEngine &Diags,
51                IntrusiveRefCntPtr<vfs::FileSystem> VFS)
52     : Opts(createDriverOptTable()), Diags(Diags), VFS(VFS), Mode(GCCMode),
53       SaveTemps(SaveTempsNone), LTOMode(LTOK_None),
54       ClangExecutable(ClangExecutable),
55       SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
56       DefaultTargetTriple(DefaultTargetTriple),
57       DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
58       CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
59       CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
60       CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
61       CCCUsePCH(true), SuppressMissingInputWarning(false) {
62
63   // Provide a sane fallback if no VFS is specified.
64   if (!this->VFS)
65     this->VFS = vfs::getRealFileSystem();
66
67   Name = llvm::sys::path::filename(ClangExecutable);
68   Dir = llvm::sys::path::parent_path(ClangExecutable);
69   InstalledDir = Dir; // Provide a sensible default installed dir.
70
71   // Compute the path to the resource directory.
72   StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
73   SmallString<128> P(Dir);
74   if (ClangResourceDir != "") {
75     llvm::sys::path::append(P, ClangResourceDir);
76   } else {
77     StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
78     llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang",
79                             CLANG_VERSION_STRING);
80   }
81   ResourceDir = P.str();
82 }
83
84 Driver::~Driver() {
85   delete Opts;
86
87   llvm::DeleteContainerSeconds(ToolChains);
88 }
89
90 void Driver::ParseDriverMode(ArrayRef<const char *> Args) {
91   const std::string OptName =
92       getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
93
94   for (const char *ArgPtr : Args) {
95     // Ingore nullptrs, they are response file's EOL markers
96     if (ArgPtr == nullptr)
97       continue;
98     const StringRef Arg = ArgPtr;
99     if (!Arg.startswith(OptName))
100       continue;
101
102     const StringRef Value = Arg.drop_front(OptName.size());
103     const unsigned M = llvm::StringSwitch<unsigned>(Value)
104                            .Case("gcc", GCCMode)
105                            .Case("g++", GXXMode)
106                            .Case("cpp", CPPMode)
107                            .Case("cl", CLMode)
108                            .Default(~0U);
109
110     if (M != ~0U)
111       Mode = static_cast<DriverMode>(M);
112     else
113       Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
114   }
115 }
116
117 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
118   llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
119
120   unsigned IncludedFlagsBitmask;
121   unsigned ExcludedFlagsBitmask;
122   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
123       getIncludeExcludeOptionFlagMasks();
124
125   unsigned MissingArgIndex, MissingArgCount;
126   InputArgList Args =
127       getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
128                           IncludedFlagsBitmask, ExcludedFlagsBitmask);
129
130   // Check for missing argument error.
131   if (MissingArgCount)
132     Diag(clang::diag::err_drv_missing_argument)
133         << Args.getArgString(MissingArgIndex) << MissingArgCount;
134
135   // Check for unsupported options.
136   for (const Arg *A : Args) {
137     if (A->getOption().hasFlag(options::Unsupported)) {
138       Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
139       continue;
140     }
141
142     // Warn about -mcpu= without an argument.
143     if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
144       Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
145     }
146   }
147
148   for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
149     Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
150
151   return Args;
152 }
153
154 // Determine which compilation mode we are in. We look for options which
155 // affect the phase, starting with the earliest phases, and record which
156 // option we used to determine the final phase.
157 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
158                                  Arg **FinalPhaseArg) const {
159   Arg *PhaseArg = nullptr;
160   phases::ID FinalPhase;
161
162   // -{E,EP,P,M,MM} only run the preprocessor.
163   if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
164       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
165       (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
166       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
167     FinalPhase = phases::Preprocess;
168
169     // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
170   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
171              (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
172              (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
173              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
174              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
175              (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
176              (PhaseArg = DAL.getLastArg(options::OPT__analyze,
177                                         options::OPT__analyze_auto)) ||
178              (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
179     FinalPhase = phases::Compile;
180
181     // -S only runs up to the backend.
182   } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
183     FinalPhase = phases::Backend;
184
185     // -c compilation only runs up to the assembler.
186   } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
187     FinalPhase = phases::Assemble;
188
189     // Otherwise do everything.
190   } else
191     FinalPhase = phases::Link;
192
193   if (FinalPhaseArg)
194     *FinalPhaseArg = PhaseArg;
195
196   return FinalPhase;
197 }
198
199 static Arg *MakeInputArg(DerivedArgList &Args, OptTable *Opts,
200                          StringRef Value) {
201   Arg *A = new Arg(Opts->getOption(options::OPT_INPUT), Value,
202                    Args.getBaseArgs().MakeIndex(Value), Value.data());
203   Args.AddSynthesizedArg(A);
204   A->claim();
205   return A;
206 }
207
208 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
209   DerivedArgList *DAL = new DerivedArgList(Args);
210
211   bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
212   bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
213   for (Arg *A : Args) {
214     // Unfortunately, we have to parse some forwarding options (-Xassembler,
215     // -Xlinker, -Xpreprocessor) because we either integrate their functionality
216     // (assembler and preprocessor), or bypass a previous driver ('collect2').
217
218     // Rewrite linker options, to replace --no-demangle with a custom internal
219     // option.
220     if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
221          A->getOption().matches(options::OPT_Xlinker)) &&
222         A->containsValue("--no-demangle")) {
223       // Add the rewritten no-demangle argument.
224       DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
225
226       // Add the remaining values as Xlinker arguments.
227       for (StringRef Val : A->getValues())
228         if (Val != "--no-demangle")
229           DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
230
231       continue;
232     }
233
234     // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
235     // some build systems. We don't try to be complete here because we don't
236     // care to encourage this usage model.
237     if (A->getOption().matches(options::OPT_Wp_COMMA) &&
238         (A->getValue(0) == StringRef("-MD") ||
239          A->getValue(0) == StringRef("-MMD"))) {
240       // Rewrite to -MD/-MMD along with -MF.
241       if (A->getValue(0) == StringRef("-MD"))
242         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
243       else
244         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
245       if (A->getNumValues() == 2)
246         DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
247                             A->getValue(1));
248       continue;
249     }
250
251     // Rewrite reserved library names.
252     if (A->getOption().matches(options::OPT_l)) {
253       StringRef Value = A->getValue();
254
255       // Rewrite unless -nostdlib is present.
256       if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
257         DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
258         continue;
259       }
260
261       // Rewrite unconditionally.
262       if (Value == "cc_kext") {
263         DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
264         continue;
265       }
266     }
267
268     // Pick up inputs via the -- option.
269     if (A->getOption().matches(options::OPT__DASH_DASH)) {
270       A->claim();
271       for (StringRef Val : A->getValues())
272         DAL->append(MakeInputArg(*DAL, Opts, Val));
273       continue;
274     }
275
276     DAL->append(A);
277   }
278
279 // Add a default value of -mlinker-version=, if one was given and the user
280 // didn't specify one.
281 #if defined(HOST_LINK_VERSION)
282   if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
283       strlen(HOST_LINK_VERSION) > 0) {
284     DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
285                       HOST_LINK_VERSION);
286     DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
287   }
288 #endif
289
290   return DAL;
291 }
292
293 /// \brief Compute target triple from args.
294 ///
295 /// This routine provides the logic to compute a target triple from various
296 /// args passed to the driver and the default triple string.
297 static llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple,
298                                         const ArgList &Args,
299                                         StringRef DarwinArchName = "") {
300   // FIXME: Already done in Compilation *Driver::BuildCompilation
301   if (const Arg *A = Args.getLastArg(options::OPT_target))
302     DefaultTargetTriple = A->getValue();
303
304   llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
305
306   // Handle Apple-specific options available here.
307   if (Target.isOSBinFormatMachO()) {
308     // If an explict Darwin arch name is given, that trumps all.
309     if (!DarwinArchName.empty()) {
310       tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
311       return Target;
312     }
313
314     // Handle the Darwin '-arch' flag.
315     if (Arg *A = Args.getLastArg(options::OPT_arch)) {
316       StringRef ArchName = A->getValue();
317       tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
318     }
319   }
320
321   // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
322   // '-mbig-endian'/'-EB'.
323   if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
324                                options::OPT_mbig_endian)) {
325     if (A->getOption().matches(options::OPT_mlittle_endian)) {
326       llvm::Triple LE = Target.getLittleEndianArchVariant();
327       if (LE.getArch() != llvm::Triple::UnknownArch)
328         Target = std::move(LE);
329     } else {
330       llvm::Triple BE = Target.getBigEndianArchVariant();
331       if (BE.getArch() != llvm::Triple::UnknownArch)
332         Target = std::move(BE);
333     }
334   }
335
336   // Skip further flag support on OSes which don't support '-m32' or '-m64'.
337   if (Target.getArch() == llvm::Triple::tce ||
338       Target.getOS() == llvm::Triple::Minix)
339     return Target;
340
341   // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
342   if (Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
343                                options::OPT_m32, options::OPT_m16)) {
344     llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
345
346     if (A->getOption().matches(options::OPT_m64)) {
347       AT = Target.get64BitArchVariant().getArch();
348       if (Target.getEnvironment() == llvm::Triple::GNUX32)
349         Target.setEnvironment(llvm::Triple::GNU);
350     } else if (A->getOption().matches(options::OPT_mx32) &&
351                Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
352       AT = llvm::Triple::x86_64;
353       Target.setEnvironment(llvm::Triple::GNUX32);
354     } else if (A->getOption().matches(options::OPT_m32)) {
355       AT = Target.get32BitArchVariant().getArch();
356       if (Target.getEnvironment() == llvm::Triple::GNUX32)
357         Target.setEnvironment(llvm::Triple::GNU);
358     } else if (A->getOption().matches(options::OPT_m16) &&
359                Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
360       AT = llvm::Triple::x86;
361       Target.setEnvironment(llvm::Triple::CODE16);
362     }
363
364     if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
365       Target.setArch(AT);
366   }
367
368   return Target;
369 }
370
371 // \brief Parse the LTO options and record the type of LTO compilation
372 // based on which -f(no-)?lto(=.*)? option occurs last.
373 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
374   LTOMode = LTOK_None;
375   if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
376                     options::OPT_fno_lto, false))
377     return;
378
379   StringRef LTOName("full");
380
381   const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
382   if (A)
383     LTOName = A->getValue();
384
385   LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
386                 .Case("full", LTOK_Full)
387                 .Case("thin", LTOK_Thin)
388                 .Default(LTOK_Unknown);
389
390   if (LTOMode == LTOK_Unknown) {
391     assert(A);
392     Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
393                                                     << A->getValue();
394   }
395 }
396
397 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
398   llvm::PrettyStackTraceString CrashInfo("Compilation construction");
399
400   // FIXME: Handle environment options which affect driver behavior, somewhere
401   // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
402
403   if (char *env = ::getenv("COMPILER_PATH")) {
404     StringRef CompilerPath = env;
405     while (!CompilerPath.empty()) {
406       std::pair<StringRef, StringRef> Split =
407           CompilerPath.split(llvm::sys::EnvPathSeparator);
408       PrefixDirs.push_back(Split.first);
409       CompilerPath = Split.second;
410     }
411   }
412
413   // We look for the driver mode option early, because the mode can affect
414   // how other options are parsed.
415   ParseDriverMode(ArgList.slice(1));
416
417   // FIXME: What are we going to do with -V and -b?
418
419   // FIXME: This stuff needs to go into the Compilation, not the driver.
420   bool CCCPrintPhases;
421
422   InputArgList Args = ParseArgStrings(ArgList.slice(1));
423
424   // Silence driver warnings if requested
425   Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
426
427   // -no-canonical-prefixes is used very early in main.
428   Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
429
430   // Ignore -pipe.
431   Args.ClaimAllArgs(options::OPT_pipe);
432
433   // Extract -ccc args.
434   //
435   // FIXME: We need to figure out where this behavior should live. Most of it
436   // should be outside in the client; the parts that aren't should have proper
437   // options, either by introducing new ones or by overloading gcc ones like -V
438   // or -b.
439   CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
440   CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
441   if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
442     CCCGenericGCCName = A->getValue();
443   CCCUsePCH =
444       Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
445   // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
446   // and getToolChain is const.
447   if (IsCLMode()) {
448     // clang-cl targets MSVC-style Win32.
449     llvm::Triple T(DefaultTargetTriple);
450     T.setOS(llvm::Triple::Win32);
451     T.setVendor(llvm::Triple::PC);
452     T.setEnvironment(llvm::Triple::MSVC);
453     DefaultTargetTriple = T.str();
454   }
455   if (const Arg *A = Args.getLastArg(options::OPT_target))
456     DefaultTargetTriple = A->getValue();
457   if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
458     Dir = InstalledDir = A->getValue();
459   for (const Arg *A : Args.filtered(options::OPT_B)) {
460     A->claim();
461     PrefixDirs.push_back(A->getValue(0));
462   }
463   if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
464     SysRoot = A->getValue();
465   if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
466     DyldPrefix = A->getValue();
467   if (Args.hasArg(options::OPT_nostdlib))
468     UseStdLib = false;
469
470   if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
471     ResourceDir = A->getValue();
472
473   if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
474     SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
475                     .Case("cwd", SaveTempsCwd)
476                     .Case("obj", SaveTempsObj)
477                     .Default(SaveTempsCwd);
478   }
479
480   setLTOMode(Args);
481
482   std::unique_ptr<llvm::opt::InputArgList> UArgs =
483       llvm::make_unique<InputArgList>(std::move(Args));
484
485   // Perform the default argument translations.
486   DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
487
488   // Owned by the host.
489   const ToolChain &TC =
490       getToolChain(*UArgs, computeTargetTriple(DefaultTargetTriple, *UArgs));
491
492   // The compilation takes ownership of Args.
493   Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
494
495   C->setCudaDeviceToolChain(
496       &getToolChain(C->getArgs(), llvm::Triple(TC.getTriple().isArch64Bit()
497                                                    ? "nvptx64-nvidia-cuda"
498                                                    : "nvptx-nvidia-cuda")));
499   if (!HandleImmediateArgs(*C))
500     return C;
501
502   // Construct the list of inputs.
503   InputList Inputs;
504   BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
505
506   // Construct the list of abstract actions to perform for this compilation. On
507   // MachO targets this uses the driver-driver and universal actions.
508   if (TC.getTriple().isOSBinFormatMachO())
509     BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
510   else
511     BuildActions(*C, C->getDefaultToolChain(), C->getArgs(), Inputs,
512                  C->getActions());
513
514   if (CCCPrintPhases) {
515     PrintActions(*C);
516     return C;
517   }
518
519   BuildJobs(*C);
520
521   return C;
522 }
523
524 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
525   llvm::opt::ArgStringList ASL;
526   for (const auto *A : Args)
527     A->render(Args, ASL);
528
529   for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
530     if (I != ASL.begin())
531       OS << ' ';
532     Command::printArg(OS, *I, true);
533   }
534   OS << '\n';
535 }
536
537 // When clang crashes, produce diagnostic information including the fully
538 // preprocessed source file(s).  Request that the developer attach the
539 // diagnostic information to a bug report.
540 void Driver::generateCompilationDiagnostics(Compilation &C,
541                                             const Command &FailingCommand) {
542   if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
543     return;
544
545   // Don't try to generate diagnostics for link or dsymutil jobs.
546   if (FailingCommand.getCreator().isLinkJob() ||
547       FailingCommand.getCreator().isDsymutilJob())
548     return;
549
550   // Print the version of the compiler.
551   PrintVersion(C, llvm::errs());
552
553   Diag(clang::diag::note_drv_command_failed_diag_msg)
554       << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
555          "crash backtrace, preprocessed source, and associated run script.";
556
557   // Suppress driver output and emit preprocessor output to temp file.
558   Mode = CPPMode;
559   CCGenDiagnostics = true;
560
561   // Save the original job command(s).
562   Command Cmd = FailingCommand;
563
564   // Keep track of whether we produce any errors while trying to produce
565   // preprocessed sources.
566   DiagnosticErrorTrap Trap(Diags);
567
568   // Suppress tool output.
569   C.initCompilationForDiagnostics();
570
571   // Construct the list of inputs.
572   InputList Inputs;
573   BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
574
575   for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
576     bool IgnoreInput = false;
577
578     // Ignore input from stdin or any inputs that cannot be preprocessed.
579     // Check type first as not all linker inputs have a value.
580     if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
581       IgnoreInput = true;
582     } else if (!strcmp(it->second->getValue(), "-")) {
583       Diag(clang::diag::note_drv_command_failed_diag_msg)
584           << "Error generating preprocessed source(s) - "
585              "ignoring input from stdin.";
586       IgnoreInput = true;
587     }
588
589     if (IgnoreInput) {
590       it = Inputs.erase(it);
591       ie = Inputs.end();
592     } else {
593       ++it;
594     }
595   }
596
597   if (Inputs.empty()) {
598     Diag(clang::diag::note_drv_command_failed_diag_msg)
599         << "Error generating preprocessed source(s) - "
600            "no preprocessable inputs.";
601     return;
602   }
603
604   // Don't attempt to generate preprocessed files if multiple -arch options are
605   // used, unless they're all duplicates.
606   llvm::StringSet<> ArchNames;
607   for (const Arg *A : C.getArgs()) {
608     if (A->getOption().matches(options::OPT_arch)) {
609       StringRef ArchName = A->getValue();
610       ArchNames.insert(ArchName);
611     }
612   }
613   if (ArchNames.size() > 1) {
614     Diag(clang::diag::note_drv_command_failed_diag_msg)
615         << "Error generating preprocessed source(s) - cannot generate "
616            "preprocessed source with multiple -arch options.";
617     return;
618   }
619
620   // Construct the list of abstract actions to perform for this compilation. On
621   // Darwin OSes this uses the driver-driver and builds universal actions.
622   const ToolChain &TC = C.getDefaultToolChain();
623   if (TC.getTriple().isOSBinFormatMachO())
624     BuildUniversalActions(C, TC, Inputs);
625   else
626     BuildActions(C, TC, C.getArgs(), Inputs, C.getActions());
627
628   BuildJobs(C);
629
630   // If there were errors building the compilation, quit now.
631   if (Trap.hasErrorOccurred()) {
632     Diag(clang::diag::note_drv_command_failed_diag_msg)
633         << "Error generating preprocessed source(s).";
634     return;
635   }
636
637   // Generate preprocessed output.
638   SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
639   C.ExecuteJobs(C.getJobs(), FailingCommands);
640
641   // If any of the preprocessing commands failed, clean up and exit.
642   if (!FailingCommands.empty()) {
643     if (!isSaveTempsEnabled())
644       C.CleanupFileList(C.getTempFiles(), true);
645
646     Diag(clang::diag::note_drv_command_failed_diag_msg)
647         << "Error generating preprocessed source(s).";
648     return;
649   }
650
651   const ArgStringList &TempFiles = C.getTempFiles();
652   if (TempFiles.empty()) {
653     Diag(clang::diag::note_drv_command_failed_diag_msg)
654         << "Error generating preprocessed source(s).";
655     return;
656   }
657
658   Diag(clang::diag::note_drv_command_failed_diag_msg)
659       << "\n********************\n\n"
660          "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
661          "Preprocessed source(s) and associated run script(s) are located at:";
662
663   SmallString<128> VFS;
664   for (const char *TempFile : TempFiles) {
665     Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
666     if (StringRef(TempFile).endswith(".cache")) {
667       // In some cases (modules) we'll dump extra data to help with reproducing
668       // the crash into a directory next to the output.
669       VFS = llvm::sys::path::filename(TempFile);
670       llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
671     }
672   }
673
674   // Assume associated files are based off of the first temporary file.
675   CrashReportInfo CrashInfo(TempFiles[0], VFS);
676
677   std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
678   std::error_code EC;
679   llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
680   if (EC) {
681     Diag(clang::diag::note_drv_command_failed_diag_msg)
682         << "Error generating run script: " + Script + " " + EC.message();
683   } else {
684     ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
685              << "# Driver args: ";
686     printArgList(ScriptOS, C.getInputArgs());
687     ScriptOS << "# Original command: ";
688     Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
689     Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
690     Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
691   }
692
693   for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
694                                             options::OPT_frewrite_map_file_EQ))
695     Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
696
697   Diag(clang::diag::note_drv_command_failed_diag_msg)
698       << "\n\n********************";
699 }
700
701 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
702   // Since argumentsFitWithinSystemLimits() may underestimate system's capacity
703   // if the tool does not support response files, there is a chance/ that things
704   // will just work without a response file, so we silently just skip it.
705   if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
706       llvm::sys::argumentsFitWithinSystemLimits(Cmd.getArguments()))
707     return;
708
709   std::string TmpName = GetTemporaryPath("response", "txt");
710   Cmd.setResponseFile(
711       C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())));
712 }
713
714 int Driver::ExecuteCompilation(
715     Compilation &C,
716     SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
717   // Just print if -### was present.
718   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
719     C.getJobs().Print(llvm::errs(), "\n", true);
720     return 0;
721   }
722
723   // If there were errors building the compilation, quit now.
724   if (Diags.hasErrorOccurred())
725     return 1;
726
727   // Set up response file names for each command, if necessary
728   for (auto &Job : C.getJobs())
729     setUpResponseFiles(C, Job);
730
731   C.ExecuteJobs(C.getJobs(), FailingCommands);
732
733   // Remove temp files.
734   C.CleanupFileList(C.getTempFiles());
735
736   // If the command succeeded, we are done.
737   if (FailingCommands.empty())
738     return 0;
739
740   // Otherwise, remove result files and print extra information about abnormal
741   // failures.
742   for (const auto &CmdPair : FailingCommands) {
743     int Res = CmdPair.first;
744     const Command *FailingCommand = CmdPair.second;
745
746     // Remove result files if we're not saving temps.
747     if (!isSaveTempsEnabled()) {
748       const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
749       C.CleanupFileMap(C.getResultFiles(), JA, true);
750
751       // Failure result files are valid unless we crashed.
752       if (Res < 0)
753         C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
754     }
755
756     // Print extra information about abnormal failures, if possible.
757     //
758     // This is ad-hoc, but we don't want to be excessively noisy. If the result
759     // status was 1, assume the command failed normally. In particular, if it
760     // was the compiler then assume it gave a reasonable error code. Failures
761     // in other tools are less common, and they generally have worse
762     // diagnostics, so always print the diagnostic there.
763     const Tool &FailingTool = FailingCommand->getCreator();
764
765     if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
766       // FIXME: See FIXME above regarding result code interpretation.
767       if (Res < 0)
768         Diag(clang::diag::err_drv_command_signalled)
769             << FailingTool.getShortName();
770       else
771         Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
772                                                   << Res;
773     }
774   }
775   return 0;
776 }
777
778 void Driver::PrintHelp(bool ShowHidden) const {
779   unsigned IncludedFlagsBitmask;
780   unsigned ExcludedFlagsBitmask;
781   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
782       getIncludeExcludeOptionFlagMasks();
783
784   ExcludedFlagsBitmask |= options::NoDriverOption;
785   if (!ShowHidden)
786     ExcludedFlagsBitmask |= HelpHidden;
787
788   getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
789                       IncludedFlagsBitmask, ExcludedFlagsBitmask);
790 }
791
792 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
793   // FIXME: The following handlers should use a callback mechanism, we don't
794   // know what the client would like to do.
795   OS << getClangFullVersion() << '\n';
796   const ToolChain &TC = C.getDefaultToolChain();
797   OS << "Target: " << TC.getTripleString() << '\n';
798
799   // Print the threading model.
800   if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
801     // Don't print if the ToolChain would have barfed on it already
802     if (TC.isThreadModelSupported(A->getValue()))
803       OS << "Thread model: " << A->getValue();
804   } else
805     OS << "Thread model: " << TC.getThreadModel();
806   OS << '\n';
807
808   // Print out the install directory.
809   OS << "InstalledDir: " << InstalledDir << '\n';
810 }
811
812 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
813 /// option.
814 static void PrintDiagnosticCategories(raw_ostream &OS) {
815   // Skip the empty category.
816   for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
817        ++i)
818     OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
819 }
820
821 bool Driver::HandleImmediateArgs(const Compilation &C) {
822   // The order these options are handled in gcc is all over the place, but we
823   // don't expect inconsistencies w.r.t. that to matter in practice.
824
825   if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
826     llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
827     return false;
828   }
829
830   if (C.getArgs().hasArg(options::OPT_dumpversion)) {
831     // Since -dumpversion is only implemented for pedantic GCC compatibility, we
832     // return an answer which matches our definition of __VERSION__.
833     //
834     // If we want to return a more correct answer some day, then we should
835     // introduce a non-pedantically GCC compatible mode to Clang in which we
836     // provide sensible definitions for -dumpversion, __VERSION__, etc.
837     llvm::outs() << "4.2.1\n";
838     return false;
839   }
840
841   if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
842     PrintDiagnosticCategories(llvm::outs());
843     return false;
844   }
845
846   if (C.getArgs().hasArg(options::OPT_help) ||
847       C.getArgs().hasArg(options::OPT__help_hidden)) {
848     PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
849     return false;
850   }
851
852   if (C.getArgs().hasArg(options::OPT__version)) {
853     // Follow gcc behavior and use stdout for --version and stderr for -v.
854     PrintVersion(C, llvm::outs());
855     return false;
856   }
857
858   if (C.getArgs().hasArg(options::OPT_v) ||
859       C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
860     PrintVersion(C, llvm::errs());
861     SuppressMissingInputWarning = true;
862   }
863
864   const ToolChain &TC = C.getDefaultToolChain();
865
866   if (C.getArgs().hasArg(options::OPT_v))
867     TC.printVerboseInfo(llvm::errs());
868
869   if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
870     llvm::outs() << "programs: =";
871     bool separator = false;
872     for (const std::string &Path : TC.getProgramPaths()) {
873       if (separator)
874         llvm::outs() << ':';
875       llvm::outs() << Path;
876       separator = true;
877     }
878     llvm::outs() << "\n";
879     llvm::outs() << "libraries: =" << ResourceDir;
880
881     StringRef sysroot = C.getSysRoot();
882
883     for (const std::string &Path : TC.getFilePaths()) {
884       // Always print a separator. ResourceDir was the first item shown.
885       llvm::outs() << ':';
886       // Interpretation of leading '=' is needed only for NetBSD.
887       if (Path[0] == '=')
888         llvm::outs() << sysroot << Path.substr(1);
889       else
890         llvm::outs() << Path;
891     }
892     llvm::outs() << "\n";
893     return false;
894   }
895
896   // FIXME: The following handlers should use a callback mechanism, we don't
897   // know what the client would like to do.
898   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
899     llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
900     return false;
901   }
902
903   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
904     llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
905     return false;
906   }
907
908   if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
909     llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
910     return false;
911   }
912
913   if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
914     for (const Multilib &Multilib : TC.getMultilibs())
915       llvm::outs() << Multilib << "\n";
916     return false;
917   }
918
919   if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
920     for (const Multilib &Multilib : TC.getMultilibs()) {
921       if (Multilib.gccSuffix().empty())
922         llvm::outs() << ".\n";
923       else {
924         StringRef Suffix(Multilib.gccSuffix());
925         assert(Suffix.front() == '/');
926         llvm::outs() << Suffix.substr(1) << "\n";
927       }
928     }
929     return false;
930   }
931   return true;
932 }
933
934 // Display an action graph human-readably.  Action A is the "sink" node
935 // and latest-occuring action. Traversal is in pre-order, visiting the
936 // inputs to each action before printing the action itself.
937 static unsigned PrintActions1(const Compilation &C, Action *A,
938                               std::map<Action *, unsigned> &Ids) {
939   if (Ids.count(A)) // A was already visited.
940     return Ids[A];
941
942   std::string str;
943   llvm::raw_string_ostream os(str);
944
945   os << Action::getClassName(A->getKind()) << ", ";
946   if (InputAction *IA = dyn_cast<InputAction>(A)) {
947     os << "\"" << IA->getInputArg().getValue() << "\"";
948   } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
949     os << '"' << BIA->getArchName() << '"' << ", {"
950        << PrintActions1(C, *BIA->begin(), Ids) << "}";
951   } else if (CudaDeviceAction *CDA = dyn_cast<CudaDeviceAction>(A)) {
952     os << '"' << CDA->getGpuArchName() << '"' << ", {"
953        << PrintActions1(C, *CDA->begin(), Ids) << "}";
954   } else {
955     const ActionList *AL;
956     if (CudaHostAction *CHA = dyn_cast<CudaHostAction>(A)) {
957       os << "{" << PrintActions1(C, *CHA->begin(), Ids) << "}"
958          << ", gpu binaries ";
959       AL = &CHA->getDeviceActions();
960     } else
961       AL = &A->getInputs();
962
963     if (AL->size()) {
964       const char *Prefix = "{";
965       for (Action *PreRequisite : *AL) {
966         os << Prefix << PrintActions1(C, PreRequisite, Ids);
967         Prefix = ", ";
968       }
969       os << "}";
970     } else
971       os << "{}";
972   }
973
974   unsigned Id = Ids.size();
975   Ids[A] = Id;
976   llvm::errs() << Id << ": " << os.str() << ", "
977                << types::getTypeName(A->getType()) << "\n";
978
979   return Id;
980 }
981
982 // Print the action graphs in a compilation C.
983 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
984 void Driver::PrintActions(const Compilation &C) const {
985   std::map<Action *, unsigned> Ids;
986   for (Action *A : C.getActions())
987     PrintActions1(C, A, Ids);
988 }
989
990 /// \brief Check whether the given input tree contains any compilation or
991 /// assembly actions.
992 static bool ContainsCompileOrAssembleAction(const Action *A) {
993   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
994       isa<AssembleJobAction>(A))
995     return true;
996
997   for (const Action *Input : *A)
998     if (ContainsCompileOrAssembleAction(Input))
999       return true;
1000
1001   return false;
1002 }
1003
1004 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1005                                    const InputList &BAInputs) const {
1006   DerivedArgList &Args = C.getArgs();
1007   ActionList &Actions = C.getActions();
1008   llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1009   // Collect the list of architectures. Duplicates are allowed, but should only
1010   // be handled once (in the order seen).
1011   llvm::StringSet<> ArchNames;
1012   SmallVector<const char *, 4> Archs;
1013   for (Arg *A : Args) {
1014     if (A->getOption().matches(options::OPT_arch)) {
1015       // Validate the option here; we don't save the type here because its
1016       // particular spelling may participate in other driver choices.
1017       llvm::Triple::ArchType Arch =
1018           tools::darwin::getArchTypeForMachOArchName(A->getValue());
1019       if (Arch == llvm::Triple::UnknownArch) {
1020         Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1021         continue;
1022       }
1023
1024       A->claim();
1025       if (ArchNames.insert(A->getValue()).second)
1026         Archs.push_back(A->getValue());
1027     }
1028   }
1029
1030   // When there is no explicit arch for this platform, make sure we still bind
1031   // the architecture (to the default) so that -Xarch_ is handled correctly.
1032   if (!Archs.size())
1033     Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1034
1035   ActionList SingleActions;
1036   BuildActions(C, TC, Args, BAInputs, SingleActions);
1037
1038   // Add in arch bindings for every top level action, as well as lipo and
1039   // dsymutil steps if needed.
1040   for (Action* Act : SingleActions) {
1041     // Make sure we can lipo this kind of output. If not (and it is an actual
1042     // output) then we disallow, since we can't create an output file with the
1043     // right name without overwriting it. We could remove this oddity by just
1044     // changing the output names to include the arch, which would also fix
1045     // -save-temps. Compatibility wins for now.
1046
1047     if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1048       Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1049           << types::getTypeName(Act->getType());
1050
1051     ActionList Inputs;
1052     for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
1053       Inputs.push_back(
1054           new BindArchAction(std::unique_ptr<Action>(Act), Archs[i]));
1055       if (i != 0)
1056         Inputs.back()->setOwnsInputs(false);
1057     }
1058
1059     // Lipo if necessary, we do it this way because we need to set the arch flag
1060     // so that -Xarch_ gets overwritten.
1061     if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1062       Actions.append(Inputs.begin(), Inputs.end());
1063     else
1064       Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
1065
1066     // Handle debug info queries.
1067     Arg *A = Args.getLastArg(options::OPT_g_Group);
1068     if (A && !A->getOption().matches(options::OPT_g0) &&
1069         !A->getOption().matches(options::OPT_gstabs) &&
1070         ContainsCompileOrAssembleAction(Actions.back())) {
1071
1072       // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1073       // have a compile input. We need to run 'dsymutil' ourselves in such cases
1074       // because the debug info will refer to a temporary object file which
1075       // will be removed at the end of the compilation process.
1076       if (Act->getType() == types::TY_Image) {
1077         ActionList Inputs;
1078         Inputs.push_back(Actions.back());
1079         Actions.pop_back();
1080         Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
1081       }
1082
1083       // Verify the debug info output.
1084       if (Args.hasArg(options::OPT_verify_debug_info)) {
1085         std::unique_ptr<Action> VerifyInput(Actions.back());
1086         Actions.pop_back();
1087         Actions.push_back(new VerifyDebugInfoJobAction(std::move(VerifyInput),
1088                                                        types::TY_Nothing));
1089       }
1090     }
1091   }
1092 }
1093
1094 /// \brief Check that the file referenced by Value exists. If it doesn't,
1095 /// issue a diagnostic and return false.
1096 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
1097                                    StringRef Value) {
1098   if (!D.getCheckInputsExist())
1099     return true;
1100
1101   // stdin always exists.
1102   if (Value == "-")
1103     return true;
1104
1105   SmallString<64> Path(Value);
1106   if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1107     if (!llvm::sys::path::is_absolute(Path)) {
1108       SmallString<64> Directory(WorkDir->getValue());
1109       llvm::sys::path::append(Directory, Value);
1110       Path.assign(Directory);
1111     }
1112   }
1113
1114   if (llvm::sys::fs::exists(Twine(Path)))
1115     return true;
1116
1117   if (D.IsCLMode() && !llvm::sys::path::is_absolute(Twine(Path)) &&
1118       llvm::sys::Process::FindInEnvPath("LIB", Value))
1119     return true;
1120
1121   D.Diag(clang::diag::err_drv_no_such_file) << Path;
1122   return false;
1123 }
1124
1125 // Construct a the list of inputs and their types.
1126 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
1127                          InputList &Inputs) const {
1128   // Track the current user specified (-x) input. We also explicitly track the
1129   // argument used to set the type; we only want to claim the type when we
1130   // actually use it, so we warn about unused -x arguments.
1131   types::ID InputType = types::TY_Nothing;
1132   Arg *InputTypeArg = nullptr;
1133
1134   // The last /TC or /TP option sets the input type to C or C++ globally.
1135   if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1136                                          options::OPT__SLASH_TP)) {
1137     InputTypeArg = TCTP;
1138     InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
1139                     ? types::TY_C
1140                     : types::TY_CXX;
1141
1142     arg_iterator it =
1143         Args.filtered_begin(options::OPT__SLASH_TC, options::OPT__SLASH_TP);
1144     const arg_iterator ie = Args.filtered_end();
1145     Arg *Previous = *it++;
1146     bool ShowNote = false;
1147     while (it != ie) {
1148       Diag(clang::diag::warn_drv_overriding_flag_option)
1149           << Previous->getSpelling() << (*it)->getSpelling();
1150       Previous = *it++;
1151       ShowNote = true;
1152     }
1153     if (ShowNote)
1154       Diag(clang::diag::note_drv_t_option_is_global);
1155
1156     // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1157     assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1158   }
1159
1160   for (Arg *A : Args) {
1161     if (A->getOption().getKind() == Option::InputClass) {
1162       const char *Value = A->getValue();
1163       types::ID Ty = types::TY_INVALID;
1164
1165       // Infer the input type if necessary.
1166       if (InputType == types::TY_Nothing) {
1167         // If there was an explicit arg for this, claim it.
1168         if (InputTypeArg)
1169           InputTypeArg->claim();
1170
1171         // stdin must be handled specially.
1172         if (memcmp(Value, "-", 2) == 0) {
1173           // If running with -E, treat as a C input (this changes the builtin
1174           // macros, for example). This may be overridden by -ObjC below.
1175           //
1176           // Otherwise emit an error but still use a valid type to avoid
1177           // spurious errors (e.g., no inputs).
1178           if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
1179             Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1180                             : clang::diag::err_drv_unknown_stdin_type);
1181           Ty = types::TY_C;
1182         } else {
1183           // Otherwise lookup by extension.
1184           // Fallback is C if invoked as C preprocessor or Object otherwise.
1185           // We use a host hook here because Darwin at least has its own
1186           // idea of what .s is.
1187           if (const char *Ext = strrchr(Value, '.'))
1188             Ty = TC.LookupTypeForExtension(Ext + 1);
1189
1190           if (Ty == types::TY_INVALID) {
1191             if (CCCIsCPP())
1192               Ty = types::TY_C;
1193             else
1194               Ty = types::TY_Object;
1195           }
1196
1197           // If the driver is invoked as C++ compiler (like clang++ or c++) it
1198           // should autodetect some input files as C++ for g++ compatibility.
1199           if (CCCIsCXX()) {
1200             types::ID OldTy = Ty;
1201             Ty = types::lookupCXXTypeForCType(Ty);
1202
1203             if (Ty != OldTy)
1204               Diag(clang::diag::warn_drv_treating_input_as_cxx)
1205                   << getTypeName(OldTy) << getTypeName(Ty);
1206           }
1207         }
1208
1209         // -ObjC and -ObjC++ override the default language, but only for "source
1210         // files". We just treat everything that isn't a linker input as a
1211         // source file.
1212         //
1213         // FIXME: Clean this up if we move the phase sequence into the type.
1214         if (Ty != types::TY_Object) {
1215           if (Args.hasArg(options::OPT_ObjC))
1216             Ty = types::TY_ObjC;
1217           else if (Args.hasArg(options::OPT_ObjCXX))
1218             Ty = types::TY_ObjCXX;
1219         }
1220       } else {
1221         assert(InputTypeArg && "InputType set w/o InputTypeArg");
1222         if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1223           // If emulating cl.exe, make sure that /TC and /TP don't affect input
1224           // object files.
1225           const char *Ext = strrchr(Value, '.');
1226           if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1227             Ty = types::TY_Object;
1228         }
1229         if (Ty == types::TY_INVALID) {
1230           Ty = InputType;
1231           InputTypeArg->claim();
1232         }
1233       }
1234
1235       if (DiagnoseInputExistence(*this, Args, Value))
1236         Inputs.push_back(std::make_pair(Ty, A));
1237
1238     } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1239       StringRef Value = A->getValue();
1240       if (DiagnoseInputExistence(*this, Args, Value)) {
1241         Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1242         Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1243       }
1244       A->claim();
1245     } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1246       StringRef Value = A->getValue();
1247       if (DiagnoseInputExistence(*this, Args, Value)) {
1248         Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1249         Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1250       }
1251       A->claim();
1252     } else if (A->getOption().hasFlag(options::LinkerInput)) {
1253       // Just treat as object type, we could make a special type for this if
1254       // necessary.
1255       Inputs.push_back(std::make_pair(types::TY_Object, A));
1256
1257     } else if (A->getOption().matches(options::OPT_x)) {
1258       InputTypeArg = A;
1259       InputType = types::lookupTypeForTypeSpecifier(A->getValue());
1260       A->claim();
1261
1262       // Follow gcc behavior and treat as linker input for invalid -x
1263       // options. Its not clear why we shouldn't just revert to unknown; but
1264       // this isn't very important, we might as well be bug compatible.
1265       if (!InputType) {
1266         Diag(clang::diag::err_drv_unknown_language) << A->getValue();
1267         InputType = types::TY_Object;
1268       }
1269     }
1270   }
1271   if (CCCIsCPP() && Inputs.empty()) {
1272     // If called as standalone preprocessor, stdin is processed
1273     // if no other input is present.
1274     Arg *A = MakeInputArg(Args, Opts, "-");
1275     Inputs.push_back(std::make_pair(types::TY_C, A));
1276   }
1277 }
1278
1279 // For each unique --cuda-gpu-arch= argument creates a TY_CUDA_DEVICE
1280 // input action and then wraps each in CudaDeviceAction paired with
1281 // appropriate GPU arch name. In case of partial (i.e preprocessing
1282 // only) or device-only compilation, each device action is added to /p
1283 // Actions and /p Current is released. Otherwise the function creates
1284 // and returns a new CudaHostAction which wraps /p Current and device
1285 // side actions.
1286 static std::unique_ptr<Action>
1287 buildCudaActions(Compilation &C, DerivedArgList &Args, const Arg *InputArg,
1288                  std::unique_ptr<Action> HostAction, ActionList &Actions) {
1289   Arg *PartialCompilationArg = Args.getLastArg(options::OPT_cuda_host_only,
1290                                                options::OPT_cuda_device_only);
1291   // Host-only compilation case.
1292   if (PartialCompilationArg &&
1293       PartialCompilationArg->getOption().matches(options::OPT_cuda_host_only))
1294     return std::unique_ptr<Action>(
1295         new CudaHostAction(std::move(HostAction), {}));
1296
1297   // Collect all cuda_gpu_arch parameters, removing duplicates.
1298   SmallVector<const char *, 4> GpuArchList;
1299   llvm::StringSet<> GpuArchNames;
1300   for (Arg *A : Args) {
1301     if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ)) {
1302       A->claim();
1303       if (GpuArchNames.insert(A->getValue()).second)
1304         GpuArchList.push_back(A->getValue());
1305     }
1306   }
1307
1308   // Default to sm_20 which is the lowest common denominator for supported GPUs.
1309   // sm_20 code should work correctly, if suboptimally, on all newer GPUs.
1310   if (GpuArchList.empty())
1311     GpuArchList.push_back("sm_20");
1312
1313   // Replicate inputs for each GPU architecture.
1314   Driver::InputList CudaDeviceInputs;
1315   for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1316     CudaDeviceInputs.push_back(std::make_pair(types::TY_CUDA_DEVICE, InputArg));
1317
1318   // Build actions for all device inputs.
1319   assert(C.getCudaDeviceToolChain() &&
1320          "Missing toolchain for device-side compilation.");
1321   ActionList CudaDeviceActions;
1322   C.getDriver().BuildActions(C, *C.getCudaDeviceToolChain(), Args,
1323                              CudaDeviceInputs, CudaDeviceActions);
1324   assert(GpuArchList.size() == CudaDeviceActions.size() &&
1325          "Failed to create actions for all devices");
1326
1327   // Check whether any of device actions stopped before they could generate PTX.
1328   bool PartialCompilation = false;
1329   for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1330     if (CudaDeviceActions[I]->getKind() != Action::BackendJobClass) {
1331       PartialCompilation = true;
1332       break;
1333     }
1334   }
1335
1336   // Figure out what to do with device actions -- pass them as inputs to the
1337   // host action or run each of them independently.
1338   bool DeviceOnlyCompilation = PartialCompilationArg != nullptr;
1339   if (PartialCompilation || DeviceOnlyCompilation) {
1340     // In case of partial or device-only compilation results of device actions
1341     // are not consumed by the host action device actions have to be added to
1342     // top-level actions list with AtTopLevel=true and run independently.
1343
1344     // -o is ambiguous if we have more than one top-level action.
1345     if (Args.hasArg(options::OPT_o) &&
1346         (!DeviceOnlyCompilation || GpuArchList.size() > 1)) {
1347       C.getDriver().Diag(
1348           clang::diag::err_drv_output_argument_with_multiple_files);
1349       return nullptr;
1350     }
1351
1352     for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1353       Actions.push_back(new CudaDeviceAction(
1354           std::unique_ptr<Action>(CudaDeviceActions[I]), GpuArchList[I],
1355           /* AtTopLevel */ true));
1356     // Kill host action in case of device-only compilation.
1357     if (DeviceOnlyCompilation)
1358       HostAction.reset(nullptr);
1359     return HostAction;
1360   }
1361
1362   // Outputs of device actions during complete CUDA compilation get created
1363   // with AtTopLevel=false and become inputs for the host action.
1364   ActionList DeviceActions;
1365   for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1366     DeviceActions.push_back(new CudaDeviceAction(
1367         std::unique_ptr<Action>(CudaDeviceActions[I]), GpuArchList[I],
1368         /* AtTopLevel */ false));
1369   // Return a new host action that incorporates original host action and all
1370   // device actions.
1371   return std::unique_ptr<Action>(
1372       new CudaHostAction(std::move(HostAction), DeviceActions));
1373 }
1374
1375 void Driver::BuildActions(Compilation &C, const ToolChain &TC,
1376                           DerivedArgList &Args, const InputList &Inputs,
1377                           ActionList &Actions) const {
1378   llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
1379
1380   if (!SuppressMissingInputWarning && Inputs.empty()) {
1381     Diag(clang::diag::err_drv_no_input_files);
1382     return;
1383   }
1384
1385   Arg *FinalPhaseArg;
1386   phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
1387
1388   if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) {
1389     Diag(clang::diag::err_drv_emit_llvm_link);
1390   }
1391
1392   // Reject -Z* at the top level, these options should never have been exposed
1393   // by gcc.
1394   if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
1395     Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
1396
1397   // Diagnose misuse of /Fo.
1398   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
1399     StringRef V = A->getValue();
1400     if (Inputs.size() > 1 && !V.empty() &&
1401         !llvm::sys::path::is_separator(V.back())) {
1402       // Check whether /Fo tries to name an output file for multiple inputs.
1403       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
1404           << A->getSpelling() << V;
1405       Args.eraseArg(options::OPT__SLASH_Fo);
1406     }
1407   }
1408
1409   // Diagnose misuse of /Fa.
1410   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
1411     StringRef V = A->getValue();
1412     if (Inputs.size() > 1 && !V.empty() &&
1413         !llvm::sys::path::is_separator(V.back())) {
1414       // Check whether /Fa tries to name an asm file for multiple inputs.
1415       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
1416           << A->getSpelling() << V;
1417       Args.eraseArg(options::OPT__SLASH_Fa);
1418     }
1419   }
1420
1421   // Diagnose misuse of /o.
1422   if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
1423     if (A->getValue()[0] == '\0') {
1424       // It has to have a value.
1425       Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
1426       Args.eraseArg(options::OPT__SLASH_o);
1427     }
1428   }
1429
1430   // Construct the actions to perform.
1431   ActionList LinkerInputs;
1432
1433   llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
1434   for (auto &I : Inputs) {
1435     types::ID InputType = I.first;
1436     const Arg *InputArg = I.second;
1437
1438     PL.clear();
1439     types::getCompilationPhases(InputType, PL);
1440
1441     // If the first step comes after the final phase we are doing as part of
1442     // this compilation, warn the user about it.
1443     phases::ID InitialPhase = PL[0];
1444     if (InitialPhase > FinalPhase) {
1445       // Claim here to avoid the more general unused warning.
1446       InputArg->claim();
1447
1448       // Suppress all unused style warnings with -Qunused-arguments
1449       if (Args.hasArg(options::OPT_Qunused_arguments))
1450         continue;
1451
1452       // Special case when final phase determined by binary name, rather than
1453       // by a command-line argument with a corresponding Arg.
1454       if (CCCIsCPP())
1455         Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
1456             << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
1457       // Special case '-E' warning on a previously preprocessed file to make
1458       // more sense.
1459       else if (InitialPhase == phases::Compile &&
1460                FinalPhase == phases::Preprocess &&
1461                getPreprocessedType(InputType) == types::TY_INVALID)
1462         Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
1463             << InputArg->getAsString(Args) << !!FinalPhaseArg
1464             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
1465       else
1466         Diag(clang::diag::warn_drv_input_file_unused)
1467             << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
1468             << !!FinalPhaseArg
1469             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
1470       continue;
1471     }
1472
1473     phases::ID CudaInjectionPhase = FinalPhase;
1474     for (const auto &Phase : PL)
1475       if (Phase <= FinalPhase && Phase == phases::Compile) {
1476         CudaInjectionPhase = Phase;
1477         break;
1478       }
1479
1480     // Build the pipeline for this file.
1481     std::unique_ptr<Action> Current(new InputAction(*InputArg, InputType));
1482     for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
1483          i != e; ++i) {
1484       phases::ID Phase = *i;
1485
1486       // We are done if this step is past what the user requested.
1487       if (Phase > FinalPhase)
1488         break;
1489
1490       // Queue linker inputs.
1491       if (Phase == phases::Link) {
1492         assert((i + 1) == e && "linking must be final compilation step.");
1493         LinkerInputs.push_back(Current.release());
1494         break;
1495       }
1496
1497       // Some types skip the assembler phase (e.g., llvm-bc), but we can't
1498       // encode this in the steps because the intermediate type depends on
1499       // arguments. Just special case here.
1500       if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
1501         continue;
1502
1503       // Otherwise construct the appropriate action.
1504       Current = ConstructPhaseAction(TC, Args, Phase, std::move(Current));
1505
1506       if (InputType == types::TY_CUDA && Phase == CudaInjectionPhase) {
1507         Current =
1508             buildCudaActions(C, Args, InputArg, std::move(Current), Actions);
1509         if (!Current)
1510           break;
1511       }
1512
1513       if (Current->getType() == types::TY_Nothing)
1514         break;
1515     }
1516
1517     // If we ended with something, add to the output list.
1518     if (Current)
1519       Actions.push_back(Current.release());
1520   }
1521
1522   // Add a link action if necessary.
1523   if (!LinkerInputs.empty())
1524     Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
1525
1526   // If we are linking, claim any options which are obviously only used for
1527   // compilation.
1528   if (FinalPhase == phases::Link && PL.size() == 1) {
1529     Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
1530     Args.ClaimAllArgs(options::OPT_cl_compile_Group);
1531   }
1532
1533   // Claim ignored clang-cl options.
1534   Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
1535
1536   // Claim --cuda-host-only arg which may be passed to non-CUDA
1537   // compilations and should not trigger warnings there.
1538   Args.ClaimAllArgs(options::OPT_cuda_host_only);
1539 }
1540
1541 std::unique_ptr<Action>
1542 Driver::ConstructPhaseAction(const ToolChain &TC, const ArgList &Args,
1543                              phases::ID Phase,
1544                              std::unique_ptr<Action> Input) const {
1545   llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
1546   // Build the appropriate action.
1547   switch (Phase) {
1548   case phases::Link:
1549     llvm_unreachable("link action invalid here.");
1550   case phases::Preprocess: {
1551     types::ID OutputTy;
1552     // -{M, MM} alter the output type.
1553     if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
1554       OutputTy = types::TY_Dependencies;
1555     } else {
1556       OutputTy = Input->getType();
1557       if (!Args.hasFlag(options::OPT_frewrite_includes,
1558                         options::OPT_fno_rewrite_includes, false) &&
1559           !CCGenDiagnostics)
1560         OutputTy = types::getPreprocessedType(OutputTy);
1561       assert(OutputTy != types::TY_INVALID &&
1562              "Cannot preprocess this input type!");
1563     }
1564     return llvm::make_unique<PreprocessJobAction>(std::move(Input), OutputTy);
1565   }
1566   case phases::Precompile: {
1567     types::ID OutputTy = types::TY_PCH;
1568     if (Args.hasArg(options::OPT_fsyntax_only)) {
1569       // Syntax checks should not emit a PCH file
1570       OutputTy = types::TY_Nothing;
1571     }
1572     return llvm::make_unique<PrecompileJobAction>(std::move(Input), OutputTy);
1573   }
1574   case phases::Compile: {
1575     if (Args.hasArg(options::OPT_fsyntax_only))
1576       return llvm::make_unique<CompileJobAction>(std::move(Input),
1577                                                  types::TY_Nothing);
1578     if (Args.hasArg(options::OPT_rewrite_objc))
1579       return llvm::make_unique<CompileJobAction>(std::move(Input),
1580                                                  types::TY_RewrittenObjC);
1581     if (Args.hasArg(options::OPT_rewrite_legacy_objc))
1582       return llvm::make_unique<CompileJobAction>(std::move(Input),
1583                                                  types::TY_RewrittenLegacyObjC);
1584     if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
1585       return llvm::make_unique<AnalyzeJobAction>(std::move(Input),
1586                                                  types::TY_Plist);
1587     if (Args.hasArg(options::OPT__migrate))
1588       return llvm::make_unique<MigrateJobAction>(std::move(Input),
1589                                                  types::TY_Remap);
1590     if (Args.hasArg(options::OPT_emit_ast))
1591       return llvm::make_unique<CompileJobAction>(std::move(Input),
1592                                                  types::TY_AST);
1593     if (Args.hasArg(options::OPT_module_file_info))
1594       return llvm::make_unique<CompileJobAction>(std::move(Input),
1595                                                  types::TY_ModuleFile);
1596     if (Args.hasArg(options::OPT_verify_pch))
1597       return llvm::make_unique<VerifyPCHJobAction>(std::move(Input),
1598                                                    types::TY_Nothing);
1599     return llvm::make_unique<CompileJobAction>(std::move(Input),
1600                                                types::TY_LLVM_BC);
1601   }
1602   case phases::Backend: {
1603     if (isUsingLTO()) {
1604       types::ID Output =
1605           Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
1606       return llvm::make_unique<BackendJobAction>(std::move(Input), Output);
1607     }
1608     if (Args.hasArg(options::OPT_emit_llvm)) {
1609       types::ID Output =
1610           Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
1611       return llvm::make_unique<BackendJobAction>(std::move(Input), Output);
1612     }
1613     return llvm::make_unique<BackendJobAction>(std::move(Input),
1614                                                types::TY_PP_Asm);
1615   }
1616   case phases::Assemble:
1617     return llvm::make_unique<AssembleJobAction>(std::move(Input),
1618                                                 types::TY_Object);
1619   }
1620
1621   llvm_unreachable("invalid phase in ConstructPhaseAction");
1622 }
1623
1624 void Driver::BuildJobs(Compilation &C) const {
1625   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1626
1627   Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
1628
1629   // It is an error to provide a -o option if we are making multiple output
1630   // files.
1631   if (FinalOutput) {
1632     unsigned NumOutputs = 0;
1633     for (const Action *A : C.getActions())
1634       if (A->getType() != types::TY_Nothing)
1635         ++NumOutputs;
1636
1637     if (NumOutputs > 1) {
1638       Diag(clang::diag::err_drv_output_argument_with_multiple_files);
1639       FinalOutput = nullptr;
1640     }
1641   }
1642
1643   // Collect the list of architectures.
1644   llvm::StringSet<> ArchNames;
1645   if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
1646     for (const Arg *A : C.getArgs())
1647       if (A->getOption().matches(options::OPT_arch))
1648         ArchNames.insert(A->getValue());
1649
1650   for (Action *A : C.getActions()) {
1651     // If we are linking an image for multiple archs then the linker wants
1652     // -arch_multiple and -final_output <final image name>. Unfortunately, this
1653     // doesn't fit in cleanly because we have to pass this information down.
1654     //
1655     // FIXME: This is a hack; find a cleaner way to integrate this into the
1656     // process.
1657     const char *LinkingOutput = nullptr;
1658     if (isa<LipoJobAction>(A)) {
1659       if (FinalOutput)
1660         LinkingOutput = FinalOutput->getValue();
1661       else
1662         LinkingOutput = getDefaultImageName();
1663     }
1664
1665     InputInfo II;
1666     BuildJobsForAction(C, A, &C.getDefaultToolChain(),
1667                        /*BoundArch*/ nullptr,
1668                        /*AtTopLevel*/ true,
1669                        /*MultipleArchs*/ ArchNames.size() > 1,
1670                        /*LinkingOutput*/ LinkingOutput, II);
1671   }
1672
1673   // If the user passed -Qunused-arguments or there were errors, don't warn
1674   // about any unused arguments.
1675   if (Diags.hasErrorOccurred() ||
1676       C.getArgs().hasArg(options::OPT_Qunused_arguments))
1677     return;
1678
1679   // Claim -### here.
1680   (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1681
1682   // Claim --driver-mode, it was handled earlier.
1683   (void)C.getArgs().hasArg(options::OPT_driver_mode);
1684
1685   for (Arg *A : C.getArgs()) {
1686     // FIXME: It would be nice to be able to send the argument to the
1687     // DiagnosticsEngine, so that extra values, position, and so on could be
1688     // printed.
1689     if (!A->isClaimed()) {
1690       if (A->getOption().hasFlag(options::NoArgumentUnused))
1691         continue;
1692
1693       // Suppress the warning automatically if this is just a flag, and it is an
1694       // instance of an argument we already claimed.
1695       const Option &Opt = A->getOption();
1696       if (Opt.getKind() == Option::FlagClass) {
1697         bool DuplicateClaimed = false;
1698
1699         for (const Arg *AA : C.getArgs().filtered(&Opt)) {
1700           if (AA->isClaimed()) {
1701             DuplicateClaimed = true;
1702             break;
1703           }
1704         }
1705
1706         if (DuplicateClaimed)
1707           continue;
1708       }
1709
1710       Diag(clang::diag::warn_drv_unused_argument)
1711           << A->getAsString(C.getArgs());
1712     }
1713   }
1714 }
1715
1716 // Returns a Tool for a given JobAction.  In case the action and its
1717 // predecessors can be combined, updates Inputs with the inputs of the
1718 // first combined action. If one of the collapsed actions is a
1719 // CudaHostAction, updates CollapsedCHA with the pointer to it so the
1720 // caller can deal with extra handling such action requires.
1721 static const Tool *selectToolForJob(Compilation &C, bool SaveTemps,
1722                                     const ToolChain *TC, const JobAction *JA,
1723                                     const ActionList *&Inputs,
1724                                     const CudaHostAction *&CollapsedCHA) {
1725   const Tool *ToolForJob = nullptr;
1726   CollapsedCHA = nullptr;
1727
1728   // See if we should look for a compiler with an integrated assembler. We match
1729   // bottom up, so what we are actually looking for is an assembler job with a
1730   // compiler input.
1731
1732   if (TC->useIntegratedAs() && !SaveTemps &&
1733       !C.getArgs().hasArg(options::OPT_via_file_asm) &&
1734       !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
1735       !C.getArgs().hasArg(options::OPT__SLASH_Fa) &&
1736       isa<AssembleJobAction>(JA) && Inputs->size() == 1 &&
1737       isa<BackendJobAction>(*Inputs->begin())) {
1738     // A BackendJob is always preceded by a CompileJob, and without
1739     // -save-temps they will always get combined together, so instead of
1740     // checking the backend tool, check if the tool for the CompileJob
1741     // has an integrated assembler.
1742     const ActionList *BackendInputs = &(*Inputs)[0]->getInputs();
1743     // Compile job may be wrapped in CudaHostAction, extract it if
1744     // that's the case and update CollapsedCHA if we combine phases.
1745     CudaHostAction *CHA = dyn_cast<CudaHostAction>(*BackendInputs->begin());
1746     JobAction *CompileJA =
1747         cast<CompileJobAction>(CHA ? *CHA->begin() : *BackendInputs->begin());
1748     assert(CompileJA && "Backend job is not preceeded by compile job.");
1749     const Tool *Compiler = TC->SelectTool(*CompileJA);
1750     if (!Compiler)
1751       return nullptr;
1752     if (Compiler->hasIntegratedAssembler()) {
1753       Inputs = &CompileJA->getInputs();
1754       ToolForJob = Compiler;
1755       CollapsedCHA = CHA;
1756     }
1757   }
1758
1759   // A backend job should always be combined with the preceding compile job
1760   // unless OPT_save_temps is enabled and the compiler is capable of emitting
1761   // LLVM IR as an intermediate output.
1762   if (isa<BackendJobAction>(JA)) {
1763     // Check if the compiler supports emitting LLVM IR.
1764     assert(Inputs->size() == 1);
1765     // Compile job may be wrapped in CudaHostAction, extract it if
1766     // that's the case and update CollapsedCHA if we combine phases.
1767     CudaHostAction *CHA = dyn_cast<CudaHostAction>(*Inputs->begin());
1768     JobAction *CompileJA =
1769         cast<CompileJobAction>(CHA ? *CHA->begin() : *Inputs->begin());
1770     assert(CompileJA && "Backend job is not preceeded by compile job.");
1771     const Tool *Compiler = TC->SelectTool(*CompileJA);
1772     if (!Compiler)
1773       return nullptr;
1774     if (!Compiler->canEmitIR() || !SaveTemps) {
1775       Inputs = &CompileJA->getInputs();
1776       ToolForJob = Compiler;
1777       CollapsedCHA = CHA;
1778     }
1779   }
1780
1781   // Otherwise use the tool for the current job.
1782   if (!ToolForJob)
1783     ToolForJob = TC->SelectTool(*JA);
1784
1785   // See if we should use an integrated preprocessor. We do so when we have
1786   // exactly one input, since this is the only use case we care about
1787   // (irrelevant since we don't support combine yet).
1788   if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
1789       !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
1790       !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
1791       !C.getArgs().hasArg(options::OPT_rewrite_objc) &&
1792       ToolForJob->hasIntegratedCPP())
1793     Inputs = &(*Inputs)[0]->getInputs();
1794
1795   return ToolForJob;
1796 }
1797
1798 void Driver::BuildJobsForAction(Compilation &C, const Action *A,
1799                                 const ToolChain *TC, const char *BoundArch,
1800                                 bool AtTopLevel, bool MultipleArchs,
1801                                 const char *LinkingOutput,
1802                                 InputInfo &Result) const {
1803   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1804
1805   InputInfoList CudaDeviceInputInfos;
1806   if (const CudaHostAction *CHA = dyn_cast<CudaHostAction>(A)) {
1807     InputInfo II;
1808     // Append outputs of device jobs to the input list.
1809     for (const Action *DA : CHA->getDeviceActions()) {
1810       BuildJobsForAction(C, DA, TC, nullptr, AtTopLevel,
1811                          /*MultipleArchs*/ false, LinkingOutput, II);
1812       CudaDeviceInputInfos.push_back(II);
1813     }
1814     // Override current action with a real host compile action and continue
1815     // processing it.
1816     A = *CHA->begin();
1817   }
1818
1819   if (const InputAction *IA = dyn_cast<InputAction>(A)) {
1820     // FIXME: It would be nice to not claim this here; maybe the old scheme of
1821     // just using Args was better?
1822     const Arg &Input = IA->getInputArg();
1823     Input.claim();
1824     if (Input.getOption().matches(options::OPT_INPUT)) {
1825       const char *Name = Input.getValue();
1826       Result = InputInfo(Name, A->getType(), Name);
1827     } else {
1828       Result = InputInfo(&Input, A->getType(), "");
1829     }
1830     return;
1831   }
1832
1833   if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1834     const ToolChain *TC;
1835     const char *ArchName = BAA->getArchName();
1836
1837     if (ArchName)
1838       TC = &getToolChain(
1839           C.getArgs(),
1840           computeTargetTriple(DefaultTargetTriple, C.getArgs(), ArchName));
1841     else
1842       TC = &C.getDefaultToolChain();
1843
1844     BuildJobsForAction(C, *BAA->begin(), TC, ArchName, AtTopLevel,
1845                        MultipleArchs, LinkingOutput, Result);
1846     return;
1847   }
1848
1849   if (const CudaDeviceAction *CDA = dyn_cast<CudaDeviceAction>(A)) {
1850     // Initial processing of CudaDeviceAction carries host params.
1851     // Call BuildJobsForAction() again, now with correct device parameters.
1852     assert(CDA->getGpuArchName() && "No GPU name in device action.");
1853     BuildJobsForAction(C, *CDA->begin(), C.getCudaDeviceToolChain(),
1854                        CDA->getGpuArchName(), CDA->isAtTopLevel(),
1855                        /*MultipleArchs*/ true, LinkingOutput, Result);
1856     return;
1857   }
1858
1859   const ActionList *Inputs = &A->getInputs();
1860
1861   const JobAction *JA = cast<JobAction>(A);
1862   const CudaHostAction *CollapsedCHA = nullptr;
1863   const Tool *T =
1864       selectToolForJob(C, isSaveTempsEnabled(), TC, JA, Inputs, CollapsedCHA);
1865   if (!T)
1866     return;
1867
1868   // If we've collapsed action list that contained CudaHostAction we
1869   // need to build jobs for device-side inputs it may have held.
1870   if (CollapsedCHA) {
1871     InputInfo II;
1872     for (const Action *DA : CollapsedCHA->getDeviceActions()) {
1873       BuildJobsForAction(C, DA, TC, "", AtTopLevel,
1874                          /*MultipleArchs*/ false, LinkingOutput, II);
1875       CudaDeviceInputInfos.push_back(II);
1876     }
1877   }
1878
1879   // Only use pipes when there is exactly one input.
1880   InputInfoList InputInfos;
1881   for (const Action *Input : *Inputs) {
1882     // Treat dsymutil and verify sub-jobs as being at the top-level too, they
1883     // shouldn't get temporary output names.
1884     // FIXME: Clean this up.
1885     bool SubJobAtTopLevel = false;
1886     if (AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A)))
1887       SubJobAtTopLevel = true;
1888
1889     InputInfo II;
1890     BuildJobsForAction(C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs,
1891                        LinkingOutput, II);
1892     InputInfos.push_back(II);
1893   }
1894
1895   // Always use the first input as the base input.
1896   const char *BaseInput = InputInfos[0].getBaseInput();
1897
1898   // ... except dsymutil actions, which use their actual input as the base
1899   // input.
1900   if (JA->getType() == types::TY_dSYM)
1901     BaseInput = InputInfos[0].getFilename();
1902
1903   // Append outputs of cuda device jobs to the input list
1904   if (CudaDeviceInputInfos.size())
1905     InputInfos.append(CudaDeviceInputInfos.begin(), CudaDeviceInputInfos.end());
1906
1907   // Determine the place to write output to, if any.
1908   if (JA->getType() == types::TY_Nothing)
1909     Result = InputInfo(A->getType(), BaseInput);
1910   else
1911     Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
1912                                           AtTopLevel, MultipleArchs),
1913                        A->getType(), BaseInput);
1914
1915   if (CCCPrintBindings && !CCGenDiagnostics) {
1916     llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
1917                  << " - \"" << T->getName() << "\", inputs: [";
1918     for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1919       llvm::errs() << InputInfos[i].getAsString();
1920       if (i + 1 != e)
1921         llvm::errs() << ", ";
1922     }
1923     llvm::errs() << "], output: " << Result.getAsString() << "\n";
1924   } else {
1925     T->ConstructJob(C, *JA, Result, InputInfos,
1926                     C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
1927   }
1928 }
1929
1930 const char *Driver::getDefaultImageName() const {
1931   llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
1932   return Target.isOSWindows() ? "a.exe" : "a.out";
1933 }
1934
1935 /// \brief Create output filename based on ArgValue, which could either be a
1936 /// full filename, filename without extension, or a directory. If ArgValue
1937 /// does not provide a filename, then use BaseName, and use the extension
1938 /// suitable for FileType.
1939 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
1940                                         StringRef BaseName,
1941                                         types::ID FileType) {
1942   SmallString<128> Filename = ArgValue;
1943
1944   if (ArgValue.empty()) {
1945     // If the argument is empty, output to BaseName in the current dir.
1946     Filename = BaseName;
1947   } else if (llvm::sys::path::is_separator(Filename.back())) {
1948     // If the argument is a directory, output to BaseName in that dir.
1949     llvm::sys::path::append(Filename, BaseName);
1950   }
1951
1952   if (!llvm::sys::path::has_extension(ArgValue)) {
1953     // If the argument didn't provide an extension, then set it.
1954     const char *Extension = types::getTypeTempSuffix(FileType, true);
1955
1956     if (FileType == types::TY_Image &&
1957         Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
1958       // The output file is a dll.
1959       Extension = "dll";
1960     }
1961
1962     llvm::sys::path::replace_extension(Filename, Extension);
1963   }
1964
1965   return Args.MakeArgString(Filename.c_str());
1966 }
1967
1968 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
1969                                        const char *BaseInput,
1970                                        const char *BoundArch, bool AtTopLevel,
1971                                        bool MultipleArchs) const {
1972   llvm::PrettyStackTraceString CrashInfo("Computing output path");
1973   // Output to a user requested destination?
1974   if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
1975     if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1976       return C.addResultFile(FinalOutput->getValue(), &JA);
1977   }
1978
1979   // For /P, preprocess to file named after BaseInput.
1980   if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
1981     assert(AtTopLevel && isa<PreprocessJobAction>(JA));
1982     StringRef BaseName = llvm::sys::path::filename(BaseInput);
1983     StringRef NameArg;
1984     if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
1985       NameArg = A->getValue();
1986     return C.addResultFile(
1987         MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
1988         &JA);
1989   }
1990
1991   // Default to writing to stdout?
1992   if (AtTopLevel && !CCGenDiagnostics &&
1993       (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
1994     return "-";
1995
1996   // Is this the assembly listing for /FA?
1997   if (JA.getType() == types::TY_PP_Asm &&
1998       (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
1999        C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
2000     // Use /Fa and the input filename to determine the asm file name.
2001     StringRef BaseName = llvm::sys::path::filename(BaseInput);
2002     StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
2003     return C.addResultFile(
2004         MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
2005         &JA);
2006   }
2007
2008   // Output to a temporary file?
2009   if ((!AtTopLevel && !isSaveTempsEnabled() &&
2010        !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
2011       CCGenDiagnostics) {
2012     StringRef Name = llvm::sys::path::filename(BaseInput);
2013     std::pair<StringRef, StringRef> Split = Name.split('.');
2014     std::string TmpName = GetTemporaryPath(
2015         Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
2016     return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
2017   }
2018
2019   SmallString<128> BasePath(BaseInput);
2020   StringRef BaseName;
2021
2022   // Dsymutil actions should use the full path.
2023   if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
2024     BaseName = BasePath;
2025   else
2026     BaseName = llvm::sys::path::filename(BasePath);
2027
2028   // Determine what the derived output name should be.
2029   const char *NamedOutput;
2030
2031   if (JA.getType() == types::TY_Object &&
2032       C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
2033     // The /Fo or /o flag decides the object filename.
2034     StringRef Val =
2035         C.getArgs()
2036             .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
2037             ->getValue();
2038     NamedOutput =
2039         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
2040   } else if (JA.getType() == types::TY_Image &&
2041              C.getArgs().hasArg(options::OPT__SLASH_Fe,
2042                                 options::OPT__SLASH_o)) {
2043     // The /Fe or /o flag names the linked file.
2044     StringRef Val =
2045         C.getArgs()
2046             .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
2047             ->getValue();
2048     NamedOutput =
2049         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
2050   } else if (JA.getType() == types::TY_Image) {
2051     if (IsCLMode()) {
2052       // clang-cl uses BaseName for the executable name.
2053       NamedOutput =
2054           MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
2055     } else if (MultipleArchs && BoundArch) {
2056       SmallString<128> Output(getDefaultImageName());
2057       Output += "-";
2058       Output.append(BoundArch);
2059       NamedOutput = C.getArgs().MakeArgString(Output.c_str());
2060     } else
2061       NamedOutput = getDefaultImageName();
2062   } else {
2063     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
2064     assert(Suffix && "All types used for output should have a suffix.");
2065
2066     std::string::size_type End = std::string::npos;
2067     if (!types::appendSuffixForType(JA.getType()))
2068       End = BaseName.rfind('.');
2069     SmallString<128> Suffixed(BaseName.substr(0, End));
2070     if (MultipleArchs && BoundArch) {
2071       Suffixed += "-";
2072       Suffixed.append(BoundArch);
2073     }
2074     // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
2075     // the unoptimized bitcode so that it does not get overwritten by the ".bc"
2076     // optimized bitcode output.
2077     if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
2078         JA.getType() == types::TY_LLVM_BC)
2079       Suffixed += ".tmp";
2080     Suffixed += '.';
2081     Suffixed += Suffix;
2082     NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
2083   }
2084
2085   // Prepend object file path if -save-temps=obj
2086   if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
2087       JA.getType() != types::TY_PCH) {
2088     Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2089     SmallString<128> TempPath(FinalOutput->getValue());
2090     llvm::sys::path::remove_filename(TempPath);
2091     StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
2092     llvm::sys::path::append(TempPath, OutputFileName);
2093     NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
2094   }
2095
2096   // If we're saving temps and the temp file conflicts with the input file,
2097   // then avoid overwriting input file.
2098   if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
2099     bool SameFile = false;
2100     SmallString<256> Result;
2101     llvm::sys::fs::current_path(Result);
2102     llvm::sys::path::append(Result, BaseName);
2103     llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
2104     // Must share the same path to conflict.
2105     if (SameFile) {
2106       StringRef Name = llvm::sys::path::filename(BaseInput);
2107       std::pair<StringRef, StringRef> Split = Name.split('.');
2108       std::string TmpName = GetTemporaryPath(
2109           Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
2110       return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
2111     }
2112   }
2113
2114   // As an annoying special case, PCH generation doesn't strip the pathname.
2115   if (JA.getType() == types::TY_PCH) {
2116     llvm::sys::path::remove_filename(BasePath);
2117     if (BasePath.empty())
2118       BasePath = NamedOutput;
2119     else
2120       llvm::sys::path::append(BasePath, NamedOutput);
2121     return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
2122   } else {
2123     return C.addResultFile(NamedOutput, &JA);
2124   }
2125 }
2126
2127 std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
2128   // Respect a limited subset of the '-Bprefix' functionality in GCC by
2129   // attempting to use this prefix when looking for file paths.
2130   for (const std::string &Dir : PrefixDirs) {
2131     if (Dir.empty())
2132       continue;
2133     SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
2134     llvm::sys::path::append(P, Name);
2135     if (llvm::sys::fs::exists(Twine(P)))
2136       return P.str();
2137   }
2138
2139   SmallString<128> P(ResourceDir);
2140   llvm::sys::path::append(P, Name);
2141   if (llvm::sys::fs::exists(Twine(P)))
2142     return P.str();
2143
2144   for (const std::string &Dir : TC.getFilePaths()) {
2145     if (Dir.empty())
2146       continue;
2147     SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
2148     llvm::sys::path::append(P, Name);
2149     if (llvm::sys::fs::exists(Twine(P)))
2150       return P.str();
2151   }
2152
2153   return Name;
2154 }
2155
2156 void Driver::generatePrefixedToolNames(
2157     const char *Tool, const ToolChain &TC,
2158     SmallVectorImpl<std::string> &Names) const {
2159   // FIXME: Needs a better variable than DefaultTargetTriple
2160   Names.emplace_back(DefaultTargetTriple + "-" + Tool);
2161   Names.emplace_back(Tool);
2162
2163   // Allow the discovery of tools prefixed with LLVM's default target triple.
2164   std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
2165   if (LLVMDefaultTargetTriple != DefaultTargetTriple)
2166     Names.emplace_back(LLVMDefaultTargetTriple + "-" + Tool);
2167 }
2168
2169 static bool ScanDirForExecutable(SmallString<128> &Dir,
2170                                  ArrayRef<std::string> Names) {
2171   for (const auto &Name : Names) {
2172     llvm::sys::path::append(Dir, Name);
2173     if (llvm::sys::fs::can_execute(Twine(Dir)))
2174       return true;
2175     llvm::sys::path::remove_filename(Dir);
2176   }
2177   return false;
2178 }
2179
2180 std::string Driver::GetProgramPath(const char *Name,
2181                                    const ToolChain &TC) const {
2182   SmallVector<std::string, 2> TargetSpecificExecutables;
2183   generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
2184
2185   // Respect a limited subset of the '-Bprefix' functionality in GCC by
2186   // attempting to use this prefix when looking for program paths.
2187   for (const auto &PrefixDir : PrefixDirs) {
2188     if (llvm::sys::fs::is_directory(PrefixDir)) {
2189       SmallString<128> P(PrefixDir);
2190       if (ScanDirForExecutable(P, TargetSpecificExecutables))
2191         return P.str();
2192     } else {
2193       SmallString<128> P(PrefixDir + Name);
2194       if (llvm::sys::fs::can_execute(Twine(P)))
2195         return P.str();
2196     }
2197   }
2198
2199   const ToolChain::path_list &List = TC.getProgramPaths();
2200   for (const auto &Path : List) {
2201     SmallString<128> P(Path);
2202     if (ScanDirForExecutable(P, TargetSpecificExecutables))
2203       return P.str();
2204   }
2205
2206   // If all else failed, search the path.
2207   for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
2208     if (llvm::ErrorOr<std::string> P =
2209             llvm::sys::findProgramByName(TargetSpecificExecutable))
2210       return *P;
2211
2212   return Name;
2213 }
2214
2215 std::string Driver::GetTemporaryPath(StringRef Prefix,
2216                                      const char *Suffix) const {
2217   SmallString<128> Path;
2218   std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
2219   if (EC) {
2220     Diag(clang::diag::err_unable_to_make_temp) << EC.message();
2221     return "";
2222   }
2223
2224   return Path.str();
2225 }
2226
2227 const ToolChain &Driver::getToolChain(const ArgList &Args,
2228                                       const llvm::Triple &Target) const {
2229
2230   ToolChain *&TC = ToolChains[Target.str()];
2231   if (!TC) {
2232     switch (Target.getOS()) {
2233     case llvm::Triple::CloudABI:
2234       TC = new toolchains::CloudABI(*this, Target, Args);
2235       break;
2236     case llvm::Triple::Darwin:
2237     case llvm::Triple::MacOSX:
2238     case llvm::Triple::IOS:
2239     case llvm::Triple::TvOS:
2240     case llvm::Triple::WatchOS:
2241       TC = new toolchains::DarwinClang(*this, Target, Args);
2242       break;
2243     case llvm::Triple::DragonFly:
2244       TC = new toolchains::DragonFly(*this, Target, Args);
2245       break;
2246     case llvm::Triple::OpenBSD:
2247       TC = new toolchains::OpenBSD(*this, Target, Args);
2248       break;
2249     case llvm::Triple::Bitrig:
2250       TC = new toolchains::Bitrig(*this, Target, Args);
2251       break;
2252     case llvm::Triple::NetBSD:
2253       TC = new toolchains::NetBSD(*this, Target, Args);
2254       break;
2255     case llvm::Triple::FreeBSD:
2256       TC = new toolchains::FreeBSD(*this, Target, Args);
2257       break;
2258     case llvm::Triple::Minix:
2259       TC = new toolchains::Minix(*this, Target, Args);
2260       break;
2261     case llvm::Triple::Linux:
2262       if (Target.getArch() == llvm::Triple::hexagon)
2263         TC = new toolchains::HexagonToolChain(*this, Target, Args);
2264       else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
2265                !Target.hasEnvironment())
2266         TC = new toolchains::MipsLLVMToolChain(*this, Target, Args);
2267       else
2268         TC = new toolchains::Linux(*this, Target, Args);
2269       break;
2270     case llvm::Triple::NaCl:
2271       TC = new toolchains::NaClToolChain(*this, Target, Args);
2272       break;
2273     case llvm::Triple::Solaris:
2274       TC = new toolchains::Solaris(*this, Target, Args);
2275       break;
2276     case llvm::Triple::AMDHSA:
2277       TC = new toolchains::AMDGPUToolChain(*this, Target, Args);
2278       break;
2279     case llvm::Triple::Win32:
2280       switch (Target.getEnvironment()) {
2281       default:
2282         if (Target.isOSBinFormatELF())
2283           TC = new toolchains::Generic_ELF(*this, Target, Args);
2284         else if (Target.isOSBinFormatMachO())
2285           TC = new toolchains::MachO(*this, Target, Args);
2286         else
2287           TC = new toolchains::Generic_GCC(*this, Target, Args);
2288         break;
2289       case llvm::Triple::GNU:
2290         TC = new toolchains::MinGW(*this, Target, Args);
2291         break;
2292       case llvm::Triple::Itanium:
2293         TC = new toolchains::CrossWindowsToolChain(*this, Target, Args);
2294         break;
2295       case llvm::Triple::MSVC:
2296       case llvm::Triple::UnknownEnvironment:
2297         TC = new toolchains::MSVCToolChain(*this, Target, Args);
2298         break;
2299       }
2300       break;
2301     case llvm::Triple::CUDA:
2302       TC = new toolchains::CudaToolChain(*this, Target, Args);
2303       break;
2304     case llvm::Triple::PS4:
2305       TC = new toolchains::PS4CPU(*this, Target, Args);
2306       break;
2307     default:
2308       // Of these targets, Hexagon is the only one that might have
2309       // an OS of Linux, in which case it got handled above already.
2310       switch (Target.getArch()) {
2311       case llvm::Triple::tce:
2312         TC = new toolchains::TCEToolChain(*this, Target, Args);
2313         break;
2314       case llvm::Triple::hexagon:
2315         TC = new toolchains::HexagonToolChain(*this, Target, Args);
2316         break;
2317       case llvm::Triple::xcore:
2318         TC = new toolchains::XCoreToolChain(*this, Target, Args);
2319         break;
2320       case llvm::Triple::wasm32:
2321       case llvm::Triple::wasm64:
2322         TC = new toolchains::WebAssembly(*this, Target, Args);
2323         break;
2324       default:
2325         if (Target.getVendor() == llvm::Triple::Myriad)
2326           TC = new toolchains::MyriadToolChain(*this, Target, Args);
2327         else if (Target.isOSBinFormatELF())
2328           TC = new toolchains::Generic_ELF(*this, Target, Args);
2329         else if (Target.isOSBinFormatMachO())
2330           TC = new toolchains::MachO(*this, Target, Args);
2331         else
2332           TC = new toolchains::Generic_GCC(*this, Target, Args);
2333       }
2334     }
2335   }
2336   return *TC;
2337 }
2338
2339 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
2340   // Say "no" if there is not exactly one input of a type clang understands.
2341   if (JA.size() != 1 || !types::isAcceptedByClang((*JA.begin())->getType()))
2342     return false;
2343
2344   // And say "no" if this is not a kind of action clang understands.
2345   if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
2346       !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
2347     return false;
2348
2349   return true;
2350 }
2351
2352 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
2353 /// grouped values as integers. Numbers which are not provided are set to 0.
2354 ///
2355 /// \return True if the entire string was parsed (9.2), or all groups were
2356 /// parsed (10.3.5extrastuff).
2357 bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
2358                                unsigned &Minor, unsigned &Micro,
2359                                bool &HadExtra) {
2360   HadExtra = false;
2361
2362   Major = Minor = Micro = 0;
2363   if (*Str == '\0')
2364     return false;
2365
2366   char *End;
2367   Major = (unsigned)strtol(Str, &End, 10);
2368   if (*Str != '\0' && *End == '\0')
2369     return true;
2370   if (*End != '.')
2371     return false;
2372
2373   Str = End + 1;
2374   Minor = (unsigned)strtol(Str, &End, 10);
2375   if (*Str != '\0' && *End == '\0')
2376     return true;
2377   if (*End != '.')
2378     return false;
2379
2380   Str = End + 1;
2381   Micro = (unsigned)strtol(Str, &End, 10);
2382   if (*Str != '\0' && *End == '\0')
2383     return true;
2384   if (Str == End)
2385     return false;
2386   HadExtra = true;
2387   return true;
2388 }
2389
2390 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
2391   unsigned IncludedFlagsBitmask = 0;
2392   unsigned ExcludedFlagsBitmask = options::NoDriverOption;
2393
2394   if (Mode == CLMode) {
2395     // Include CL and Core options.
2396     IncludedFlagsBitmask |= options::CLOption;
2397     IncludedFlagsBitmask |= options::CoreOption;
2398   } else {
2399     ExcludedFlagsBitmask |= options::CLOption;
2400   }
2401
2402   return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
2403 }
2404
2405 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
2406   return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
2407 }