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