1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang/Driver/Driver.h"
10 #include "InputInfo.h"
11 #include "ToolChains/AIX.h"
12 #include "ToolChains/AMDGPU.h"
13 #include "ToolChains/AVR.h"
14 #include "ToolChains/Ananas.h"
15 #include "ToolChains/BareMetal.h"
16 #include "ToolChains/Clang.h"
17 #include "ToolChains/CloudABI.h"
18 #include "ToolChains/Contiki.h"
19 #include "ToolChains/CrossWindows.h"
20 #include "ToolChains/Cuda.h"
21 #include "ToolChains/Darwin.h"
22 #include "ToolChains/DragonFly.h"
23 #include "ToolChains/FreeBSD.h"
24 #include "ToolChains/Fuchsia.h"
25 #include "ToolChains/Gnu.h"
26 #include "ToolChains/HIP.h"
27 #include "ToolChains/Haiku.h"
28 #include "ToolChains/Hexagon.h"
29 #include "ToolChains/Hurd.h"
30 #include "ToolChains/Lanai.h"
31 #include "ToolChains/Linux.h"
32 #include "ToolChains/MSP430.h"
33 #include "ToolChains/MSVC.h"
34 #include "ToolChains/MinGW.h"
35 #include "ToolChains/Minix.h"
36 #include "ToolChains/MipsLinux.h"
37 #include "ToolChains/Myriad.h"
38 #include "ToolChains/NaCl.h"
39 #include "ToolChains/NetBSD.h"
40 #include "ToolChains/OpenBSD.h"
41 #include "ToolChains/PPCLinux.h"
42 #include "ToolChains/PS4CPU.h"
43 #include "ToolChains/RISCVToolchain.h"
44 #include "ToolChains/Solaris.h"
45 #include "ToolChains/TCE.h"
46 #include "ToolChains/VEToolchain.h"
47 #include "ToolChains/WebAssembly.h"
48 #include "ToolChains/XCore.h"
49 #include "clang/Basic/Version.h"
50 #include "clang/Config/config.h"
51 #include "clang/Driver/Action.h"
52 #include "clang/Driver/Compilation.h"
53 #include "clang/Driver/DriverDiagnostic.h"
54 #include "clang/Driver/Job.h"
55 #include "clang/Driver/Options.h"
56 #include "clang/Driver/SanitizerArgs.h"
57 #include "clang/Driver/Tool.h"
58 #include "clang/Driver/ToolChain.h"
59 #include "llvm/ADT/ArrayRef.h"
60 #include "llvm/ADT/STLExtras.h"
61 #include "llvm/ADT/SmallSet.h"
62 #include "llvm/ADT/StringExtras.h"
63 #include "llvm/ADT/StringSet.h"
64 #include "llvm/ADT/StringSwitch.h"
65 #include "llvm/Config/llvm-config.h"
66 #include "llvm/Option/Arg.h"
67 #include "llvm/Option/ArgList.h"
68 #include "llvm/Option/OptSpecifier.h"
69 #include "llvm/Option/OptTable.h"
70 #include "llvm/Option/Option.h"
71 #include "llvm/Support/CommandLine.h"
72 #include "llvm/Support/ErrorHandling.h"
73 #include "llvm/Support/FileSystem.h"
74 #include "llvm/Support/FormatVariadic.h"
75 #include "llvm/Support/Host.h"
76 #include "llvm/Support/Path.h"
77 #include "llvm/Support/PrettyStackTrace.h"
78 #include "llvm/Support/Process.h"
79 #include "llvm/Support/Program.h"
80 #include "llvm/Support/StringSaver.h"
81 #include "llvm/Support/TargetRegistry.h"
82 #include "llvm/Support/VirtualFileSystem.h"
83 #include "llvm/Support/raw_ostream.h"
84 #include <map>
85 #include <memory>
86 #include <utility>
87 #if LLVM_ON_UNIX
88 #include <unistd.h> // getpid
89 #include <sysexits.h> // EX_IOERR
90 #endif
91 
92 using namespace clang::driver;
93 using namespace clang;
94 using namespace llvm::opt;
95 
96 // static
97 std::string Driver::GetResourcesPath(StringRef BinaryPath,
98                                      StringRef CustomResourceDir) {
99   // Since the resource directory is embedded in the module hash, it's important
100   // that all places that need it call this function, so that they get the
101   // exact same string ("a/../b/" and "b/" get different hashes, for example).
102 
103   // Dir is bin/ or lib/, depending on where BinaryPath is.
104   std::string Dir = std::string(llvm::sys::path::parent_path(BinaryPath));
105 
106   SmallString<128> P(Dir);
107   if (CustomResourceDir != "") {
108     llvm::sys::path::append(P, CustomResourceDir);
109   } else {
110     // On Windows, libclang.dll is in bin/.
111     // On non-Windows, libclang.so/.dylib is in lib/.
112     // With a static-library build of libclang, LibClangPath will contain the
113     // path of the embedding binary, which for LLVM binaries will be in bin/.
114     // ../lib gets us to lib/ in both cases.
115     P = llvm::sys::path::parent_path(Dir);
116     llvm::sys::path::append(P, Twine("lib") + CLANG_LIBDIR_SUFFIX, "clang",
117                             CLANG_VERSION_STRING);
118   }
119 
120   return std::string(P.str());
121 }
122 
123 Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
124                DiagnosticsEngine &Diags,
125                IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
126     : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
127       SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None),
128       ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
129       DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
130       CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
131       CCCPrintBindings(false), CCPrintOptions(false), CCPrintHeaders(false),
132       CCLogDiagnostics(false), CCGenDiagnostics(false),
133       TargetTriple(TargetTriple), CCCGenericGCCName(""), Saver(Alloc),
134       CheckInputsExist(true), GenReproducer(false),
135       SuppressMissingInputWarning(false) {
136   // Provide a sane fallback if no VFS is specified.
137   if (!this->VFS)
138     this->VFS = llvm::vfs::getRealFileSystem();
139 
140   Name = std::string(llvm::sys::path::filename(ClangExecutable));
141   Dir = std::string(llvm::sys::path::parent_path(ClangExecutable));
142   InstalledDir = Dir; // Provide a sensible default installed dir.
143 
144   if ((!SysRoot.empty()) && llvm::sys::path::is_relative(SysRoot)) {
145     // Prepend InstalledDir if SysRoot is relative
146     SmallString<128> P(InstalledDir);
147     llvm::sys::path::append(P, SysRoot);
148     SysRoot = std::string(P);
149   }
150 
151 #if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
152   SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
153 #endif
154 #if defined(CLANG_CONFIG_FILE_USER_DIR)
155   UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
156 #endif
157 
158   // Compute the path to the resource directory.
159   ResourceDir = GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
160 }
161 
162 void Driver::ParseDriverMode(StringRef ProgramName,
163                              ArrayRef<const char *> Args) {
164   if (ClangNameParts.isEmpty())
165     ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
166   setDriverModeFromOption(ClangNameParts.DriverMode);
167 
168   for (const char *ArgPtr : Args) {
169     // Ignore nullptrs, they are the response file's EOL markers.
170     if (ArgPtr == nullptr)
171       continue;
172     const StringRef Arg = ArgPtr;
173     setDriverModeFromOption(Arg);
174   }
175 }
176 
177 void Driver::setDriverModeFromOption(StringRef Opt) {
178   const std::string OptName =
179       getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
180   if (!Opt.startswith(OptName))
181     return;
182   StringRef Value = Opt.drop_front(OptName.size());
183 
184   if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
185                    .Case("gcc", GCCMode)
186                    .Case("g++", GXXMode)
187                    .Case("cpp", CPPMode)
188                    .Case("cl", CLMode)
189                    .Case("flang", FlangMode)
190                    .Default(None))
191     Mode = *M;
192   else
193     Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
194 }
195 
196 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
197                                      bool IsClCompatMode,
198                                      bool &ContainsError) {
199   llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
200   ContainsError = false;
201 
202   unsigned IncludedFlagsBitmask;
203   unsigned ExcludedFlagsBitmask;
204   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
205       getIncludeExcludeOptionFlagMasks(IsClCompatMode);
206 
207   unsigned MissingArgIndex, MissingArgCount;
208   InputArgList Args =
209       getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
210                           IncludedFlagsBitmask, ExcludedFlagsBitmask);
211 
212   // Check for missing argument error.
213   if (MissingArgCount) {
214     Diag(diag::err_drv_missing_argument)
215         << Args.getArgString(MissingArgIndex) << MissingArgCount;
216     ContainsError |=
217         Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
218                                  SourceLocation()) > DiagnosticsEngine::Warning;
219   }
220 
221   // Check for unsupported options.
222   for (const Arg *A : Args) {
223     if (A->getOption().hasFlag(options::Unsupported)) {
224       unsigned DiagID;
225       auto ArgString = A->getAsString(Args);
226       std::string Nearest;
227       if (getOpts().findNearest(
228             ArgString, Nearest, IncludedFlagsBitmask,
229             ExcludedFlagsBitmask | options::Unsupported) > 1) {
230         DiagID = diag::err_drv_unsupported_opt;
231         Diag(DiagID) << ArgString;
232       } else {
233         DiagID = diag::err_drv_unsupported_opt_with_suggestion;
234         Diag(DiagID) << ArgString << Nearest;
235       }
236       ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
237                        DiagnosticsEngine::Warning;
238       continue;
239     }
240 
241     // Warn about -mcpu= without an argument.
242     if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
243       Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
244       ContainsError |= Diags.getDiagnosticLevel(
245                            diag::warn_drv_empty_joined_argument,
246                            SourceLocation()) > DiagnosticsEngine::Warning;
247     }
248   }
249 
250   for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
251     unsigned DiagID;
252     auto ArgString = A->getAsString(Args);
253     std::string Nearest;
254     if (getOpts().findNearest(
255           ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
256       DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
257                           : diag::err_drv_unknown_argument;
258       Diags.Report(DiagID) << ArgString;
259     } else {
260       DiagID = IsCLMode()
261                    ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
262                    : diag::err_drv_unknown_argument_with_suggestion;
263       Diags.Report(DiagID) << ArgString << Nearest;
264     }
265     ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
266                      DiagnosticsEngine::Warning;
267   }
268 
269   return Args;
270 }
271 
272 // Determine which compilation mode we are in. We look for options which
273 // affect the phase, starting with the earliest phases, and record which
274 // option we used to determine the final phase.
275 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
276                                  Arg **FinalPhaseArg) const {
277   Arg *PhaseArg = nullptr;
278   phases::ID FinalPhase;
279 
280   // -{E,EP,P,M,MM} only run the preprocessor.
281   if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
282       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
283       (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
284       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
285     FinalPhase = phases::Preprocess;
286 
287   // --precompile only runs up to precompilation.
288   } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
289     FinalPhase = phases::Precompile;
290 
291   // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
292   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
293              (PhaseArg = DAL.getLastArg(options::OPT_print_supported_cpus)) ||
294              (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
295              (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
296              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
297              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
298              (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
299              (PhaseArg = DAL.getLastArg(options::OPT__analyze)) ||
300              (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
301     FinalPhase = phases::Compile;
302 
303   // -S only runs up to the backend.
304   } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
305     FinalPhase = phases::Backend;
306 
307   // -c compilation only runs up to the assembler.
308   } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
309     FinalPhase = phases::Assemble;
310 
311   // Otherwise do everything.
312   } else
313     FinalPhase = phases::Link;
314 
315   if (FinalPhaseArg)
316     *FinalPhaseArg = PhaseArg;
317 
318   return FinalPhase;
319 }
320 
321 static Arg *MakeInputArg(DerivedArgList &Args, const OptTable &Opts,
322                          StringRef Value, bool Claim = true) {
323   Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
324                    Args.getBaseArgs().MakeIndex(Value), Value.data());
325   Args.AddSynthesizedArg(A);
326   if (Claim)
327     A->claim();
328   return A;
329 }
330 
331 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
332   const llvm::opt::OptTable &Opts = getOpts();
333   DerivedArgList *DAL = new DerivedArgList(Args);
334 
335   bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
336   bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
337   bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
338   for (Arg *A : Args) {
339     // Unfortunately, we have to parse some forwarding options (-Xassembler,
340     // -Xlinker, -Xpreprocessor) because we either integrate their functionality
341     // (assembler and preprocessor), or bypass a previous driver ('collect2').
342 
343     // Rewrite linker options, to replace --no-demangle with a custom internal
344     // option.
345     if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
346          A->getOption().matches(options::OPT_Xlinker)) &&
347         A->containsValue("--no-demangle")) {
348       // Add the rewritten no-demangle argument.
349       DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_Xlinker__no_demangle));
350 
351       // Add the remaining values as Xlinker arguments.
352       for (StringRef Val : A->getValues())
353         if (Val != "--no-demangle")
354           DAL->AddSeparateArg(A, Opts.getOption(options::OPT_Xlinker), Val);
355 
356       continue;
357     }
358 
359     // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
360     // some build systems. We don't try to be complete here because we don't
361     // care to encourage this usage model.
362     if (A->getOption().matches(options::OPT_Wp_COMMA) &&
363         (A->getValue(0) == StringRef("-MD") ||
364          A->getValue(0) == StringRef("-MMD"))) {
365       // Rewrite to -MD/-MMD along with -MF.
366       if (A->getValue(0) == StringRef("-MD"))
367         DAL->AddFlagArg(A, Opts.getOption(options::OPT_MD));
368       else
369         DAL->AddFlagArg(A, Opts.getOption(options::OPT_MMD));
370       if (A->getNumValues() == 2)
371         DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue(1));
372       continue;
373     }
374 
375     // Rewrite reserved library names.
376     if (A->getOption().matches(options::OPT_l)) {
377       StringRef Value = A->getValue();
378 
379       // Rewrite unless -nostdlib is present.
380       if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx &&
381           Value == "stdc++") {
382         DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_stdcxx));
383         continue;
384       }
385 
386       // Rewrite unconditionally.
387       if (Value == "cc_kext") {
388         DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_cckext));
389         continue;
390       }
391     }
392 
393     // Pick up inputs via the -- option.
394     if (A->getOption().matches(options::OPT__DASH_DASH)) {
395       A->claim();
396       for (StringRef Val : A->getValues())
397         DAL->append(MakeInputArg(*DAL, Opts, Val, false));
398       continue;
399     }
400 
401     DAL->append(A);
402   }
403 
404   // Enforce -static if -miamcu is present.
405   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
406     DAL->AddFlagArg(0, Opts.getOption(options::OPT_static));
407 
408 // Add a default value of -mlinker-version=, if one was given and the user
409 // didn't specify one.
410 #if defined(HOST_LINK_VERSION)
411   if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
412       strlen(HOST_LINK_VERSION) > 0) {
413     DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ),
414                       HOST_LINK_VERSION);
415     DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
416   }
417 #endif
418 
419   return DAL;
420 }
421 
422 /// Compute target triple from args.
423 ///
424 /// This routine provides the logic to compute a target triple from various
425 /// args passed to the driver and the default triple string.
426 static llvm::Triple computeTargetTriple(const Driver &D,
427                                         StringRef TargetTriple,
428                                         const ArgList &Args,
429                                         StringRef DarwinArchName = "") {
430   // FIXME: Already done in Compilation *Driver::BuildCompilation
431   if (const Arg *A = Args.getLastArg(options::OPT_target))
432     TargetTriple = A->getValue();
433 
434   llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
435 
436   // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
437   // -gnu* only, and we can not change this, so we have to detect that case as
438   // being the Hurd OS.
439   if (TargetTriple.find("-unknown-gnu") != StringRef::npos ||
440       TargetTriple.find("-pc-gnu") != StringRef::npos)
441     Target.setOSName("hurd");
442 
443   // Handle Apple-specific options available here.
444   if (Target.isOSBinFormatMachO()) {
445     // If an explicit Darwin arch name is given, that trumps all.
446     if (!DarwinArchName.empty()) {
447       tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
448       return Target;
449     }
450 
451     // Handle the Darwin '-arch' flag.
452     if (Arg *A = Args.getLastArg(options::OPT_arch)) {
453       StringRef ArchName = A->getValue();
454       tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
455     }
456   }
457 
458   // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
459   // '-mbig-endian'/'-EB'.
460   if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
461                                options::OPT_mbig_endian)) {
462     if (A->getOption().matches(options::OPT_mlittle_endian)) {
463       llvm::Triple LE = Target.getLittleEndianArchVariant();
464       if (LE.getArch() != llvm::Triple::UnknownArch)
465         Target = std::move(LE);
466     } else {
467       llvm::Triple BE = Target.getBigEndianArchVariant();
468       if (BE.getArch() != llvm::Triple::UnknownArch)
469         Target = std::move(BE);
470     }
471   }
472 
473   // Skip further flag support on OSes which don't support '-m32' or '-m64'.
474   if (Target.getArch() == llvm::Triple::tce ||
475       Target.getOS() == llvm::Triple::Minix)
476     return Target;
477 
478   // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
479   Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
480                            options::OPT_m32, options::OPT_m16);
481   if (A) {
482     llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
483 
484     if (A->getOption().matches(options::OPT_m64)) {
485       AT = Target.get64BitArchVariant().getArch();
486       if (Target.getEnvironment() == llvm::Triple::GNUX32)
487         Target.setEnvironment(llvm::Triple::GNU);
488     } else if (A->getOption().matches(options::OPT_mx32) &&
489                Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
490       AT = llvm::Triple::x86_64;
491       Target.setEnvironment(llvm::Triple::GNUX32);
492     } else if (A->getOption().matches(options::OPT_m32)) {
493       AT = Target.get32BitArchVariant().getArch();
494       if (Target.getEnvironment() == llvm::Triple::GNUX32)
495         Target.setEnvironment(llvm::Triple::GNU);
496     } else if (A->getOption().matches(options::OPT_m16) &&
497                Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
498       AT = llvm::Triple::x86;
499       Target.setEnvironment(llvm::Triple::CODE16);
500     }
501 
502     if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
503       Target.setArch(AT);
504   }
505 
506   // Handle -miamcu flag.
507   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
508     if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
509       D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
510                                                        << Target.str();
511 
512     if (A && !A->getOption().matches(options::OPT_m32))
513       D.Diag(diag::err_drv_argument_not_allowed_with)
514           << "-miamcu" << A->getBaseArg().getAsString(Args);
515 
516     Target.setArch(llvm::Triple::x86);
517     Target.setArchName("i586");
518     Target.setEnvironment(llvm::Triple::UnknownEnvironment);
519     Target.setEnvironmentName("");
520     Target.setOS(llvm::Triple::ELFIAMCU);
521     Target.setVendor(llvm::Triple::UnknownVendor);
522     Target.setVendorName("intel");
523   }
524 
525   // If target is MIPS adjust the target triple
526   // accordingly to provided ABI name.
527   A = Args.getLastArg(options::OPT_mabi_EQ);
528   if (A && Target.isMIPS()) {
529     StringRef ABIName = A->getValue();
530     if (ABIName == "32") {
531       Target = Target.get32BitArchVariant();
532       if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
533           Target.getEnvironment() == llvm::Triple::GNUABIN32)
534         Target.setEnvironment(llvm::Triple::GNU);
535     } else if (ABIName == "n32") {
536       Target = Target.get64BitArchVariant();
537       if (Target.getEnvironment() == llvm::Triple::GNU ||
538           Target.getEnvironment() == llvm::Triple::GNUABI64)
539         Target.setEnvironment(llvm::Triple::GNUABIN32);
540     } else if (ABIName == "64") {
541       Target = Target.get64BitArchVariant();
542       if (Target.getEnvironment() == llvm::Triple::GNU ||
543           Target.getEnvironment() == llvm::Triple::GNUABIN32)
544         Target.setEnvironment(llvm::Triple::GNUABI64);
545     }
546   }
547 
548   // If target is RISC-V adjust the target triple according to
549   // provided architecture name
550   A = Args.getLastArg(options::OPT_march_EQ);
551   if (A && Target.isRISCV()) {
552     StringRef ArchName = A->getValue();
553     if (ArchName.startswith_lower("rv32"))
554       Target.setArch(llvm::Triple::riscv32);
555     else if (ArchName.startswith_lower("rv64"))
556       Target.setArch(llvm::Triple::riscv64);
557   }
558 
559   return Target;
560 }
561 
562 // Parse the LTO options and record the type of LTO compilation
563 // based on which -f(no-)?lto(=.*)? option occurs last.
564 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
565   LTOMode = LTOK_None;
566   if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
567                     options::OPT_fno_lto, false))
568     return;
569 
570   StringRef LTOName("full");
571 
572   const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
573   if (A)
574     LTOName = A->getValue();
575 
576   LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
577                 .Case("full", LTOK_Full)
578                 .Case("thin", LTOK_Thin)
579                 .Default(LTOK_Unknown);
580 
581   if (LTOMode == LTOK_Unknown) {
582     assert(A);
583     Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
584                                                     << A->getValue();
585   }
586 }
587 
588 /// Compute the desired OpenMP runtime from the flags provided.
589 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
590   StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
591 
592   const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
593   if (A)
594     RuntimeName = A->getValue();
595 
596   auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
597                 .Case("libomp", OMPRT_OMP)
598                 .Case("libgomp", OMPRT_GOMP)
599                 .Case("libiomp5", OMPRT_IOMP5)
600                 .Default(OMPRT_Unknown);
601 
602   if (RT == OMPRT_Unknown) {
603     if (A)
604       Diag(diag::err_drv_unsupported_option_argument)
605           << A->getOption().getName() << A->getValue();
606     else
607       // FIXME: We could use a nicer diagnostic here.
608       Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
609   }
610 
611   return RT;
612 }
613 
614 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
615                                               InputList &Inputs) {
616 
617   //
618   // CUDA/HIP
619   //
620   // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
621   // or HIP type. However, mixed CUDA/HIP compilation is not supported.
622   bool IsCuda =
623       llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
624         return types::isCuda(I.first);
625       });
626   bool IsHIP =
627       llvm::any_of(Inputs,
628                    [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
629                      return types::isHIP(I.first);
630                    }) ||
631       C.getInputArgs().hasArg(options::OPT_hip_link);
632   if (IsCuda && IsHIP) {
633     Diag(clang::diag::err_drv_mix_cuda_hip);
634     return;
635   }
636   if (IsCuda) {
637     const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
638     const llvm::Triple &HostTriple = HostTC->getTriple();
639     StringRef DeviceTripleStr;
640     auto OFK = Action::OFK_Cuda;
641     DeviceTripleStr =
642         HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" : "nvptx-nvidia-cuda";
643     llvm::Triple CudaTriple(DeviceTripleStr);
644     // Use the CUDA and host triples as the key into the ToolChains map,
645     // because the device toolchain we create depends on both.
646     auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
647     if (!CudaTC) {
648       CudaTC = std::make_unique<toolchains::CudaToolChain>(
649           *this, CudaTriple, *HostTC, C.getInputArgs(), OFK);
650     }
651     C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
652   } else if (IsHIP) {
653     const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
654     const llvm::Triple &HostTriple = HostTC->getTriple();
655     StringRef DeviceTripleStr;
656     auto OFK = Action::OFK_HIP;
657     DeviceTripleStr = "amdgcn-amd-amdhsa";
658     llvm::Triple HIPTriple(DeviceTripleStr);
659     // Use the HIP and host triples as the key into the ToolChains map,
660     // because the device toolchain we create depends on both.
661     auto &HIPTC = ToolChains[HIPTriple.str() + "/" + HostTriple.str()];
662     if (!HIPTC) {
663       HIPTC = std::make_unique<toolchains::HIPToolChain>(
664           *this, HIPTriple, *HostTC, C.getInputArgs());
665     }
666     C.addOffloadDeviceToolChain(HIPTC.get(), OFK);
667   }
668 
669   //
670   // OpenMP
671   //
672   // We need to generate an OpenMP toolchain if the user specified targets with
673   // the -fopenmp-targets option.
674   if (Arg *OpenMPTargets =
675           C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
676     if (OpenMPTargets->getNumValues()) {
677       // We expect that -fopenmp-targets is always used in conjunction with the
678       // option -fopenmp specifying a valid runtime with offloading support,
679       // i.e. libomp or libiomp.
680       bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
681           options::OPT_fopenmp, options::OPT_fopenmp_EQ,
682           options::OPT_fno_openmp, false);
683       if (HasValidOpenMPRuntime) {
684         OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
685         HasValidOpenMPRuntime =
686             OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
687       }
688 
689       if (HasValidOpenMPRuntime) {
690         llvm::StringMap<const char *> FoundNormalizedTriples;
691         for (const char *Val : OpenMPTargets->getValues()) {
692           llvm::Triple TT(Val);
693           std::string NormalizedName = TT.normalize();
694 
695           // Make sure we don't have a duplicate triple.
696           auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
697           if (Duplicate != FoundNormalizedTriples.end()) {
698             Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
699                 << Val << Duplicate->second;
700             continue;
701           }
702 
703           // Store the current triple so that we can check for duplicates in the
704           // following iterations.
705           FoundNormalizedTriples[NormalizedName] = Val;
706 
707           // If the specified target is invalid, emit a diagnostic.
708           if (TT.getArch() == llvm::Triple::UnknownArch)
709             Diag(clang::diag::err_drv_invalid_omp_target) << Val;
710           else {
711             const ToolChain *TC;
712             // CUDA toolchains have to be selected differently. They pair host
713             // and device in their implementation.
714             if (TT.isNVPTX()) {
715               const ToolChain *HostTC =
716                   C.getSingleOffloadToolChain<Action::OFK_Host>();
717               assert(HostTC && "Host toolchain should be always defined.");
718               auto &CudaTC =
719                   ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
720               if (!CudaTC)
721                 CudaTC = std::make_unique<toolchains::CudaToolChain>(
722                     *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
723               TC = CudaTC.get();
724             } else
725               TC = &getToolChain(C.getInputArgs(), TT);
726             C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
727           }
728         }
729       } else
730         Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
731     } else
732       Diag(clang::diag::warn_drv_empty_joined_argument)
733           << OpenMPTargets->getAsString(C.getInputArgs());
734   }
735 
736   //
737   // TODO: Add support for other offloading programming models here.
738   //
739 }
740 
741 /// Looks the given directories for the specified file.
742 ///
743 /// \param[out] FilePath File path, if the file was found.
744 /// \param[in]  Dirs Directories used for the search.
745 /// \param[in]  FileName Name of the file to search for.
746 /// \return True if file was found.
747 ///
748 /// Looks for file specified by FileName sequentially in directories specified
749 /// by Dirs.
750 ///
751 static bool searchForFile(SmallVectorImpl<char> &FilePath,
752                           ArrayRef<std::string> Dirs,
753                           StringRef FileName) {
754   SmallString<128> WPath;
755   for (const std::string &Dir : Dirs) {
756     if (Dir.empty())
757       continue;
758     WPath.clear();
759     llvm::sys::path::append(WPath, Dir, FileName);
760     llvm::sys::path::native(WPath);
761     if (llvm::sys::fs::is_regular_file(WPath)) {
762       FilePath = std::move(WPath);
763       return true;
764     }
765   }
766   return false;
767 }
768 
769 bool Driver::readConfigFile(StringRef FileName) {
770   // Try reading the given file.
771   SmallVector<const char *, 32> NewCfgArgs;
772   if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
773     Diag(diag::err_drv_cannot_read_config_file) << FileName;
774     return true;
775   }
776 
777   // Read options from config file.
778   llvm::SmallString<128> CfgFileName(FileName);
779   llvm::sys::path::native(CfgFileName);
780   ConfigFile = std::string(CfgFileName.str());
781   bool ContainErrors;
782   CfgOptions = std::make_unique<InputArgList>(
783       ParseArgStrings(NewCfgArgs, IsCLMode(), ContainErrors));
784   if (ContainErrors) {
785     CfgOptions.reset();
786     return true;
787   }
788 
789   if (CfgOptions->hasArg(options::OPT_config)) {
790     CfgOptions.reset();
791     Diag(diag::err_drv_nested_config_file);
792     return true;
793   }
794 
795   // Claim all arguments that come from a configuration file so that the driver
796   // does not warn on any that is unused.
797   for (Arg *A : *CfgOptions)
798     A->claim();
799   return false;
800 }
801 
802 bool Driver::loadConfigFile() {
803   std::string CfgFileName;
804   bool FileSpecifiedExplicitly = false;
805 
806   // Process options that change search path for config files.
807   if (CLOptions) {
808     if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
809       SmallString<128> CfgDir;
810       CfgDir.append(
811           CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
812       if (!CfgDir.empty()) {
813         if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
814           SystemConfigDir.clear();
815         else
816           SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
817       }
818     }
819     if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
820       SmallString<128> CfgDir;
821       CfgDir.append(
822           CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
823       if (!CfgDir.empty()) {
824         if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
825           UserConfigDir.clear();
826         else
827           UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
828       }
829     }
830   }
831 
832   // First try to find config file specified in command line.
833   if (CLOptions) {
834     std::vector<std::string> ConfigFiles =
835         CLOptions->getAllArgValues(options::OPT_config);
836     if (ConfigFiles.size() > 1) {
837       if (!std::all_of(
838               ConfigFiles.begin(), ConfigFiles.end(),
839               [ConfigFiles](std::string s) { return s == ConfigFiles[0]; })) {
840         Diag(diag::err_drv_duplicate_config);
841         return true;
842       }
843     }
844 
845     if (!ConfigFiles.empty()) {
846       CfgFileName = ConfigFiles.front();
847       assert(!CfgFileName.empty());
848 
849       // If argument contains directory separator, treat it as a path to
850       // configuration file.
851       if (llvm::sys::path::has_parent_path(CfgFileName)) {
852         SmallString<128> CfgFilePath;
853         if (llvm::sys::path::is_relative(CfgFileName))
854           llvm::sys::fs::current_path(CfgFilePath);
855         llvm::sys::path::append(CfgFilePath, CfgFileName);
856         if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
857           Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
858           return true;
859         }
860         return readConfigFile(CfgFilePath);
861       }
862 
863       FileSpecifiedExplicitly = true;
864     }
865   }
866 
867   // If config file is not specified explicitly, try to deduce configuration
868   // from executable name. For instance, an executable 'armv7l-clang' will
869   // search for config file 'armv7l-clang.cfg'.
870   if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
871     CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
872 
873   if (CfgFileName.empty())
874     return false;
875 
876   // Determine architecture part of the file name, if it is present.
877   StringRef CfgFileArch = CfgFileName;
878   size_t ArchPrefixLen = CfgFileArch.find('-');
879   if (ArchPrefixLen == StringRef::npos)
880     ArchPrefixLen = CfgFileArch.size();
881   llvm::Triple CfgTriple;
882   CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
883   CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
884   if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
885     ArchPrefixLen = 0;
886 
887   if (!StringRef(CfgFileName).endswith(".cfg"))
888     CfgFileName += ".cfg";
889 
890   // If config file starts with architecture name and command line options
891   // redefine architecture (with options like -m32 -LE etc), try finding new
892   // config file with that architecture.
893   SmallString<128> FixedConfigFile;
894   size_t FixedArchPrefixLen = 0;
895   if (ArchPrefixLen) {
896     // Get architecture name from config file name like 'i386.cfg' or
897     // 'armv7l-clang.cfg'.
898     // Check if command line options changes effective triple.
899     llvm::Triple EffectiveTriple = computeTargetTriple(*this,
900                                              CfgTriple.getTriple(), *CLOptions);
901     if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
902       FixedConfigFile = EffectiveTriple.getArchName();
903       FixedArchPrefixLen = FixedConfigFile.size();
904       // Append the rest of original file name so that file name transforms
905       // like: i386-clang.cfg -> x86_64-clang.cfg.
906       if (ArchPrefixLen < CfgFileName.size())
907         FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
908     }
909   }
910 
911   // Prepare list of directories where config file is searched for.
912   SmallVector<std::string, 3> CfgFileSearchDirs;
913   CfgFileSearchDirs.push_back(UserConfigDir);
914   CfgFileSearchDirs.push_back(SystemConfigDir);
915   CfgFileSearchDirs.push_back(Dir);
916 
917   // Try to find config file. First try file with corrected architecture.
918   llvm::SmallString<128> CfgFilePath;
919   if (!FixedConfigFile.empty()) {
920     if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
921       return readConfigFile(CfgFilePath);
922     // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
923     FixedConfigFile.resize(FixedArchPrefixLen);
924     FixedConfigFile.append(".cfg");
925     if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
926       return readConfigFile(CfgFilePath);
927   }
928 
929   // Then try original file name.
930   if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
931     return readConfigFile(CfgFilePath);
932 
933   // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
934   if (!ClangNameParts.ModeSuffix.empty() &&
935       !ClangNameParts.TargetPrefix.empty()) {
936     CfgFileName.assign(ClangNameParts.TargetPrefix);
937     CfgFileName.append(".cfg");
938     if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
939       return readConfigFile(CfgFilePath);
940   }
941 
942   // Report error but only if config file was specified explicitly, by option
943   // --config. If it was deduced from executable name, it is not an error.
944   if (FileSpecifiedExplicitly) {
945     Diag(diag::err_drv_config_file_not_found) << CfgFileName;
946     for (const std::string &SearchDir : CfgFileSearchDirs)
947       if (!SearchDir.empty())
948         Diag(diag::note_drv_config_file_searched_in) << SearchDir;
949     return true;
950   }
951 
952   return false;
953 }
954 
955 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
956   llvm::PrettyStackTraceString CrashInfo("Compilation construction");
957 
958   // FIXME: Handle environment options which affect driver behavior, somewhere
959   // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
960 
961   if (Optional<std::string> CompilerPathValue =
962           llvm::sys::Process::GetEnv("COMPILER_PATH")) {
963     StringRef CompilerPath = *CompilerPathValue;
964     while (!CompilerPath.empty()) {
965       std::pair<StringRef, StringRef> Split =
966           CompilerPath.split(llvm::sys::EnvPathSeparator);
967       PrefixDirs.push_back(std::string(Split.first));
968       CompilerPath = Split.second;
969     }
970   }
971 
972   // We look for the driver mode option early, because the mode can affect
973   // how other options are parsed.
974   ParseDriverMode(ClangExecutable, ArgList.slice(1));
975 
976   // FIXME: What are we going to do with -V and -b?
977 
978   // Arguments specified in command line.
979   bool ContainsError;
980   CLOptions = std::make_unique<InputArgList>(
981       ParseArgStrings(ArgList.slice(1), IsCLMode(), ContainsError));
982 
983   // Try parsing configuration file.
984   if (!ContainsError)
985     ContainsError = loadConfigFile();
986   bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
987 
988   // All arguments, from both config file and command line.
989   InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
990                                               : std::move(*CLOptions));
991 
992   // The args for config files or /clang: flags belong to different InputArgList
993   // objects than Args. This copies an Arg from one of those other InputArgLists
994   // to the ownership of Args.
995   auto appendOneArg = [&Args](const Arg *Opt, const Arg *BaseArg) {
996       unsigned Index = Args.MakeIndex(Opt->getSpelling());
997       Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
998                                      Index, BaseArg);
999       Copy->getValues() = Opt->getValues();
1000       if (Opt->isClaimed())
1001         Copy->claim();
1002       Args.append(Copy);
1003   };
1004 
1005   if (HasConfigFile)
1006     for (auto *Opt : *CLOptions) {
1007       if (Opt->getOption().matches(options::OPT_config))
1008         continue;
1009       const Arg *BaseArg = &Opt->getBaseArg();
1010       if (BaseArg == Opt)
1011         BaseArg = nullptr;
1012       appendOneArg(Opt, BaseArg);
1013     }
1014 
1015   // In CL mode, look for any pass-through arguments
1016   if (IsCLMode() && !ContainsError) {
1017     SmallVector<const char *, 16> CLModePassThroughArgList;
1018     for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
1019       A->claim();
1020       CLModePassThroughArgList.push_back(A->getValue());
1021     }
1022 
1023     if (!CLModePassThroughArgList.empty()) {
1024       // Parse any pass through args using default clang processing rather
1025       // than clang-cl processing.
1026       auto CLModePassThroughOptions = std::make_unique<InputArgList>(
1027           ParseArgStrings(CLModePassThroughArgList, false, ContainsError));
1028 
1029       if (!ContainsError)
1030         for (auto *Opt : *CLModePassThroughOptions) {
1031           appendOneArg(Opt, nullptr);
1032         }
1033     }
1034   }
1035 
1036   // Check for working directory option before accessing any files
1037   if (Arg *WD = Args.getLastArg(options::OPT_working_directory))
1038     if (VFS->setCurrentWorkingDirectory(WD->getValue()))
1039       Diag(diag::err_drv_unable_to_set_working_directory) << WD->getValue();
1040 
1041   // FIXME: This stuff needs to go into the Compilation, not the driver.
1042   bool CCCPrintPhases;
1043 
1044   // Silence driver warnings if requested
1045   Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
1046 
1047   // -no-canonical-prefixes is used very early in main.
1048   Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
1049 
1050   // f(no-)integated-cc1 is also used very early in main.
1051   Args.ClaimAllArgs(options::OPT_fintegrated_cc1);
1052   Args.ClaimAllArgs(options::OPT_fno_integrated_cc1);
1053 
1054   // Ignore -pipe.
1055   Args.ClaimAllArgs(options::OPT_pipe);
1056 
1057   // Extract -ccc args.
1058   //
1059   // FIXME: We need to figure out where this behavior should live. Most of it
1060   // should be outside in the client; the parts that aren't should have proper
1061   // options, either by introducing new ones or by overloading gcc ones like -V
1062   // or -b.
1063   CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
1064   CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
1065   if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
1066     CCCGenericGCCName = A->getValue();
1067   GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
1068                                options::OPT_fno_crash_diagnostics,
1069                                !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
1070   // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
1071   // and getToolChain is const.
1072   if (IsCLMode()) {
1073     // clang-cl targets MSVC-style Win32.
1074     llvm::Triple T(TargetTriple);
1075     T.setOS(llvm::Triple::Win32);
1076     T.setVendor(llvm::Triple::PC);
1077     T.setEnvironment(llvm::Triple::MSVC);
1078     T.setObjectFormat(llvm::Triple::COFF);
1079     TargetTriple = T.str();
1080   }
1081   if (const Arg *A = Args.getLastArg(options::OPT_target))
1082     TargetTriple = A->getValue();
1083   if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
1084     Dir = InstalledDir = A->getValue();
1085   for (const Arg *A : Args.filtered(options::OPT_B)) {
1086     A->claim();
1087     PrefixDirs.push_back(A->getValue(0));
1088   }
1089   if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
1090     SysRoot = A->getValue();
1091   if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
1092     DyldPrefix = A->getValue();
1093 
1094   if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
1095     ResourceDir = A->getValue();
1096 
1097   if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
1098     SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1099                     .Case("cwd", SaveTempsCwd)
1100                     .Case("obj", SaveTempsObj)
1101                     .Default(SaveTempsCwd);
1102   }
1103 
1104   setLTOMode(Args);
1105 
1106   // Process -fembed-bitcode= flags.
1107   if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1108     StringRef Name = A->getValue();
1109     unsigned Model = llvm::StringSwitch<unsigned>(Name)
1110         .Case("off", EmbedNone)
1111         .Case("all", EmbedBitcode)
1112         .Case("bitcode", EmbedBitcode)
1113         .Case("marker", EmbedMarker)
1114         .Default(~0U);
1115     if (Model == ~0U) {
1116       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1117                                                 << Name;
1118     } else
1119       BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
1120   }
1121 
1122   std::unique_ptr<llvm::opt::InputArgList> UArgs =
1123       std::make_unique<InputArgList>(std::move(Args));
1124 
1125   // Perform the default argument translations.
1126   DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
1127 
1128   // Owned by the host.
1129   const ToolChain &TC = getToolChain(
1130       *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
1131 
1132   // The compilation takes ownership of Args.
1133   Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1134                                    ContainsError);
1135 
1136   if (!HandleImmediateArgs(*C))
1137     return C;
1138 
1139   // Construct the list of inputs.
1140   InputList Inputs;
1141   BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
1142 
1143   // Populate the tool chains for the offloading devices, if any.
1144   CreateOffloadingDeviceToolChains(*C, Inputs);
1145 
1146   // Construct the list of abstract actions to perform for this compilation. On
1147   // MachO targets this uses the driver-driver and universal actions.
1148   if (TC.getTriple().isOSBinFormatMachO())
1149     BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
1150   else
1151     BuildActions(*C, C->getArgs(), Inputs, C->getActions());
1152 
1153   if (CCCPrintPhases) {
1154     PrintActions(*C);
1155     return C;
1156   }
1157 
1158   BuildJobs(*C);
1159 
1160   return C;
1161 }
1162 
1163 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1164   llvm::opt::ArgStringList ASL;
1165   for (const auto *A : Args)
1166     A->render(Args, ASL);
1167 
1168   for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1169     if (I != ASL.begin())
1170       OS << ' ';
1171     llvm::sys::printArg(OS, *I, true);
1172   }
1173   OS << '\n';
1174 }
1175 
1176 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1177                                     SmallString<128> &CrashDiagDir) {
1178   using namespace llvm::sys;
1179   assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1180          "Only knows about .crash files on Darwin");
1181 
1182   // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1183   // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1184   // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1185   path::home_directory(CrashDiagDir);
1186   if (CrashDiagDir.startswith("/var/root"))
1187     CrashDiagDir = "/";
1188   path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1189   int PID =
1190 #if LLVM_ON_UNIX
1191       getpid();
1192 #else
1193       0;
1194 #endif
1195   std::error_code EC;
1196   fs::file_status FileStatus;
1197   TimePoint<> LastAccessTime;
1198   SmallString<128> CrashFilePath;
1199   // Lookup the .crash files and get the one generated by a subprocess spawned
1200   // by this driver invocation.
1201   for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1202        File != FileEnd && !EC; File.increment(EC)) {
1203     StringRef FileName = path::filename(File->path());
1204     if (!FileName.startswith(Name))
1205       continue;
1206     if (fs::status(File->path(), FileStatus))
1207       continue;
1208     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1209         llvm::MemoryBuffer::getFile(File->path());
1210     if (!CrashFile)
1211       continue;
1212     // The first line should start with "Process:", otherwise this isn't a real
1213     // .crash file.
1214     StringRef Data = CrashFile.get()->getBuffer();
1215     if (!Data.startswith("Process:"))
1216       continue;
1217     // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1218     size_t ParentProcPos = Data.find("Parent Process:");
1219     if (ParentProcPos == StringRef::npos)
1220       continue;
1221     size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1222     if (LineEnd == StringRef::npos)
1223       continue;
1224     StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1225     int OpenBracket = -1, CloseBracket = -1;
1226     for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1227       if (ParentProcess[i] == '[')
1228         OpenBracket = i;
1229       if (ParentProcess[i] == ']')
1230         CloseBracket = i;
1231     }
1232     // Extract the parent process PID from the .crash file and check whether
1233     // it matches this driver invocation pid.
1234     int CrashPID;
1235     if (OpenBracket < 0 || CloseBracket < 0 ||
1236         ParentProcess.slice(OpenBracket + 1, CloseBracket)
1237             .getAsInteger(10, CrashPID) || CrashPID != PID) {
1238       continue;
1239     }
1240 
1241     // Found a .crash file matching the driver pid. To avoid getting an older
1242     // and misleading crash file, continue looking for the most recent.
1243     // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1244     // multiple crashes poiting to the same parent process. Since the driver
1245     // does not collect pid information for the dispatched invocation there's
1246     // currently no way to distinguish among them.
1247     const auto FileAccessTime = FileStatus.getLastModificationTime();
1248     if (FileAccessTime > LastAccessTime) {
1249       CrashFilePath.assign(File->path());
1250       LastAccessTime = FileAccessTime;
1251     }
1252   }
1253 
1254   // If found, copy it over to the location of other reproducer files.
1255   if (!CrashFilePath.empty()) {
1256     EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1257     if (EC)
1258       return false;
1259     return true;
1260   }
1261 
1262   return false;
1263 }
1264 
1265 // When clang crashes, produce diagnostic information including the fully
1266 // preprocessed source file(s).  Request that the developer attach the
1267 // diagnostic information to a bug report.
1268 void Driver::generateCompilationDiagnostics(
1269     Compilation &C, const Command &FailingCommand,
1270     StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
1271   if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
1272     return;
1273 
1274   // Don't try to generate diagnostics for link or dsymutil jobs.
1275   if (FailingCommand.getCreator().isLinkJob() ||
1276       FailingCommand.getCreator().isDsymutilJob())
1277     return;
1278 
1279   // Print the version of the compiler.
1280   PrintVersion(C, llvm::errs());
1281 
1282   // Suppress driver output and emit preprocessor output to temp file.
1283   Mode = CPPMode;
1284   CCGenDiagnostics = true;
1285 
1286   // Save the original job command(s).
1287   Command Cmd = FailingCommand;
1288 
1289   // Keep track of whether we produce any errors while trying to produce
1290   // preprocessed sources.
1291   DiagnosticErrorTrap Trap(Diags);
1292 
1293   // Suppress tool output.
1294   C.initCompilationForDiagnostics();
1295 
1296   // Construct the list of inputs.
1297   InputList Inputs;
1298   BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
1299 
1300   for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
1301     bool IgnoreInput = false;
1302 
1303     // Ignore input from stdin or any inputs that cannot be preprocessed.
1304     // Check type first as not all linker inputs have a value.
1305     if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
1306       IgnoreInput = true;
1307     } else if (!strcmp(it->second->getValue(), "-")) {
1308       Diag(clang::diag::note_drv_command_failed_diag_msg)
1309           << "Error generating preprocessed source(s) - "
1310              "ignoring input from stdin.";
1311       IgnoreInput = true;
1312     }
1313 
1314     if (IgnoreInput) {
1315       it = Inputs.erase(it);
1316       ie = Inputs.end();
1317     } else {
1318       ++it;
1319     }
1320   }
1321 
1322   if (Inputs.empty()) {
1323     Diag(clang::diag::note_drv_command_failed_diag_msg)
1324         << "Error generating preprocessed source(s) - "
1325            "no preprocessable inputs.";
1326     return;
1327   }
1328 
1329   // Don't attempt to generate preprocessed files if multiple -arch options are
1330   // used, unless they're all duplicates.
1331   llvm::StringSet<> ArchNames;
1332   for (const Arg *A : C.getArgs()) {
1333     if (A->getOption().matches(options::OPT_arch)) {
1334       StringRef ArchName = A->getValue();
1335       ArchNames.insert(ArchName);
1336     }
1337   }
1338   if (ArchNames.size() > 1) {
1339     Diag(clang::diag::note_drv_command_failed_diag_msg)
1340         << "Error generating preprocessed source(s) - cannot generate "
1341            "preprocessed source with multiple -arch options.";
1342     return;
1343   }
1344 
1345   // Construct the list of abstract actions to perform for this compilation. On
1346   // Darwin OSes this uses the driver-driver and builds universal actions.
1347   const ToolChain &TC = C.getDefaultToolChain();
1348   if (TC.getTriple().isOSBinFormatMachO())
1349     BuildUniversalActions(C, TC, Inputs);
1350   else
1351     BuildActions(C, C.getArgs(), Inputs, C.getActions());
1352 
1353   BuildJobs(C);
1354 
1355   // If there were errors building the compilation, quit now.
1356   if (Trap.hasErrorOccurred()) {
1357     Diag(clang::diag::note_drv_command_failed_diag_msg)
1358         << "Error generating preprocessed source(s).";
1359     return;
1360   }
1361 
1362   // Generate preprocessed output.
1363   SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
1364   C.ExecuteJobs(C.getJobs(), FailingCommands);
1365 
1366   // If any of the preprocessing commands failed, clean up and exit.
1367   if (!FailingCommands.empty()) {
1368     Diag(clang::diag::note_drv_command_failed_diag_msg)
1369         << "Error generating preprocessed source(s).";
1370     return;
1371   }
1372 
1373   const ArgStringList &TempFiles = C.getTempFiles();
1374   if (TempFiles.empty()) {
1375     Diag(clang::diag::note_drv_command_failed_diag_msg)
1376         << "Error generating preprocessed source(s).";
1377     return;
1378   }
1379 
1380   Diag(clang::diag::note_drv_command_failed_diag_msg)
1381       << "\n********************\n\n"
1382          "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1383          "Preprocessed source(s) and associated run script(s) are located at:";
1384 
1385   SmallString<128> VFS;
1386   SmallString<128> ReproCrashFilename;
1387   for (const char *TempFile : TempFiles) {
1388     Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
1389     if (Report)
1390       Report->TemporaryFiles.push_back(TempFile);
1391     if (ReproCrashFilename.empty()) {
1392       ReproCrashFilename = TempFile;
1393       llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1394     }
1395     if (StringRef(TempFile).endswith(".cache")) {
1396       // In some cases (modules) we'll dump extra data to help with reproducing
1397       // the crash into a directory next to the output.
1398       VFS = llvm::sys::path::filename(TempFile);
1399       llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1400     }
1401   }
1402 
1403   // Assume associated files are based off of the first temporary file.
1404   CrashReportInfo CrashInfo(TempFiles[0], VFS);
1405 
1406   llvm::SmallString<128> Script(CrashInfo.Filename);
1407   llvm::sys::path::replace_extension(Script, "sh");
1408   std::error_code EC;
1409   llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew);
1410   if (EC) {
1411     Diag(clang::diag::note_drv_command_failed_diag_msg)
1412         << "Error generating run script: " << Script << " " << EC.message();
1413   } else {
1414     ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
1415              << "# Driver args: ";
1416     printArgList(ScriptOS, C.getInputArgs());
1417     ScriptOS << "# Original command: ";
1418     Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
1419     Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
1420     if (!AdditionalInformation.empty())
1421       ScriptOS << "\n# Additional information: " << AdditionalInformation
1422                << "\n";
1423     if (Report)
1424       Report->TemporaryFiles.push_back(std::string(Script.str()));
1425     Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
1426   }
1427 
1428   // On darwin, provide information about the .crash diagnostic report.
1429   if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1430     SmallString<128> CrashDiagDir;
1431     if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1432       Diag(clang::diag::note_drv_command_failed_diag_msg)
1433           << ReproCrashFilename.str();
1434     } else { // Suggest a directory for the user to look for .crash files.
1435       llvm::sys::path::append(CrashDiagDir, Name);
1436       CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1437       Diag(clang::diag::note_drv_command_failed_diag_msg)
1438           << "Crash backtrace is located in";
1439       Diag(clang::diag::note_drv_command_failed_diag_msg)
1440           << CrashDiagDir.str();
1441       Diag(clang::diag::note_drv_command_failed_diag_msg)
1442           << "(choose the .crash file that corresponds to your crash)";
1443     }
1444   }
1445 
1446   for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1447                                             options::OPT_frewrite_map_file_EQ))
1448     Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1449 
1450   Diag(clang::diag::note_drv_command_failed_diag_msg)
1451       << "\n\n********************";
1452 }
1453 
1454 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1455   // Since commandLineFitsWithinSystemLimits() may underestimate system's
1456   // capacity if the tool does not support response files, there is a chance/
1457   // that things will just work without a response file, so we silently just
1458   // skip it.
1459   if (Cmd.getResponseFileSupport().ResponseKind ==
1460           ResponseFileSupport::RF_None ||
1461       llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(),
1462                                                    Cmd.getArguments()))
1463     return;
1464 
1465   std::string TmpName = GetTemporaryPath("response", "txt");
1466   Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1467 }
1468 
1469 int Driver::ExecuteCompilation(
1470     Compilation &C,
1471     SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1472   // Just print if -### was present.
1473   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1474     C.getJobs().Print(llvm::errs(), "\n", true);
1475     return 0;
1476   }
1477 
1478   // If there were errors building the compilation, quit now.
1479   if (Diags.hasErrorOccurred())
1480     return 1;
1481 
1482   // Set up response file names for each command, if necessary
1483   for (auto &Job : C.getJobs())
1484     setUpResponseFiles(C, Job);
1485 
1486   C.ExecuteJobs(C.getJobs(), FailingCommands);
1487 
1488   // If the command succeeded, we are done.
1489   if (FailingCommands.empty())
1490     return 0;
1491 
1492   // Otherwise, remove result files and print extra information about abnormal
1493   // failures.
1494   int Res = 0;
1495   for (const auto &CmdPair : FailingCommands) {
1496     int CommandRes = CmdPair.first;
1497     const Command *FailingCommand = CmdPair.second;
1498 
1499     // Remove result files if we're not saving temps.
1500     if (!isSaveTempsEnabled()) {
1501       const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1502       C.CleanupFileMap(C.getResultFiles(), JA, true);
1503 
1504       // Failure result files are valid unless we crashed.
1505       if (CommandRes < 0)
1506         C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1507     }
1508 
1509 #if LLVM_ON_UNIX
1510     // llvm/lib/Support/Unix/Signals.inc will exit with a special return code
1511     // for SIGPIPE. Do not print diagnostics for this case.
1512     if (CommandRes == EX_IOERR) {
1513       Res = CommandRes;
1514       continue;
1515     }
1516 #endif
1517 
1518     // Print extra information about abnormal failures, if possible.
1519     //
1520     // This is ad-hoc, but we don't want to be excessively noisy. If the result
1521     // status was 1, assume the command failed normally. In particular, if it
1522     // was the compiler then assume it gave a reasonable error code. Failures
1523     // in other tools are less common, and they generally have worse
1524     // diagnostics, so always print the diagnostic there.
1525     const Tool &FailingTool = FailingCommand->getCreator();
1526 
1527     if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
1528       // FIXME: See FIXME above regarding result code interpretation.
1529       if (CommandRes < 0)
1530         Diag(clang::diag::err_drv_command_signalled)
1531             << FailingTool.getShortName();
1532       else
1533         Diag(clang::diag::err_drv_command_failed)
1534             << FailingTool.getShortName() << CommandRes;
1535     }
1536   }
1537   return Res;
1538 }
1539 
1540 void Driver::PrintHelp(bool ShowHidden) const {
1541   unsigned IncludedFlagsBitmask;
1542   unsigned ExcludedFlagsBitmask;
1543   std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1544       getIncludeExcludeOptionFlagMasks(IsCLMode());
1545 
1546   ExcludedFlagsBitmask |= options::NoDriverOption;
1547   if (!ShowHidden)
1548     ExcludedFlagsBitmask |= HelpHidden;
1549 
1550   std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1551   getOpts().PrintHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
1552                       IncludedFlagsBitmask, ExcludedFlagsBitmask,
1553                       /*ShowAllAliases=*/false);
1554 }
1555 
1556 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1557   // FIXME: The following handlers should use a callback mechanism, we don't
1558   // know what the client would like to do.
1559   OS << getClangFullVersion() << '\n';
1560   const ToolChain &TC = C.getDefaultToolChain();
1561   OS << "Target: " << TC.getTripleString() << '\n';
1562 
1563   // Print the threading model.
1564   if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1565     // Don't print if the ToolChain would have barfed on it already
1566     if (TC.isThreadModelSupported(A->getValue()))
1567       OS << "Thread model: " << A->getValue();
1568   } else
1569     OS << "Thread model: " << TC.getThreadModel();
1570   OS << '\n';
1571 
1572   // Print out the install directory.
1573   OS << "InstalledDir: " << InstalledDir << '\n';
1574 
1575   // If configuration file was used, print its path.
1576   if (!ConfigFile.empty())
1577     OS << "Configuration file: " << ConfigFile << '\n';
1578 }
1579 
1580 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1581 /// option.
1582 static void PrintDiagnosticCategories(raw_ostream &OS) {
1583   // Skip the empty category.
1584   for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1585        ++i)
1586     OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1587 }
1588 
1589 void Driver::HandleAutocompletions(StringRef PassedFlags) const {
1590   if (PassedFlags == "")
1591     return;
1592   // Print out all options that start with a given argument. This is used for
1593   // shell autocompletion.
1594   std::vector<std::string> SuggestedCompletions;
1595   std::vector<std::string> Flags;
1596 
1597   unsigned short DisableFlags =
1598       options::NoDriverOption | options::Unsupported | options::Ignored;
1599 
1600   // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
1601   // because the latter indicates that the user put space before pushing tab
1602   // which should end up in a file completion.
1603   const bool HasSpace = PassedFlags.endswith(",");
1604 
1605   // Parse PassedFlags by "," as all the command-line flags are passed to this
1606   // function separated by ","
1607   StringRef TargetFlags = PassedFlags;
1608   while (TargetFlags != "") {
1609     StringRef CurFlag;
1610     std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1611     Flags.push_back(std::string(CurFlag));
1612   }
1613 
1614   // We want to show cc1-only options only when clang is invoked with -cc1 or
1615   // -Xclang.
1616   if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1"))
1617     DisableFlags &= ~options::NoDriverOption;
1618 
1619   const llvm::opt::OptTable &Opts = getOpts();
1620   StringRef Cur;
1621   Cur = Flags.at(Flags.size() - 1);
1622   StringRef Prev;
1623   if (Flags.size() >= 2) {
1624     Prev = Flags.at(Flags.size() - 2);
1625     SuggestedCompletions = Opts.suggestValueCompletions(Prev, Cur);
1626   }
1627 
1628   if (SuggestedCompletions.empty())
1629     SuggestedCompletions = Opts.suggestValueCompletions(Cur, "");
1630 
1631   // If Flags were empty, it means the user typed `clang [tab]` where we should
1632   // list all possible flags. If there was no value completion and the user
1633   // pressed tab after a space, we should fall back to a file completion.
1634   // We're printing a newline to be consistent with what we print at the end of
1635   // this function.
1636   if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
1637     llvm::outs() << '\n';
1638     return;
1639   }
1640 
1641   // When flag ends with '=' and there was no value completion, return empty
1642   // string and fall back to the file autocompletion.
1643   if (SuggestedCompletions.empty() && !Cur.endswith("=")) {
1644     // If the flag is in the form of "--autocomplete=-foo",
1645     // we were requested to print out all option names that start with "-foo".
1646     // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
1647     SuggestedCompletions = Opts.findByPrefix(Cur, DisableFlags);
1648 
1649     // We have to query the -W flags manually as they're not in the OptTable.
1650     // TODO: Find a good way to add them to OptTable instead and them remove
1651     // this code.
1652     for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
1653       if (S.startswith(Cur))
1654         SuggestedCompletions.push_back(std::string(S));
1655   }
1656 
1657   // Sort the autocomplete candidates so that shells print them out in a
1658   // deterministic order. We could sort in any way, but we chose
1659   // case-insensitive sorting for consistency with the -help option
1660   // which prints out options in the case-insensitive alphabetical order.
1661   llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
1662     if (int X = A.compare_lower(B))
1663       return X < 0;
1664     return A.compare(B) > 0;
1665   });
1666 
1667   llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1668 }
1669 
1670 bool Driver::HandleImmediateArgs(const Compilation &C) {
1671   // The order these options are handled in gcc is all over the place, but we
1672   // don't expect inconsistencies w.r.t. that to matter in practice.
1673 
1674   if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1675     llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1676     return false;
1677   }
1678 
1679   if (C.getArgs().hasArg(options::OPT_dumpversion)) {
1680     // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1681     // return an answer which matches our definition of __VERSION__.
1682     llvm::outs() << CLANG_VERSION_STRING << "\n";
1683     return false;
1684   }
1685 
1686   if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1687     PrintDiagnosticCategories(llvm::outs());
1688     return false;
1689   }
1690 
1691   if (C.getArgs().hasArg(options::OPT_help) ||
1692       C.getArgs().hasArg(options::OPT__help_hidden)) {
1693     PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
1694     return false;
1695   }
1696 
1697   if (C.getArgs().hasArg(options::OPT__version)) {
1698     // Follow gcc behavior and use stdout for --version and stderr for -v.
1699     PrintVersion(C, llvm::outs());
1700     return false;
1701   }
1702 
1703   if (C.getArgs().hasArg(options::OPT_v) ||
1704       C.getArgs().hasArg(options::OPT__HASH_HASH_HASH) ||
1705       C.getArgs().hasArg(options::OPT_print_supported_cpus)) {
1706     PrintVersion(C, llvm::errs());
1707     SuppressMissingInputWarning = true;
1708   }
1709 
1710   if (C.getArgs().hasArg(options::OPT_v)) {
1711     if (!SystemConfigDir.empty())
1712       llvm::errs() << "System configuration file directory: "
1713                    << SystemConfigDir << "\n";
1714     if (!UserConfigDir.empty())
1715       llvm::errs() << "User configuration file directory: "
1716                    << UserConfigDir << "\n";
1717   }
1718 
1719   const ToolChain &TC = C.getDefaultToolChain();
1720 
1721   if (C.getArgs().hasArg(options::OPT_v))
1722     TC.printVerboseInfo(llvm::errs());
1723 
1724   if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
1725     llvm::outs() << ResourceDir << '\n';
1726     return false;
1727   }
1728 
1729   if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1730     llvm::outs() << "programs: =";
1731     bool separator = false;
1732     for (const std::string &Path : TC.getProgramPaths()) {
1733       if (separator)
1734         llvm::outs() << llvm::sys::EnvPathSeparator;
1735       llvm::outs() << Path;
1736       separator = true;
1737     }
1738     llvm::outs() << "\n";
1739     llvm::outs() << "libraries: =" << ResourceDir;
1740 
1741     StringRef sysroot = C.getSysRoot();
1742 
1743     for (const std::string &Path : TC.getFilePaths()) {
1744       // Always print a separator. ResourceDir was the first item shown.
1745       llvm::outs() << llvm::sys::EnvPathSeparator;
1746       // Interpretation of leading '=' is needed only for NetBSD.
1747       if (Path[0] == '=')
1748         llvm::outs() << sysroot << Path.substr(1);
1749       else
1750         llvm::outs() << Path;
1751     }
1752     llvm::outs() << "\n";
1753     return false;
1754   }
1755 
1756   // FIXME: The following handlers should use a callback mechanism, we don't
1757   // know what the client would like to do.
1758   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
1759     llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
1760     return false;
1761   }
1762 
1763   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
1764     StringRef ProgName = A->getValue();
1765 
1766     // Null program name cannot have a path.
1767     if (! ProgName.empty())
1768       llvm::outs() << GetProgramPath(ProgName, TC);
1769 
1770     llvm::outs() << "\n";
1771     return false;
1772   }
1773 
1774   if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
1775     StringRef PassedFlags = A->getValue();
1776     HandleAutocompletions(PassedFlags);
1777     return false;
1778   }
1779 
1780   if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
1781     ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1782     const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1783     RegisterEffectiveTriple TripleRAII(TC, Triple);
1784     switch (RLT) {
1785     case ToolChain::RLT_CompilerRT:
1786       llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1787       break;
1788     case ToolChain::RLT_Libgcc:
1789       llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1790       break;
1791     }
1792     return false;
1793   }
1794 
1795   if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
1796     for (const Multilib &Multilib : TC.getMultilibs())
1797       llvm::outs() << Multilib << "\n";
1798     return false;
1799   }
1800 
1801   if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
1802     const Multilib &Multilib = TC.getMultilib();
1803     if (Multilib.gccSuffix().empty())
1804       llvm::outs() << ".\n";
1805     else {
1806       StringRef Suffix(Multilib.gccSuffix());
1807       assert(Suffix.front() == '/');
1808       llvm::outs() << Suffix.substr(1) << "\n";
1809     }
1810     return false;
1811   }
1812 
1813   if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
1814     llvm::outs() << TC.getTripleString() << "\n";
1815     return false;
1816   }
1817 
1818   if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
1819     const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1820     llvm::outs() << Triple.getTriple() << "\n";
1821     return false;
1822   }
1823 
1824   if (C.getArgs().hasArg(options::OPT_print_targets)) {
1825     llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
1826     return false;
1827   }
1828 
1829   return true;
1830 }
1831 
1832 enum {
1833   TopLevelAction = 0,
1834   HeadSibAction = 1,
1835   OtherSibAction = 2,
1836 };
1837 
1838 // Display an action graph human-readably.  Action A is the "sink" node
1839 // and latest-occuring action. Traversal is in pre-order, visiting the
1840 // inputs to each action before printing the action itself.
1841 static unsigned PrintActions1(const Compilation &C, Action *A,
1842                               std::map<Action *, unsigned> &Ids,
1843                               Twine Indent = {}, int Kind = TopLevelAction) {
1844   if (Ids.count(A)) // A was already visited.
1845     return Ids[A];
1846 
1847   std::string str;
1848   llvm::raw_string_ostream os(str);
1849 
1850   auto getSibIndent = [](int K) -> Twine {
1851     return (K == HeadSibAction) ? "   " : (K == OtherSibAction) ? "|  " : "";
1852   };
1853 
1854   Twine SibIndent = Indent + getSibIndent(Kind);
1855   int SibKind = HeadSibAction;
1856   os << Action::getClassName(A->getKind()) << ", ";
1857   if (InputAction *IA = dyn_cast<InputAction>(A)) {
1858     os << "\"" << IA->getInputArg().getValue() << "\"";
1859   } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1860     os << '"' << BIA->getArchName() << '"' << ", {"
1861        << PrintActions1(C, *BIA->input_begin(), Ids, SibIndent, SibKind) << "}";
1862   } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1863     bool IsFirst = true;
1864     OA->doOnEachDependence(
1865         [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1866           assert(TC && "Unknown host toolchain");
1867           // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1868           // sm_35 this will generate:
1869           // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1870           // (nvptx64-nvidia-cuda:sm_35) {#ID}
1871           if (!IsFirst)
1872             os << ", ";
1873           os << '"';
1874           os << A->getOffloadingKindPrefix();
1875           os << " (";
1876           os << TC->getTriple().normalize();
1877           if (BoundArch)
1878             os << ":" << BoundArch;
1879           os << ")";
1880           os << '"';
1881           os << " {" << PrintActions1(C, A, Ids, SibIndent, SibKind) << "}";
1882           IsFirst = false;
1883           SibKind = OtherSibAction;
1884         });
1885   } else {
1886     const ActionList *AL = &A->getInputs();
1887 
1888     if (AL->size()) {
1889       const char *Prefix = "{";
1890       for (Action *PreRequisite : *AL) {
1891         os << Prefix << PrintActions1(C, PreRequisite, Ids, SibIndent, SibKind);
1892         Prefix = ", ";
1893         SibKind = OtherSibAction;
1894       }
1895       os << "}";
1896     } else
1897       os << "{}";
1898   }
1899 
1900   // Append offload info for all options other than the offloading action
1901   // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1902   std::string offload_str;
1903   llvm::raw_string_ostream offload_os(offload_str);
1904   if (!isa<OffloadAction>(A)) {
1905     auto S = A->getOffloadingKindPrefix();
1906     if (!S.empty()) {
1907       offload_os << ", (" << S;
1908       if (A->getOffloadingArch())
1909         offload_os << ", " << A->getOffloadingArch();
1910       offload_os << ")";
1911     }
1912   }
1913 
1914   auto getSelfIndent = [](int K) -> Twine {
1915     return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : "";
1916   };
1917 
1918   unsigned Id = Ids.size();
1919   Ids[A] = Id;
1920   llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", "
1921                << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1922 
1923   return Id;
1924 }
1925 
1926 // Print the action graphs in a compilation C.
1927 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
1928 void Driver::PrintActions(const Compilation &C) const {
1929   std::map<Action *, unsigned> Ids;
1930   for (Action *A : C.getActions())
1931     PrintActions1(C, A, Ids);
1932 }
1933 
1934 /// Check whether the given input tree contains any compilation or
1935 /// assembly actions.
1936 static bool ContainsCompileOrAssembleAction(const Action *A) {
1937   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1938       isa<AssembleJobAction>(A))
1939     return true;
1940 
1941   for (const Action *Input : A->inputs())
1942     if (ContainsCompileOrAssembleAction(Input))
1943       return true;
1944 
1945   return false;
1946 }
1947 
1948 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1949                                    const InputList &BAInputs) const {
1950   DerivedArgList &Args = C.getArgs();
1951   ActionList &Actions = C.getActions();
1952   llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1953   // Collect the list of architectures. Duplicates are allowed, but should only
1954   // be handled once (in the order seen).
1955   llvm::StringSet<> ArchNames;
1956   SmallVector<const char *, 4> Archs;
1957   for (Arg *A : Args) {
1958     if (A->getOption().matches(options::OPT_arch)) {
1959       // Validate the option here; we don't save the type here because its
1960       // particular spelling may participate in other driver choices.
1961       llvm::Triple::ArchType Arch =
1962           tools::darwin::getArchTypeForMachOArchName(A->getValue());
1963       if (Arch == llvm::Triple::UnknownArch) {
1964         Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1965         continue;
1966       }
1967 
1968       A->claim();
1969       if (ArchNames.insert(A->getValue()).second)
1970         Archs.push_back(A->getValue());
1971     }
1972   }
1973 
1974   // When there is no explicit arch for this platform, make sure we still bind
1975   // the architecture (to the default) so that -Xarch_ is handled correctly.
1976   if (!Archs.size())
1977     Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
1978 
1979   ActionList SingleActions;
1980   BuildActions(C, Args, BAInputs, SingleActions);
1981 
1982   // Add in arch bindings for every top level action, as well as lipo and
1983   // dsymutil steps if needed.
1984   for (Action* Act : SingleActions) {
1985     // Make sure we can lipo this kind of output. If not (and it is an actual
1986     // output) then we disallow, since we can't create an output file with the
1987     // right name without overwriting it. We could remove this oddity by just
1988     // changing the output names to include the arch, which would also fix
1989     // -save-temps. Compatibility wins for now.
1990 
1991     if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
1992       Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1993           << types::getTypeName(Act->getType());
1994 
1995     ActionList Inputs;
1996     for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1997       Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
1998 
1999     // Lipo if necessary, we do it this way because we need to set the arch flag
2000     // so that -Xarch_ gets overwritten.
2001     if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
2002       Actions.append(Inputs.begin(), Inputs.end());
2003     else
2004       Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
2005 
2006     // Handle debug info queries.
2007     Arg *A = Args.getLastArg(options::OPT_g_Group);
2008     bool enablesDebugInfo = A && !A->getOption().matches(options::OPT_g0) &&
2009                             !A->getOption().matches(options::OPT_gstabs);
2010     if ((enablesDebugInfo || willEmitRemarks(Args)) &&
2011         ContainsCompileOrAssembleAction(Actions.back())) {
2012 
2013       // Add a 'dsymutil' step if necessary, when debug info is enabled and we
2014       // have a compile input. We need to run 'dsymutil' ourselves in such cases
2015       // because the debug info will refer to a temporary object file which
2016       // will be removed at the end of the compilation process.
2017       if (Act->getType() == types::TY_Image) {
2018         ActionList Inputs;
2019         Inputs.push_back(Actions.back());
2020         Actions.pop_back();
2021         Actions.push_back(
2022             C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
2023       }
2024 
2025       // Verify the debug info output.
2026       if (Args.hasArg(options::OPT_verify_debug_info)) {
2027         Action* LastAction = Actions.back();
2028         Actions.pop_back();
2029         Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
2030             LastAction, types::TY_Nothing));
2031       }
2032     }
2033   }
2034 }
2035 
2036 bool Driver::DiagnoseInputExistence(const DerivedArgList &Args, StringRef Value,
2037                                     types::ID Ty, bool TypoCorrect) const {
2038   if (!getCheckInputsExist())
2039     return true;
2040 
2041   // stdin always exists.
2042   if (Value == "-")
2043     return true;
2044 
2045   if (getVFS().exists(Value))
2046     return true;
2047 
2048   if (IsCLMode()) {
2049     if (!llvm::sys::path::is_absolute(Twine(Value)) &&
2050         llvm::sys::Process::FindInEnvPath("LIB", Value))
2051       return true;
2052 
2053     if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
2054       // Arguments to the /link flag might cause the linker to search for object
2055       // and library files in paths we don't know about. Don't error in such
2056       // cases.
2057       return true;
2058     }
2059   }
2060 
2061   if (TypoCorrect) {
2062     // Check if the filename is a typo for an option flag. OptTable thinks
2063     // that all args that are not known options and that start with / are
2064     // filenames, but e.g. `/diagnostic:caret` is more likely a typo for
2065     // the option `/diagnostics:caret` than a reference to a file in the root
2066     // directory.
2067     unsigned IncludedFlagsBitmask;
2068     unsigned ExcludedFlagsBitmask;
2069     std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
2070         getIncludeExcludeOptionFlagMasks(IsCLMode());
2071     std::string Nearest;
2072     if (getOpts().findNearest(Value, Nearest, IncludedFlagsBitmask,
2073                               ExcludedFlagsBitmask) <= 1) {
2074       Diag(clang::diag::err_drv_no_such_file_with_suggestion)
2075           << Value << Nearest;
2076       return false;
2077     }
2078   }
2079 
2080   Diag(clang::diag::err_drv_no_such_file) << Value;
2081   return false;
2082 }
2083 
2084 // Construct a the list of inputs and their types.
2085 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
2086                          InputList &Inputs) const {
2087   const llvm::opt::OptTable &Opts = getOpts();
2088   // Track the current user specified (-x) input. We also explicitly track the
2089   // argument used to set the type; we only want to claim the type when we
2090   // actually use it, so we warn about unused -x arguments.
2091   types::ID InputType = types::TY_Nothing;
2092   Arg *InputTypeArg = nullptr;
2093 
2094   // The last /TC or /TP option sets the input type to C or C++ globally.
2095   if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
2096                                          options::OPT__SLASH_TP)) {
2097     InputTypeArg = TCTP;
2098     InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
2099                     ? types::TY_C
2100                     : types::TY_CXX;
2101 
2102     Arg *Previous = nullptr;
2103     bool ShowNote = false;
2104     for (Arg *A :
2105          Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
2106       if (Previous) {
2107         Diag(clang::diag::warn_drv_overriding_flag_option)
2108           << Previous->getSpelling() << A->getSpelling();
2109         ShowNote = true;
2110       }
2111       Previous = A;
2112     }
2113     if (ShowNote)
2114       Diag(clang::diag::note_drv_t_option_is_global);
2115 
2116     // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
2117     assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
2118   }
2119 
2120   for (Arg *A : Args) {
2121     if (A->getOption().getKind() == Option::InputClass) {
2122       const char *Value = A->getValue();
2123       types::ID Ty = types::TY_INVALID;
2124 
2125       // Infer the input type if necessary.
2126       if (InputType == types::TY_Nothing) {
2127         // If there was an explicit arg for this, claim it.
2128         if (InputTypeArg)
2129           InputTypeArg->claim();
2130 
2131         // stdin must be handled specially.
2132         if (memcmp(Value, "-", 2) == 0) {
2133           // If running with -E, treat as a C input (this changes the builtin
2134           // macros, for example). This may be overridden by -ObjC below.
2135           //
2136           // Otherwise emit an error but still use a valid type to avoid
2137           // spurious errors (e.g., no inputs).
2138           if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
2139             Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2140                             : clang::diag::err_drv_unknown_stdin_type);
2141           Ty = types::TY_C;
2142         } else {
2143           // Otherwise lookup by extension.
2144           // Fallback is C if invoked as C preprocessor, C++ if invoked with
2145           // clang-cl /E, or Object otherwise.
2146           // We use a host hook here because Darwin at least has its own
2147           // idea of what .s is.
2148           if (const char *Ext = strrchr(Value, '.'))
2149             Ty = TC.LookupTypeForExtension(Ext + 1);
2150 
2151           if (Ty == types::TY_INVALID) {
2152             if (CCCIsCPP())
2153               Ty = types::TY_C;
2154             else if (IsCLMode() && Args.hasArgNoClaim(options::OPT_E))
2155               Ty = types::TY_CXX;
2156             else
2157               Ty = types::TY_Object;
2158           }
2159 
2160           // If the driver is invoked as C++ compiler (like clang++ or c++) it
2161           // should autodetect some input files as C++ for g++ compatibility.
2162           if (CCCIsCXX()) {
2163             types::ID OldTy = Ty;
2164             Ty = types::lookupCXXTypeForCType(Ty);
2165 
2166             if (Ty != OldTy)
2167               Diag(clang::diag::warn_drv_treating_input_as_cxx)
2168                   << getTypeName(OldTy) << getTypeName(Ty);
2169           }
2170 
2171           // If running with -fthinlto-index=, extensions that normally identify
2172           // native object files actually identify LLVM bitcode files.
2173           if (Args.hasArgNoClaim(options::OPT_fthinlto_index_EQ) &&
2174               Ty == types::TY_Object)
2175             Ty = types::TY_LLVM_BC;
2176         }
2177 
2178         // -ObjC and -ObjC++ override the default language, but only for "source
2179         // files". We just treat everything that isn't a linker input as a
2180         // source file.
2181         //
2182         // FIXME: Clean this up if we move the phase sequence into the type.
2183         if (Ty != types::TY_Object) {
2184           if (Args.hasArg(options::OPT_ObjC))
2185             Ty = types::TY_ObjC;
2186           else if (Args.hasArg(options::OPT_ObjCXX))
2187             Ty = types::TY_ObjCXX;
2188         }
2189       } else {
2190         assert(InputTypeArg && "InputType set w/o InputTypeArg");
2191         if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2192           // If emulating cl.exe, make sure that /TC and /TP don't affect input
2193           // object files.
2194           const char *Ext = strrchr(Value, '.');
2195           if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2196             Ty = types::TY_Object;
2197         }
2198         if (Ty == types::TY_INVALID) {
2199           Ty = InputType;
2200           InputTypeArg->claim();
2201         }
2202       }
2203 
2204       if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true))
2205         Inputs.push_back(std::make_pair(Ty, A));
2206 
2207     } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2208       StringRef Value = A->getValue();
2209       if (DiagnoseInputExistence(Args, Value, types::TY_C,
2210                                  /*TypoCorrect=*/false)) {
2211         Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2212         Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2213       }
2214       A->claim();
2215     } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2216       StringRef Value = A->getValue();
2217       if (DiagnoseInputExistence(Args, Value, types::TY_CXX,
2218                                  /*TypoCorrect=*/false)) {
2219         Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2220         Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2221       }
2222       A->claim();
2223     } else if (A->getOption().hasFlag(options::LinkerInput)) {
2224       // Just treat as object type, we could make a special type for this if
2225       // necessary.
2226       Inputs.push_back(std::make_pair(types::TY_Object, A));
2227 
2228     } else if (A->getOption().matches(options::OPT_x)) {
2229       InputTypeArg = A;
2230       InputType = types::lookupTypeForTypeSpecifier(A->getValue());
2231       A->claim();
2232 
2233       // Follow gcc behavior and treat as linker input for invalid -x
2234       // options. Its not clear why we shouldn't just revert to unknown; but
2235       // this isn't very important, we might as well be bug compatible.
2236       if (!InputType) {
2237         Diag(clang::diag::err_drv_unknown_language) << A->getValue();
2238         InputType = types::TY_Object;
2239       }
2240     } else if (A->getOption().getID() == options::OPT_U) {
2241       assert(A->getNumValues() == 1 && "The /U option has one value.");
2242       StringRef Val = A->getValue(0);
2243       if (Val.find_first_of("/\\") != StringRef::npos) {
2244         // Warn about e.g. "/Users/me/myfile.c".
2245         Diag(diag::warn_slash_u_filename) << Val;
2246         Diag(diag::note_use_dashdash);
2247       }
2248     }
2249   }
2250   if (CCCIsCPP() && Inputs.empty()) {
2251     // If called as standalone preprocessor, stdin is processed
2252     // if no other input is present.
2253     Arg *A = MakeInputArg(Args, Opts, "-");
2254     Inputs.push_back(std::make_pair(types::TY_C, A));
2255   }
2256 }
2257 
2258 namespace {
2259 /// Provides a convenient interface for different programming models to generate
2260 /// the required device actions.
2261 class OffloadingActionBuilder final {
2262   /// Flag used to trace errors in the builder.
2263   bool IsValid = false;
2264 
2265   /// The compilation that is using this builder.
2266   Compilation &C;
2267 
2268   /// Map between an input argument and the offload kinds used to process it.
2269   std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2270 
2271   /// Builder interface. It doesn't build anything or keep any state.
2272   class DeviceActionBuilder {
2273   public:
2274     typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy;
2275 
2276     enum ActionBuilderReturnCode {
2277       // The builder acted successfully on the current action.
2278       ABRT_Success,
2279       // The builder didn't have to act on the current action.
2280       ABRT_Inactive,
2281       // The builder was successful and requested the host action to not be
2282       // generated.
2283       ABRT_Ignore_Host,
2284     };
2285 
2286   protected:
2287     /// Compilation associated with this builder.
2288     Compilation &C;
2289 
2290     /// Tool chains associated with this builder. The same programming
2291     /// model may have associated one or more tool chains.
2292     SmallVector<const ToolChain *, 2> ToolChains;
2293 
2294     /// The derived arguments associated with this builder.
2295     DerivedArgList &Args;
2296 
2297     /// The inputs associated with this builder.
2298     const Driver::InputList &Inputs;
2299 
2300     /// The associated offload kind.
2301     Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2302 
2303   public:
2304     DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2305                         const Driver::InputList &Inputs,
2306                         Action::OffloadKind AssociatedOffloadKind)
2307         : C(C), Args(Args), Inputs(Inputs),
2308           AssociatedOffloadKind(AssociatedOffloadKind) {}
2309     virtual ~DeviceActionBuilder() {}
2310 
2311     /// Fill up the array \a DA with all the device dependences that should be
2312     /// added to the provided host action \a HostAction. By default it is
2313     /// inactive.
2314     virtual ActionBuilderReturnCode
2315     getDeviceDependences(OffloadAction::DeviceDependences &DA,
2316                          phases::ID CurPhase, phases::ID FinalPhase,
2317                          PhasesTy &Phases) {
2318       return ABRT_Inactive;
2319     }
2320 
2321     /// Update the state to include the provided host action \a HostAction as a
2322     /// dependency of the current device action. By default it is inactive.
2323     virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2324       return ABRT_Inactive;
2325     }
2326 
2327     /// Append top level actions generated by the builder.
2328     virtual void appendTopLevelActions(ActionList &AL) {}
2329 
2330     /// Append linker device actions generated by the builder.
2331     virtual void appendLinkDeviceActions(ActionList &AL) {}
2332 
2333     /// Append linker host action generated by the builder.
2334     virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; }
2335 
2336     /// Append linker actions generated by the builder.
2337     virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2338 
2339     /// Initialize the builder. Return true if any initialization errors are
2340     /// found.
2341     virtual bool initialize() { return false; }
2342 
2343     /// Return true if the builder can use bundling/unbundling.
2344     virtual bool canUseBundlerUnbundler() const { return false; }
2345 
2346     /// Return true if this builder is valid. We have a valid builder if we have
2347     /// associated device tool chains.
2348     bool isValid() { return !ToolChains.empty(); }
2349 
2350     /// Return the associated offload kind.
2351     Action::OffloadKind getAssociatedOffloadKind() {
2352       return AssociatedOffloadKind;
2353     }
2354   };
2355 
2356   /// Base class for CUDA/HIP action builder. It injects device code in
2357   /// the host backend action.
2358   class CudaActionBuilderBase : public DeviceActionBuilder {
2359   protected:
2360     /// Flags to signal if the user requested host-only or device-only
2361     /// compilation.
2362     bool CompileHostOnly = false;
2363     bool CompileDeviceOnly = false;
2364     bool EmitLLVM = false;
2365     bool EmitAsm = false;
2366 
2367     /// List of GPU architectures to use in this compilation.
2368     SmallVector<CudaArch, 4> GpuArchList;
2369 
2370     /// The CUDA actions for the current input.
2371     ActionList CudaDeviceActions;
2372 
2373     /// The CUDA fat binary if it was generated for the current input.
2374     Action *CudaFatBinary = nullptr;
2375 
2376     /// Flag that is set to true if this builder acted on the current input.
2377     bool IsActive = false;
2378 
2379     /// Flag for -fgpu-rdc.
2380     bool Relocatable = false;
2381 
2382     /// Default GPU architecture if there's no one specified.
2383     CudaArch DefaultCudaArch = CudaArch::UNKNOWN;
2384 
2385   public:
2386     CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2387                           const Driver::InputList &Inputs,
2388                           Action::OffloadKind OFKind)
2389         : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
2390 
2391     ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2392       // While generating code for CUDA, we only depend on the host input action
2393       // to trigger the creation of all the CUDA device actions.
2394 
2395       // If we are dealing with an input action, replicate it for each GPU
2396       // architecture. If we are in host-only mode we return 'success' so that
2397       // the host uses the CUDA offload kind.
2398       if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2399         assert(!GpuArchList.empty() &&
2400                "We should have at least one GPU architecture.");
2401 
2402         // If the host input is not CUDA or HIP, we don't need to bother about
2403         // this input.
2404         if (IA->getType() != types::TY_CUDA &&
2405             IA->getType() != types::TY_HIP) {
2406           // The builder will ignore this input.
2407           IsActive = false;
2408           return ABRT_Inactive;
2409         }
2410 
2411         // Set the flag to true, so that the builder acts on the current input.
2412         IsActive = true;
2413 
2414         if (CompileHostOnly)
2415           return ABRT_Success;
2416 
2417         // Replicate inputs for each GPU architecture.
2418         auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2419                                                  : types::TY_CUDA_DEVICE;
2420         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2421           CudaDeviceActions.push_back(
2422               C.MakeAction<InputAction>(IA->getInputArg(), Ty));
2423         }
2424 
2425         return ABRT_Success;
2426       }
2427 
2428       // If this is an unbundling action use it as is for each CUDA toolchain.
2429       if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2430 
2431         // If -fgpu-rdc is disabled, should not unbundle since there is no
2432         // device code to link.
2433         if (!Relocatable)
2434           return ABRT_Inactive;
2435 
2436         CudaDeviceActions.clear();
2437         auto *IA = cast<InputAction>(UA->getInputs().back());
2438         std::string FileName = IA->getInputArg().getAsString(Args);
2439         // Check if the type of the file is the same as the action. Do not
2440         // unbundle it if it is not. Do not unbundle .so files, for example,
2441         // which are not object files.
2442         if (IA->getType() == types::TY_Object &&
2443             (!llvm::sys::path::has_extension(FileName) ||
2444              types::lookupTypeForExtension(
2445                  llvm::sys::path::extension(FileName).drop_front()) !=
2446                  types::TY_Object))
2447           return ABRT_Inactive;
2448 
2449         for (auto Arch : GpuArchList) {
2450           CudaDeviceActions.push_back(UA);
2451           UA->registerDependentActionInfo(ToolChains[0], CudaArchToString(Arch),
2452                                           AssociatedOffloadKind);
2453         }
2454         return ABRT_Success;
2455       }
2456 
2457       return IsActive ? ABRT_Success : ABRT_Inactive;
2458     }
2459 
2460     void appendTopLevelActions(ActionList &AL) override {
2461       // Utility to append actions to the top level list.
2462       auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
2463         OffloadAction::DeviceDependences Dep;
2464         Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
2465                 AssociatedOffloadKind);
2466         AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2467       };
2468 
2469       // If we have a fat binary, add it to the list.
2470       if (CudaFatBinary) {
2471         AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
2472         CudaDeviceActions.clear();
2473         CudaFatBinary = nullptr;
2474         return;
2475       }
2476 
2477       if (CudaDeviceActions.empty())
2478         return;
2479 
2480       // If we have CUDA actions at this point, that's because we have a have
2481       // partial compilation, so we should have an action for each GPU
2482       // architecture.
2483       assert(CudaDeviceActions.size() == GpuArchList.size() &&
2484              "Expecting one action per GPU architecture.");
2485       assert(ToolChains.size() == 1 &&
2486              "Expecting to have a sing CUDA toolchain.");
2487       for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2488         AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2489 
2490       CudaDeviceActions.clear();
2491     }
2492 
2493     bool initialize() override {
2494       assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2495              AssociatedOffloadKind == Action::OFK_HIP);
2496 
2497       // We don't need to support CUDA.
2498       if (AssociatedOffloadKind == Action::OFK_Cuda &&
2499           !C.hasOffloadToolChain<Action::OFK_Cuda>())
2500         return false;
2501 
2502       // We don't need to support HIP.
2503       if (AssociatedOffloadKind == Action::OFK_HIP &&
2504           !C.hasOffloadToolChain<Action::OFK_HIP>())
2505         return false;
2506 
2507       Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2508           options::OPT_fno_gpu_rdc, /*Default=*/false);
2509 
2510       const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2511       assert(HostTC && "No toolchain for host compilation.");
2512       if (HostTC->getTriple().isNVPTX() ||
2513           HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2514         // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
2515         // an error and abort pipeline construction early so we don't trip
2516         // asserts that assume device-side compilation.
2517         C.getDriver().Diag(diag::err_drv_cuda_host_arch)
2518             << HostTC->getTriple().getArchName();
2519         return true;
2520       }
2521 
2522       ToolChains.push_back(
2523           AssociatedOffloadKind == Action::OFK_Cuda
2524               ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2525               : C.getSingleOffloadToolChain<Action::OFK_HIP>());
2526 
2527       Arg *PartialCompilationArg = Args.getLastArg(
2528           options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2529           options::OPT_cuda_compile_host_device);
2530       CompileHostOnly = PartialCompilationArg &&
2531                         PartialCompilationArg->getOption().matches(
2532                             options::OPT_cuda_host_only);
2533       CompileDeviceOnly = PartialCompilationArg &&
2534                           PartialCompilationArg->getOption().matches(
2535                               options::OPT_cuda_device_only);
2536       EmitLLVM = Args.getLastArg(options::OPT_emit_llvm);
2537       EmitAsm = Args.getLastArg(options::OPT_S);
2538 
2539       // Collect all cuda_gpu_arch parameters, removing duplicates.
2540       std::set<CudaArch> GpuArchs;
2541       bool Error = false;
2542       for (Arg *A : Args) {
2543         if (!(A->getOption().matches(options::OPT_offload_arch_EQ) ||
2544               A->getOption().matches(options::OPT_no_offload_arch_EQ)))
2545           continue;
2546         A->claim();
2547 
2548         const StringRef ArchStr = A->getValue();
2549         if (A->getOption().matches(options::OPT_no_offload_arch_EQ) &&
2550             ArchStr == "all") {
2551           GpuArchs.clear();
2552           continue;
2553         }
2554         CudaArch Arch = StringToCudaArch(ArchStr);
2555         if (Arch == CudaArch::UNKNOWN) {
2556           C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2557           Error = true;
2558         } else if (A->getOption().matches(options::OPT_offload_arch_EQ))
2559           GpuArchs.insert(Arch);
2560         else if (A->getOption().matches(options::OPT_no_offload_arch_EQ))
2561           GpuArchs.erase(Arch);
2562         else
2563           llvm_unreachable("Unexpected option.");
2564       }
2565 
2566       // Collect list of GPUs remaining in the set.
2567       for (CudaArch Arch : GpuArchs)
2568         GpuArchList.push_back(Arch);
2569 
2570       // Default to sm_20 which is the lowest common denominator for
2571       // supported GPUs.  sm_20 code should work correctly, if
2572       // suboptimally, on all newer GPUs.
2573       if (GpuArchList.empty())
2574         GpuArchList.push_back(DefaultCudaArch);
2575 
2576       return Error;
2577     }
2578   };
2579 
2580   /// \brief CUDA action builder. It injects device code in the host backend
2581   /// action.
2582   class CudaActionBuilder final : public CudaActionBuilderBase {
2583   public:
2584     CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2585                       const Driver::InputList &Inputs)
2586         : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {
2587       DefaultCudaArch = CudaArch::SM_20;
2588     }
2589 
2590     ActionBuilderReturnCode
2591     getDeviceDependences(OffloadAction::DeviceDependences &DA,
2592                          phases::ID CurPhase, phases::ID FinalPhase,
2593                          PhasesTy &Phases) override {
2594       if (!IsActive)
2595         return ABRT_Inactive;
2596 
2597       // If we don't have more CUDA actions, we don't have any dependences to
2598       // create for the host.
2599       if (CudaDeviceActions.empty())
2600         return ABRT_Success;
2601 
2602       assert(CudaDeviceActions.size() == GpuArchList.size() &&
2603              "Expecting one action per GPU architecture.");
2604       assert(!CompileHostOnly &&
2605              "Not expecting CUDA actions in host-only compilation.");
2606 
2607       // If we are generating code for the device or we are in a backend phase,
2608       // we attempt to generate the fat binary. We compile each arch to ptx and
2609       // assemble to cubin, then feed the cubin *and* the ptx into a device
2610       // "link" action, which uses fatbinary to combine these cubins into one
2611       // fatbin.  The fatbin is then an input to the host action if not in
2612       // device-only mode.
2613       if (CompileDeviceOnly || CurPhase == phases::Backend) {
2614         ActionList DeviceActions;
2615         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2616           // Produce the device action from the current phase up to the assemble
2617           // phase.
2618           for (auto Ph : Phases) {
2619             // Skip the phases that were already dealt with.
2620             if (Ph < CurPhase)
2621               continue;
2622             // We have to be consistent with the host final phase.
2623             if (Ph > FinalPhase)
2624               break;
2625 
2626             CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
2627                 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
2628 
2629             if (Ph == phases::Assemble)
2630               break;
2631           }
2632 
2633           // If we didn't reach the assemble phase, we can't generate the fat
2634           // binary. We don't need to generate the fat binary if we are not in
2635           // device-only mode.
2636           if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2637               CompileDeviceOnly)
2638             continue;
2639 
2640           Action *AssembleAction = CudaDeviceActions[I];
2641           assert(AssembleAction->getType() == types::TY_Object);
2642           assert(AssembleAction->getInputs().size() == 1);
2643 
2644           Action *BackendAction = AssembleAction->getInputs()[0];
2645           assert(BackendAction->getType() == types::TY_PP_Asm);
2646 
2647           for (auto &A : {AssembleAction, BackendAction}) {
2648             OffloadAction::DeviceDependences DDep;
2649             DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
2650                      Action::OFK_Cuda);
2651             DeviceActions.push_back(
2652                 C.MakeAction<OffloadAction>(DDep, A->getType()));
2653           }
2654         }
2655 
2656         // We generate the fat binary if we have device input actions.
2657         if (!DeviceActions.empty()) {
2658           CudaFatBinary =
2659               C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2660 
2661           if (!CompileDeviceOnly) {
2662             DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2663                    Action::OFK_Cuda);
2664             // Clear the fat binary, it is already a dependence to an host
2665             // action.
2666             CudaFatBinary = nullptr;
2667           }
2668 
2669           // Remove the CUDA actions as they are already connected to an host
2670           // action or fat binary.
2671           CudaDeviceActions.clear();
2672         }
2673 
2674         // We avoid creating host action in device-only mode.
2675         return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
2676       } else if (CurPhase > phases::Backend) {
2677         // If we are past the backend phase and still have a device action, we
2678         // don't have to do anything as this action is already a device
2679         // top-level action.
2680         return ABRT_Success;
2681       }
2682 
2683       assert(CurPhase < phases::Backend && "Generating single CUDA "
2684                                            "instructions should only occur "
2685                                            "before the backend phase!");
2686 
2687       // By default, we produce an action for each device arch.
2688       for (Action *&A : CudaDeviceActions)
2689         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2690 
2691       return ABRT_Success;
2692     }
2693   };
2694   /// \brief HIP action builder. It injects device code in the host backend
2695   /// action.
2696   class HIPActionBuilder final : public CudaActionBuilderBase {
2697     /// The linker inputs obtained for each device arch.
2698     SmallVector<ActionList, 8> DeviceLinkerInputs;
2699 
2700   public:
2701     HIPActionBuilder(Compilation &C, DerivedArgList &Args,
2702                      const Driver::InputList &Inputs)
2703         : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {
2704       DefaultCudaArch = CudaArch::GFX803;
2705     }
2706 
2707     bool canUseBundlerUnbundler() const override { return true; }
2708 
2709     ActionBuilderReturnCode
2710     getDeviceDependences(OffloadAction::DeviceDependences &DA,
2711                          phases::ID CurPhase, phases::ID FinalPhase,
2712                          PhasesTy &Phases) override {
2713       // amdgcn does not support linking of object files, therefore we skip
2714       // backend and assemble phases to output LLVM IR. Except for generating
2715       // non-relocatable device coee, where we generate fat binary for device
2716       // code and pass to host in Backend phase.
2717       if (CudaDeviceActions.empty())
2718         return ABRT_Success;
2719 
2720       assert(((CurPhase == phases::Link && Relocatable) ||
2721               CudaDeviceActions.size() == GpuArchList.size()) &&
2722              "Expecting one action per GPU architecture.");
2723       assert(!CompileHostOnly &&
2724              "Not expecting CUDA actions in host-only compilation.");
2725 
2726       if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM &&
2727           !EmitAsm) {
2728         // If we are in backend phase, we attempt to generate the fat binary.
2729         // We compile each arch to IR and use a link action to generate code
2730         // object containing ISA. Then we use a special "link" action to create
2731         // a fat binary containing all the code objects for different GPU's.
2732         // The fat binary is then an input to the host action.
2733         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2734           auto BackendAction = C.getDriver().ConstructPhaseAction(
2735               C, Args, phases::Backend, CudaDeviceActions[I],
2736               AssociatedOffloadKind);
2737           auto AssembleAction = C.getDriver().ConstructPhaseAction(
2738               C, Args, phases::Assemble, BackendAction, AssociatedOffloadKind);
2739           // Create a link action to link device IR with device library
2740           // and generate ISA.
2741           ActionList AL;
2742           AL.push_back(AssembleAction);
2743           CudaDeviceActions[I] =
2744               C.MakeAction<LinkJobAction>(AL, types::TY_Image);
2745 
2746           // OffloadingActionBuilder propagates device arch until an offload
2747           // action. Since the next action for creating fatbin does
2748           // not have device arch, whereas the above link action and its input
2749           // have device arch, an offload action is needed to stop the null
2750           // device arch of the next action being propagated to the above link
2751           // action.
2752           OffloadAction::DeviceDependences DDep;
2753           DDep.add(*CudaDeviceActions[I], *ToolChains.front(),
2754                    CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2755           CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
2756               DDep, CudaDeviceActions[I]->getType());
2757         }
2758         // Create HIP fat binary with a special "link" action.
2759         CudaFatBinary =
2760             C.MakeAction<LinkJobAction>(CudaDeviceActions,
2761                 types::TY_HIP_FATBIN);
2762 
2763         if (!CompileDeviceOnly) {
2764           DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2765                  AssociatedOffloadKind);
2766           // Clear the fat binary, it is already a dependence to an host
2767           // action.
2768           CudaFatBinary = nullptr;
2769         }
2770 
2771         // Remove the CUDA actions as they are already connected to an host
2772         // action or fat binary.
2773         CudaDeviceActions.clear();
2774 
2775         return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
2776       } else if (CurPhase == phases::Link) {
2777         // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
2778         // This happens to each device action originated from each input file.
2779         // Later on, device actions in DeviceLinkerInputs are used to create
2780         // device link actions in appendLinkDependences and the created device
2781         // link actions are passed to the offload action as device dependence.
2782         DeviceLinkerInputs.resize(CudaDeviceActions.size());
2783         auto LI = DeviceLinkerInputs.begin();
2784         for (auto *A : CudaDeviceActions) {
2785           LI->push_back(A);
2786           ++LI;
2787         }
2788 
2789         // We will pass the device action as a host dependence, so we don't
2790         // need to do anything else with them.
2791         CudaDeviceActions.clear();
2792         return ABRT_Success;
2793       }
2794 
2795       // By default, we produce an action for each device arch.
2796       for (Action *&A : CudaDeviceActions)
2797         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
2798                                                AssociatedOffloadKind);
2799 
2800       return (CompileDeviceOnly && CurPhase == FinalPhase) ? ABRT_Ignore_Host
2801                                                            : ABRT_Success;
2802     }
2803 
2804     void appendLinkDeviceActions(ActionList &AL) override {
2805       if (DeviceLinkerInputs.size() == 0)
2806         return;
2807 
2808       assert(DeviceLinkerInputs.size() == GpuArchList.size() &&
2809              "Linker inputs and GPU arch list sizes do not match.");
2810 
2811       // Append a new link action for each device.
2812       unsigned I = 0;
2813       for (auto &LI : DeviceLinkerInputs) {
2814         // Each entry in DeviceLinkerInputs corresponds to a GPU arch.
2815         auto *DeviceLinkAction =
2816             C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2817         // Linking all inputs for the current GPU arch.
2818         // LI contains all the inputs for the linker.
2819         OffloadAction::DeviceDependences DeviceLinkDeps;
2820         DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0],
2821             CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2822         AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps,
2823             DeviceLinkAction->getType()));
2824         ++I;
2825       }
2826       DeviceLinkerInputs.clear();
2827 
2828       // Create a host object from all the device images by embedding them
2829       // in a fat binary.
2830       OffloadAction::DeviceDependences DDeps;
2831       auto *TopDeviceLinkAction =
2832           C.MakeAction<LinkJobAction>(AL, types::TY_Object);
2833       DDeps.add(*TopDeviceLinkAction, *ToolChains[0],
2834           nullptr, AssociatedOffloadKind);
2835 
2836       // Offload the host object to the host linker.
2837       AL.push_back(C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType()));
2838     }
2839 
2840     Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); }
2841 
2842     void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
2843   };
2844 
2845   /// OpenMP action builder. The host bitcode is passed to the device frontend
2846   /// and all the device linked images are passed to the host link phase.
2847   class OpenMPActionBuilder final : public DeviceActionBuilder {
2848     /// The OpenMP actions for the current input.
2849     ActionList OpenMPDeviceActions;
2850 
2851     /// The linker inputs obtained for each toolchain.
2852     SmallVector<ActionList, 8> DeviceLinkerInputs;
2853 
2854   public:
2855     OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2856                         const Driver::InputList &Inputs)
2857         : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2858 
2859     ActionBuilderReturnCode
2860     getDeviceDependences(OffloadAction::DeviceDependences &DA,
2861                          phases::ID CurPhase, phases::ID FinalPhase,
2862                          PhasesTy &Phases) override {
2863       if (OpenMPDeviceActions.empty())
2864         return ABRT_Inactive;
2865 
2866       // We should always have an action for each input.
2867       assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2868              "Number of OpenMP actions and toolchains do not match.");
2869 
2870       // The host only depends on device action in the linking phase, when all
2871       // the device images have to be embedded in the host image.
2872       if (CurPhase == phases::Link) {
2873         assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2874                "Toolchains and linker inputs sizes do not match.");
2875         auto LI = DeviceLinkerInputs.begin();
2876         for (auto *A : OpenMPDeviceActions) {
2877           LI->push_back(A);
2878           ++LI;
2879         }
2880 
2881         // We passed the device action as a host dependence, so we don't need to
2882         // do anything else with them.
2883         OpenMPDeviceActions.clear();
2884         return ABRT_Success;
2885       }
2886 
2887       // By default, we produce an action for each device arch.
2888       for (Action *&A : OpenMPDeviceActions)
2889         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2890 
2891       return ABRT_Success;
2892     }
2893 
2894     ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2895 
2896       // If this is an input action replicate it for each OpenMP toolchain.
2897       if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2898         OpenMPDeviceActions.clear();
2899         for (unsigned I = 0; I < ToolChains.size(); ++I)
2900           OpenMPDeviceActions.push_back(
2901               C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2902         return ABRT_Success;
2903       }
2904 
2905       // If this is an unbundling action use it as is for each OpenMP toolchain.
2906       if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2907         OpenMPDeviceActions.clear();
2908         auto *IA = cast<InputAction>(UA->getInputs().back());
2909         std::string FileName = IA->getInputArg().getAsString(Args);
2910         // Check if the type of the file is the same as the action. Do not
2911         // unbundle it if it is not. Do not unbundle .so files, for example,
2912         // which are not object files.
2913         if (IA->getType() == types::TY_Object &&
2914             (!llvm::sys::path::has_extension(FileName) ||
2915              types::lookupTypeForExtension(
2916                  llvm::sys::path::extension(FileName).drop_front()) !=
2917                  types::TY_Object))
2918           return ABRT_Inactive;
2919         for (unsigned I = 0; I < ToolChains.size(); ++I) {
2920           OpenMPDeviceActions.push_back(UA);
2921           UA->registerDependentActionInfo(
2922               ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2923         }
2924         return ABRT_Success;
2925       }
2926 
2927       // When generating code for OpenMP we use the host compile phase result as
2928       // a dependence to the device compile phase so that it can learn what
2929       // declarations should be emitted. However, this is not the only use for
2930       // the host action, so we prevent it from being collapsed.
2931       if (isa<CompileJobAction>(HostAction)) {
2932         HostAction->setCannotBeCollapsedWithNextDependentAction();
2933         assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2934                "Toolchains and device action sizes do not match.");
2935         OffloadAction::HostDependence HDep(
2936             *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2937             /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2938         auto TC = ToolChains.begin();
2939         for (Action *&A : OpenMPDeviceActions) {
2940           assert(isa<CompileJobAction>(A));
2941           OffloadAction::DeviceDependences DDep;
2942           DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2943           A = C.MakeAction<OffloadAction>(HDep, DDep);
2944           ++TC;
2945         }
2946       }
2947       return ABRT_Success;
2948     }
2949 
2950     void appendTopLevelActions(ActionList &AL) override {
2951       if (OpenMPDeviceActions.empty())
2952         return;
2953 
2954       // We should always have an action for each input.
2955       assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2956              "Number of OpenMP actions and toolchains do not match.");
2957 
2958       // Append all device actions followed by the proper offload action.
2959       auto TI = ToolChains.begin();
2960       for (auto *A : OpenMPDeviceActions) {
2961         OffloadAction::DeviceDependences Dep;
2962         Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2963         AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2964         ++TI;
2965       }
2966       // We no longer need the action stored in this builder.
2967       OpenMPDeviceActions.clear();
2968     }
2969 
2970     void appendLinkDeviceActions(ActionList &AL) override {
2971       assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2972              "Toolchains and linker inputs sizes do not match.");
2973 
2974       // Append a new link action for each device.
2975       auto TC = ToolChains.begin();
2976       for (auto &LI : DeviceLinkerInputs) {
2977         auto *DeviceLinkAction =
2978             C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2979         OffloadAction::DeviceDependences DeviceLinkDeps;
2980         DeviceLinkDeps.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2981 		        Action::OFK_OpenMP);
2982         AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps,
2983             DeviceLinkAction->getType()));
2984         ++TC;
2985       }
2986       DeviceLinkerInputs.clear();
2987     }
2988 
2989     Action* appendLinkHostActions(ActionList &AL) override {
2990       // Create wrapper bitcode from the result of device link actions and compile
2991       // it to an object which will be added to the host link command.
2992       auto *BC = C.MakeAction<OffloadWrapperJobAction>(AL, types::TY_LLVM_BC);
2993       auto *ASM = C.MakeAction<BackendJobAction>(BC, types::TY_PP_Asm);
2994       return C.MakeAction<AssembleJobAction>(ASM, types::TY_Object);
2995     }
2996 
2997     void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
2998 
2999     bool initialize() override {
3000       // Get the OpenMP toolchains. If we don't get any, the action builder will
3001       // know there is nothing to do related to OpenMP offloading.
3002       auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
3003       for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
3004            ++TI)
3005         ToolChains.push_back(TI->second);
3006 
3007       DeviceLinkerInputs.resize(ToolChains.size());
3008       return false;
3009     }
3010 
3011     bool canUseBundlerUnbundler() const override {
3012       // OpenMP should use bundled files whenever possible.
3013       return true;
3014     }
3015   };
3016 
3017   ///
3018   /// TODO: Add the implementation for other specialized builders here.
3019   ///
3020 
3021   /// Specialized builders being used by this offloading action builder.
3022   SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
3023 
3024   /// Flag set to true if all valid builders allow file bundling/unbundling.
3025   bool CanUseBundler;
3026 
3027 public:
3028   OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
3029                           const Driver::InputList &Inputs)
3030       : C(C) {
3031     // Create a specialized builder for each device toolchain.
3032 
3033     IsValid = true;
3034 
3035     // Create a specialized builder for CUDA.
3036     SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
3037 
3038     // Create a specialized builder for HIP.
3039     SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
3040 
3041     // Create a specialized builder for OpenMP.
3042     SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
3043 
3044     //
3045     // TODO: Build other specialized builders here.
3046     //
3047 
3048     // Initialize all the builders, keeping track of errors. If all valid
3049     // builders agree that we can use bundling, set the flag to true.
3050     unsigned ValidBuilders = 0u;
3051     unsigned ValidBuildersSupportingBundling = 0u;
3052     for (auto *SB : SpecializedBuilders) {
3053       IsValid = IsValid && !SB->initialize();
3054 
3055       // Update the counters if the builder is valid.
3056       if (SB->isValid()) {
3057         ++ValidBuilders;
3058         if (SB->canUseBundlerUnbundler())
3059           ++ValidBuildersSupportingBundling;
3060       }
3061     }
3062     CanUseBundler =
3063         ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
3064   }
3065 
3066   ~OffloadingActionBuilder() {
3067     for (auto *SB : SpecializedBuilders)
3068       delete SB;
3069   }
3070 
3071   /// Generate an action that adds device dependences (if any) to a host action.
3072   /// If no device dependence actions exist, just return the host action \a
3073   /// HostAction. If an error is found or if no builder requires the host action
3074   /// to be generated, return nullptr.
3075   Action *
3076   addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
3077                                    phases::ID CurPhase, phases::ID FinalPhase,
3078                                    DeviceActionBuilder::PhasesTy &Phases) {
3079     if (!IsValid)
3080       return nullptr;
3081 
3082     if (SpecializedBuilders.empty())
3083       return HostAction;
3084 
3085     assert(HostAction && "Invalid host action!");
3086 
3087     OffloadAction::DeviceDependences DDeps;
3088     // Check if all the programming models agree we should not emit the host
3089     // action. Also, keep track of the offloading kinds employed.
3090     auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3091     unsigned InactiveBuilders = 0u;
3092     unsigned IgnoringBuilders = 0u;
3093     for (auto *SB : SpecializedBuilders) {
3094       if (!SB->isValid()) {
3095         ++InactiveBuilders;
3096         continue;
3097       }
3098 
3099       auto RetCode =
3100           SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
3101 
3102       // If the builder explicitly says the host action should be ignored,
3103       // we need to increment the variable that tracks the builders that request
3104       // the host object to be ignored.
3105       if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
3106         ++IgnoringBuilders;
3107 
3108       // Unless the builder was inactive for this action, we have to record the
3109       // offload kind because the host will have to use it.
3110       if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3111         OffloadKind |= SB->getAssociatedOffloadKind();
3112     }
3113 
3114     // If all builders agree that the host object should be ignored, just return
3115     // nullptr.
3116     if (IgnoringBuilders &&
3117         SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
3118       return nullptr;
3119 
3120     if (DDeps.getActions().empty())
3121       return HostAction;
3122 
3123     // We have dependences we need to bundle together. We use an offload action
3124     // for that.
3125     OffloadAction::HostDependence HDep(
3126         *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3127         /*BoundArch=*/nullptr, DDeps);
3128     return C.MakeAction<OffloadAction>(HDep, DDeps);
3129   }
3130 
3131   /// Generate an action that adds a host dependence to a device action. The
3132   /// results will be kept in this action builder. Return true if an error was
3133   /// found.
3134   bool addHostDependenceToDeviceActions(Action *&HostAction,
3135                                         const Arg *InputArg) {
3136     if (!IsValid)
3137       return true;
3138 
3139     // If we are supporting bundling/unbundling and the current action is an
3140     // input action of non-source file, we replace the host action by the
3141     // unbundling action. The bundler tool has the logic to detect if an input
3142     // is a bundle or not and if the input is not a bundle it assumes it is a
3143     // host file. Therefore it is safe to create an unbundling action even if
3144     // the input is not a bundle.
3145     if (CanUseBundler && isa<InputAction>(HostAction) &&
3146         InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
3147         !types::isSrcFile(HostAction->getType())) {
3148       auto UnbundlingHostAction =
3149           C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
3150       UnbundlingHostAction->registerDependentActionInfo(
3151           C.getSingleOffloadToolChain<Action::OFK_Host>(),
3152           /*BoundArch=*/StringRef(), Action::OFK_Host);
3153       HostAction = UnbundlingHostAction;
3154     }
3155 
3156     assert(HostAction && "Invalid host action!");
3157 
3158     // Register the offload kinds that are used.
3159     auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3160     for (auto *SB : SpecializedBuilders) {
3161       if (!SB->isValid())
3162         continue;
3163 
3164       auto RetCode = SB->addDeviceDepences(HostAction);
3165 
3166       // Host dependences for device actions are not compatible with that same
3167       // action being ignored.
3168       assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
3169              "Host dependence not expected to be ignored.!");
3170 
3171       // Unless the builder was inactive for this action, we have to record the
3172       // offload kind because the host will have to use it.
3173       if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3174         OffloadKind |= SB->getAssociatedOffloadKind();
3175     }
3176 
3177     // Do not use unbundler if the Host does not depend on device action.
3178     if (OffloadKind == Action::OFK_None && CanUseBundler)
3179       if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3180         HostAction = UA->getInputs().back();
3181 
3182     return false;
3183   }
3184 
3185   /// Add the offloading top level actions to the provided action list. This
3186   /// function can replace the host action by a bundling action if the
3187   /// programming models allow it.
3188   bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3189                              const Arg *InputArg) {
3190     // Get the device actions to be appended.
3191     ActionList OffloadAL;
3192     for (auto *SB : SpecializedBuilders) {
3193       if (!SB->isValid())
3194         continue;
3195       SB->appendTopLevelActions(OffloadAL);
3196     }
3197 
3198     // If we can use the bundler, replace the host action by the bundling one in
3199     // the resulting list. Otherwise, just append the device actions. For
3200     // device only compilation, HostAction is a null pointer, therefore only do
3201     // this when HostAction is not a null pointer.
3202     if (CanUseBundler && HostAction &&
3203         HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) {
3204       // Add the host action to the list in order to create the bundling action.
3205       OffloadAL.push_back(HostAction);
3206 
3207       // We expect that the host action was just appended to the action list
3208       // before this method was called.
3209       assert(HostAction == AL.back() && "Host action not in the list??");
3210       HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3211       AL.back() = HostAction;
3212     } else
3213       AL.append(OffloadAL.begin(), OffloadAL.end());
3214 
3215     // Propagate to the current host action (if any) the offload information
3216     // associated with the current input.
3217     if (HostAction)
3218       HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3219                                            /*BoundArch=*/nullptr);
3220     return false;
3221   }
3222 
3223   Action* makeHostLinkAction() {
3224     // Build a list of device linking actions.
3225     ActionList DeviceAL;
3226     for (DeviceActionBuilder *SB : SpecializedBuilders) {
3227       if (!SB->isValid())
3228         continue;
3229       SB->appendLinkDeviceActions(DeviceAL);
3230     }
3231 
3232     if (DeviceAL.empty())
3233       return nullptr;
3234 
3235     // Let builders add host linking actions.
3236     Action* HA;
3237     for (DeviceActionBuilder *SB : SpecializedBuilders) {
3238       if (!SB->isValid())
3239         continue;
3240       HA = SB->appendLinkHostActions(DeviceAL);
3241     }
3242     return HA;
3243   }
3244 
3245   /// Processes the host linker action. This currently consists of replacing it
3246   /// with an offload action if there are device link objects and propagate to
3247   /// the host action all the offload kinds used in the current compilation. The
3248   /// resulting action is returned.
3249   Action *processHostLinkAction(Action *HostAction) {
3250     // Add all the dependences from the device linking actions.
3251     OffloadAction::DeviceDependences DDeps;
3252     for (auto *SB : SpecializedBuilders) {
3253       if (!SB->isValid())
3254         continue;
3255 
3256       SB->appendLinkDependences(DDeps);
3257     }
3258 
3259     // Calculate all the offload kinds used in the current compilation.
3260     unsigned ActiveOffloadKinds = 0u;
3261     for (auto &I : InputArgToOffloadKindMap)
3262       ActiveOffloadKinds |= I.second;
3263 
3264     // If we don't have device dependencies, we don't have to create an offload
3265     // action.
3266     if (DDeps.getActions().empty()) {
3267       // Propagate all the active kinds to host action. Given that it is a link
3268       // action it is assumed to depend on all actions generated so far.
3269       HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
3270                                            /*BoundArch=*/nullptr);
3271       return HostAction;
3272     }
3273 
3274     // Create the offload action with all dependences. When an offload action
3275     // is created the kinds are propagated to the host action, so we don't have
3276     // to do that explicitly here.
3277     OffloadAction::HostDependence HDep(
3278         *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3279         /*BoundArch*/ nullptr, ActiveOffloadKinds);
3280     return C.MakeAction<OffloadAction>(HDep, DDeps);
3281   }
3282 };
3283 } // anonymous namespace.
3284 
3285 void Driver::handleArguments(Compilation &C, DerivedArgList &Args,
3286                              const InputList &Inputs,
3287                              ActionList &Actions) const {
3288 
3289   // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
3290   Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3291   Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
3292   if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3293     Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3294     Args.eraseArg(options::OPT__SLASH_Yc);
3295     Args.eraseArg(options::OPT__SLASH_Yu);
3296     YcArg = YuArg = nullptr;
3297   }
3298   if (YcArg && Inputs.size() > 1) {
3299     Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3300     Args.eraseArg(options::OPT__SLASH_Yc);
3301     YcArg = nullptr;
3302   }
3303 
3304   Arg *FinalPhaseArg;
3305   phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
3306 
3307   if (FinalPhase == phases::Link) {
3308     if (Args.hasArg(options::OPT_emit_llvm))
3309       Diag(clang::diag::err_drv_emit_llvm_link);
3310     if (IsCLMode() && LTOMode != LTOK_None &&
3311         !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
3312       Diag(clang::diag::err_drv_lto_without_lld);
3313   }
3314 
3315   if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3316     // If only preprocessing or /Y- is used, all pch handling is disabled.
3317     // Rather than check for it everywhere, just remove clang-cl pch-related
3318     // flags here.
3319     Args.eraseArg(options::OPT__SLASH_Fp);
3320     Args.eraseArg(options::OPT__SLASH_Yc);
3321     Args.eraseArg(options::OPT__SLASH_Yu);
3322     YcArg = YuArg = nullptr;
3323   }
3324 
3325   unsigned LastPLSize = 0;
3326   for (auto &I : Inputs) {
3327     types::ID InputType = I.first;
3328     const Arg *InputArg = I.second;
3329 
3330     auto PL = types::getCompilationPhases(InputType);
3331     LastPLSize = PL.size();
3332 
3333     // If the first step comes after the final phase we are doing as part of
3334     // this compilation, warn the user about it.
3335     phases::ID InitialPhase = PL[0];
3336     if (InitialPhase > FinalPhase) {
3337       if (InputArg->isClaimed())
3338         continue;
3339 
3340       // Claim here to avoid the more general unused warning.
3341       InputArg->claim();
3342 
3343       // Suppress all unused style warnings with -Qunused-arguments
3344       if (Args.hasArg(options::OPT_Qunused_arguments))
3345         continue;
3346 
3347       // Special case when final phase determined by binary name, rather than
3348       // by a command-line argument with a corresponding Arg.
3349       if (CCCIsCPP())
3350         Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
3351             << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
3352       // Special case '-E' warning on a previously preprocessed file to make
3353       // more sense.
3354       else if (InitialPhase == phases::Compile &&
3355                (Args.getLastArg(options::OPT__SLASH_EP,
3356                                 options::OPT__SLASH_P) ||
3357                 Args.getLastArg(options::OPT_E) ||
3358                 Args.getLastArg(options::OPT_M, options::OPT_MM)) &&
3359                getPreprocessedType(InputType) == types::TY_INVALID)
3360         Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
3361             << InputArg->getAsString(Args) << !!FinalPhaseArg
3362             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3363       else
3364         Diag(clang::diag::warn_drv_input_file_unused)
3365             << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3366             << !!FinalPhaseArg
3367             << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3368       continue;
3369     }
3370 
3371     if (YcArg) {
3372       // Add a separate precompile phase for the compile phase.
3373       if (FinalPhase >= phases::Compile) {
3374         const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
3375         // Build the pipeline for the pch file.
3376         Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType);
3377         for (phases::ID Phase : types::getCompilationPhases(HeaderType))
3378           ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3379         assert(ClangClPch);
3380         Actions.push_back(ClangClPch);
3381         // The driver currently exits after the first failed command.  This
3382         // relies on that behavior, to make sure if the pch generation fails,
3383         // the main compilation won't run.
3384         // FIXME: If the main compilation fails, the PCH generation should
3385         // probably not be considered successful either.
3386       }
3387     }
3388   }
3389 
3390   // If we are linking, claim any options which are obviously only used for
3391   // compilation.
3392   // FIXME: Understand why the last Phase List length is used here.
3393   if (FinalPhase == phases::Link && LastPLSize == 1) {
3394     Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
3395     Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3396   }
3397 }
3398 
3399 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
3400                           const InputList &Inputs, ActionList &Actions) const {
3401   llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
3402 
3403   if (!SuppressMissingInputWarning && Inputs.empty()) {
3404     Diag(clang::diag::err_drv_no_input_files);
3405     return;
3406   }
3407 
3408   // Reject -Z* at the top level, these options should never have been exposed
3409   // by gcc.
3410   if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
3411     Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
3412 
3413   // Diagnose misuse of /Fo.
3414   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
3415     StringRef V = A->getValue();
3416     if (Inputs.size() > 1 && !V.empty() &&
3417         !llvm::sys::path::is_separator(V.back())) {
3418       // Check whether /Fo tries to name an output file for multiple inputs.
3419       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3420           << A->getSpelling() << V;
3421       Args.eraseArg(options::OPT__SLASH_Fo);
3422     }
3423   }
3424 
3425   // Diagnose misuse of /Fa.
3426   if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
3427     StringRef V = A->getValue();
3428     if (Inputs.size() > 1 && !V.empty() &&
3429         !llvm::sys::path::is_separator(V.back())) {
3430       // Check whether /Fa tries to name an asm file for multiple inputs.
3431       Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3432           << A->getSpelling() << V;
3433       Args.eraseArg(options::OPT__SLASH_Fa);
3434     }
3435   }
3436 
3437   // Diagnose misuse of /o.
3438   if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
3439     if (A->getValue()[0] == '\0') {
3440       // It has to have a value.
3441       Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
3442       Args.eraseArg(options::OPT__SLASH_o);
3443     }
3444   }
3445 
3446   handleArguments(C, Args, Inputs, Actions);
3447 
3448   // Builder to be used to build offloading actions.
3449   OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
3450 
3451   // Construct the actions to perform.
3452   HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
3453   ActionList LinkerInputs;
3454   ActionList MergerInputs;
3455 
3456   for (auto &I : Inputs) {
3457     types::ID InputType = I.first;
3458     const Arg *InputArg = I.second;
3459 
3460     auto PL = types::getCompilationPhases(*this, Args, InputType);
3461     if (PL.empty())
3462       continue;
3463 
3464     auto FullPL = types::getCompilationPhases(InputType);
3465 
3466     // Build the pipeline for this file.
3467     Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3468 
3469     // Use the current host action in any of the offloading actions, if
3470     // required.
3471     if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3472       break;
3473 
3474     for (phases::ID Phase : PL) {
3475 
3476       // Add any offload action the host action depends on.
3477       Current = OffloadBuilder.addDeviceDependencesToHostAction(
3478           Current, InputArg, Phase, PL.back(), FullPL);
3479       if (!Current)
3480         break;
3481 
3482       // Queue linker inputs.
3483       if (Phase == phases::Link) {
3484         assert(Phase == PL.back() && "linking must be final compilation step.");
3485         LinkerInputs.push_back(Current);
3486         Current = nullptr;
3487         break;
3488       }
3489 
3490       // TODO: Consider removing this because the merged may not end up being
3491       // the final Phase in the pipeline. Perhaps the merged could just merge
3492       // and then pass an artifact of some sort to the Link Phase.
3493       // Queue merger inputs.
3494       if (Phase == phases::IfsMerge) {
3495         assert(Phase == PL.back() && "merging must be final compilation step.");
3496         MergerInputs.push_back(Current);
3497         Current = nullptr;
3498         break;
3499       }
3500 
3501       // Each precompiled header file after a module file action is a module
3502       // header of that same module file, rather than being compiled to a
3503       // separate PCH.
3504       if (Phase == phases::Precompile && HeaderModuleAction &&
3505           getPrecompiledType(InputType) == types::TY_PCH) {
3506         HeaderModuleAction->addModuleHeaderInput(Current);
3507         Current = nullptr;
3508         break;
3509       }
3510 
3511       // FIXME: Should we include any prior module file outputs as inputs of
3512       // later actions in the same command line?
3513 
3514       // Otherwise construct the appropriate action.
3515       Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
3516 
3517       // We didn't create a new action, so we will just move to the next phase.
3518       if (NewCurrent == Current)
3519         continue;
3520 
3521       if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
3522         HeaderModuleAction = HMA;
3523 
3524       Current = NewCurrent;
3525 
3526       // Use the current host action in any of the offloading actions, if
3527       // required.
3528       if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3529         break;
3530 
3531       if (Current->getType() == types::TY_Nothing)
3532         break;
3533     }
3534 
3535     // If we ended with something, add to the output list.
3536     if (Current)
3537       Actions.push_back(Current);
3538 
3539     // Add any top level actions generated for offloading.
3540     OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
3541   }
3542 
3543   // Add a link action if necessary.
3544   if (!LinkerInputs.empty()) {
3545     if (Action *Wrapper = OffloadBuilder.makeHostLinkAction())
3546       LinkerInputs.push_back(Wrapper);
3547     Action *LA;
3548     // Check if this Linker Job should emit a static library.
3549     if (ShouldEmitStaticLibrary(Args)) {
3550       LA = C.MakeAction<StaticLibJobAction>(LinkerInputs, types::TY_Image);
3551     } else {
3552       LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3553     }
3554     LA = OffloadBuilder.processHostLinkAction(LA);
3555     Actions.push_back(LA);
3556   }
3557 
3558   // Add an interface stubs merge action if necessary.
3559   if (!MergerInputs.empty())
3560     Actions.push_back(
3561         C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
3562 
3563   if (Args.hasArg(options::OPT_emit_interface_stubs)) {
3564     auto PhaseList = types::getCompilationPhases(
3565         types::TY_IFS_CPP,
3566         Args.hasArg(options::OPT_c) ? phases::Compile : phases::LastPhase);
3567 
3568     ActionList MergerInputs;
3569 
3570     for (auto &I : Inputs) {
3571       types::ID InputType = I.first;
3572       const Arg *InputArg = I.second;
3573 
3574       // Currently clang and the llvm assembler do not support generating symbol
3575       // stubs from assembly, so we skip the input on asm files. For ifs files
3576       // we rely on the normal pipeline setup in the pipeline setup code above.
3577       if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm ||
3578           InputType == types::TY_Asm)
3579         continue;
3580 
3581       Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3582 
3583       for (auto Phase : PhaseList) {
3584         switch (Phase) {
3585         default:
3586           llvm_unreachable(
3587               "IFS Pipeline can only consist of Compile followed by IfsMerge.");
3588         case phases::Compile: {
3589           // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs
3590           // files where the .o file is located. The compile action can not
3591           // handle this.
3592           if (InputType == types::TY_Object)
3593             break;
3594 
3595           Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP);
3596           break;
3597         }
3598         case phases::IfsMerge: {
3599           assert(Phase == PhaseList.back() &&
3600                  "merging must be final compilation step.");
3601           MergerInputs.push_back(Current);
3602           Current = nullptr;
3603           break;
3604         }
3605         }
3606       }
3607 
3608       // If we ended with something, add to the output list.
3609       if (Current)
3610         Actions.push_back(Current);
3611     }
3612 
3613     // Add an interface stubs merge action if necessary.
3614     if (!MergerInputs.empty())
3615       Actions.push_back(
3616           C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
3617   }
3618 
3619   // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a custom
3620   // Compile phase that prints out supported cpu models and quits.
3621   if (Arg *A = Args.getLastArg(options::OPT_print_supported_cpus)) {
3622     // Use the -mcpu=? flag as the dummy input to cc1.
3623     Actions.clear();
3624     Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C);
3625     Actions.push_back(
3626         C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing));
3627     for (auto &I : Inputs)
3628       I.second->claim();
3629   }
3630 
3631   // Claim ignored clang-cl options.
3632   Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
3633 
3634   // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3635   // to non-CUDA compilations and should not trigger warnings there.
3636   Args.ClaimAllArgs(options::OPT_cuda_host_only);
3637   Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
3638 }
3639 
3640 Action *Driver::ConstructPhaseAction(
3641     Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3642     Action::OffloadKind TargetDeviceOffloadKind) const {
3643   llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
3644 
3645   // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3646   // encode this in the steps because the intermediate type depends on
3647   // arguments. Just special case here.
3648   if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3649     return Input;
3650 
3651   // Build the appropriate action.
3652   switch (Phase) {
3653   case phases::Link:
3654     llvm_unreachable("link action invalid here.");
3655   case phases::IfsMerge:
3656     llvm_unreachable("ifsmerge action invalid here.");
3657   case phases::Preprocess: {
3658     types::ID OutputTy;
3659     // -M and -MM specify the dependency file name by altering the output type,
3660     // -if -MD and -MMD are not specified.
3661     if (Args.hasArg(options::OPT_M, options::OPT_MM) &&
3662         !Args.hasArg(options::OPT_MD, options::OPT_MMD)) {
3663       OutputTy = types::TY_Dependencies;
3664     } else {
3665       OutputTy = Input->getType();
3666       if (!Args.hasFlag(options::OPT_frewrite_includes,
3667                         options::OPT_fno_rewrite_includes, false) &&
3668           !Args.hasFlag(options::OPT_frewrite_imports,
3669                         options::OPT_fno_rewrite_imports, false) &&
3670           !CCGenDiagnostics)
3671         OutputTy = types::getPreprocessedType(OutputTy);
3672       assert(OutputTy != types::TY_INVALID &&
3673              "Cannot preprocess this input type!");
3674     }
3675     return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
3676   }
3677   case phases::Precompile: {
3678     types::ID OutputTy = getPrecompiledType(Input->getType());
3679     assert(OutputTy != types::TY_INVALID &&
3680            "Cannot precompile this input type!");
3681 
3682     // If we're given a module name, precompile header file inputs as a
3683     // module, not as a precompiled header.
3684     const char *ModName = nullptr;
3685     if (OutputTy == types::TY_PCH) {
3686       if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
3687         ModName = A->getValue();
3688       if (ModName)
3689         OutputTy = types::TY_ModuleFile;
3690     }
3691 
3692     if (Args.hasArg(options::OPT_fsyntax_only)) {
3693       // Syntax checks should not emit a PCH file
3694       OutputTy = types::TY_Nothing;
3695     }
3696 
3697     if (ModName)
3698       return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
3699                                                            ModName);
3700     return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
3701   }
3702   case phases::Compile: {
3703     if (Args.hasArg(options::OPT_fsyntax_only))
3704       return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
3705     if (Args.hasArg(options::OPT_rewrite_objc))
3706       return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
3707     if (Args.hasArg(options::OPT_rewrite_legacy_objc))
3708       return C.MakeAction<CompileJobAction>(Input,
3709                                             types::TY_RewrittenLegacyObjC);
3710     if (Args.hasArg(options::OPT__analyze))
3711       return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
3712     if (Args.hasArg(options::OPT__migrate))
3713       return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
3714     if (Args.hasArg(options::OPT_emit_ast))
3715       return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
3716     if (Args.hasArg(options::OPT_module_file_info))
3717       return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
3718     if (Args.hasArg(options::OPT_verify_pch))
3719       return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3720     return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
3721   }
3722   case phases::Backend: {
3723     if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
3724       types::ID Output =
3725           Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
3726       return C.MakeAction<BackendJobAction>(Input, Output);
3727     }
3728     if (Args.hasArg(options::OPT_emit_llvm) ||
3729         (TargetDeviceOffloadKind == Action::OFK_HIP &&
3730          Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
3731                       false))) {
3732       types::ID Output =
3733           Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
3734       return C.MakeAction<BackendJobAction>(Input, Output);
3735     }
3736     return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
3737   }
3738   case phases::Assemble:
3739     return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
3740   }
3741 
3742   llvm_unreachable("invalid phase in ConstructPhaseAction");
3743 }
3744 
3745 void Driver::BuildJobs(Compilation &C) const {
3746   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3747 
3748   Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3749 
3750   // It is an error to provide a -o option if we are making multiple output
3751   // files. There are exceptions:
3752   //
3753   // IfsMergeJob: when generating interface stubs enabled we want to be able to
3754   // generate the stub file at the same time that we generate the real
3755   // library/a.out. So when a .o, .so, etc are the output, with clang interface
3756   // stubs there will also be a .ifs and .ifso at the same location.
3757   //
3758   // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled
3759   // and -c is passed, we still want to be able to generate a .ifs file while
3760   // we are also generating .o files. So we allow more than one output file in
3761   // this case as well.
3762   //
3763   if (FinalOutput) {
3764     unsigned NumOutputs = 0;
3765     unsigned NumIfsOutputs = 0;
3766     for (const Action *A : C.getActions())
3767       if (A->getType() != types::TY_Nothing &&
3768           !(A->getKind() == Action::IfsMergeJobClass ||
3769             (A->getType() == clang::driver::types::TY_IFS_CPP &&
3770              A->getKind() == clang::driver::Action::CompileJobClass &&
3771              0 == NumIfsOutputs++) ||
3772             (A->getKind() == Action::BindArchClass && A->getInputs().size() &&
3773              A->getInputs().front()->getKind() == Action::IfsMergeJobClass)))
3774         ++NumOutputs;
3775 
3776     if (NumOutputs > 1) {
3777       Diag(clang::diag::err_drv_output_argument_with_multiple_files);
3778       FinalOutput = nullptr;
3779     }
3780   }
3781 
3782   // Collect the list of architectures.
3783   llvm::StringSet<> ArchNames;
3784   if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
3785     for (const Arg *A : C.getArgs())
3786       if (A->getOption().matches(options::OPT_arch))
3787         ArchNames.insert(A->getValue());
3788 
3789   // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3790   std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
3791   for (Action *A : C.getActions()) {
3792     // If we are linking an image for multiple archs then the linker wants
3793     // -arch_multiple and -final_output <final image name>. Unfortunately, this
3794     // doesn't fit in cleanly because we have to pass this information down.
3795     //
3796     // FIXME: This is a hack; find a cleaner way to integrate this into the
3797     // process.
3798     const char *LinkingOutput = nullptr;
3799     if (isa<LipoJobAction>(A)) {
3800       if (FinalOutput)
3801         LinkingOutput = FinalOutput->getValue();
3802       else
3803         LinkingOutput = getDefaultImageName();
3804     }
3805 
3806     BuildJobsForAction(C, A, &C.getDefaultToolChain(),
3807                        /*BoundArch*/ StringRef(),
3808                        /*AtTopLevel*/ true,
3809                        /*MultipleArchs*/ ArchNames.size() > 1,
3810                        /*LinkingOutput*/ LinkingOutput, CachedResults,
3811                        /*TargetDeviceOffloadKind*/ Action::OFK_None);
3812   }
3813 
3814   // If we have more than one job, then disable integrated-cc1 for now.
3815   if (C.getJobs().size() > 1)
3816     for (auto &J : C.getJobs())
3817       J.InProcess = false;
3818 
3819   // If the user passed -Qunused-arguments or there were errors, don't warn
3820   // about any unused arguments.
3821   if (Diags.hasErrorOccurred() ||
3822       C.getArgs().hasArg(options::OPT_Qunused_arguments))
3823     return;
3824 
3825   // Claim -### here.
3826   (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
3827 
3828   // Claim --driver-mode, --rsp-quoting, it was handled earlier.
3829   (void)C.getArgs().hasArg(options::OPT_driver_mode);
3830   (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
3831 
3832   for (Arg *A : C.getArgs()) {
3833     // FIXME: It would be nice to be able to send the argument to the
3834     // DiagnosticsEngine, so that extra values, position, and so on could be
3835     // printed.
3836     if (!A->isClaimed()) {
3837       if (A->getOption().hasFlag(options::NoArgumentUnused))
3838         continue;
3839 
3840       // Suppress the warning automatically if this is just a flag, and it is an
3841       // instance of an argument we already claimed.
3842       const Option &Opt = A->getOption();
3843       if (Opt.getKind() == Option::FlagClass) {
3844         bool DuplicateClaimed = false;
3845 
3846         for (const Arg *AA : C.getArgs().filtered(&Opt)) {
3847           if (AA->isClaimed()) {
3848             DuplicateClaimed = true;
3849             break;
3850           }
3851         }
3852 
3853         if (DuplicateClaimed)
3854           continue;
3855       }
3856 
3857       // In clang-cl, don't mention unknown arguments here since they have
3858       // already been warned about.
3859       if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
3860         Diag(clang::diag::warn_drv_unused_argument)
3861             << A->getAsString(C.getArgs());
3862     }
3863   }
3864 }
3865 
3866 namespace {
3867 /// Utility class to control the collapse of dependent actions and select the
3868 /// tools accordingly.
3869 class ToolSelector final {
3870   /// The tool chain this selector refers to.
3871   const ToolChain &TC;
3872 
3873   /// The compilation this selector refers to.
3874   const Compilation &C;
3875 
3876   /// The base action this selector refers to.
3877   const JobAction *BaseAction;
3878 
3879   /// Set to true if the current toolchain refers to host actions.
3880   bool IsHostSelector;
3881 
3882   /// Set to true if save-temps and embed-bitcode functionalities are active.
3883   bool SaveTemps;
3884   bool EmbedBitcode;
3885 
3886   /// Get previous dependent action or null if that does not exist. If
3887   /// \a CanBeCollapsed is false, that action must be legal to collapse or
3888   /// null will be returned.
3889   const JobAction *getPrevDependentAction(const ActionList &Inputs,
3890                                           ActionList &SavedOffloadAction,
3891                                           bool CanBeCollapsed = true) {
3892     // An option can be collapsed only if it has a single input.
3893     if (Inputs.size() != 1)
3894       return nullptr;
3895 
3896     Action *CurAction = *Inputs.begin();
3897     if (CanBeCollapsed &&
3898         !CurAction->isCollapsingWithNextDependentActionLegal())
3899       return nullptr;
3900 
3901     // If the input action is an offload action. Look through it and save any
3902     // offload action that can be dropped in the event of a collapse.
3903     if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
3904       // If the dependent action is a device action, we will attempt to collapse
3905       // only with other device actions. Otherwise, we would do the same but
3906       // with host actions only.
3907       if (!IsHostSelector) {
3908         if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
3909           CurAction =
3910               OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
3911           if (CanBeCollapsed &&
3912               !CurAction->isCollapsingWithNextDependentActionLegal())
3913             return nullptr;
3914           SavedOffloadAction.push_back(OA);
3915           return dyn_cast<JobAction>(CurAction);
3916         }
3917       } else if (OA->hasHostDependence()) {
3918         CurAction = OA->getHostDependence();
3919         if (CanBeCollapsed &&
3920             !CurAction->isCollapsingWithNextDependentActionLegal())
3921           return nullptr;
3922         SavedOffloadAction.push_back(OA);
3923         return dyn_cast<JobAction>(CurAction);
3924       }
3925       return nullptr;
3926     }
3927 
3928     return dyn_cast<JobAction>(CurAction);
3929   }
3930 
3931   /// Return true if an assemble action can be collapsed.
3932   bool canCollapseAssembleAction() const {
3933     return TC.useIntegratedAs() && !SaveTemps &&
3934            !C.getArgs().hasArg(options::OPT_via_file_asm) &&
3935            !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
3936            !C.getArgs().hasArg(options::OPT__SLASH_Fa);
3937   }
3938 
3939   /// Return true if a preprocessor action can be collapsed.
3940   bool canCollapsePreprocessorAction() const {
3941     return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
3942            !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
3943            !C.getArgs().hasArg(options::OPT_rewrite_objc);
3944   }
3945 
3946   /// Struct that relates an action with the offload actions that would be
3947   /// collapsed with it.
3948   struct JobActionInfo final {
3949     /// The action this info refers to.
3950     const JobAction *JA = nullptr;
3951     /// The offload actions we need to take care off if this action is
3952     /// collapsed.
3953     ActionList SavedOffloadAction;
3954   };
3955 
3956   /// Append collapsed offload actions from the give nnumber of elements in the
3957   /// action info array.
3958   static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
3959                                            ArrayRef<JobActionInfo> &ActionInfo,
3960                                            unsigned ElementNum) {
3961     assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3962     for (unsigned I = 0; I < ElementNum; ++I)
3963       CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3964                                     ActionInfo[I].SavedOffloadAction.end());
3965   }
3966 
3967   /// Functions that attempt to perform the combining. They detect if that is
3968   /// legal, and if so they update the inputs \a Inputs and the offload action
3969   /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3970   /// the combined action is returned. If the combining is not legal or if the
3971   /// tool does not exist, null is returned.
3972   /// Currently three kinds of collapsing are supported:
3973   ///  - Assemble + Backend + Compile;
3974   ///  - Assemble + Backend ;
3975   ///  - Backend + Compile.
3976   const Tool *
3977   combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3978                                 ActionList &Inputs,
3979                                 ActionList &CollapsedOffloadAction) {
3980     if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3981       return nullptr;
3982     auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3983     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3984     auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3985     if (!AJ || !BJ || !CJ)
3986       return nullptr;
3987 
3988     // Get compiler tool.
3989     const Tool *T = TC.SelectTool(*CJ);
3990     if (!T)
3991       return nullptr;
3992 
3993     // When using -fembed-bitcode, it is required to have the same tool (clang)
3994     // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3995     if (EmbedBitcode) {
3996       const Tool *BT = TC.SelectTool(*BJ);
3997       if (BT == T)
3998         return nullptr;
3999     }
4000 
4001     if (!T->hasIntegratedAssembler())
4002       return nullptr;
4003 
4004     Inputs = CJ->getInputs();
4005     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4006                                  /*NumElements=*/3);
4007     return T;
4008   }
4009   const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
4010                                      ActionList &Inputs,
4011                                      ActionList &CollapsedOffloadAction) {
4012     if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
4013       return nullptr;
4014     auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
4015     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
4016     if (!AJ || !BJ)
4017       return nullptr;
4018 
4019     // Get backend tool.
4020     const Tool *T = TC.SelectTool(*BJ);
4021     if (!T)
4022       return nullptr;
4023 
4024     if (!T->hasIntegratedAssembler())
4025       return nullptr;
4026 
4027     Inputs = BJ->getInputs();
4028     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4029                                  /*NumElements=*/2);
4030     return T;
4031   }
4032   const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
4033                                     ActionList &Inputs,
4034                                     ActionList &CollapsedOffloadAction) {
4035     if (ActionInfo.size() < 2)
4036       return nullptr;
4037     auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
4038     auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
4039     if (!BJ || !CJ)
4040       return nullptr;
4041 
4042     // Check if the initial input (to the compile job or its predessor if one
4043     // exists) is LLVM bitcode. In that case, no preprocessor step is required
4044     // and we can still collapse the compile and backend jobs when we have
4045     // -save-temps. I.e. there is no need for a separate compile job just to
4046     // emit unoptimized bitcode.
4047     bool InputIsBitcode = true;
4048     for (size_t i = 1; i < ActionInfo.size(); i++)
4049       if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
4050           ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
4051         InputIsBitcode = false;
4052         break;
4053       }
4054     if (!InputIsBitcode && !canCollapsePreprocessorAction())
4055       return nullptr;
4056 
4057     // Get compiler tool.
4058     const Tool *T = TC.SelectTool(*CJ);
4059     if (!T)
4060       return nullptr;
4061 
4062     if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
4063       return nullptr;
4064 
4065     Inputs = CJ->getInputs();
4066     AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4067                                  /*NumElements=*/2);
4068     return T;
4069   }
4070 
4071   /// Updates the inputs if the obtained tool supports combining with
4072   /// preprocessor action, and the current input is indeed a preprocessor
4073   /// action. If combining results in the collapse of offloading actions, those
4074   /// are appended to \a CollapsedOffloadAction.
4075   void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
4076                                ActionList &CollapsedOffloadAction) {
4077     if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
4078       return;
4079 
4080     // Attempt to get a preprocessor action dependence.
4081     ActionList PreprocessJobOffloadActions;
4082     ActionList NewInputs;
4083     for (Action *A : Inputs) {
4084       auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
4085       if (!PJ || !isa<PreprocessJobAction>(PJ)) {
4086         NewInputs.push_back(A);
4087         continue;
4088       }
4089 
4090       // This is legal to combine. Append any offload action we found and add the
4091       // current input to preprocessor inputs.
4092       CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
4093                                     PreprocessJobOffloadActions.end());
4094       NewInputs.append(PJ->input_begin(), PJ->input_end());
4095     }
4096     Inputs = NewInputs;
4097   }
4098 
4099 public:
4100   ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
4101                const Compilation &C, bool SaveTemps, bool EmbedBitcode)
4102       : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
4103         EmbedBitcode(EmbedBitcode) {
4104     assert(BaseAction && "Invalid base action.");
4105     IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
4106   }
4107 
4108   /// Check if a chain of actions can be combined and return the tool that can
4109   /// handle the combination of actions. The pointer to the current inputs \a
4110   /// Inputs and the list of offload actions \a CollapsedOffloadActions
4111   /// connected to collapsed actions are updated accordingly. The latter enables
4112   /// the caller of the selector to process them afterwards instead of just
4113   /// dropping them. If no suitable tool is found, null will be returned.
4114   const Tool *getTool(ActionList &Inputs,
4115                       ActionList &CollapsedOffloadAction) {
4116     //
4117     // Get the largest chain of actions that we could combine.
4118     //
4119 
4120     SmallVector<JobActionInfo, 5> ActionChain(1);
4121     ActionChain.back().JA = BaseAction;
4122     while (ActionChain.back().JA) {
4123       const Action *CurAction = ActionChain.back().JA;
4124 
4125       // Grow the chain by one element.
4126       ActionChain.resize(ActionChain.size() + 1);
4127       JobActionInfo &AI = ActionChain.back();
4128 
4129       // Attempt to fill it with the
4130       AI.JA =
4131           getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
4132     }
4133 
4134     // Pop the last action info as it could not be filled.
4135     ActionChain.pop_back();
4136 
4137     //
4138     // Attempt to combine actions. If all combining attempts failed, just return
4139     // the tool of the provided action. At the end we attempt to combine the
4140     // action with any preprocessor action it may depend on.
4141     //
4142 
4143     const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
4144                                                   CollapsedOffloadAction);
4145     if (!T)
4146       T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
4147     if (!T)
4148       T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
4149     if (!T) {
4150       Inputs = BaseAction->getInputs();
4151       T = TC.SelectTool(*BaseAction);
4152     }
4153 
4154     combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
4155     return T;
4156   }
4157 };
4158 }
4159 
4160 /// Return a string that uniquely identifies the result of a job. The bound arch
4161 /// is not necessarily represented in the toolchain's triple -- for example,
4162 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
4163 /// Also, we need to add the offloading device kind, as the same tool chain can
4164 /// be used for host and device for some programming models, e.g. OpenMP.
4165 static std::string GetTriplePlusArchString(const ToolChain *TC,
4166                                            StringRef BoundArch,
4167                                            Action::OffloadKind OffloadKind) {
4168   std::string TriplePlusArch = TC->getTriple().normalize();
4169   if (!BoundArch.empty()) {
4170     TriplePlusArch += "-";
4171     TriplePlusArch += BoundArch;
4172   }
4173   TriplePlusArch += "-";
4174   TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
4175   return TriplePlusArch;
4176 }
4177 
4178 InputInfo Driver::BuildJobsForAction(
4179     Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
4180     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
4181     std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
4182     Action::OffloadKind TargetDeviceOffloadKind) const {
4183   std::pair<const Action *, std::string> ActionTC = {
4184       A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4185   auto CachedResult = CachedResults.find(ActionTC);
4186   if (CachedResult != CachedResults.end()) {
4187     return CachedResult->second;
4188   }
4189   InputInfo Result = BuildJobsForActionNoCache(
4190       C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
4191       CachedResults, TargetDeviceOffloadKind);
4192   CachedResults[ActionTC] = Result;
4193   return Result;
4194 }
4195 
4196 InputInfo Driver::BuildJobsForActionNoCache(
4197     Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
4198     bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
4199     std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
4200     Action::OffloadKind TargetDeviceOffloadKind) const {
4201   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
4202 
4203   InputInfoList OffloadDependencesInputInfo;
4204   bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
4205   if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
4206     // The 'Darwin' toolchain is initialized only when its arguments are
4207     // computed. Get the default arguments for OFK_None to ensure that
4208     // initialization is performed before processing the offload action.
4209     // FIXME: Remove when darwin's toolchain is initialized during construction.
4210     C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
4211 
4212     // The offload action is expected to be used in four different situations.
4213     //
4214     // a) Set a toolchain/architecture/kind for a host action:
4215     //    Host Action 1 -> OffloadAction -> Host Action 2
4216     //
4217     // b) Set a toolchain/architecture/kind for a device action;
4218     //    Device Action 1 -> OffloadAction -> Device Action 2
4219     //
4220     // c) Specify a device dependence to a host action;
4221     //    Device Action 1  _
4222     //                      \
4223     //      Host Action 1  ---> OffloadAction -> Host Action 2
4224     //
4225     // d) Specify a host dependence to a device action.
4226     //      Host Action 1  _
4227     //                      \
4228     //    Device Action 1  ---> OffloadAction -> Device Action 2
4229     //
4230     // For a) and b), we just return the job generated for the dependence. For
4231     // c) and d) we override the current action with the host/device dependence
4232     // if the current toolchain is host/device and set the offload dependences
4233     // info with the jobs obtained from the device/host dependence(s).
4234 
4235     // If there is a single device option, just generate the job for it.
4236     if (OA->hasSingleDeviceDependence()) {
4237       InputInfo DevA;
4238       OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
4239                                        const char *DepBoundArch) {
4240         DevA =
4241             BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
4242                                /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
4243                                CachedResults, DepA->getOffloadingDeviceKind());
4244       });
4245       return DevA;
4246     }
4247 
4248     // If 'Action 2' is host, we generate jobs for the device dependences and
4249     // override the current action with the host dependence. Otherwise, we
4250     // generate the host dependences and override the action with the device
4251     // dependence. The dependences can't therefore be a top-level action.
4252     OA->doOnEachDependence(
4253         /*IsHostDependence=*/BuildingForOffloadDevice,
4254         [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4255           OffloadDependencesInputInfo.push_back(BuildJobsForAction(
4256               C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
4257               /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
4258               DepA->getOffloadingDeviceKind()));
4259         });
4260 
4261     A = BuildingForOffloadDevice
4262             ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
4263             : OA->getHostDependence();
4264   }
4265 
4266   if (const InputAction *IA = dyn_cast<InputAction>(A)) {
4267     // FIXME: It would be nice to not claim this here; maybe the old scheme of
4268     // just using Args was better?
4269     const Arg &Input = IA->getInputArg();
4270     Input.claim();
4271     if (Input.getOption().matches(options::OPT_INPUT)) {
4272       const char *Name = Input.getValue();
4273       return InputInfo(A, Name, /* _BaseInput = */ Name);
4274     }
4275     return InputInfo(A, &Input, /* _BaseInput = */ "");
4276   }
4277 
4278   if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
4279     const ToolChain *TC;
4280     StringRef ArchName = BAA->getArchName();
4281 
4282     if (!ArchName.empty())
4283       TC = &getToolChain(C.getArgs(),
4284                          computeTargetTriple(*this, TargetTriple,
4285                                              C.getArgs(), ArchName));
4286     else
4287       TC = &C.getDefaultToolChain();
4288 
4289     return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
4290                               MultipleArchs, LinkingOutput, CachedResults,
4291                               TargetDeviceOffloadKind);
4292   }
4293 
4294 
4295   ActionList Inputs = A->getInputs();
4296 
4297   const JobAction *JA = cast<JobAction>(A);
4298   ActionList CollapsedOffloadActions;
4299 
4300   ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
4301                   embedBitcodeInObject() && !isUsingLTO());
4302   const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
4303 
4304   if (!T)
4305     return InputInfo();
4306 
4307   // If we've collapsed action list that contained OffloadAction we
4308   // need to build jobs for host/device-side inputs it may have held.
4309   for (const auto *OA : CollapsedOffloadActions)
4310     cast<OffloadAction>(OA)->doOnEachDependence(
4311         /*IsHostDependence=*/BuildingForOffloadDevice,
4312         [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4313           OffloadDependencesInputInfo.push_back(BuildJobsForAction(
4314               C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
4315               /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
4316               DepA->getOffloadingDeviceKind()));
4317         });
4318 
4319   // Only use pipes when there is exactly one input.
4320   InputInfoList InputInfos;
4321   for (const Action *Input : Inputs) {
4322     // Treat dsymutil and verify sub-jobs as being at the top-level too, they
4323     // shouldn't get temporary output names.
4324     // FIXME: Clean this up.
4325     bool SubJobAtTopLevel =
4326         AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
4327     InputInfos.push_back(BuildJobsForAction(
4328         C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
4329         CachedResults, A->getOffloadingDeviceKind()));
4330   }
4331 
4332   // Always use the first input as the base input.
4333   const char *BaseInput = InputInfos[0].getBaseInput();
4334 
4335   // ... except dsymutil actions, which use their actual input as the base
4336   // input.
4337   if (JA->getType() == types::TY_dSYM)
4338     BaseInput = InputInfos[0].getFilename();
4339 
4340   // ... and in header module compilations, which use the module name.
4341   if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
4342     BaseInput = ModuleJA->getModuleName();
4343 
4344   // Append outputs of offload device jobs to the input list
4345   if (!OffloadDependencesInputInfo.empty())
4346     InputInfos.append(OffloadDependencesInputInfo.begin(),
4347                       OffloadDependencesInputInfo.end());
4348 
4349   // Set the effective triple of the toolchain for the duration of this job.
4350   llvm::Triple EffectiveTriple;
4351   const ToolChain &ToolTC = T->getToolChain();
4352   const ArgList &Args =
4353       C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
4354   if (InputInfos.size() != 1) {
4355     EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
4356   } else {
4357     // Pass along the input type if it can be unambiguously determined.
4358     EffectiveTriple = llvm::Triple(
4359         ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
4360   }
4361   RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
4362 
4363   // Determine the place to write output to, if any.
4364   InputInfo Result;
4365   InputInfoList UnbundlingResults;
4366   if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
4367     // If we have an unbundling job, we need to create results for all the
4368     // outputs. We also update the results cache so that other actions using
4369     // this unbundling action can get the right results.
4370     for (auto &UI : UA->getDependentActionsInfo()) {
4371       assert(UI.DependentOffloadKind != Action::OFK_None &&
4372              "Unbundling with no offloading??");
4373 
4374       // Unbundling actions are never at the top level. When we generate the
4375       // offloading prefix, we also do that for the host file because the
4376       // unbundling action does not change the type of the output which can
4377       // cause a overwrite.
4378       std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4379           UI.DependentOffloadKind,
4380           UI.DependentToolChain->getTriple().normalize(),
4381           /*CreatePrefixForHost=*/true);
4382       auto CurI = InputInfo(
4383           UA,
4384           GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
4385                              /*AtTopLevel=*/false,
4386                              MultipleArchs ||
4387                                  UI.DependentOffloadKind == Action::OFK_HIP,
4388                              OffloadingPrefix),
4389           BaseInput);
4390       // Save the unbundling result.
4391       UnbundlingResults.push_back(CurI);
4392 
4393       // Get the unique string identifier for this dependence and cache the
4394       // result.
4395       StringRef Arch;
4396       if (TargetDeviceOffloadKind == Action::OFK_HIP) {
4397         if (UI.DependentOffloadKind == Action::OFK_Host)
4398           Arch = StringRef();
4399         else
4400           Arch = UI.DependentBoundArch;
4401       } else
4402         Arch = BoundArch;
4403 
4404       CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
4405                                                 UI.DependentOffloadKind)}] =
4406           CurI;
4407     }
4408 
4409     // Now that we have all the results generated, select the one that should be
4410     // returned for the current depending action.
4411     std::pair<const Action *, std::string> ActionTC = {
4412         A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4413     assert(CachedResults.find(ActionTC) != CachedResults.end() &&
4414            "Result does not exist??");
4415     Result = CachedResults[ActionTC];
4416   } else if (JA->getType() == types::TY_Nothing)
4417     Result = InputInfo(A, BaseInput);
4418   else {
4419     // We only have to generate a prefix for the host if this is not a top-level
4420     // action.
4421     std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4422         A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
4423         /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
4424             !AtTopLevel);
4425     if (isa<OffloadWrapperJobAction>(JA)) {
4426       OffloadingPrefix += "-wrapper";
4427       if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
4428         BaseInput = FinalOutput->getValue();
4429       else
4430         BaseInput = getDefaultImageName();
4431     }
4432     Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
4433                                              AtTopLevel, MultipleArchs,
4434                                              OffloadingPrefix),
4435                        BaseInput);
4436   }
4437 
4438   if (CCCPrintBindings && !CCGenDiagnostics) {
4439     llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
4440                  << " - \"" << T->getName() << "\", inputs: [";
4441     for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
4442       llvm::errs() << InputInfos[i].getAsString();
4443       if (i + 1 != e)
4444         llvm::errs() << ", ";
4445     }
4446     if (UnbundlingResults.empty())
4447       llvm::errs() << "], output: " << Result.getAsString() << "\n";
4448     else {
4449       llvm::errs() << "], outputs: [";
4450       for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
4451         llvm::errs() << UnbundlingResults[i].getAsString();
4452         if (i + 1 != e)
4453           llvm::errs() << ", ";
4454       }
4455       llvm::errs() << "] \n";
4456     }
4457   } else {
4458     if (UnbundlingResults.empty())
4459       T->ConstructJob(
4460           C, *JA, Result, InputInfos,
4461           C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4462           LinkingOutput);
4463     else
4464       T->ConstructJobMultipleOutputs(
4465           C, *JA, UnbundlingResults, InputInfos,
4466           C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4467           LinkingOutput);
4468   }
4469   return Result;
4470 }
4471 
4472 const char *Driver::getDefaultImageName() const {
4473   llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
4474   return Target.isOSWindows() ? "a.exe" : "a.out";
4475 }
4476 
4477 /// Create output filename based on ArgValue, which could either be a
4478 /// full filename, filename without extension, or a directory. If ArgValue
4479 /// does not provide a filename, then use BaseName, and use the extension
4480 /// suitable for FileType.
4481 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
4482                                         StringRef BaseName,
4483                                         types::ID FileType) {
4484   SmallString<128> Filename = ArgValue;
4485 
4486   if (ArgValue.empty()) {
4487     // If the argument is empty, output to BaseName in the current dir.
4488     Filename = BaseName;
4489   } else if (llvm::sys::path::is_separator(Filename.back())) {
4490     // If the argument is a directory, output to BaseName in that dir.
4491     llvm::sys::path::append(Filename, BaseName);
4492   }
4493 
4494   if (!llvm::sys::path::has_extension(ArgValue)) {
4495     // If the argument didn't provide an extension, then set it.
4496     const char *Extension = types::getTypeTempSuffix(FileType, true);
4497 
4498     if (FileType == types::TY_Image &&
4499         Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
4500       // The output file is a dll.
4501       Extension = "dll";
4502     }
4503 
4504     llvm::sys::path::replace_extension(Filename, Extension);
4505   }
4506 
4507   return Args.MakeArgString(Filename.c_str());
4508 }
4509 
4510 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
4511                                        const char *BaseInput,
4512                                        StringRef BoundArch, bool AtTopLevel,
4513                                        bool MultipleArchs,
4514                                        StringRef OffloadingPrefix) const {
4515   llvm::PrettyStackTraceString CrashInfo("Computing output path");
4516   // Output to a user requested destination?
4517   if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
4518     if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
4519       return C.addResultFile(FinalOutput->getValue(), &JA);
4520   }
4521 
4522   // For /P, preprocess to file named after BaseInput.
4523   if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
4524     assert(AtTopLevel && isa<PreprocessJobAction>(JA));
4525     StringRef BaseName = llvm::sys::path::filename(BaseInput);
4526     StringRef NameArg;
4527     if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
4528       NameArg = A->getValue();
4529     return C.addResultFile(
4530         MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
4531         &JA);
4532   }
4533 
4534   // Default to writing to stdout?
4535   if (AtTopLevel && !CCGenDiagnostics && isa<PreprocessJobAction>(JA))
4536     return "-";
4537 
4538   // Is this the assembly listing for /FA?
4539   if (JA.getType() == types::TY_PP_Asm &&
4540       (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
4541        C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
4542     // Use /Fa and the input filename to determine the asm file name.
4543     StringRef BaseName = llvm::sys::path::filename(BaseInput);
4544     StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
4545     return C.addResultFile(
4546         MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
4547         &JA);
4548   }
4549 
4550   // Output to a temporary file?
4551   if ((!AtTopLevel && !isSaveTempsEnabled() &&
4552        !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
4553       CCGenDiagnostics) {
4554     StringRef Name = llvm::sys::path::filename(BaseInput);
4555     std::pair<StringRef, StringRef> Split = Name.split('.');
4556     SmallString<128> TmpName;
4557     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4558     Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
4559     if (CCGenDiagnostics && A) {
4560       SmallString<128> CrashDirectory(A->getValue());
4561       if (!getVFS().exists(CrashDirectory))
4562         llvm::sys::fs::create_directories(CrashDirectory);
4563       llvm::sys::path::append(CrashDirectory, Split.first);
4564       const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%";
4565       std::error_code EC = llvm::sys::fs::createUniqueFile(
4566           CrashDirectory + Middle + Suffix, TmpName);
4567       if (EC) {
4568         Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4569         return "";
4570       }
4571     } else {
4572       TmpName = GetTemporaryPath(Split.first, Suffix);
4573     }
4574     return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4575   }
4576 
4577   SmallString<128> BasePath(BaseInput);
4578   StringRef BaseName;
4579 
4580   // Dsymutil actions should use the full path.
4581   if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
4582     BaseName = BasePath;
4583   else
4584     BaseName = llvm::sys::path::filename(BasePath);
4585 
4586   // Determine what the derived output name should be.
4587   const char *NamedOutput;
4588 
4589   if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
4590       C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
4591     // The /Fo or /o flag decides the object filename.
4592     StringRef Val =
4593         C.getArgs()
4594             .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
4595             ->getValue();
4596     NamedOutput =
4597         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
4598   } else if (JA.getType() == types::TY_Image &&
4599              C.getArgs().hasArg(options::OPT__SLASH_Fe,
4600                                 options::OPT__SLASH_o)) {
4601     // The /Fe or /o flag names the linked file.
4602     StringRef Val =
4603         C.getArgs()
4604             .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
4605             ->getValue();
4606     NamedOutput =
4607         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
4608   } else if (JA.getType() == types::TY_Image) {
4609     if (IsCLMode()) {
4610       // clang-cl uses BaseName for the executable name.
4611       NamedOutput =
4612           MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
4613     } else {
4614       SmallString<128> Output(getDefaultImageName());
4615       // HIP image for device compilation with -fno-gpu-rdc is per compilation
4616       // unit.
4617       bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
4618                         !C.getArgs().hasFlag(options::OPT_fgpu_rdc,
4619                                              options::OPT_fno_gpu_rdc, false);
4620       if (IsHIPNoRDC) {
4621         Output = BaseName;
4622         llvm::sys::path::replace_extension(Output, "");
4623       }
4624       Output += OffloadingPrefix;
4625       if (MultipleArchs && !BoundArch.empty()) {
4626         Output += "-";
4627         Output.append(BoundArch);
4628       }
4629       if (IsHIPNoRDC)
4630         Output += ".out";
4631       NamedOutput = C.getArgs().MakeArgString(Output.c_str());
4632     }
4633   } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
4634     NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
4635   } else {
4636     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4637     assert(Suffix && "All types used for output should have a suffix.");
4638 
4639     std::string::size_type End = std::string::npos;
4640     if (!types::appendSuffixForType(JA.getType()))
4641       End = BaseName.rfind('.');
4642     SmallString<128> Suffixed(BaseName.substr(0, End));
4643     Suffixed += OffloadingPrefix;
4644     if (MultipleArchs && !BoundArch.empty()) {
4645       Suffixed += "-";
4646       Suffixed.append(BoundArch);
4647     }
4648     // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
4649     // the unoptimized bitcode so that it does not get overwritten by the ".bc"
4650     // optimized bitcode output.
4651     auto IsHIPRDCInCompilePhase = [](const JobAction &JA,
4652                                      const llvm::opt::DerivedArgList &Args) {
4653       // The relocatable compilation in HIP implies -emit-llvm. Similarly, use a
4654       // ".tmp.bc" suffix for the unoptimized bitcode (generated in the compile
4655       // phase.)
4656       return isa<CompileJobAction>(JA) &&
4657              JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
4658              Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4659                           false);
4660     };
4661     if (!AtTopLevel && JA.getType() == types::TY_LLVM_BC &&
4662         (C.getArgs().hasArg(options::OPT_emit_llvm) ||
4663          IsHIPRDCInCompilePhase(JA, C.getArgs())))
4664       Suffixed += ".tmp";
4665     Suffixed += '.';
4666     Suffixed += Suffix;
4667     NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
4668   }
4669 
4670   // Prepend object file path if -save-temps=obj
4671   if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
4672       JA.getType() != types::TY_PCH) {
4673     Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4674     SmallString<128> TempPath(FinalOutput->getValue());
4675     llvm::sys::path::remove_filename(TempPath);
4676     StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
4677     llvm::sys::path::append(TempPath, OutputFileName);
4678     NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
4679   }
4680 
4681   // If we're saving temps and the temp file conflicts with the input file,
4682   // then avoid overwriting input file.
4683   if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
4684     bool SameFile = false;
4685     SmallString<256> Result;
4686     llvm::sys::fs::current_path(Result);
4687     llvm::sys::path::append(Result, BaseName);
4688     llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
4689     // Must share the same path to conflict.
4690     if (SameFile) {
4691       StringRef Name = llvm::sys::path::filename(BaseInput);
4692       std::pair<StringRef, StringRef> Split = Name.split('.');
4693       std::string TmpName = GetTemporaryPath(
4694           Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
4695       return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4696     }
4697   }
4698 
4699   // As an annoying special case, PCH generation doesn't strip the pathname.
4700   if (JA.getType() == types::TY_PCH && !IsCLMode()) {
4701     llvm::sys::path::remove_filename(BasePath);
4702     if (BasePath.empty())
4703       BasePath = NamedOutput;
4704     else
4705       llvm::sys::path::append(BasePath, NamedOutput);
4706     return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
4707   } else {
4708     return C.addResultFile(NamedOutput, &JA);
4709   }
4710 }
4711 
4712 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
4713   // Search for Name in a list of paths.
4714   auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
4715       -> llvm::Optional<std::string> {
4716     // Respect a limited subset of the '-Bprefix' functionality in GCC by
4717     // attempting to use this prefix when looking for file paths.
4718     for (const auto &Dir : P) {
4719       if (Dir.empty())
4720         continue;
4721       SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
4722       llvm::sys::path::append(P, Name);
4723       if (llvm::sys::fs::exists(Twine(P)))
4724         return std::string(P);
4725     }
4726     return None;
4727   };
4728 
4729   if (auto P = SearchPaths(PrefixDirs))
4730     return *P;
4731 
4732   SmallString<128> R(ResourceDir);
4733   llvm::sys::path::append(R, Name);
4734   if (llvm::sys::fs::exists(Twine(R)))
4735     return std::string(R.str());
4736 
4737   SmallString<128> P(TC.getCompilerRTPath());
4738   llvm::sys::path::append(P, Name);
4739   if (llvm::sys::fs::exists(Twine(P)))
4740     return std::string(P.str());
4741 
4742   SmallString<128> D(Dir);
4743   llvm::sys::path::append(D, "..", Name);
4744   if (llvm::sys::fs::exists(Twine(D)))
4745     return std::string(D.str());
4746 
4747   if (auto P = SearchPaths(TC.getLibraryPaths()))
4748     return *P;
4749 
4750   if (auto P = SearchPaths(TC.getFilePaths()))
4751     return *P;
4752 
4753   return std::string(Name);
4754 }
4755 
4756 void Driver::generatePrefixedToolNames(
4757     StringRef Tool, const ToolChain &TC,
4758     SmallVectorImpl<std::string> &Names) const {
4759   // FIXME: Needs a better variable than TargetTriple
4760   Names.emplace_back((TargetTriple + "-" + Tool).str());
4761   Names.emplace_back(Tool);
4762 
4763   // Allow the discovery of tools prefixed with LLVM's default target triple.
4764   std::string DefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4765   if (DefaultTargetTriple != TargetTriple)
4766     Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
4767 }
4768 
4769 static bool ScanDirForExecutable(SmallString<128> &Dir,
4770                                  const std::string &Name) {
4771   llvm::sys::path::append(Dir, Name);
4772   if (llvm::sys::fs::can_execute(Twine(Dir)))
4773     return true;
4774   llvm::sys::path::remove_filename(Dir);
4775   return false;
4776 }
4777 
4778 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
4779   SmallVector<std::string, 2> TargetSpecificExecutables;
4780   generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4781 
4782   // Respect a limited subset of the '-Bprefix' functionality in GCC by
4783   // attempting to use this prefix when looking for program paths.
4784   for (const auto &PrefixDir : PrefixDirs) {
4785     if (llvm::sys::fs::is_directory(PrefixDir)) {
4786       SmallString<128> P(PrefixDir);
4787       for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
4788         if (ScanDirForExecutable(P, TargetSpecificExecutable))
4789           return std::string(P.str());
4790     } else {
4791       SmallString<128> P((PrefixDir + Name).str());
4792       if (llvm::sys::fs::can_execute(Twine(P)))
4793         return std::string(P.str());
4794     }
4795   }
4796 
4797   const ToolChain::path_list &List = TC.getProgramPaths();
4798   for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) {
4799     // For each possible name of the tool look for it in
4800     // program paths first, then the path.
4801     // Higher priority names will be first, meaning that
4802     // a higher priority name in the path will be found
4803     // instead of a lower priority name in the program path.
4804     // E.g. <triple>-gcc on the path will be found instead
4805     // of gcc in the program path
4806     for (const auto &Path : List) {
4807       SmallString<128> P(Path);
4808       if (ScanDirForExecutable(P, TargetSpecificExecutable))
4809         return std::string(P.str());
4810     }
4811 
4812     // Fall back to the path
4813     if (llvm::ErrorOr<std::string> P =
4814             llvm::sys::findProgramByName(TargetSpecificExecutable))
4815       return *P;
4816   }
4817 
4818   return std::string(Name);
4819 }
4820 
4821 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
4822   SmallString<128> Path;
4823   std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
4824   if (EC) {
4825     Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4826     return "";
4827   }
4828 
4829   return std::string(Path.str());
4830 }
4831 
4832 std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
4833   SmallString<128> Path;
4834   std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
4835   if (EC) {
4836     Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4837     return "";
4838   }
4839 
4840   return std::string(Path.str());
4841 }
4842 
4843 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
4844   SmallString<128> Output;
4845   if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
4846     // FIXME: If anybody needs it, implement this obscure rule:
4847     // "If you specify a directory without a file name, the default file name
4848     // is VCx0.pch., where x is the major version of Visual C++ in use."
4849     Output = FpArg->getValue();
4850 
4851     // "If you do not specify an extension as part of the path name, an
4852     // extension of .pch is assumed. "
4853     if (!llvm::sys::path::has_extension(Output))
4854       Output += ".pch";
4855   } else {
4856     if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
4857       Output = YcArg->getValue();
4858     if (Output.empty())
4859       Output = BaseName;
4860     llvm::sys::path::replace_extension(Output, ".pch");
4861   }
4862   return std::string(Output.str());
4863 }
4864 
4865 const ToolChain &Driver::getToolChain(const ArgList &Args,
4866                                       const llvm::Triple &Target) const {
4867 
4868   auto &TC = ToolChains[Target.str()];
4869   if (!TC) {
4870     switch (Target.getOS()) {
4871     case llvm::Triple::AIX:
4872       TC = std::make_unique<toolchains::AIX>(*this, Target, Args);
4873       break;
4874     case llvm::Triple::Haiku:
4875       TC = std::make_unique<toolchains::Haiku>(*this, Target, Args);
4876       break;
4877     case llvm::Triple::Ananas:
4878       TC = std::make_unique<toolchains::Ananas>(*this, Target, Args);
4879       break;
4880     case llvm::Triple::CloudABI:
4881       TC = std::make_unique<toolchains::CloudABI>(*this, Target, Args);
4882       break;
4883     case llvm::Triple::Darwin:
4884     case llvm::Triple::MacOSX:
4885     case llvm::Triple::IOS:
4886     case llvm::Triple::TvOS:
4887     case llvm::Triple::WatchOS:
4888       TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args);
4889       break;
4890     case llvm::Triple::DragonFly:
4891       TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args);
4892       break;
4893     case llvm::Triple::OpenBSD:
4894       TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args);
4895       break;
4896     case llvm::Triple::NetBSD:
4897       TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args);
4898       break;
4899     case llvm::Triple::FreeBSD:
4900       TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args);
4901       break;
4902     case llvm::Triple::Minix:
4903       TC = std::make_unique<toolchains::Minix>(*this, Target, Args);
4904       break;
4905     case llvm::Triple::Linux:
4906     case llvm::Triple::ELFIAMCU:
4907       if (Target.getArch() == llvm::Triple::hexagon)
4908         TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
4909                                                              Args);
4910       else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
4911                !Target.hasEnvironment())
4912         TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
4913                                                               Args);
4914       else if (Target.getArch() == llvm::Triple::ppc ||
4915                Target.getArch() == llvm::Triple::ppc64 ||
4916                Target.getArch() == llvm::Triple::ppc64le)
4917         TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
4918                                                               Args);
4919       else if (Target.getArch() == llvm::Triple::ve)
4920         TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
4921 
4922       else
4923         TC = std::make_unique<toolchains::Linux>(*this, Target, Args);
4924       break;
4925     case llvm::Triple::NaCl:
4926       TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
4927       break;
4928     case llvm::Triple::Fuchsia:
4929       TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args);
4930       break;
4931     case llvm::Triple::Solaris:
4932       TC = std::make_unique<toolchains::Solaris>(*this, Target, Args);
4933       break;
4934     case llvm::Triple::AMDHSA:
4935       TC = std::make_unique<toolchains::ROCMToolChain>(*this, Target, Args);
4936       break;
4937     case llvm::Triple::AMDPAL:
4938     case llvm::Triple::Mesa3D:
4939       TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
4940       break;
4941     case llvm::Triple::Win32:
4942       switch (Target.getEnvironment()) {
4943       default:
4944         if (Target.isOSBinFormatELF())
4945           TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
4946         else if (Target.isOSBinFormatMachO())
4947           TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
4948         else
4949           TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
4950         break;
4951       case llvm::Triple::GNU:
4952         TC = std::make_unique<toolchains::MinGW>(*this, Target, Args);
4953         break;
4954       case llvm::Triple::Itanium:
4955         TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
4956                                                                   Args);
4957         break;
4958       case llvm::Triple::MSVC:
4959       case llvm::Triple::UnknownEnvironment:
4960         if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
4961                 .startswith_lower("bfd"))
4962           TC = std::make_unique<toolchains::CrossWindowsToolChain>(
4963               *this, Target, Args);
4964         else
4965           TC =
4966               std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
4967         break;
4968       }
4969       break;
4970     case llvm::Triple::PS4:
4971       TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args);
4972       break;
4973     case llvm::Triple::Contiki:
4974       TC = std::make_unique<toolchains::Contiki>(*this, Target, Args);
4975       break;
4976     case llvm::Triple::Hurd:
4977       TC = std::make_unique<toolchains::Hurd>(*this, Target, Args);
4978       break;
4979     default:
4980       // Of these targets, Hexagon is the only one that might have
4981       // an OS of Linux, in which case it got handled above already.
4982       switch (Target.getArch()) {
4983       case llvm::Triple::tce:
4984         TC = std::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
4985         break;
4986       case llvm::Triple::tcele:
4987         TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
4988         break;
4989       case llvm::Triple::hexagon:
4990         TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
4991                                                              Args);
4992         break;
4993       case llvm::Triple::lanai:
4994         TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
4995         break;
4996       case llvm::Triple::xcore:
4997         TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
4998         break;
4999       case llvm::Triple::wasm32:
5000       case llvm::Triple::wasm64:
5001         TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args);
5002         break;
5003       case llvm::Triple::avr:
5004         TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
5005         break;
5006       case llvm::Triple::msp430:
5007         TC =
5008             std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
5009         break;
5010       case llvm::Triple::riscv32:
5011       case llvm::Triple::riscv64:
5012         TC = std::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
5013         break;
5014       case llvm::Triple::ve:
5015         TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
5016         break;
5017       default:
5018         if (Target.getVendor() == llvm::Triple::Myriad)
5019           TC = std::make_unique<toolchains::MyriadToolChain>(*this, Target,
5020                                                               Args);
5021         else if (toolchains::BareMetal::handlesTarget(Target))
5022           TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
5023         else if (Target.isOSBinFormatELF())
5024           TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
5025         else if (Target.isOSBinFormatMachO())
5026           TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
5027         else
5028           TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
5029       }
5030     }
5031   }
5032 
5033   // Intentionally omitted from the switch above: llvm::Triple::CUDA.  CUDA
5034   // compiles always need two toolchains, the CUDA toolchain and the host
5035   // toolchain.  So the only valid way to create a CUDA toolchain is via
5036   // CreateOffloadingDeviceToolChains.
5037 
5038   return *TC;
5039 }
5040 
5041 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
5042   // Say "no" if there is not exactly one input of a type clang understands.
5043   if (JA.size() != 1 ||
5044       !types::isAcceptedByClang((*JA.input_begin())->getType()))
5045     return false;
5046 
5047   // And say "no" if this is not a kind of action clang understands.
5048   if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
5049       !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5050     return false;
5051 
5052   return true;
5053 }
5054 
5055 bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const {
5056   // Say "no" if there is not exactly one input of a type flang understands.
5057   if (JA.size() != 1 ||
5058       !types::isFortran((*JA.input_begin())->getType()))
5059     return false;
5060 
5061   // And say "no" if this is not a kind of action flang understands.
5062   if (!isa<PreprocessJobAction>(JA) && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5063     return false;
5064 
5065   return true;
5066 }
5067 
5068 bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const {
5069   // Only emit static library if the flag is set explicitly.
5070   if (Args.hasArg(options::OPT_emit_static_lib))
5071     return true;
5072   return false;
5073 }
5074 
5075 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
5076 /// grouped values as integers. Numbers which are not provided are set to 0.
5077 ///
5078 /// \return True if the entire string was parsed (9.2), or all groups were
5079 /// parsed (10.3.5extrastuff).
5080 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
5081                                unsigned &Micro, bool &HadExtra) {
5082   HadExtra = false;
5083 
5084   Major = Minor = Micro = 0;
5085   if (Str.empty())
5086     return false;
5087 
5088   if (Str.consumeInteger(10, Major))
5089     return false;
5090   if (Str.empty())
5091     return true;
5092   if (Str[0] != '.')
5093     return false;
5094 
5095   Str = Str.drop_front(1);
5096 
5097   if (Str.consumeInteger(10, Minor))
5098     return false;
5099   if (Str.empty())
5100     return true;
5101   if (Str[0] != '.')
5102     return false;
5103   Str = Str.drop_front(1);
5104 
5105   if (Str.consumeInteger(10, Micro))
5106     return false;
5107   if (!Str.empty())
5108     HadExtra = true;
5109   return true;
5110 }
5111 
5112 /// Parse digits from a string \p Str and fulfill \p Digits with
5113 /// the parsed numbers. This method assumes that the max number of
5114 /// digits to look for is equal to Digits.size().
5115 ///
5116 /// \return True if the entire string was parsed and there are
5117 /// no extra characters remaining at the end.
5118 bool Driver::GetReleaseVersion(StringRef Str,
5119                                MutableArrayRef<unsigned> Digits) {
5120   if (Str.empty())
5121     return false;
5122 
5123   unsigned CurDigit = 0;
5124   while (CurDigit < Digits.size()) {
5125     unsigned Digit;
5126     if (Str.consumeInteger(10, Digit))
5127       return false;
5128     Digits[CurDigit] = Digit;
5129     if (Str.empty())
5130       return true;
5131     if (Str[0] != '.')
5132       return false;
5133     Str = Str.drop_front(1);
5134     CurDigit++;
5135   }
5136 
5137   // More digits than requested, bail out...
5138   return false;
5139 }
5140 
5141 std::pair<unsigned, unsigned>
5142 Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const {
5143   unsigned IncludedFlagsBitmask = 0;
5144   unsigned ExcludedFlagsBitmask = options::NoDriverOption;
5145 
5146   if (IsClCompatMode) {
5147     // Include CL and Core options.
5148     IncludedFlagsBitmask |= options::CLOption;
5149     IncludedFlagsBitmask |= options::CoreOption;
5150   } else {
5151     ExcludedFlagsBitmask |= options::CLOption;
5152   }
5153 
5154   return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
5155 }
5156 
5157 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
5158   return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
5159 }
5160 
5161 bool clang::driver::willEmitRemarks(const ArgList &Args) {
5162   // -fsave-optimization-record enables it.
5163   if (Args.hasFlag(options::OPT_fsave_optimization_record,
5164                    options::OPT_fno_save_optimization_record, false))
5165     return true;
5166 
5167   // -fsave-optimization-record=<format> enables it as well.
5168   if (Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
5169                    options::OPT_fno_save_optimization_record, false))
5170     return true;
5171 
5172   // -foptimization-record-file alone enables it too.
5173   if (Args.hasFlag(options::OPT_foptimization_record_file_EQ,
5174                    options::OPT_fno_save_optimization_record, false))
5175     return true;
5176 
5177   // -foptimization-record-passes alone enables it too.
5178   if (Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
5179                    options::OPT_fno_save_optimization_record, false))
5180     return true;
5181   return false;
5182 }
5183