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