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