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