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