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/SmallSet.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSet.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/Option/Arg.h"
31 #include "llvm/Option/ArgList.h"
32 #include "llvm/Option/OptSpecifier.h"
33 #include "llvm/Option/OptTable.h"
34 #include "llvm/Option/Option.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 #include <utility>
45 
46 using namespace clang::driver;
47 using namespace clang;
48 using namespace llvm::opt;
49 
50 Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
51                DiagnosticsEngine &Diags,
52                IntrusiveRefCntPtr<vfs::FileSystem> VFS)
53     : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
54       Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
55       LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
56       SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
57       DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
58       CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
59       CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
60       CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
61       CCCGenericGCCName(""), CheckInputsExist(true), CCCUsePCH(true),
62       SuppressMissingInputWarning(false) {
63 
64   // Provide a sane fallback if no VFS is specified.
65   if (!this->VFS)
66     this->VFS = vfs::getRealFileSystem();
67 
68   Name = llvm::sys::path::filename(ClangExecutable);
69   Dir = llvm::sys::path::parent_path(ClangExecutable);
70   InstalledDir = Dir; // Provide a sensible default installed dir.
71 
72   // Compute the path to the resource directory.
73   StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
74   SmallString<128> P(Dir);
75   if (ClangResourceDir != "") {
76     llvm::sys::path::append(P, ClangResourceDir);
77   } else {
78     StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
79     llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang",
80                             CLANG_VERSION_STRING);
81   }
82   ResourceDir = P.str();
83 }
84 
85 Driver::~Driver() {
86   delete Opts;
87 
88   llvm::DeleteContainerSeconds(ToolChains);
89 }
90 
91 void Driver::ParseDriverMode(StringRef ProgramName,
92                              ArrayRef<const char *> Args) {
93   auto Default = ToolChain::getTargetAndModeFromProgramName(ProgramName);
94   StringRef DefaultMode(Default.second);
95   setDriverModeFromOption(DefaultMode);
96 
97   for (const char *ArgPtr : Args) {
98     // Ingore nullptrs, they are response file's EOL markers
99     if (ArgPtr == nullptr)
100       continue;
101     const StringRef Arg = ArgPtr;
102     setDriverModeFromOption(Arg);
103   }
104 }
105 
106 void Driver::setDriverModeFromOption(StringRef Opt) {
107   const std::string OptName =
108       getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
109   if (!Opt.startswith(OptName))
110     return;
111   StringRef Value = Opt.drop_front(OptName.size());
112 
113   const unsigned M = llvm::StringSwitch<unsigned>(Value)
114                          .Case("gcc", GCCMode)
115                          .Case("g++", GXXMode)
116                          .Case("cpp", CPPMode)
117                          .Case("cl", CLMode)
118                          .Default(~0U);
119 
120   if (M != ~0U)
121     Mode = static_cast<DriverMode>(M);
122   else
123     Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
124 }
125 
126 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
127   llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
128 
129   unsigned IncludedFlagsBitmask;
130   unsigned ExcludedFlagsBitmask;
131   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
132       getIncludeExcludeOptionFlagMasks();
133 
134   unsigned MissingArgIndex, MissingArgCount;
135   InputArgList Args =
136       getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
137                           IncludedFlagsBitmask, ExcludedFlagsBitmask);
138 
139   // Check for missing argument error.
140   if (MissingArgCount)
141     Diag(clang::diag::err_drv_missing_argument)
142         << Args.getArgString(MissingArgIndex) << MissingArgCount;
143 
144   // Check for unsupported options.
145   for (const Arg *A : Args) {
146     if (A->getOption().hasFlag(options::Unsupported)) {
147       Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
148       continue;
149     }
150 
151     // Warn about -mcpu= without an argument.
152     if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
153       Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
154     }
155   }
156 
157   for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
158     Diags.Report(IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl :
159                               diag::err_drv_unknown_argument)
160       << A->getAsString(Args);
161 
162   return Args;
163 }
164 
165 // Determine which compilation mode we are in. We look for options which
166 // affect the phase, starting with the earliest phases, and record which
167 // option we used to determine the final phase.
168 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
169                                  Arg **FinalPhaseArg) const {
170   Arg *PhaseArg = nullptr;
171   phases::ID FinalPhase;
172 
173   // -{E,EP,P,M,MM} only run the preprocessor.
174   if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
175       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
176       (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
177       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
178     FinalPhase = phases::Preprocess;
179 
180     // --precompile only runs up to precompilation.
181   } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
182     FinalPhase = phases::Precompile;
183 
184     // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
185   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
186              (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
187              (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
188              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
189              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
190              (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
191              (PhaseArg = DAL.getLastArg(options::OPT__analyze,
192                                         options::OPT__analyze_auto)) ||
193              (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
194     FinalPhase = phases::Compile;
195 
196     // -S only runs up to the backend.
197   } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
198     FinalPhase = phases::Backend;
199 
200     // -c compilation only runs up to the assembler.
201   } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
202     FinalPhase = phases::Assemble;
203 
204     // Otherwise do everything.
205   } else
206     FinalPhase = phases::Link;
207 
208   if (FinalPhaseArg)
209     *FinalPhaseArg = PhaseArg;
210 
211   return FinalPhase;
212 }
213 
214 static Arg *MakeInputArg(DerivedArgList &Args, OptTable *Opts,
215                          StringRef Value) {
216   Arg *A = new Arg(Opts->getOption(options::OPT_INPUT), Value,
217                    Args.getBaseArgs().MakeIndex(Value), Value.data());
218   Args.AddSynthesizedArg(A);
219   A->claim();
220   return A;
221 }
222 
223 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
224   DerivedArgList *DAL = new DerivedArgList(Args);
225 
226   bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
227   bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
228   for (Arg *A : Args) {
229     // Unfortunately, we have to parse some forwarding options (-Xassembler,
230     // -Xlinker, -Xpreprocessor) because we either integrate their functionality
231     // (assembler and preprocessor), or bypass a previous driver ('collect2').
232 
233     // Rewrite linker options, to replace --no-demangle with a custom internal
234     // option.
235     if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
236          A->getOption().matches(options::OPT_Xlinker)) &&
237         A->containsValue("--no-demangle")) {
238       // Add the rewritten no-demangle argument.
239       DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
240 
241       // Add the remaining values as Xlinker arguments.
242       for (StringRef Val : A->getValues())
243         if (Val != "--no-demangle")
244           DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
245 
246       continue;
247     }
248 
249     // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
250     // some build systems. We don't try to be complete here because we don't
251     // care to encourage this usage model.
252     if (A->getOption().matches(options::OPT_Wp_COMMA) &&
253         (A->getValue(0) == StringRef("-MD") ||
254          A->getValue(0) == StringRef("-MMD"))) {
255       // Rewrite to -MD/-MMD along with -MF.
256       if (A->getValue(0) == StringRef("-MD"))
257         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
258       else
259         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
260       if (A->getNumValues() == 2)
261         DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
262                             A->getValue(1));
263       continue;
264     }
265 
266     // Rewrite reserved library names.
267     if (A->getOption().matches(options::OPT_l)) {
268       StringRef Value = A->getValue();
269 
270       // Rewrite unless -nostdlib is present.
271       if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
272         DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
273         continue;
274       }
275 
276       // Rewrite unconditionally.
277       if (Value == "cc_kext") {
278         DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
279         continue;
280       }
281     }
282 
283     // Pick up inputs via the -- option.
284     if (A->getOption().matches(options::OPT__DASH_DASH)) {
285       A->claim();
286       for (StringRef Val : A->getValues())
287         DAL->append(MakeInputArg(*DAL, Opts, Val));
288       continue;
289     }
290 
291     DAL->append(A);
292   }
293 
294   // Enforce -static if -miamcu is present.
295   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
296     DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
297 
298 // Add a default value of -mlinker-version=, if one was given and the user
299 // didn't specify one.
300 #if defined(HOST_LINK_VERSION)
301   if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
302       strlen(HOST_LINK_VERSION) > 0) {
303     DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
304                       HOST_LINK_VERSION);
305     DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
306   }
307 #endif
308 
309   return DAL;
310 }
311 
312 /// \brief Compute target triple from args.
313 ///
314 /// This routine provides the logic to compute a target triple from various
315 /// args passed to the driver and the default triple string.
316 static llvm::Triple computeTargetTriple(const Driver &D,
317                                         StringRef DefaultTargetTriple,
318                                         const ArgList &Args,
319                                         StringRef DarwinArchName = "") {
320   // FIXME: Already done in Compilation *Driver::BuildCompilation
321   if (const Arg *A = Args.getLastArg(options::OPT_target))
322     DefaultTargetTriple = A->getValue();
323 
324   llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
325 
326   // Handle Apple-specific options available here.
327   if (Target.isOSBinFormatMachO()) {
328     // If an explict Darwin arch name is given, that trumps all.
329     if (!DarwinArchName.empty()) {
330       tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
331       return Target;
332     }
333 
334     // Handle the Darwin '-arch' flag.
335     if (Arg *A = Args.getLastArg(options::OPT_arch)) {
336       StringRef ArchName = A->getValue();
337       tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
338     }
339   }
340 
341   // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
342   // '-mbig-endian'/'-EB'.
343   if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
344                                options::OPT_mbig_endian)) {
345     if (A->getOption().matches(options::OPT_mlittle_endian)) {
346       llvm::Triple LE = Target.getLittleEndianArchVariant();
347       if (LE.getArch() != llvm::Triple::UnknownArch)
348         Target = std::move(LE);
349     } else {
350       llvm::Triple BE = Target.getBigEndianArchVariant();
351       if (BE.getArch() != llvm::Triple::UnknownArch)
352         Target = std::move(BE);
353     }
354   }
355 
356   // Skip further flag support on OSes which don't support '-m32' or '-m64'.
357   if (Target.getArch() == llvm::Triple::tce ||
358       Target.getOS() == llvm::Triple::Minix)
359     return Target;
360 
361   // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
362   Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
363                            options::OPT_m32, options::OPT_m16);
364   if (A) {
365     llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
366 
367     if (A->getOption().matches(options::OPT_m64)) {
368       AT = Target.get64BitArchVariant().getArch();
369       if (Target.getEnvironment() == llvm::Triple::GNUX32)
370         Target.setEnvironment(llvm::Triple::GNU);
371     } else if (A->getOption().matches(options::OPT_mx32) &&
372                Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
373       AT = llvm::Triple::x86_64;
374       Target.setEnvironment(llvm::Triple::GNUX32);
375     } else if (A->getOption().matches(options::OPT_m32)) {
376       AT = Target.get32BitArchVariant().getArch();
377       if (Target.getEnvironment() == llvm::Triple::GNUX32)
378         Target.setEnvironment(llvm::Triple::GNU);
379     } else if (A->getOption().matches(options::OPT_m16) &&
380                Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
381       AT = llvm::Triple::x86;
382       Target.setEnvironment(llvm::Triple::CODE16);
383     }
384 
385     if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
386       Target.setArch(AT);
387   }
388 
389   // Handle -miamcu flag.
390   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
391     if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
392       D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
393                                                        << Target.str();
394 
395     if (A && !A->getOption().matches(options::OPT_m32))
396       D.Diag(diag::err_drv_argument_not_allowed_with)
397           << "-miamcu" << A->getBaseArg().getAsString(Args);
398 
399     Target.setArch(llvm::Triple::x86);
400     Target.setArchName("i586");
401     Target.setEnvironment(llvm::Triple::UnknownEnvironment);
402     Target.setEnvironmentName("");
403     Target.setOS(llvm::Triple::ELFIAMCU);
404     Target.setVendor(llvm::Triple::UnknownVendor);
405     Target.setVendorName("intel");
406   }
407 
408   return Target;
409 }
410 
411 // \brief Parse the LTO options and record the type of LTO compilation
412 // based on which -f(no-)?lto(=.*)? option occurs last.
413 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
414   LTOMode = LTOK_None;
415   if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
416                     options::OPT_fno_lto, false))
417     return;
418 
419   StringRef LTOName("full");
420 
421   const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
422   if (A)
423     LTOName = A->getValue();
424 
425   LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
426                 .Case("full", LTOK_Full)
427                 .Case("thin", LTOK_Thin)
428                 .Default(LTOK_Unknown);
429 
430   if (LTOMode == LTOK_Unknown) {
431     assert(A);
432     Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
433                                                     << A->getValue();
434   }
435 }
436 
437 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
438                                               InputList &Inputs) {
439 
440   //
441   // CUDA
442   //
443   // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
444   if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
445         return types::isCuda(I.first);
446       })) {
447     const ToolChain &TC = getToolChain(
448         C.getInputArgs(),
449         llvm::Triple(C.getSingleOffloadToolChain<Action::OFK_Host>()
450                              ->getTriple()
451                              .isArch64Bit()
452                          ? "nvptx64-nvidia-cuda"
453                          : "nvptx-nvidia-cuda"));
454     C.addOffloadDeviceToolChain(&TC, Action::OFK_Cuda);
455   }
456 
457   //
458   // TODO: Add support for other offloading programming models here.
459   //
460 
461   return;
462 }
463 
464 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
465   llvm::PrettyStackTraceString CrashInfo("Compilation construction");
466 
467   // FIXME: Handle environment options which affect driver behavior, somewhere
468   // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
469 
470   if (Optional<std::string> CompilerPathValue =
471           llvm::sys::Process::GetEnv("COMPILER_PATH")) {
472     StringRef CompilerPath = *CompilerPathValue;
473     while (!CompilerPath.empty()) {
474       std::pair<StringRef, StringRef> Split =
475           CompilerPath.split(llvm::sys::EnvPathSeparator);
476       PrefixDirs.push_back(Split.first);
477       CompilerPath = Split.second;
478     }
479   }
480 
481   // We look for the driver mode option early, because the mode can affect
482   // how other options are parsed.
483   ParseDriverMode(ClangExecutable, ArgList.slice(1));
484 
485   // FIXME: What are we going to do with -V and -b?
486 
487   // FIXME: This stuff needs to go into the Compilation, not the driver.
488   bool CCCPrintPhases;
489 
490   InputArgList Args = ParseArgStrings(ArgList.slice(1));
491 
492   // Silence driver warnings if requested
493   Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
494 
495   // -no-canonical-prefixes is used very early in main.
496   Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
497 
498   // Ignore -pipe.
499   Args.ClaimAllArgs(options::OPT_pipe);
500 
501   // Extract -ccc args.
502   //
503   // FIXME: We need to figure out where this behavior should live. Most of it
504   // should be outside in the client; the parts that aren't should have proper
505   // options, either by introducing new ones or by overloading gcc ones like -V
506   // or -b.
507   CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
508   CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
509   if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
510     CCCGenericGCCName = A->getValue();
511   CCCUsePCH =
512       Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
513   // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
514   // and getToolChain is const.
515   if (IsCLMode()) {
516     // clang-cl targets MSVC-style Win32.
517     llvm::Triple T(DefaultTargetTriple);
518     T.setOS(llvm::Triple::Win32);
519     T.setVendor(llvm::Triple::PC);
520     T.setEnvironment(llvm::Triple::MSVC);
521     DefaultTargetTriple = T.str();
522   }
523   if (const Arg *A = Args.getLastArg(options::OPT_target))
524     DefaultTargetTriple = A->getValue();
525   if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
526     Dir = InstalledDir = A->getValue();
527   for (const Arg *A : Args.filtered(options::OPT_B)) {
528     A->claim();
529     PrefixDirs.push_back(A->getValue(0));
530   }
531   if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
532     SysRoot = A->getValue();
533   if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
534     DyldPrefix = A->getValue();
535   if (Args.hasArg(options::OPT_nostdlib))
536     UseStdLib = false;
537 
538   if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
539     ResourceDir = A->getValue();
540 
541   if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
542     SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
543                     .Case("cwd", SaveTempsCwd)
544                     .Case("obj", SaveTempsObj)
545                     .Default(SaveTempsCwd);
546   }
547 
548   setLTOMode(Args);
549 
550   // Ignore -fembed-bitcode options with LTO
551   // since the output will be bitcode anyway.
552   if (getLTOMode() == LTOK_None) {
553     if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
554       StringRef Name = A->getValue();
555       unsigned Model = llvm::StringSwitch<unsigned>(Name)
556           .Case("off", EmbedNone)
557           .Case("all", EmbedBitcode)
558           .Case("bitcode", EmbedBitcode)
559           .Case("marker", EmbedMarker)
560           .Default(~0U);
561       if (Model == ~0U) {
562         Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
563                                                   << Name;
564       } else
565         BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
566     }
567   } else {
568     // claim the bitcode option under LTO so no warning is issued.
569     Args.ClaimAllArgs(options::OPT_fembed_bitcode_EQ);
570   }
571 
572   std::unique_ptr<llvm::opt::InputArgList> UArgs =
573       llvm::make_unique<InputArgList>(std::move(Args));
574 
575   // Perform the default argument translations.
576   DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
577 
578   // Owned by the host.
579   const ToolChain &TC = getToolChain(
580       *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
581 
582   // The compilation takes ownership of Args.
583   Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
584 
585   if (!HandleImmediateArgs(*C))
586     return C;
587 
588   // Construct the list of inputs.
589   InputList Inputs;
590   BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
591 
592   // Populate the tool chains for the offloading devices, if any.
593   CreateOffloadingDeviceToolChains(*C, Inputs);
594 
595   // Construct the list of abstract actions to perform for this compilation. On
596   // MachO targets this uses the driver-driver and universal actions.
597   if (TC.getTriple().isOSBinFormatMachO())
598     BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
599   else
600     BuildActions(*C, C->getArgs(), Inputs, C->getActions());
601 
602   if (CCCPrintPhases) {
603     PrintActions(*C);
604     return C;
605   }
606 
607   BuildJobs(*C);
608 
609   return C;
610 }
611 
612 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
613   llvm::opt::ArgStringList ASL;
614   for (const auto *A : Args)
615     A->render(Args, ASL);
616 
617   for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
618     if (I != ASL.begin())
619       OS << ' ';
620     Command::printArg(OS, *I, true);
621   }
622   OS << '\n';
623 }
624 
625 // When clang crashes, produce diagnostic information including the fully
626 // preprocessed source file(s).  Request that the developer attach the
627 // diagnostic information to a bug report.
628 void Driver::generateCompilationDiagnostics(Compilation &C,
629                                             const Command &FailingCommand) {
630   if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
631     return;
632 
633   // Don't try to generate diagnostics for link or dsymutil jobs.
634   if (FailingCommand.getCreator().isLinkJob() ||
635       FailingCommand.getCreator().isDsymutilJob())
636     return;
637 
638   // Print the version of the compiler.
639   PrintVersion(C, llvm::errs());
640 
641   Diag(clang::diag::note_drv_command_failed_diag_msg)
642       << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
643          "crash backtrace, preprocessed source, and associated run script.";
644 
645   // Suppress driver output and emit preprocessor output to temp file.
646   Mode = CPPMode;
647   CCGenDiagnostics = true;
648 
649   // Save the original job command(s).
650   Command Cmd = FailingCommand;
651 
652   // Keep track of whether we produce any errors while trying to produce
653   // preprocessed sources.
654   DiagnosticErrorTrap Trap(Diags);
655 
656   // Suppress tool output.
657   C.initCompilationForDiagnostics();
658 
659   // Construct the list of inputs.
660   InputList Inputs;
661   BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
662 
663   for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
664     bool IgnoreInput = false;
665 
666     // Ignore input from stdin or any inputs that cannot be preprocessed.
667     // Check type first as not all linker inputs have a value.
668     if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
669       IgnoreInput = true;
670     } else if (!strcmp(it->second->getValue(), "-")) {
671       Diag(clang::diag::note_drv_command_failed_diag_msg)
672           << "Error generating preprocessed source(s) - "
673              "ignoring input from stdin.";
674       IgnoreInput = true;
675     }
676 
677     if (IgnoreInput) {
678       it = Inputs.erase(it);
679       ie = Inputs.end();
680     } else {
681       ++it;
682     }
683   }
684 
685   if (Inputs.empty()) {
686     Diag(clang::diag::note_drv_command_failed_diag_msg)
687         << "Error generating preprocessed source(s) - "
688            "no preprocessable inputs.";
689     return;
690   }
691 
692   // Don't attempt to generate preprocessed files if multiple -arch options are
693   // used, unless they're all duplicates.
694   llvm::StringSet<> ArchNames;
695   for (const Arg *A : C.getArgs()) {
696     if (A->getOption().matches(options::OPT_arch)) {
697       StringRef ArchName = A->getValue();
698       ArchNames.insert(ArchName);
699     }
700   }
701   if (ArchNames.size() > 1) {
702     Diag(clang::diag::note_drv_command_failed_diag_msg)
703         << "Error generating preprocessed source(s) - cannot generate "
704            "preprocessed source with multiple -arch options.";
705     return;
706   }
707 
708   // Construct the list of abstract actions to perform for this compilation. On
709   // Darwin OSes this uses the driver-driver and builds universal actions.
710   const ToolChain &TC = C.getDefaultToolChain();
711   if (TC.getTriple().isOSBinFormatMachO())
712     BuildUniversalActions(C, TC, Inputs);
713   else
714     BuildActions(C, C.getArgs(), Inputs, C.getActions());
715 
716   BuildJobs(C);
717 
718   // If there were errors building the compilation, quit now.
719   if (Trap.hasErrorOccurred()) {
720     Diag(clang::diag::note_drv_command_failed_diag_msg)
721         << "Error generating preprocessed source(s).";
722     return;
723   }
724 
725   // Generate preprocessed output.
726   SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
727   C.ExecuteJobs(C.getJobs(), FailingCommands);
728 
729   // If any of the preprocessing commands failed, clean up and exit.
730   if (!FailingCommands.empty()) {
731     if (!isSaveTempsEnabled())
732       C.CleanupFileList(C.getTempFiles(), true);
733 
734     Diag(clang::diag::note_drv_command_failed_diag_msg)
735         << "Error generating preprocessed source(s).";
736     return;
737   }
738 
739   const ArgStringList &TempFiles = C.getTempFiles();
740   if (TempFiles.empty()) {
741     Diag(clang::diag::note_drv_command_failed_diag_msg)
742         << "Error generating preprocessed source(s).";
743     return;
744   }
745 
746   Diag(clang::diag::note_drv_command_failed_diag_msg)
747       << "\n********************\n\n"
748          "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
749          "Preprocessed source(s) and associated run script(s) are located at:";
750 
751   SmallString<128> VFS;
752   for (const char *TempFile : TempFiles) {
753     Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
754     if (StringRef(TempFile).endswith(".cache")) {
755       // In some cases (modules) we'll dump extra data to help with reproducing
756       // the crash into a directory next to the output.
757       VFS = llvm::sys::path::filename(TempFile);
758       llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
759     }
760   }
761 
762   // Assume associated files are based off of the first temporary file.
763   CrashReportInfo CrashInfo(TempFiles[0], VFS);
764 
765   std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
766   std::error_code EC;
767   llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
768   if (EC) {
769     Diag(clang::diag::note_drv_command_failed_diag_msg)
770         << "Error generating run script: " + Script + " " + EC.message();
771   } else {
772     ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
773              << "# Driver args: ";
774     printArgList(ScriptOS, C.getInputArgs());
775     ScriptOS << "# Original command: ";
776     Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
777     Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
778     Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
779   }
780 
781   for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
782                                             options::OPT_frewrite_map_file_EQ))
783     Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
784 
785   Diag(clang::diag::note_drv_command_failed_diag_msg)
786       << "\n\n********************";
787 }
788 
789 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
790   // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
791   // if the tool does not support response files, there is a chance/ that things
792   // will just work without a response file, so we silently just skip it.
793   if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
794       llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
795     return;
796 
797   std::string TmpName = GetTemporaryPath("response", "txt");
798   Cmd.setResponseFile(
799       C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())));
800 }
801 
802 int Driver::ExecuteCompilation(
803     Compilation &C,
804     SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
805   // Just print if -### was present.
806   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
807     C.getJobs().Print(llvm::errs(), "\n", true);
808     return 0;
809   }
810 
811   // If there were errors building the compilation, quit now.
812   if (Diags.hasErrorOccurred())
813     return 1;
814 
815   // Set up response file names for each command, if necessary
816   for (auto &Job : C.getJobs())
817     setUpResponseFiles(C, Job);
818 
819   C.ExecuteJobs(C.getJobs(), FailingCommands);
820 
821   // Remove temp files.
822   C.CleanupFileList(C.getTempFiles());
823 
824   // If the command succeeded, we are done.
825   if (FailingCommands.empty())
826     return 0;
827 
828   // Otherwise, remove result files and print extra information about abnormal
829   // failures.
830   for (const auto &CmdPair : FailingCommands) {
831     int Res = CmdPair.first;
832     const Command *FailingCommand = CmdPair.second;
833 
834     // Remove result files if we're not saving temps.
835     if (!isSaveTempsEnabled()) {
836       const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
837       C.CleanupFileMap(C.getResultFiles(), JA, true);
838 
839       // Failure result files are valid unless we crashed.
840       if (Res < 0)
841         C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
842     }
843 
844     // Print extra information about abnormal failures, if possible.
845     //
846     // This is ad-hoc, but we don't want to be excessively noisy. If the result
847     // status was 1, assume the command failed normally. In particular, if it
848     // was the compiler then assume it gave a reasonable error code. Failures
849     // in other tools are less common, and they generally have worse
850     // diagnostics, so always print the diagnostic there.
851     const Tool &FailingTool = FailingCommand->getCreator();
852 
853     if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
854       // FIXME: See FIXME above regarding result code interpretation.
855       if (Res < 0)
856         Diag(clang::diag::err_drv_command_signalled)
857             << FailingTool.getShortName();
858       else
859         Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
860                                                   << Res;
861     }
862   }
863   return 0;
864 }
865 
866 void Driver::PrintHelp(bool ShowHidden) const {
867   unsigned IncludedFlagsBitmask;
868   unsigned ExcludedFlagsBitmask;
869   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
870       getIncludeExcludeOptionFlagMasks();
871 
872   ExcludedFlagsBitmask |= options::NoDriverOption;
873   if (!ShowHidden)
874     ExcludedFlagsBitmask |= HelpHidden;
875 
876   getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
877                       IncludedFlagsBitmask, ExcludedFlagsBitmask);
878 }
879 
880 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
881   // FIXME: The following handlers should use a callback mechanism, we don't
882   // know what the client would like to do.
883   OS << getClangFullVersion() << '\n';
884   const ToolChain &TC = C.getDefaultToolChain();
885   OS << "Target: " << TC.getTripleString() << '\n';
886 
887   // Print the threading model.
888   if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
889     // Don't print if the ToolChain would have barfed on it already
890     if (TC.isThreadModelSupported(A->getValue()))
891       OS << "Thread model: " << A->getValue();
892   } else
893     OS << "Thread model: " << TC.getThreadModel();
894   OS << '\n';
895 
896   // Print out the install directory.
897   OS << "InstalledDir: " << InstalledDir << '\n';
898 }
899 
900 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
901 /// option.
902 static void PrintDiagnosticCategories(raw_ostream &OS) {
903   // Skip the empty category.
904   for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
905        ++i)
906     OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
907 }
908 
909 bool Driver::HandleImmediateArgs(const Compilation &C) {
910   // The order these options are handled in gcc is all over the place, but we
911   // don't expect inconsistencies w.r.t. that to matter in practice.
912 
913   if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
914     llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
915     return false;
916   }
917 
918   if (C.getArgs().hasArg(options::OPT_dumpversion)) {
919     // Since -dumpversion is only implemented for pedantic GCC compatibility, we
920     // return an answer which matches our definition of __VERSION__.
921     //
922     // If we want to return a more correct answer some day, then we should
923     // introduce a non-pedantically GCC compatible mode to Clang in which we
924     // provide sensible definitions for -dumpversion, __VERSION__, etc.
925     llvm::outs() << "4.2.1\n";
926     return false;
927   }
928 
929   if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
930     PrintDiagnosticCategories(llvm::outs());
931     return false;
932   }
933 
934   if (C.getArgs().hasArg(options::OPT_help) ||
935       C.getArgs().hasArg(options::OPT__help_hidden)) {
936     PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
937     return false;
938   }
939 
940   if (C.getArgs().hasArg(options::OPT__version)) {
941     // Follow gcc behavior and use stdout for --version and stderr for -v.
942     PrintVersion(C, llvm::outs());
943     return false;
944   }
945 
946   if (C.getArgs().hasArg(options::OPT_v) ||
947       C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
948     PrintVersion(C, llvm::errs());
949     SuppressMissingInputWarning = true;
950   }
951 
952   const ToolChain &TC = C.getDefaultToolChain();
953 
954   if (C.getArgs().hasArg(options::OPT_v))
955     TC.printVerboseInfo(llvm::errs());
956 
957   if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
958     llvm::outs() << "programs: =";
959     bool separator = false;
960     for (const std::string &Path : TC.getProgramPaths()) {
961       if (separator)
962         llvm::outs() << ':';
963       llvm::outs() << Path;
964       separator = true;
965     }
966     llvm::outs() << "\n";
967     llvm::outs() << "libraries: =" << ResourceDir;
968 
969     StringRef sysroot = C.getSysRoot();
970 
971     for (const std::string &Path : TC.getFilePaths()) {
972       // Always print a separator. ResourceDir was the first item shown.
973       llvm::outs() << ':';
974       // Interpretation of leading '=' is needed only for NetBSD.
975       if (Path[0] == '=')
976         llvm::outs() << sysroot << Path.substr(1);
977       else
978         llvm::outs() << Path;
979     }
980     llvm::outs() << "\n";
981     return false;
982   }
983 
984   // FIXME: The following handlers should use a callback mechanism, we don't
985   // know what the client would like to do.
986   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
987     llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
988     return false;
989   }
990 
991   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
992     llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
993     return false;
994   }
995 
996   if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
997     ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
998     switch (RLT) {
999     case ToolChain::RLT_CompilerRT:
1000       llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1001       break;
1002     case ToolChain::RLT_Libgcc:
1003       llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1004       break;
1005     }
1006     return false;
1007   }
1008 
1009   if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
1010     for (const Multilib &Multilib : TC.getMultilibs())
1011       llvm::outs() << Multilib << "\n";
1012     return false;
1013   }
1014 
1015   if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
1016     for (const Multilib &Multilib : TC.getMultilibs()) {
1017       if (Multilib.gccSuffix().empty())
1018         llvm::outs() << ".\n";
1019       else {
1020         StringRef Suffix(Multilib.gccSuffix());
1021         assert(Suffix.front() == '/');
1022         llvm::outs() << Suffix.substr(1) << "\n";
1023       }
1024     }
1025     return false;
1026   }
1027   return true;
1028 }
1029 
1030 // Display an action graph human-readably.  Action A is the "sink" node
1031 // and latest-occuring action. Traversal is in pre-order, visiting the
1032 // inputs to each action before printing the action itself.
1033 static unsigned PrintActions1(const Compilation &C, Action *A,
1034                               std::map<Action *, unsigned> &Ids) {
1035   if (Ids.count(A)) // A was already visited.
1036     return Ids[A];
1037 
1038   std::string str;
1039   llvm::raw_string_ostream os(str);
1040 
1041   os << Action::getClassName(A->getKind()) << ", ";
1042   if (InputAction *IA = dyn_cast<InputAction>(A)) {
1043     os << "\"" << IA->getInputArg().getValue() << "\"";
1044   } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1045     os << '"' << BIA->getArchName() << '"' << ", {"
1046        << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
1047   } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1048     bool IsFirst = true;
1049     OA->doOnEachDependence(
1050         [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1051           // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1052           // sm_35 this will generate:
1053           // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1054           // (nvptx64-nvidia-cuda:sm_35) {#ID}
1055           if (!IsFirst)
1056             os << ", ";
1057           os << '"';
1058           if (TC)
1059             os << A->getOffloadingKindPrefix();
1060           else
1061             os << "host";
1062           os << " (";
1063           os << TC->getTriple().normalize();
1064 
1065           if (BoundArch)
1066             os << ":" << BoundArch;
1067           os << ")";
1068           os << '"';
1069           os << " {" << PrintActions1(C, A, Ids) << "}";
1070           IsFirst = false;
1071         });
1072   } else {
1073     const ActionList *AL = &A->getInputs();
1074 
1075     if (AL->size()) {
1076       const char *Prefix = "{";
1077       for (Action *PreRequisite : *AL) {
1078         os << Prefix << PrintActions1(C, PreRequisite, Ids);
1079         Prefix = ", ";
1080       }
1081       os << "}";
1082     } else
1083       os << "{}";
1084   }
1085 
1086   // Append offload info for all options other than the offloading action
1087   // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1088   std::string offload_str;
1089   llvm::raw_string_ostream offload_os(offload_str);
1090   if (!isa<OffloadAction>(A)) {
1091     auto S = A->getOffloadingKindPrefix();
1092     if (!S.empty()) {
1093       offload_os << ", (" << S;
1094       if (A->getOffloadingArch())
1095         offload_os << ", " << A->getOffloadingArch();
1096       offload_os << ")";
1097     }
1098   }
1099 
1100   unsigned Id = Ids.size();
1101   Ids[A] = Id;
1102   llvm::errs() << Id << ": " << os.str() << ", "
1103                << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1104 
1105   return Id;
1106 }
1107 
1108 // Print the action graphs in a compilation C.
1109 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
1110 void Driver::PrintActions(const Compilation &C) const {
1111   std::map<Action *, unsigned> Ids;
1112   for (Action *A : C.getActions())
1113     PrintActions1(C, A, Ids);
1114 }
1115 
1116 /// \brief Check whether the given input tree contains any compilation or
1117 /// assembly actions.
1118 static bool ContainsCompileOrAssembleAction(const Action *A) {
1119   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1120       isa<AssembleJobAction>(A))
1121     return true;
1122 
1123   for (const Action *Input : A->inputs())
1124     if (ContainsCompileOrAssembleAction(Input))
1125       return true;
1126 
1127   return false;
1128 }
1129 
1130 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1131                                    const InputList &BAInputs) const {
1132   DerivedArgList &Args = C.getArgs();
1133   ActionList &Actions = C.getActions();
1134   llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1135   // Collect the list of architectures. Duplicates are allowed, but should only
1136   // be handled once (in the order seen).
1137   llvm::StringSet<> ArchNames;
1138   SmallVector<const char *, 4> Archs;
1139   for (Arg *A : Args) {
1140     if (A->getOption().matches(options::OPT_arch)) {
1141       // Validate the option here; we don't save the type here because its
1142       // particular spelling may participate in other driver choices.
1143       llvm::Triple::ArchType Arch =
1144           tools::darwin::getArchTypeForMachOArchName(A->getValue());
1145       if (Arch == llvm::Triple::UnknownArch) {
1146         Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1147         continue;
1148       }
1149 
1150       A->claim();
1151       if (ArchNames.insert(A->getValue()).second)
1152         Archs.push_back(A->getValue());
1153     }
1154   }
1155 
1156   // When there is no explicit arch for this platform, make sure we still bind
1157   // the architecture (to the default) so that -Xarch_ is handled correctly.
1158   if (!Archs.size())
1159     Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1160 
1161   ActionList SingleActions;
1162   BuildActions(C, Args, BAInputs, SingleActions);
1163 
1164   // Add in arch bindings for every top level action, as well as lipo and
1165   // dsymutil steps if needed.
1166   for (Action* Act : SingleActions) {
1167     // Make sure we can lipo this kind of output. If not (and it is an actual
1168     // output) then we disallow, since we can't create an output file with the
1169     // right name without overwriting it. We could remove this oddity by just
1170     // changing the output names to include the arch, which would also fix
1171     // -save-temps. Compatibility wins for now.
1172 
1173     if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1174       Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1175           << types::getTypeName(Act->getType());
1176 
1177     ActionList Inputs;
1178     for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1179       Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
1180 
1181     // Lipo if necessary, we do it this way because we need to set the arch flag
1182     // so that -Xarch_ gets overwritten.
1183     if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1184       Actions.append(Inputs.begin(), Inputs.end());
1185     else
1186       Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
1187 
1188     // Handle debug info queries.
1189     Arg *A = Args.getLastArg(options::OPT_g_Group);
1190     if (A && !A->getOption().matches(options::OPT_g0) &&
1191         !A->getOption().matches(options::OPT_gstabs) &&
1192         ContainsCompileOrAssembleAction(Actions.back())) {
1193 
1194       // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1195       // have a compile input. We need to run 'dsymutil' ourselves in such cases
1196       // because the debug info will refer to a temporary object file which
1197       // will be removed at the end of the compilation process.
1198       if (Act->getType() == types::TY_Image) {
1199         ActionList Inputs;
1200         Inputs.push_back(Actions.back());
1201         Actions.pop_back();
1202         Actions.push_back(
1203             C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
1204       }
1205 
1206       // Verify the debug info output.
1207       if (Args.hasArg(options::OPT_verify_debug_info)) {
1208         Action* LastAction = Actions.back();
1209         Actions.pop_back();
1210         Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1211             LastAction, types::TY_Nothing));
1212       }
1213     }
1214   }
1215 }
1216 
1217 /// \brief Check that the file referenced by Value exists. If it doesn't,
1218 /// issue a diagnostic and return false.
1219 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
1220                                    StringRef Value, types::ID Ty) {
1221   if (!D.getCheckInputsExist())
1222     return true;
1223 
1224   // stdin always exists.
1225   if (Value == "-")
1226     return true;
1227 
1228   SmallString<64> Path(Value);
1229   if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1230     if (!llvm::sys::path::is_absolute(Path)) {
1231       SmallString<64> Directory(WorkDir->getValue());
1232       llvm::sys::path::append(Directory, Value);
1233       Path.assign(Directory);
1234     }
1235   }
1236 
1237   if (llvm::sys::fs::exists(Twine(Path)))
1238     return true;
1239 
1240   if (D.IsCLMode()) {
1241     if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1242         llvm::sys::Process::FindInEnvPath("LIB", Value))
1243       return true;
1244 
1245     if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1246       // Arguments to the /link flag might cause the linker to search for object
1247       // and library files in paths we don't know about. Don't error in such
1248       // cases.
1249       return true;
1250     }
1251   }
1252 
1253   D.Diag(clang::diag::err_drv_no_such_file) << Path;
1254   return false;
1255 }
1256 
1257 // Construct a the list of inputs and their types.
1258 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
1259                          InputList &Inputs) const {
1260   // Track the current user specified (-x) input. We also explicitly track the
1261   // argument used to set the type; we only want to claim the type when we
1262   // actually use it, so we warn about unused -x arguments.
1263   types::ID InputType = types::TY_Nothing;
1264   Arg *InputTypeArg = nullptr;
1265 
1266   // The last /TC or /TP option sets the input type to C or C++ globally.
1267   if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1268                                          options::OPT__SLASH_TP)) {
1269     InputTypeArg = TCTP;
1270     InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
1271                     ? types::TY_C
1272                     : types::TY_CXX;
1273 
1274     arg_iterator it =
1275         Args.filtered_begin(options::OPT__SLASH_TC, options::OPT__SLASH_TP);
1276     const arg_iterator ie = Args.filtered_end();
1277     Arg *Previous = *it++;
1278     bool ShowNote = false;
1279     while (it != ie) {
1280       Diag(clang::diag::warn_drv_overriding_flag_option)
1281           << Previous->getSpelling() << (*it)->getSpelling();
1282       Previous = *it++;
1283       ShowNote = true;
1284     }
1285     if (ShowNote)
1286       Diag(clang::diag::note_drv_t_option_is_global);
1287 
1288     // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1289     assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1290   }
1291 
1292   for (Arg *A : Args) {
1293     if (A->getOption().getKind() == Option::InputClass) {
1294       const char *Value = A->getValue();
1295       types::ID Ty = types::TY_INVALID;
1296 
1297       // Infer the input type if necessary.
1298       if (InputType == types::TY_Nothing) {
1299         // If there was an explicit arg for this, claim it.
1300         if (InputTypeArg)
1301           InputTypeArg->claim();
1302 
1303         // stdin must be handled specially.
1304         if (memcmp(Value, "-", 2) == 0) {
1305           // If running with -E, treat as a C input (this changes the builtin
1306           // macros, for example). This may be overridden by -ObjC below.
1307           //
1308           // Otherwise emit an error but still use a valid type to avoid
1309           // spurious errors (e.g., no inputs).
1310           if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
1311             Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1312                             : clang::diag::err_drv_unknown_stdin_type);
1313           Ty = types::TY_C;
1314         } else {
1315           // Otherwise lookup by extension.
1316           // Fallback is C if invoked as C preprocessor or Object otherwise.
1317           // We use a host hook here because Darwin at least has its own
1318           // idea of what .s is.
1319           if (const char *Ext = strrchr(Value, '.'))
1320             Ty = TC.LookupTypeForExtension(Ext + 1);
1321 
1322           if (Ty == types::TY_INVALID) {
1323             if (CCCIsCPP())
1324               Ty = types::TY_C;
1325             else
1326               Ty = types::TY_Object;
1327           }
1328 
1329           // If the driver is invoked as C++ compiler (like clang++ or c++) it
1330           // should autodetect some input files as C++ for g++ compatibility.
1331           if (CCCIsCXX()) {
1332             types::ID OldTy = Ty;
1333             Ty = types::lookupCXXTypeForCType(Ty);
1334 
1335             if (Ty != OldTy)
1336               Diag(clang::diag::warn_drv_treating_input_as_cxx)
1337                   << getTypeName(OldTy) << getTypeName(Ty);
1338           }
1339         }
1340 
1341         // -ObjC and -ObjC++ override the default language, but only for "source
1342         // files". We just treat everything that isn't a linker input as a
1343         // source file.
1344         //
1345         // FIXME: Clean this up if we move the phase sequence into the type.
1346         if (Ty != types::TY_Object) {
1347           if (Args.hasArg(options::OPT_ObjC))
1348             Ty = types::TY_ObjC;
1349           else if (Args.hasArg(options::OPT_ObjCXX))
1350             Ty = types::TY_ObjCXX;
1351         }
1352       } else {
1353         assert(InputTypeArg && "InputType set w/o InputTypeArg");
1354         if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1355           // If emulating cl.exe, make sure that /TC and /TP don't affect input
1356           // object files.
1357           const char *Ext = strrchr(Value, '.');
1358           if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1359             Ty = types::TY_Object;
1360         }
1361         if (Ty == types::TY_INVALID) {
1362           Ty = InputType;
1363           InputTypeArg->claim();
1364         }
1365       }
1366 
1367       if (DiagnoseInputExistence(*this, Args, Value, Ty))
1368         Inputs.push_back(std::make_pair(Ty, A));
1369 
1370     } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1371       StringRef Value = A->getValue();
1372       if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
1373         Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1374         Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1375       }
1376       A->claim();
1377     } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1378       StringRef Value = A->getValue();
1379       if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
1380         Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1381         Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1382       }
1383       A->claim();
1384     } else if (A->getOption().hasFlag(options::LinkerInput)) {
1385       // Just treat as object type, we could make a special type for this if
1386       // necessary.
1387       Inputs.push_back(std::make_pair(types::TY_Object, A));
1388 
1389     } else if (A->getOption().matches(options::OPT_x)) {
1390       InputTypeArg = A;
1391       InputType = types::lookupTypeForTypeSpecifier(A->getValue());
1392       A->claim();
1393 
1394       // Follow gcc behavior and treat as linker input for invalid -x
1395       // options. Its not clear why we shouldn't just revert to unknown; but
1396       // this isn't very important, we might as well be bug compatible.
1397       if (!InputType) {
1398         Diag(clang::diag::err_drv_unknown_language) << A->getValue();
1399         InputType = types::TY_Object;
1400       }
1401     }
1402   }
1403   if (CCCIsCPP() && Inputs.empty()) {
1404     // If called as standalone preprocessor, stdin is processed
1405     // if no other input is present.
1406     Arg *A = MakeInputArg(Args, Opts, "-");
1407     Inputs.push_back(std::make_pair(types::TY_C, A));
1408   }
1409 }
1410 
1411 namespace {
1412 /// Provides a convenient interface for different programming models to generate
1413 /// the required device actions.
1414 class OffloadingActionBuilder final {
1415   /// Flag used to trace errors in the builder.
1416   bool IsValid = false;
1417 
1418   /// The compilation that is using this builder.
1419   Compilation &C;
1420 
1421   /// The derived arguments associated with this builder.
1422   DerivedArgList &Args;
1423 
1424   /// Map between an input argument and the offload kinds used to process it.
1425   std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
1426 
1427   /// Builder interface. It doesn't build anything or keep any state.
1428   class DeviceActionBuilder {
1429   public:
1430     typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
1431 
1432     enum ActionBuilderReturnCode {
1433       // The builder acted successfully on the current action.
1434       ABRT_Success,
1435       // The builder didn't have to act on the current action.
1436       ABRT_Inactive,
1437       // The builder was successful and requested the host action to not be
1438       // generated.
1439       ABRT_Ignore_Host,
1440     };
1441 
1442   protected:
1443     /// Compilation associated with this builder.
1444     Compilation &C;
1445 
1446     /// Tool chains associated with this builder. The same programming
1447     /// model may have associated one or more tool chains.
1448     SmallVector<const ToolChain *, 2> ToolChains;
1449 
1450     /// The derived arguments associated with this builder.
1451     DerivedArgList &Args;
1452 
1453     /// The inputs associated with this builder.
1454     const Driver::InputList &Inputs;
1455 
1456     /// The associated offload kind.
1457     Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
1458 
1459   public:
1460     DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
1461                         const Driver::InputList &Inputs,
1462                         Action::OffloadKind AssociatedOffloadKind)
1463         : C(C), Args(Args), Inputs(Inputs),
1464           AssociatedOffloadKind(AssociatedOffloadKind) {}
1465     virtual ~DeviceActionBuilder() {}
1466 
1467     /// Fill up the array \a DA with all the device dependences that should be
1468     /// added to the provided host action \a HostAction. By default it is
1469     /// inactive.
1470     virtual ActionBuilderReturnCode
1471     getDeviceDepences(OffloadAction::DeviceDependences &DA, phases::ID CurPhase,
1472                       phases::ID FinalPhase, PhasesTy &Phases) {
1473       return ABRT_Inactive;
1474     }
1475 
1476     /// Update the state to include the provided host action \a HostAction as a
1477     /// dependency of the current device action. By default it is inactive.
1478     virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
1479       return ABRT_Inactive;
1480     }
1481 
1482     /// Append top level actions generated by the builder. Return true if errors
1483     /// were found.
1484     virtual void appendTopLevelActions(ActionList &AL) {}
1485 
1486     /// Append linker actions generated by the builder. Return true if errors
1487     /// were found.
1488     virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
1489 
1490     /// Initialize the builder. Return true if any initialization errors are
1491     /// found.
1492     virtual bool initialize() { return false; }
1493 
1494     /// Return true if this builder is valid. We have a valid builder if we have
1495     /// associated device tool chains.
1496     bool isValid() { return !ToolChains.empty(); }
1497 
1498     /// Return the associated offload kind.
1499     Action::OffloadKind getAssociatedOffloadKind() {
1500       return AssociatedOffloadKind;
1501     }
1502   };
1503 
1504   /// \brief CUDA action builder. It injects device code in the host backend
1505   /// action.
1506   class CudaActionBuilder final : public DeviceActionBuilder {
1507     /// Flags to signal if the user requested host-only or device-only
1508     /// compilation.
1509     bool CompileHostOnly = false;
1510     bool CompileDeviceOnly = false;
1511 
1512     /// List of GPU architectures to use in this compilation.
1513     SmallVector<CudaArch, 4> GpuArchList;
1514 
1515     /// The CUDA actions for the current input.
1516     ActionList CudaDeviceActions;
1517 
1518     /// The CUDA fat binary if it was generated for the current input.
1519     Action *CudaFatBinary = nullptr;
1520 
1521     /// Flag that is set to true if this builder acted on the current input.
1522     bool IsActive = false;
1523 
1524   public:
1525     CudaActionBuilder(Compilation &C, DerivedArgList &Args,
1526                       const Driver::InputList &Inputs)
1527         : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {}
1528 
1529     ActionBuilderReturnCode
1530     getDeviceDepences(OffloadAction::DeviceDependences &DA, phases::ID CurPhase,
1531                       phases::ID FinalPhase, PhasesTy &Phases) override {
1532       if (!IsActive)
1533         return ABRT_Inactive;
1534 
1535       // If we don't have more CUDA actions, we don't have any dependences to
1536       // create for the host.
1537       if (CudaDeviceActions.empty())
1538         return ABRT_Success;
1539 
1540       assert(CudaDeviceActions.size() == GpuArchList.size() &&
1541              "Expecting one action per GPU architecture.");
1542       assert(!CompileHostOnly &&
1543              "Not expecting CUDA actions in host-only compilation.");
1544 
1545       // If we are generating code for the device or we are in a backend phase,
1546       // we attempt to generate the fat binary. We compile each arch to ptx and
1547       // assemble to cubin, then feed the cubin *and* the ptx into a device
1548       // "link" action, which uses fatbinary to combine these cubins into one
1549       // fatbin.  The fatbin is then an input to the host action if not in
1550       // device-only mode.
1551       if (CompileDeviceOnly || CurPhase == phases::Backend) {
1552         ActionList DeviceActions;
1553         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1554           // Produce the device action from the current phase up to the assemble
1555           // phase.
1556           for (auto Ph : Phases) {
1557             // Skip the phases that were already dealt with.
1558             if (Ph < CurPhase)
1559               continue;
1560             // We have to be consistent with the host final phase.
1561             if (Ph > FinalPhase)
1562               break;
1563 
1564             CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
1565                 C, Args, Ph, CudaDeviceActions[I]);
1566 
1567             if (Ph == phases::Assemble)
1568               break;
1569           }
1570 
1571           // If we didn't reach the assemble phase, we can't generate the fat
1572           // binary. We don't need to generate the fat binary if we are not in
1573           // device-only mode.
1574           if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
1575               CompileDeviceOnly)
1576             continue;
1577 
1578           Action *AssembleAction = CudaDeviceActions[I];
1579           assert(AssembleAction->getType() == types::TY_Object);
1580           assert(AssembleAction->getInputs().size() == 1);
1581 
1582           Action *BackendAction = AssembleAction->getInputs()[0];
1583           assert(BackendAction->getType() == types::TY_PP_Asm);
1584 
1585           for (auto &A : {AssembleAction, BackendAction}) {
1586             OffloadAction::DeviceDependences DDep;
1587             DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
1588                      Action::OFK_Cuda);
1589             DeviceActions.push_back(
1590                 C.MakeAction<OffloadAction>(DDep, A->getType()));
1591           }
1592         }
1593 
1594         // We generate the fat binary if we have device input actions.
1595         if (!DeviceActions.empty()) {
1596           CudaFatBinary =
1597               C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
1598 
1599           if (!CompileDeviceOnly) {
1600             DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
1601                    Action::OFK_Cuda);
1602             // Clear the fat binary, it is already a dependence to an host
1603             // action.
1604             CudaFatBinary = nullptr;
1605           }
1606 
1607           // Remove the CUDA actions as they are already connected to an host
1608           // action or fat binary.
1609           CudaDeviceActions.clear();
1610         }
1611 
1612         // We avoid creating host action in device-only mode.
1613         return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
1614       }
1615 
1616       assert(CurPhase < phases::Backend && "Generating single CUDA "
1617                                            "instructions should only occur "
1618                                            "before the backend phase!");
1619 
1620       // By default, we produce an action for each device arch.
1621       for (Action *&A : CudaDeviceActions)
1622         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
1623 
1624       return ABRT_Success;
1625     }
1626 
1627     ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
1628       // While generating code for CUDA, we only depend on the host input action
1629       // to trigger the creation of all the CUDA device actions.
1630 
1631       // If we are dealing with an input action, replicate it for each GPU
1632       // architecture. If we are in host-only mode we return 'success' so that
1633       // the host uses the CUDA offload kind.
1634       if (auto *IA = dyn_cast<InputAction>(HostAction)) {
1635         assert(!GpuArchList.empty() &&
1636                "We should have at least one GPU architecture.");
1637 
1638         // If the host input is not CUDA, we don't need to bother about this
1639         // input.
1640         if (IA->getType() != types::TY_CUDA) {
1641           // The builder will ignore this input.
1642           IsActive = false;
1643           return ABRT_Inactive;
1644         }
1645 
1646         // Set the flag to true, so that the builder acts on the current input.
1647         IsActive = true;
1648 
1649         if (CompileHostOnly)
1650           return ABRT_Success;
1651 
1652         // Replicate inputs for each GPU architecture.
1653         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1654           CudaDeviceActions.push_back(C.MakeAction<InputAction>(
1655               IA->getInputArg(), types::TY_CUDA_DEVICE));
1656 
1657         return ABRT_Success;
1658       }
1659 
1660       return IsActive ? ABRT_Success : ABRT_Inactive;
1661     }
1662 
1663     void appendTopLevelActions(ActionList &AL) override {
1664       // Utility to append actions to the top level list.
1665       auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
1666         OffloadAction::DeviceDependences Dep;
1667         Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
1668                 Action::OFK_Cuda);
1669         AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
1670       };
1671 
1672       // If we have a fat binary, add it to the list.
1673       if (CudaFatBinary) {
1674         AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
1675         CudaDeviceActions.clear();
1676         CudaFatBinary = nullptr;
1677         return;
1678       }
1679 
1680       if (CudaDeviceActions.empty())
1681         return;
1682 
1683       // If we have CUDA actions at this point, that's because we have a have
1684       // partial compilation, so we should have an action for each GPU
1685       // architecture.
1686       assert(CudaDeviceActions.size() == GpuArchList.size() &&
1687              "Expecting one action per GPU architecture.");
1688       assert(ToolChains.size() == 1 &&
1689              "Expecting to have a sing CUDA toolchain.");
1690       for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1691         AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
1692 
1693       CudaDeviceActions.clear();
1694     }
1695 
1696     bool initialize() override {
1697       // We don't need to support CUDA.
1698       if (!C.hasOffloadToolChain<Action::OFK_Cuda>())
1699         return false;
1700 
1701       const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
1702       assert(HostTC && "No toolchain for host compilation.");
1703       if (HostTC->getTriple().isNVPTX()) {
1704         // We do not support targeting NVPTX for host compilation. Throw
1705         // an error and abort pipeline construction early so we don't trip
1706         // asserts that assume device-side compilation.
1707         C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
1708         return true;
1709       }
1710 
1711       ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>());
1712 
1713       Arg *PartialCompilationArg = Args.getLastArg(
1714           options::OPT_cuda_host_only, options::OPT_cuda_device_only,
1715           options::OPT_cuda_compile_host_device);
1716       CompileHostOnly = PartialCompilationArg &&
1717                         PartialCompilationArg->getOption().matches(
1718                             options::OPT_cuda_host_only);
1719       CompileDeviceOnly = PartialCompilationArg &&
1720                           PartialCompilationArg->getOption().matches(
1721                               options::OPT_cuda_device_only);
1722 
1723       // Collect all cuda_gpu_arch parameters, removing duplicates.
1724       llvm::SmallSet<CudaArch, 4> GpuArchs;
1725       bool Error = false;
1726       for (Arg *A : Args) {
1727         if (!A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
1728           continue;
1729         A->claim();
1730 
1731         const auto &ArchStr = A->getValue();
1732         CudaArch Arch = StringToCudaArch(ArchStr);
1733         if (Arch == CudaArch::UNKNOWN) {
1734           C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
1735           Error = true;
1736         } else if (GpuArchs.insert(Arch).second)
1737           GpuArchList.push_back(Arch);
1738       }
1739 
1740       // Default to sm_20 which is the lowest common denominator for supported
1741       // GPUs.
1742       // sm_20 code should work correctly, if suboptimally, on all newer GPUs.
1743       if (GpuArchList.empty())
1744         GpuArchList.push_back(CudaArch::SM_20);
1745 
1746       return Error;
1747     }
1748   };
1749 
1750   /// Add the implementation for other specialized builders here.
1751 
1752   /// Specialized builders being used by this offloading action builder.
1753   SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
1754 
1755 public:
1756   OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
1757                           const Driver::InputList &Inputs)
1758       : C(C), Args(Args) {
1759     // Create a specialized builder for each device toolchain.
1760 
1761     IsValid = true;
1762 
1763     // Create a specialized builder for CUDA.
1764     SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
1765 
1766     //
1767     // TODO: Build other specialized builders here.
1768     //
1769 
1770     // Initialize all the builders, keeping track of errors.
1771     for (auto *SB : SpecializedBuilders)
1772       IsValid = IsValid && !SB->initialize();
1773   }
1774 
1775   ~OffloadingActionBuilder() {
1776     for (auto *SB : SpecializedBuilders)
1777       delete SB;
1778   }
1779 
1780   /// Generate an action that adds device dependences (if any) to a host action.
1781   /// If no device dependence actions exist, just return the host action \a
1782   /// HostAction. If an error is found or if no builder requires the host action
1783   /// to be generated, return nullptr.
1784   Action *
1785   addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
1786                                    phases::ID CurPhase, phases::ID FinalPhase,
1787                                    DeviceActionBuilder::PhasesTy &Phases) {
1788     if (!IsValid)
1789       return nullptr;
1790 
1791     if (SpecializedBuilders.empty())
1792       return HostAction;
1793 
1794     assert(HostAction && "Invalid host action!");
1795 
1796     OffloadAction::DeviceDependences DDeps;
1797     // Check if all the programming models agree we should not emit the host
1798     // action. Also, keep track of the offloading kinds employed.
1799     auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
1800     unsigned InactiveBuilders = 0u;
1801     unsigned IgnoringBuilders = 0u;
1802     for (auto *SB : SpecializedBuilders) {
1803       if (!SB->isValid()) {
1804         ++InactiveBuilders;
1805         continue;
1806       }
1807 
1808       auto RetCode = SB->getDeviceDepences(DDeps, CurPhase, FinalPhase, Phases);
1809 
1810       // If the builder explicitly says the host action should be ignored,
1811       // we need to increment the variable that tracks the builders that request
1812       // the host object to be ignored.
1813       if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
1814         ++IgnoringBuilders;
1815 
1816       // Unless the builder was inactive for this action, we have to record the
1817       // offload kind because the host will have to use it.
1818       if (RetCode != DeviceActionBuilder::ABRT_Inactive)
1819         OffloadKind |= SB->getAssociatedOffloadKind();
1820     }
1821 
1822     // If all builders agree that the host object should be ignored, just return
1823     // nullptr.
1824     if (IgnoringBuilders &&
1825         SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
1826       return nullptr;
1827 
1828     if (DDeps.getActions().empty())
1829       return HostAction;
1830 
1831     // We have dependences we need to bundle together. We use an offload action
1832     // for that.
1833     OffloadAction::HostDependence HDep(
1834         *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
1835         /*BoundArch=*/nullptr, DDeps);
1836     return C.MakeAction<OffloadAction>(HDep, DDeps);
1837   }
1838 
1839   /// Generate an action that adds a host dependence to a device action. The
1840   /// results will be kept in this action builder. Return true if an error was
1841   /// found.
1842   bool addHostDependenceToDeviceActions(Action *HostAction,
1843                                         const Arg *InputArg) {
1844     if (!IsValid)
1845       return true;
1846 
1847     assert(HostAction && "Invalid host action!");
1848 
1849     // Register the offload kinds that are used.
1850     auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
1851     for (auto *SB : SpecializedBuilders) {
1852       if (!SB->isValid())
1853         continue;
1854 
1855       auto RetCode = SB->addDeviceDepences(HostAction);
1856 
1857       // Host dependences for device actions are not compatible with that same
1858       // action being ignored.
1859       assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
1860              "Host dependence not expected to be ignored.!");
1861 
1862       // Unless the builder was inactive for this action, we have to record the
1863       // offload kind because the host will have to use it.
1864       if (RetCode != DeviceActionBuilder::ABRT_Inactive)
1865         OffloadKind |= SB->getAssociatedOffloadKind();
1866     }
1867 
1868     return false;
1869   }
1870 
1871   /// Add the offloading top level actions to the provided action list.
1872   bool appendTopLevelActions(ActionList &AL, Action *HostAction,
1873                              const Arg *InputArg) {
1874     auto NumActions = AL.size();
1875 
1876     for (auto *SB : SpecializedBuilders) {
1877       if (!SB->isValid())
1878         continue;
1879       SB->appendTopLevelActions(AL);
1880     }
1881 
1882     assert(NumActions <= AL.size() && "Expecting more actions, not less!");
1883 
1884     // Propagate to the current host action (if any) the offload information
1885     // associated with the current input.
1886     if (HostAction)
1887       HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
1888                                            /*BoundArch=*/nullptr);
1889 
1890     // If any action is added by the builders, -o is ambiguous if we have more
1891     // than one top-level action.
1892     if (NumActions < AL.size() && Args.hasArg(options::OPT_o) &&
1893         AL.size() > 1) {
1894       C.getDriver().Diag(
1895           clang::diag::err_drv_output_argument_with_multiple_files);
1896       return true;
1897     }
1898 
1899     return false;
1900   }
1901 
1902   /// Processes the host linker action. This currently consists of replacing it
1903   /// with an offload action if there are device link objects and propagate to
1904   /// the host action all the offload kinds used in the current compilation. The
1905   /// resulting action is returned.
1906   Action *processHostLinkAction(Action *HostAction) {
1907     // Add all the dependences from the device linking actions.
1908     OffloadAction::DeviceDependences DDeps;
1909     for (auto *SB : SpecializedBuilders) {
1910       if (!SB->isValid())
1911         continue;
1912 
1913       SB->appendLinkDependences(DDeps);
1914     }
1915 
1916     // Calculate all the offload kinds used in the current compilation.
1917     unsigned ActiveOffloadKinds = 0u;
1918     for (auto &I : InputArgToOffloadKindMap)
1919       ActiveOffloadKinds |= I.second;
1920 
1921     // If we don't have device dependencies, we don't have to create an offload
1922     // action.
1923     if (DDeps.getActions().empty()) {
1924       // Propagate all the active kinds to host action. Given that it is a link
1925       // action it is assumed to depend on all actions generated so far.
1926       HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
1927                                            /*BoundArch=*/nullptr);
1928       return HostAction;
1929     }
1930 
1931     // Create the offload action with all dependences. When an offload action
1932     // is created the kinds are propagated to the host action, so we don't have
1933     // to do that explicitely here.
1934     OffloadAction::HostDependence HDep(
1935         *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
1936         /*BoundArch*/ nullptr, ActiveOffloadKinds);
1937     return C.MakeAction<OffloadAction>(HDep, DDeps);
1938   }
1939 };
1940 } // anonymous namespace.
1941 
1942 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
1943                           const InputList &Inputs, ActionList &Actions) const {
1944   llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
1945 
1946   if (!SuppressMissingInputWarning && Inputs.empty()) {
1947     Diag(clang::diag::err_drv_no_input_files);
1948     return;
1949   }
1950 
1951   Arg *FinalPhaseArg;
1952   phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
1953 
1954   if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) {
1955     Diag(clang::diag::err_drv_emit_llvm_link);
1956   }
1957 
1958   // Reject -Z* at the top level, these options should never have been exposed
1959   // by gcc.
1960   if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
1961     Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
1962 
1963   // Diagnose misuse of /Fo.
1964   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
1965     StringRef V = A->getValue();
1966     if (Inputs.size() > 1 && !V.empty() &&
1967         !llvm::sys::path::is_separator(V.back())) {
1968       // Check whether /Fo tries to name an output file for multiple inputs.
1969       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
1970           << A->getSpelling() << V;
1971       Args.eraseArg(options::OPT__SLASH_Fo);
1972     }
1973   }
1974 
1975   // Diagnose misuse of /Fa.
1976   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
1977     StringRef V = A->getValue();
1978     if (Inputs.size() > 1 && !V.empty() &&
1979         !llvm::sys::path::is_separator(V.back())) {
1980       // Check whether /Fa tries to name an asm file for multiple inputs.
1981       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
1982           << A->getSpelling() << V;
1983       Args.eraseArg(options::OPT__SLASH_Fa);
1984     }
1985   }
1986 
1987   // Diagnose misuse of /o.
1988   if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
1989     if (A->getValue()[0] == '\0') {
1990       // It has to have a value.
1991       Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
1992       Args.eraseArg(options::OPT__SLASH_o);
1993     }
1994   }
1995 
1996   // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
1997   // * no filename after it
1998   // * both /Yc and /Yu passed but with different filenames
1999   // * corresponding file not also passed as /FI
2000   Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2001   Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2002   if (YcArg && YcArg->getValue()[0] == '\0') {
2003     Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2004     Args.eraseArg(options::OPT__SLASH_Yc);
2005     YcArg = nullptr;
2006   }
2007   if (YuArg && YuArg->getValue()[0] == '\0') {
2008     Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2009     Args.eraseArg(options::OPT__SLASH_Yu);
2010     YuArg = nullptr;
2011   }
2012   if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2013     Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2014     Args.eraseArg(options::OPT__SLASH_Yc);
2015     Args.eraseArg(options::OPT__SLASH_Yu);
2016     YcArg = YuArg = nullptr;
2017   }
2018   if (YcArg || YuArg) {
2019     StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
2020     bool FoundMatchingInclude = false;
2021     for (const Arg *Inc : Args.filtered(options::OPT_include)) {
2022       // FIXME: Do case-insensitive matching and consider / and \ as equal.
2023       if (Inc->getValue() == Val)
2024         FoundMatchingInclude = true;
2025     }
2026     if (!FoundMatchingInclude) {
2027       Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
2028           << (YcArg ? YcArg : YuArg)->getSpelling();
2029       Args.eraseArg(options::OPT__SLASH_Yc);
2030       Args.eraseArg(options::OPT__SLASH_Yu);
2031       YcArg = YuArg = nullptr;
2032     }
2033   }
2034   if (YcArg && Inputs.size() > 1) {
2035     Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2036     Args.eraseArg(options::OPT__SLASH_Yc);
2037     YcArg = nullptr;
2038   }
2039   if (Args.hasArg(options::OPT__SLASH_Y_)) {
2040     // /Y- disables all pch handling.  Rather than check for it everywhere,
2041     // just remove clang-cl pch-related flags here.
2042     Args.eraseArg(options::OPT__SLASH_Fp);
2043     Args.eraseArg(options::OPT__SLASH_Yc);
2044     Args.eraseArg(options::OPT__SLASH_Yu);
2045     YcArg = YuArg = nullptr;
2046   }
2047 
2048   // Builder to be used to build offloading actions.
2049   OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
2050 
2051   // Construct the actions to perform.
2052   ActionList LinkerInputs;
2053 
2054   llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
2055   for (auto &I : Inputs) {
2056     types::ID InputType = I.first;
2057     const Arg *InputArg = I.second;
2058 
2059     PL.clear();
2060     types::getCompilationPhases(InputType, PL);
2061 
2062     // If the first step comes after the final phase we are doing as part of
2063     // this compilation, warn the user about it.
2064     phases::ID InitialPhase = PL[0];
2065     if (InitialPhase > FinalPhase) {
2066       // Claim here to avoid the more general unused warning.
2067       InputArg->claim();
2068 
2069       // Suppress all unused style warnings with -Qunused-arguments
2070       if (Args.hasArg(options::OPT_Qunused_arguments))
2071         continue;
2072 
2073       // Special case when final phase determined by binary name, rather than
2074       // by a command-line argument with a corresponding Arg.
2075       if (CCCIsCPP())
2076         Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
2077             << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
2078       // Special case '-E' warning on a previously preprocessed file to make
2079       // more sense.
2080       else if (InitialPhase == phases::Compile &&
2081                FinalPhase == phases::Preprocess &&
2082                getPreprocessedType(InputType) == types::TY_INVALID)
2083         Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
2084             << InputArg->getAsString(Args) << !!FinalPhaseArg
2085             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
2086       else
2087         Diag(clang::diag::warn_drv_input_file_unused)
2088             << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
2089             << !!FinalPhaseArg
2090             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
2091       continue;
2092     }
2093 
2094     if (YcArg) {
2095       // Add a separate precompile phase for the compile phase.
2096       if (FinalPhase >= phases::Compile) {
2097         const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
2098         llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
2099         types::getCompilationPhases(HeaderType, PCHPL);
2100         Arg *PchInputArg = MakeInputArg(Args, Opts, YcArg->getValue());
2101 
2102         // Build the pipeline for the pch file.
2103         Action *ClangClPch =
2104             C.MakeAction<InputAction>(*PchInputArg, HeaderType);
2105         for (phases::ID Phase : PCHPL)
2106           ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
2107         assert(ClangClPch);
2108         Actions.push_back(ClangClPch);
2109         // The driver currently exits after the first failed command.  This
2110         // relies on that behavior, to make sure if the pch generation fails,
2111         // the main compilation won't run.
2112       }
2113     }
2114 
2115     // Build the pipeline for this file.
2116     Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
2117 
2118     // Use the current host action in any of the offloading actions, if
2119     // required.
2120     if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2121       break;
2122 
2123     for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
2124          i != e; ++i) {
2125       phases::ID Phase = *i;
2126 
2127       // We are done if this step is past what the user requested.
2128       if (Phase > FinalPhase)
2129         break;
2130 
2131       // Add any offload action the host action depends on.
2132       Current = OffloadBuilder.addDeviceDependencesToHostAction(
2133           Current, InputArg, Phase, FinalPhase, PL);
2134       if (!Current)
2135         break;
2136 
2137       // Queue linker inputs.
2138       if (Phase == phases::Link) {
2139         assert((i + 1) == e && "linking must be final compilation step.");
2140         LinkerInputs.push_back(Current);
2141         Current = nullptr;
2142         break;
2143       }
2144 
2145       // Otherwise construct the appropriate action.
2146       auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
2147 
2148       // We didn't create a new action, so we will just move to the next phase.
2149       if (NewCurrent == Current)
2150         continue;
2151 
2152       Current = NewCurrent;
2153 
2154       // Use the current host action in any of the offloading actions, if
2155       // required.
2156       if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2157         break;
2158 
2159       if (Current->getType() == types::TY_Nothing)
2160         break;
2161     }
2162 
2163     // If we ended with something, add to the output list.
2164     if (Current)
2165       Actions.push_back(Current);
2166 
2167     // Add any top level actions generated for offloading.
2168     OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
2169   }
2170 
2171   // Add a link action if necessary.
2172   if (!LinkerInputs.empty()) {
2173     Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
2174     LA = OffloadBuilder.processHostLinkAction(LA);
2175     Actions.push_back(LA);
2176   }
2177 
2178   // If we are linking, claim any options which are obviously only used for
2179   // compilation.
2180   if (FinalPhase == phases::Link && PL.size() == 1) {
2181     Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
2182     Args.ClaimAllArgs(options::OPT_cl_compile_Group);
2183   }
2184 
2185   // Claim ignored clang-cl options.
2186   Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
2187 
2188   // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
2189   // to non-CUDA compilations and should not trigger warnings there.
2190   Args.ClaimAllArgs(options::OPT_cuda_host_only);
2191   Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
2192 }
2193 
2194 Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
2195                                      phases::ID Phase, Action *Input) const {
2196   llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
2197 
2198   // Some types skip the assembler phase (e.g., llvm-bc), but we can't
2199   // encode this in the steps because the intermediate type depends on
2200   // arguments. Just special case here.
2201   if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
2202     return Input;
2203 
2204   // Build the appropriate action.
2205   switch (Phase) {
2206   case phases::Link:
2207     llvm_unreachable("link action invalid here.");
2208   case phases::Preprocess: {
2209     types::ID OutputTy;
2210     // -{M, MM} alter the output type.
2211     if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
2212       OutputTy = types::TY_Dependencies;
2213     } else {
2214       OutputTy = Input->getType();
2215       if (!Args.hasFlag(options::OPT_frewrite_includes,
2216                         options::OPT_fno_rewrite_includes, false) &&
2217           !CCGenDiagnostics)
2218         OutputTy = types::getPreprocessedType(OutputTy);
2219       assert(OutputTy != types::TY_INVALID &&
2220              "Cannot preprocess this input type!");
2221     }
2222     return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
2223   }
2224   case phases::Precompile: {
2225     types::ID OutputTy = getPrecompiledType(Input->getType());
2226     assert(OutputTy != types::TY_INVALID &&
2227            "Cannot precompile this input type!");
2228     if (Args.hasArg(options::OPT_fsyntax_only)) {
2229       // Syntax checks should not emit a PCH file
2230       OutputTy = types::TY_Nothing;
2231     }
2232     return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
2233   }
2234   case phases::Compile: {
2235     if (Args.hasArg(options::OPT_fsyntax_only))
2236       return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
2237     if (Args.hasArg(options::OPT_rewrite_objc))
2238       return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
2239     if (Args.hasArg(options::OPT_rewrite_legacy_objc))
2240       return C.MakeAction<CompileJobAction>(Input,
2241                                             types::TY_RewrittenLegacyObjC);
2242     if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
2243       return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
2244     if (Args.hasArg(options::OPT__migrate))
2245       return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
2246     if (Args.hasArg(options::OPT_emit_ast))
2247       return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
2248     if (Args.hasArg(options::OPT_module_file_info))
2249       return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
2250     if (Args.hasArg(options::OPT_verify_pch))
2251       return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
2252     return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
2253   }
2254   case phases::Backend: {
2255     if (isUsingLTO()) {
2256       types::ID Output =
2257           Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
2258       return C.MakeAction<BackendJobAction>(Input, Output);
2259     }
2260     if (Args.hasArg(options::OPT_emit_llvm)) {
2261       types::ID Output =
2262           Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
2263       return C.MakeAction<BackendJobAction>(Input, Output);
2264     }
2265     return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
2266   }
2267   case phases::Assemble:
2268     return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
2269   }
2270 
2271   llvm_unreachable("invalid phase in ConstructPhaseAction");
2272 }
2273 
2274 void Driver::BuildJobs(Compilation &C) const {
2275   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
2276 
2277   Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2278 
2279   // It is an error to provide a -o option if we are making multiple output
2280   // files.
2281   if (FinalOutput) {
2282     unsigned NumOutputs = 0;
2283     for (const Action *A : C.getActions())
2284       if (A->getType() != types::TY_Nothing)
2285         ++NumOutputs;
2286 
2287     if (NumOutputs > 1) {
2288       Diag(clang::diag::err_drv_output_argument_with_multiple_files);
2289       FinalOutput = nullptr;
2290     }
2291   }
2292 
2293   // Collect the list of architectures.
2294   llvm::StringSet<> ArchNames;
2295   if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
2296     for (const Arg *A : C.getArgs())
2297       if (A->getOption().matches(options::OPT_arch))
2298         ArchNames.insert(A->getValue());
2299 
2300   // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
2301   std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
2302   for (Action *A : C.getActions()) {
2303     // If we are linking an image for multiple archs then the linker wants
2304     // -arch_multiple and -final_output <final image name>. Unfortunately, this
2305     // doesn't fit in cleanly because we have to pass this information down.
2306     //
2307     // FIXME: This is a hack; find a cleaner way to integrate this into the
2308     // process.
2309     const char *LinkingOutput = nullptr;
2310     if (isa<LipoJobAction>(A)) {
2311       if (FinalOutput)
2312         LinkingOutput = FinalOutput->getValue();
2313       else
2314         LinkingOutput = getDefaultImageName();
2315     }
2316 
2317     BuildJobsForAction(C, A, &C.getDefaultToolChain(),
2318                        /*BoundArch*/ StringRef(),
2319                        /*AtTopLevel*/ true,
2320                        /*MultipleArchs*/ ArchNames.size() > 1,
2321                        /*LinkingOutput*/ LinkingOutput, CachedResults,
2322                        /*BuildForOffloadDevice*/ false);
2323   }
2324 
2325   // If the user passed -Qunused-arguments or there were errors, don't warn
2326   // about any unused arguments.
2327   if (Diags.hasErrorOccurred() ||
2328       C.getArgs().hasArg(options::OPT_Qunused_arguments))
2329     return;
2330 
2331   // Claim -### here.
2332   (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
2333 
2334   // Claim --driver-mode, --rsp-quoting, it was handled earlier.
2335   (void)C.getArgs().hasArg(options::OPT_driver_mode);
2336   (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
2337 
2338   for (Arg *A : C.getArgs()) {
2339     // FIXME: It would be nice to be able to send the argument to the
2340     // DiagnosticsEngine, so that extra values, position, and so on could be
2341     // printed.
2342     if (!A->isClaimed()) {
2343       if (A->getOption().hasFlag(options::NoArgumentUnused))
2344         continue;
2345 
2346       // Suppress the warning automatically if this is just a flag, and it is an
2347       // instance of an argument we already claimed.
2348       const Option &Opt = A->getOption();
2349       if (Opt.getKind() == Option::FlagClass) {
2350         bool DuplicateClaimed = false;
2351 
2352         for (const Arg *AA : C.getArgs().filtered(&Opt)) {
2353           if (AA->isClaimed()) {
2354             DuplicateClaimed = true;
2355             break;
2356           }
2357         }
2358 
2359         if (DuplicateClaimed)
2360           continue;
2361       }
2362 
2363       // In clang-cl, don't mention unknown arguments here since they have
2364       // already been warned about.
2365       if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
2366         Diag(clang::diag::warn_drv_unused_argument)
2367             << A->getAsString(C.getArgs());
2368     }
2369   }
2370 }
2371 /// Collapse an offloading action looking for a job of the given type. The input
2372 /// action is changed to the input of the collapsed sequence. If we effectively
2373 /// had a collapse return the corresponding offloading action, otherwise return
2374 /// null.
2375 template <typename T>
2376 static OffloadAction *collapseOffloadingAction(Action *&CurAction) {
2377   if (!CurAction)
2378     return nullptr;
2379   if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
2380     if (OA->hasHostDependence())
2381       if (auto *HDep = dyn_cast<T>(OA->getHostDependence())) {
2382         CurAction = HDep;
2383         return OA;
2384       }
2385     if (OA->hasSingleDeviceDependence())
2386       if (auto *DDep = dyn_cast<T>(OA->getSingleDeviceDependence())) {
2387         CurAction = DDep;
2388         return OA;
2389       }
2390   }
2391   return nullptr;
2392 }
2393 // Returns a Tool for a given JobAction.  In case the action and its
2394 // predecessors can be combined, updates Inputs with the inputs of the
2395 // first combined action. If one of the collapsed actions is a
2396 // CudaHostAction, updates CollapsedCHA with the pointer to it so the
2397 // caller can deal with extra handling such action requires.
2398 static const Tool *selectToolForJob(Compilation &C, bool SaveTemps,
2399                                     bool EmbedBitcode, const ToolChain *TC,
2400                                     const JobAction *JA,
2401                                     const ActionList *&Inputs,
2402                                     ActionList &CollapsedOffloadAction) {
2403   const Tool *ToolForJob = nullptr;
2404   CollapsedOffloadAction.clear();
2405 
2406   // See if we should look for a compiler with an integrated assembler. We match
2407   // bottom up, so what we are actually looking for is an assembler job with a
2408   // compiler input.
2409 
2410   // Look through offload actions between assembler and backend actions.
2411   Action *BackendJA = (isa<AssembleJobAction>(JA) && Inputs->size() == 1)
2412                           ? *Inputs->begin()
2413                           : nullptr;
2414   auto *BackendOA = collapseOffloadingAction<BackendJobAction>(BackendJA);
2415 
2416   if (TC->useIntegratedAs() && !SaveTemps &&
2417       !C.getArgs().hasArg(options::OPT_via_file_asm) &&
2418       !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
2419       !C.getArgs().hasArg(options::OPT__SLASH_Fa) && BackendJA &&
2420       isa<BackendJobAction>(BackendJA)) {
2421     // A BackendJob is always preceded by a CompileJob, and without -save-temps
2422     // or -fembed-bitcode, they will always get combined together, so instead of
2423     // checking the backend tool, check if the tool for the CompileJob has an
2424     // integrated assembler. For -fembed-bitcode, CompileJob is still used to
2425     // look up tools for BackendJob, but they need to match before we can split
2426     // them.
2427 
2428     // Look through offload actions between backend and compile actions.
2429     Action *CompileJA = *BackendJA->getInputs().begin();
2430     auto *CompileOA = collapseOffloadingAction<CompileJobAction>(CompileJA);
2431 
2432     assert(CompileJA && isa<CompileJobAction>(CompileJA) &&
2433            "Backend job is not preceeded by compile job.");
2434     const Tool *Compiler = TC->SelectTool(*cast<CompileJobAction>(CompileJA));
2435     if (!Compiler)
2436       return nullptr;
2437     // When using -fembed-bitcode, it is required to have the same tool (clang)
2438     // for both CompilerJA and BackendJA. Otherwise, combine two stages.
2439     if (EmbedBitcode) {
2440       JobAction *InputJA = cast<JobAction>(*Inputs->begin());
2441       const Tool *BackendTool = TC->SelectTool(*InputJA);
2442       if (BackendTool == Compiler)
2443         CompileJA = InputJA;
2444     }
2445     if (Compiler->hasIntegratedAssembler()) {
2446       Inputs = &CompileJA->getInputs();
2447       ToolForJob = Compiler;
2448       // Save the collapsed offload actions because they may still contain
2449       // device actions.
2450       if (CompileOA)
2451         CollapsedOffloadAction.push_back(CompileOA);
2452       if (BackendOA)
2453         CollapsedOffloadAction.push_back(BackendOA);
2454     }
2455   }
2456 
2457   // A backend job should always be combined with the preceding compile job
2458   // unless OPT_save_temps or OPT_fembed_bitcode is enabled and the compiler is
2459   // capable of emitting LLVM IR as an intermediate output.
2460   if (isa<BackendJobAction>(JA)) {
2461     // Check if the compiler supports emitting LLVM IR.
2462     assert(Inputs->size() == 1);
2463 
2464     // Look through offload actions between backend and compile actions.
2465     Action *CompileJA = *JA->getInputs().begin();
2466     auto *CompileOA = collapseOffloadingAction<CompileJobAction>(CompileJA);
2467 
2468     assert(CompileJA && isa<CompileJobAction>(CompileJA) &&
2469            "Backend job is not preceeded by compile job.");
2470     const Tool *Compiler = TC->SelectTool(*cast<CompileJobAction>(CompileJA));
2471     if (!Compiler)
2472       return nullptr;
2473     if (!Compiler->canEmitIR() ||
2474         (!SaveTemps && !EmbedBitcode)) {
2475       Inputs = &CompileJA->getInputs();
2476       ToolForJob = Compiler;
2477 
2478       if (CompileOA)
2479         CollapsedOffloadAction.push_back(CompileOA);
2480     }
2481   }
2482 
2483   // Otherwise use the tool for the current job.
2484   if (!ToolForJob)
2485     ToolForJob = TC->SelectTool(*JA);
2486 
2487   // See if we should use an integrated preprocessor. We do so when we have
2488   // exactly one input, since this is the only use case we care about
2489   // (irrelevant since we don't support combine yet).
2490 
2491   // Look through offload actions after preprocessing.
2492   Action *PreprocessJA = (Inputs->size() == 1) ? *Inputs->begin() : nullptr;
2493   auto *PreprocessOA =
2494       collapseOffloadingAction<PreprocessJobAction>(PreprocessJA);
2495 
2496   if (PreprocessJA && isa<PreprocessJobAction>(PreprocessJA) &&
2497       !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
2498       !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
2499       !C.getArgs().hasArg(options::OPT_rewrite_objc) &&
2500       ToolForJob->hasIntegratedCPP()) {
2501     Inputs = &PreprocessJA->getInputs();
2502     if (PreprocessOA)
2503       CollapsedOffloadAction.push_back(PreprocessOA);
2504   }
2505 
2506   return ToolForJob;
2507 }
2508 
2509 InputInfo Driver::BuildJobsForAction(
2510     Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
2511     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
2512     std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
2513     bool BuildForOffloadDevice) const {
2514   // The bound arch is not necessarily represented in the toolchain's triple --
2515   // for example, armv7 and armv7s both map to the same triple -- so we need
2516   // both in our map.
2517   std::string TriplePlusArch = TC->getTriple().normalize();
2518   if (!BoundArch.empty()) {
2519     TriplePlusArch += "-";
2520     TriplePlusArch += BoundArch;
2521   }
2522   std::pair<const Action *, std::string> ActionTC = {A, TriplePlusArch};
2523   auto CachedResult = CachedResults.find(ActionTC);
2524   if (CachedResult != CachedResults.end()) {
2525     return CachedResult->second;
2526   }
2527   InputInfo Result = BuildJobsForActionNoCache(
2528       C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
2529       CachedResults, BuildForOffloadDevice);
2530   CachedResults[ActionTC] = Result;
2531   return Result;
2532 }
2533 
2534 InputInfo Driver::BuildJobsForActionNoCache(
2535     Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
2536     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
2537     std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
2538     bool BuildForOffloadDevice) const {
2539   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
2540 
2541   InputInfoList OffloadDependencesInputInfo;
2542   if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
2543     // The offload action is expected to be used in four different situations.
2544     //
2545     // a) Set a toolchain/architecture/kind for a host action:
2546     //    Host Action 1 -> OffloadAction -> Host Action 2
2547     //
2548     // b) Set a toolchain/architecture/kind for a device action;
2549     //    Device Action 1 -> OffloadAction -> Device Action 2
2550     //
2551     // c) Specify a device dependences to a host action;
2552     //    Device Action 1  _
2553     //                      \
2554     //      Host Action 1  ---> OffloadAction -> Host Action 2
2555     //
2556     // d) Specify a host dependence to a device action.
2557     //      Host Action 1  _
2558     //                      \
2559     //    Device Action 1  ---> OffloadAction -> Device Action 2
2560     //
2561     // For a) and b), we just return the job generated for the dependence. For
2562     // c) and d) we override the current action with the host/device dependence
2563     // if the current toolchain is host/device and set the offload dependences
2564     // info with the jobs obtained from the device/host dependence(s).
2565 
2566     // If there is a single device option, just generate the job for it.
2567     if (OA->hasSingleDeviceDependence()) {
2568       InputInfo DevA;
2569       OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
2570                                        const char *DepBoundArch) {
2571         DevA =
2572             BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
2573                                /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
2574                                CachedResults, /*BuildForOffloadDevice=*/true);
2575       });
2576       return DevA;
2577     }
2578 
2579     // If 'Action 2' is host, we generate jobs for the device dependences and
2580     // override the current action with the host dependence. Otherwise, we
2581     // generate the host dependences and override the action with the device
2582     // dependence. The dependences can't therefore be a top-level action.
2583     OA->doOnEachDependence(
2584         /*IsHostDependence=*/BuildForOffloadDevice,
2585         [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
2586           OffloadDependencesInputInfo.push_back(BuildJobsForAction(
2587               C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
2588               /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
2589               /*BuildForOffloadDevice=*/DepA->getOffloadingDeviceKind() !=
2590                   Action::OFK_None));
2591         });
2592 
2593     A = BuildForOffloadDevice
2594             ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
2595             : OA->getHostDependence();
2596   }
2597 
2598   if (const InputAction *IA = dyn_cast<InputAction>(A)) {
2599     // FIXME: It would be nice to not claim this here; maybe the old scheme of
2600     // just using Args was better?
2601     const Arg &Input = IA->getInputArg();
2602     Input.claim();
2603     if (Input.getOption().matches(options::OPT_INPUT)) {
2604       const char *Name = Input.getValue();
2605       return InputInfo(A, Name, /* BaseInput = */ Name);
2606     }
2607     return InputInfo(A, &Input, /* BaseInput = */ "");
2608   }
2609 
2610   if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
2611     const ToolChain *TC;
2612     StringRef ArchName = BAA->getArchName();
2613 
2614     if (!ArchName.empty())
2615       TC = &getToolChain(C.getArgs(),
2616                          computeTargetTriple(*this, DefaultTargetTriple,
2617                                              C.getArgs(), ArchName));
2618     else
2619       TC = &C.getDefaultToolChain();
2620 
2621     return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
2622                               MultipleArchs, LinkingOutput, CachedResults,
2623                               BuildForOffloadDevice);
2624   }
2625 
2626 
2627   const ActionList *Inputs = &A->getInputs();
2628 
2629   const JobAction *JA = cast<JobAction>(A);
2630   ActionList CollapsedOffloadActions;
2631 
2632   const Tool *T =
2633       selectToolForJob(C, isSaveTempsEnabled(), embedBitcodeEnabled(), TC, JA,
2634                        Inputs, CollapsedOffloadActions);
2635   if (!T)
2636     return InputInfo();
2637 
2638   // If we've collapsed action list that contained OffloadAction we
2639   // need to build jobs for host/device-side inputs it may have held.
2640   for (const auto *OA : CollapsedOffloadActions)
2641     cast<OffloadAction>(OA)->doOnEachDependence(
2642         /*IsHostDependence=*/BuildForOffloadDevice,
2643         [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
2644           OffloadDependencesInputInfo.push_back(BuildJobsForAction(
2645               C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
2646               /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
2647               /*BuildForOffloadDevice=*/DepA->getOffloadingDeviceKind() !=
2648                   Action::OFK_None));
2649         });
2650 
2651   // Only use pipes when there is exactly one input.
2652   InputInfoList InputInfos;
2653   for (const Action *Input : *Inputs) {
2654     // Treat dsymutil and verify sub-jobs as being at the top-level too, they
2655     // shouldn't get temporary output names.
2656     // FIXME: Clean this up.
2657     bool SubJobAtTopLevel =
2658         AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
2659     InputInfos.push_back(BuildJobsForAction(
2660         C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
2661         CachedResults, BuildForOffloadDevice));
2662   }
2663 
2664   // Always use the first input as the base input.
2665   const char *BaseInput = InputInfos[0].getBaseInput();
2666 
2667   // ... except dsymutil actions, which use their actual input as the base
2668   // input.
2669   if (JA->getType() == types::TY_dSYM)
2670     BaseInput = InputInfos[0].getFilename();
2671 
2672   // Append outputs of offload device jobs to the input list
2673   if (!OffloadDependencesInputInfo.empty())
2674     InputInfos.append(OffloadDependencesInputInfo.begin(),
2675                       OffloadDependencesInputInfo.end());
2676 
2677   // Set the effective triple of the toolchain for the duration of this job.
2678   llvm::Triple EffectiveTriple;
2679   const ToolChain &ToolTC = T->getToolChain();
2680   const ArgList &Args = C.getArgsForToolChain(TC, BoundArch);
2681   if (InputInfos.size() != 1) {
2682     EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
2683   } else {
2684     // Pass along the input type if it can be unambiguously determined.
2685     EffectiveTriple = llvm::Triple(
2686         ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
2687   }
2688   RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
2689 
2690   // Determine the place to write output to, if any.
2691   InputInfo Result;
2692   if (JA->getType() == types::TY_Nothing)
2693     Result = InputInfo(A, BaseInput);
2694   else
2695     Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
2696                                              AtTopLevel, MultipleArchs,
2697                                              TC->getTriple().normalize()),
2698                        BaseInput);
2699 
2700   if (CCCPrintBindings && !CCGenDiagnostics) {
2701     llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
2702                  << " - \"" << T->getName() << "\", inputs: [";
2703     for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
2704       llvm::errs() << InputInfos[i].getAsString();
2705       if (i + 1 != e)
2706         llvm::errs() << ", ";
2707     }
2708     llvm::errs() << "], output: " << Result.getAsString() << "\n";
2709   } else {
2710     T->ConstructJob(C, *JA, Result, InputInfos,
2711                     C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
2712   }
2713   return Result;
2714 }
2715 
2716 const char *Driver::getDefaultImageName() const {
2717   llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
2718   return Target.isOSWindows() ? "a.exe" : "a.out";
2719 }
2720 
2721 /// \brief Create output filename based on ArgValue, which could either be a
2722 /// full filename, filename without extension, or a directory. If ArgValue
2723 /// does not provide a filename, then use BaseName, and use the extension
2724 /// suitable for FileType.
2725 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
2726                                         StringRef BaseName,
2727                                         types::ID FileType) {
2728   SmallString<128> Filename = ArgValue;
2729 
2730   if (ArgValue.empty()) {
2731     // If the argument is empty, output to BaseName in the current dir.
2732     Filename = BaseName;
2733   } else if (llvm::sys::path::is_separator(Filename.back())) {
2734     // If the argument is a directory, output to BaseName in that dir.
2735     llvm::sys::path::append(Filename, BaseName);
2736   }
2737 
2738   if (!llvm::sys::path::has_extension(ArgValue)) {
2739     // If the argument didn't provide an extension, then set it.
2740     const char *Extension = types::getTypeTempSuffix(FileType, true);
2741 
2742     if (FileType == types::TY_Image &&
2743         Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
2744       // The output file is a dll.
2745       Extension = "dll";
2746     }
2747 
2748     llvm::sys::path::replace_extension(Filename, Extension);
2749   }
2750 
2751   return Args.MakeArgString(Filename.c_str());
2752 }
2753 
2754 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
2755                                        const char *BaseInput,
2756                                        StringRef BoundArch, bool AtTopLevel,
2757                                        bool MultipleArchs,
2758                                        StringRef NormalizedTriple) const {
2759   llvm::PrettyStackTraceString CrashInfo("Computing output path");
2760   // Output to a user requested destination?
2761   if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
2762     if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
2763       return C.addResultFile(FinalOutput->getValue(), &JA);
2764   }
2765 
2766   // For /P, preprocess to file named after BaseInput.
2767   if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
2768     assert(AtTopLevel && isa<PreprocessJobAction>(JA));
2769     StringRef BaseName = llvm::sys::path::filename(BaseInput);
2770     StringRef NameArg;
2771     if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
2772       NameArg = A->getValue();
2773     return C.addResultFile(
2774         MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
2775         &JA);
2776   }
2777 
2778   // Default to writing to stdout?
2779   if (AtTopLevel && !CCGenDiagnostics &&
2780       (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
2781     return "-";
2782 
2783   // Is this the assembly listing for /FA?
2784   if (JA.getType() == types::TY_PP_Asm &&
2785       (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
2786        C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
2787     // Use /Fa and the input filename to determine the asm file name.
2788     StringRef BaseName = llvm::sys::path::filename(BaseInput);
2789     StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
2790     return C.addResultFile(
2791         MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
2792         &JA);
2793   }
2794 
2795   // Output to a temporary file?
2796   if ((!AtTopLevel && !isSaveTempsEnabled() &&
2797        !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
2798       CCGenDiagnostics) {
2799     StringRef Name = llvm::sys::path::filename(BaseInput);
2800     std::pair<StringRef, StringRef> Split = Name.split('.');
2801     std::string TmpName = GetTemporaryPath(
2802         Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
2803     return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
2804   }
2805 
2806   SmallString<128> BasePath(BaseInput);
2807   StringRef BaseName;
2808 
2809   // Dsymutil actions should use the full path.
2810   if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
2811     BaseName = BasePath;
2812   else
2813     BaseName = llvm::sys::path::filename(BasePath);
2814 
2815   // Determine what the derived output name should be.
2816   const char *NamedOutput;
2817 
2818   if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
2819       C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
2820     // The /Fo or /o flag decides the object filename.
2821     StringRef Val =
2822         C.getArgs()
2823             .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
2824             ->getValue();
2825     NamedOutput =
2826         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
2827   } else if (JA.getType() == types::TY_Image &&
2828              C.getArgs().hasArg(options::OPT__SLASH_Fe,
2829                                 options::OPT__SLASH_o)) {
2830     // The /Fe or /o flag names the linked file.
2831     StringRef Val =
2832         C.getArgs()
2833             .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
2834             ->getValue();
2835     NamedOutput =
2836         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
2837   } else if (JA.getType() == types::TY_Image) {
2838     if (IsCLMode()) {
2839       // clang-cl uses BaseName for the executable name.
2840       NamedOutput =
2841           MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
2842     } else if (MultipleArchs && !BoundArch.empty()) {
2843       SmallString<128> Output(getDefaultImageName());
2844       Output += JA.getOffloadingFileNamePrefix(NormalizedTriple);
2845       Output += "-";
2846       Output.append(BoundArch);
2847       NamedOutput = C.getArgs().MakeArgString(Output.c_str());
2848     } else {
2849       NamedOutput = getDefaultImageName();
2850     }
2851   } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
2852     NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName).c_str());
2853   } else {
2854     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
2855     assert(Suffix && "All types used for output should have a suffix.");
2856 
2857     std::string::size_type End = std::string::npos;
2858     if (!types::appendSuffixForType(JA.getType()))
2859       End = BaseName.rfind('.');
2860     SmallString<128> Suffixed(BaseName.substr(0, End));
2861     Suffixed += JA.getOffloadingFileNamePrefix(NormalizedTriple);
2862     if (MultipleArchs && !BoundArch.empty()) {
2863       Suffixed += "-";
2864       Suffixed.append(BoundArch);
2865     }
2866     // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
2867     // the unoptimized bitcode so that it does not get overwritten by the ".bc"
2868     // optimized bitcode output.
2869     if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
2870         JA.getType() == types::TY_LLVM_BC)
2871       Suffixed += ".tmp";
2872     Suffixed += '.';
2873     Suffixed += Suffix;
2874     NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
2875   }
2876 
2877   // Prepend object file path if -save-temps=obj
2878   if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
2879       JA.getType() != types::TY_PCH) {
2880     Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2881     SmallString<128> TempPath(FinalOutput->getValue());
2882     llvm::sys::path::remove_filename(TempPath);
2883     StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
2884     llvm::sys::path::append(TempPath, OutputFileName);
2885     NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
2886   }
2887 
2888   // If we're saving temps and the temp file conflicts with the input file,
2889   // then avoid overwriting input file.
2890   if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
2891     bool SameFile = false;
2892     SmallString<256> Result;
2893     llvm::sys::fs::current_path(Result);
2894     llvm::sys::path::append(Result, BaseName);
2895     llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
2896     // Must share the same path to conflict.
2897     if (SameFile) {
2898       StringRef Name = llvm::sys::path::filename(BaseInput);
2899       std::pair<StringRef, StringRef> Split = Name.split('.');
2900       std::string TmpName = GetTemporaryPath(
2901           Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
2902       return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
2903     }
2904   }
2905 
2906   // As an annoying special case, PCH generation doesn't strip the pathname.
2907   if (JA.getType() == types::TY_PCH && !IsCLMode()) {
2908     llvm::sys::path::remove_filename(BasePath);
2909     if (BasePath.empty())
2910       BasePath = NamedOutput;
2911     else
2912       llvm::sys::path::append(BasePath, NamedOutput);
2913     return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
2914   } else {
2915     return C.addResultFile(NamedOutput, &JA);
2916   }
2917 }
2918 
2919 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
2920   // Respect a limited subset of the '-Bprefix' functionality in GCC by
2921   // attempting to use this prefix when looking for file paths.
2922   for (const std::string &Dir : PrefixDirs) {
2923     if (Dir.empty())
2924       continue;
2925     SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
2926     llvm::sys::path::append(P, Name);
2927     if (llvm::sys::fs::exists(Twine(P)))
2928       return P.str();
2929   }
2930 
2931   SmallString<128> P(ResourceDir);
2932   llvm::sys::path::append(P, Name);
2933   if (llvm::sys::fs::exists(Twine(P)))
2934     return P.str();
2935 
2936   for (const std::string &Dir : TC.getFilePaths()) {
2937     if (Dir.empty())
2938       continue;
2939     SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
2940     llvm::sys::path::append(P, Name);
2941     if (llvm::sys::fs::exists(Twine(P)))
2942       return P.str();
2943   }
2944 
2945   return Name;
2946 }
2947 
2948 void Driver::generatePrefixedToolNames(
2949     StringRef Tool, const ToolChain &TC,
2950     SmallVectorImpl<std::string> &Names) const {
2951   // FIXME: Needs a better variable than DefaultTargetTriple
2952   Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
2953   Names.emplace_back(Tool);
2954 
2955   // Allow the discovery of tools prefixed with LLVM's default target triple.
2956   std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
2957   if (LLVMDefaultTargetTriple != DefaultTargetTriple)
2958     Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str());
2959 }
2960 
2961 static bool ScanDirForExecutable(SmallString<128> &Dir,
2962                                  ArrayRef<std::string> Names) {
2963   for (const auto &Name : Names) {
2964     llvm::sys::path::append(Dir, Name);
2965     if (llvm::sys::fs::can_execute(Twine(Dir)))
2966       return true;
2967     llvm::sys::path::remove_filename(Dir);
2968   }
2969   return false;
2970 }
2971 
2972 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
2973   SmallVector<std::string, 2> TargetSpecificExecutables;
2974   generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
2975 
2976   // Respect a limited subset of the '-Bprefix' functionality in GCC by
2977   // attempting to use this prefix when looking for program paths.
2978   for (const auto &PrefixDir : PrefixDirs) {
2979     if (llvm::sys::fs::is_directory(PrefixDir)) {
2980       SmallString<128> P(PrefixDir);
2981       if (ScanDirForExecutable(P, TargetSpecificExecutables))
2982         return P.str();
2983     } else {
2984       SmallString<128> P((PrefixDir + Name).str());
2985       if (llvm::sys::fs::can_execute(Twine(P)))
2986         return P.str();
2987     }
2988   }
2989 
2990   const ToolChain::path_list &List = TC.getProgramPaths();
2991   for (const auto &Path : List) {
2992     SmallString<128> P(Path);
2993     if (ScanDirForExecutable(P, TargetSpecificExecutables))
2994       return P.str();
2995   }
2996 
2997   // If all else failed, search the path.
2998   for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
2999     if (llvm::ErrorOr<std::string> P =
3000             llvm::sys::findProgramByName(TargetSpecificExecutable))
3001       return *P;
3002 
3003   return Name;
3004 }
3005 
3006 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
3007   SmallString<128> Path;
3008   std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
3009   if (EC) {
3010     Diag(clang::diag::err_unable_to_make_temp) << EC.message();
3011     return "";
3012   }
3013 
3014   return Path.str();
3015 }
3016 
3017 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
3018   SmallString<128> Output;
3019   if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
3020     // FIXME: If anybody needs it, implement this obscure rule:
3021     // "If you specify a directory without a file name, the default file name
3022     // is VCx0.pch., where x is the major version of Visual C++ in use."
3023     Output = FpArg->getValue();
3024 
3025     // "If you do not specify an extension as part of the path name, an
3026     // extension of .pch is assumed. "
3027     if (!llvm::sys::path::has_extension(Output))
3028       Output += ".pch";
3029   } else {
3030     Output = BaseName;
3031     llvm::sys::path::replace_extension(Output, ".pch");
3032   }
3033   return Output.str();
3034 }
3035 
3036 const ToolChain &Driver::getToolChain(const ArgList &Args,
3037                                       const llvm::Triple &Target) const {
3038 
3039   ToolChain *&TC = ToolChains[Target.str()];
3040   if (!TC) {
3041     switch (Target.getOS()) {
3042     case llvm::Triple::Haiku:
3043       TC = new toolchains::Haiku(*this, Target, Args);
3044       break;
3045     case llvm::Triple::CloudABI:
3046       TC = new toolchains::CloudABI(*this, Target, Args);
3047       break;
3048     case llvm::Triple::Darwin:
3049     case llvm::Triple::MacOSX:
3050     case llvm::Triple::IOS:
3051     case llvm::Triple::TvOS:
3052     case llvm::Triple::WatchOS:
3053       TC = new toolchains::DarwinClang(*this, Target, Args);
3054       break;
3055     case llvm::Triple::DragonFly:
3056       TC = new toolchains::DragonFly(*this, Target, Args);
3057       break;
3058     case llvm::Triple::OpenBSD:
3059       TC = new toolchains::OpenBSD(*this, Target, Args);
3060       break;
3061     case llvm::Triple::Bitrig:
3062       TC = new toolchains::Bitrig(*this, Target, Args);
3063       break;
3064     case llvm::Triple::NetBSD:
3065       TC = new toolchains::NetBSD(*this, Target, Args);
3066       break;
3067     case llvm::Triple::FreeBSD:
3068       TC = new toolchains::FreeBSD(*this, Target, Args);
3069       break;
3070     case llvm::Triple::Minix:
3071       TC = new toolchains::Minix(*this, Target, Args);
3072       break;
3073     case llvm::Triple::Linux:
3074     case llvm::Triple::ELFIAMCU:
3075       if (Target.getArch() == llvm::Triple::hexagon)
3076         TC = new toolchains::HexagonToolChain(*this, Target, Args);
3077       else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
3078                !Target.hasEnvironment())
3079         TC = new toolchains::MipsLLVMToolChain(*this, Target, Args);
3080       else
3081         TC = new toolchains::Linux(*this, Target, Args);
3082       break;
3083     case llvm::Triple::NaCl:
3084       TC = new toolchains::NaClToolChain(*this, Target, Args);
3085       break;
3086     case llvm::Triple::Fuchsia:
3087       TC = new toolchains::Fuchsia(*this, Target, Args);
3088       break;
3089     case llvm::Triple::Solaris:
3090       TC = new toolchains::Solaris(*this, Target, Args);
3091       break;
3092     case llvm::Triple::AMDHSA:
3093       TC = new toolchains::AMDGPUToolChain(*this, Target, Args);
3094       break;
3095     case llvm::Triple::Win32:
3096       switch (Target.getEnvironment()) {
3097       default:
3098         if (Target.isOSBinFormatELF())
3099           TC = new toolchains::Generic_ELF(*this, Target, Args);
3100         else if (Target.isOSBinFormatMachO())
3101           TC = new toolchains::MachO(*this, Target, Args);
3102         else
3103           TC = new toolchains::Generic_GCC(*this, Target, Args);
3104         break;
3105       case llvm::Triple::GNU:
3106         TC = new toolchains::MinGW(*this, Target, Args);
3107         break;
3108       case llvm::Triple::Itanium:
3109         TC = new toolchains::CrossWindowsToolChain(*this, Target, Args);
3110         break;
3111       case llvm::Triple::MSVC:
3112       case llvm::Triple::UnknownEnvironment:
3113         TC = new toolchains::MSVCToolChain(*this, Target, Args);
3114         break;
3115       }
3116       break;
3117     case llvm::Triple::CUDA:
3118       TC = new toolchains::CudaToolChain(*this, Target, Args);
3119       break;
3120     case llvm::Triple::PS4:
3121       TC = new toolchains::PS4CPU(*this, Target, Args);
3122       break;
3123     default:
3124       // Of these targets, Hexagon is the only one that might have
3125       // an OS of Linux, in which case it got handled above already.
3126       switch (Target.getArch()) {
3127       case llvm::Triple::tce:
3128         TC = new toolchains::TCEToolChain(*this, Target, Args);
3129         break;
3130       case llvm::Triple::hexagon:
3131         TC = new toolchains::HexagonToolChain(*this, Target, Args);
3132         break;
3133       case llvm::Triple::lanai:
3134         TC = new toolchains::LanaiToolChain(*this, Target, Args);
3135         break;
3136       case llvm::Triple::xcore:
3137         TC = new toolchains::XCoreToolChain(*this, Target, Args);
3138         break;
3139       case llvm::Triple::wasm32:
3140       case llvm::Triple::wasm64:
3141         TC = new toolchains::WebAssembly(*this, Target, Args);
3142         break;
3143       default:
3144         if (Target.getVendor() == llvm::Triple::Myriad)
3145           TC = new toolchains::MyriadToolChain(*this, Target, Args);
3146         else if (Target.isOSBinFormatELF())
3147           TC = new toolchains::Generic_ELF(*this, Target, Args);
3148         else if (Target.isOSBinFormatMachO())
3149           TC = new toolchains::MachO(*this, Target, Args);
3150         else
3151           TC = new toolchains::Generic_GCC(*this, Target, Args);
3152       }
3153     }
3154   }
3155   return *TC;
3156 }
3157 
3158 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
3159   // Say "no" if there is not exactly one input of a type clang understands.
3160   if (JA.size() != 1 ||
3161       !types::isAcceptedByClang((*JA.input_begin())->getType()))
3162     return false;
3163 
3164   // And say "no" if this is not a kind of action clang understands.
3165   if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
3166       !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
3167     return false;
3168 
3169   return true;
3170 }
3171 
3172 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
3173 /// grouped values as integers. Numbers which are not provided are set to 0.
3174 ///
3175 /// \return True if the entire string was parsed (9.2), or all groups were
3176 /// parsed (10.3.5extrastuff).
3177 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
3178                                unsigned &Micro, bool &HadExtra) {
3179   HadExtra = false;
3180 
3181   Major = Minor = Micro = 0;
3182   if (Str.empty())
3183     return false;
3184 
3185   if (Str.consumeInteger(10, Major))
3186     return false;
3187   if (Str.empty())
3188     return true;
3189   if (Str[0] != '.')
3190     return false;
3191 
3192   Str = Str.drop_front(1);
3193 
3194   if (Str.consumeInteger(10, Minor))
3195     return false;
3196   if (Str.empty())
3197     return true;
3198   if (Str[0] != '.')
3199     return false;
3200   Str = Str.drop_front(1);
3201 
3202   if (Str.consumeInteger(10, Micro))
3203     return false;
3204   if (!Str.empty())
3205     HadExtra = true;
3206   return true;
3207 }
3208 
3209 /// Parse digits from a string \p Str and fulfill \p Digits with
3210 /// the parsed numbers. This method assumes that the max number of
3211 /// digits to look for is equal to Digits.size().
3212 ///
3213 /// \return True if the entire string was parsed and there are
3214 /// no extra characters remaining at the end.
3215 bool Driver::GetReleaseVersion(StringRef Str,
3216                                MutableArrayRef<unsigned> Digits) {
3217   if (Str.empty())
3218     return false;
3219 
3220   unsigned CurDigit = 0;
3221   while (CurDigit < Digits.size()) {
3222     unsigned Digit;
3223     if (Str.consumeInteger(10, Digit))
3224       return false;
3225     Digits[CurDigit] = Digit;
3226     if (Str.empty())
3227       return true;
3228     if (Str[0] != '.')
3229       return false;
3230     Str = Str.drop_front(1);
3231     CurDigit++;
3232   }
3233 
3234   // More digits than requested, bail out...
3235   return false;
3236 }
3237 
3238 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
3239   unsigned IncludedFlagsBitmask = 0;
3240   unsigned ExcludedFlagsBitmask = options::NoDriverOption;
3241 
3242   if (Mode == CLMode) {
3243     // Include CL and Core options.
3244     IncludedFlagsBitmask |= options::CLOption;
3245     IncludedFlagsBitmask |= options::CoreOption;
3246   } else {
3247     ExcludedFlagsBitmask |= options::CLOption;
3248   }
3249 
3250   return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
3251 }
3252 
3253 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
3254   return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
3255 }
3256